/** * Agent Handoff - Transfer conversations between agents * * Python parity with praisonaiagents/agent/handoff.py: * - HandoffError, HandoffCycleError, HandoffDepthError, HandoffTimeoutError, * HandoffValidationError (all re-based on PraisonAIError from ../errors) * - ContextPolicy enum * - HandoffToolPolicy / HandoffToolPolicyMode (tool boundary enforcement) * - HandoffConfig, HandoffInputData, HandoffResult * - Handoff class with safety checks * - parallelHandoffs (fan-out with a concurrency semaphore) * - RECOMMENDED_PROMPT_PREFIX, promptWithHandoffInstructions * * The context filtering (`contextPolicy`, `maxContextMessages`, * `maxContextTokens`, `preserveSystem`), the invocation-scoped history seeding * and the handoff chain that `detectCycles`/`maxDepth` read live in * `./handoff-context`. */ import type { EnhancedAgent } from './enhanced'; import { PraisonAIError, type AgentErrorKind, type LegacyErrorCategory } from '../errors-base'; export { currentHandoffChain, currentHandoffDepth, runWithHandoffChain, selectHandoffMessages, resetHandoffChain, } from './handoff-context'; /** * Recommended prompt prefix for agents that support handoffs. * Python parity with praisonaiagents/agent/handoff.py */ export declare const RECOMMENDED_PROMPT_PREFIX = "You are a helpful assistant that can delegate tasks to specialized agents when appropriate.\nWhen you determine that a task would be better handled by another agent, use the appropriate handoff tool.\nAlways explain to the user why you are transferring them to another agent."; /** * Build a prompt with handoff instructions appended. * Python parity with praisonaiagents/agent/handoff.py * * @param basePrompt - The base system prompt * @param handoffs - Array of Handoff objects * @returns Combined prompt with handoff instructions */ export declare function promptWithHandoffInstructions(basePrompt: string, handoffs: Handoff[]): string; /** * Keyword options of `HandoffError`. * Python parity: praisonaiagents/errors.py:340-350 (`HandoffError.__init__`) */ export interface HandoffErrorOptions { /** Agent the handoff started from. Default `"unknown"`. */ sourceAgent?: string; /** Agent the handoff was aimed at. Default `null`. */ targetAgent?: string | null; agentId?: string; runId?: string; errorCategory?: AgentErrorKind | LegacyErrorCategory | string; /** Handoff errors usually need investigation. Default `false`. */ isRetryable?: boolean; /** Extra structured metadata (snake_case keys, as in Python). */ context?: Record; } /** * The tool name a handoff gets when the caller named none. * * Python parity (`Handoff.default_tool_name`, handoff.py): the target agent's * name is lower-cased with spaces turned into underscores and prefixed with * `transfer_to_`. Getting this wrong is not cosmetic -- the string is the * function name in the tool schema sent to the provider. The previous * `handoff_to_${agent.name}` form passed the name through raw, so an agent * called "Support Bot" produced `handoff_to_Support Bot`, which contains a * space and is rejected by the OpenAI tool-name rule `^[a-zA-Z0-9_-]{1,64}$`. * * Any character Python's transform leaves unsafe is folded to `_` as a final * guard; for every name Python handles correctly the two agree byte for byte. * * The whole result is finally capped at the provider's 64-character function * name limit (`^[a-zA-Z0-9_-]{1,64}$`). Python does not truncate, so an agent * name over 52 characters produces an over-length name there that the API * rejects outright; capping here keeps the common case byte-identical while * turning that pathological case from a hard API rejection into a usable name. * * @param agentName - The target agent's name. * @returns A provider-legal tool name (<=64 chars), e.g. `transfer_to_support_bot`. */ export declare function defaultHandoffToolName(agentName: string): string; /** * The tool description a handoff gets when the caller supplied none. * * Python parity (`Handoff.default_tool_description`, handoff.py): the target's * name, then its role in parentheses and its goal after a dash, both only when * present. This string is the tool's `description` in the schema the model * reads and is repeated in the system prompt, so the old * `Transfer conversation to ` gave the model strictly less to route on * than Python did. * * @param agent - The handoff target; `role` and `goal` are read when set. * @returns e.g. `Transfer task to Support Bot (Assistant) - Help users`. */ export declare function defaultHandoffToolDescription(agent: { name: string; role?: string; goal?: string; }): string; /** * Agent handoff/delegation failed. * * Includes source/target agent context (`context.source_agent`, * `context.target_agent`) for multi-agent debugging. * Python parity: praisonaiagents/errors.py:333-365 (`HandoffError`) */ export declare class HandoffError extends PraisonAIError { readonly sourceAgent: string; readonly targetAgent: string | null; constructor(message: string, options?: HandoffErrorOptions); } /** * Keyword options of `HandoffCycleError`. * Python parity: praisonaiagents/errors.py:410 (`cycle_path`) */ export interface HandoffCycleErrorOptions extends HandoffErrorOptions { /** The agent chain that closed the loop; recorded in `context.cycle_path` when non-empty. */ cyclePath?: string[]; } /** * Circular handoff dependency detected. * * Python parity: praisonaiagents/errors.py:407-415 (`HandoffCycleError`). * The legacy TypeScript form `new HandoffCycleError(chain)` still works and * derives Python's message (`Handoff cycle detected: a -> b -> a`). */ export declare class HandoffCycleError extends HandoffError { /** Backward-compatibility alias of `context.cycle_path` (Python: `self.chain`). */ readonly chain: string[] | null; constructor(message: string, options?: HandoffCycleErrorOptions); /** @deprecated legacy form; prefer `(message, { cyclePath })`. */ constructor(chain: string[]); } /** * Keyword options of `HandoffDepthError`. * Python parity: praisonaiagents/errors.py:421 (`max_depth`, `current_depth`) */ export interface HandoffDepthErrorOptions extends HandoffErrorOptions { maxDepth?: number; currentDepth?: number; } /** * Maximum handoff depth exceeded. * * Python parity: praisonaiagents/errors.py:418-429 (`HandoffDepthError`). * `context.max_depth` / `context.current_depth` are always present (`null` * when not given). The legacy TypeScript form `new HandoffDepthError(depth, * maxDepth)` still works and derives the message * `Max handoff depth exceeded: > `. */ export declare class HandoffDepthError extends HandoffError { /** Backward-compatibility alias of `context.current_depth` (Python: `self.depth`). */ readonly depth: number | null; /** Backward-compatibility alias of `context.max_depth` (Python: `self.max_depth`). */ readonly maxDepth: number | null; constructor(message: string, options?: HandoffDepthErrorOptions); /** @deprecated legacy form; prefer `(message, { currentDepth, maxDepth })`. */ constructor(depth: number, maxDepth: number); } /** * Keyword options of `HandoffTimeoutError`. `isRetryable` is not accepted: * timeouts are always retryable (Python forces `is_retryable=True`). * Python parity: praisonaiagents/errors.py:435 (`timeout_seconds`) */ export interface HandoffTimeoutErrorOptions extends Omit { /** Recorded in `context.timeout_seconds` when non-zero. */ timeoutSeconds?: number; } /** * Handoff operation timed out. Always retryable. * * Python parity: praisonaiagents/errors.py:432-440 (`HandoffTimeoutError`). * The legacy TypeScript form `new HandoffTimeoutError(timeout, agentName)` * still works: it derives `Handoff to timed out after s` and * records the agent as `targetAgent`. */ export declare class HandoffTimeoutError extends HandoffError { /** Backward-compatibility alias of `context.timeout_seconds` (Python: `self.timeout`). */ readonly timeout: number | null; /** Backward-compatibility alias of `targetAgent`. */ readonly agentName: string | null; constructor(message: string, options?: HandoffTimeoutErrorOptions); /** @deprecated legacy form; prefer `(message, { timeoutSeconds, targetAgent })`. */ constructor(timeout: number, agentName: string); } /** * Keyword options of `HandoffValidationError`. `isRetryable` is not accepted: * schema errors need code fixes (Python forces `is_retryable=False`). * Python parity: praisonaiagents/errors.py:446 (`validation_errors`) */ export interface HandoffValidationErrorOptions extends Omit { /** Individual schema violations; recorded in `context.validation_errors` when non-empty. */ validationErrors?: any[]; } /** * Raised when a typed handoff payload does not satisfy the declared schema. * * Appends a remediation hint to the message unless it already mentions * "Check payload" or "schema", and never marks the error retryable. * Python parity: praisonaiagents/errors.py:443-455 (`HandoffValidationError`) */ export declare class HandoffValidationError extends HandoffError { readonly validationErrors: any[] | null; constructor(message: string, options?: HandoffValidationErrorOptions); } /** * Policy for context sharing during handoff. */ export declare const ContextPolicy: { readonly FULL: "full"; readonly SUMMARY: "summary"; readonly NONE: "none"; readonly LAST_N: "last_n"; }; export type ContextPolicyType = typeof ContextPolicy[keyof typeof ContextPolicy]; /** * Tool filtering mode for a handoff. Python parity with * `HandoffToolPolicy.mode: Literal["intersect", "passthrough"]`. * * - `intersect` (DEFAULT, secure by default): the target only keeps tools * that both it and the source agent have. * - `passthrough` (legacy, opt-in): the target keeps its full tool set. */ export declare const HandoffToolPolicyMode: { readonly INTERSECT: "intersect"; readonly PASSTHROUGH: "passthrough"; }; export type HandoffToolPolicyMode = typeof HandoffToolPolicyMode[keyof typeof HandoffToolPolicyMode]; /** * Policy for tool boundary enforcement during handoff. * Python parity with the `HandoffToolPolicy` dataclass. * * `blockedTools` are stripped in every mode, regardless of intersection. */ export interface HandoffToolPolicy { /** Python parity: mode (default "intersect"). */ mode?: HandoffToolPolicyMode; /** Python parity: blocked_tools (default []). Tool names always stripped. */ blockedTools?: string[]; } /** A `HandoffToolPolicy` with Python's dataclass defaults applied. */ export interface ResolvedHandoffToolPolicy { mode: HandoffToolPolicyMode; blockedTools: string[]; } /** Python's `HandoffToolPolicy()` defaults: intersect mode, nothing blocked. */ export declare const DEFAULT_HANDOFF_TOOL_POLICY: Readonly; /** Apply Python's defaults to a (possibly partial) tool policy. */ export declare function resolveHandoffToolPolicy(policy?: HandoffToolPolicy | null): ResolvedHandoffToolPolicy; /** * The name a tool is known by, mirroring Python's * `getattr(tool, 'name', getattr(tool, '__name__', str(tool)))` over the * tool shapes the TypeScript agents hold: FunctionTool / `{ name }` objects, * OpenAI-style `{ type: 'function', function: { name } }` definitions, and * plain functions. */ export declare function handoffToolName(tool: unknown): string; /** * The minimum an agent needs to take part in a handoff: a name, a `chat`, * and (optionally) a tool list, read the way Python reads `agent.tools`. */ export interface HandoffAgentLike { name: string; chat: (...args: any[]) => Promise; /** Simple `Agent`: the configured tool list. */ tools?: unknown[]; /** `EnhancedAgent`: tools live in a registry exposed via `getTools()`. */ getTools?: () => unknown[]; } /** Read an agent's tools the way Python's `getattr(agent, 'tools', None) or []` does. */ export declare function listAgentTools(agent: HandoffAgentLike | null | undefined): unknown[]; /** * Data passed to a handoff target agent. */ export interface HandoffInputData { messages: any[]; context: Record; sourceAgent?: string; handoffDepth?: number; handoffChain?: string[]; } /** * A zod-like schema: anything exposing `parse` (and optionally `safeParse`). */ export interface ParseableSchema { parse(input: unknown): unknown; safeParse?(input: unknown): { success: boolean; data?: unknown; error?: unknown; }; _def?: any; } /** * Accepted shapes for `HandoffConfig.inputType`: a JSON-schema object * (`{ type: 'object', properties, required }`) or a zod-like schema. */ export type HandoffInputType = Record | ParseableSchema; /** * Unified configuration for handoff behavior. * Python parity with HandoffConfig dataclass. */ export interface HandoffConfig { /** The target agent to hand off to */ agent: EnhancedAgent; /** Custom tool name (defaults to transfer_to_) */ name?: string; /** Custom tool description */ description?: string; /** Condition function to determine if handoff should trigger */ condition?: (context: HandoffContext) => boolean; /** Function to filter/transform input before passing to target agent */ transformContext?: (messages: any[]) => any[]; /** Python parity: input_type (Optional[type], default None). JSON schema or zod-like schema describing the structured handoff input; becomes the handoff tool's parameters and validates `context.input`. */ inputType?: HandoffInputType; /** Python parity: config (Optional[HandoffConfig], default None). Nested settings merged beneath the top-level ones (top-level keys win). */ config?: Partial; /** How to share context during handoff (default: summary for safety) */ contextPolicy?: ContextPolicyType; /** Maximum tokens to include in context */ maxContextTokens?: number; /** Maximum messages to include (for LAST_N policy) */ maxContextMessages?: number; /** Whether to preserve system messages in context */ preserveSystem?: boolean; /** * Python parity: tool_policy (HandoffToolPolicy, default intersect mode with * nothing blocked). Which of the target's tools survive the handoff. */ toolPolicy?: HandoffToolPolicy; /** Timeout for handoff execution in seconds */ timeoutSeconds?: number; /** Maximum concurrent handoffs (0 = unlimited) */ maxConcurrent?: number; /** Enable cycle detection to prevent infinite loops */ detectCycles?: boolean; /** Maximum handoff chain depth */ maxDepth?: number; /** Python parity: allow_parallel (bool, default False). Required by `parallelHandoffs` when a config is passed. */ allowParallel?: boolean; /** Callback when handoff starts */ onHandoff?: (context: HandoffContext) => void | Promise; /** Callback when handoff completes */ onComplete?: (result: HandoffResult) => void | Promise; /** Callback when handoff fails */ onError?: (error: Error) => void | Promise; } export interface HandoffContext { messages: any[]; lastMessage: string; topic?: string; metadata?: Record; /** Structured input for the handoff; validated against `inputType` when one is set. */ input?: unknown; /** * The agent performing the handoff (Python's `source_agent`). Needed for * the `intersect` tool policy: without it the source has no tools, so the * intersection is empty and the target runs with no tools at all. */ sourceAgent?: HandoffAgentLike; /** * The agents already traversed to reach this handoff, oldest first * (Python's `_handoff_chain_var`). `detectCycles` refuses a target that * appears in it and `maxDepth` refuses a chain longer than the limit. * * Leave it unset and the chain in force for the current execution is used, * which is what nested handoffs want: `execute()` runs the target inside a * scope carrying the extended chain. Set it to resume a chain that crossed * a process boundary (a queued handoff, a rehydrated request) or to start * one deliberately deep. `execute()` writes the extended chain back onto the * result's context, so passing `result.context` onward threads it by hand. */ handoffChain?: readonly string[]; } /** * The settings a Handoff runs with once the nested `config` block has been * merged beneath the top-level keys and Python's defaults applied. */ export interface ResolvedHandoffConfig { contextPolicy: ContextPolicyType; maxContextTokens: number; maxContextMessages: number; preserveSystem: boolean; toolPolicy: ResolvedHandoffToolPolicy; timeoutSeconds: number; maxConcurrent: number; detectCycles: boolean; maxDepth: number; allowParallel: boolean; onHandoff?: (context: HandoffContext) => void | Promise; onComplete?: (result: HandoffResult) => void | Promise; onError?: (error: Error) => void | Promise; } export interface HandoffResult { handedOffTo: string; response: string; context: HandoffContext; } /** * Handoff class - Represents a handoff target */ export declare class Handoff { readonly targetAgent: EnhancedAgent; readonly name: string; readonly description: string; readonly condition?: (context: HandoffContext) => boolean; readonly transformContext?: (messages: any[]) => any[]; /** Python parity: input_type. */ readonly inputType?: HandoffInputType; /** Effective settings after merging the nested `config` block (top-level keys win). */ readonly config: ResolvedHandoffConfig; /** * This handoff's own concurrency gate, created on first use. Per instance, * as in Python: one process-wide semaphore would let whichever handoff ran * first impose its `maxConcurrent` on every other. */ private semaphore; constructor(config: HandoffConfig); /** * Check if handoff should be triggered */ shouldTrigger(context: HandoffContext): boolean; /** * Validate `input` against `inputType`. Returns the parsed value (zod) or * the input itself (JSON schema). Throws HandoffError on failure. Without * an `inputType` the input passes through untouched. */ validateInput(input: unknown): unknown; /** * Compute the tool set the target may use for this handoff, from the * configured `toolPolicy`. Python parity with `Handoff._compute_effective_tools`. * * @returns `null` for unrestricted access (passthrough with nothing * blocked, so the target runs with its own configured tools); otherwise * the filtered list, where `[]` means *no tools* — in intersect mode an * empty intersection is the security boundary, not a fallback. */ computeEffectiveTools(sourceAgent?: HandoffAgentLike | null): unknown[] | null; /** * Run the target's `chat` so that it sees exactly `effectiveTools` * (Python: `self.agent.chat(prompt, tools=effective_tools)`). * * - `null`: no restriction; the target uses its own tools. * - A simple `Agent` (`chat(prompt, previousResult?, signal?, options?)`) * takes the per-call `options.tools` override, which replaces its tools * for that call only — no shared state is touched. * - Any other agent has its tool set swapped for the duration of the call * and restored afterwards, the way Python scopes `_seed_target_history`. */ private chatWithTools; /** * Refuse the handoff if it would close a loop or run too deep. Python * parity with `Handoff._check_safety`, including the order: a cycle is * reported before a depth overrun, and both are checked before anything is * pushed onto the chain. * * @param chain The agents already traversed, oldest first. * @param sourceName The agent performing this handoff. * @throws {HandoffCycleError} when `detectCycles` is on and the target is * already in the chain. * @throws {HandoffDepthError} when the chain is already `maxDepth` long. */ private checkSafety; /** * Run `fn` under this handoff's `maxConcurrent` limit. `0` (or less) means * unlimited, as in Python, where `_get_semaphore()` returns `None`. * * The wait for a slot is deliberately outside the timeout, matching * Python's `async with semaphore: await asyncio.wait_for(...)`: a handoff * queued behind five others must not be failed for the queue's length. */ private runWithinConcurrencyLimit; /** * Run `fn` under this handoff's `timeoutSeconds`, which `0` (or less) * disables. Python parity with the `asyncio.wait_for` in `execute_async`, * including the error: `HandoffTimeoutError`, always retryable. * * JavaScript cannot cancel the target's in-flight promise the way * `wait_for` cancels a task, so the abandoned call is left with a no-op * rejection handler: it must not surface later as an unhandled rejection * that takes the process down long after the handoff was reported failed. */ private runWithinTimeout; /** * Execute the handoff. * * What the target sees is decided by the context settings: `contextPolicy` * (with `maxContextMessages`, `maxContextTokens` and `preserveSystem`) * selects messages from `context.messages`, `transformContext` may reshape * the selection, and the result is seeded onto the target's conversation for * the duration of the call. Python parity with `_prepare_context` + * `_seed_target_history`. * * The target's tools are filtered by `config.toolPolicy` before it runs. * In the default `intersect` mode the filter needs to know the source * agent's tools: pass it as `context.sourceAgent`. * * Safety and execution limits apply around that: `detectCycles`/`maxDepth` * are checked before the target is touched, `maxConcurrent` bounds how many * of this handoff's executions run at once, and `timeoutSeconds` bounds the * target's turn. * * @throws {HandoffCycleError} the target is already in the handoff chain. * @throws {HandoffDepthError} the chain is already `maxDepth` long. * @throws {HandoffTimeoutError} the target exceeded `timeoutSeconds`. */ execute(context: HandoffContext): Promise; /** * Get tool definition for LLM. With an `inputType` the tool's parameters * are that schema (as in Python, where the input type's fields become the * tool signature); otherwise a free-text `reason` is offered. */ getToolDefinition(): { name: string; description: string; parameters: any; }; } /** * Create a handoff configuration */ export declare function handoff(config: HandoffConfig): Handoff; /** * Handoff filters - Common condition functions */ export declare const handoffFilters: { /** * Trigger handoff based on topic keywords */ topic: (keywords: string | string[]) => (context: HandoffContext) => boolean; /** * Trigger handoff based on metadata */ metadata: (key: string, value: any) => (context: HandoffContext) => boolean; /** * Always trigger */ always: () => () => boolean; /** * Never trigger (manual only) */ never: () => () => boolean; /** * Combine multiple conditions with AND */ and: (...conditions: Array<(context: HandoffContext) => boolean>) => (context: HandoffContext) => boolean; /** * Combine multiple conditions with OR */ or: (...conditions: Array<(context: HandoffContext) => boolean>) => (context: HandoffContext) => boolean; }; /** One fan-out target: Python's `(agent, prompt)` tuple, or the same as an object. */ export type ParallelHandoffTarget = [agent: EnhancedAgent | HandoffAgentLike, prompt: string] | { agent: EnhancedAgent | HandoffAgentLike; prompt: string; }; /** Options for `parallelHandoffs`; Python's keyword parameters under camelCase. */ export interface ParallelHandoffsOptions { /** * Python parity: max_concurrent (int, default 5). Maximum handoffs in * flight at once; 0 or negative means unlimited. When omitted and a * `config` is given, `config.maxConcurrent` is used. */ maxConcurrent?: number; /** * Python parity: config (Optional[HandoffConfig]). Applied to every * handoff (tool policy, callbacks, ...). Must have `allowParallel: true`, * as in Python where a config without `allow_parallel` is rejected. */ config?: Partial>; } /** * Outcome of one fan-out handoff. Python parity with the `HandoffResult` * dataclass `parallel_handoffs` returns: a failed target never rejects the * whole batch, it becomes a `success: false` entry carrying the error. */ export interface ParallelHandoffResult extends HandoffResult { success: boolean; /** Name of the agent that performed the handoff. */ sourceAgent: string; /** Wall-clock seconds the handoff took (0 on failure, as in Python). */ durationSeconds: number; /** The failure message when `success` is false. */ error?: string; } /** * Execute several handoffs from one source agent concurrently, with a cap * on how many run at once. Python parity with `parallel_handoffs`. * * Each target gets its own `Handoff` built from `options.config`, executed * with `source` as the handoff's source agent (so the default `intersect` * tool policy is enforced against the source's tools) and the source's * conversation history as context. Results come back in the order the * targets were given, one per target: a target that throws is reported as * `{ success: false, error }` and does not fail the others. * * @param source The agent performing the handoffs. * @param targets `[agent, prompt]` pairs (or `{ agent, prompt }` objects). * @param options `maxConcurrent` (default 5, 0 = unlimited) and `config`. * @throws HandoffError when `source` is missing, a target is malformed, or a * `config` is given without `allowParallel: true`. */ export declare function parallelHandoffs(source: EnhancedAgent | HandoffAgentLike, targets: ParallelHandoffTarget[], options?: ParallelHandoffsOptions): Promise;