@librechat/agents 3.1.78-dev.0 → 3.1.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/graphs/Graph.cjs +7 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +30 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +7 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +30 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +29 -0
- package/package.json +1 -1
- package/src/graphs/Graph.ts +9 -0
- package/src/scripts/subagent-configurable-inheritance.ts +252 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +148 -0
- package/src/tools/subagent/SubagentExecutor.ts +60 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubagentExecutor.mjs","sources":["../../../../src/tools/subagent/SubagentExecutor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport { BaseCallbackHandler } from '@langchain/core/callbacks/base';\nimport { HumanMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type { Callbacks } from '@langchain/core/callbacks/manager';\nimport type {\n AgentInputs,\n StandardGraphInput,\n ResolvedSubagentConfig,\n SubagentConfig,\n SubagentUpdateEvent,\n SubagentUpdatePhase,\n ToolExecuteBatchRequest,\n TokenCounter,\n} from '@/types';\nimport type { AggregatedHookResult, HookRegistry } from '@/hooks';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs/Graph';\nimport { GraphEvents, Callback } from '@/common';\nimport type { HandlerRegistry } from '@/events';\nimport { executeHooks } from '@/hooks';\n\nconst DEFAULT_MAX_TURNS = 25;\nconst RECURSION_MULTIPLIER = 3;\nconst ERROR_MESSAGE_MAX_CHARS = 200;\n\nconst HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n});\n\nexport type SubagentExecuteParams = {\n description: string;\n subagentType: string;\n threadId?: string;\n /**\n * Parent-side `tool_call_id` of the `subagent` tool invocation that\n * triggered this execution. Surfaced on {@link SubagentUpdateEvent} so\n * hosts can correlate child updates back to the originating tool call\n * without relying on event ordering heuristics.\n */\n parentToolCallId?: string;\n};\n\nexport type SubagentExecuteResult = {\n content: string;\n messages: BaseMessage[];\n};\n\n/**\n * Factory that constructs a child graph for subagent execution. Injected\n * rather than imported so that `SubagentExecutor` does not have a runtime\n * dependency on `StandardGraph` — this avoids a circular dependency between\n * `src/graphs/Graph.ts` and `src/tools/subagent/` that would otherwise break\n * Rollup's chunking under `preserveModules`.\n */\nexport type ChildGraphFactory = (input: StandardGraphInput) => StandardGraph;\n\nexport type SubagentExecutorOptions = {\n configs: Map<string, ResolvedSubagentConfig>;\n parentSignal?: AbortSignal;\n hookRegistry?: HookRegistry;\n parentRunId: string;\n parentAgentId?: string;\n tokenCounter?: TokenCounter;\n /** Remaining nesting budget. 0 or negative blocks execution. */\n maxDepth?: number;\n /**\n * Factory for constructing the isolated child graph. Callers pass\n * `(input) => new StandardGraph(input)` — injected to break a circular\n * module dependency.\n */\n createChildGraph: ChildGraphFactory;\n /**\n * Parent's event handler registry. When provided, child-graph events are\n * forwarded through this registry so hosts can:\n * (a) execute event-driven tools (`ON_TOOL_EXECUTE` routed to parent's handler),\n * (b) surface child activity to a UI via wrapped {@link GraphEvents.ON_SUBAGENT_UPDATE}.\n * When omitted, the child runs fully isolated (legacy behavior).\n *\n * Can be a direct `HandlerRegistry` or a zero-arg getter — use the getter\n * form when the registry is assigned to the graph AFTER the executor is\n * constructed (the current `Run.create` flow sets `handlerRegistry`\n * post-`createWorkflow`, so `createAgentNode` must capture lazily).\n */\n parentHandlerRegistry?: HandlerRegistry | (() => HandlerRegistry | undefined);\n};\n\nexport class SubagentExecutor {\n private readonly configs: Map<string, ResolvedSubagentConfig>;\n private readonly parentSignal?: AbortSignal;\n private readonly hookRegistry?: HookRegistry;\n private readonly parentRunId: string;\n private readonly parentAgentId?: string;\n private readonly tokenCounter?: TokenCounter;\n private readonly maxDepth: number;\n private readonly createChildGraph: ChildGraphFactory;\n private readonly resolveParentHandlerRegistry?: () =>\n | HandlerRegistry\n | undefined;\n\n constructor(options: SubagentExecutorOptions) {\n this.configs = options.configs;\n this.parentSignal = options.parentSignal;\n this.hookRegistry = options.hookRegistry;\n this.parentRunId = options.parentRunId;\n this.parentAgentId = options.parentAgentId;\n this.tokenCounter = options.tokenCounter;\n this.maxDepth = options.maxDepth ?? 1;\n this.createChildGraph = options.createChildGraph;\n const rawRegistry = options.parentHandlerRegistry;\n if (typeof rawRegistry === 'function') {\n this.resolveParentHandlerRegistry = rawRegistry;\n } else if (rawRegistry != null) {\n this.resolveParentHandlerRegistry = (): HandlerRegistry => rawRegistry;\n }\n }\n\n /** Snapshot of the parent's registry at the moment a subagent is dispatched. */\n private getParentHandlerRegistry(): HandlerRegistry | undefined {\n return this.resolveParentHandlerRegistry?.();\n }\n\n async execute(params: SubagentExecuteParams): Promise<SubagentExecuteResult> {\n const { description, subagentType, threadId, parentToolCallId } = params;\n const config = this.configs.get(subagentType);\n\n if (!config) {\n const available = [...this.configs.keys()].join(', ');\n return {\n content: `Error: Unknown subagent type \"${subagentType}\". Available types: ${available}`,\n messages: [],\n };\n }\n\n if (this.maxDepth <= 0) {\n return {\n content: 'Error: Maximum subagent nesting depth exceeded.',\n messages: [],\n };\n }\n\n const childAgentId =\n config.agentInputs.agentId ||\n `${this.parentAgentId ?? 'agent'}_sub_${nanoid(8)}`;\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStart', this.parentRunId) === true\n ) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStart',\n runId: this.parentRunId,\n threadId,\n parentAgentId: this.parentAgentId,\n agentId: childAgentId,\n agentType: subagentType,\n inputs: [new HumanMessage(description)],\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK);\n\n /**\n * `ask` is treated identically to `deny` in the subagent context:\n * subagents are non-interactive, so there is no prompt path for `ask`.\n * Both decisions block execution and return a \"Blocked\" tool result.\n */\n if (hookResult.decision === 'deny' || hookResult.decision === 'ask') {\n return {\n content: `Blocked: ${hookResult.reason ?? 'Blocked by hook'}`,\n messages: [],\n };\n }\n }\n\n const parentRegistry = this.getParentHandlerRegistry();\n const forwardingEnabled = parentRegistry != null;\n /**\n * Keep `toolDefinitions` only when the host has actually wired an\n * `ON_TOOL_EXECUTE` handler. `Run` always constructs a `HandlerRegistry`,\n * so treating any registry as \"forwarding enabled\" would leak\n * `toolDefinitions` into children whose hosts cannot execute them — the\n * child's `ToolNode` batch promise would hang forever with no handler to\n * resolve/reject. Gating on the tool-execute handler preserves the\n * recoverable \"no tools\" path for registry-but-no-handler configs.\n */\n const hasToolExecuteHandler =\n parentRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) != null;\n const childInputs = buildChildInputs(\n config,\n childAgentId,\n this.maxDepth,\n /* keepToolDefinitions */ hasToolExecuteHandler\n );\n const childRunId = `${this.parentRunId}_sub_${nanoid(8)}`;\n const maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;\n\n const childGraph = this.createChildGraph({\n runId: childRunId,\n signal: this.parentSignal,\n agents: [childInputs],\n tokenCounter: this.tokenCounter,\n });\n\n const forwarder = forwardingEnabled\n ? this.createForwarderCallback({\n parentRegistry: parentRegistry!,\n subagentType,\n subagentAgentId: childAgentId,\n childRunId,\n parentToolCallId,\n })\n : undefined;\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'start',\n label: `Subagent \"${subagentType}\" started`,\n });\n }\n\n let result: { messages: BaseMessage[] };\n try {\n const workflow = childGraph.createWorkflow();\n /**\n * When `parentHandlerRegistry` is provided (forwarding mode), attach a\n * lightweight callback that intercepts the child's `on_custom_event`\n * dispatches and routes them to the parent's registry — either as\n * operational events (ON_TOOL_EXECUTE) or wrapped ON_SUBAGENT_UPDATE\n * envelopes. Native LangChain streaming events (on_chat_model_stream,\n * etc.) still do NOT propagate to the parent's outer streamEvents\n * iterator — the `callbacks` array REPLACES the inherited chain, so\n * parent handlers won't receive child stream chunks and raise \"No\n * agent context found\" lookups on the parent's agentContexts map.\n *\n * When no registry is provided (legacy isolation), `callbacks: []`\n * fully detaches the child.\n *\n * `runName` gives the child a distinct LangSmith trace root (avoids\n * nested trace pollution).\n */\n const callbacks: Callbacks = forwarder ? [forwarder] : [];\n result = await workflow.invoke(\n { messages: [new HumanMessage(description)] },\n {\n recursionLimit: maxTurns * RECURSION_MULTIPLIER,\n signal: this.parentSignal,\n callbacks,\n runName: `subagent:${subagentType}`,\n configurable: {\n thread_id: childRunId,\n },\n }\n );\n } catch (error) {\n const errorMessage = truncateErrorMessage(error);\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'error',\n label: `Subagent \"${subagentType}\" errored: ${errorMessage}`,\n data: { message: errorMessage },\n });\n }\n childGraph.clearHeavyState();\n return {\n content: `Subagent error: ${errorMessage}`,\n messages: [],\n };\n }\n\n const filteredContent = filterSubagentResult(result.messages);\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStop', this.parentRunId) === true\n ) {\n /**\n * Awaited (not fire-and-forget) for deterministic test synchronization\n * and consistency with PostCompact. The parent is already waiting on the\n * tool result, so the small extra latency is acceptable. Errors are\n * swallowed — SubagentStop is observational.\n */\n await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStop',\n runId: this.parentRunId,\n threadId,\n agentId: childAgentId,\n agentType: subagentType,\n messages: result.messages,\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch(() => {\n /* SubagentStop is observational — swallow errors */\n });\n }\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'stop',\n label: `Subagent \"${subagentType}\" finished`,\n });\n }\n\n childGraph.clearHeavyState();\n\n return { content: filteredContent, messages: result.messages };\n }\n\n /**\n * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the\n * parent's handler registry. Silent no-op when no parent registry is set.\n * Errors are swallowed — update events are observational.\n */\n private async emitSubagentUpdate(\n parentRegistry: HandlerRegistry,\n args: {\n childRunId: string;\n subagentType: string;\n subagentAgentId: string;\n parentToolCallId?: string;\n phase: SubagentUpdatePhase;\n data?: unknown;\n label?: string;\n }\n ): Promise<void> {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: this.parentRunId,\n subagentRunId: args.childRunId,\n subagentType: args.subagentType,\n subagentAgentId: args.subagentAgentId,\n parentAgentId: this.parentAgentId,\n parentToolCallId: args.parentToolCallId,\n phase: args.phase,\n data: args.data,\n label: args.label,\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n }\n\n /**\n * Builds a BaseCallbackHandler that intercepts the child graph's custom\n * events. Routing rules:\n * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE\n * handler (so event-driven tools work identically for child and parent).\n * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /\n * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a\n * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable\n * label, delivered to the parent's subagent-update handler.\n * - Everything else → ignored (keeps parent's UI scoped to the events it\n * cares about; host apps can extend by registering more phases).\n */\n private createForwarderCallback(args: {\n parentRegistry: HandlerRegistry;\n subagentType: string;\n subagentAgentId: string;\n childRunId: string;\n parentToolCallId?: string;\n }): BaseCallbackHandler {\n const {\n parentRegistry,\n subagentType,\n subagentAgentId,\n childRunId,\n parentToolCallId,\n } = args;\n const parentRunId = this.parentRunId;\n const parentAgentId = this.parentAgentId;\n\n const wrap = async (\n eventName: string,\n phase: SubagentUpdatePhase,\n data: unknown\n ): Promise<void> => {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: parentRunId,\n subagentRunId: childRunId,\n subagentType,\n subagentAgentId,\n parentAgentId,\n parentToolCallId,\n phase,\n data,\n label: summarizeEvent(eventName, data),\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n };\n\n const handler = BaseCallbackHandler.fromMethods({\n [Callback.CUSTOM_EVENT]: async (\n eventName: string,\n data: unknown\n ): Promise<void> => {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const toolHandler = parentRegistry.getHandler(\n GraphEvents.ON_TOOL_EXECUTE\n );\n if (toolHandler) {\n await toolHandler.handle(\n GraphEvents.ON_TOOL_EXECUTE,\n data as ToolExecuteBatchRequest\n );\n }\n /**\n * We also surface a short notice in the subagent-update stream so\n * the UI can show \"calling <tool>\" for each tool the child spawns.\n */\n await wrap(eventName, 'run_step', data);\n return;\n }\n\n if (eventName === GraphEvents.ON_RUN_STEP) {\n await wrap(eventName, 'run_step', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_DELTA) {\n await wrap(eventName, 'run_step_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n await wrap(eventName, 'run_step_completed', data);\n return;\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n await wrap(eventName, 'message_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_REASONING_DELTA) {\n await wrap(eventName, 'reasoning_delta', data);\n return;\n }\n },\n });\n /**\n * `awaitHandlers = true` is required so the child's `ToolNode` actually\n * blocks on the parent's `ON_TOOL_EXECUTE` handler until it resolves\n * the batch request. The same flag applies to observational events\n * (message_delta, run_step, …), which means a slow\n * `ON_SUBAGENT_UPDATE` handler on the host serializes the child\n * stream. If host-side latency becomes a concern, a future\n * refinement could split operational and observational events into\n * separate callback handlers with distinct await semantics.\n */\n handler.awaitHandlers = true;\n return handler;\n }\n}\n\n/**\n * Produces a short single-line label for an arbitrary forwarded child event.\n * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show\n * a compact status ticker without parsing the raw payload.\n */\nexport function summarizeEvent(eventName: string, data: unknown): string {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const req = data as { toolCalls?: Array<{ name?: string }> };\n const names = (req.toolCalls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0 ? `Calling ${names.join(', ')}` : 'Calling tool';\n }\n if (eventName === GraphEvents.ON_RUN_STEP) {\n const step = data as {\n type?: string;\n stepDetails?: { type?: string; tool_calls?: Array<{ name?: string }> };\n };\n const detailType = step.stepDetails?.type ?? step.type ?? 'step';\n if (detailType === 'tool_calls') {\n const names = (step.stepDetails?.tool_calls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0\n ? `Using tool: ${names.join(', ')}`\n : 'Planning tool call';\n }\n if (detailType === 'message_creation') {\n return 'Thinking…';\n }\n return `Step: ${detailType}`;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const step = data as {\n result?: {\n type?: string;\n tool_call?: { name?: string; output?: string };\n };\n };\n const tool = step.result?.tool_call;\n if (tool?.name != null && tool.name !== '') {\n return `Tool ${tool.name} complete`;\n }\n return 'Step complete';\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n return 'Streaming…';\n }\n return eventName;\n}\n\n/**\n * Walk messages from last to first, returning the text content of the most\n * recent AIMessage that has any. Non-text blocks (tool_use, thinking,\n * redacted_thinking, tool_result) are stripped. If the last AIMessage is\n * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk\n * continues to earlier AIMessages so partial progress is salvaged — this\n * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.\n * Returns \"Task completed\" only when no AIMessage in the history contains\n * any text.\n */\nexport function filterSubagentResult(messages: BaseMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() !== 'ai') {\n continue;\n }\n\n const content = messages[i].content;\n\n if (typeof content === 'string') {\n if (content) return content;\n continue;\n }\n\n if (!Array.isArray(content)) {\n continue;\n }\n\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if ('type' in block && block.type === 'text' && 'text' in block) {\n textParts.push(block.text as string);\n }\n }\n\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n return 'Task completed';\n}\n\n/**\n * Resolve self-spawn configs by filling in agentInputs from the parent context.\n * Returns configs with agentInputs guaranteed present. Throws on duplicate\n * `type` values to prevent silent config shadowing.\n */\nexport function resolveSubagentConfigs(\n configs: SubagentConfig[],\n parentContext: AgentContext\n): ResolvedSubagentConfig[] {\n const resolved = configs\n .map((config) => {\n if (config.agentInputs != null) {\n return config as ResolvedSubagentConfig;\n }\n if (config.self !== true || parentContext._sourceInputs == null) {\n return null;\n }\n return {\n ...config,\n agentInputs: { ...parentContext._sourceInputs },\n } as ResolvedSubagentConfig;\n })\n .filter((c): c is ResolvedSubagentConfig => c != null);\n\n const seenTypes = new Set<string>();\n for (const config of resolved) {\n if (seenTypes.has(config.type)) {\n throw new Error(\n `Duplicate subagent type \"${config.type}\". Each SubagentConfig must have a unique \"type\" field.`\n );\n }\n seenTypes.add(config.type);\n }\n\n return resolved;\n}\n\n/**\n * Build child AgentInputs from a resolved config, stripping nesting and\n * (optionally) event-driven fields. When `allowNested: true`, the child's\n * `maxSubagentDepth` is decremented so that depth is consumed as the call\n * chain deepens across graph boundaries — the parent's executor-level check\n * alone cannot see into the child graph's separate executor.\n *\n * When `keepToolDefinitions` is `true`, the child retains the parent's\n * `toolDefinitions` so event-driven tools remain usable. This is only safe\n * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a\n * registered handler — otherwise the child will hang on tool dispatch.\n *\n * @remarks Advanced utility: exported primarily for testing and by\n * {@link SubagentExecutor}. Host applications configuring subagents should\n * not need to call this directly — it is invoked internally when a subagent\n * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,\n * child's decremented `maxSubagentDepth` on the returned inputs) is the\n * mechanism that bounds nesting across graph boundaries; callers must\n * respect it.\n */\nexport function buildChildInputs(\n config: ResolvedSubagentConfig,\n childAgentId: string,\n parentMaxDepth: number,\n keepToolDefinitions: boolean = false\n): AgentInputs {\n const { agentInputs } = config;\n const childInputs: AgentInputs = {\n ...agentInputs,\n agentId: childAgentId,\n toolDefinitions: keepToolDefinitions\n ? agentInputs.toolDefinitions\n : undefined,\n /**\n * Subagents run in an isolated context by contract. Parent-run-scoped\n * fields that would otherwise survive the shallow-spread clone — the\n * cross-run conversation summary and the prior-turn tool-discovery\n * set — are cleared here so the child starts fresh. Host applications\n * that want a subagent to see parent context must thread it in\n * explicitly (e.g. via the `description` argument to the subagent\n * tool), not via inherited state.\n */\n initialSummary: undefined,\n discoveredTools: undefined,\n };\n\n if (config.allowNested === true) {\n childInputs.maxSubagentDepth = Math.max(0, parentMaxDepth - 1);\n } else {\n childInputs.subagentConfigs = undefined;\n childInputs.maxSubagentDepth = undefined;\n }\n\n return childInputs;\n}\n\nfunction truncateErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.length <= ERROR_MESSAGE_MAX_CHARS) {\n return message;\n }\n return `${message.slice(0, ERROR_MESSAGE_MAX_CHARS)}...`;\n}\n"],"names":[],"mappings":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C,CAAA,GAAA,CAAK;AAC1D;;;;"}
|
|
1
|
+
{"version":3,"file":"SubagentExecutor.mjs","sources":["../../../../src/tools/subagent/SubagentExecutor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport { BaseCallbackHandler } from '@langchain/core/callbacks/base';\nimport { HumanMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type { Callbacks } from '@langchain/core/callbacks/manager';\nimport type {\n AgentInputs,\n StandardGraphInput,\n ResolvedSubagentConfig,\n SubagentConfig,\n SubagentUpdateEvent,\n SubagentUpdatePhase,\n ToolExecuteBatchRequest,\n TokenCounter,\n} from '@/types';\nimport type { AggregatedHookResult, HookRegistry } from '@/hooks';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs/Graph';\nimport { GraphEvents, Callback } from '@/common';\nimport type { HandlerRegistry } from '@/events';\nimport { executeHooks } from '@/hooks';\n\nconst DEFAULT_MAX_TURNS = 25;\nconst RECURSION_MULTIPLIER = 3;\nconst ERROR_MESSAGE_MAX_CHARS = 200;\n\nconst HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n});\n\nexport type SubagentExecuteParams = {\n description: string;\n subagentType: string;\n threadId?: string;\n /**\n * Parent-side `tool_call_id` of the `subagent` tool invocation that\n * triggered this execution. Surfaced on {@link SubagentUpdateEvent} so\n * hosts can correlate child updates back to the originating tool call\n * without relying on event ordering heuristics.\n */\n parentToolCallId?: string;\n /**\n * Snapshot of the parent invocation's `config.configurable` at the\n * spawn-tool call site. Inherited verbatim into the child workflow's\n * `configurable` so host-set fields (`requestBody`, `user`,\n * `userMCPAuthMap`, etc.) propagate — fixing MCP body-placeholder\n * substitution and per-user lookups for subagent tool calls.\n *\n * Inheritance details (verified empirically against LangGraph):\n * - host-set keys propagate as-is into the child's tool dispatches;\n * - `thread_id` propagates (with `childRunId` as a fallback when\n * parent did not supply one) — matches the \"subagent is part of\n * the same conversation\" mental model and aligns with the\n * `sessionId: this.parentRunId` convention this executor already\n * uses for `SubagentStart` / `SubagentStop` hooks;\n * - `parent_run_id` propagates when the host put it on parent's\n * configurable;\n * - `run_id` is *overwritten by the LangGraph runtime* at child\n * invoke time regardless of what we forward — child's tool\n * dispatches see the child graph's runtime runId in\n * `configurable.run_id`, not the parent's. Hosts that need\n * parent-scoped run identity for downstream consumers should\n * plumb it via a host-defined key (e.g. `requestBody.messageId`),\n * not `run_id`.\n *\n * A future revision will likely make this inheritance configurable\n * per spawn type — background / async subagents may want isolation\n * rather than sharing parent's host context.\n */\n parentConfigurable?: Record<string, unknown>;\n};\n\nexport type SubagentExecuteResult = {\n content: string;\n messages: BaseMessage[];\n};\n\n/**\n * Factory that constructs a child graph for subagent execution. Injected\n * rather than imported so that `SubagentExecutor` does not have a runtime\n * dependency on `StandardGraph` — this avoids a circular dependency between\n * `src/graphs/Graph.ts` and `src/tools/subagent/` that would otherwise break\n * Rollup's chunking under `preserveModules`.\n */\nexport type ChildGraphFactory = (input: StandardGraphInput) => StandardGraph;\n\nexport type SubagentExecutorOptions = {\n configs: Map<string, ResolvedSubagentConfig>;\n parentSignal?: AbortSignal;\n hookRegistry?: HookRegistry;\n parentRunId: string;\n parentAgentId?: string;\n tokenCounter?: TokenCounter;\n /** Remaining nesting budget. 0 or negative blocks execution. */\n maxDepth?: number;\n /**\n * Factory for constructing the isolated child graph. Callers pass\n * `(input) => new StandardGraph(input)` — injected to break a circular\n * module dependency.\n */\n createChildGraph: ChildGraphFactory;\n /**\n * Parent's event handler registry. When provided, child-graph events are\n * forwarded through this registry so hosts can:\n * (a) execute event-driven tools (`ON_TOOL_EXECUTE` routed to parent's handler),\n * (b) surface child activity to a UI via wrapped {@link GraphEvents.ON_SUBAGENT_UPDATE}.\n * When omitted, the child runs fully isolated (legacy behavior).\n *\n * Can be a direct `HandlerRegistry` or a zero-arg getter — use the getter\n * form when the registry is assigned to the graph AFTER the executor is\n * constructed (the current `Run.create` flow sets `handlerRegistry`\n * post-`createWorkflow`, so `createAgentNode` must capture lazily).\n */\n parentHandlerRegistry?: HandlerRegistry | (() => HandlerRegistry | undefined);\n};\n\nexport class SubagentExecutor {\n private readonly configs: Map<string, ResolvedSubagentConfig>;\n private readonly parentSignal?: AbortSignal;\n private readonly hookRegistry?: HookRegistry;\n private readonly parentRunId: string;\n private readonly parentAgentId?: string;\n private readonly tokenCounter?: TokenCounter;\n private readonly maxDepth: number;\n private readonly createChildGraph: ChildGraphFactory;\n private readonly resolveParentHandlerRegistry?: () =>\n | HandlerRegistry\n | undefined;\n\n constructor(options: SubagentExecutorOptions) {\n this.configs = options.configs;\n this.parentSignal = options.parentSignal;\n this.hookRegistry = options.hookRegistry;\n this.parentRunId = options.parentRunId;\n this.parentAgentId = options.parentAgentId;\n this.tokenCounter = options.tokenCounter;\n this.maxDepth = options.maxDepth ?? 1;\n this.createChildGraph = options.createChildGraph;\n const rawRegistry = options.parentHandlerRegistry;\n if (typeof rawRegistry === 'function') {\n this.resolveParentHandlerRegistry = rawRegistry;\n } else if (rawRegistry != null) {\n this.resolveParentHandlerRegistry = (): HandlerRegistry => rawRegistry;\n }\n }\n\n /** Snapshot of the parent's registry at the moment a subagent is dispatched. */\n private getParentHandlerRegistry(): HandlerRegistry | undefined {\n return this.resolveParentHandlerRegistry?.();\n }\n\n async execute(params: SubagentExecuteParams): Promise<SubagentExecuteResult> {\n const { description, subagentType, threadId, parentToolCallId } = params;\n const config = this.configs.get(subagentType);\n\n if (!config) {\n const available = [...this.configs.keys()].join(', ');\n return {\n content: `Error: Unknown subagent type \"${subagentType}\". Available types: ${available}`,\n messages: [],\n };\n }\n\n if (this.maxDepth <= 0) {\n return {\n content: 'Error: Maximum subagent nesting depth exceeded.',\n messages: [],\n };\n }\n\n const childAgentId =\n config.agentInputs.agentId ||\n `${this.parentAgentId ?? 'agent'}_sub_${nanoid(8)}`;\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStart', this.parentRunId) === true\n ) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStart',\n runId: this.parentRunId,\n threadId,\n parentAgentId: this.parentAgentId,\n agentId: childAgentId,\n agentType: subagentType,\n inputs: [new HumanMessage(description)],\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK);\n\n /**\n * `ask` is treated identically to `deny` in the subagent context:\n * subagents are non-interactive, so there is no prompt path for `ask`.\n * Both decisions block execution and return a \"Blocked\" tool result.\n */\n if (hookResult.decision === 'deny' || hookResult.decision === 'ask') {\n return {\n content: `Blocked: ${hookResult.reason ?? 'Blocked by hook'}`,\n messages: [],\n };\n }\n }\n\n const parentRegistry = this.getParentHandlerRegistry();\n const forwardingEnabled = parentRegistry != null;\n /**\n * Keep `toolDefinitions` only when the host has actually wired an\n * `ON_TOOL_EXECUTE` handler. `Run` always constructs a `HandlerRegistry`,\n * so treating any registry as \"forwarding enabled\" would leak\n * `toolDefinitions` into children whose hosts cannot execute them — the\n * child's `ToolNode` batch promise would hang forever with no handler to\n * resolve/reject. Gating on the tool-execute handler preserves the\n * recoverable \"no tools\" path for registry-but-no-handler configs.\n */\n const hasToolExecuteHandler =\n parentRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) != null;\n const childInputs = buildChildInputs(\n config,\n childAgentId,\n this.maxDepth,\n /* keepToolDefinitions */ hasToolExecuteHandler\n );\n const childRunId = `${this.parentRunId}_sub_${nanoid(8)}`;\n const maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;\n\n const childGraph = this.createChildGraph({\n runId: childRunId,\n signal: this.parentSignal,\n agents: [childInputs],\n tokenCounter: this.tokenCounter,\n });\n\n const forwarder = forwardingEnabled\n ? this.createForwarderCallback({\n parentRegistry: parentRegistry!,\n subagentType,\n subagentAgentId: childAgentId,\n childRunId,\n parentToolCallId,\n })\n : undefined;\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'start',\n label: `Subagent \"${subagentType}\" started`,\n });\n }\n\n let result: { messages: BaseMessage[] };\n try {\n const workflow = childGraph.createWorkflow();\n /**\n * When `parentHandlerRegistry` is provided (forwarding mode), attach a\n * lightweight callback that intercepts the child's `on_custom_event`\n * dispatches and routes them to the parent's registry — either as\n * operational events (ON_TOOL_EXECUTE) or wrapped ON_SUBAGENT_UPDATE\n * envelopes. Native LangChain streaming events (on_chat_model_stream,\n * etc.) still do NOT propagate to the parent's outer streamEvents\n * iterator — the `callbacks` array REPLACES the inherited chain, so\n * parent handlers won't receive child stream chunks and raise \"No\n * agent context found\" lookups on the parent's agentContexts map.\n *\n * When no registry is provided (legacy isolation), `callbacks: []`\n * fully detaches the child.\n *\n * `runName` gives the child a distinct LangSmith trace root (avoids\n * nested trace pollution).\n */\n const callbacks: Callbacks = forwarder ? [forwarder] : [];\n /**\n * Inherit the parent's `configurable` verbatim — host-set fields\n * (`requestBody`, `user`, `userMCPAuthMap`, etc.) AND the run-\n * identity fields (`run_id`, `parent_run_id`, `thread_id`) all\n * propagate.\n *\n * Run-identity propagation is intentional and matches the\n * convention this executor itself already uses for `SubagentStart`\n * / `SubagentStop` hooks (`sessionId: this.parentRunId`): the\n * subagent runs under the parent's session scope, not its own.\n * Forwarding `run_id` / `parent_run_id` / `thread_id` makes\n * `ToolNode`'s hook lookups (`hasHookFor(eventName, runId)`),\n * `ToolOutputReferenceRegistry` keying, and trace lineage all\n * resolve to the parent's session for tools dispatched from the\n * subagent — so `PreToolUse` / `PostToolUse` hooks the host\n * registered against the parent's run fire for subagent tool\n * calls too. \"Same run\" matches the user-perceptual mental model.\n *\n * `thread_id` falls back to `childRunId` only when the parent\n * didn't supply one (legacy behavior preserved for hosts that\n * never set thread_id).\n *\n * NOTE: a future revision will likely make this configurable per\n * spawn type — e.g. a background / async subagent that runs after\n * the parent's run completes wants isolation, not inheritance.\n * For now the inheritance path matches LibreChat's primary use\n * case (synchronous subagents within a single user turn).\n */\n const inheritedConfigurable: Record<string, unknown> =\n params.parentConfigurable ?? {};\n result = await workflow.invoke(\n { messages: [new HumanMessage(description)] },\n {\n recursionLimit: maxTurns * RECURSION_MULTIPLIER,\n signal: this.parentSignal,\n callbacks,\n runName: `subagent:${subagentType}`,\n configurable: {\n thread_id: childRunId,\n ...inheritedConfigurable,\n },\n }\n );\n } catch (error) {\n const errorMessage = truncateErrorMessage(error);\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'error',\n label: `Subagent \"${subagentType}\" errored: ${errorMessage}`,\n data: { message: errorMessage },\n });\n }\n childGraph.clearHeavyState();\n return {\n content: `Subagent error: ${errorMessage}`,\n messages: [],\n };\n }\n\n const filteredContent = filterSubagentResult(result.messages);\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStop', this.parentRunId) === true\n ) {\n /**\n * Awaited (not fire-and-forget) for deterministic test synchronization\n * and consistency with PostCompact. The parent is already waiting on the\n * tool result, so the small extra latency is acceptable. Errors are\n * swallowed — SubagentStop is observational.\n */\n await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStop',\n runId: this.parentRunId,\n threadId,\n agentId: childAgentId,\n agentType: subagentType,\n messages: result.messages,\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch(() => {\n /* SubagentStop is observational — swallow errors */\n });\n }\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'stop',\n label: `Subagent \"${subagentType}\" finished`,\n });\n }\n\n childGraph.clearHeavyState();\n\n return { content: filteredContent, messages: result.messages };\n }\n\n /**\n * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the\n * parent's handler registry. Silent no-op when no parent registry is set.\n * Errors are swallowed — update events are observational.\n */\n private async emitSubagentUpdate(\n parentRegistry: HandlerRegistry,\n args: {\n childRunId: string;\n subagentType: string;\n subagentAgentId: string;\n parentToolCallId?: string;\n phase: SubagentUpdatePhase;\n data?: unknown;\n label?: string;\n }\n ): Promise<void> {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: this.parentRunId,\n subagentRunId: args.childRunId,\n subagentType: args.subagentType,\n subagentAgentId: args.subagentAgentId,\n parentAgentId: this.parentAgentId,\n parentToolCallId: args.parentToolCallId,\n phase: args.phase,\n data: args.data,\n label: args.label,\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n }\n\n /**\n * Builds a BaseCallbackHandler that intercepts the child graph's custom\n * events. Routing rules:\n * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE\n * handler (so event-driven tools work identically for child and parent).\n * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /\n * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a\n * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable\n * label, delivered to the parent's subagent-update handler.\n * - Everything else → ignored (keeps parent's UI scoped to the events it\n * cares about; host apps can extend by registering more phases).\n */\n private createForwarderCallback(args: {\n parentRegistry: HandlerRegistry;\n subagentType: string;\n subagentAgentId: string;\n childRunId: string;\n parentToolCallId?: string;\n }): BaseCallbackHandler {\n const {\n parentRegistry,\n subagentType,\n subagentAgentId,\n childRunId,\n parentToolCallId,\n } = args;\n const parentRunId = this.parentRunId;\n const parentAgentId = this.parentAgentId;\n\n const wrap = async (\n eventName: string,\n phase: SubagentUpdatePhase,\n data: unknown\n ): Promise<void> => {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: parentRunId,\n subagentRunId: childRunId,\n subagentType,\n subagentAgentId,\n parentAgentId,\n parentToolCallId,\n phase,\n data,\n label: summarizeEvent(eventName, data),\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n };\n\n const handler = BaseCallbackHandler.fromMethods({\n [Callback.CUSTOM_EVENT]: async (\n eventName: string,\n data: unknown\n ): Promise<void> => {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const toolHandler = parentRegistry.getHandler(\n GraphEvents.ON_TOOL_EXECUTE\n );\n if (toolHandler) {\n await toolHandler.handle(\n GraphEvents.ON_TOOL_EXECUTE,\n data as ToolExecuteBatchRequest\n );\n }\n /**\n * We also surface a short notice in the subagent-update stream so\n * the UI can show \"calling <tool>\" for each tool the child spawns.\n */\n await wrap(eventName, 'run_step', data);\n return;\n }\n\n if (eventName === GraphEvents.ON_RUN_STEP) {\n await wrap(eventName, 'run_step', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_DELTA) {\n await wrap(eventName, 'run_step_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n await wrap(eventName, 'run_step_completed', data);\n return;\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n await wrap(eventName, 'message_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_REASONING_DELTA) {\n await wrap(eventName, 'reasoning_delta', data);\n return;\n }\n },\n });\n /**\n * `awaitHandlers = true` is required so the child's `ToolNode` actually\n * blocks on the parent's `ON_TOOL_EXECUTE` handler until it resolves\n * the batch request. The same flag applies to observational events\n * (message_delta, run_step, …), which means a slow\n * `ON_SUBAGENT_UPDATE` handler on the host serializes the child\n * stream. If host-side latency becomes a concern, a future\n * refinement could split operational and observational events into\n * separate callback handlers with distinct await semantics.\n */\n handler.awaitHandlers = true;\n return handler;\n }\n}\n\n/**\n * Produces a short single-line label for an arbitrary forwarded child event.\n * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show\n * a compact status ticker without parsing the raw payload.\n */\nexport function summarizeEvent(eventName: string, data: unknown): string {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const req = data as { toolCalls?: Array<{ name?: string }> };\n const names = (req.toolCalls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0 ? `Calling ${names.join(', ')}` : 'Calling tool';\n }\n if (eventName === GraphEvents.ON_RUN_STEP) {\n const step = data as {\n type?: string;\n stepDetails?: { type?: string; tool_calls?: Array<{ name?: string }> };\n };\n const detailType = step.stepDetails?.type ?? step.type ?? 'step';\n if (detailType === 'tool_calls') {\n const names = (step.stepDetails?.tool_calls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0\n ? `Using tool: ${names.join(', ')}`\n : 'Planning tool call';\n }\n if (detailType === 'message_creation') {\n return 'Thinking…';\n }\n return `Step: ${detailType}`;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const step = data as {\n result?: {\n type?: string;\n tool_call?: { name?: string; output?: string };\n };\n };\n const tool = step.result?.tool_call;\n if (tool?.name != null && tool.name !== '') {\n return `Tool ${tool.name} complete`;\n }\n return 'Step complete';\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n return 'Streaming…';\n }\n return eventName;\n}\n\n/**\n * Walk messages from last to first, returning the text content of the most\n * recent AIMessage that has any. Non-text blocks (tool_use, thinking,\n * redacted_thinking, tool_result) are stripped. If the last AIMessage is\n * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk\n * continues to earlier AIMessages so partial progress is salvaged — this\n * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.\n * Returns \"Task completed\" only when no AIMessage in the history contains\n * any text.\n */\nexport function filterSubagentResult(messages: BaseMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() !== 'ai') {\n continue;\n }\n\n const content = messages[i].content;\n\n if (typeof content === 'string') {\n if (content) return content;\n continue;\n }\n\n if (!Array.isArray(content)) {\n continue;\n }\n\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if ('type' in block && block.type === 'text' && 'text' in block) {\n textParts.push(block.text as string);\n }\n }\n\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n return 'Task completed';\n}\n\n/**\n * Resolve self-spawn configs by filling in agentInputs from the parent context.\n * Returns configs with agentInputs guaranteed present. Throws on duplicate\n * `type` values to prevent silent config shadowing.\n */\nexport function resolveSubagentConfigs(\n configs: SubagentConfig[],\n parentContext: AgentContext\n): ResolvedSubagentConfig[] {\n const resolved = configs\n .map((config) => {\n if (config.agentInputs != null) {\n return config as ResolvedSubagentConfig;\n }\n if (config.self !== true || parentContext._sourceInputs == null) {\n return null;\n }\n return {\n ...config,\n agentInputs: { ...parentContext._sourceInputs },\n } as ResolvedSubagentConfig;\n })\n .filter((c): c is ResolvedSubagentConfig => c != null);\n\n const seenTypes = new Set<string>();\n for (const config of resolved) {\n if (seenTypes.has(config.type)) {\n throw new Error(\n `Duplicate subagent type \"${config.type}\". Each SubagentConfig must have a unique \"type\" field.`\n );\n }\n seenTypes.add(config.type);\n }\n\n return resolved;\n}\n\n/**\n * Build child AgentInputs from a resolved config, stripping nesting and\n * (optionally) event-driven fields. When `allowNested: true`, the child's\n * `maxSubagentDepth` is decremented so that depth is consumed as the call\n * chain deepens across graph boundaries — the parent's executor-level check\n * alone cannot see into the child graph's separate executor.\n *\n * When `keepToolDefinitions` is `true`, the child retains the parent's\n * `toolDefinitions` so event-driven tools remain usable. This is only safe\n * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a\n * registered handler — otherwise the child will hang on tool dispatch.\n *\n * @remarks Advanced utility: exported primarily for testing and by\n * {@link SubagentExecutor}. Host applications configuring subagents should\n * not need to call this directly — it is invoked internally when a subagent\n * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,\n * child's decremented `maxSubagentDepth` on the returned inputs) is the\n * mechanism that bounds nesting across graph boundaries; callers must\n * respect it.\n */\nexport function buildChildInputs(\n config: ResolvedSubagentConfig,\n childAgentId: string,\n parentMaxDepth: number,\n keepToolDefinitions: boolean = false\n): AgentInputs {\n const { agentInputs } = config;\n const childInputs: AgentInputs = {\n ...agentInputs,\n agentId: childAgentId,\n toolDefinitions: keepToolDefinitions\n ? agentInputs.toolDefinitions\n : undefined,\n /**\n * Subagents run in an isolated context by contract. Parent-run-scoped\n * fields that would otherwise survive the shallow-spread clone — the\n * cross-run conversation summary and the prior-turn tool-discovery\n * set — are cleared here so the child starts fresh. Host applications\n * that want a subagent to see parent context must thread it in\n * explicitly (e.g. via the `description` argument to the subagent\n * tool), not via inherited state.\n */\n initialSummary: undefined,\n discoveredTools: undefined,\n };\n\n if (config.allowNested === true) {\n childInputs.maxSubagentDepth = Math.max(0, parentMaxDepth - 1);\n } else {\n childInputs.subagentConfigs = undefined;\n childInputs.maxSubagentDepth = undefined;\n }\n\n return childInputs;\n}\n\nfunction truncateErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.length <= ERROR_MESSAGE_MAX_CHARS) {\n return message;\n }\n return `${message.slice(0, ERROR_MESSAGE_MAX_CHARS)}...`;\n}\n"],"names":[],"mappings":";;;;;;;AAsBA,MAAM,iBAAiB,GAAG,EAAE;AAC5B,MAAM,oBAAoB,GAAG,CAAC;AAC9B,MAAM,uBAAuB,GAAG,GAAG;AAEnC,MAAM,aAAa,GAAyB,MAAM,CAAC,MAAM,CAAC;AACxD,IAAA,kBAAkB,EAAE,EAAc;AAClC,IAAA,MAAM,EAAE,EAAc;AACvB,CAAA,CAAC;MAwFW,gBAAgB,CAAA;AACV,IAAA,OAAO;AACP,IAAA,YAAY;AACZ,IAAA,YAAY;AACZ,IAAA,WAAW;AACX,IAAA,aAAa;AACb,IAAA,YAAY;AACZ,IAAA,QAAQ;AACR,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;;;;;;;;AAmBG;AACG,SAAU,gBAAgB,CAC9B,MAA8B,EAC9B,YAAoB,EACpB,cAAsB,EACtB,mBAAA,GAA+B,KAAK,EAAA;AAEpC,IAAA,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM;AAC9B,IAAA,MAAM,WAAW,GAAgB;AAC/B,QAAA,GAAG,WAAW;AACd,QAAA,OAAO,EAAE,YAAY;AACrB,QAAA,eAAe,EAAE;cACb,WAAW,CAAC;AACd,cAAE,SAAS;AACb;;;;;;;;AAQG;AACH,QAAA,cAAc,EAAE,SAAS;AACzB,QAAA,eAAe,EAAE,SAAS;KAC3B;AAED,IAAA,IAAI,MAAM,CAAC,WAAW,KAAK,IAAI,EAAE;AAC/B,QAAA,WAAW,CAAC,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,cAAc,GAAG,CAAC,CAAC;IAChE;SAAO;AACL,QAAA,WAAW,CAAC,eAAe,GAAG,SAAS;AACvC,QAAA,WAAW,CAAC,gBAAgB,GAAG,SAAS;IAC1C;AAEA,IAAA,OAAO,WAAW;AACpB;AAEA,SAAS,oBAAoB,CAAC,KAAc,EAAA;AAC1C,IAAA,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AACtE,IAAA,IAAI,OAAO,CAAC,MAAM,IAAI,uBAAuB,EAAE;AAC7C,QAAA,OAAO,OAAO;IAChB;IACA,OAAO,CAAA,EAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,uBAAuB,CAAC,CAAA,GAAA,CAAK;AAC1D;;;;"}
|
|
@@ -15,6 +15,35 @@ export type SubagentExecuteParams = {
|
|
|
15
15
|
* without relying on event ordering heuristics.
|
|
16
16
|
*/
|
|
17
17
|
parentToolCallId?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Snapshot of the parent invocation's `config.configurable` at the
|
|
20
|
+
* spawn-tool call site. Inherited verbatim into the child workflow's
|
|
21
|
+
* `configurable` so host-set fields (`requestBody`, `user`,
|
|
22
|
+
* `userMCPAuthMap`, etc.) propagate — fixing MCP body-placeholder
|
|
23
|
+
* substitution and per-user lookups for subagent tool calls.
|
|
24
|
+
*
|
|
25
|
+
* Inheritance details (verified empirically against LangGraph):
|
|
26
|
+
* - host-set keys propagate as-is into the child's tool dispatches;
|
|
27
|
+
* - `thread_id` propagates (with `childRunId` as a fallback when
|
|
28
|
+
* parent did not supply one) — matches the "subagent is part of
|
|
29
|
+
* the same conversation" mental model and aligns with the
|
|
30
|
+
* `sessionId: this.parentRunId` convention this executor already
|
|
31
|
+
* uses for `SubagentStart` / `SubagentStop` hooks;
|
|
32
|
+
* - `parent_run_id` propagates when the host put it on parent's
|
|
33
|
+
* configurable;
|
|
34
|
+
* - `run_id` is *overwritten by the LangGraph runtime* at child
|
|
35
|
+
* invoke time regardless of what we forward — child's tool
|
|
36
|
+
* dispatches see the child graph's runtime runId in
|
|
37
|
+
* `configurable.run_id`, not the parent's. Hosts that need
|
|
38
|
+
* parent-scoped run identity for downstream consumers should
|
|
39
|
+
* plumb it via a host-defined key (e.g. `requestBody.messageId`),
|
|
40
|
+
* not `run_id`.
|
|
41
|
+
*
|
|
42
|
+
* A future revision will likely make this inheritance configurable
|
|
43
|
+
* per spawn type — background / async subagents may want isolation
|
|
44
|
+
* rather than sharing parent's host context.
|
|
45
|
+
*/
|
|
46
|
+
parentConfigurable?: Record<string, unknown>;
|
|
18
47
|
};
|
|
19
48
|
export type SubagentExecuteResult = {
|
|
20
49
|
content: string;
|
package/package.json
CHANGED
package/src/graphs/Graph.ts
CHANGED
|
@@ -1471,6 +1471,15 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
|
1471
1471
|
subagentType,
|
|
1472
1472
|
threadId,
|
|
1473
1473
|
parentToolCallId,
|
|
1474
|
+
/**
|
|
1475
|
+
* Forward the parent's `configurable` so host-set fields
|
|
1476
|
+
* (`requestBody`, `user`, etc.) propagate into the child
|
|
1477
|
+
* workflow. The executor scrubs run-identity fields before
|
|
1478
|
+
* forwarding — see `SubagentExecuteParams.parentConfigurable`.
|
|
1479
|
+
*/
|
|
1480
|
+
parentConfigurable: config.configurable as
|
|
1481
|
+
| Record<string, unknown>
|
|
1482
|
+
| undefined,
|
|
1474
1483
|
});
|
|
1475
1484
|
return result.content;
|
|
1476
1485
|
}, buildSubagentToolParams(resolvedConfigs));
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { config } from 'dotenv';
|
|
2
|
+
config();
|
|
3
|
+
|
|
4
|
+
import { HumanMessage } from '@langchain/core/messages';
|
|
5
|
+
import type * as t from '@/types';
|
|
6
|
+
import { ChatModelStreamHandler } from '@/stream';
|
|
7
|
+
import { ToolEndHandler, ModelEndHandler } from '@/events';
|
|
8
|
+
import { Providers, GraphEvents } from '@/common';
|
|
9
|
+
import { Run } from '@/run';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Live verification that host-set fields on the parent's outer
|
|
13
|
+
* `configurable` (e.g. `requestBody`, `user`, `userMCPAuthMap`)
|
|
14
|
+
* propagate into the subagent's `ON_TOOL_EXECUTE` dispatches.
|
|
15
|
+
*
|
|
16
|
+
* Pass criteria: when the SUBAGENT calls the calculator tool, the
|
|
17
|
+
* `data.configurable` arriving at the parent's ON_TOOL_EXECUTE
|
|
18
|
+
* handler contains every key the parent put on its outer
|
|
19
|
+
* configurable (with `thread_id` overridden to a child run id).
|
|
20
|
+
*/
|
|
21
|
+
const apiKey = process.env.OPENAI_API_KEY!;
|
|
22
|
+
if (!apiKey) {
|
|
23
|
+
console.error('Missing OPENAI_API_KEY');
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const calculatorDef: t.LCTool = {
|
|
28
|
+
name: 'calculator',
|
|
29
|
+
description: 'Evaluate a math expression. Use for any arithmetic.',
|
|
30
|
+
parameters: {
|
|
31
|
+
type: 'object',
|
|
32
|
+
properties: {
|
|
33
|
+
expression: {
|
|
34
|
+
type: 'string',
|
|
35
|
+
description: "A JS math expression, e.g. '42 * 58'",
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
required: ['expression'],
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
type ConfigurableSnapshot = {
|
|
43
|
+
agentId: string | undefined;
|
|
44
|
+
configurable: Record<string, unknown> | undefined;
|
|
45
|
+
metadata: Record<string, unknown> | undefined;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
async function main() {
|
|
49
|
+
console.log('=== Subagent parentConfigurable inheritance — live ===\n');
|
|
50
|
+
|
|
51
|
+
// Parent has NO tools — it can only delegate via the math subagent.
|
|
52
|
+
// The math subagent has the calculator. This forces the spawn-subagent
|
|
53
|
+
// path so we can observe the subagent's `ON_TOOL_EXECUTE` dispatch.
|
|
54
|
+
const mathSubagentInputs: t.AgentInputs = {
|
|
55
|
+
agentId: 'math-worker',
|
|
56
|
+
provider: Providers.OPENAI,
|
|
57
|
+
clientOptions: { modelName: 'gpt-4o', apiKey },
|
|
58
|
+
instructions:
|
|
59
|
+
'You compute arithmetic. Always use the calculator tool — never estimate. Return the final numeric result as plain text.',
|
|
60
|
+
maxContextTokens: 8000,
|
|
61
|
+
toolDefinitions: [calculatorDef],
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const parentAgent: t.AgentInputs = {
|
|
65
|
+
agentId: 'supervisor',
|
|
66
|
+
provider: Providers.OPENAI,
|
|
67
|
+
clientOptions: { modelName: 'gpt-4o', apiKey },
|
|
68
|
+
instructions: `You delegate arithmetic to the "math" subagent. You have NO calculator yourself. For any math task, spawn the "math" subagent with the full task as its description, then echo the subagent's text result back to the user.`,
|
|
69
|
+
maxContextTokens: 8000,
|
|
70
|
+
// No toolDefinitions on the parent — only the subagent gets the calculator.
|
|
71
|
+
subagentConfigs: [
|
|
72
|
+
{
|
|
73
|
+
type: 'math',
|
|
74
|
+
name: 'math',
|
|
75
|
+
description:
|
|
76
|
+
'A focused arithmetic worker that uses the calculator tool to compute numerical results.',
|
|
77
|
+
agentInputs: mathSubagentInputs,
|
|
78
|
+
},
|
|
79
|
+
],
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const parentSnapshots: ConfigurableSnapshot[] = [];
|
|
83
|
+
const subagentSnapshots: ConfigurableSnapshot[] = [];
|
|
84
|
+
|
|
85
|
+
const customHandlers: Record<string, t.EventHandler> = {
|
|
86
|
+
[GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
|
|
87
|
+
[GraphEvents.TOOL_END]: new ToolEndHandler(),
|
|
88
|
+
[GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
|
|
89
|
+
[GraphEvents.ON_TOOL_EXECUTE]: {
|
|
90
|
+
handle: (_event, rawData): void => {
|
|
91
|
+
const data = rawData as t.ToolExecuteBatchRequest;
|
|
92
|
+
const snapshot: ConfigurableSnapshot = {
|
|
93
|
+
agentId: data.agentId,
|
|
94
|
+
configurable: data.configurable as Record<string, unknown> | undefined,
|
|
95
|
+
metadata: data.metadata as Record<string, unknown> | undefined,
|
|
96
|
+
};
|
|
97
|
+
const callsLabel = data.toolCalls.map((c) => c.name).join(',');
|
|
98
|
+
// Parent and subagent have different agent IDs in this script
|
|
99
|
+
// (parent: 'supervisor', subagent: 'math-worker'). With a self-spawn
|
|
100
|
+
// subagent both would be the same; this script uses a non-self
|
|
101
|
+
// subagent precisely so we can distinguish reliably.
|
|
102
|
+
const isSubagent = data.agentId !== 'supervisor';
|
|
103
|
+
const metadataRunId = (data.metadata as { run_id?: string } | undefined)
|
|
104
|
+
?.run_id;
|
|
105
|
+
if (isSubagent) {
|
|
106
|
+
subagentSnapshots.push(snapshot);
|
|
107
|
+
} else {
|
|
108
|
+
parentSnapshots.push(snapshot);
|
|
109
|
+
}
|
|
110
|
+
console.log(
|
|
111
|
+
`[ON_TOOL_EXECUTE] origin=${isSubagent ? 'SUBAGENT' : 'PARENT'} agentId=${data.agentId} calls=${callsLabel}`
|
|
112
|
+
);
|
|
113
|
+
console.log(
|
|
114
|
+
` metadata keys: ${Object.keys(data.metadata ?? {}).join(',') || '<none>'}`
|
|
115
|
+
);
|
|
116
|
+
console.log(
|
|
117
|
+
` metadata.run_id="${metadataRunId ?? '<none>'}" configurable.run_id="${(data.configurable as { run_id?: string } | undefined)?.run_id ?? '<none>'}" configurable.thread_id="${(data.configurable as { thread_id?: string } | undefined)?.thread_id ?? '<none>'}"`
|
|
118
|
+
);
|
|
119
|
+
const results: t.ToolExecuteResult[] = data.toolCalls.map((call) => {
|
|
120
|
+
const args = call.args as { expression?: string };
|
|
121
|
+
const expression = args.expression ?? '';
|
|
122
|
+
let content: string;
|
|
123
|
+
try {
|
|
124
|
+
// eslint-disable-next-line no-eval
|
|
125
|
+
const result = eval(expression);
|
|
126
|
+
content = `${expression} = ${result}`;
|
|
127
|
+
} catch (err) {
|
|
128
|
+
content = `Error: ${String(err)}`;
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
toolCallId: call.id!,
|
|
132
|
+
status: 'success',
|
|
133
|
+
content,
|
|
134
|
+
};
|
|
135
|
+
});
|
|
136
|
+
data.resolve(results);
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const run = await Run.create<t.IState>({
|
|
142
|
+
runId: `sub-cfg-inherit-${Date.now()}`,
|
|
143
|
+
graphConfig: { type: 'standard', agents: [parentAgent] },
|
|
144
|
+
customHandlers,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const question = new HumanMessage(
|
|
148
|
+
'Compute (42 * 58) + (13 ** 3). Use the self subagent, and have it use the calculator.'
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
// Parent's outer configurable carries host-set fields AND explicit
|
|
152
|
+
// run-identity fields so we can verify whether LangGraph respects or
|
|
153
|
+
// overwrites parent's `run_id` / `parent_run_id` when we forward them
|
|
154
|
+
// into the child's `workflow.invoke`.
|
|
155
|
+
const outerConfigurable = {
|
|
156
|
+
thread_id: 'parent-thread-conv-xyz',
|
|
157
|
+
run_id: 'parent-run-id-001',
|
|
158
|
+
parent_run_id: 'grandparent-run-id-000',
|
|
159
|
+
user_id: 'user_abc',
|
|
160
|
+
user: { id: 'user_abc', email: 'a@b.c', role: 'USER' },
|
|
161
|
+
requestBody: {
|
|
162
|
+
messageId: 'msg-response-id-001',
|
|
163
|
+
conversationId: 'parent-thread-conv-xyz',
|
|
164
|
+
parentMessageId: 'user-message-id-000',
|
|
165
|
+
},
|
|
166
|
+
userMCPAuthMap: { 'mcp-github': { token: 'abc' } },
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
console.log('User:', question.content);
|
|
170
|
+
console.log('Parent outer configurable keys:', Object.keys(outerConfigurable));
|
|
171
|
+
console.log();
|
|
172
|
+
|
|
173
|
+
await run.processStream(
|
|
174
|
+
{ messages: [question] },
|
|
175
|
+
{
|
|
176
|
+
configurable: outerConfigurable,
|
|
177
|
+
version: 'v2' as const,
|
|
178
|
+
}
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
console.log('\n=== Verification ===');
|
|
182
|
+
console.log(
|
|
183
|
+
`Parent ON_TOOL_EXECUTE dispatches captured: ${parentSnapshots.length}`
|
|
184
|
+
);
|
|
185
|
+
console.log(
|
|
186
|
+
`Subagent ON_TOOL_EXECUTE dispatches captured: ${subagentSnapshots.length}`
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
if (subagentSnapshots.length === 0) {
|
|
190
|
+
console.error(
|
|
191
|
+
'\n❌ FAIL: subagent never invoked a tool — model may not have spawned the subagent.'
|
|
192
|
+
);
|
|
193
|
+
process.exit(2);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const expectedHostKeys = ['user_id', 'user', 'requestBody', 'userMCPAuthMap'];
|
|
197
|
+
let allPassed = true;
|
|
198
|
+
subagentSnapshots.forEach((snap, idx) => {
|
|
199
|
+
const cfg = snap.configurable ?? {};
|
|
200
|
+
const meta = snap.metadata ?? {};
|
|
201
|
+
console.log(
|
|
202
|
+
`\nSubagent dispatch #${idx + 1} (agentId=${snap.agentId}, metadata.run_id=${(meta as { run_id?: string }).run_id ?? '-'}):`
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
// Host-set fields must propagate.
|
|
206
|
+
for (const key of expectedHostKeys) {
|
|
207
|
+
const present = key in cfg;
|
|
208
|
+
const value = cfg[key];
|
|
209
|
+
console.log(
|
|
210
|
+
` ${present ? '✅' : '❌'} ${key} = ${JSON.stringify(value)}`
|
|
211
|
+
);
|
|
212
|
+
if (!present) allPassed = false;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Run-identity fields: with full inheritance we expect parent's
|
|
216
|
+
// values to flow through. LangGraph runtime MAY overwrite them at
|
|
217
|
+
// child-invoke time — the script logs what actually arrived so we
|
|
218
|
+
// can see empirically what propagates.
|
|
219
|
+
console.log(` ⓘ thread_id observed: "${cfg.thread_id as string}" (parent's: "${outerConfigurable.thread_id}")`);
|
|
220
|
+
console.log(` ⓘ run_id observed: "${cfg.run_id as string}" (parent's: "${outerConfigurable.run_id}")`);
|
|
221
|
+
console.log(` ⓘ parent_run_id observed: "${cfg.parent_run_id as string}" (parent's: "${outerConfigurable.parent_run_id}")`);
|
|
222
|
+
|
|
223
|
+
const threadInherited = cfg.thread_id === outerConfigurable.thread_id;
|
|
224
|
+
const runInherited = cfg.run_id === outerConfigurable.run_id;
|
|
225
|
+
const parentRunInherited =
|
|
226
|
+
cfg.parent_run_id === outerConfigurable.parent_run_id;
|
|
227
|
+
console.log(
|
|
228
|
+
` ${threadInherited ? '✅' : '⚠️ '} thread_id inherited from parent: ${threadInherited}`
|
|
229
|
+
);
|
|
230
|
+
console.log(
|
|
231
|
+
` ${runInherited ? '✅' : '⚠️ '} run_id inherited from parent: ${runInherited}`
|
|
232
|
+
);
|
|
233
|
+
console.log(
|
|
234
|
+
` ${parentRunInherited ? '✅' : '⚠️ '} parent_run_id inherited from parent: ${parentRunInherited}`
|
|
235
|
+
);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
if (allPassed) {
|
|
239
|
+
console.log(
|
|
240
|
+
'\n✅ Host-set fields propagate. (Run-identity inheritance is informational — see ⚠️ markers above for any LangGraph-runtime overwrites.)'
|
|
241
|
+
);
|
|
242
|
+
process.exit(0);
|
|
243
|
+
} else {
|
|
244
|
+
console.log('\n❌ FAIL: at least one expected host-set key was missing.');
|
|
245
|
+
process.exit(1);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
main().catch((err) => {
|
|
250
|
+
console.error('Script error:', err);
|
|
251
|
+
process.exit(1);
|
|
252
|
+
});
|
|
@@ -546,6 +546,154 @@ describe('SubagentExecutor', () => {
|
|
|
546
546
|
expect(observedChildInputs!.maxSubagentDepth).toBeUndefined();
|
|
547
547
|
});
|
|
548
548
|
|
|
549
|
+
describe('parentConfigurable inheritance', () => {
|
|
550
|
+
/**
|
|
551
|
+
* Build a stub factory that captures the second argument to
|
|
552
|
+
* `workflow.invoke()` (the runnable config) so tests can assert on
|
|
553
|
+
* the `configurable` we forwarded to the child graph.
|
|
554
|
+
*/
|
|
555
|
+
function makeCapturingGraphFactory(): {
|
|
556
|
+
factory: () => StandardGraph;
|
|
557
|
+
getInvokeConfig: () => Record<string, unknown> | undefined;
|
|
558
|
+
} {
|
|
559
|
+
let capturedConfig: Record<string, unknown> | undefined;
|
|
560
|
+
const factory = (): StandardGraph =>
|
|
561
|
+
({
|
|
562
|
+
createWorkflow: (): { invoke: jest.Mock } => ({
|
|
563
|
+
invoke: jest
|
|
564
|
+
.fn()
|
|
565
|
+
.mockImplementation(
|
|
566
|
+
async (
|
|
567
|
+
_input: unknown,
|
|
568
|
+
config: Record<string, unknown>
|
|
569
|
+
): Promise<{ messages: BaseMessage[] }> => {
|
|
570
|
+
capturedConfig = config;
|
|
571
|
+
return { messages: [new AIMessage('done')] };
|
|
572
|
+
}
|
|
573
|
+
),
|
|
574
|
+
}),
|
|
575
|
+
clearHeavyState: jest.fn(),
|
|
576
|
+
}) as unknown as StandardGraph;
|
|
577
|
+
return { factory, getInvokeConfig: () => capturedConfig };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
it('forwards parentConfigurable into the child workflow.invoke configurable', async () => {
|
|
581
|
+
const { factory, getInvokeConfig } = makeCapturingGraphFactory();
|
|
582
|
+
const executor = createExecutor({ createChildGraph: factory });
|
|
583
|
+
|
|
584
|
+
await executor.execute({
|
|
585
|
+
description: 'task',
|
|
586
|
+
subagentType: 'researcher',
|
|
587
|
+
parentConfigurable: {
|
|
588
|
+
requestBody: { messageId: 'msg-123', conversationId: 'conv-456' },
|
|
589
|
+
user: { id: 'user_abc' },
|
|
590
|
+
user_id: 'user_abc',
|
|
591
|
+
userMCPAuthMap: { 'mcp-github': { token: 'abc' } },
|
|
592
|
+
},
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
const invokeConfig = getInvokeConfig();
|
|
596
|
+
expect(invokeConfig).toBeDefined();
|
|
597
|
+
const configurable = invokeConfig!.configurable as Record<string, unknown>;
|
|
598
|
+
expect(configurable.requestBody).toEqual({
|
|
599
|
+
messageId: 'msg-123',
|
|
600
|
+
conversationId: 'conv-456',
|
|
601
|
+
});
|
|
602
|
+
expect(configurable.user).toEqual({ id: 'user_abc' });
|
|
603
|
+
expect(configurable.user_id).toBe('user_abc');
|
|
604
|
+
expect(configurable.userMCPAuthMap).toEqual({
|
|
605
|
+
'mcp-github': { token: 'abc' },
|
|
606
|
+
});
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
it('inherits parent thread_id when supplied (subagent is part of same conversation)', async () => {
|
|
610
|
+
const { factory, getInvokeConfig } = makeCapturingGraphFactory();
|
|
611
|
+
const executor = createExecutor({
|
|
612
|
+
createChildGraph: factory,
|
|
613
|
+
parentRunId: 'parent-run-xyz',
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
await executor.execute({
|
|
617
|
+
description: 'task',
|
|
618
|
+
subagentType: 'researcher',
|
|
619
|
+
parentConfigurable: { thread_id: 'parent-thread-conv-abc' },
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
const configurable = getInvokeConfig()!.configurable as Record<
|
|
623
|
+
string,
|
|
624
|
+
unknown
|
|
625
|
+
>;
|
|
626
|
+
expect(configurable.thread_id).toBe('parent-thread-conv-abc');
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
it('falls back to childRunId for thread_id when parent did not supply one', async () => {
|
|
630
|
+
const { factory, getInvokeConfig } = makeCapturingGraphFactory();
|
|
631
|
+
const executor = createExecutor({
|
|
632
|
+
createChildGraph: factory,
|
|
633
|
+
parentRunId: 'parent-run-xyz',
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
await executor.execute({
|
|
637
|
+
description: 'task',
|
|
638
|
+
subagentType: 'researcher',
|
|
639
|
+
parentConfigurable: { user_id: 'user_abc' },
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
const configurable = getInvokeConfig()!.configurable as Record<
|
|
643
|
+
string,
|
|
644
|
+
unknown
|
|
645
|
+
>;
|
|
646
|
+
expect(configurable.thread_id as string).toMatch(/^parent-run-xyz_sub_/);
|
|
647
|
+
expect(configurable.user_id).toBe('user_abc');
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
it('forwards run-identity fields verbatim into the child invoke configurable', async () => {
|
|
651
|
+
const { factory, getInvokeConfig } = makeCapturingGraphFactory();
|
|
652
|
+
const executor = createExecutor({ createChildGraph: factory });
|
|
653
|
+
|
|
654
|
+
await executor.execute({
|
|
655
|
+
description: 'task',
|
|
656
|
+
subagentType: 'researcher',
|
|
657
|
+
parentConfigurable: {
|
|
658
|
+
run_id: 'parent-run-id',
|
|
659
|
+
parent_run_id: 'grandparent-run-id',
|
|
660
|
+
requestBody: { messageId: 'msg-1' },
|
|
661
|
+
},
|
|
662
|
+
});
|
|
663
|
+
|
|
664
|
+
const configurable = getInvokeConfig()!.configurable as Record<
|
|
665
|
+
string,
|
|
666
|
+
unknown
|
|
667
|
+
>;
|
|
668
|
+
// The SDK forwards these fields as part of its inheritance contract.
|
|
669
|
+
// NOTE: the LangGraph runtime overwrites `configurable.run_id` at
|
|
670
|
+
// actual child-invoke time (verified empirically); this unit test
|
|
671
|
+
// only asserts what the SDK forwards into `workflow.invoke` — not
|
|
672
|
+
// what tools downstream observe. `parent_run_id` and other
|
|
673
|
+
// host-set keys do survive the runtime pass-through.
|
|
674
|
+
expect(configurable.run_id).toBe('parent-run-id');
|
|
675
|
+
expect(configurable.parent_run_id).toBe('grandparent-run-id');
|
|
676
|
+
expect(configurable.requestBody).toEqual({ messageId: 'msg-1' });
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
it('does not require parentConfigurable (back-compat with hosts that omit it)', async () => {
|
|
680
|
+
const { factory, getInvokeConfig } = makeCapturingGraphFactory();
|
|
681
|
+
const executor = createExecutor({ createChildGraph: factory });
|
|
682
|
+
|
|
683
|
+
await executor.execute({
|
|
684
|
+
description: 'task',
|
|
685
|
+
subagentType: 'researcher',
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
const configurable = getInvokeConfig()!.configurable as Record<
|
|
689
|
+
string,
|
|
690
|
+
unknown
|
|
691
|
+
>;
|
|
692
|
+
// Only thread_id (childRunId fallback) is set when no parent context is supplied.
|
|
693
|
+
expect(Object.keys(configurable)).toEqual(['thread_id']);
|
|
694
|
+
});
|
|
695
|
+
});
|
|
696
|
+
|
|
549
697
|
describe('hooks', () => {
|
|
550
698
|
let capturedStart: unknown;
|
|
551
699
|
let capturedStop: unknown;
|