import type { AttributeValue } from '@opentelemetry/api'; import type { InvokableAgent } from '../types/agent.js'; import type { MultiAgentInput, MultiAgentInvokeOptions } from './multiagent.js'; import { HookableEvent } from '../hooks/events.js'; import type { HookCallback, HookableEventConstructor, HookCleanup } from '../hooks/types.js'; import type { MultiAgentPlugin } from './plugins.js'; import type { SessionManager } from '../session/session-manager.js'; import type { AgentNodeOptions } from './nodes.js'; import { AgentNode } from './nodes.js'; import { MultiAgentResult } from './state.js'; import type { MultiAgent } from './multiagent.js'; import type { MultiAgentStreamEvent } from './events.js'; /** * Runtime configuration for swarm execution. */ export interface SwarmConfig { /** Max total agent executions (including start). Defaults to `Infinity` (no limit). */ maxSteps?: number; /** * Wall-clock ceiling for the entire swarm invocation, in milliseconds. Defaults to `Infinity` * (no limit). Composed with each node's cancel signal, so a node that exceeds this bound * mid-execution will be aborted (cooperatively). */ timeout?: number; /** * Fallback per-node wall-clock ceiling in milliseconds. Applied to any node that doesn't * set its own `timeout`. Defaults to `Infinity` (no limit). * * Enforced via `AbortSignal` — cancellation is cooperative, so a tool that neither polls * its cancel signal nor forwards it to a cancellable API can run past this deadline. */ nodeTimeout?: number; } /** * Input type for swarm nodes. Pass an {@link InvokableAgent} directly for the simple case, * or {@link AgentNodeOptions} for per-node config. */ export type SwarmNodeDefinition = InvokableAgent | AgentNodeOptions; export interface SwarmOptions extends SwarmConfig { /** Unique identifier. Defaults to `'swarm'`. */ id?: string; /** Swarm agents. Pass agents directly or use {@link AgentNodeOptions} for per-node config. */ nodes: SwarmNodeDefinition[]; /** Agent id that receives the initial input. Defaults to the first agent in `nodes`. */ start?: string; /** Session manager for saving and restoring swarm sessions. */ sessionManager?: SessionManager; /** Plugins for event-driven extensibility. */ plugins?: MultiAgentPlugin[]; /** Custom trace attributes to include on all spans. */ traceAttributes?: Record; } /** * Swarm multi-agent orchestration pattern. * * Agents execute sequentially, each deciding whether to hand off to another agent or * produce a final response. Routing is driven by structured output: each agent receives * a Zod schema with `agentId`, `message`, and optional `context` fields. When `agentId` * is present, the swarm hands off to that agent with `message` as input. When omitted, * `message` becomes the final response. * * Key design choices vs the Python SDK: * - Handoffs use structured output rather than an injected `handoff_to_agent` tool. * Routing logic stays in the orchestrator, not inside tool callbacks. * - Context is passed as serialized JSON text blocks rather than a mutable SharedContext. * - A single `maxSteps` limit replaces Python's separate `max_handoffs`/`max_iterations`. * - Agent descriptions are embedded in the structured output schema for routing decisions. * - Exceeding `maxSteps` throws an exception. Python returns a FAILED result. * * @example * ```typescript * const swarm = new Swarm({ * nodes: [researcher, writer], * start: 'researcher', * maxSteps: 10, * }) * * const result = await swarm.invoke('Explain quantum computing') * ``` */ export declare class Swarm implements MultiAgent { readonly id: string; readonly nodes: ReadonlyMap; readonly config: Required; private readonly _pluginRegistry; private readonly _hookRegistry; private readonly _tracer; readonly start: AgentNode; readonly sessionManager?: SessionManager | undefined; private _initialized; /** * State retained across invocations when a run ends INTERRUPTED. Lets * `swarm.invoke(responses)` resume on the same instance without requiring a * SessionManager, mirroring single-agent ergonomics. Cleared when a run * terminates in any non-INTERRUPTED state. */ private _pendingInterruptState?; constructor(options: SwarmOptions); /** * Initialize the swarm. Invokes the {@link MultiAgentInitializedEvent} callback. * Called automatically on first invocation. */ initialize(): Promise; /** * Register a hook callback for a specific swarm event type. * * @param eventType - The event class constructor to register the callback for * @param callback - The callback function to invoke when the event occurs * @returns Cleanup function that removes the callback when invoked */ addHook(eventType: HookableEventConstructor, callback: HookCallback): HookCleanup; /** * Invoke swarm and return final result (consumes stream). * * @param input - The input to pass to the start agent * @param options - Optional per-invocation options (e.g., {@link InvocationState}) * @returns Promise resolving to the final MultiAgentResult */ invoke(input: MultiAgentInput, options?: MultiAgentInvokeOptions): Promise; /** * Stream swarm execution, yielding events as agents execute. * Invokes hook callbacks for each event before yielding. * * @param input - The input to pass to the start agent * @param options - Optional per-invocation options (e.g., {@link InvocationState}) * @returns Async generator yielding streaming events and returning a MultiAgentResult */ stream(input: MultiAgentInput, options?: MultiAgentInvokeOptions): AsyncGenerator; private _stream; /** Invokes hook callbacks on an event, then yields it. */ private _emit; private _streamNode; private _validateConfig; private _resolveNodes; private _resolveStart; private _resolveContent; /** * Builds the input for the next node after a handoff, or returns the input as-is * when there is no handoff (initial or resume invocation). The caller passes the * original `MultiAgentInput` through; resume responses flow through here untouched * so the underlying agent sees them directly. */ private _resolveNodeInput; /** * Checks whether the swarm has exceeded its step limit with work still pending. * * This is only an error when the loop exhausted its step budget while the last agent * still requested a handoff (i.e. there was more work to do). If the swarm completed * normally on its final allowed step (no pending handoff), no error is thrown. * * @param state - Current swarm execution state * @param handoff - The last handoff result from the most recent agent execution * @throws Error when step limit is reached with a pending handoff */ private _checkSteps; /** * Finds the next node to execute from a restored {@link MultiAgentState}. * * When the session manager restores state from a snapshot, `state.results` * contains results from the previous invocation in completion order. The last * result's structured output contains the handoff decision — if it has an * `agentId`, that is the node the previous run intended to hand off to but * never executed (e.g. due to a crash). We resume from that handoff target. * * If the last result has no `agentId`, the previous run completed normally * and there is nothing to resume. * * @returns The handoff target node and its handoff context, or `undefined` for a fresh start */ private _findResumeNode; private _buildHandoffSchema; } //# sourceMappingURL=swarm.d.ts.map