Forge documentation
Library referenceTypeScript

@forge-sdk/agent

Agent abstractions, tool loops, workflows, sub-agent delegation, and messaging for the Forge SDK

Agent abstractions, tool loops, workflows, sub-agent delegation, and messaging for the Forge SDK

Package contract

FieldValue
Languagetypescript
Source version0.1.0
Manifestforge-ts/packages/forge-agent/package.json
Source files8
EvidenceSource reference; registry publication and runtime conformance are separate checks

Import boundary

import * as api from '@forge-sdk/agent';

Use a source checkout or your verified private registry. Manifest coordinates identify the package; they do not establish that a public registry release exists.

Source reference

Download package reference JSON. Each original source file and generated declaration artifact has its own SHA-256 digest. Function bodies and constant values are omitted from downloads. These are source declaration inventories, not compiler-resolved rustdoc, TypeDoc, DocC, or Dokka output. Private modules can contain public declarations that are not reachable through the package boundary; consult the entry point before importing.

agent.ts

Read declaration text · 2 declaration entries

export interface AgentConfig {
  /** A human-readable name for this agent. */
  readonly name: string;
  /** The language model to use for inference. */
  readonly model: LanguageModel;
  /** Optional system prompt. */
  readonly systemPrompt?: string;
  /** Maximum tool loop iterations. Defaults to 10. */
  readonly maxIterations?: number;
  /** Generation options for model calls. */
  readonly generateOptions?: GenerateOptions;
  /** The approval handler for tool execution. Defaults to AutoApprove. */
  readonly approvalHandler?: ApprovalHandler;
  /** Custom stop conditions for the tool loop. */
  readonly stopConditions?: readonly AgentStopCondition[];
  /** Optional agent DID for audit trail integration. */
  readonly agentDid?: string;
}

export class ToolLoopAgent {
  readonly name: string;
  readonly agentDid: string | undefined;
  readonly registry: ToolRegistry;
  readonly healthProfile: HealthProfile;
  readonly lifecycle: LifecycleManager;
  constructor(config: AgentConfig);
  async initialize(): Promise<void>;
  async run(userMessage: string): Promise<ToolLoopOutput>;
  async pause(): Promise<void>;
  async resume(): Promise<void>;
  async terminate(): Promise<void>;
  get isRunning(): boolean;
  get isTerminated(): boolean;
}

error.ts

Read declaration text · 3 declaration entries

export const ForgeAgentErrorCode /* type inferred in source */;

export type ForgeAgentErrorCodeType =
  (typeof ForgeAgentErrorCode)[keyof typeof ForgeAgentErrorCode];

export class ForgeAgentError extends Error {
  public readonly code: ForgeAgentErrorCodeType;
  static maxIterationsExceeded(
    maxIterations: number,
    lastToolNames: readonly string[]
  ): ForgeAgentError;
  static toolNotFound(toolName: string, available: readonly string[]): ForgeAgentError;
  static toolExecutionFailed(toolName: string, reason: string): ForgeAgentError;
  static modelError(reason: string): ForgeAgentError;
  static workflowFailed(
    workflowId: string,
    stepIndex: number,
    reason: string
  ): ForgeAgentError;
  static delegationFailed(parentDid: string, reason: string): ForgeAgentError;
  static invalidState(
    currentState: string,
    requiredState: string,
    operation: string
  ): ForgeAgentError;
  static channelError(reason: string): ForgeAgentError;
  static core(cause: string): ForgeAgentError;
  isMaxIterationsExceeded(): boolean;
  isToolNotFound(): boolean;
  isWorkflowFailed(): boolean;
  isDelegationFailed(): boolean;
}

index.ts

Read declaration text · 7 declaration entries

export { ForgeAgentError, ForgeAgentErrorCode, type ForgeAgentErrorCodeType } from './error.js';

export {
  AgentStopReason,
  type AgentStopCondition,
  type LoopContext,
  maxIterations,
  maxTotalTokens,
  modelStopsNaturally,
  customStop,
  evaluateStopConditions,
} from './loop-control.js';

export {
  type ToolLoopConfig,
  type ToolLoopIteration,
  type ToolLoopOutput,
  runToolLoop,
} from './tool-loop.js';

export {
  type AgentConfig,
  ToolLoopAgent,
} from './agent.js';

export {
  type WorkflowStep,
  type WorkflowResult,
  type RouterFn,
  SequentialWorkflow,
  ParallelWorkflow,
  RouterWorkflow,
} from './workflow.js';

export {
  type SubAgentConfig,
  createSubAgent,
  runSubAgentTask,
} from './subagent.js';

export {
  type AgentMessage,
  MessageType,
  type TypedMessage,
  AgentChannel,
  createAgentMessage,
  createTypedMessage,
} from './messaging.js';

loop-control.ts

Read declaration text · 9 declaration entries

export const AgentStopReason /* type inferred in source */;

export type AgentStopReason = (typeof AgentStopReason)[keyof typeof AgentStopReason];

export interface AgentStopCondition {
  /** A human-readable name for this stop condition. */
  readonly name: string;

  /**
   * Evaluates the stop condition against the current loop context.
   *
   * @param context - The current loop iteration context.
   * @returns `true` if the loop should stop.
   */
  check(context: LoopContext): boolean;
}

export interface LoopContext {
  /** The current iteration number (0-indexed). */
  readonly iteration: number;
  /** The cumulative token usage across all iterations. */
  readonly totalUsage: Usage;
  /** The finish reason from the last model call. */
  readonly lastFinishReason: FinishReason;
  /** The number of tool calls in the last iteration. */
  readonly lastToolCallCount: number;
}

export function maxIterations(max: number): AgentStopCondition;

export function maxTotalTokens(max: number): AgentStopCondition;

export function modelStopsNaturally(): AgentStopCondition;

export function customStop(
  name: string,
  predicate: (context: LoopContext) => boolean
): AgentStopCondition;

export function evaluateStopConditions(
  context: LoopContext,
  conditions: readonly AgentStopCondition[]
): { reason: AgentStopReason; conditionName: string } | undefined;

messaging.ts

Read declaration text · 7 declaration entries

export interface AgentMessage {
  /** Unique message identifier. */
  readonly id: string;
  /** The OAS DID of the sending agent. */
  readonly senderDid: string;
  /** The OAS DID of the recipient agent. */
  readonly recipientDid: string;
  /** The message payload (arbitrary JSON-serializable data). */
  readonly payload: unknown;
  /** The UTC timestamp when the message was created. */
  readonly timestamp: Timestamp;
}

export const MessageType /* type inferred in source */;

export type MessageType = (typeof MessageType)[keyof typeof MessageType];

export interface TypedMessage extends AgentMessage {
  /** The message type discriminator. */
  readonly messageType: MessageType;
  /** Optional correlation ID for request-response pairing. */
  readonly correlationId?: string;
}

export class AgentChannel {
  constructor(capacity: number = 1000);
  send(message: AgentMessage): void;
  receive(): AgentMessage | undefined;
  drain(): AgentMessage[];
  get size(): number;
  get isEmpty(): boolean;
  get capacity(): number;
}

export function createAgentMessage(
  senderDid: string,
  recipientDid: string,
  payload: unknown
): AgentMessage;

export function createTypedMessage(
  senderDid: string,
  recipientDid: string,
  payload: unknown,
  messageType: MessageType,
  correlationId?: string
): TypedMessage;

subagent.ts

Read declaration text · 3 declaration entries

export interface SubAgentConfig {
  /** A human-readable name for the sub-agent. */
  readonly name: string;
  /** The language model for the sub-agent (may differ from parent). */
  readonly model: LanguageModel;
  /** Optional system prompt for the sub-agent. */
  readonly systemPrompt?: string;
  /** Maximum tool loop iterations. Defaults to 10. */
  readonly maxIterations?: number;
  /** Generation options for the sub-agent's model calls. */
  readonly generateOptions?: GenerateOptions;
  /** Approval handler for the sub-agent. Defaults to parent's handler. */
  readonly approvalHandler?: ApprovalHandler;
  /** Custom stop conditions for the sub-agent. */
  readonly stopConditions?: readonly AgentStopCondition[];
  /**
   * Tool names to grant to the sub-agent. Must be a subset of the
   * parent's registered tools.
   *
   * ANVIL Spec section 11.3: child_capabilities subset_of parent_capabilities.
   */
  readonly allowedTools?: readonly string[];
  /** Optional sub-agent DID. */
  readonly agentDid?: string;
}

export function createSubAgent(
  parent: ToolLoopAgent,
  config: SubAgentConfig
): ToolLoopAgent;

export async function runSubAgentTask(
  parent: ToolLoopAgent,
  config: SubAgentConfig,
  message: string
): Promise<import('./tool-loop.js').ToolLoopOutput>;

tool-loop.ts

Read declaration text · 4 declaration entries

export interface ToolLoopConfig {
  /** The language model to use for inference. */
  readonly model: LanguageModel;
  /** The tool registry containing available tools and their executors. */
  readonly registry: ToolRegistry;
  /** Optional system prompt prepended to every conversation. */
  readonly systemPrompt?: string;
  /** Maximum number of tool loop iterations. Defaults to 10. */
  readonly maxIterations?: number;
  /** Generation options for model calls. */
  readonly generateOptions?: GenerateOptions;
  /** The approval handler for tool execution. Defaults to AutoApprove. */
  readonly approvalHandler?: ApprovalHandler;
  /** Custom stop conditions evaluated after each iteration. */
  readonly stopConditions?: readonly AgentStopCondition[];
  /** The health profile to update with tool invocations and inference calls. */
  readonly healthProfile?: HealthProfile;
}

export interface ToolLoopIteration {
  /** The iteration index (0-based). */
  readonly index: number;
  /** The model's response message for this iteration. */
  readonly assistantMessage: ModelMessage;
  /** The tool calls requested by the model (empty if none). */
  readonly toolCalls: readonly ToolCall[];
  /** The tool results from executing the tool calls (empty if no calls). */
  readonly toolResults: readonly ToolResult[];
  /** Token usage for this iteration. */
  readonly usage: Usage;
}

export interface ToolLoopOutput {
  /** The final text response from the model. */
  readonly finalText: string;
  /** All iterations executed during the loop. */
  readonly iterations: readonly ToolLoopIteration[];
  /** The total token usage across all iterations. */
  readonly totalUsage: Usage;
  /** The reason the loop stopped. */
  readonly stopReason: string;
  /** The complete conversation history including all messages. */
  readonly messages: readonly ModelMessage[];
}

export async function runToolLoop(
  config: ToolLoopConfig,
  userMessage: string
): Promise<ToolLoopOutput>;

workflow.ts

Read declaration text · 6 declaration entries

export interface WorkflowStep {
  /** The name of the agent that executed this step. */
  readonly agentName: string;
  /** The output from the agent's tool loop. */
  readonly output: ToolLoopOutput;
  /** The wall-clock duration of this step in milliseconds. */
  readonly durationMs: number;
}

export interface WorkflowResult {
  /** The workflow identifier. */
  readonly workflowId: string;
  /** All steps executed in the workflow. */
  readonly steps: readonly WorkflowStep[];
  /** The total wall-clock duration of the workflow in milliseconds. */
  readonly totalDurationMs: number;
}

export class SequentialWorkflow {
  readonly workflowId: string;
  constructor(workflowId: string, agents: readonly ToolLoopAgent[]);
  async run(initialMessage: string): Promise<WorkflowResult>;
}

export class ParallelWorkflow {
  readonly workflowId: string;
  constructor(workflowId: string, agents: readonly ToolLoopAgent[]);
  async run(message: string): Promise<WorkflowResult>;
}

export type RouterFn = (
  message: string,
  agents: readonly ToolLoopAgent[]
) => number | Promise<number>;

export class RouterWorkflow {
  readonly workflowId: string;
  constructor(
    workflowId: string,
    agents: readonly ToolLoopAgent[],
    router: RouterFn
  );
  async run(message: string): Promise<WorkflowResult>;
}

Continue

On this page