@truefoundry/trueforge-core 0.1.0 → 0.1.2
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/README.md +27 -0
- package/dist/agent-session/ITurnResourceResolver.d.ts +8 -7
- package/dist/agent-session/ITurnResourceResolver.d.ts.map +1 -1
- package/dist/agent-session/ITurnResourceResolver.js.map +1 -1
- package/dist/agent-session/SessionHandle.d.ts +12 -0
- package/dist/agent-session/SessionHandle.d.ts.map +1 -1
- package/dist/agent-session/SessionHandle.js +74 -33
- package/dist/agent-session/SessionHandle.js.map +1 -1
- package/dist/agent-session/SessionHandle.mjs +74 -33
- package/dist/agent-session/SessionHandle.mjs.map +1 -1
- package/dist/agent-session/TurnResourceResolver.d.ts +3 -8
- package/dist/agent-session/TurnResourceResolver.d.ts.map +1 -1
- package/dist/agent-session/TurnResourceResolver.js +6 -2
- package/dist/agent-session/TurnResourceResolver.js.map +1 -1
- package/dist/agent-session/TurnResourceResolver.mjs +6 -2
- package/dist/agent-session/TurnResourceResolver.mjs.map +1 -1
- package/dist/agent-session/schemas/turn.d.ts.map +1 -1
- package/dist/agent-session/schemas/turn.js +3 -1
- package/dist/agent-session/schemas/turn.js.map +1 -1
- package/dist/agent-session/schemas/turn.mjs +3 -1
- package/dist/agent-session/schemas/turn.mjs.map +1 -1
- package/dist/agent-session/store/ISessionStore.d.ts +7 -6
- package/dist/agent-session/store/ISessionStore.d.ts.map +1 -1
- package/dist/agent-session/store/ISessionStore.js.map +1 -1
- package/dist/agent-session/store/InMemorySessionStore.d.ts.map +1 -1
- package/dist/agent-session/store/InMemorySessionStore.js +25 -10
- package/dist/agent-session/store/InMemorySessionStore.js.map +1 -1
- package/dist/agent-session/store/InMemorySessionStore.mjs +25 -10
- package/dist/agent-session/store/InMemorySessionStore.mjs.map +1 -1
- package/dist/agent-session/store/OffsetPageToken.d.ts.map +1 -1
- package/dist/agent-session/store/OffsetPageToken.js +3 -1
- package/dist/agent-session/store/OffsetPageToken.js.map +1 -1
- package/dist/agent-session/store/OffsetPageToken.mjs +3 -1
- package/dist/agent-session/store/OffsetPageToken.mjs.map +1 -1
- package/dist/agent-session/store/SessionListPageToken.d.ts.map +1 -1
- package/dist/agent-session/store/SessionListPageToken.js +3 -1
- package/dist/agent-session/store/SessionListPageToken.js.map +1 -1
- package/dist/agent-session/store/SessionListPageToken.mjs +3 -1
- package/dist/agent-session/store/SessionListPageToken.mjs.map +1 -1
- package/dist/core/InstructionBuilder.d.ts.map +1 -1
- package/dist/core/InstructionBuilder.js +12 -4
- package/dist/core/InstructionBuilder.js.map +1 -1
- package/dist/core/InstructionBuilder.mjs +12 -4
- package/dist/core/InstructionBuilder.mjs.map +1 -1
- package/dist/core/capabilities/builtins/AskUserQuestion.d.ts.map +1 -1
- package/dist/core/capabilities/builtins/AskUserQuestion.js +5 -0
- package/dist/core/capabilities/builtins/AskUserQuestion.js.map +1 -1
- package/dist/core/capabilities/builtins/AskUserQuestion.mjs +5 -0
- package/dist/core/capabilities/builtins/AskUserQuestion.mjs.map +1 -1
- package/dist/core/capabilities/builtins/LargeToolResponse.d.ts.map +1 -1
- package/dist/core/capabilities/builtins/LargeToolResponse.js +6 -2
- package/dist/core/capabilities/builtins/LargeToolResponse.js.map +1 -1
- package/dist/core/capabilities/builtins/LargeToolResponse.mjs +6 -2
- package/dist/core/capabilities/builtins/LargeToolResponse.mjs.map +1 -1
- package/dist/core/llm/VercelAILLM.d.ts.map +1 -1
- package/dist/core/llm/VercelAILLM.js +6 -2
- package/dist/core/llm/VercelAILLM.js.map +1 -1
- package/dist/core/llm/VercelAILLM.mjs +6 -2
- package/dist/core/llm/VercelAILLM.mjs.map +1 -1
- package/dist/core/mcp/RemoteMCP.d.ts.map +1 -1
- package/dist/core/mcp/RemoteMCP.js +15 -5
- package/dist/core/mcp/RemoteMCP.js.map +1 -1
- package/dist/core/mcp/RemoteMCP.mjs +15 -5
- package/dist/core/mcp/RemoteMCP.mjs.map +1 -1
- package/dist/core/mcp/ToolSelectorPolicy.d.ts.map +1 -1
- package/dist/core/mcp/ToolSelectorPolicy.js +3 -1
- package/dist/core/mcp/ToolSelectorPolicy.js.map +1 -1
- package/dist/core/mcp/ToolSelectorPolicy.mjs +3 -1
- package/dist/core/mcp/ToolSelectorPolicy.mjs.map +1 -1
- package/dist/core/mcp/ToolSet.d.ts.map +1 -1
- package/dist/core/mcp/ToolSet.js +9 -3
- package/dist/core/mcp/ToolSet.js.map +1 -1
- package/dist/core/mcp/ToolSet.mjs +9 -3
- package/dist/core/mcp/ToolSet.mjs.map +1 -1
- package/dist/core/mcp/convertMCPServers.d.ts.map +1 -1
- package/dist/core/mcp/convertMCPServers.js +6 -2
- package/dist/core/mcp/convertMCPServers.js.map +1 -1
- package/dist/core/mcp/convertMCPServers.mjs +6 -2
- package/dist/core/mcp/convertMCPServers.mjs.map +1 -1
- package/dist/core/mcp/remoteMcpClient.d.ts.map +1 -1
- package/dist/core/mcp/remoteMcpClient.js +21 -7
- package/dist/core/mcp/remoteMcpClient.js.map +1 -1
- package/dist/core/mcp/remoteMcpClient.mjs +21 -7
- package/dist/core/mcp/remoteMcpClient.mjs.map +1 -1
- package/dist/core/mcp/toolSelectors.d.ts.map +1 -1
- package/dist/core/mcp/toolSelectors.js +18 -6
- package/dist/core/mcp/toolSelectors.js.map +1 -1
- package/dist/core/mcp/toolSelectors.mjs +18 -6
- package/dist/core/mcp/toolSelectors.mjs.map +1 -1
- package/dist/core/runtime/AgentThread.d.ts.map +1 -1
- package/dist/core/runtime/AgentThread.js +42 -17
- package/dist/core/runtime/AgentThread.js.map +1 -1
- package/dist/core/runtime/AgentThread.mjs +42 -17
- package/dist/core/runtime/AgentThread.mjs.map +1 -1
- package/dist/core/runtime/AgentThreadOrchestrator.d.ts.map +1 -1
- package/dist/core/runtime/AgentThreadOrchestrator.js +27 -9
- package/dist/core/runtime/AgentThreadOrchestrator.js.map +1 -1
- package/dist/core/runtime/AgentThreadOrchestrator.mjs +27 -9
- package/dist/core/runtime/AgentThreadOrchestrator.mjs.map +1 -1
- package/dist/core/runtime/DeferredTool.d.ts.map +1 -1
- package/dist/core/runtime/DeferredTool.js +15 -5
- package/dist/core/runtime/DeferredTool.js.map +1 -1
- package/dist/core/runtime/DeferredTool.mjs +15 -5
- package/dist/core/runtime/DeferredTool.mjs.map +1 -1
- package/dist/core/runtime/contextUtils.d.ts.map +1 -1
- package/dist/core/runtime/contextUtils.js +3 -1
- package/dist/core/runtime/contextUtils.js.map +1 -1
- package/dist/core/runtime/contextUtils.mjs +3 -1
- package/dist/core/runtime/contextUtils.mjs.map +1 -1
- package/dist/core/sandbox/Sandbox.d.ts.map +1 -1
- package/dist/core/sandbox/Sandbox.js +12 -4
- package/dist/core/sandbox/Sandbox.js.map +1 -1
- package/dist/core/sandbox/Sandbox.mjs +12 -4
- package/dist/core/sandbox/Sandbox.mjs.map +1 -1
- package/dist/core/sandbox/codeMode/CodeModeDispatcher.d.ts.map +1 -1
- package/dist/core/sandbox/codeMode/CodeModeDispatcher.js +9 -3
- package/dist/core/sandbox/codeMode/CodeModeDispatcher.js.map +1 -1
- package/dist/core/sandbox/codeMode/CodeModeDispatcher.mjs +9 -3
- package/dist/core/sandbox/codeMode/CodeModeDispatcher.mjs.map +1 -1
- package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.d.ts.map +1 -1
- package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.js +9 -3
- package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.js.map +1 -1
- package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.mjs +9 -3
- package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.mjs.map +1 -1
- package/dist/core/sandbox/provider/DaytonaProvider.d.ts +17 -0
- package/dist/core/sandbox/provider/DaytonaProvider.d.ts.map +1 -1
- package/dist/core/sandbox/provider/DaytonaProvider.js +83 -17
- package/dist/core/sandbox/provider/DaytonaProvider.js.map +1 -1
- package/dist/core/sandbox/provider/DaytonaProvider.mjs +83 -17
- package/dist/core/sandbox/provider/DaytonaProvider.mjs.map +1 -1
- package/dist/core/sandbox/provider/TFYSandboxProvider.d.ts.map +1 -1
- package/dist/core/sandbox/provider/TFYSandboxProvider.js +12 -4
- package/dist/core/sandbox/provider/TFYSandboxProvider.js.map +1 -1
- package/dist/core/sandbox/provider/TFYSandboxProvider.mjs +12 -4
- package/dist/core/sandbox/provider/TFYSandboxProvider.mjs.map +1 -1
- package/dist/core/sandbox/skills/SkillMounter.d.ts.map +1 -1
- package/dist/core/sandbox/skills/SkillMounter.js +3 -1
- package/dist/core/sandbox/skills/SkillMounter.js.map +1 -1
- package/dist/core/sandbox/skills/SkillMounter.mjs +3 -1
- package/dist/core/sandbox/skills/SkillMounter.mjs.map +1 -1
- package/dist/core/util/abort.d.ts.map +1 -1
- package/dist/core/util/abort.js +3 -1
- package/dist/core/util/abort.js.map +1 -1
- package/dist/core/util/abort.mjs +3 -1
- package/dist/core/util/abort.mjs.map +1 -1
- package/package.json +10 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/runtime/AgentThread.ts"],"sourcesContent":["import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat';\nimport type { Logger } from 'winston';\nimport type { AgentCapability, CapabilityState } from '../capabilities/AgentCapability';\nimport type {\n AgentContextProcessorOutput,\n AgentContextProcessorOverwriteContext,\n AgentThreadExecutionContext,\n PostToolCallAgentContextProcessor,\n PreLLMAgentContextProcessor,\n PreLLMEphemeralAgentContextProcessor,\n PreSendContextProcessor,\n} from '../capabilities/AgentContextProcessor';\nimport { SUB_AGENT_IDENTITY } from '../capabilities/builtins/DynamicSubAgents';\nimport type { ToolResponseProcessor } from '../capabilities/ToolResponseProcessor';\nimport { AgentHarnessError, InvalidAgentSendInputError } from '../errors';\nimport type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';\nimport {\n EventType,\n newEventId,\n type AgentApprovalDecisionMessage,\n type AgentInfo,\n type AgentOutputEvent,\n type AgentParent,\n type MCPInitializeEvent,\n type MCPServerInitInfo,\n type ModelMessageDeltaEvent,\n type ModelMessageEvent,\n type ModelMessageUsage,\n type SandboxCreatedEvent,\n type ThreadOverwriteContextEvent,\n type ToolApprovalRequiredEvent,\n type ToolResponseEvent,\n type ToolResponseRequiredEvent,\n type UserToolApprovalMessage,\n type UserToolResponseMessage,\n} from '../events/schema';\nimport { InstructionBuilder, ROOT_AGENT_IDENTITY } from '../InstructionBuilder';\nimport type { LLMCreateParamsStreaming } from '../llm/ILLM';\nimport {\n type CompletionUsage,\n type ExtendedChatCompletionChunk,\n type FinishReason,\n type InternalEnrichedAssistantMessage,\n type InternalEnrichedToolCall,\n type LLMToolMessage,\n type LLMUserMessage,\n type RawAssistantMessage,\n} from '../llm/LLMTypes';\nimport { toOpenAIResponseFormat } from '../llm/responseFormat';\nimport { toOpenAIChatMessage } from '../llm/toOpenAIChatMessage';\nimport { estimateTokensForString } from '../llm/usage';\nimport { convertMCPServersToTools, type ConvertToolsResult, type MappedMCPTool } from '../mcp/convertMCPServers';\nimport { executeToolCalls } from '../mcp/executeToolCalls';\nimport type { IToolSet, MCPAuthRequired } from '../mcp/IMCPServer';\nimport type { Sandbox, SandboxInfo } from '../sandbox/Sandbox';\nimport type { AgentTracing } from '../tracing/AgentTracing';\nimport { describeUnknownError, extractErrorLogFields } from '../util/errorLogFields';\nimport type { AgentDefinition } from './AgentDefinition';\nimport type {\n AgentThreadConstructorInput,\n AgentThreadRuntimeSendBatch,\n AgentThreadRuntimeSendInput,\n AgentThreadSnapshot,\n} from './AgentThread.types';\nimport {\n InternalEventType,\n type AgentThreadAppendContext,\n type AgentThreadEvent,\n type ContextMessage,\n type InternalCapabilityStateEvent,\n type InternalMCPAuthRequiredEvent,\n type InternalThreadDoneEvent,\n type SubAgentCompletionMarker,\n} from './AgentThread.types';\nimport {\n currentContextUsageFromCompletion,\n getEmptyCurrentContextUsage,\n mergeCurrentContextUsage,\n type CurrentContextUsage,\n} from './contextUsage';\nimport {\n assistantMessageContentToStringForSubAgent,\n estimateTokensForContextMessages,\n INTERNAL_SYSTEM_PROMPT,\n isApprovalDecisionMessage,\n isClientSideToolResponseMessage,\n isInputUserMessage,\n isLLMContextMessage,\n isLLMToolMessage,\n makeUnknownToolInfo,\n scanApprovalDecisions,\n toEnrichedToolCall,\n toToolCallInfo,\n} from './contextUtils';\nimport { DeferredTool } from './DeferredTool';\nimport { createEmptyAgentThreadMetrics, updateMetricsFromUsage, type AgentThreadMetrics } from './metrics';\nimport { getClosableOpenToolCallIds, OpenToolCallCloser } from './OpenToolCallCloser';\nimport { isEmptyMessageContent, processAgentUserInput, type AgentInputUserMessage } from './UserInputMessage';\n\nconst DEFAULT_ITERATION_LIMIT = 25;\n\ntype AgentThreadState = 'llm-call-required' | 'tool-response-required' | 'user-input-required';\n\ntype StepOutcome = 'exit' | 'continue';\n\nconst VALID_TRANSITIONS: Record<AgentThreadState, AgentThreadState[]> = {\n 'llm-call-required': ['tool-response-required', 'user-input-required'],\n 'tool-response-required': ['llm-call-required'],\n // user-input-required transitions to:\n // tool-response-required — after approval decisions are appended (approval flow)\n // llm-call-required — after client-side tool responses resolve tool calls directly\n 'user-input-required': ['tool-response-required', 'llm-call-required'],\n};\n\nfunction assertValidTransition(from: AgentThreadState, to: AgentThreadState): void {\n if (!VALID_TRANSITIONS[from].includes(to)) {\n throw new Error(`Invalid state transition: ${from} → ${to}`);\n }\n}\n\nfunction deriveAgentThreadState(context: ContextMessage[]): AgentThreadState {\n const openToolCallIds = getOpenToolCallIds(context);\n if (openToolCallIds.size === 0) return 'llm-call-required';\n\n const assistant = lastAssistantInContext(context);\n const decisions = scanApprovalDecisions(context);\n const hasPendingApproval = assistant?.tool_calls?.some(\n tc => openToolCallIds.has(tc.id) && tc.tool_info.is_approval_required === true && !decisions.has(tc.id),\n );\n const hasPendingClientSideTool = assistant?.tool_calls?.some(\n tc => openToolCallIds.has(tc.id) && tc.tool_info.is_client_side === true,\n );\n return hasPendingApproval || hasPendingClientSideTool ? 'user-input-required' : 'tool-response-required';\n}\n\nfunction hasToolCalls(message: InternalEnrichedAssistantMessage): boolean {\n return Boolean(message.tool_calls && message.tool_calls.length > 0);\n}\n\n// Tool call ids issued by the last assistant message that have no matching\n// tool response after it. Walks the context tail-first and stops at the last\n// assistant message — under the invariant that older assistant tool_calls are\n// already resolved, only the last assistant message can have open ids.\nfunction getOpenToolCallIds(context: ContextMessage[]): Set<string> {\n const resolvedToolCallIds = new Set<string>();\n const openToolCallIds = new Set<string>();\n for (let i = context.length - 1; i >= 0; i--) {\n const msg = context[i];\n if (msg === undefined) continue;\n if (!isLLMContextMessage(msg)) continue;\n if (msg.role === 'tool') {\n resolvedToolCallIds.add(msg.tool_call_id);\n continue;\n }\n if (msg.role === 'assistant') {\n for (const tc of msg.tool_calls ?? []) openToolCallIds.add(tc.id);\n for (const id of resolvedToolCallIds) openToolCallIds.delete(id);\n break;\n }\n }\n return openToolCallIds;\n}\n\nfunction lastAssistantInContext(context: ContextMessage[]): InternalEnrichedAssistantMessage | undefined {\n return context.findLast(\n (msg): msg is InternalEnrichedAssistantMessage => isLLMContextMessage(msg) && msg.role === 'assistant',\n );\n}\n\n// Open tool calls that block a new user message: the open set minus those OpenToolCallCloser will\n// auto-close during preSend. Lets a user message resume a thread whose only open calls are dangling\n// regular tool calls (which the closer repairs), while still blocking on approval/client-side/\n// sub-agent calls that genuinely need resolution. Takes the already-computed open set; copies it\n// since it mutates (deletes) the closable ids.\nfunction getUnclosableOpenToolCallIds(context: ContextMessage[], openToolCallIds: Set<string>): Set<string> {\n const blockingOpenToolCallIds = new Set(openToolCallIds);\n for (const id of getClosableOpenToolCallIds(context)) {\n blockingOpenToolCallIds.delete(id);\n }\n return blockingOpenToolCallIds;\n}\n\nfunction buildMCPInitializeEvent(initInfo: MCPServerInitInfo[], threadId: string): MCPInitializeEvent {\n return {\n type: EventType.MCP_INITIALIZE,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: threadId,\n mcp_servers: initInfo,\n };\n}\n\nfunction buildMCPAuthRequiredEvent(\n authRequirementInfo: MCPAuthRequired[],\n threadId: string,\n): InternalMCPAuthRequiredEvent {\n return {\n type: InternalEventType.MCP_AUTH_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n mcp_servers: authRequirementInfo.flatMap(or => or.servers.map(s => ({ ...s, thread_ids: [threadId] }))),\n // threadId identifies which thread triggered auth for each server so AgentThreadOrchestrator can merge\n // auth events across parallel sub-agents by server.\n thread_id: null,\n };\n}\n\nfunction buildSandboxCreatedEvent(info: SandboxInfo): SandboxCreatedEvent {\n return {\n type: EventType.SANDBOX_CREATED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n ...info,\n thread_id: null,\n };\n}\n\nfunction buildModelMessageEvent({\n assistantMessage,\n threadId,\n finishReason,\n usage,\n id,\n}: {\n assistantMessage: InternalEnrichedAssistantMessage;\n threadId: string;\n finishReason: FinishReason | null;\n usage: ModelMessageUsage | undefined;\n id: string;\n}): ModelMessageEvent {\n // `thinking_blocks` / `source` stay on the context message for replay; strip them from the client event.\n const { role, tool_calls, thinking_blocks, source, ...rest } = assistantMessage;\n void role;\n void thinking_blocks;\n void source;\n const event: ModelMessageEvent = {\n ...rest,\n tool_calls: tool_calls?.map(toEnrichedToolCall),\n type: EventType.MODEL_MESSAGE,\n id,\n created_at: new Date().toISOString(),\n thread_id: threadId,\n finish_reason: finishReason,\n ...(usage && { usage }),\n };\n return event;\n}\n\nfunction validateUserMessage(\n message: { content: AgentInputUserMessage['content'] },\n blockingOpenToolCallIds: Set<string>,\n index: number,\n): void {\n if (isEmptyMessageContent(message.content)) {\n throw new InvalidAgentSendInputError(`messages[${String(index)}] user message has empty content`);\n }\n if (blockingOpenToolCallIds.size > 0) {\n throw new InvalidAgentSendInputError('user message cannot be sent while approvals or questions are pending');\n }\n}\n\nfunction validateToolMessage(\n message: LLMToolMessage | UserToolResponseMessage,\n openToolCallIds: Set<string>,\n index: number,\n): void {\n if (!openToolCallIds.has(message.tool_call_id)) {\n throw new InvalidAgentSendInputError(\n `messages[${String(index)}] no open tool call for tool_call_id '${message.tool_call_id}'`,\n );\n }\n}\n\nfunction validateApprovalMessage(\n message: UserToolApprovalMessage,\n pendingApprovalIds: Set<string>,\n index: number,\n): void {\n if (!pendingApprovalIds.has(message.tool_call_id)) {\n throw new InvalidAgentSendInputError(\n `messages[${String(index)}] no pending approval for tool_call_id '${message.tool_call_id}'`,\n );\n }\n}\n\nfunction getPendingApprovalToolCalls(context: ContextMessage[]): InternalEnrichedToolCall[] {\n const openToolCallIds = getOpenToolCallIds(context);\n const decisions = scanApprovalDecisions(context);\n const assistant = lastAssistantInContext(context);\n return (assistant?.tool_calls ?? []).filter(\n tc => openToolCallIds.has(tc.id) && tc.tool_info.is_approval_required === true && !decisions.has(tc.id),\n );\n}\n\nfunction getPendingClientSideToolCalls(context: ContextMessage[]): InternalEnrichedToolCall[] {\n const openToolCallIds = getOpenToolCallIds(context);\n const assistant = lastAssistantInContext(context);\n return (assistant?.tool_calls ?? []).filter(tc => openToolCallIds.has(tc.id) && tc.tool_info.is_client_side === true);\n}\n\nfunction validateInputMessageTypesGivenContext(\n context: ContextMessage[],\n messages: AgentThreadRuntimeSendInput[],\n): void {\n // Full open set: validates incoming tool responses and dedupes within the batch.\n const openToolCallIds = getOpenToolCallIds(context);\n // Subset that blocks a fresh user message: excludes calls OpenToolCallCloser will auto-close\n // during preSend, so a dangling regular tool call doesn't reject a user message it will repair.\n const blockingOpenToolCallIds = getUnclosableOpenToolCallIds(context, openToolCallIds);\n const pendingApprovalIds = new Set(getPendingApprovalToolCalls(context).map(tc => tc.id));\n const pendingClientSideIds = new Set(getPendingClientSideToolCalls(context).map(tc => tc.id));\n\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m === undefined) continue;\n if (isApprovalDecisionMessage(m)) {\n validateApprovalMessage(m, pendingApprovalIds, i);\n pendingApprovalIds.delete(m.tool_call_id);\n } else if (isInputUserMessage(m)) {\n validateUserMessage(m, blockingOpenToolCallIds, i);\n } else if (isClientSideToolResponseMessage(m) || isLLMToolMessage(m)) {\n validateToolMessage(m, openToolCallIds, i);\n openToolCallIds.delete(m.tool_call_id);\n blockingOpenToolCallIds.delete(m.tool_call_id);\n pendingClientSideIds.delete(m.tool_call_id);\n } else {\n const _exhaustive: never = m;\n throw new InvalidAgentSendInputError(\n `messages[${String(i)}] has unsupported type: ${JSON.stringify(_exhaustive)}`,\n );\n }\n }\n\n // A send for a thread awaiting user input must resolve every pending approval and client-side\n // tool call in the same batch; any left unresolved (including an empty batch) is a blocker.\n if (pendingApprovalIds.size > 0 || pendingClientSideIds.size > 0) {\n const missing = [...pendingApprovalIds, ...pendingClientSideIds];\n throw new InvalidAgentSendInputError(\n `Send batch must resolve all pending tool calls awaiting user input. Missing: ${missing.join(', ')}`,\n );\n }\n}\n\nasync function buildModelMessageDeltaEvent({\n chunk,\n threadId,\n toolMapping,\n usage,\n id,\n logger,\n}: {\n chunk: ExtendedChatCompletionChunk;\n threadId: string;\n toolMapping: Map<string, MappedMCPTool>;\n usage: ModelMessageUsage | undefined;\n id: string;\n logger: Logger;\n}): Promise<ModelMessageDeltaEvent | undefined> {\n const choice = chunk.choices[0];\n const delta = choice?.delta;\n const finishReason = choice?.finish_reason;\n\n if (!delta || (Object.keys(delta).length === 0 && !finishReason && !usage)) {\n return;\n }\n\n // Drop empty deltas that carry no displayable or actionable data\n if (!delta.tool_calls?.length && !delta.content && !delta.reasoning_content && !finishReason && !usage) {\n return;\n }\n\n const toolCalls = delta.tool_calls ?? [];\n for (const toolCall of toolCalls) {\n if (toolCall.function?.name) {\n const toolInfo = toolMapping.get(toolCall.function.name);\n if (!toolInfo) {\n logger.warn(`LLM called unknown tool: Tool ${toolCall.function.name} not found in tool mapping.`);\n toolCall.tool_info = toToolCallInfo(makeUnknownToolInfo(toolCall.function.name));\n continue;\n }\n toolCall.tool_info = toToolCallInfo(\n await toolInfo.toolSet.toolCallInfo({ name: toolInfo.originalToolName }, false /* resolveUnderlyingTool */),\n );\n }\n }\n\n // Strip legacy `function_call` and replay-only `thinking_blocks` so neither reaches the client or delta stream.\n const { role, function_call, thinking_blocks, ...deltaWithoutRole } = delta;\n void role;\n void function_call;\n void thinking_blocks;\n return {\n ...deltaWithoutRole,\n type: EventType.MODEL_MESSAGE_DELTA,\n id,\n thread_id: threadId,\n ...(finishReason && { finish_reason: finishReason }),\n ...(usage && { usage }),\n };\n}\n\nasync function buildContextAssistantMessage(\n assistantMessage: RawAssistantMessage,\n toolMapping: Map<string, MappedMCPTool>,\n): Promise<InternalEnrichedAssistantMessage> {\n // Omit tool_calls when empty; OpenAI rejects `tool_calls: []` on replay.\n if (!assistantMessage.tool_calls?.length) {\n const { tool_calls, ...rest } = assistantMessage;\n void tool_calls;\n return rest;\n }\n\n // Sequential loop instead of Promise.all: the first call populates the MCP server's tool cache\n // (via listTools), making subsequent calls instant cache hits.\n // No race conditions either way but parallelism buys nothing here.\n const enrichedToolCalls = [];\n for (const toolCall of assistantMessage.tool_calls) {\n const toolInfo = toolMapping.get(toolCall.function.name);\n if (!toolInfo) {\n enrichedToolCalls.push({ ...toolCall, tool_info: makeUnknownToolInfo(toolCall.function.name) });\n continue;\n }\n const tool_info = await toolInfo.toolSet.toolCallInfo(\n {\n name: toolInfo.originalToolName,\n arguments: tryParseToolArgs(toolCall.function.arguments),\n },\n // During context persistence, we have the complete message and hence the tool arguments are available.\n // Hence, we resolve the underlying tool to get the tool information.\n true /* resolveUnderlyingTool */,\n );\n enrichedToolCalls.push({ ...toolCall, tool_info });\n }\n return { ...assistantMessage, tool_calls: enrichedToolCalls };\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// Args are only used by DeferredTool to delegate to the underlying server.\n// Defensive parse — hallucinated JSON shouldn't crash assistant-message construction.\nfunction tryParseToolArgs(args: string | undefined): Record<string, unknown> {\n if (!args) return {};\n try {\n const parsed: unknown = JSON.parse(args);\n return isJsonObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\n// State-sync contract: in-memory state must stay consistent with what the consumer\n// def foo():\n// for x in range(1, 10):\n// yield x\n// # This cannot raise exception\n// # This does not execute if update_redis fails.\n// update_local_context(x)\n// for x in foo():\n// # This can raise exception.\n// update_redis(x)\n\nexport class AgentThread {\n readonly threadId: string;\n readonly parent?: AgentParent | undefined;\n readonly definition: AgentDefinition;\n readonly title: string;\n readonly agentInfo?: AgentInfo | undefined;\n\n private context: ContextMessage[];\n private currentContextUsage: CurrentContextUsage;\n private preSendContextProcessors: PreSendContextProcessor[];\n private preLLMContextProcessors: PreLLMAgentContextProcessor[];\n private preEphemeralLLMContextProcessors: PreLLMEphemeralAgentContextProcessor[];\n private postToolCallContextProcessor: PostToolCallAgentContextProcessor[];\n\n private instruction: string | undefined;\n private toolResponseProcessors: ToolResponseProcessor[];\n private instructionBuilders: readonly ((builder: InstructionBuilder) => void)[];\n private systemToolSets: readonly IToolSet[];\n private deferredTool?: DeferredTool | undefined;\n private convertedTools: ConvertToolsResult | undefined;\n private pendingSandboxCreatedEvents: SandboxCreatedEvent[] = [];\n private sandbox?: Sandbox | undefined;\n private readonly tracing: AgentTracing;\n private readonly logger: Logger;\n\n private metrics: AgentThreadMetrics = createEmptyAgentThreadMetrics();\n private tfyManagedServerNames = new Set<string>();\n\n private contextBusy = false;\n private preSendRanThisTurn = false;\n private currentState: AgentThreadState | null = null;\n private readonly preComputedCompletion?: SubAgentCompletionMarker | undefined;\n /** Mirrored capability KV — source for toSnapshot().capability_state. */\n private capabilityState: CapabilityState = {};\n private readonly capabilityStateKeys: ReadonlySet<string>;\n\n constructor(input: AgentThreadConstructorInput) {\n this.tracing = input.tracing;\n this.logger = input.logger.child({ module: 'AgentThread' });\n this.threadId = input.threadId;\n this.definition = input.definition;\n this.context = input.context ? [...input.context] : [];\n this.title = input.title;\n this.parent = input.parent;\n this.currentContextUsage = input.currentContextUsage ?? getEmptyCurrentContextUsage();\n this.agentInfo = input.agentInfo;\n this.preComputedCompletion = input.preComputedCompletion;\n this.sandbox = input.sandbox;\n\n const capabilities = input.capabilities ?? [];\n this.systemToolSets = capabilities.flatMap(c => c.systemToolSets ?? []);\n this.preLLMContextProcessors = capabilities.flatMap(c => c.preLLMProcessors ?? []);\n this.preEphemeralLLMContextProcessors = capabilities.flatMap(c => c.preLLMEphemeralProcessors ?? []);\n this.postToolCallContextProcessor = capabilities.flatMap(c => c.postToolCallProcessors ?? []);\n this.toolResponseProcessors = capabilities.flatMap(c => c.toolResponseProcessors ?? []);\n this.instructionBuilders = capabilities.flatMap(c => c.instructionBuilders ?? []);\n const capabilityPreSend = capabilities.flatMap(c => c.preSendProcessors ?? []);\n // OpenToolCallCloser is fixed core before contributed preSend processors.\n this.preSendContextProcessors = [new OpenToolCallCloser(), ...capabilityPreSend];\n\n assertUniqueStateKeys(capabilities);\n const claimed = claimCapabilityState(capabilities, input.capabilityState, this.logger);\n this.capabilityState = claimed;\n this.capabilityStateKeys = new Set(\n capabilities.map(c => c.state?.key).filter((k): k is string => typeof k === 'string'),\n );\n for (const capability of capabilities) {\n if (!capability.state) continue;\n const value = claimed[capability.state.key];\n if (value !== undefined) {\n capability.state.load(value);\n }\n }\n\n if (this.definition.toolSets?.length) {\n this.deferredTool = new DeferredTool(this.definition.toolSets, {\n tracing: this.tracing,\n logger: input.logger,\n });\n }\n\n if (this.sandbox) {\n this.sandbox.configureCodeMode(this.definition.toolSets ?? []);\n }\n\n this.instruction = this.buildInstruction(this.definition.instruction);\n }\n\n private buildInstruction(userInstruction?: string): string {\n const identity = this.parent ? SUB_AGENT_IDENTITY : ROOT_AGENT_IDENTITY;\n const builder = InstructionBuilder.createSystemPrompt(identity);\n const capabilities = builder.beginSection('agent-capabilities');\n capabilities.addSection('internal-messages', INTERNAL_SYSTEM_PROMPT);\n\n if (this.sandbox) {\n this.sandbox.buildInstruction(capabilities);\n }\n if (this.deferredTool) {\n this.deferredTool.buildInstruction(capabilities);\n }\n for (const build of this.instructionBuilders) {\n build(capabilities);\n }\n if (!this.parent && userInstruction?.trim()) {\n builder.addSection('user-instructions', userInstruction.trim(), true);\n }\n return builder.build();\n }\n\n public async *send(messages: AgentThreadRuntimeSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {\n // An empty batch is a no-op only when the thread is not awaiting user input.\n // While awaiting input, fall through so the validator rejects the empty/incomplete batch.\n if (messages.length === 0 && !this.isAwaitingUserInput()) {\n return;\n }\n this.throwIfContextBusy();\n\n this.contextBusy = true;\n try {\n for await (const event of this.executeContextProcessors('preSend')) {\n yield event;\n }\n this.preSendRanThisTurn = true;\n\n validateInputMessageTypesGivenContext(this.context, messages);\n\n const approvals: UserToolApprovalMessage[] = [];\n const clientSideToolResponses: UserToolResponseMessage[] = [];\n const contextMessages: (LLMUserMessage | LLMToolMessage)[] = [];\n\n for (const m of messages) {\n if (isApprovalDecisionMessage(m)) {\n approvals.push(m);\n } else if (isClientSideToolResponseMessage(m)) {\n clientSideToolResponses.push(m);\n } else if (isInputUserMessage(m)) {\n const result = await processAgentUserInput(m, this.sandbox);\n contextMessages.push(result.message);\n if (result.sandboxCreated) {\n this.pendingSandboxCreatedEvents.push(buildSandboxCreatedEvent(result.sandboxCreated));\n }\n } else if (isLLMToolMessage(m)) {\n contextMessages.push(m);\n } else {\n const _exhaustive: never = m;\n throw new InvalidAgentSendInputError(`Unsupported send input: ${JSON.stringify(_exhaustive)}`);\n }\n }\n\n if (approvals.length > 0 || clientSideToolResponses.length > 0) {\n const approvalContext: AgentApprovalDecisionMessage[] = approvals.map(a => ({\n type: EventType.USER_TOOL_APPROVAL,\n tool_call_id: a.tool_call_id,\n approval: a.approval,\n }));\n const toolResponseContext: LLMToolMessage[] = clientSideToolResponses.map(m => ({\n role: 'tool',\n tool_call_id: m.tool_call_id,\n content: m.content,\n }));\n yield* this.appendToContext({\n context: [...approvalContext, ...toolResponseContext],\n output: [],\n currentContextUsage: undefined,\n usage: undefined,\n });\n }\n if (contextMessages.length > 0) {\n yield* this.appendToContext({\n context: contextMessages,\n output: [],\n currentContextUsage: undefined,\n usage: undefined,\n });\n }\n } finally {\n this.contextBusy = false;\n }\n }\n\n private throwIfContextBusy(): void {\n if (this.contextBusy) {\n throw new Error(`context is busy for thread ${this.threadId}`);\n }\n }\n\n private deriveState(): AgentThreadState {\n const next = deriveAgentThreadState(this.context);\n if (this.currentState) {\n assertValidTransition(this.currentState, next);\n }\n this.currentState = next;\n return next;\n }\n\n private *appendToContext(opts: {\n context: ContextMessage[];\n output: AgentOutputEvent[];\n currentContextUsage: CurrentContextUsage | undefined;\n usage: CompletionUsage | undefined;\n completion?: SubAgentCompletionMarker | undefined;\n }): Generator<AgentThreadAppendContext, void, unknown> {\n const { context, output, currentContextUsage, usage, completion } = opts;\n\n const newCurrentContextUsage =\n currentContextUsage ??\n mergeCurrentContextUsage(this.currentContextUsage, estimateTokensForContextMessages(context));\n\n const event: AgentThreadAppendContext = {\n type: InternalEventType.AGENT_CONTEXT_APPEND,\n thread_id: this.threadId,\n context,\n output,\n current_context_usage: newCurrentContextUsage,\n ...(completion && { completion }),\n };\n\n // Update metrics before yield so we still count it if the stream stops here.\n if (usage) {\n updateMetricsFromUsage(this.metrics, usage);\n }\n\n yield event;\n\n this.context = this.context.concat(context);\n this.currentContextUsage = newCurrentContextUsage;\n }\n\n private *overwriteContext(\n payload: AgentContextProcessorOverwriteContext,\n ): Generator<ThreadOverwriteContextEvent, void, unknown> {\n const event: ThreadOverwriteContextEvent = {\n thread_id: this.threadId,\n ...payload,\n };\n // Update metrics before yield so we still count it if the stream stops here.\n updateMetricsFromUsage(this.metrics, payload.usage);\n\n yield event;\n this.context = payload.context;\n this.currentContextUsage = payload.current_context_usage;\n this.metrics.total_summarizations++;\n }\n\n private generateErrorEvent(message: string, output?: ModelMessageEvent): InternalThreadDoneEvent {\n return {\n type: InternalEventType.AGENT_DONE,\n status: 'error',\n thread_id: this.threadId,\n title: this.title,\n error: message,\n parent: this.parent,\n send_to_parent: this.parent\n ? {\n role: 'tool',\n content: message,\n tool_call_id: this.parent.tool_call_id,\n }\n : undefined,\n ...(output && { output }),\n };\n }\n\n public hasOpenToolCallId(toolCallId: string): boolean {\n return getOpenToolCallIds(this.context).has(toolCallId);\n }\n\n // True when this thread is paused waiting on the user to resolve a pending tool\n // approval or a client-side tool response.\n public isAwaitingUserInput(): boolean {\n return (\n getPendingApprovalToolCalls(this.context).length > 0 || getPendingClientSideToolCalls(this.context).length > 0\n );\n }\n\n // Pure validation of an input batch against this thread's current context; throws\n // on an invalid/incomplete batch without mutating the context.\n public validateSendInput(messages: AgentThreadRuntimeSendBatch): void {\n validateInputMessageTypesGivenContext(this.context, messages);\n }\n\n public toSnapshot(): AgentThreadSnapshot {\n const capability_state = Object.keys(this.capabilityState).length > 0 ? { ...this.capabilityState } : null;\n return {\n thread_id: this.threadId,\n context: this.context,\n current_context_usage: this.currentContextUsage,\n parent: this.parent ?? null,\n agent_info: this.agentInfo ?? null,\n completion: this.preComputedCompletion ?? null,\n capability_state,\n };\n }\n\n public getAgentThreadMetrics(): AgentThreadMetrics {\n return { ...this.metrics };\n }\n\n private transformToLLMRequest(tools: ChatCompletionTool[]): LLMCreateParamsStreaming {\n let messages: ChatCompletionMessageParam[] = [];\n\n if (this.instruction) {\n messages.push({\n role: 'system',\n content: this.instruction,\n });\n }\n\n if (this.definition.messages) {\n for (const msg of this.definition.messages) {\n if (isLLMContextMessage(msg)) {\n messages.push(toOpenAIChatMessage(msg));\n }\n }\n }\n\n // NOTE: all this code-golf is to remove `tool_info` before sending the message to Gateway\n // ApprovalDecisionMessage rows are persisted in context but must not be sent to the LLM.\n const contextMessages = this.context.filter(isLLMContextMessage).map(msg => toOpenAIChatMessage(msg));\n\n messages.push(...contextMessages);\n\n for (const processor of this.preEphemeralLLMContextProcessors) {\n messages = processor.processPreLLMEphemeral(messages) ?? messages;\n }\n\n // modelParams may include provider extensions (e.g. reasoning_effort) beyond the SDK's\n // ChatCompletionCreateParamsStreaming field set; assign after constructing the typed body.\n // Model identity is owned by modelClient — do not set `model` on the request.\n const requestBody: LLMCreateParamsStreaming = {\n messages,\n stream: true,\n ...(this.definition.responseFormat !== undefined\n ? { response_format: toOpenAIResponseFormat(this.definition.responseFormat) }\n : {}),\n };\n if (this.definition.modelParams) {\n Object.assign(requestBody, this.definition.modelParams);\n }\n\n if (tools.length > 0) {\n requestBody.tools = tools;\n }\n\n return requestBody;\n }\n\n private computeAssistantMessageUsage(params: {\n requestBody: LLMCreateParamsStreaming;\n usage: CompletionUsage;\n toolMapping: Map<string, MappedMCPTool>;\n }): ModelMessageUsage {\n const { requestBody, usage, toolMapping } = params;\n // Sub-agents have no <user-instructions> section — their agent.instruction is\n // SUB_AGENT_IDENTITY which is harness content, not user-defined instructions.\n const trimmedInstruction = this.definition.instruction?.trim() ?? '';\n const instructionsEstimate = this.parent ? 0 : Math.round(estimateTokensForString(trimmedInstruction));\n\n const skillsEstimate = this.sandbox?.estimateSkillsTokens() ?? 0;\n\n let tfyManagedToolTokens = 0;\n let userToolTokens = 0;\n if (requestBody.tools) {\n for (const tool of requestBody.tools) {\n const toolTokens = Math.round(estimateTokensForString(JSON.stringify(tool)));\n const info = 'function' in tool ? toolMapping.get(tool.function.name) : undefined;\n if (info && this.tfyManagedServerNames.has(info.toolSet.name)) {\n tfyManagedToolTokens += toolTokens;\n } else {\n userToolTokens += toolTokens;\n }\n }\n }\n\n const totalInstructionTokens = Math.round(estimateTokensForString(this.instruction ?? ''));\n const harnessInstructionTokens = Math.max(0, totalInstructionTokens - instructionsEstimate - skillsEstimate);\n const harnessEstimate = harnessInstructionTokens + tfyManagedToolTokens;\n\n const estimatedComponentsTotal = harnessEstimate + skillsEstimate + instructionsEstimate + userToolTokens;\n const messagesEstimate = Math.max(0, usage.input_tokens - estimatedComponentsTotal);\n\n return {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cache_read_tokens: usage.cache_read_tokens,\n cache_write_tokens: usage.cache_write_tokens,\n input_tokens_breakdown: {\n harness: harnessEstimate,\n skills: skillsEstimate,\n instructions: instructionsEstimate,\n tool_definitions: userToolTokens,\n messages: messagesEstimate,\n },\n };\n }\n\n private executeContextProcessors(hook: 'preSend'): AsyncGenerator<AgentThreadAppendContext, void, unknown>;\n private executeContextProcessors(\n hook: 'preLLM' | 'postToolCall',\n ): AsyncGenerator<\n | ThreadOverwriteContextEvent\n | AgentThreadAppendContext\n | { type: typeof InternalEventType.PASSTHROUGH; event: RegisteredPassthroughEvent }\n | InternalCapabilityStateEvent,\n void,\n unknown\n >;\n private async *executeContextProcessors(\n hook: 'preSend' | 'preLLM' | 'postToolCall',\n ): AsyncGenerator<\n | ThreadOverwriteContextEvent\n | AgentThreadAppendContext\n | { type: typeof InternalEventType.PASSTHROUGH; event: RegisteredPassthroughEvent }\n | InternalCapabilityStateEvent,\n void,\n unknown\n > {\n let processors: ((\n execution: Readonly<AgentThreadExecutionContext>,\n ) => AsyncIterable<AgentContextProcessorOutput>)[];\n switch (hook) {\n case 'preSend':\n processors = this.preSendContextProcessors.map(p => p.processPreSend.bind(p));\n break;\n case 'preLLM':\n processors = this.preLLMContextProcessors.map(p => p.processPreLLM.bind(p));\n break;\n case 'postToolCall':\n processors = this.postToolCallContextProcessor.map(p => p.processPostToolCall.bind(p));\n break;\n default:\n throw new Error(`Unknown hook: ${String(hook)}`);\n }\n\n const execution: Readonly<AgentThreadExecutionContext> = {\n threadId: this.threadId,\n sandbox: this.sandbox,\n currentContextUsage: this.currentContextUsage,\n context: this.context,\n };\n\n for (const processor of processors) {\n for await (const response of processor(execution)) {\n switch (response.type) {\n case InternalEventType.AGENT_CONTEXT_APPEND:\n yield* this.appendToContext({\n context: response.context,\n output: response.output,\n currentContextUsage: response.current_context_usage ?? this.currentContextUsage,\n usage: undefined,\n });\n break;\n case EventType.AGENT_CONTEXT_OVERWRITE:\n yield* this.overwriteContext(response);\n break;\n case InternalEventType.PASSTHROUGH:\n yield response;\n break;\n case InternalEventType.CAPABILITY_STATE:\n if (!this.capabilityStateKeys.has(response.key)) {\n throw new AgentHarnessError(\n 'capability_state_error',\n `CAPABILITY_STATE key '${response.key}' is not declared by any capability on thread '${this.threadId}'`,\n );\n }\n yield {\n type: InternalEventType.CAPABILITY_STATE,\n thread_id: this.threadId,\n key: response.key,\n state: response.state,\n };\n this.capabilityState[response.key] = response.state;\n break;\n default: {\n const _exhaustive: never = response;\n return _exhaustive;\n }\n }\n }\n }\n }\n\n private async init(): Promise<{\n initializationInfo: MCPServerInitInfo[];\n authRequirementInfo: MCPAuthRequired[];\n }> {\n if (this.convertedTools) {\n return { initializationInfo: [], authRequirementInfo: [] };\n }\n return this.initTools();\n }\n\n private async initTools(): Promise<{\n initializationInfo: MCPServerInitInfo[];\n authRequirementInfo: MCPAuthRequired[];\n }> {\n const tfyManagedServers: IToolSet[] = [...this.systemToolSets];\n if (this.sandbox) {\n tfyManagedServers.push(this.sandbox);\n }\n if (this.deferredTool) {\n tfyManagedServers.push(this.deferredTool);\n }\n const userServers = [...(this.definition.toolSets ?? [])];\n\n const { convertedTools, initializationInfo, authRequirementInfo } = await convertMCPServersToTools({\n tfyManagedServers,\n userServers,\n });\n this.convertedTools = convertedTools;\n this.tfyManagedServerNames = new Set(tfyManagedServers.map(s => s.name));\n return { initializationInfo, authRequirementInfo };\n }\n\n private getConvertedTools(): ConvertToolsResult {\n if (!this.convertedTools) {\n throw new Error('unreachable');\n }\n return this.convertedTools;\n }\n\n private async *stepLLMCall(\n tools: ChatCompletionTool[],\n toolMapping: Map<string, MappedMCPTool>,\n signal?: AbortSignal,\n ): AsyncGenerator<AgentThreadEvent, { outcome: StepOutcome; modelMessageEventId: string }, unknown> {\n const modelMessageEventId = newEventId();\n if (signal?.aborted) {\n return { outcome: 'exit', modelMessageEventId };\n }\n\n for await (const event of this.executeContextProcessors('preLLM')) {\n yield event;\n }\n\n const requestBody = this.transformToLLMRequest(tools);\n const llmStream = this.definition.modelClient.create(requestBody);\n\n // We start the delta stream with a model message event.\n yield {\n type: EventType.MODEL_MESSAGE,\n thread_id: this.threadId,\n created_at: new Date().toISOString(),\n id: modelMessageEventId,\n } satisfies ModelMessageEvent;\n\n let firstDeltaTimestamped = false;\n let result = await llmStream.next();\n let modelMessageUsage: ModelMessageUsage | undefined = undefined;\n while (!result.done) {\n const chunk = result.value;\n if (chunk.usage) {\n modelMessageUsage = this.computeAssistantMessageUsage({\n requestBody,\n usage: chunk.usage,\n toolMapping,\n });\n }\n const event = await buildModelMessageDeltaEvent({\n chunk,\n threadId: this.threadId,\n toolMapping,\n usage: modelMessageUsage,\n id: modelMessageEventId,\n logger: this.logger,\n });\n if (event) {\n if (!firstDeltaTimestamped) {\n firstDeltaTimestamped = true;\n yield { ...event, created_at: new Date().toISOString() };\n } else {\n yield event;\n }\n }\n result = await llmStream.next();\n }\n\n // If the stream was aborted mid-way, result.value.output is only a partial\n // accumulation of the deltas — not the true complete response. Skip the\n // final model.message event to avoid emitting an inconsistent assembled message.\n if (signal?.aborted) {\n return { outcome: 'exit', modelMessageEventId };\n }\n\n // should be computed by this point but in case provider never gives out any delta with usage, compute it now.\n modelMessageUsage ??= this.computeAssistantMessageUsage({\n requestBody,\n usage: result.value.usage,\n toolMapping,\n });\n const assistantMessage: InternalEnrichedAssistantMessage = await buildContextAssistantMessage(\n result.value.output,\n toolMapping,\n );\n const finishReason = result.value.finish_reason;\n const agentAssistantMessage = buildModelMessageEvent({\n assistantMessage,\n threadId: this.threadId,\n finishReason,\n usage: modelMessageUsage,\n id: modelMessageEventId,\n });\n\n let completion: SubAgentCompletionMarker | undefined;\n if (this.parent) {\n if (finishReason === 'length') {\n const errorMessage = assistantMessageContentToStringForSubAgent(\n assistantMessage.content,\n 'max_tokens breached',\n );\n completion = {\n type: 'error',\n output: agentAssistantMessage,\n error_message: errorMessage,\n send_to_parent: { role: 'tool', tool_call_id: this.parent.tool_call_id, content: errorMessage },\n };\n } else if (!hasToolCalls(assistantMessage)) {\n const content = assistantMessageContentToStringForSubAgent(assistantMessage.content);\n completion = {\n type: 'done',\n output: agentAssistantMessage,\n send_to_parent: { role: 'tool', tool_call_id: this.parent.tool_call_id, content },\n };\n }\n }\n\n yield* this.appendToContext({\n context: [assistantMessage],\n output: [agentAssistantMessage],\n currentContextUsage: currentContextUsageFromCompletion(result.value.usage),\n usage: result.value.usage,\n completion,\n });\n\n if (finishReason === 'length') {\n const errorContent = completion?.error_message ?? 'max_tokens breached';\n yield this.generateErrorEvent(errorContent, agentAssistantMessage);\n return { outcome: 'exit', modelMessageEventId };\n }\n\n if (!hasToolCalls(assistantMessage)) {\n yield {\n type: InternalEventType.AGENT_DONE,\n status: 'done',\n thread_id: this.threadId,\n title: this.title,\n output: agentAssistantMessage,\n parent: this.parent,\n send_to_parent: completion?.send_to_parent,\n };\n return { outcome: 'exit', modelMessageEventId };\n }\n\n return { outcome: 'continue', modelMessageEventId };\n }\n\n private async *stepToolResponse(\n toolMapping: Map<string, MappedMCPTool>,\n ): AsyncGenerator<AgentThreadEvent, StepOutcome, unknown> {\n const assistantMessage = lastAssistantInContext(this.context);\n if (!assistantMessage) {\n throw new Error('unreachable');\n }\n\n const openIds = getOpenToolCallIds(this.context);\n const openCalls = assistantMessage.tool_calls?.filter(tc => openIds.has(tc.id)) ?? [];\n const decisions = scanApprovalDecisions(this.context);\n\n const assistantForExecution: InternalEnrichedAssistantMessage = {\n ...assistantMessage,\n tool_calls: openCalls,\n };\n const {\n toolCallResults,\n initializationInfo,\n createThreadEvents,\n sandboxCreated,\n authRequirementInfo,\n approvalRequiredToolCalls,\n clientSideToolCalls,\n events: passthroughEvents,\n } = await executeToolCalls({\n assistantMessage: assistantForExecution,\n toolMapping,\n threadId: this.threadId,\n approvalDecisions: decisions,\n });\n void clientSideToolCalls;\n if (approvalRequiredToolCalls.length > 0) {\n throw new Error('Unreachable');\n }\n this.metrics.total_tool_calls += toolCallResults.length;\n this.metrics.total_sub_agents += createThreadEvents.length;\n\n if (initializationInfo.length > 0) {\n yield buildMCPInitializeEvent(initializationInfo, this.threadId);\n }\n\n if (sandboxCreated) {\n yield buildSandboxCreatedEvent(sandboxCreated);\n }\n\n for (const event of passthroughEvents) {\n yield { type: InternalEventType.PASSTHROUGH, event };\n }\n\n const toolIdsBeforeProcessing = toolCallResults.map(t => t.message.tool_call_id);\n const toolResponseExecution: Readonly<AgentThreadExecutionContext> = {\n threadId: this.threadId,\n sandbox: this.sandbox,\n currentContextUsage: this.currentContextUsage,\n context: this.context,\n };\n for (const processor of this.toolResponseProcessors) {\n const processorResult = await processor.process(toolCallResults, toolResponseExecution);\n if (processorResult.sandboxCreated) {\n yield buildSandboxCreatedEvent(processorResult.sandboxCreated);\n }\n for (const event of processorResult.events ?? []) {\n yield { type: InternalEventType.PASSTHROUGH, event };\n }\n }\n if (toolIdsBeforeProcessing.length !== toolCallResults.length) {\n throw Error('Some tool call processor has removed tool call.');\n }\n const toolIdsAfterProcessing = new Set(toolCallResults.map(t => t.message.tool_call_id));\n\n if (!toolIdsBeforeProcessing.every(id => toolIdsAfterProcessing.has(id))) {\n throw Error('Tool call IDs do not match after processing.');\n }\n\n const agentToolMessages: ToolResponseEvent[] = toolCallResults.map(t => {\n const { role, ...toolMessage } = t.message;\n void role;\n return {\n ...toolMessage,\n type: EventType.TOOL_RESPONSE,\n id: newEventId(),\n created_at: t.completedAt,\n thread_id: this.threadId,\n };\n });\n for (const msg of agentToolMessages) {\n yield msg;\n }\n // tool.response is persisted by the session/response layer when yielded; only mutate context here.\n yield* this.appendToContext({\n context: toolCallResults.map(t => t.message),\n output: [],\n currentContextUsage: undefined,\n usage: undefined,\n });\n\n if (authRequirementInfo.length > 0) {\n yield buildMCPAuthRequiredEvent(authRequirementInfo, this.threadId);\n return 'exit';\n }\n\n for await (const event of this.executeContextProcessors('postToolCall')) {\n yield event;\n }\n for (const event of createThreadEvents) {\n yield event;\n }\n if (createThreadEvents.length > 0) {\n return 'exit';\n }\n\n return 'continue';\n }\n\n private *stepUserInputRequired(modelMessageEventId: string): Generator<AgentThreadEvent, StepOutcome, unknown> {\n const pendingClientSideToolCalls = getPendingClientSideToolCalls(this.context);\n if (pendingClientSideToolCalls.length > 0) {\n const responseRequiredEvent: ToolResponseRequiredEvent = {\n type: EventType.TOOL_RESPONSE_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: this.threadId,\n tool_calls: pendingClientSideToolCalls.map(tc => ({ id: tc.id, source_event_id: modelMessageEventId })),\n };\n yield responseRequiredEvent;\n }\n\n const pendingApprovalToolCalls = getPendingApprovalToolCalls(this.context);\n if (pendingApprovalToolCalls.length > 0) {\n const event: ToolApprovalRequiredEvent = {\n type: EventType.TOOL_APPROVAL_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: this.threadId,\n tool_calls: pendingApprovalToolCalls.map(({ id }) => ({ id, source_event_id: modelMessageEventId })),\n };\n yield event;\n }\n return 'exit';\n }\n\n private buildReplayEvent(c: SubAgentCompletionMarker): InternalThreadDoneEvent {\n const base = {\n type: InternalEventType.AGENT_DONE,\n thread_id: this.threadId,\n title: this.title,\n parent: this.parent,\n send_to_parent: c.send_to_parent,\n };\n return c.type === 'done'\n ? { ...base, status: 'done', output: c.output }\n : { ...base, status: 'error', error: c.error_message ?? 'Sub-agent errored', output: c.output };\n }\n\n public async *execute(options?: {\n signal?: AbortSignal | undefined;\n }): AsyncGenerator<AgentThreadEvent, void, unknown> {\n const signal = options?.signal;\n\n this.throwIfContextBusy();\n this.contextBusy = true;\n this.currentState = null;\n\n // there should always be this top level try-catch block because agent execution cant raise an error. it should yield an error event.\n try {\n if (this.preComputedCompletion) {\n yield this.buildReplayEvent(this.preComputedCompletion);\n return;\n }\n\n if (!this.preSendRanThisTurn) {\n for await (const event of this.executeContextProcessors('preSend')) {\n yield event;\n }\n }\n this.preSendRanThisTurn = false;\n const { initializationInfo, authRequirementInfo } = await this.tracing.withInitSpan(() => this.init());\n\n if (initializationInfo.length > 0) {\n yield buildMCPInitializeEvent(initializationInfo, this.threadId);\n }\n\n if (authRequirementInfo.length > 0) {\n yield buildMCPAuthRequiredEvent(authRequirementInfo, this.threadId);\n return;\n }\n\n const { tools, toolMapping } = this.getConvertedTools();\n\n const iterationLimit = this.definition.iterationLimit ?? DEFAULT_ITERATION_LIMIT;\n // Starts empty; set only after stepLLMCall in this execute(). That is intentional:\n // user-input-required is only reachable here right after an LLM step that produced\n // pending approval/client-side tools (which sets currentModelMessageEventId first).\n // A resumed turn that is still awaiting user input never reaches this loop — orchestrator\n // send() / validateSendInput rejects empty or incomplete batches before execute runs.\n let currentModelMessageEventId = '';\n\n for (;;) {\n for (;;) {\n const sandboxCreatedEvent = this.pendingSandboxCreatedEvents.shift();\n if (sandboxCreatedEvent === undefined) break;\n yield sandboxCreatedEvent;\n }\n\n const state = this.deriveState();\n let outcome: StepOutcome;\n switch (state) {\n case 'llm-call-required': {\n // Cancel only before network/side-effecting steps (LLM call, tool execution), never before 'user-input-required', so the required event is always emitted once the assistant message is committed.\n if (signal?.aborted) return;\n if (this.metrics.iterations >= iterationLimit) {\n yield this.generateErrorEvent(\n `You have reached iteration limit of ${String(iterationLimit)}, please request again`,\n );\n return;\n }\n this.metrics.iterations++;\n\n const llmResult = yield* this.stepLLMCall(tools, toolMapping, signal);\n outcome = llmResult.outcome;\n currentModelMessageEventId = llmResult.modelMessageEventId;\n break;\n }\n case 'tool-response-required': {\n if (signal?.aborted) return;\n outcome = yield* this.stepToolResponse(toolMapping);\n break;\n }\n case 'user-input-required': {\n // Intentionally no cancellation check here — see comment in 'llm-call-required'.\n // source_event_id comes from currentModelMessageEventId; see comment where it is declared.\n outcome = yield* this.stepUserInputRequired(currentModelMessageEventId);\n break;\n }\n default: {\n throw new Error('unreachable');\n }\n }\n if (outcome === 'exit') return;\n }\n } catch (error) {\n // Providers / transports often reject with plain objects; instanceof Error would\n // otherwise collapse those into an opaque \"Unknown error occurred\" in Agent Steps.\n this.logger.error('Agent thread execution failed', extractErrorLogFields(error));\n yield this.generateErrorEvent(describeUnknownError(error));\n } finally {\n this.contextBusy = false;\n }\n }\n}\n\nfunction assertUniqueStateKeys(capabilities: readonly AgentCapability[]): void {\n const seen = new Set<string>();\n for (const capability of capabilities) {\n const key = capability.state?.key;\n if (!key) continue;\n if (seen.has(key)) {\n throw new AgentHarnessError(\n 'capability_state_error',\n `Duplicate capability state key '${key}' — each key may be claimed by at most one capability`,\n );\n }\n seen.add(key);\n }\n}\n\nfunction claimCapabilityState(\n capabilities: readonly AgentCapability[],\n input: CapabilityState | undefined,\n logger: Logger,\n): CapabilityState {\n if (!input) return {};\n const claimedKeys = new Set(capabilities.map(c => c.state?.key).filter((k): k is string => typeof k === 'string'));\n const claimed: CapabilityState = {};\n for (const [key, value] of Object.entries(input)) {\n if (!claimedKeys.has(key)) {\n logger.warn(`Dropping unclaimed capability_state key '${key}' — no capability declares it`);\n continue;\n }\n claimed[key] = value;\n }\n return claimed;\n}\n"],"mappings":";AAYA,SAAS,0BAA0B;AAEnC,SAAS,mBAAmB,kCAAkC;AAE9D;AAAA,EACE;AAAA,EACA;AAAA,OAiBK;AACP,SAAS,oBAAoB,2BAA2B;AAExD,OASO;AACP,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,+BAA+B;AACxC,SAAS,gCAA6E;AACtF,SAAS,wBAAwB;AAIjC,SAAS,sBAAsB,6BAA6B;AAQ5D;AAAA,EACE;AAAA,OAQK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,+BAA+B,8BAAuD;AAC/F,SAAS,4BAA4B,0BAA0B;AAC/D,SAAS,uBAAuB,6BAAyD;AAEzF,IAAM,0BAA0B;AAMhC,IAAM,oBAAkE;AAAA,EACtE,qBAAqB,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AA,EACd;AACF;AAEA,SAAS,qBACP,cACA,OACA,QACiB;AACjB,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,QAAM,cAAc,IAAI,IAAI,aAAa,IAAI,OAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,CAAC;AACjH,QAAM,UAA2B,CAAC;AAClC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,CAAC,YAAY,IAAI,GAAG,GAAG;AACzB,aAAO,KAAK,4CAA4C,GAAG,oCAA+B;AAC1F;AAAA,IACF;AACA,YAAQ,GAAG,IAAI;AAAA,EACjB;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/runtime/AgentThread.ts"],"sourcesContent":["import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat';\nimport type { Logger } from 'winston';\nimport type { AgentCapability, CapabilityState } from '../capabilities/AgentCapability';\nimport type {\n AgentContextProcessorOutput,\n AgentContextProcessorOverwriteContext,\n AgentThreadExecutionContext,\n PostToolCallAgentContextProcessor,\n PreLLMAgentContextProcessor,\n PreLLMEphemeralAgentContextProcessor,\n PreSendContextProcessor,\n} from '../capabilities/AgentContextProcessor';\nimport { SUB_AGENT_IDENTITY } from '../capabilities/builtins/DynamicSubAgents';\nimport type { ToolResponseProcessor } from '../capabilities/ToolResponseProcessor';\nimport { AgentHarnessError, InvalidAgentSendInputError } from '../errors';\nimport type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';\nimport {\n EventType,\n newEventId,\n type AgentApprovalDecisionMessage,\n type AgentInfo,\n type AgentOutputEvent,\n type AgentParent,\n type MCPInitializeEvent,\n type MCPServerInitInfo,\n type ModelMessageDeltaEvent,\n type ModelMessageEvent,\n type ModelMessageUsage,\n type SandboxCreatedEvent,\n type ThreadOverwriteContextEvent,\n type ToolApprovalRequiredEvent,\n type ToolResponseEvent,\n type ToolResponseRequiredEvent,\n type UserToolApprovalMessage,\n type UserToolResponseMessage,\n} from '../events/schema';\nimport { InstructionBuilder, ROOT_AGENT_IDENTITY } from '../InstructionBuilder';\nimport type { LLMCreateParamsStreaming } from '../llm/ILLM';\nimport {\n type CompletionUsage,\n type ExtendedChatCompletionChunk,\n type FinishReason,\n type InternalEnrichedAssistantMessage,\n type InternalEnrichedToolCall,\n type LLMToolMessage,\n type LLMUserMessage,\n type RawAssistantMessage,\n} from '../llm/LLMTypes';\nimport { toOpenAIResponseFormat } from '../llm/responseFormat';\nimport { toOpenAIChatMessage } from '../llm/toOpenAIChatMessage';\nimport { estimateTokensForString } from '../llm/usage';\nimport { convertMCPServersToTools, type ConvertToolsResult, type MappedMCPTool } from '../mcp/convertMCPServers';\nimport { executeToolCalls } from '../mcp/executeToolCalls';\nimport type { IToolSet, MCPAuthRequired } from '../mcp/IMCPServer';\nimport type { Sandbox, SandboxInfo } from '../sandbox/Sandbox';\nimport type { AgentTracing } from '../tracing/AgentTracing';\nimport { describeUnknownError, extractErrorLogFields } from '../util/errorLogFields';\nimport type { AgentDefinition } from './AgentDefinition';\nimport type {\n AgentThreadConstructorInput,\n AgentThreadRuntimeSendBatch,\n AgentThreadRuntimeSendInput,\n AgentThreadSnapshot,\n} from './AgentThread.types';\nimport {\n InternalEventType,\n type AgentThreadAppendContext,\n type AgentThreadEvent,\n type ContextMessage,\n type InternalCapabilityStateEvent,\n type InternalMCPAuthRequiredEvent,\n type InternalThreadDoneEvent,\n type SubAgentCompletionMarker,\n} from './AgentThread.types';\nimport {\n currentContextUsageFromCompletion,\n getEmptyCurrentContextUsage,\n mergeCurrentContextUsage,\n type CurrentContextUsage,\n} from './contextUsage';\nimport {\n assistantMessageContentToStringForSubAgent,\n estimateTokensForContextMessages,\n INTERNAL_SYSTEM_PROMPT,\n isApprovalDecisionMessage,\n isClientSideToolResponseMessage,\n isInputUserMessage,\n isLLMContextMessage,\n isLLMToolMessage,\n makeUnknownToolInfo,\n scanApprovalDecisions,\n toEnrichedToolCall,\n toToolCallInfo,\n} from './contextUtils';\nimport { DeferredTool } from './DeferredTool';\nimport { createEmptyAgentThreadMetrics, updateMetricsFromUsage, type AgentThreadMetrics } from './metrics';\nimport { getClosableOpenToolCallIds, OpenToolCallCloser } from './OpenToolCallCloser';\nimport { isEmptyMessageContent, processAgentUserInput, type AgentInputUserMessage } from './UserInputMessage';\n\nconst DEFAULT_ITERATION_LIMIT = 25;\n\ntype AgentThreadState = 'llm-call-required' | 'tool-response-required' | 'user-input-required';\n\ntype StepOutcome = 'exit' | 'continue';\n\nconst VALID_TRANSITIONS: Record<AgentThreadState, AgentThreadState[]> = {\n 'llm-call-required': ['tool-response-required', 'user-input-required'],\n 'tool-response-required': ['llm-call-required'],\n // user-input-required transitions to:\n // tool-response-required — after approval decisions are appended (approval flow)\n // llm-call-required — after client-side tool responses resolve tool calls directly\n 'user-input-required': ['tool-response-required', 'llm-call-required'],\n};\n\nfunction assertValidTransition(from: AgentThreadState, to: AgentThreadState): void {\n if (!VALID_TRANSITIONS[from].includes(to)) {\n throw new Error(`Invalid state transition: ${from} → ${to}`);\n }\n}\n\nfunction deriveAgentThreadState(context: ContextMessage[]): AgentThreadState {\n const openToolCallIds = getOpenToolCallIds(context);\n if (openToolCallIds.size === 0) {\n return 'llm-call-required';\n }\n\n const assistant = lastAssistantInContext(context);\n const decisions = scanApprovalDecisions(context);\n const hasPendingApproval = assistant?.tool_calls?.some(\n tc => openToolCallIds.has(tc.id) && tc.tool_info.is_approval_required === true && !decisions.has(tc.id),\n );\n const hasPendingClientSideTool = assistant?.tool_calls?.some(\n tc => openToolCallIds.has(tc.id) && tc.tool_info.is_client_side === true,\n );\n return hasPendingApproval || hasPendingClientSideTool ? 'user-input-required' : 'tool-response-required';\n}\n\nfunction hasToolCalls(message: InternalEnrichedAssistantMessage): boolean {\n return Boolean(message.tool_calls && message.tool_calls.length > 0);\n}\n\n// Tool call ids issued by the last assistant message that have no matching\n// tool response after it. Walks the context tail-first and stops at the last\n// assistant message — under the invariant that older assistant tool_calls are\n// already resolved, only the last assistant message can have open ids.\nfunction getOpenToolCallIds(context: ContextMessage[]): Set<string> {\n const resolvedToolCallIds = new Set<string>();\n const openToolCallIds = new Set<string>();\n for (let i = context.length - 1; i >= 0; i--) {\n const msg = context[i];\n if (msg === undefined) {\n continue;\n }\n if (!isLLMContextMessage(msg)) {\n continue;\n }\n if (msg.role === 'tool') {\n resolvedToolCallIds.add(msg.tool_call_id);\n continue;\n }\n if (msg.role === 'assistant') {\n for (const tc of msg.tool_calls ?? []) {\n openToolCallIds.add(tc.id);\n }\n for (const id of resolvedToolCallIds) {\n openToolCallIds.delete(id);\n }\n break;\n }\n }\n return openToolCallIds;\n}\n\nfunction lastAssistantInContext(context: ContextMessage[]): InternalEnrichedAssistantMessage | undefined {\n return context.findLast(\n (msg): msg is InternalEnrichedAssistantMessage => isLLMContextMessage(msg) && msg.role === 'assistant',\n );\n}\n\n// Open tool calls that block a new user message: the open set minus those OpenToolCallCloser will\n// auto-close during preSend. Lets a user message resume a thread whose only open calls are dangling\n// regular tool calls (which the closer repairs), while still blocking on approval/client-side/\n// sub-agent calls that genuinely need resolution. Takes the already-computed open set; copies it\n// since it mutates (deletes) the closable ids.\nfunction getUnclosableOpenToolCallIds(context: ContextMessage[], openToolCallIds: Set<string>): Set<string> {\n const blockingOpenToolCallIds = new Set(openToolCallIds);\n for (const id of getClosableOpenToolCallIds(context)) {\n blockingOpenToolCallIds.delete(id);\n }\n return blockingOpenToolCallIds;\n}\n\nfunction buildMCPInitializeEvent(initInfo: MCPServerInitInfo[], threadId: string): MCPInitializeEvent {\n return {\n type: EventType.MCP_INITIALIZE,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: threadId,\n mcp_servers: initInfo,\n };\n}\n\nfunction buildMCPAuthRequiredEvent(\n authRequirementInfo: MCPAuthRequired[],\n threadId: string,\n): InternalMCPAuthRequiredEvent {\n return {\n type: InternalEventType.MCP_AUTH_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n mcp_servers: authRequirementInfo.flatMap(or => or.servers.map(s => ({ ...s, thread_ids: [threadId] }))),\n // threadId identifies which thread triggered auth for each server so AgentThreadOrchestrator can merge\n // auth events across parallel sub-agents by server.\n thread_id: null,\n };\n}\n\nfunction buildSandboxCreatedEvent(info: SandboxInfo): SandboxCreatedEvent {\n return {\n type: EventType.SANDBOX_CREATED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n ...info,\n thread_id: null,\n };\n}\n\nfunction buildModelMessageEvent({\n assistantMessage,\n threadId,\n finishReason,\n usage,\n id,\n}: {\n assistantMessage: InternalEnrichedAssistantMessage;\n threadId: string;\n finishReason: FinishReason | null;\n usage: ModelMessageUsage | undefined;\n id: string;\n}): ModelMessageEvent {\n // `thinking_blocks` / `source` stay on the context message for replay; strip them from the client event.\n const { role, tool_calls, thinking_blocks, source, ...rest } = assistantMessage;\n void role;\n void thinking_blocks;\n void source;\n const event: ModelMessageEvent = {\n ...rest,\n tool_calls: tool_calls?.map(toEnrichedToolCall),\n type: EventType.MODEL_MESSAGE,\n id,\n created_at: new Date().toISOString(),\n thread_id: threadId,\n finish_reason: finishReason,\n ...(usage && { usage }),\n };\n return event;\n}\n\nfunction validateUserMessage(\n message: { content: AgentInputUserMessage['content'] },\n blockingOpenToolCallIds: Set<string>,\n index: number,\n): void {\n if (isEmptyMessageContent(message.content)) {\n throw new InvalidAgentSendInputError(`messages[${String(index)}] user message has empty content`);\n }\n if (blockingOpenToolCallIds.size > 0) {\n throw new InvalidAgentSendInputError('user message cannot be sent while approvals or questions are pending');\n }\n}\n\nfunction validateToolMessage(\n message: LLMToolMessage | UserToolResponseMessage,\n openToolCallIds: Set<string>,\n index: number,\n): void {\n if (!openToolCallIds.has(message.tool_call_id)) {\n throw new InvalidAgentSendInputError(\n `messages[${String(index)}] no open tool call for tool_call_id '${message.tool_call_id}'`,\n );\n }\n}\n\nfunction validateApprovalMessage(\n message: UserToolApprovalMessage,\n pendingApprovalIds: Set<string>,\n index: number,\n): void {\n if (!pendingApprovalIds.has(message.tool_call_id)) {\n throw new InvalidAgentSendInputError(\n `messages[${String(index)}] no pending approval for tool_call_id '${message.tool_call_id}'`,\n );\n }\n}\n\nfunction getPendingApprovalToolCalls(context: ContextMessage[]): InternalEnrichedToolCall[] {\n const openToolCallIds = getOpenToolCallIds(context);\n const decisions = scanApprovalDecisions(context);\n const assistant = lastAssistantInContext(context);\n return (assistant?.tool_calls ?? []).filter(\n tc => openToolCallIds.has(tc.id) && tc.tool_info.is_approval_required === true && !decisions.has(tc.id),\n );\n}\n\nfunction getPendingClientSideToolCalls(context: ContextMessage[]): InternalEnrichedToolCall[] {\n const openToolCallIds = getOpenToolCallIds(context);\n const assistant = lastAssistantInContext(context);\n return (assistant?.tool_calls ?? []).filter(tc => openToolCallIds.has(tc.id) && tc.tool_info.is_client_side === true);\n}\n\nfunction validateInputMessageTypesGivenContext(\n context: ContextMessage[],\n messages: AgentThreadRuntimeSendInput[],\n): void {\n // Full open set: validates incoming tool responses and dedupes within the batch.\n const openToolCallIds = getOpenToolCallIds(context);\n // Subset that blocks a fresh user message: excludes calls OpenToolCallCloser will auto-close\n // during preSend, so a dangling regular tool call doesn't reject a user message it will repair.\n const blockingOpenToolCallIds = getUnclosableOpenToolCallIds(context, openToolCallIds);\n const pendingApprovalIds = new Set(getPendingApprovalToolCalls(context).map(tc => tc.id));\n const pendingClientSideIds = new Set(getPendingClientSideToolCalls(context).map(tc => tc.id));\n\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m === undefined) {\n continue;\n }\n if (isApprovalDecisionMessage(m)) {\n validateApprovalMessage(m, pendingApprovalIds, i);\n pendingApprovalIds.delete(m.tool_call_id);\n } else if (isInputUserMessage(m)) {\n validateUserMessage(m, blockingOpenToolCallIds, i);\n } else if (isClientSideToolResponseMessage(m) || isLLMToolMessage(m)) {\n validateToolMessage(m, openToolCallIds, i);\n openToolCallIds.delete(m.tool_call_id);\n blockingOpenToolCallIds.delete(m.tool_call_id);\n pendingClientSideIds.delete(m.tool_call_id);\n } else {\n const _exhaustive: never = m;\n throw new InvalidAgentSendInputError(\n `messages[${String(i)}] has unsupported type: ${JSON.stringify(_exhaustive)}`,\n );\n }\n }\n\n // A send for a thread awaiting user input must resolve every pending approval and client-side\n // tool call in the same batch; any left unresolved (including an empty batch) is a blocker.\n if (pendingApprovalIds.size > 0 || pendingClientSideIds.size > 0) {\n const missing = [...pendingApprovalIds, ...pendingClientSideIds];\n throw new InvalidAgentSendInputError(\n `Send batch must resolve all pending tool calls awaiting user input. Missing: ${missing.join(', ')}`,\n );\n }\n}\n\nasync function buildModelMessageDeltaEvent({\n chunk,\n threadId,\n toolMapping,\n usage,\n id,\n logger,\n}: {\n chunk: ExtendedChatCompletionChunk;\n threadId: string;\n toolMapping: Map<string, MappedMCPTool>;\n usage: ModelMessageUsage | undefined;\n id: string;\n logger: Logger;\n}): Promise<ModelMessageDeltaEvent | undefined> {\n const choice = chunk.choices[0];\n const delta = choice?.delta;\n const finishReason = choice?.finish_reason;\n\n if (!delta || (Object.keys(delta).length === 0 && !finishReason && !usage)) {\n return;\n }\n\n // Drop empty deltas that carry no displayable or actionable data\n if (!delta.tool_calls?.length && !delta.content && !delta.reasoning_content && !finishReason && !usage) {\n return;\n }\n\n const toolCalls = delta.tool_calls ?? [];\n for (const toolCall of toolCalls) {\n if (toolCall.function?.name) {\n const toolInfo = toolMapping.get(toolCall.function.name);\n if (!toolInfo) {\n logger.warn(`LLM called unknown tool: Tool ${toolCall.function.name} not found in tool mapping.`);\n toolCall.tool_info = toToolCallInfo(makeUnknownToolInfo(toolCall.function.name));\n continue;\n }\n toolCall.tool_info = toToolCallInfo(\n await toolInfo.toolSet.toolCallInfo({ name: toolInfo.originalToolName }, false /* resolveUnderlyingTool */),\n );\n }\n }\n\n // Strip legacy `function_call` and replay-only `thinking_blocks` so neither reaches the client or delta stream.\n const { role, function_call, thinking_blocks, ...deltaWithoutRole } = delta;\n void role;\n void function_call;\n void thinking_blocks;\n return {\n ...deltaWithoutRole,\n type: EventType.MODEL_MESSAGE_DELTA,\n id,\n thread_id: threadId,\n ...(finishReason && { finish_reason: finishReason }),\n ...(usage && { usage }),\n };\n}\n\nasync function buildContextAssistantMessage(\n assistantMessage: RawAssistantMessage,\n toolMapping: Map<string, MappedMCPTool>,\n): Promise<InternalEnrichedAssistantMessage> {\n // Omit tool_calls when empty; OpenAI rejects `tool_calls: []` on replay.\n if (!assistantMessage.tool_calls?.length) {\n const { tool_calls, ...rest } = assistantMessage;\n void tool_calls;\n return rest;\n }\n\n // Sequential loop instead of Promise.all: the first call populates the MCP server's tool cache\n // (via listTools), making subsequent calls instant cache hits.\n // No race conditions either way but parallelism buys nothing here.\n const enrichedToolCalls = [];\n for (const toolCall of assistantMessage.tool_calls) {\n const toolInfo = toolMapping.get(toolCall.function.name);\n if (!toolInfo) {\n enrichedToolCalls.push({ ...toolCall, tool_info: makeUnknownToolInfo(toolCall.function.name) });\n continue;\n }\n const tool_info = await toolInfo.toolSet.toolCallInfo(\n {\n name: toolInfo.originalToolName,\n arguments: tryParseToolArgs(toolCall.function.arguments),\n },\n // During context persistence, we have the complete message and hence the tool arguments are available.\n // Hence, we resolve the underlying tool to get the tool information.\n true /* resolveUnderlyingTool */,\n );\n enrichedToolCalls.push({ ...toolCall, tool_info });\n }\n return { ...assistantMessage, tool_calls: enrichedToolCalls };\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// Args are only used by DeferredTool to delegate to the underlying server.\n// Defensive parse — hallucinated JSON shouldn't crash assistant-message construction.\nfunction tryParseToolArgs(args: string | undefined): Record<string, unknown> {\n if (!args) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(args);\n return isJsonObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\n// State-sync contract: in-memory state must stay consistent with what the consumer\n// def foo():\n// for x in range(1, 10):\n// yield x\n// # This cannot raise exception\n// # This does not execute if update_redis fails.\n// update_local_context(x)\n// for x in foo():\n// # This can raise exception.\n// update_redis(x)\n\nexport class AgentThread {\n readonly threadId: string;\n readonly parent?: AgentParent | undefined;\n readonly definition: AgentDefinition;\n readonly title: string;\n readonly agentInfo?: AgentInfo | undefined;\n\n private context: ContextMessage[];\n private currentContextUsage: CurrentContextUsage;\n private preSendContextProcessors: PreSendContextProcessor[];\n private preLLMContextProcessors: PreLLMAgentContextProcessor[];\n private preEphemeralLLMContextProcessors: PreLLMEphemeralAgentContextProcessor[];\n private postToolCallContextProcessor: PostToolCallAgentContextProcessor[];\n\n private instruction: string | undefined;\n private toolResponseProcessors: ToolResponseProcessor[];\n private instructionBuilders: readonly ((builder: InstructionBuilder) => void)[];\n private systemToolSets: readonly IToolSet[];\n private deferredTool?: DeferredTool | undefined;\n private convertedTools: ConvertToolsResult | undefined;\n private pendingSandboxCreatedEvents: SandboxCreatedEvent[] = [];\n private sandbox?: Sandbox | undefined;\n private readonly tracing: AgentTracing;\n private readonly logger: Logger;\n\n private metrics: AgentThreadMetrics = createEmptyAgentThreadMetrics();\n private tfyManagedServerNames = new Set<string>();\n\n private contextBusy = false;\n private preSendRanThisTurn = false;\n private currentState: AgentThreadState | null = null;\n private readonly preComputedCompletion?: SubAgentCompletionMarker | undefined;\n /** Mirrored capability KV — source for toSnapshot().capability_state. */\n private capabilityState: CapabilityState = {};\n private readonly capabilityStateKeys: ReadonlySet<string>;\n\n constructor(input: AgentThreadConstructorInput) {\n this.tracing = input.tracing;\n this.logger = input.logger.child({ module: 'AgentThread' });\n this.threadId = input.threadId;\n this.definition = input.definition;\n this.context = input.context ? [...input.context] : [];\n this.title = input.title;\n this.parent = input.parent;\n this.currentContextUsage = input.currentContextUsage ?? getEmptyCurrentContextUsage();\n this.agentInfo = input.agentInfo;\n this.preComputedCompletion = input.preComputedCompletion;\n this.sandbox = input.sandbox;\n\n const capabilities = input.capabilities ?? [];\n this.systemToolSets = capabilities.flatMap(c => c.systemToolSets ?? []);\n this.preLLMContextProcessors = capabilities.flatMap(c => c.preLLMProcessors ?? []);\n this.preEphemeralLLMContextProcessors = capabilities.flatMap(c => c.preLLMEphemeralProcessors ?? []);\n this.postToolCallContextProcessor = capabilities.flatMap(c => c.postToolCallProcessors ?? []);\n this.toolResponseProcessors = capabilities.flatMap(c => c.toolResponseProcessors ?? []);\n this.instructionBuilders = capabilities.flatMap(c => c.instructionBuilders ?? []);\n const capabilityPreSend = capabilities.flatMap(c => c.preSendProcessors ?? []);\n // OpenToolCallCloser is fixed core before contributed preSend processors.\n this.preSendContextProcessors = [new OpenToolCallCloser(), ...capabilityPreSend];\n\n assertUniqueStateKeys(capabilities);\n const claimed = claimCapabilityState(capabilities, input.capabilityState, this.logger);\n this.capabilityState = claimed;\n this.capabilityStateKeys = new Set(\n capabilities.map(c => c.state?.key).filter((k): k is string => typeof k === 'string'),\n );\n for (const capability of capabilities) {\n if (!capability.state) {\n continue;\n }\n const value = claimed[capability.state.key];\n if (value !== undefined) {\n capability.state.load(value);\n }\n }\n\n if (this.definition.toolSets?.length) {\n this.deferredTool = new DeferredTool(this.definition.toolSets, {\n tracing: this.tracing,\n logger: input.logger,\n });\n }\n\n this.instruction = this.buildInstruction(this.definition.instruction);\n }\n\n private buildInstruction(userInstruction?: string): string {\n const identity = this.parent ? SUB_AGENT_IDENTITY : ROOT_AGENT_IDENTITY;\n const builder = InstructionBuilder.createSystemPrompt(identity);\n const capabilities = builder.beginSection('agent-capabilities');\n capabilities.addSection('internal-messages', INTERNAL_SYSTEM_PROMPT);\n\n if (this.sandbox) {\n this.sandbox.buildInstruction(capabilities);\n }\n if (this.deferredTool) {\n this.deferredTool.buildInstruction(capabilities);\n }\n for (const build of this.instructionBuilders) {\n build(capabilities);\n }\n if (!this.parent && userInstruction?.trim()) {\n builder.addSection('user-instructions', userInstruction.trim(), true);\n }\n return builder.build();\n }\n\n public async *send(messages: AgentThreadRuntimeSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {\n // An empty batch is a no-op only when the thread is not awaiting user input.\n // While awaiting input, fall through so the validator rejects the empty/incomplete batch.\n if (messages.length === 0 && !this.isAwaitingUserInput()) {\n return;\n }\n this.throwIfContextBusy();\n\n this.contextBusy = true;\n try {\n for await (const event of this.executeContextProcessors('preSend')) {\n yield event;\n }\n this.preSendRanThisTurn = true;\n\n validateInputMessageTypesGivenContext(this.context, messages);\n\n const approvals: UserToolApprovalMessage[] = [];\n const clientSideToolResponses: UserToolResponseMessage[] = [];\n const contextMessages: (LLMUserMessage | LLMToolMessage)[] = [];\n\n for (const m of messages) {\n if (isApprovalDecisionMessage(m)) {\n approvals.push(m);\n } else if (isClientSideToolResponseMessage(m)) {\n clientSideToolResponses.push(m);\n } else if (isInputUserMessage(m)) {\n const result = await processAgentUserInput(m, this.sandbox);\n contextMessages.push(result.message);\n if (result.sandboxCreated) {\n this.pendingSandboxCreatedEvents.push(buildSandboxCreatedEvent(result.sandboxCreated));\n }\n } else if (isLLMToolMessage(m)) {\n contextMessages.push(m);\n } else {\n const _exhaustive: never = m;\n throw new InvalidAgentSendInputError(`Unsupported send input: ${JSON.stringify(_exhaustive)}`);\n }\n }\n\n if (approvals.length > 0 || clientSideToolResponses.length > 0) {\n const approvalContext: AgentApprovalDecisionMessage[] = approvals.map(a => ({\n type: EventType.USER_TOOL_APPROVAL,\n tool_call_id: a.tool_call_id,\n approval: a.approval,\n }));\n const toolResponseContext: LLMToolMessage[] = clientSideToolResponses.map(m => ({\n role: 'tool',\n tool_call_id: m.tool_call_id,\n content: m.content,\n }));\n yield* this.appendToContext({\n context: [...approvalContext, ...toolResponseContext],\n output: [],\n currentContextUsage: undefined,\n usage: undefined,\n });\n }\n if (contextMessages.length > 0) {\n yield* this.appendToContext({\n context: contextMessages,\n output: [],\n currentContextUsage: undefined,\n usage: undefined,\n });\n }\n } finally {\n this.contextBusy = false;\n }\n }\n\n private throwIfContextBusy(): void {\n if (this.contextBusy) {\n throw new Error(`context is busy for thread ${this.threadId}`);\n }\n }\n\n private deriveState(): AgentThreadState {\n const next = deriveAgentThreadState(this.context);\n if (this.currentState) {\n assertValidTransition(this.currentState, next);\n }\n this.currentState = next;\n return next;\n }\n\n private *appendToContext(opts: {\n context: ContextMessage[];\n output: AgentOutputEvent[];\n currentContextUsage: CurrentContextUsage | undefined;\n usage: CompletionUsage | undefined;\n completion?: SubAgentCompletionMarker | undefined;\n }): Generator<AgentThreadAppendContext, void, unknown> {\n const { context, output, currentContextUsage, usage, completion } = opts;\n\n const newCurrentContextUsage =\n currentContextUsage ??\n mergeCurrentContextUsage(this.currentContextUsage, estimateTokensForContextMessages(context));\n\n const event: AgentThreadAppendContext = {\n type: InternalEventType.AGENT_CONTEXT_APPEND,\n thread_id: this.threadId,\n context,\n output,\n current_context_usage: newCurrentContextUsage,\n ...(completion && { completion }),\n };\n\n // Update metrics before yield so we still count it if the stream stops here.\n if (usage) {\n updateMetricsFromUsage(this.metrics, usage);\n }\n\n yield event;\n\n this.context = this.context.concat(context);\n this.currentContextUsage = newCurrentContextUsage;\n }\n\n private *overwriteContext(\n payload: AgentContextProcessorOverwriteContext,\n ): Generator<ThreadOverwriteContextEvent, void, unknown> {\n const event: ThreadOverwriteContextEvent = {\n thread_id: this.threadId,\n ...payload,\n };\n // Update metrics before yield so we still count it if the stream stops here.\n updateMetricsFromUsage(this.metrics, payload.usage);\n\n yield event;\n this.context = payload.context;\n this.currentContextUsage = payload.current_context_usage;\n this.metrics.total_summarizations++;\n }\n\n private generateErrorEvent(message: string, output?: ModelMessageEvent): InternalThreadDoneEvent {\n return {\n type: InternalEventType.AGENT_DONE,\n status: 'error',\n thread_id: this.threadId,\n title: this.title,\n error: message,\n parent: this.parent,\n send_to_parent: this.parent\n ? {\n role: 'tool',\n content: message,\n tool_call_id: this.parent.tool_call_id,\n }\n : undefined,\n ...(output && { output }),\n };\n }\n\n public hasOpenToolCallId(toolCallId: string): boolean {\n return getOpenToolCallIds(this.context).has(toolCallId);\n }\n\n // True when this thread is paused waiting on the user to resolve a pending tool\n // approval or a client-side tool response.\n public isAwaitingUserInput(): boolean {\n return (\n getPendingApprovalToolCalls(this.context).length > 0 || getPendingClientSideToolCalls(this.context).length > 0\n );\n }\n\n // Pure validation of an input batch against this thread's current context; throws\n // on an invalid/incomplete batch without mutating the context.\n public validateSendInput(messages: AgentThreadRuntimeSendBatch): void {\n validateInputMessageTypesGivenContext(this.context, messages);\n }\n\n public toSnapshot(): AgentThreadSnapshot {\n const capability_state = Object.keys(this.capabilityState).length > 0 ? { ...this.capabilityState } : null;\n return {\n thread_id: this.threadId,\n context: this.context,\n current_context_usage: this.currentContextUsage,\n parent: this.parent ?? null,\n agent_info: this.agentInfo ?? null,\n completion: this.preComputedCompletion ?? null,\n capability_state,\n };\n }\n\n public getAgentThreadMetrics(): AgentThreadMetrics {\n return { ...this.metrics };\n }\n\n private transformToLLMRequest(tools: ChatCompletionTool[]): LLMCreateParamsStreaming {\n let messages: ChatCompletionMessageParam[] = [];\n\n if (this.instruction) {\n messages.push({\n role: 'system',\n content: this.instruction,\n });\n }\n\n if (this.definition.messages) {\n for (const msg of this.definition.messages) {\n if (isLLMContextMessage(msg)) {\n messages.push(toOpenAIChatMessage(msg));\n }\n }\n }\n\n // NOTE: all this code-golf is to remove `tool_info` before sending the message to Gateway\n // ApprovalDecisionMessage rows are persisted in context but must not be sent to the LLM.\n const contextMessages = this.context.filter(isLLMContextMessage).map(msg => toOpenAIChatMessage(msg));\n\n messages.push(...contextMessages);\n\n for (const processor of this.preEphemeralLLMContextProcessors) {\n messages = processor.processPreLLMEphemeral(messages) ?? messages;\n }\n\n // modelParams may include provider extensions (e.g. reasoning_effort) beyond the SDK's\n // ChatCompletionCreateParamsStreaming field set; assign after constructing the typed body.\n // Model identity is owned by modelClient — do not set `model` on the request.\n const requestBody: LLMCreateParamsStreaming = {\n messages,\n stream: true,\n ...(this.definition.responseFormat !== undefined\n ? { response_format: toOpenAIResponseFormat(this.definition.responseFormat) }\n : {}),\n };\n if (this.definition.modelParams) {\n Object.assign(requestBody, this.definition.modelParams);\n }\n\n if (tools.length > 0) {\n requestBody.tools = tools;\n }\n\n return requestBody;\n }\n\n private computeAssistantMessageUsage(params: {\n requestBody: LLMCreateParamsStreaming;\n usage: CompletionUsage;\n toolMapping: Map<string, MappedMCPTool>;\n }): ModelMessageUsage {\n const { requestBody, usage, toolMapping } = params;\n // Sub-agents have no <user-instructions> section — their agent.instruction is\n // SUB_AGENT_IDENTITY which is harness content, not user-defined instructions.\n const trimmedInstruction = this.definition.instruction?.trim() ?? '';\n const instructionsEstimate = this.parent ? 0 : Math.round(estimateTokensForString(trimmedInstruction));\n\n const skillsEstimate = this.sandbox?.estimateSkillsTokens() ?? 0;\n\n let tfyManagedToolTokens = 0;\n let userToolTokens = 0;\n if (requestBody.tools) {\n for (const tool of requestBody.tools) {\n const toolTokens = Math.round(estimateTokensForString(JSON.stringify(tool)));\n const info = 'function' in tool ? toolMapping.get(tool.function.name) : undefined;\n if (info && this.tfyManagedServerNames.has(info.toolSet.name)) {\n tfyManagedToolTokens += toolTokens;\n } else {\n userToolTokens += toolTokens;\n }\n }\n }\n\n const totalInstructionTokens = Math.round(estimateTokensForString(this.instruction ?? ''));\n const harnessInstructionTokens = Math.max(0, totalInstructionTokens - instructionsEstimate - skillsEstimate);\n const harnessEstimate = harnessInstructionTokens + tfyManagedToolTokens;\n\n const estimatedComponentsTotal = harnessEstimate + skillsEstimate + instructionsEstimate + userToolTokens;\n const messagesEstimate = Math.max(0, usage.input_tokens - estimatedComponentsTotal);\n\n return {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cache_read_tokens: usage.cache_read_tokens,\n cache_write_tokens: usage.cache_write_tokens,\n input_tokens_breakdown: {\n harness: harnessEstimate,\n skills: skillsEstimate,\n instructions: instructionsEstimate,\n tool_definitions: userToolTokens,\n messages: messagesEstimate,\n },\n };\n }\n\n private executeContextProcessors(hook: 'preSend'): AsyncGenerator<AgentThreadAppendContext, void, unknown>;\n private executeContextProcessors(\n hook: 'preLLM' | 'postToolCall',\n ): AsyncGenerator<\n | ThreadOverwriteContextEvent\n | AgentThreadAppendContext\n | { type: typeof InternalEventType.PASSTHROUGH; event: RegisteredPassthroughEvent }\n | InternalCapabilityStateEvent,\n void,\n unknown\n >;\n private async *executeContextProcessors(\n hook: 'preSend' | 'preLLM' | 'postToolCall',\n ): AsyncGenerator<\n | ThreadOverwriteContextEvent\n | AgentThreadAppendContext\n | { type: typeof InternalEventType.PASSTHROUGH; event: RegisteredPassthroughEvent }\n | InternalCapabilityStateEvent,\n void,\n unknown\n > {\n let processors: ((\n execution: Readonly<AgentThreadExecutionContext>,\n ) => AsyncIterable<AgentContextProcessorOutput>)[];\n switch (hook) {\n case 'preSend':\n processors = this.preSendContextProcessors.map(p => p.processPreSend.bind(p));\n break;\n case 'preLLM':\n processors = this.preLLMContextProcessors.map(p => p.processPreLLM.bind(p));\n break;\n case 'postToolCall':\n processors = this.postToolCallContextProcessor.map(p => p.processPostToolCall.bind(p));\n break;\n default:\n throw new Error(`Unknown hook: ${String(hook)}`);\n }\n\n const execution: Readonly<AgentThreadExecutionContext> = {\n threadId: this.threadId,\n sandbox: this.sandbox,\n currentContextUsage: this.currentContextUsage,\n context: this.context,\n };\n\n for (const processor of processors) {\n for await (const response of processor(execution)) {\n switch (response.type) {\n case InternalEventType.AGENT_CONTEXT_APPEND:\n yield* this.appendToContext({\n context: response.context,\n output: response.output,\n currentContextUsage: response.current_context_usage ?? this.currentContextUsage,\n usage: undefined,\n });\n break;\n case EventType.AGENT_CONTEXT_OVERWRITE:\n yield* this.overwriteContext(response);\n break;\n case InternalEventType.PASSTHROUGH:\n yield response;\n break;\n case InternalEventType.CAPABILITY_STATE:\n if (!this.capabilityStateKeys.has(response.key)) {\n throw new AgentHarnessError(\n 'capability_state_error',\n `CAPABILITY_STATE key '${response.key}' is not declared by any capability on thread '${this.threadId}'`,\n );\n }\n yield {\n type: InternalEventType.CAPABILITY_STATE,\n thread_id: this.threadId,\n key: response.key,\n state: response.state,\n };\n this.capabilityState[response.key] = response.state;\n break;\n default: {\n const _exhaustive: never = response;\n return _exhaustive;\n }\n }\n }\n }\n }\n\n private async init(): Promise<{\n initializationInfo: MCPServerInitInfo[];\n authRequirementInfo: MCPAuthRequired[];\n }> {\n if (this.convertedTools) {\n return { initializationInfo: [], authRequirementInfo: [] };\n }\n return this.initTools();\n }\n\n private async initTools(): Promise<{\n initializationInfo: MCPServerInitInfo[];\n authRequirementInfo: MCPAuthRequired[];\n }> {\n const tfyManagedServers: IToolSet[] = [...this.systemToolSets];\n if (this.sandbox) {\n tfyManagedServers.push(this.sandbox);\n }\n if (this.deferredTool) {\n tfyManagedServers.push(this.deferredTool);\n }\n const userServers = [...(this.definition.toolSets ?? [])];\n\n const { convertedTools, initializationInfo, authRequirementInfo } = await convertMCPServersToTools({\n tfyManagedServers,\n userServers,\n });\n this.convertedTools = convertedTools;\n this.tfyManagedServerNames = new Set(tfyManagedServers.map(s => s.name));\n return { initializationInfo, authRequirementInfo };\n }\n\n private getConvertedTools(): ConvertToolsResult {\n if (!this.convertedTools) {\n throw new Error('unreachable');\n }\n return this.convertedTools;\n }\n\n private async *stepLLMCall(\n tools: ChatCompletionTool[],\n toolMapping: Map<string, MappedMCPTool>,\n signal?: AbortSignal,\n ): AsyncGenerator<AgentThreadEvent, { outcome: StepOutcome; modelMessageEventId: string }, unknown> {\n const modelMessageEventId = newEventId();\n if (signal?.aborted) {\n return { outcome: 'exit', modelMessageEventId };\n }\n\n for await (const event of this.executeContextProcessors('preLLM')) {\n yield event;\n }\n\n const requestBody = this.transformToLLMRequest(tools);\n const llmStream = this.definition.modelClient.create(requestBody);\n\n // We start the delta stream with a model message event.\n yield {\n type: EventType.MODEL_MESSAGE,\n thread_id: this.threadId,\n created_at: new Date().toISOString(),\n id: modelMessageEventId,\n } satisfies ModelMessageEvent;\n\n let firstDeltaTimestamped = false;\n let result = await llmStream.next();\n let modelMessageUsage: ModelMessageUsage | undefined = undefined;\n while (!result.done) {\n const chunk = result.value;\n if (chunk.usage) {\n modelMessageUsage = this.computeAssistantMessageUsage({\n requestBody,\n usage: chunk.usage,\n toolMapping,\n });\n }\n const event = await buildModelMessageDeltaEvent({\n chunk,\n threadId: this.threadId,\n toolMapping,\n usage: modelMessageUsage,\n id: modelMessageEventId,\n logger: this.logger,\n });\n if (event) {\n if (!firstDeltaTimestamped) {\n firstDeltaTimestamped = true;\n yield { ...event, created_at: new Date().toISOString() };\n } else {\n yield event;\n }\n }\n result = await llmStream.next();\n }\n\n // If the stream was aborted mid-way, result.value.output is only a partial\n // accumulation of the deltas — not the true complete response. Skip the\n // final model.message event to avoid emitting an inconsistent assembled message.\n if (signal?.aborted) {\n return { outcome: 'exit', modelMessageEventId };\n }\n\n // should be computed by this point but in case provider never gives out any delta with usage, compute it now.\n modelMessageUsage ??= this.computeAssistantMessageUsage({\n requestBody,\n usage: result.value.usage,\n toolMapping,\n });\n const assistantMessage: InternalEnrichedAssistantMessage = await buildContextAssistantMessage(\n result.value.output,\n toolMapping,\n );\n const finishReason = result.value.finish_reason;\n const agentAssistantMessage = buildModelMessageEvent({\n assistantMessage,\n threadId: this.threadId,\n finishReason,\n usage: modelMessageUsage,\n id: modelMessageEventId,\n });\n\n let completion: SubAgentCompletionMarker | undefined;\n if (this.parent) {\n if (finishReason === 'length') {\n const errorMessage = assistantMessageContentToStringForSubAgent(\n assistantMessage.content,\n 'max_tokens breached',\n );\n completion = {\n type: 'error',\n output: agentAssistantMessage,\n error_message: errorMessage,\n send_to_parent: { role: 'tool', tool_call_id: this.parent.tool_call_id, content: errorMessage },\n };\n } else if (!hasToolCalls(assistantMessage)) {\n const content = assistantMessageContentToStringForSubAgent(assistantMessage.content);\n completion = {\n type: 'done',\n output: agentAssistantMessage,\n send_to_parent: { role: 'tool', tool_call_id: this.parent.tool_call_id, content },\n };\n }\n }\n\n yield* this.appendToContext({\n context: [assistantMessage],\n output: [agentAssistantMessage],\n currentContextUsage: currentContextUsageFromCompletion(result.value.usage),\n usage: result.value.usage,\n completion,\n });\n\n if (finishReason === 'length') {\n const errorContent = completion?.error_message ?? 'max_tokens breached';\n yield this.generateErrorEvent(errorContent, agentAssistantMessage);\n return { outcome: 'exit', modelMessageEventId };\n }\n\n if (!hasToolCalls(assistantMessage)) {\n yield {\n type: InternalEventType.AGENT_DONE,\n status: 'done',\n thread_id: this.threadId,\n title: this.title,\n output: agentAssistantMessage,\n parent: this.parent,\n send_to_parent: completion?.send_to_parent,\n };\n return { outcome: 'exit', modelMessageEventId };\n }\n\n return { outcome: 'continue', modelMessageEventId };\n }\n\n private async *stepToolResponse(\n toolMapping: Map<string, MappedMCPTool>,\n ): AsyncGenerator<AgentThreadEvent, StepOutcome, unknown> {\n const assistantMessage = lastAssistantInContext(this.context);\n if (!assistantMessage) {\n throw new Error('unreachable');\n }\n\n const openIds = getOpenToolCallIds(this.context);\n const openCalls = assistantMessage.tool_calls?.filter(tc => openIds.has(tc.id)) ?? [];\n const decisions = scanApprovalDecisions(this.context);\n\n const assistantForExecution: InternalEnrichedAssistantMessage = {\n ...assistantMessage,\n tool_calls: openCalls,\n };\n const {\n toolCallResults,\n initializationInfo,\n createThreadEvents,\n sandboxCreated,\n authRequirementInfo,\n approvalRequiredToolCalls,\n clientSideToolCalls,\n events: passthroughEvents,\n } = await executeToolCalls({\n assistantMessage: assistantForExecution,\n toolMapping,\n threadId: this.threadId,\n approvalDecisions: decisions,\n });\n void clientSideToolCalls;\n if (approvalRequiredToolCalls.length > 0) {\n throw new Error('Unreachable');\n }\n this.metrics.total_tool_calls += toolCallResults.length;\n this.metrics.total_sub_agents += createThreadEvents.length;\n\n if (initializationInfo.length > 0) {\n yield buildMCPInitializeEvent(initializationInfo, this.threadId);\n }\n\n if (sandboxCreated) {\n yield buildSandboxCreatedEvent(sandboxCreated);\n }\n\n for (const event of passthroughEvents) {\n yield { type: InternalEventType.PASSTHROUGH, event };\n }\n\n const toolIdsBeforeProcessing = toolCallResults.map(t => t.message.tool_call_id);\n const toolResponseExecution: Readonly<AgentThreadExecutionContext> = {\n threadId: this.threadId,\n sandbox: this.sandbox,\n currentContextUsage: this.currentContextUsage,\n context: this.context,\n };\n for (const processor of this.toolResponseProcessors) {\n const processorResult = await processor.process(toolCallResults, toolResponseExecution);\n if (processorResult.sandboxCreated) {\n yield buildSandboxCreatedEvent(processorResult.sandboxCreated);\n }\n for (const event of processorResult.events ?? []) {\n yield { type: InternalEventType.PASSTHROUGH, event };\n }\n }\n if (toolIdsBeforeProcessing.length !== toolCallResults.length) {\n throw Error('Some tool call processor has removed tool call.');\n }\n const toolIdsAfterProcessing = new Set(toolCallResults.map(t => t.message.tool_call_id));\n\n if (!toolIdsBeforeProcessing.every(id => toolIdsAfterProcessing.has(id))) {\n throw Error('Tool call IDs do not match after processing.');\n }\n\n const agentToolMessages: ToolResponseEvent[] = toolCallResults.map(t => {\n const { role, ...toolMessage } = t.message;\n void role;\n return {\n ...toolMessage,\n type: EventType.TOOL_RESPONSE,\n id: newEventId(),\n created_at: t.completedAt,\n thread_id: this.threadId,\n };\n });\n for (const msg of agentToolMessages) {\n yield msg;\n }\n // tool.response is persisted by the session/response layer when yielded; only mutate context here.\n yield* this.appendToContext({\n context: toolCallResults.map(t => t.message),\n output: [],\n currentContextUsage: undefined,\n usage: undefined,\n });\n\n if (authRequirementInfo.length > 0) {\n yield buildMCPAuthRequiredEvent(authRequirementInfo, this.threadId);\n return 'exit';\n }\n\n for await (const event of this.executeContextProcessors('postToolCall')) {\n yield event;\n }\n for (const event of createThreadEvents) {\n yield event;\n }\n if (createThreadEvents.length > 0) {\n return 'exit';\n }\n\n return 'continue';\n }\n\n private *stepUserInputRequired(modelMessageEventId: string): Generator<AgentThreadEvent, StepOutcome, unknown> {\n const pendingClientSideToolCalls = getPendingClientSideToolCalls(this.context);\n if (pendingClientSideToolCalls.length > 0) {\n const responseRequiredEvent: ToolResponseRequiredEvent = {\n type: EventType.TOOL_RESPONSE_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: this.threadId,\n tool_calls: pendingClientSideToolCalls.map(tc => ({ id: tc.id, source_event_id: modelMessageEventId })),\n };\n yield responseRequiredEvent;\n }\n\n const pendingApprovalToolCalls = getPendingApprovalToolCalls(this.context);\n if (pendingApprovalToolCalls.length > 0) {\n const event: ToolApprovalRequiredEvent = {\n type: EventType.TOOL_APPROVAL_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: this.threadId,\n tool_calls: pendingApprovalToolCalls.map(({ id }) => ({ id, source_event_id: modelMessageEventId })),\n };\n yield event;\n }\n return 'exit';\n }\n\n private buildReplayEvent(c: SubAgentCompletionMarker): InternalThreadDoneEvent {\n const base = {\n type: InternalEventType.AGENT_DONE,\n thread_id: this.threadId,\n title: this.title,\n parent: this.parent,\n send_to_parent: c.send_to_parent,\n };\n return c.type === 'done'\n ? { ...base, status: 'done', output: c.output }\n : { ...base, status: 'error', error: c.error_message ?? 'Sub-agent errored', output: c.output };\n }\n\n public async *execute(options?: {\n signal?: AbortSignal | undefined;\n }): AsyncGenerator<AgentThreadEvent, void, unknown> {\n const signal = options?.signal;\n\n this.throwIfContextBusy();\n this.contextBusy = true;\n this.currentState = null;\n\n // there should always be this top level try-catch block because agent execution cant raise an error. it should yield an error event.\n try {\n if (this.preComputedCompletion) {\n yield this.buildReplayEvent(this.preComputedCompletion);\n return;\n }\n\n if (!this.preSendRanThisTurn) {\n for await (const event of this.executeContextProcessors('preSend')) {\n yield event;\n }\n }\n this.preSendRanThisTurn = false;\n const { initializationInfo, authRequirementInfo } = await this.tracing.withInitSpan(() => this.init());\n\n if (initializationInfo.length > 0) {\n yield buildMCPInitializeEvent(initializationInfo, this.threadId);\n }\n\n if (authRequirementInfo.length > 0) {\n yield buildMCPAuthRequiredEvent(authRequirementInfo, this.threadId);\n return;\n }\n\n const { tools, toolMapping } = this.getConvertedTools();\n\n const iterationLimit = this.definition.iterationLimit ?? DEFAULT_ITERATION_LIMIT;\n // Starts empty; set only after stepLLMCall in this execute(). That is intentional:\n // user-input-required is only reachable here right after an LLM step that produced\n // pending approval/client-side tools (which sets currentModelMessageEventId first).\n // A resumed turn that is still awaiting user input never reaches this loop — orchestrator\n // send() / validateSendInput rejects empty or incomplete batches before execute runs.\n let currentModelMessageEventId = '';\n\n for (;;) {\n for (;;) {\n const sandboxCreatedEvent = this.pendingSandboxCreatedEvents.shift();\n if (sandboxCreatedEvent === undefined) {\n break;\n }\n yield sandboxCreatedEvent;\n }\n\n const state = this.deriveState();\n let outcome: StepOutcome;\n switch (state) {\n case 'llm-call-required': {\n // Cancel only before network/side-effecting steps (LLM call, tool execution), never before 'user-input-required', so the required event is always emitted once the assistant message is committed.\n if (signal?.aborted) {\n return;\n }\n if (this.metrics.iterations >= iterationLimit) {\n yield this.generateErrorEvent(\n `You have reached iteration limit of ${String(iterationLimit)}, please request again`,\n );\n return;\n }\n this.metrics.iterations++;\n\n const llmResult = yield* this.stepLLMCall(tools, toolMapping, signal);\n outcome = llmResult.outcome;\n currentModelMessageEventId = llmResult.modelMessageEventId;\n break;\n }\n case 'tool-response-required': {\n if (signal?.aborted) {\n return;\n }\n outcome = yield* this.stepToolResponse(toolMapping);\n break;\n }\n case 'user-input-required': {\n // Intentionally no cancellation check here — see comment in 'llm-call-required'.\n // source_event_id comes from currentModelMessageEventId; see comment where it is declared.\n outcome = yield* this.stepUserInputRequired(currentModelMessageEventId);\n break;\n }\n default: {\n throw new Error('unreachable');\n }\n }\n if (outcome === 'exit') {\n return;\n }\n }\n } catch (error) {\n // Providers / transports often reject with plain objects; instanceof Error would\n // otherwise collapse those into an opaque \"Unknown error occurred\" in Agent Steps.\n this.logger.error('Agent thread execution failed', extractErrorLogFields(error));\n yield this.generateErrorEvent(describeUnknownError(error));\n } finally {\n this.contextBusy = false;\n }\n }\n}\n\nfunction assertUniqueStateKeys(capabilities: readonly AgentCapability[]): void {\n const seen = new Set<string>();\n for (const capability of capabilities) {\n const key = capability.state?.key;\n if (!key) {\n continue;\n }\n if (seen.has(key)) {\n throw new AgentHarnessError(\n 'capability_state_error',\n `Duplicate capability state key '${key}' — each key may be claimed by at most one capability`,\n );\n }\n seen.add(key);\n }\n}\n\nfunction claimCapabilityState(\n capabilities: readonly AgentCapability[],\n input: CapabilityState | undefined,\n logger: Logger,\n): CapabilityState {\n if (!input) {\n return {};\n }\n const claimedKeys = new Set(capabilities.map(c => c.state?.key).filter((k): k is string => typeof k === 'string'));\n const claimed: CapabilityState = {};\n for (const [key, value] of Object.entries(input)) {\n if (!claimedKeys.has(key)) {\n logger.warn(`Dropping unclaimed capability_state key '${key}' — no capability declares it`);\n continue;\n }\n claimed[key] = value;\n }\n return claimed;\n}\n"],"mappings":";AAYA,SAAS,0BAA0B;AAEnC,SAAS,mBAAmB,kCAAkC;AAE9D;AAAA,EACE;AAAA,EACA;AAAA,OAiBK;AACP,SAAS,oBAAoB,2BAA2B;AAExD,OASO;AACP,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,+BAA+B;AACxC,SAAS,gCAA6E;AACtF,SAAS,wBAAwB;AAIjC,SAAS,sBAAsB,6BAA6B;AAQ5D;AAAA,EACE;AAAA,OAQK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,+BAA+B,8BAAuD;AAC/F,SAAS,4BAA4B,0BAA0B;AAC/D,SAAS,uBAAuB,6BAAyD;AAEzF,IAAM,0BAA0B;AAMhC,IAAM,oBAAkE;AAAA,EACtE,qBAAqB,CAAC,0BAA0B,qBAAqB;AAAA,EACrE,0BAA0B,CAAC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAI9C,uBAAuB,CAAC,0BAA0B,mBAAmB;AACvE;AAEA,SAAS,sBAAsB,MAAw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QACiB;AACjB,MAAI,CAAC,OAAO;AACV,WAAO,CAAC;AAAA,EACV;AACA,QAAM,cAAc,IAAI,IAAI,aAAa,IAAI,OAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,CAAC;AACjH,QAAM,UAA2B,CAAC;AAClC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,CAAC,YAAY,IAAI,GAAG,GAAG;AACzB,aAAO,KAAK,4CAA4C,GAAG,oCAA+B;AAC1F;AAAA,IACF;AACA,YAAQ,GAAG,IAAI;AAAA,EACjB;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentThreadOrchestrator.d.ts","sourceRoot":"","sources":["../../../src/core/runtime/AgentThreadOrchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAWtC,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGjF,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,gBAAgB,EACrB,KAAK,yBAAyB,EAC9B,KAAK,0BAA0B,EAC/B,KAAK,oBAAoB,EAG1B,MAAM,qBAAqB,CAAC;AAQ7B,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAwD,KAAK,kBAAkB,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"AgentThreadOrchestrator.d.ts","sourceRoot":"","sources":["../../../src/core/runtime/AgentThreadOrchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAWtC,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAG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0B,EAAE,OAAO,CAAC,CAqGjF;CACF"}
|
|
@@ -36,8 +36,12 @@ var MAX_PARALLEL_SUB_AGENTS = 5;
|
|
|
36
36
|
function agentThreadEventToTerminalFields(event) {
|
|
37
37
|
switch (event.type) {
|
|
38
38
|
case import_AgentThread2.InternalEventType.AGENT_DONE: {
|
|
39
|
-
if ("parent" in event && event.parent)
|
|
40
|
-
|
|
39
|
+
if ("parent" in event && event.parent) {
|
|
40
|
+
return {};
|
|
41
|
+
}
|
|
42
|
+
if (event.status === "error") {
|
|
43
|
+
return {};
|
|
44
|
+
}
|
|
41
45
|
return { output: event.output };
|
|
42
46
|
}
|
|
43
47
|
case import_schema.EventType.TOOL_APPROVAL_REQUIRED:
|
|
@@ -53,7 +57,9 @@ function isUserToolApprovalOrResponseBatch(messages) {
|
|
|
53
57
|
}
|
|
54
58
|
function getMainThreadId(agentThreads) {
|
|
55
59
|
for (const thread of agentThreads.values()) {
|
|
56
|
-
if (!thread.parent)
|
|
60
|
+
if (!thread.parent) {
|
|
61
|
+
return thread.threadId;
|
|
62
|
+
}
|
|
57
63
|
}
|
|
58
64
|
throw new Error("Unreachable: no root thread found");
|
|
59
65
|
}
|
|
@@ -68,7 +74,9 @@ function getActiveAgentThreads(agentThreads) {
|
|
|
68
74
|
}
|
|
69
75
|
return leaves.map((id) => {
|
|
70
76
|
const agentThread = agentThreads.get(id);
|
|
71
|
-
if (!agentThread)
|
|
77
|
+
if (!agentThread) {
|
|
78
|
+
throw new Error("unreachable");
|
|
79
|
+
}
|
|
72
80
|
return agentThread;
|
|
73
81
|
});
|
|
74
82
|
}
|
|
@@ -283,9 +291,13 @@ var AgentThreadOrchestrator = class {
|
|
|
283
291
|
return { shouldStopExecution: true };
|
|
284
292
|
case import_AgentThread2.InternalEventType.AGENT_DONE: {
|
|
285
293
|
if (chunk.parent) {
|
|
286
|
-
if (!chunk.send_to_parent)
|
|
294
|
+
if (!chunk.send_to_parent) {
|
|
295
|
+
throw new Error("unreachable");
|
|
296
|
+
}
|
|
287
297
|
const parentThread = this.agentThreads.get(chunk.parent.thread_id);
|
|
288
|
-
if (!parentThread)
|
|
298
|
+
if (!parentThread) {
|
|
299
|
+
throw new Error("unreachable: parent thread missing");
|
|
300
|
+
}
|
|
289
301
|
const subAgentToolIsOpen = parentThread.hasOpenToolCallId(chunk.parent.tool_call_id);
|
|
290
302
|
if (subAgentToolIsOpen) {
|
|
291
303
|
const parentToolResponse = {
|
|
@@ -362,7 +374,9 @@ var AgentThreadOrchestrator = class {
|
|
|
362
374
|
});
|
|
363
375
|
try {
|
|
364
376
|
while (agentThreads.size > 0) {
|
|
365
|
-
if (shouldStopExecution)
|
|
377
|
+
if (shouldStopExecution) {
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
366
380
|
const activeThreads = getActiveAgentThreads(agentThreads);
|
|
367
381
|
for (let i = 0; i < activeThreads.length && !shouldStopExecution; i += MAX_PARALLEL_SUB_AGENTS) {
|
|
368
382
|
const batch = activeThreads.slice(i, i + MAX_PARALLEL_SUB_AGENTS);
|
|
@@ -389,8 +403,12 @@ var AgentThreadOrchestrator = class {
|
|
|
389
403
|
}
|
|
390
404
|
if (chunk.type !== import_AgentThread2.InternalEventType.PASSTHROUGH) {
|
|
391
405
|
const { output: outputContribution, requiredAction } = agentThreadEventToTerminalFields(chunk);
|
|
392
|
-
if (outputContribution)
|
|
393
|
-
|
|
406
|
+
if (outputContribution) {
|
|
407
|
+
output = outputContribution;
|
|
408
|
+
}
|
|
409
|
+
if (requiredAction) {
|
|
410
|
+
requiredActions.push(requiredAction);
|
|
411
|
+
}
|
|
394
412
|
}
|
|
395
413
|
}
|
|
396
414
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/runtime/AgentThreadOrchestrator.ts"],"sourcesContent":["import type { Logger } from 'winston';\nimport { AgentHarnessError, InvalidAgentSendInputError } from '../errors';\nimport {\n EventType,\n newEventId,\n type ActionRequiredEvent,\n type ModelMessageEvent,\n type ToolResponseEvent,\n type UserToolApprovalMessage,\n type UserToolResponseMessage,\n} from '../events/schema';\nimport type { AgentExecutionTrace, AgentTracing } from '../tracing/AgentTracing';\nimport { onSignalAbort } from '../util/abort';\nimport { mergeAsyncGenerators } from '../util/promiseUtils';\nimport { AgentThread } from './AgentThread';\nimport type { AgentThreadRuntimeSendBatch } from './AgentThread.types';\nimport {\n InternalEventType,\n type AgentThreadAppendContext,\n type AgentThreadEvent,\n type AgentThreadExecutionEvent,\n type AgentThreadExecutionResult,\n type AgentThreadSendBatch,\n type InternalMCPAuthRequiredEvent,\n type InternalMCPServerAuthInfo,\n} from './AgentThread.types';\nimport {\n assistantMessageContentToStringForSubAgent,\n getThreadId,\n isApprovalDecisionMessage,\n isClientSideToolResponseMessage,\n isInternalThreadDoneError,\n} from './contextUtils';\nimport type { CreateDynamicSubAgentThread } from './CreateDynamicSubAgentThread';\nimport { addAgentThreadMetrics, createEmptyAgentThreadMetrics, type AgentThreadMetrics } from './metrics';\n\nconst MAX_PARALLEL_SUB_AGENTS = 5;\n\nfunction agentThreadEventToTerminalFields(event: AgentThreadExecutionEvent): {\n output?: ModelMessageEvent | undefined;\n requiredAction?: ActionRequiredEvent | undefined;\n} {\n switch (event.type) {\n case InternalEventType.AGENT_DONE: {\n if ('parent' in event && event.parent) return {};\n if (event.status === 'error') return {};\n return { output: event.output };\n }\n case EventType.TOOL_APPROVAL_REQUIRED:\n case EventType.TOOL_RESPONSE_REQUIRED:\n return { requiredAction: event };\n default:\n return {};\n }\n}\n\ntype UserToolApprovalOrResponseBatch = (UserToolApprovalMessage | UserToolResponseMessage)[];\n\nfunction isUserToolApprovalOrResponseBatch(\n messages: AgentThreadSendBatch,\n): messages is UserToolApprovalOrResponseBatch {\n const first = messages[0];\n return first !== undefined && (isApprovalDecisionMessage(first) || isClientSideToolResponseMessage(first));\n}\n\nfunction getMainThreadId(agentThreads: Map<string, AgentThread>): string {\n for (const thread of agentThreads.values()) {\n if (!thread.parent) return thread.threadId;\n }\n throw new Error('Unreachable: no root thread found');\n}\n\nfunction getActiveAgentThreads(agentThreads: Map<string, AgentThread>): AgentThread[] {\n const nodes = new Set(agentThreads.keys());\n const parentNodes = new Set(\n [...agentThreads.values()].map(a => a.parent?.thread_id).filter((a): a is string => Boolean(a)),\n );\n const leaves = [...nodes].filter(id => !parentNodes.has(id));\n if (leaves.length === 0) {\n throw new Error('We cannot have zero leave agents');\n }\n return leaves.map(id => {\n const agentThread = agentThreads.get(id);\n if (!agentThread) throw new Error('unreachable');\n return agentThread;\n });\n}\n\nfunction mergeAuthEvents(events: InternalMCPAuthRequiredEvent[]): InternalMCPAuthRequiredEvent {\n const serverMap = new Map<string, InternalMCPServerAuthInfo>();\n for (const event of events) {\n for (const entry of event.mcp_servers) {\n const existing = serverMap.get(entry.id);\n if (existing) {\n existing.thread_ids.push(...entry.thread_ids);\n } else {\n serverMap.set(entry.id, { ...entry, thread_ids: [...entry.thread_ids] });\n }\n }\n }\n return {\n type: InternalEventType.MCP_AUTH_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: null,\n mcp_servers: [...serverMap.values()],\n };\n}\n\nfunction wrapGeneratorWithTrace<T, TReturn = void, TNext = unknown>(\n trace: AgentExecutionTrace,\n generator: AsyncGenerator<T, TReturn, TNext>,\n): AsyncGenerator<T, TReturn, TNext> {\n const wrapped: AsyncGenerator<T, TReturn, TNext> = {\n [Symbol.asyncIterator]() {\n return this;\n },\n next(...[value]: [] | [TNext]) {\n return trace.runInContext(() => (value === undefined ? generator.next() : generator.next(value)));\n },\n return(value: TReturn | PromiseLike<TReturn>) {\n return trace.runInContext(() => generator.return(value));\n },\n throw(e: unknown) {\n return trace.runInContext(() => generator.throw(e));\n },\n [Symbol.asyncDispose]() {\n return generator[Symbol.asyncDispose]();\n },\n };\n return wrapped;\n}\n\ninterface RootAgentSpanHandle {\n trace: AgentExecutionTrace;\n wrapThreadWithContext(thread: AgentThread, signal?: AbortSignal): AsyncGenerator<AgentThreadEvent>;\n setOutputFromEvent(chunk: AgentThreadEvent): void;\n finalize(thread: AgentThread, error?: unknown): void;\n end(): void;\n}\n\nfunction createRootAgentSpan(mainThread: AgentThread, tracing: AgentTracing): RootAgentSpanHandle {\n const trace = tracing.startRootSpan(\n JSON.stringify({ instructions: mainThread.definition.instruction, messages: mainThread.definition.messages }),\n );\n let rootAgentErrorMessage: string | undefined;\n let rootAgentCompleted = false;\n\n return {\n trace,\n wrapThreadWithContext(thread: AgentThread, signal?: AbortSignal) {\n return wrapGeneratorWithTrace(trace, thread.execute({ signal }));\n },\n setOutputFromEvent(chunk: AgentThreadEvent) {\n rootAgentCompleted = true;\n if (chunk.type === InternalEventType.AGENT_DONE) {\n if (isInternalThreadDoneError(chunk)) {\n rootAgentErrorMessage = chunk.error;\n trace.setOutput(JSON.stringify({ error: chunk.error }));\n } else {\n const content = assistantMessageContentToStringForSubAgent(chunk.output.content);\n trace.setOutput(JSON.stringify({ result: content }));\n }\n }\n },\n finalize(thread: AgentThread, error?: unknown) {\n trace.setMetrics(thread.getAgentThreadMetrics());\n if (error) {\n trace.setError(error);\n } else if (rootAgentErrorMessage || !rootAgentCompleted) {\n trace.setError(rootAgentErrorMessage ?? 'Agent execution interrupted');\n } else {\n trace.setSuccess();\n }\n },\n end() {\n trace.end();\n },\n };\n}\n\n/** @internal Exported for sub-agent span finalization tests. */\nexport async function* wrapWithSubAgentSpan(\n parentTrace: AgentExecutionTrace,\n currentThread: AgentThread,\n signal?: AbortSignal,\n): AsyncGenerator<AgentThreadEvent> {\n const agentInfo = currentThread.agentInfo;\n if (!agentInfo) {\n throw new Error('Sub-agent thread is missing agentInfo');\n }\n const subTrace = parentTrace.startSubAgent(agentInfo.name, JSON.stringify({ instructions: agentInfo.input }));\n const generator = wrapGeneratorWithTrace(subTrace, currentThread.execute({ signal }));\n\n try {\n for await (const event of generator) {\n if (event.type === InternalEventType.AGENT_DONE) {\n if (isInternalThreadDoneError(event)) {\n subTrace.setOutput(JSON.stringify({ error: event.error }));\n subTrace.setMetrics(currentThread.getAgentThreadMetrics());\n subTrace.setError(event.error);\n } else {\n const content = assistantMessageContentToStringForSubAgent(event.output.content);\n subTrace.setOutput(JSON.stringify({ result: content }));\n subTrace.setMetrics(currentThread.getAgentThreadMetrics());\n subTrace.setSuccess();\n }\n // end() only in finally so every path finalizes exactly once\n }\n yield event;\n }\n } catch (error) {\n subTrace.setError(error);\n throw error;\n } finally {\n subTrace.end();\n }\n}\n\nexport interface AgentThreadOrchestratorInput {\n agentThreads: Map<string, AgentThread>;\n createDynamicSubAgentThread: CreateDynamicSubAgentThread;\n tracing: AgentTracing;\n logger: Logger;\n}\n\nexport class AgentThreadOrchestrator {\n private readonly agentThreads: Map<string, AgentThread>;\n private readonly createDynamicSubAgentThread: CreateDynamicSubAgentThread;\n private readonly tracing: AgentTracing;\n private readonly logger: Logger;\n // Finished sub-agents removed from `agentThreads`; kept so totals still include them.\n private finishedSubAgentMetrics: AgentThreadMetrics = createEmptyAgentThreadMetrics();\n\n constructor(params: AgentThreadOrchestratorInput) {\n this.agentThreads = params.agentThreads;\n this.createDynamicSubAgentThread = params.createDynamicSubAgentThread;\n this.tracing = params.tracing;\n this.logger = params.logger.child({ module: 'AgentThreadOrchestrator' });\n }\n\n /**\n * Turn-wide metrics so far: live threads plus finished sub-agents.\n * Safe mid-flight and after cancel/error (`execute()` may not return).\n * Each thread is counted once — a sub-agent moves from live → finished atomically.\n */\n public getMetrics(): AgentThreadMetrics {\n const total = createEmptyAgentThreadMetrics();\n addAgentThreadMetrics(total, this.finishedSubAgentMetrics);\n for (const thread of this.agentThreads.values()) {\n addAgentThreadMetrics(total, thread.getAgentThreadMetrics());\n }\n return total;\n }\n\n public async *send(messages: AgentThreadSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {\n const byThread = new Map<string, AgentThreadRuntimeSendBatch>();\n for (const thread of this.agentThreads.values()) {\n byThread.set(thread.threadId, []);\n }\n\n if (isUserToolApprovalOrResponseBatch(messages)) {\n const grouped = new Map<string, UserToolApprovalOrResponseBatch[number][]>();\n for (const msg of messages) {\n const threadId = msg.thread_id;\n if (!byThread.has(threadId)) {\n throw new InvalidAgentSendInputError(`unknown thread_id: ${threadId}`);\n }\n const batch = grouped.get(threadId) ?? [];\n batch.push(msg);\n grouped.set(threadId, batch);\n }\n for (const [threadId, batch] of grouped) {\n byThread.set(threadId, batch);\n }\n } else if (messages.length > 0) {\n if (this.agentThreads.size > 1) {\n throw new InvalidAgentSendInputError(\n 'Cannot process user messages while sub agents are running, please send empty input for previous conversation to complete',\n );\n }\n byThread.set(getMainThreadId(this.agentThreads), messages);\n }\n\n const validationErrors: string[] = [];\n for (const [threadId, batch] of byThread) {\n const thread = this.agentThreads.get(threadId);\n if (!thread) {\n throw new Error(`AgentThreadOrchestrator.send: unknown threadId ${threadId}`);\n }\n try {\n thread.validateSendInput(batch);\n } catch (e) {\n if (e instanceof AgentHarnessError && e.code === 'invalid_send_input') {\n validationErrors.push(`thread ${threadId}: ${e.message}`);\n } else {\n throw e;\n }\n }\n }\n if (validationErrors.length > 0) {\n throw new InvalidAgentSendInputError(validationErrors.join('; '));\n }\n\n for (const [threadId, batch] of byThread) {\n yield* this.sendToThread(threadId, batch);\n }\n }\n\n private async *sendToThread(\n threadId: string,\n messages: AgentThreadRuntimeSendBatch,\n ): AsyncGenerator<AgentThreadAppendContext, void, unknown> {\n const thread = this.agentThreads.get(threadId);\n if (!thread) {\n throw new Error(`AgentThreadOrchestrator.sendToThread: unknown threadId ${threadId}`);\n }\n yield* thread.send(messages);\n }\n\n private async *processAgentStreamChunk(\n chunk: Exclude<AgentThreadEvent, InternalMCPAuthRequiredEvent>,\n signal: AbortSignal,\n ): AsyncGenerator<AgentThreadExecutionEvent, { shouldStopExecution: boolean }, unknown> {\n if (chunk.type === InternalEventType.PASSTHROUGH) {\n yield chunk.event;\n return { shouldStopExecution: false };\n }\n\n if (!('thread_id' in chunk) || chunk.thread_id == null) {\n yield chunk;\n return { shouldStopExecution: false };\n }\n\n const currentThread = this.agentThreads.get(chunk.thread_id);\n if (!currentThread) {\n throw new Error('unreachable');\n }\n\n switch (chunk.type) {\n case EventType.TOOL_APPROVAL_REQUIRED:\n case EventType.TOOL_RESPONSE_REQUIRED:\n yield chunk;\n return { shouldStopExecution: true };\n case InternalEventType.AGENT_DONE: {\n if (chunk.parent) {\n if (!chunk.send_to_parent) throw new Error('unreachable');\n const parentThread = this.agentThreads.get(chunk.parent.thread_id);\n if (!parentThread) throw new Error('unreachable: parent thread missing');\n const subAgentToolIsOpen = parentThread.hasOpenToolCallId(chunk.parent.tool_call_id);\n if (subAgentToolIsOpen) {\n const parentToolResponse: ToolResponseEvent = {\n type: EventType.TOOL_RESPONSE,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: chunk.parent.thread_id,\n tool_call_id: chunk.send_to_parent.tool_call_id,\n content: '',\n };\n yield parentToolResponse;\n yield* this.sendToThread(chunk.parent.thread_id, [chunk.send_to_parent]);\n }\n yield chunk;\n // Move metrics to the finished bucket and drop the live entry with no `yield` between,\n // so getMetrics() counts this sub-agent once. After `yield chunk` per durable-state.\n addAgentThreadMetrics(this.finishedSubAgentMetrics, currentThread.getAgentThreadMetrics());\n this.agentThreads.delete(chunk.thread_id);\n return { shouldStopExecution: false };\n }\n yield chunk;\n return { shouldStopExecution: true };\n }\n case InternalEventType.AGENT_CREATE_SUBAGENT: {\n const parent = {\n tool_call_id: chunk.tool_call_id,\n thread_id: chunk.thread_id,\n };\n const subAgentThreadId = getThreadId();\n const subAgentThread = await this.createDynamicSubAgentThread({\n parentDefinition: currentThread.definition,\n request: chunk.agent_info,\n threadId: subAgentThreadId,\n parent,\n signal,\n });\n\n yield {\n type: EventType.THREAD_CREATED,\n id: newEventId(),\n agent_info: {\n type: 'dynamic',\n name: chunk.agent_info.name,\n input: chunk.agent_info.input,\n model: chunk.agent_info.model,\n },\n created_at: new Date().toISOString(),\n parent,\n title: chunk.agent_info.name,\n thread_id: subAgentThreadId,\n };\n this.agentThreads.set(subAgentThreadId, subAgentThread);\n return { shouldStopExecution: false };\n }\n default:\n yield chunk;\n return { shouldStopExecution: false };\n }\n }\n\n public async *execute({\n signal,\n }: {\n signal: AbortSignal;\n }): AsyncGenerator<AgentThreadExecutionEvent, AgentThreadExecutionResult, unknown> {\n const { agentThreads } = this;\n\n let shouldStopExecution = false;\n let caughtError: unknown;\n let output: ModelMessageEvent | null = null;\n const requiredActions: ActionRequiredEvent[] = [];\n let rootAgentError: AgentThreadExecutionResult['root_agent_error'];\n const pendingAuthEvents: InternalMCPAuthRequiredEvent[] = [];\n const mainThread = [...agentThreads.values()].find(e => !e.parent);\n if (!mainThread) {\n throw new Error('Unreachable: no root thread found');\n }\n const rootSpan = createRootAgentSpan(mainThread, this.tracing);\n\n onSignalAbort(signal, () => {\n shouldStopExecution = true;\n });\n\n try {\n while (agentThreads.size > 0) {\n if (shouldStopExecution) break;\n\n const activeThreads = getActiveAgentThreads(agentThreads);\n\n for (let i = 0; i < activeThreads.length && !shouldStopExecution; i += MAX_PARALLEL_SUB_AGENTS) {\n const batch = activeThreads.slice(i, i + MAX_PARALLEL_SUB_AGENTS);\n const generators = batch.map(thread => {\n if (!thread.parent) {\n return rootSpan.wrapThreadWithContext(thread, signal);\n }\n return wrapWithSubAgentSpan(rootSpan.trace, thread, signal);\n });\n\n for await (const chunk of mergeAsyncGenerators(generators, this.logger)) {\n if (chunk.type === InternalEventType.MCP_AUTH_REQUIRED) {\n pendingAuthEvents.push(chunk);\n shouldStopExecution = true;\n continue;\n }\n if (chunk.type === InternalEventType.AGENT_DONE && !chunk.parent) {\n // Root-thread only — sub-agent AGENT_DONE would overwrite root trace output /\n // leave a stale error; sub-agent spans finalize in wrapWithSubAgentSpan.\n rootSpan.setOutputFromEvent(chunk);\n }\n\n const result = yield* this.processAgentStreamChunk(chunk, signal);\n if (result.shouldStopExecution) {\n shouldStopExecution = true;\n if (\n !rootAgentError &&\n chunk.type === InternalEventType.AGENT_DONE &&\n isInternalThreadDoneError(chunk) &&\n !chunk.parent\n ) {\n rootAgentError = { error: chunk.error, output: chunk.output };\n }\n if (chunk.type !== InternalEventType.PASSTHROUGH) {\n const { output: outputContribution, requiredAction } = agentThreadEventToTerminalFields(chunk);\n if (outputContribution) output = outputContribution;\n if (requiredAction) requiredActions.push(requiredAction);\n }\n }\n }\n }\n }\n } catch (error) {\n caughtError = error;\n throw error;\n } finally {\n rootSpan.finalize(mainThread, caughtError);\n rootSpan.end();\n }\n\n if (pendingAuthEvents.length > 0) {\n const authEvent = mergeAuthEvents(pendingAuthEvents);\n yield authEvent;\n const authRequiredAction: ActionRequiredEvent = {\n type: EventType.MCP_AUTH_REQUIRED,\n id: authEvent.id,\n created_at: authEvent.created_at,\n thread_id: authEvent.thread_id,\n mcp_servers: authEvent.mcp_servers.map(({ thread_ids, ...s }) => {\n void thread_ids;\n return s;\n }),\n };\n requiredActions.push(authRequiredAction);\n }\n\n return {\n output,\n required_actions: requiredActions,\n root_agent_error: rootAgentError,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA8D;AAC9D,oBAQO;AAEP,mBAA8B;AAC9B,0BAAqC;AACrC,yBAA4B;AAE5B,IAAAA,sBASO;AACP,0BAMO;AAEP,qBAA8F;AAE9F,IAAM,0BAA0B;AAEhC,SAAS,iCAAiC,OAGxC;AACA,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK,sCAAkB,YAAY;AACjC,UAAI,YAAY,SAAS,MAAM,OAAQ,QAAO,CAAC;AAC/C,UAAI,MAAM,WAAW,QAAS,QAAO,CAAC;AACtC,aAAO,EAAE,QAAQ,MAAM,OAAO;AAAA,IAChC;AAAA,IACA,KAAK,wBAAU;AAAA,IACf,KAAK,wBAAU;AACb,aAAO,EAAE,gBAAgB,MAAM;AAAA,IACjC;AACE,aAAO,CAAC;AAAA,EACZ;AACF;AAIA,SAAS,kCACP,UAC6C;AAC7C,QAAM,QAAQ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GAAG,EAAE,MAAM;AAC/D,eAAK;AACL,iBAAO;AAAA,QACT,CAAC;AAAA,MACH;AACA,sBAAgB,KAAK,kBAAkB;AAAA,IACzC;AAEA,WAAO;AAAA,MACL;AAAA,MACA,kBAAkB;AAAA,MAClB,kBAAkB;AAAA,IACpB;AAAA,EACF;AACF;","names":["import_AgentThread"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/runtime/AgentThreadOrchestrator.ts"],"sourcesContent":["import type { Logger } from 'winston';\nimport { AgentHarnessError, InvalidAgentSendInputError } from '../errors';\nimport {\n EventType,\n newEventId,\n type ActionRequiredEvent,\n type ModelMessageEvent,\n type ToolResponseEvent,\n type UserToolApprovalMessage,\n type UserToolResponseMessage,\n} from '../events/schema';\nimport type { AgentExecutionTrace, AgentTracing } from '../tracing/AgentTracing';\nimport { onSignalAbort } from '../util/abort';\nimport { mergeAsyncGenerators } from '../util/promiseUtils';\nimport { AgentThread } from './AgentThread';\nimport type { AgentThreadRuntimeSendBatch } from './AgentThread.types';\nimport {\n InternalEventType,\n type AgentThreadAppendContext,\n type AgentThreadEvent,\n type AgentThreadExecutionEvent,\n type AgentThreadExecutionResult,\n type AgentThreadSendBatch,\n type InternalMCPAuthRequiredEvent,\n type InternalMCPServerAuthInfo,\n} from './AgentThread.types';\nimport {\n assistantMessageContentToStringForSubAgent,\n getThreadId,\n isApprovalDecisionMessage,\n isClientSideToolResponseMessage,\n isInternalThreadDoneError,\n} from './contextUtils';\nimport type { CreateDynamicSubAgentThread } from './CreateDynamicSubAgentThread';\nimport { addAgentThreadMetrics, createEmptyAgentThreadMetrics, type AgentThreadMetrics } from './metrics';\n\nconst MAX_PARALLEL_SUB_AGENTS = 5;\n\nfunction agentThreadEventToTerminalFields(event: AgentThreadExecutionEvent): {\n output?: ModelMessageEvent | undefined;\n requiredAction?: ActionRequiredEvent | undefined;\n} {\n switch (event.type) {\n case InternalEventType.AGENT_DONE: {\n if ('parent' in event && event.parent) {\n return {};\n }\n if (event.status === 'error') {\n return {};\n }\n return { output: event.output };\n }\n case EventType.TOOL_APPROVAL_REQUIRED:\n case EventType.TOOL_RESPONSE_REQUIRED:\n return { requiredAction: event };\n default:\n return {};\n }\n}\n\ntype UserToolApprovalOrResponseBatch = (UserToolApprovalMessage | UserToolResponseMessage)[];\n\nfunction isUserToolApprovalOrResponseBatch(\n messages: AgentThreadSendBatch,\n): messages is UserToolApprovalOrResponseBatch {\n const first = messages[0];\n return first !== undefined && (isApprovalDecisionMessage(first) || isClientSideToolResponseMessage(first));\n}\n\nfunction getMainThreadId(agentThreads: Map<string, AgentThread>): string {\n for (const thread of agentThreads.values()) {\n if (!thread.parent) {\n return thread.threadId;\n }\n }\n throw new Error('Unreachable: no root thread found');\n}\n\nfunction getActiveAgentThreads(agentThreads: Map<string, AgentThread>): AgentThread[] {\n const nodes = new Set(agentThreads.keys());\n const parentNodes = new Set(\n [...agentThreads.values()].map(a => a.parent?.thread_id).filter((a): a is string => Boolean(a)),\n );\n const leaves = [...nodes].filter(id => !parentNodes.has(id));\n if (leaves.length === 0) {\n throw new Error('We cannot have zero leave agents');\n }\n return leaves.map(id => {\n const agentThread = agentThreads.get(id);\n if (!agentThread) {\n throw new Error('unreachable');\n }\n return agentThread;\n });\n}\n\nfunction mergeAuthEvents(events: InternalMCPAuthRequiredEvent[]): InternalMCPAuthRequiredEvent {\n const serverMap = new Map<string, InternalMCPServerAuthInfo>();\n for (const event of events) {\n for (const entry of event.mcp_servers) {\n const existing = serverMap.get(entry.id);\n if (existing) {\n existing.thread_ids.push(...entry.thread_ids);\n } else {\n serverMap.set(entry.id, { ...entry, thread_ids: [...entry.thread_ids] });\n }\n }\n }\n return {\n type: InternalEventType.MCP_AUTH_REQUIRED,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: null,\n mcp_servers: [...serverMap.values()],\n };\n}\n\nfunction wrapGeneratorWithTrace<T, TReturn = void, TNext = unknown>(\n trace: AgentExecutionTrace,\n generator: AsyncGenerator<T, TReturn, TNext>,\n): AsyncGenerator<T, TReturn, TNext> {\n const wrapped: AsyncGenerator<T, TReturn, TNext> = {\n [Symbol.asyncIterator]() {\n return this;\n },\n next(...[value]: [] | [TNext]) {\n return trace.runInContext(() => (value === undefined ? generator.next() : generator.next(value)));\n },\n return(value: TReturn | PromiseLike<TReturn>) {\n return trace.runInContext(() => generator.return(value));\n },\n throw(e: unknown) {\n return trace.runInContext(() => generator.throw(e));\n },\n [Symbol.asyncDispose]() {\n return generator[Symbol.asyncDispose]();\n },\n };\n return wrapped;\n}\n\ninterface RootAgentSpanHandle {\n trace: AgentExecutionTrace;\n wrapThreadWithContext(thread: AgentThread, signal?: AbortSignal): AsyncGenerator<AgentThreadEvent>;\n setOutputFromEvent(chunk: AgentThreadEvent): void;\n finalize(thread: AgentThread, error?: unknown): void;\n end(): void;\n}\n\nfunction createRootAgentSpan(mainThread: AgentThread, tracing: AgentTracing): RootAgentSpanHandle {\n const trace = tracing.startRootSpan(\n JSON.stringify({ instructions: mainThread.definition.instruction, messages: mainThread.definition.messages }),\n );\n let rootAgentErrorMessage: string | undefined;\n let rootAgentCompleted = false;\n\n return {\n trace,\n wrapThreadWithContext(thread: AgentThread, signal?: AbortSignal) {\n return wrapGeneratorWithTrace(trace, thread.execute({ signal }));\n },\n setOutputFromEvent(chunk: AgentThreadEvent) {\n rootAgentCompleted = true;\n if (chunk.type === InternalEventType.AGENT_DONE) {\n if (isInternalThreadDoneError(chunk)) {\n rootAgentErrorMessage = chunk.error;\n trace.setOutput(JSON.stringify({ error: chunk.error }));\n } else {\n const content = assistantMessageContentToStringForSubAgent(chunk.output.content);\n trace.setOutput(JSON.stringify({ result: content }));\n }\n }\n },\n finalize(thread: AgentThread, error?: unknown) {\n trace.setMetrics(thread.getAgentThreadMetrics());\n if (error) {\n trace.setError(error);\n } else if (rootAgentErrorMessage || !rootAgentCompleted) {\n trace.setError(rootAgentErrorMessage ?? 'Agent execution interrupted');\n } else {\n trace.setSuccess();\n }\n },\n end() {\n trace.end();\n },\n };\n}\n\n/** @internal Exported for sub-agent span finalization tests. */\nexport async function* wrapWithSubAgentSpan(\n parentTrace: AgentExecutionTrace,\n currentThread: AgentThread,\n signal?: AbortSignal,\n): AsyncGenerator<AgentThreadEvent> {\n const agentInfo = currentThread.agentInfo;\n if (!agentInfo) {\n throw new Error('Sub-agent thread is missing agentInfo');\n }\n const subTrace = parentTrace.startSubAgent(agentInfo.name, JSON.stringify({ instructions: agentInfo.input }));\n const generator = wrapGeneratorWithTrace(subTrace, currentThread.execute({ signal }));\n\n try {\n for await (const event of generator) {\n if (event.type === InternalEventType.AGENT_DONE) {\n if (isInternalThreadDoneError(event)) {\n subTrace.setOutput(JSON.stringify({ error: event.error }));\n subTrace.setMetrics(currentThread.getAgentThreadMetrics());\n subTrace.setError(event.error);\n } else {\n const content = assistantMessageContentToStringForSubAgent(event.output.content);\n subTrace.setOutput(JSON.stringify({ result: content }));\n subTrace.setMetrics(currentThread.getAgentThreadMetrics());\n subTrace.setSuccess();\n }\n // end() only in finally so every path finalizes exactly once\n }\n yield event;\n }\n } catch (error) {\n subTrace.setError(error);\n throw error;\n } finally {\n subTrace.end();\n }\n}\n\nexport interface AgentThreadOrchestratorInput {\n agentThreads: Map<string, AgentThread>;\n createDynamicSubAgentThread: CreateDynamicSubAgentThread;\n tracing: AgentTracing;\n logger: Logger;\n}\n\nexport class AgentThreadOrchestrator {\n private readonly agentThreads: Map<string, AgentThread>;\n private readonly createDynamicSubAgentThread: CreateDynamicSubAgentThread;\n private readonly tracing: AgentTracing;\n private readonly logger: Logger;\n // Finished sub-agents removed from `agentThreads`; kept so totals still include them.\n private finishedSubAgentMetrics: AgentThreadMetrics = createEmptyAgentThreadMetrics();\n\n constructor(params: AgentThreadOrchestratorInput) {\n this.agentThreads = params.agentThreads;\n this.createDynamicSubAgentThread = params.createDynamicSubAgentThread;\n this.tracing = params.tracing;\n this.logger = params.logger.child({ module: 'AgentThreadOrchestrator' });\n }\n\n /**\n * Turn-wide metrics so far: live threads plus finished sub-agents.\n * Safe mid-flight and after cancel/error (`execute()` may not return).\n * Each thread is counted once — a sub-agent moves from live → finished atomically.\n */\n public getMetrics(): AgentThreadMetrics {\n const total = createEmptyAgentThreadMetrics();\n addAgentThreadMetrics(total, this.finishedSubAgentMetrics);\n for (const thread of this.agentThreads.values()) {\n addAgentThreadMetrics(total, thread.getAgentThreadMetrics());\n }\n return total;\n }\n\n public async *send(messages: AgentThreadSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {\n const byThread = new Map<string, AgentThreadRuntimeSendBatch>();\n for (const thread of this.agentThreads.values()) {\n byThread.set(thread.threadId, []);\n }\n\n if (isUserToolApprovalOrResponseBatch(messages)) {\n const grouped = new Map<string, UserToolApprovalOrResponseBatch[number][]>();\n for (const msg of messages) {\n const threadId = msg.thread_id;\n if (!byThread.has(threadId)) {\n throw new InvalidAgentSendInputError(`unknown thread_id: ${threadId}`);\n }\n const batch = grouped.get(threadId) ?? [];\n batch.push(msg);\n grouped.set(threadId, batch);\n }\n for (const [threadId, batch] of grouped) {\n byThread.set(threadId, batch);\n }\n } else if (messages.length > 0) {\n if (this.agentThreads.size > 1) {\n throw new InvalidAgentSendInputError(\n 'Cannot process user messages while sub agents are running, please send empty input for previous conversation to complete',\n );\n }\n byThread.set(getMainThreadId(this.agentThreads), messages);\n }\n\n const validationErrors: string[] = [];\n for (const [threadId, batch] of byThread) {\n const thread = this.agentThreads.get(threadId);\n if (!thread) {\n throw new Error(`AgentThreadOrchestrator.send: unknown threadId ${threadId}`);\n }\n try {\n thread.validateSendInput(batch);\n } catch (e) {\n if (e instanceof AgentHarnessError && e.code === 'invalid_send_input') {\n validationErrors.push(`thread ${threadId}: ${e.message}`);\n } else {\n throw e;\n }\n }\n }\n if (validationErrors.length > 0) {\n throw new InvalidAgentSendInputError(validationErrors.join('; '));\n }\n\n for (const [threadId, batch] of byThread) {\n yield* this.sendToThread(threadId, batch);\n }\n }\n\n private async *sendToThread(\n threadId: string,\n messages: AgentThreadRuntimeSendBatch,\n ): AsyncGenerator<AgentThreadAppendContext, void, unknown> {\n const thread = this.agentThreads.get(threadId);\n if (!thread) {\n throw new Error(`AgentThreadOrchestrator.sendToThread: unknown threadId ${threadId}`);\n }\n yield* thread.send(messages);\n }\n\n private async *processAgentStreamChunk(\n chunk: Exclude<AgentThreadEvent, InternalMCPAuthRequiredEvent>,\n signal: AbortSignal,\n ): AsyncGenerator<AgentThreadExecutionEvent, { shouldStopExecution: boolean }, unknown> {\n if (chunk.type === InternalEventType.PASSTHROUGH) {\n yield chunk.event;\n return { shouldStopExecution: false };\n }\n\n if (!('thread_id' in chunk) || chunk.thread_id == null) {\n yield chunk;\n return { shouldStopExecution: false };\n }\n\n const currentThread = this.agentThreads.get(chunk.thread_id);\n if (!currentThread) {\n throw new Error('unreachable');\n }\n\n switch (chunk.type) {\n case EventType.TOOL_APPROVAL_REQUIRED:\n case EventType.TOOL_RESPONSE_REQUIRED:\n yield chunk;\n return { shouldStopExecution: true };\n case InternalEventType.AGENT_DONE: {\n if (chunk.parent) {\n if (!chunk.send_to_parent) {\n throw new Error('unreachable');\n }\n const parentThread = this.agentThreads.get(chunk.parent.thread_id);\n if (!parentThread) {\n throw new Error('unreachable: parent thread missing');\n }\n const subAgentToolIsOpen = parentThread.hasOpenToolCallId(chunk.parent.tool_call_id);\n if (subAgentToolIsOpen) {\n const parentToolResponse: ToolResponseEvent = {\n type: EventType.TOOL_RESPONSE,\n id: newEventId(),\n created_at: new Date().toISOString(),\n thread_id: chunk.parent.thread_id,\n tool_call_id: chunk.send_to_parent.tool_call_id,\n content: '',\n };\n yield parentToolResponse;\n yield* this.sendToThread(chunk.parent.thread_id, [chunk.send_to_parent]);\n }\n yield chunk;\n // Move metrics to the finished bucket and drop the live entry with no `yield` between,\n // so getMetrics() counts this sub-agent once. After `yield chunk` per durable-state.\n addAgentThreadMetrics(this.finishedSubAgentMetrics, currentThread.getAgentThreadMetrics());\n this.agentThreads.delete(chunk.thread_id);\n return { shouldStopExecution: false };\n }\n yield chunk;\n return { shouldStopExecution: true };\n }\n case InternalEventType.AGENT_CREATE_SUBAGENT: {\n const parent = {\n tool_call_id: chunk.tool_call_id,\n thread_id: chunk.thread_id,\n };\n const subAgentThreadId = getThreadId();\n const subAgentThread = await this.createDynamicSubAgentThread({\n parentDefinition: currentThread.definition,\n request: chunk.agent_info,\n threadId: subAgentThreadId,\n parent,\n signal,\n });\n\n yield {\n type: EventType.THREAD_CREATED,\n id: newEventId(),\n agent_info: {\n type: 'dynamic',\n name: chunk.agent_info.name,\n input: chunk.agent_info.input,\n model: chunk.agent_info.model,\n },\n created_at: new Date().toISOString(),\n parent,\n title: chunk.agent_info.name,\n thread_id: subAgentThreadId,\n };\n this.agentThreads.set(subAgentThreadId, subAgentThread);\n return { shouldStopExecution: false };\n }\n default:\n yield chunk;\n return { shouldStopExecution: false };\n }\n }\n\n public async *execute({\n signal,\n }: {\n signal: AbortSignal;\n }): AsyncGenerator<AgentThreadExecutionEvent, AgentThreadExecutionResult, unknown> {\n const { agentThreads } = this;\n\n let shouldStopExecution = false;\n let caughtError: unknown;\n let output: ModelMessageEvent | null = null;\n const requiredActions: ActionRequiredEvent[] = [];\n let rootAgentError: AgentThreadExecutionResult['root_agent_error'];\n const pendingAuthEvents: InternalMCPAuthRequiredEvent[] = [];\n const mainThread = [...agentThreads.values()].find(e => !e.parent);\n if (!mainThread) {\n throw new Error('Unreachable: no root thread found');\n }\n const rootSpan = createRootAgentSpan(mainThread, this.tracing);\n\n onSignalAbort(signal, () => {\n shouldStopExecution = true;\n });\n\n try {\n while (agentThreads.size > 0) {\n if (shouldStopExecution) {\n break;\n }\n\n const activeThreads = getActiveAgentThreads(agentThreads);\n\n for (let i = 0; i < activeThreads.length && !shouldStopExecution; i += MAX_PARALLEL_SUB_AGENTS) {\n const batch = activeThreads.slice(i, i + MAX_PARALLEL_SUB_AGENTS);\n const generators = batch.map(thread => {\n if (!thread.parent) {\n return rootSpan.wrapThreadWithContext(thread, signal);\n }\n return wrapWithSubAgentSpan(rootSpan.trace, thread, signal);\n });\n\n for await (const chunk of mergeAsyncGenerators(generators, this.logger)) {\n if (chunk.type === InternalEventType.MCP_AUTH_REQUIRED) {\n pendingAuthEvents.push(chunk);\n shouldStopExecution = true;\n continue;\n }\n if (chunk.type === InternalEventType.AGENT_DONE && !chunk.parent) {\n // Root-thread only — sub-agent AGENT_DONE would overwrite root trace output /\n // leave a stale error; sub-agent spans finalize in wrapWithSubAgentSpan.\n rootSpan.setOutputFromEvent(chunk);\n }\n\n const result = yield* this.processAgentStreamChunk(chunk, signal);\n if (result.shouldStopExecution) {\n shouldStopExecution = true;\n if (\n !rootAgentError &&\n chunk.type === InternalEventType.AGENT_DONE &&\n isInternalThreadDoneError(chunk) &&\n !chunk.parent\n ) {\n rootAgentError = { error: chunk.error, output: chunk.output };\n }\n if (chunk.type !== InternalEventType.PASSTHROUGH) {\n const { output: outputContribution, requiredAction } = agentThreadEventToTerminalFields(chunk);\n if (outputContribution) {\n output = outputContribution;\n }\n if (requiredAction) {\n requiredActions.push(requiredAction);\n }\n }\n }\n }\n }\n }\n } catch (error) {\n caughtError = error;\n throw error;\n } finally {\n rootSpan.finalize(mainThread, caughtError);\n rootSpan.end();\n }\n\n if (pendingAuthEvents.length > 0) {\n const authEvent = mergeAuthEvents(pendingAuthEvents);\n yield authEvent;\n const authRequiredAction: ActionRequiredEvent = {\n type: EventType.MCP_AUTH_REQUIRED,\n id: authEvent.id,\n created_at: authEvent.created_at,\n thread_id: authEvent.thread_id,\n mcp_servers: authEvent.mcp_servers.map(({ thread_ids, ...s }) => {\n void thread_ids;\n return s;\n }),\n };\n requiredActions.push(authRequiredAction);\n }\n\n return {\n output,\n required_actions: requiredActions,\n root_agent_error: rootAgentError,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA8D;AAC9D,oBAQO;AAEP,mBAA8B;AAC9B,0BAAqC;AACrC,yBAA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