@caupulican/pi-agent-core 0.85.0 → 0.85.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +148 -37
- package/dist/agent-loop.js.map +1 -1
- package/dist/agent.d.ts +4 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +10 -3
- package/dist/agent.js.map +1 -1
- package/dist/compaction/loop.d.ts +1 -1
- package/dist/compaction/loop.d.ts.map +1 -1
- package/dist/compaction/loop.js +7 -2
- package/dist/compaction/loop.js.map +1 -1
- package/dist/tool-failure-memory.d.ts +17 -2
- package/dist/tool-failure-memory.d.ts.map +1 -1
- package/dist/tool-failure-memory.js +100 -10
- package/dist/tool-failure-memory.js.map +1 -1
- package/package.json +2 -2
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAWxD,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAiBrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAI9C,SAAS,mBAAmB,CAAC,QAAwB;IACpD,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AACH,CAAC;AAED,MAAM,aAAa,GAAG;IACrB,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,SAAS;IACd,QAAQ,EAAE,SAAS;IACnB,OAAO,EAAE,EAAE;IACX,SAAS,EAAE,KAAK;IAChB,KAAK,EAAE,EAAE;IACT,IAAI,E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K,CAAC,UAAU,CAAC,CAAC;gBAC1C,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;gBAChD,MAAM;YACP,CAAC;YAED,KAAK,UAAU;gBACd,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC;oBACtE,IAAI,CAAC,MAAM,CAAC,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC;gBACvD,CAAC;gBACD,MAAM;YAEP,KAAK,WAAW;gBACf,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { streamSimple } from \"@caupulican/pi-ai/stream\";\nimport type {\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tTransport,\n} from \"@caupulican/pi-ai/types\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai/validation\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\nimport { createEmptyUsage } from \"./usage.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tresolveRequestReasoning?: AgentLoopConfig[\"resolveRequestReasoning\"];\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\ttextToolCallProtocol?: SimpleStreamOptions[\"textToolCallProtocol\"];\n\tonTextToolProtocolParse?: SimpleStreamOptions[\"onTextToolProtocolParse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tbackgroundToolCallAfterMs?: AgentLoopConfig[\"backgroundToolCallAfterMs\"];\n\thandoffToolCall?: AgentLoopConfig[\"handoffToolCall\"];\n\tsubscribeToolCallHandoffRequest?: AgentLoopConfig[\"subscribeToolCallHandoffRequest\"];\n\tonToolArgumentValidation?: (event: ToolArgumentValidationTelemetryEvent) => void;\n\ttoolArgumentTeachEnabled?: boolean;\n\ttoolValidationEscalationThreshold?: number;\n\tonToolValidationEscalation?: AgentLoopConfig[\"onToolValidationEscalation\"];\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxStallTurns?: number;\n\tonRunawayStop?: AgentLoopConfig[\"onRunawayStop\"];\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic resolveRequestReasoning?: AgentLoopConfig[\"resolveRequestReasoning\"];\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic textToolCallProtocol?: SimpleStreamOptions[\"textToolCallProtocol\"];\n\tpublic onTextToolProtocolParse?: SimpleStreamOptions[\"onTextToolProtocolParse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic backgroundToolCallAfterMs?: AgentLoopConfig[\"backgroundToolCallAfterMs\"];\n\tpublic handoffToolCall?: AgentLoopConfig[\"handoffToolCall\"];\n\tpublic subscribeToolCallHandoffRequest?: AgentLoopConfig[\"subscribeToolCallHandoffRequest\"];\n\tpublic onToolArgumentValidation?: (event: ToolArgumentValidationTelemetryEvent) => void;\n\tpublic toolArgumentTeachEnabled?: boolean;\n\tpublic toolValidationEscalationThreshold?: number;\n\tpublic onToolValidationEscalation?: AgentLoopConfig[\"onToolValidationEscalation\"];\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Runaway-loop backstop for repeated identical tool-call turns. */\n\tpublic maxStallTurns?: number;\n\t/** Observability hook fired once if the {@link maxStallTurns} runaway backstop trips. */\n\tpublic onRunawayStop?: AgentLoopConfig[\"onRunawayStop\"];\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.resolveRequestReasoning = options.resolveRequestReasoning;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.textToolCallProtocol = options.textToolCallProtocol;\n\t\tthis.onTextToolProtocolParse = options.onTextToolProtocolParse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.backgroundToolCallAfterMs = options.backgroundToolCallAfterMs;\n\t\tthis.handoffToolCall = options.handoffToolCall;\n\t\tthis.subscribeToolCallHandoffRequest = options.subscribeToolCallHandoffRequest;\n\t\tthis.onToolArgumentValidation = options.onToolArgumentValidation;\n\t\tthis.toolArgumentTeachEnabled = options.toolArgumentTeachEnabled;\n\t\tthis.toolValidationEscalationThreshold = options.toolValidationEscalationThreshold;\n\t\tthis.onToolValidationEscalation = options.onToolValidationEscalation;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxStallTurns = options.maxStallTurns;\n\t\tthis.onRunawayStop = options.onRunawayStop;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel,\n\t\t\ttemperature: this.textToolCallProtocol ? 0 : undefined,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttextToolCallProtocol: this.textToolCallProtocol,\n\t\t\tonTextToolProtocolParse: this.onTextToolProtocolParse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxStallTurns: this.maxStallTurns,\n\t\t\tonRunawayStop: this.onRunawayStop,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolArgumentTeachEnabled: this.toolArgumentTeachEnabled,\n\t\t\tonToolArgumentValidation: this.onToolArgumentValidation,\n\t\t\ttoolValidationEscalationThreshold: this.toolValidationEscalationThreshold,\n\t\t\tonToolValidationEscalation: this.onToolValidationEscalation,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tbackgroundToolCallAfterMs: this.backgroundToolCallAfterMs,\n\t\t\thandoffToolCall: this.handoffToolCall,\n\t\t\tsubscribeToolCallHandoffRequest: this.subscribeToolCallHandoffRequest,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tresolveRequestReasoning: this.resolveRequestReasoning,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: createEmptyUsage(),\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAWxD,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAiBrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAI9C,SAAS,mBAAmB,CAAC,Q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;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { streamSimple } from \"@caupulican/pi-ai/stream\";\nimport type {\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tTransport,\n} from \"@caupulican/pi-ai/types\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai/validation\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\nimport { createEmptyUsage } from \"./usage.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tresolveRequestReasoning?: AgentLoopConfig[\"resolveRequestReasoning\"];\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\ttextToolCallProtocol?: SimpleStreamOptions[\"textToolCallProtocol\"];\n\tonTextToolProtocolParse?: SimpleStreamOptions[\"onTextToolProtocolParse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tbackgroundToolCallAfterMs?: AgentLoopConfig[\"backgroundToolCallAfterMs\"];\n\thandoffToolCall?: AgentLoopConfig[\"handoffToolCall\"];\n\tsubscribeToolCallHandoffRequest?: AgentLoopConfig[\"subscribeToolCallHandoffRequest\"];\n\tonToolArgumentValidation?: (event: ToolArgumentValidationTelemetryEvent) => void;\n\ttoolArgumentTeachEnabled?: boolean;\n\ttoolValidationEscalationThreshold?: number;\n\tonToolValidationEscalation?: AgentLoopConfig[\"onToolValidationEscalation\"];\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxStallTurns?: number;\n\tonRunawayStop?: AgentLoopConfig[\"onRunawayStop\"];\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/** A second foreground operation tried to acquire an Agent that still owns an active run. */\nexport class AgentBusyError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentBusyError\";\n\t}\n}\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic resolveRequestReasoning?: AgentLoopConfig[\"resolveRequestReasoning\"];\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic textToolCallProtocol?: SimpleStreamOptions[\"textToolCallProtocol\"];\n\tpublic onTextToolProtocolParse?: SimpleStreamOptions[\"onTextToolProtocolParse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic backgroundToolCallAfterMs?: AgentLoopConfig[\"backgroundToolCallAfterMs\"];\n\tpublic handoffToolCall?: AgentLoopConfig[\"handoffToolCall\"];\n\tpublic subscribeToolCallHandoffRequest?: AgentLoopConfig[\"subscribeToolCallHandoffRequest\"];\n\tpublic onToolArgumentValidation?: (event: ToolArgumentValidationTelemetryEvent) => void;\n\tpublic toolArgumentTeachEnabled?: boolean;\n\tpublic toolValidationEscalationThreshold?: number;\n\tpublic onToolValidationEscalation?: AgentLoopConfig[\"onToolValidationEscalation\"];\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Runaway-loop backstop for repeated identical tool-call turns. */\n\tpublic maxStallTurns?: number;\n\t/** Observability hook fired once if the {@link maxStallTurns} runaway backstop trips. */\n\tpublic onRunawayStop?: AgentLoopConfig[\"onRunawayStop\"];\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.resolveRequestReasoning = options.resolveRequestReasoning;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.textToolCallProtocol = options.textToolCallProtocol;\n\t\tthis.onTextToolProtocolParse = options.onTextToolProtocolParse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.backgroundToolCallAfterMs = options.backgroundToolCallAfterMs;\n\t\tthis.handoffToolCall = options.handoffToolCall;\n\t\tthis.subscribeToolCallHandoffRequest = options.subscribeToolCallHandoffRequest;\n\t\tthis.onToolArgumentValidation = options.onToolArgumentValidation;\n\t\tthis.toolArgumentTeachEnabled = options.toolArgumentTeachEnabled;\n\t\tthis.toolValidationEscalationThreshold = options.toolValidationEscalationThreshold;\n\t\tthis.onToolValidationEscalation = options.onToolValidationEscalation;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxStallTurns = options.maxStallTurns;\n\t\tthis.onRunawayStop = options.onRunawayStop;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentBusyError(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentBusyError(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel,\n\t\t\ttemperature: this.textToolCallProtocol ? 0 : undefined,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttextToolCallProtocol: this.textToolCallProtocol,\n\t\t\tonTextToolProtocolParse: this.onTextToolProtocolParse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxStallTurns: this.maxStallTurns,\n\t\t\tonRunawayStop: this.onRunawayStop,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolArgumentTeachEnabled: this.toolArgumentTeachEnabled,\n\t\t\tonToolArgumentValidation: this.onToolArgumentValidation,\n\t\t\ttoolValidationEscalationThreshold: this.toolValidationEscalationThreshold,\n\t\t\tonToolValidationEscalation: this.onToolValidationEscalation,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tbackgroundToolCallAfterMs: this.backgroundToolCallAfterMs,\n\t\t\thandoffToolCall: this.handoffToolCall,\n\t\t\tsubscribeToolCallHandoffRequest: this.subscribeToolCallHandoffRequest,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tresolveRequestReasoning: this.resolveRequestReasoning,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentBusyError(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: createEmptyUsage(),\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
|
|
@@ -22,7 +22,7 @@ export interface CompactionLoopDeps {
|
|
|
22
22
|
summarizeAndVerify(params: CompactionCycleParams, model: Model<any>, apiKey: string | undefined, headers: Record<string, string> | undefined, branch: SessionEntry[]): Promise<{
|
|
23
23
|
result: CompactionResult;
|
|
24
24
|
}>;
|
|
25
|
-
buildDeterministicCheckpoint(): Promise<{
|
|
25
|
+
buildDeterministicCheckpoint(params: CompactionCycleParams): Promise<{
|
|
26
26
|
result: CompactionResult;
|
|
27
27
|
}> | {
|
|
28
28
|
result: CompactionResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../../src/compaction/loop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,KAAK,gBAAgB,EAAsC,MAAM,iBAAiB,CAAC;AAG5F,MAAM,WAAW,qBAAqB;IACrC,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IAC/B,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,iBAAiB,EAAE,OAAO,CAAC;CAC3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I,MAAM,CAAC;IACnC,qBAAqB,CAAC,IAAI,OAAO,CAAC;IAClC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,MAAM,qBAAqB,GAC9B;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC7D;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAMtD,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAuJhG"}
|
package/dist/compaction/loop.js
CHANGED
|
@@ -49,7 +49,7 @@ export async function runCompactionLoop(deps) {
|
|
|
49
49
|
return { kind: "failed", reason: "aborted", cycles: cycle - 1 };
|
|
50
50
|
}
|
|
51
51
|
try {
|
|
52
|
-
const built = await Promise.resolve(deps.buildDeterministicCheckpoint());
|
|
52
|
+
const built = await Promise.resolve(deps.buildDeterministicCheckpoint(params));
|
|
53
53
|
const result = mergeCompactionVerificationReports(built.result, pendingVerificationReports);
|
|
54
54
|
pendingVerificationReports.length = 0;
|
|
55
55
|
await deps.apply(result);
|
|
@@ -103,7 +103,7 @@ export async function runCompactionLoop(deps) {
|
|
|
103
103
|
}
|
|
104
104
|
if (lastCause === "deterministic-required") {
|
|
105
105
|
try {
|
|
106
|
-
const built = await Promise.resolve(deps.buildDeterministicCheckpoint());
|
|
106
|
+
const built = await Promise.resolve(deps.buildDeterministicCheckpoint(params));
|
|
107
107
|
const deterministicResult = mergeCompactionVerificationReports(built.result, pendingVerificationReports);
|
|
108
108
|
pendingVerificationReports.length = 0;
|
|
109
109
|
await deps.apply(deterministicResult);
|
|
@@ -171,6 +171,11 @@ function selectCycleParams(cycle, cause, lastParams, baseKeepRecent) {
|
|
|
171
171
|
else if (cause === "effect-not-restored") {
|
|
172
172
|
params.chunked = true;
|
|
173
173
|
params.keepRecentTokens = Math.max(1, Math.floor(lastParams.keepRecentTokens / 2));
|
|
174
|
+
// The first verified summary already paid the model cost. If applying it did not restore
|
|
175
|
+
// headroom, repeating the same summarization request can stall a tool loop for minutes while
|
|
176
|
+
// protected recent/image content remains unchanged. Finish the bounded retry with the
|
|
177
|
+
// deterministic checkpoint at the stricter cut instead of buying two more equivalent calls.
|
|
178
|
+
params.deterministicOnly = true;
|
|
174
179
|
}
|
|
175
180
|
return params;
|
|
176
181
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.js","sourceRoot":"","sources":["../../src/compaction/loop.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D,OAAO,EAAyB,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAA2B,MAAM,mBAAmB,CAAC;AA0CzF,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEnC,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,IAAwB;IAC/D,IAAI,SAAS,GAAG,OAAO,CAAC;IACxB,IAAI,UAA6C,CAAC;IAClD,IAAI,kBAAsC,CAAC;IAC3C,IAAI,aAA2C,CAAC;IAChD,IAAI,YAAgC,CAAC;IACrC,IAAI,uBAA2C,CAAC;IAChD,IAAI,+BAA+B,GAAG,KAAK,CAAC;IAC5C,MAAM,0BAA0B,GAAyB,EAAE,CAAC;IAC5D,IAAI,cAAc,GAAG,IAAI,CAAC,uBAAuB,CAAC,CAAC,CAAC,IAAI,CAAC,uBAAuB,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;IACzG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,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ai\";\nimport { classifyFailure } from \"../reliability/classifier.ts\";\nimport type { SessionEntry } from \"../session/session-manager.ts\";\nimport { type CompactionResult, mergeCompactionVerificationReports } from \"./compaction.ts\";\nimport { CompactionVerificationError, type VerificationReport } from \"./verification.ts\";\n\nexport interface CompactionCycleParams {\n\tmodelTier: \"cheap\" | \"session\";\n\tkeepRecentTokens: number;\n\tchunked: boolean;\n\tdeterministicOnly: boolean;\n}\n\nexport interface ModelAndAuth {\n\tmodel: Model<any>;\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n\tfailure?: string;\n}\n\nexport interface CompactionLoopDeps {\n\tmeasureLiveTokens(): number;\n\tshouldCompact(tokens: number): boolean;\n\tgetPostApplyMargin(): number;\n\tgetBranch(): SessionEntry[];\n\tresolveModelAndAuth(modelTier: CompactionCycleParams[\"modelTier\"]): Promise<ModelAndAuth>;\n\tsummarizeAndVerify(\n\t\tparams: CompactionCycleParams,\n\t\tmodel: Model<any>,\n\t\tapiKey: string | undefined,\n\t\theaders: Record<string, string> | undefined,\n\t\tbranch: SessionEntry[],\n\t): Promise<{ result: CompactionResult }>;\n\tbuildDeterministicCheckpoint(): Promise<{ result: CompactionResult }> | { result: CompactionResult };\n\tapply(result: CompactionResult): Promise<void> | void;\n\tonTransition(info: { cycle: number; from: string; cause: string; detail?: string }): void;\n\tgetBaseKeepRecentTokens?(): number;\n\tverifyPostApplyEffect?(): boolean;\n\tsignal?: AbortSignal;\n}\n\nexport type CompactionLoopOutcome =\n\t| { kind: \"success\"; result: CompactionResult; cycles: number }\n\t| { kind: \"skip\"; reason: string }\n\t| { kind: \"failed\"; reason: string; cycles: number };\n\nconst MAX_CYCLES = 4;\nconst MAX_LLM_CYCLES = 3;\nconst DEFAULT_KEEP_RECENT = 20_000;\n\nexport async function runCompactionLoop(deps: CompactionLoopDeps): Promise<CompactionLoopOutcome> {\n\tlet lastCause = \"start\";\n\tlet lastParams: CompactionCycleParams | undefined;\n\tlet lastObservedTokens: number | undefined;\n\tlet appliedResult: CompactionResult | undefined;\n\tlet lastModelKey: string | undefined;\n\tlet ownTrailingCompactionId: string | undefined;\n\tlet ownTrailingCompactionNeedsRetry = false;\n\tconst pendingVerificationReports: VerificationReport[] = [];\n\tlet baseKeepRecent = deps.getBaseKeepRecentTokens ? deps.getBaseKeepRecentTokens() : DEFAULT_KEEP_RECENT;\n\tif (!Number.isFinite(baseKeepRecent) || baseKeepRecent <= 0) {\n\t\tbaseKeepRecent = DEFAULT_KEEP_RECENT;\n\t}\n\n\tfor (let cycle = 1; cycle <= MAX_CYCLES; cycle++) {\n\t\tif (deps.signal?.aborted) {\n\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle - 1 };\n\t\t}\n\n\t\tconst branch = deps.getBranch();\n\t\tconst trailingEntry = branch[branch.length - 1];\n\t\tif (branch.length > 0 && trailingEntry?.type === \"compaction\") {\n\t\t\tif (appliedResult && trailingEntry.id === ownTrailingCompactionId) {\n\t\t\t\tif (!ownTrailingCompactionNeedsRetry) return { kind: \"success\", result: appliedResult, cycles: cycle - 1 };\n\t\t\t} else {\n\t\t\t\treturn { kind: \"skip\", reason: \"already compacted\" };\n\t\t\t}\n\t\t}\n\n\t\tconst observedTokens = deps.measureLiveTokens();\n\t\tif (cycle === 1 && !deps.shouldCompact(observedTokens)) {\n\t\t\treturn {\n\t\t\t\tkind: \"skip\",\n\t\t\t\treason:\n\t\t\t\t\tbranch.length > 0 && branch[branch.length - 1]?.type === \"compaction\"\n\t\t\t\t\t\t? \"already compacted\"\n\t\t\t\t\t\t: \"within threshold\",\n\t\t\t};\n\t\t}\n\n\t\tconst selectedParams = selectCycleParams(cycle, lastCause, lastParams, baseKeepRecent);\n\t\tlet params = enforceMonotonicProgress(selectedParams, lastParams, observedTokens, lastObservedTokens, lastCause);\n\t\tlastObservedTokens = observedTokens;\n\n\t\tif (params.deterministicOnly || cycle > MAX_LLM_CYCLES) {\n\t\t\tif (deps.signal?.aborted) {\n\t\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle - 1 };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst built = await Promise.resolve(deps.buildDeterministicCheckpoint());\n\t\t\t\tconst result = mergeCompactionVerificationReports(built.result, pendingVerificationReports);\n\t\t\t\tpendingVerificationReports.length = 0;\n\t\t\t\tawait deps.apply(result);\n\t\t\t\treturn { kind: \"success\", result, cycles: cycle };\n\t\t\t} catch (error) {\n\t\t\t\treturn { kind: \"failed\", reason: mapFailureCause(error).cause, cycles: cycle };\n\t\t\t}\n\t\t}\n\n\t\tlet modelInfo: ModelAndAuth;\n\t\ttry {\n\t\t\tmodelInfo = await deps.resolveModelAndAuth(params.modelTier);\n\t\t} catch {\n\t\t\tlastCause = \"auth-failed\";\n\t\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step0\", cause: lastCause });\n\t\t\tcontinue;\n\t\t}\n\t\tif (modelInfo.failure) {\n\t\t\tlastCause = \"auth-failed\";\n\t\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step0\", cause: lastCause });\n\t\t\tcontinue;\n\t\t}\n\t\tconst currentModelKey = modelKey(modelInfo.model);\n\t\tif (\n\t\t\t(lastCause === \"gate-failed\" || lastCause === \"length-stop\") &&\n\t\t\tlastParams &&\n\t\t\tparams.modelTier !== lastParams.modelTier &&\n\t\t\tlastModelKey === currentModelKey\n\t\t) {\n\t\t\tparams = { ...params, modelTier: lastParams.modelTier };\n\t\t}\n\t\tlastParams = params;\n\t\tlastModelKey = currentModelKey;\n\n\t\tlet result: CompactionResult;\n\t\ttry {\n\t\t\t({ result } = await deps.summarizeAndVerify(\n\t\t\t\tparams,\n\t\t\t\tmodelInfo.model,\n\t\t\t\tmodelInfo.apiKey,\n\t\t\t\tmodelInfo.headers,\n\t\t\t\tbranch,\n\t\t\t));\n\t\t} catch (error) {\n\t\t\tif (deps.signal?.aborted) {\n\t\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle };\n\t\t\t}\n\t\t\tif (error instanceof CompactionVerificationError) {\n\t\t\t\tpendingVerificationReports.push(...error.reports);\n\t\t\t}\n\t\t\tconst failure = mapFailureCause(error, modelInfo.model.provider);\n\t\t\tlastCause = failure.cause;\n\t\t\tif (lastCause === \"aborted\") {\n\t\t\t\treturn { kind: \"failed\", reason: lastCause, cycles: cycle };\n\t\t\t}\n\t\t\tif (lastCause === \"provider-failure\") {\n\t\t\t\treturn { kind: \"failed\", reason: error instanceof Error ? error.message : String(error), cycles: cycle };\n\t\t\t}\n\t\t\tif (lastCause === \"deterministic-required\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst built = await Promise.resolve(deps.buildDeterministicCheckpoint());\n\t\t\t\t\tconst deterministicResult = mergeCompactionVerificationReports(built.result, pendingVerificationReports);\n\t\t\t\t\tpendingVerificationReports.length = 0;\n\t\t\t\t\tawait deps.apply(deterministicResult);\n\t\t\t\t\treturn { kind: \"success\", result: deterministicResult, cycles: cycle };\n\t\t\t\t} catch (deterministicError) {\n\t\t\t\t\treturn { kind: \"failed\", reason: mapFailureCause(deterministicError).cause, cycles: cycle };\n\t\t\t\t}\n\t\t\t}\n\t\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step3\", cause: lastCause, detail: failure.detail });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (deps.signal?.aborted) {\n\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle };\n\t\t}\n\t\tmergeCompactionVerificationReports(result, pendingVerificationReports);\n\t\tpendingVerificationReports.length = 0;\n\t\tawait deps.apply(result);\n\t\tappliedResult = result;\n\t\tconst branchAfterApply = deps.getBranch();\n\t\tconst trailingAfterApply = branchAfterApply[branchAfterApply.length - 1];\n\t\townTrailingCompactionId = trailingAfterApply?.type === \"compaction\" ? trailingAfterApply.id : undefined;\n\n\t\tif (deps.verifyPostApplyEffect?.() === false) {\n\t\t\townTrailingCompactionNeedsRetry = false;\n\t\t\treturn { kind: \"success\", result, cycles: cycle };\n\t\t}\n\n\t\tconst measuredAfter = deps.measureLiveTokens();\n\t\tif (!deps.shouldCompact(measuredAfter + deps.getPostApplyMargin())) {\n\t\t\townTrailingCompactionNeedsRetry = false;\n\t\t\treturn { kind: \"success\", result, cycles: cycle };\n\t\t}\n\n\t\townTrailingCompactionNeedsRetry = true;\n\t\tlastCause = \"effect-not-restored\";\n\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step5\", cause: lastCause });\n\t}\n\n\treturn { kind: \"failed\", reason: \"exhausted-compaction-cycles\", cycles: MAX_CYCLES };\n}\n\nfunction selectCycleParams(\n\tcycle: number,\n\tcause: string,\n\tlastParams: CompactionCycleParams | undefined,\n\tbaseKeepRecent: number,\n): CompactionCycleParams {\n\tif (cycle >= MAX_CYCLES) {\n\t\treturn {\n\t\t\tmodelTier: lastParams?.modelTier ?? \"session\",\n\t\t\tkeepRecentTokens: Math.max(1, Math.floor((lastParams?.keepRecentTokens ?? baseKeepRecent) / 2)),\n\t\t\tchunked: true,\n\t\t\tdeterministicOnly: true,\n\t\t};\n\t}\n\n\tif (!lastParams) {\n\t\treturn {\n\t\t\tmodelTier: \"cheap\",\n\t\t\tkeepRecentTokens: Math.max(1, baseKeepRecent),\n\t\t\tchunked: false,\n\t\t\tdeterministicOnly: false,\n\t\t};\n\t}\n\n\tconst params: CompactionCycleParams = {\n\t\t...lastParams,\n\t\tdeterministicOnly: false,\n\t};\n\n\tif (cause === \"gate-failed\" || cause === \"auth-failed\" || cause === \"length-stop\") {\n\t\tparams.modelTier = \"session\";\n\t} else if (cause === \"input-overflow\") {\n\t\tparams.chunked = true;\n\t} else if (cause === \"effect-not-restored\") {\n\t\tparams.chunked = true;\n\t\tparams.keepRecentTokens = Math.max(1, Math.floor(lastParams.keepRecentTokens / 2));\n\t}\n\n\treturn params;\n}\n\nfunction enforceMonotonicProgress(\n\tparams: CompactionCycleParams,\n\tlastParams: CompactionCycleParams | undefined,\n\tobservedTokens: number,\n\tlastObservedTokens: number | undefined,\n\tlastCause: string,\n): CompactionCycleParams {\n\tif (\n\t\t!lastParams ||\n\t\tparams.deterministicOnly ||\n\t\t(lastObservedTokens !== undefined && observedTokens < lastObservedTokens)\n\t) {\n\t\treturn params;\n\t}\n\tif (!sameParams(params, lastParams)) {\n\t\treturn params;\n\t}\n\tif (lastCause === \"gate-failed\") {\n\t\treturn params;\n\t}\n\n\tconst keepRecentTokens = Math.max(1, Math.floor(params.keepRecentTokens / 2));\n\tif (keepRecentTokens !== params.keepRecentTokens) {\n\t\treturn { ...params, chunked: true, keepRecentTokens };\n\t}\n\tif (!params.chunked) {\n\t\treturn { ...params, chunked: true };\n\t}\n\treturn { ...params, modelTier: params.modelTier === \"cheap\" ? \"session\" : \"cheap\" };\n}\n\nfunction modelKey(model: Model<any>): string {\n\treturn `${model.provider}:${model.id}:${model.api}:${model.baseUrl ?? \"\"}`;\n}\n\nfunction sameParams(a: CompactionCycleParams, b: CompactionCycleParams): boolean {\n\treturn (\n\t\ta.modelTier === b.modelTier &&\n\t\ta.keepRecentTokens === b.keepRecentTokens &&\n\t\ta.chunked === b.chunked &&\n\t\ta.deterministicOnly === b.deterministicOnly\n\t);\n}\n\nfunction mapFailureCause(error: unknown, provider?: string): { cause: string; detail?: string } {\n\tconst message = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n\tif (message.includes(\"gate-failed\")) return { cause: \"gate-failed\", detail: boundedDetail(message) };\n\tif (message.includes(\"summary-demand-exceeds-reserve\"))\n\t\treturn { cause: \"deterministic-required\", detail: boundedDetail(message) };\n\tif (message.includes(\"input-overflow\")) return { cause: \"input-overflow\", detail: boundedDetail(message) };\n\t// A length-stopped summary lost gated sections; escalating the tier buys a larger output cap.\n\tif (message.includes(\"summary-length-stop\")) return { cause: \"length-stop\", detail: boundedDetail(message) };\n\tif (message.includes(\"auto-compaction-cancelled\")) return { cause: \"aborted\", detail: boundedDetail(message) };\n\tconst classified = classifyFailure({ message, provider });\n\tif (classified.retryable) return { cause: \"provider-failure\", detail: boundedDetail(message) };\n\tif (\n\t\tclassified.reason === \"auth\" ||\n\t\tclassified.reason === \"billing_or_quota\" ||\n\t\tmessage.includes(\"api key\") ||\n\t\tmessage.includes(\"not compacted\")\n\t)\n\t\treturn { cause: \"auth-failed\", detail: boundedDetail(message) };\n\treturn { cause: \"unknown-failure\", detail: boundedDetail(message) };\n}\n\nfunction boundedDetail(message: string): string | undefined {\n\tif (!message) return undefined;\n\treturn message.length > 500 ? `${message.slice(0, 500)}…` : message;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loop.js","sourceRoot":"","sources":["../../src/compaction/loop.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D,OAAO,EAAyB,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAA2B,MAAM,mBAAmB,CAAC;AA4CzF,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEnC,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,IAAwB;IAC/D,IAAI,SAAS,GAAG,OAAO,CAAC;IACxB,IAAI,UAA6C,CAAC;IAClD,IAAI,kBAAsC,CAAC;IAC3C,IAAI,aAA2C,CAAC;IAChD,IAAI,YAAgC,CAAC;IACrC,IAAI,uBAA2C,CAAC;IAChD,IAAI,+BAA+B,GAAG,KAAK,CAAC;IAC5C,MAAM,0BAA0B,GAAyB,EAAE,CAAC;IAC5D,IAAI,cAAc,GAAG,IAAI,CAAC,uBAAuB,CAAC,CAAC,CAAC,IAAI,CAAC,uBAAuB,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;IACzG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,cAAc,IAAI,CAAC,EAAE,CAAC;QAC7D,cAAc,GAAG,mBAAmB,CAAC;IACtC,CAAC;IAED,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,UA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yFailure } from \"../reliability/classifier.ts\";\nimport type { SessionEntry } from \"../session/session-manager.ts\";\nimport { type CompactionResult, mergeCompactionVerificationReports } from \"./compaction.ts\";\nimport { CompactionVerificationError, type VerificationReport } from \"./verification.ts\";\n\nexport interface CompactionCycleParams {\n\tmodelTier: \"cheap\" | \"session\";\n\tkeepRecentTokens: number;\n\tchunked: boolean;\n\tdeterministicOnly: boolean;\n}\n\nexport interface ModelAndAuth {\n\tmodel: Model<any>;\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n\tfailure?: string;\n}\n\nexport interface CompactionLoopDeps {\n\tmeasureLiveTokens(): number;\n\tshouldCompact(tokens: number): boolean;\n\tgetPostApplyMargin(): number;\n\tgetBranch(): SessionEntry[];\n\tresolveModelAndAuth(modelTier: CompactionCycleParams[\"modelTier\"]): Promise<ModelAndAuth>;\n\tsummarizeAndVerify(\n\t\tparams: CompactionCycleParams,\n\t\tmodel: Model<any>,\n\t\tapiKey: string | undefined,\n\t\theaders: Record<string, string> | undefined,\n\t\tbranch: SessionEntry[],\n\t): Promise<{ result: CompactionResult }>;\n\tbuildDeterministicCheckpoint(\n\t\tparams: CompactionCycleParams,\n\t): Promise<{ result: CompactionResult }> | { result: CompactionResult };\n\tapply(result: CompactionResult): Promise<void> | void;\n\tonTransition(info: { cycle: number; from: string; cause: string; detail?: string }): void;\n\tgetBaseKeepRecentTokens?(): number;\n\tverifyPostApplyEffect?(): boolean;\n\tsignal?: AbortSignal;\n}\n\nexport type CompactionLoopOutcome =\n\t| { kind: \"success\"; result: CompactionResult; cycles: number }\n\t| { kind: \"skip\"; reason: string }\n\t| { kind: \"failed\"; reason: string; cycles: number };\n\nconst MAX_CYCLES = 4;\nconst MAX_LLM_CYCLES = 3;\nconst DEFAULT_KEEP_RECENT = 20_000;\n\nexport async function runCompactionLoop(deps: CompactionLoopDeps): Promise<CompactionLoopOutcome> {\n\tlet lastCause = \"start\";\n\tlet lastParams: CompactionCycleParams | undefined;\n\tlet lastObservedTokens: number | undefined;\n\tlet appliedResult: CompactionResult | undefined;\n\tlet lastModelKey: string | undefined;\n\tlet ownTrailingCompactionId: string | undefined;\n\tlet ownTrailingCompactionNeedsRetry = false;\n\tconst pendingVerificationReports: VerificationReport[] = [];\n\tlet baseKeepRecent = deps.getBaseKeepRecentTokens ? deps.getBaseKeepRecentTokens() : DEFAULT_KEEP_RECENT;\n\tif (!Number.isFinite(baseKeepRecent) || baseKeepRecent <= 0) {\n\t\tbaseKeepRecent = DEFAULT_KEEP_RECENT;\n\t}\n\n\tfor (let cycle = 1; cycle <= MAX_CYCLES; cycle++) {\n\t\tif (deps.signal?.aborted) {\n\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle - 1 };\n\t\t}\n\n\t\tconst branch = deps.getBranch();\n\t\tconst trailingEntry = branch[branch.length - 1];\n\t\tif (branch.length > 0 && trailingEntry?.type === \"compaction\") {\n\t\t\tif (appliedResult && trailingEntry.id === ownTrailingCompactionId) {\n\t\t\t\tif (!ownTrailingCompactionNeedsRetry) return { kind: \"success\", result: appliedResult, cycles: cycle - 1 };\n\t\t\t} else {\n\t\t\t\treturn { kind: \"skip\", reason: \"already compacted\" };\n\t\t\t}\n\t\t}\n\n\t\tconst observedTokens = deps.measureLiveTokens();\n\t\tif (cycle === 1 && !deps.shouldCompact(observedTokens)) {\n\t\t\treturn {\n\t\t\t\tkind: \"skip\",\n\t\t\t\treason:\n\t\t\t\t\tbranch.length > 0 && branch[branch.length - 1]?.type === \"compaction\"\n\t\t\t\t\t\t? \"already compacted\"\n\t\t\t\t\t\t: \"within threshold\",\n\t\t\t};\n\t\t}\n\n\t\tconst selectedParams = selectCycleParams(cycle, lastCause, lastParams, baseKeepRecent);\n\t\tlet params = enforceMonotonicProgress(selectedParams, lastParams, observedTokens, lastObservedTokens, lastCause);\n\t\tlastObservedTokens = observedTokens;\n\n\t\tif (params.deterministicOnly || cycle > MAX_LLM_CYCLES) {\n\t\t\tif (deps.signal?.aborted) {\n\t\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle - 1 };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst built = await Promise.resolve(deps.buildDeterministicCheckpoint(params));\n\t\t\t\tconst result = mergeCompactionVerificationReports(built.result, pendingVerificationReports);\n\t\t\t\tpendingVerificationReports.length = 0;\n\t\t\t\tawait deps.apply(result);\n\t\t\t\treturn { kind: \"success\", result, cycles: cycle };\n\t\t\t} catch (error) {\n\t\t\t\treturn { kind: \"failed\", reason: mapFailureCause(error).cause, cycles: cycle };\n\t\t\t}\n\t\t}\n\n\t\tlet modelInfo: ModelAndAuth;\n\t\ttry {\n\t\t\tmodelInfo = await deps.resolveModelAndAuth(params.modelTier);\n\t\t} catch {\n\t\t\tlastCause = \"auth-failed\";\n\t\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step0\", cause: lastCause });\n\t\t\tcontinue;\n\t\t}\n\t\tif (modelInfo.failure) {\n\t\t\tlastCause = \"auth-failed\";\n\t\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step0\", cause: lastCause });\n\t\t\tcontinue;\n\t\t}\n\t\tconst currentModelKey = modelKey(modelInfo.model);\n\t\tif (\n\t\t\t(lastCause === \"gate-failed\" || lastCause === \"length-stop\") &&\n\t\t\tlastParams &&\n\t\t\tparams.modelTier !== lastParams.modelTier &&\n\t\t\tlastModelKey === currentModelKey\n\t\t) {\n\t\t\tparams = { ...params, modelTier: lastParams.modelTier };\n\t\t}\n\t\tlastParams = params;\n\t\tlastModelKey = currentModelKey;\n\n\t\tlet result: CompactionResult;\n\t\ttry {\n\t\t\t({ result } = await deps.summarizeAndVerify(\n\t\t\t\tparams,\n\t\t\t\tmodelInfo.model,\n\t\t\t\tmodelInfo.apiKey,\n\t\t\t\tmodelInfo.headers,\n\t\t\t\tbranch,\n\t\t\t));\n\t\t} catch (error) {\n\t\t\tif (deps.signal?.aborted) {\n\t\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle };\n\t\t\t}\n\t\t\tif (error instanceof CompactionVerificationError) {\n\t\t\t\tpendingVerificationReports.push(...error.reports);\n\t\t\t}\n\t\t\tconst failure = mapFailureCause(error, modelInfo.model.provider);\n\t\t\tlastCause = failure.cause;\n\t\t\tif (lastCause === \"aborted\") {\n\t\t\t\treturn { kind: \"failed\", reason: lastCause, cycles: cycle };\n\t\t\t}\n\t\t\tif (lastCause === \"provider-failure\") {\n\t\t\t\treturn { kind: \"failed\", reason: error instanceof Error ? error.message : String(error), cycles: cycle };\n\t\t\t}\n\t\t\tif (lastCause === \"deterministic-required\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst built = await Promise.resolve(deps.buildDeterministicCheckpoint(params));\n\t\t\t\t\tconst deterministicResult = mergeCompactionVerificationReports(built.result, pendingVerificationReports);\n\t\t\t\t\tpendingVerificationReports.length = 0;\n\t\t\t\t\tawait deps.apply(deterministicResult);\n\t\t\t\t\treturn { kind: \"success\", result: deterministicResult, cycles: cycle };\n\t\t\t\t} catch (deterministicError) {\n\t\t\t\t\treturn { kind: \"failed\", reason: mapFailureCause(deterministicError).cause, cycles: cycle };\n\t\t\t\t}\n\t\t\t}\n\t\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step3\", cause: lastCause, detail: failure.detail });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (deps.signal?.aborted) {\n\t\t\treturn { kind: \"failed\", reason: \"aborted\", cycles: cycle };\n\t\t}\n\t\tmergeCompactionVerificationReports(result, pendingVerificationReports);\n\t\tpendingVerificationReports.length = 0;\n\t\tawait deps.apply(result);\n\t\tappliedResult = result;\n\t\tconst branchAfterApply = deps.getBranch();\n\t\tconst trailingAfterApply = branchAfterApply[branchAfterApply.length - 1];\n\t\townTrailingCompactionId = trailingAfterApply?.type === \"compaction\" ? trailingAfterApply.id : undefined;\n\n\t\tif (deps.verifyPostApplyEffect?.() === false) {\n\t\t\townTrailingCompactionNeedsRetry = false;\n\t\t\treturn { kind: \"success\", result, cycles: cycle };\n\t\t}\n\n\t\tconst measuredAfter = deps.measureLiveTokens();\n\t\tif (!deps.shouldCompact(measuredAfter + deps.getPostApplyMargin())) {\n\t\t\townTrailingCompactionNeedsRetry = false;\n\t\t\treturn { kind: \"success\", result, cycles: cycle };\n\t\t}\n\n\t\townTrailingCompactionNeedsRetry = true;\n\t\tlastCause = \"effect-not-restored\";\n\t\tdeps.onTransition({ cycle: cycle + 1, from: \"step5\", cause: lastCause });\n\t}\n\n\treturn { kind: \"failed\", reason: \"exhausted-compaction-cycles\", cycles: MAX_CYCLES };\n}\n\nfunction selectCycleParams(\n\tcycle: number,\n\tcause: string,\n\tlastParams: CompactionCycleParams | undefined,\n\tbaseKeepRecent: number,\n): CompactionCycleParams {\n\tif (cycle >= MAX_CYCLES) {\n\t\treturn {\n\t\t\tmodelTier: lastParams?.modelTier ?? \"session\",\n\t\t\tkeepRecentTokens: Math.max(1, Math.floor((lastParams?.keepRecentTokens ?? baseKeepRecent) / 2)),\n\t\t\tchunked: true,\n\t\t\tdeterministicOnly: true,\n\t\t};\n\t}\n\n\tif (!lastParams) {\n\t\treturn {\n\t\t\tmodelTier: \"cheap\",\n\t\t\tkeepRecentTokens: Math.max(1, baseKeepRecent),\n\t\t\tchunked: false,\n\t\t\tdeterministicOnly: false,\n\t\t};\n\t}\n\n\tconst params: CompactionCycleParams = {\n\t\t...lastParams,\n\t\tdeterministicOnly: false,\n\t};\n\n\tif (cause === \"gate-failed\" || cause === \"auth-failed\" || cause === \"length-stop\") {\n\t\tparams.modelTier = \"session\";\n\t} else if (cause === \"input-overflow\") {\n\t\tparams.chunked = true;\n\t} else if (cause === \"effect-not-restored\") {\n\t\tparams.chunked = true;\n\t\tparams.keepRecentTokens = Math.max(1, Math.floor(lastParams.keepRecentTokens / 2));\n\t\t// The first verified summary already paid the model cost. If applying it did not restore\n\t\t// headroom, repeating the same summarization request can stall a tool loop for minutes while\n\t\t// protected recent/image content remains unchanged. Finish the bounded retry with the\n\t\t// deterministic checkpoint at the stricter cut instead of buying two more equivalent calls.\n\t\tparams.deterministicOnly = true;\n\t}\n\n\treturn params;\n}\n\nfunction enforceMonotonicProgress(\n\tparams: CompactionCycleParams,\n\tlastParams: CompactionCycleParams | undefined,\n\tobservedTokens: number,\n\tlastObservedTokens: number | undefined,\n\tlastCause: string,\n): CompactionCycleParams {\n\tif (\n\t\t!lastParams ||\n\t\tparams.deterministicOnly ||\n\t\t(lastObservedTokens !== undefined && observedTokens < lastObservedTokens)\n\t) {\n\t\treturn params;\n\t}\n\tif (!sameParams(params, lastParams)) {\n\t\treturn params;\n\t}\n\tif (lastCause === \"gate-failed\") {\n\t\treturn params;\n\t}\n\n\tconst keepRecentTokens = Math.max(1, Math.floor(params.keepRecentTokens / 2));\n\tif (keepRecentTokens !== params.keepRecentTokens) {\n\t\treturn { ...params, chunked: true, keepRecentTokens };\n\t}\n\tif (!params.chunked) {\n\t\treturn { ...params, chunked: true };\n\t}\n\treturn { ...params, modelTier: params.modelTier === \"cheap\" ? \"session\" : \"cheap\" };\n}\n\nfunction modelKey(model: Model<any>): string {\n\treturn `${model.provider}:${model.id}:${model.api}:${model.baseUrl ?? \"\"}`;\n}\n\nfunction sameParams(a: CompactionCycleParams, b: CompactionCycleParams): boolean {\n\treturn (\n\t\ta.modelTier === b.modelTier &&\n\t\ta.keepRecentTokens === b.keepRecentTokens &&\n\t\ta.chunked === b.chunked &&\n\t\ta.deterministicOnly === b.deterministicOnly\n\t);\n}\n\nfunction mapFailureCause(error: unknown, provider?: string): { cause: string; detail?: string } {\n\tconst message = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n\tif (message.includes(\"gate-failed\")) return { cause: \"gate-failed\", detail: boundedDetail(message) };\n\tif (message.includes(\"summary-demand-exceeds-reserve\"))\n\t\treturn { cause: \"deterministic-required\", detail: boundedDetail(message) };\n\tif (message.includes(\"input-overflow\")) return { cause: \"input-overflow\", detail: boundedDetail(message) };\n\t// A length-stopped summary lost gated sections; escalating the tier buys a larger output cap.\n\tif (message.includes(\"summary-length-stop\")) return { cause: \"length-stop\", detail: boundedDetail(message) };\n\tif (message.includes(\"auto-compaction-cancelled\")) return { cause: \"aborted\", detail: boundedDetail(message) };\n\tconst classified = classifyFailure({ message, provider });\n\tif (classified.retryable) return { cause: \"provider-failure\", detail: boundedDetail(message) };\n\tif (\n\t\tclassified.reason === \"auth\" ||\n\t\tclassified.reason === \"billing_or_quota\" ||\n\t\tmessage.includes(\"api key\") ||\n\t\tmessage.includes(\"not compacted\")\n\t)\n\t\treturn { cause: \"auth-failed\", detail: boundedDetail(message) };\n\treturn { cause: \"unknown-failure\", detail: boundedDetail(message) };\n}\n\nfunction boundedDetail(message: string): string | undefined {\n\tif (!message) return undefined;\n\treturn message.length > 500 ? `${message.slice(0, 500)}…` : message;\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ToolFailurePhase } from "@caupulican/pi-ai/tool-repair-registry";
|
|
1
2
|
import type { AgentMessage, AgentToolResult } from "./types.ts";
|
|
2
3
|
declare const TOOL_FAILURE_MEMORY_VERSION = 1;
|
|
3
4
|
declare const TOOL_FAILURE_DIRECTIVE_VERSION = 1;
|
|
@@ -9,6 +10,7 @@ export interface ToolFailureMemoryRecord {
|
|
|
9
10
|
operation: string;
|
|
10
11
|
occurrence: number;
|
|
11
12
|
state: ToolFailureState;
|
|
13
|
+
phase: ToolFailurePhase;
|
|
12
14
|
failureCode: string;
|
|
13
15
|
diagnostic?: string;
|
|
14
16
|
correction: string;
|
|
@@ -20,7 +22,10 @@ export interface ToolFailureMemoryDetails {
|
|
|
20
22
|
export interface ToolFailureDirectiveDetails {
|
|
21
23
|
piToolFailureDirective: {
|
|
22
24
|
version: typeof TOOL_FAILURE_DIRECTIVE_VERSION;
|
|
25
|
+
state: ToolFailureState;
|
|
26
|
+
phase: ToolFailurePhase;
|
|
23
27
|
failureCode: string;
|
|
28
|
+
diagnostic?: string;
|
|
24
29
|
nextAction: string;
|
|
25
30
|
};
|
|
26
31
|
}
|
|
@@ -32,16 +37,26 @@ export type ToolFailureMemoryTracker = Map<string, ToolFailureMemoryRecord>;
|
|
|
32
37
|
*/
|
|
33
38
|
export declare function normalizeToolSignature(pairs: Array<[string, unknown]>): string;
|
|
34
39
|
export declare function classifyToolFailure(message: string, errorClass?: string): string;
|
|
35
|
-
export declare function toolFailureCorrection(message: string, state: ToolFailureState): string;
|
|
40
|
+
export declare function toolFailureCorrection(message: string, state: ToolFailureState, phase?: ToolFailurePhase): string;
|
|
36
41
|
export interface ToolFailureAssessment {
|
|
37
42
|
failureCode: string;
|
|
43
|
+
phase: ToolFailurePhase;
|
|
38
44
|
diagnostic?: string;
|
|
39
45
|
guidance: string;
|
|
40
46
|
attemptMemory?: "discard";
|
|
41
47
|
}
|
|
42
48
|
export declare function assessToolFailure(message: string, state: ToolFailureState, errorClass?: string): ToolFailureAssessment;
|
|
49
|
+
export interface ToolFailureTelemetry {
|
|
50
|
+
state: ToolFailureState;
|
|
51
|
+
phase: ToolFailurePhase;
|
|
52
|
+
failureCode: string;
|
|
53
|
+
diagnostic?: string;
|
|
54
|
+
nextAction: string;
|
|
55
|
+
}
|
|
56
|
+
/** Read only bounded failure identity and guidance; operation arguments never cross this telemetry boundary. */
|
|
57
|
+
export declare function readToolFailureTelemetry(details: unknown): ToolFailureTelemetry | undefined;
|
|
43
58
|
export declare function createToolFailureMemoryTracker(messages: AgentMessage[]): ToolFailureMemoryTracker;
|
|
44
|
-
export declare function rememberToolFailure(tracker: ToolFailureMemoryTracker, tool: string, args: unknown, state: ToolFailureState, failureCode: string, correction: string, diagnostic?: string): ToolFailureMemoryRecord;
|
|
59
|
+
export declare function rememberToolFailure(tracker: ToolFailureMemoryTracker, tool: string, args: unknown, state: ToolFailureState, failureCode: string, correction: string, diagnostic?: string, phase?: ToolFailurePhase): ToolFailureMemoryRecord;
|
|
45
60
|
export declare function clearToolFailure(tracker: ToolFailureMemoryTracker, tool: string, args: unknown): void;
|
|
46
61
|
export declare function createToolFailureResult(record: ToolFailureMemoryRecord, terminate?: boolean): AgentToolResult<ToolFailureResultDetails>;
|
|
47
62
|
export declare function sanitizeToolFailureContext(messages: AgentMessage[], systemPrompt: string): {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-failure-memory.d.ts","sourceRoot":"","sources":["../src/tool-failure-memory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"tool-failure-memory.d.ts","sourceRoot":"","sources":["../src/tool-failure-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,gBAAgB,EACrB,MAAM,wCAAwC,CAAC;AAEhD,OAAO,KAAK,EAAE,YAAY,EAAiB,eAAe,EAAE,MAAM,YAAY,CAAC;AAG/E,QAAA,MAAM,2BAA2B,IAAI,CAAC;AACtC,QAAA,MAAM,8BAA8B,IAAI,CAAC;AAazC,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,UAAU,CAAC;AAErD,MAAM,WAAW,uBAAuB;IACvC,OAAO,EAAE,OAAO,2BAA2B,CAAC;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,gBAAgB,CAAC;IACxB,KAAK,EAAE,gBAAgB,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,SAAS,CAAC;CAC1B;AAED,MAAM,WAAW,wBAAwB;IACxC,mBAAmB,EAAE,uBAAuB,CAAC;CAC7C;AAED,MAAM,WAAW,2BAA2B;IAC3C,sBAAsB,EAAE;QACvB,OAAO,EAAE,OAAO,8BAA8B,CAAC;QAC/C,KAAK,EAAE,gBAAgB,CAAC;QACxB,KAAK,EAAE,gBAAgB,CAAC;QACxB,WAAW,EAAE,MAAM,CAAC;QACpB,UAAU,CAAC,EAAE,MAAM,CAAC;QACp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,CAClC,OAAO,EAAE,wBAAwB,EACjC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,OAAO,EACb,KAAK,EAAE,gBAAgB,EACvB,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,EAClB,UAAU,CAAC,EAAE,MAAM,EACnB,KAAK,GAAE,gBAA4D,GACjE,uBAAuB,CAuCzB;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,wBAAwB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAErG;AAQD,wBAAgB,uBAAuB,CACtC,MAAM,EAAE,uBAAuB,EAC/B,SAAS,CAAC,EAAE,OAAO,GACjB,eAAe,CAAC,wBAAwB,CAAC,CAiC3C;AAMD,wBAAgB,0BAA0B,CACzC,QAAQ,EAAE,YAAY,EAAE,EACxB,YAAY,EAAE,MAAM,GAClB;IAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CA6CpD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getToolExecutionAttemptMemory, getToolExecutionErrorPolicy } from "@caupulican/pi-ai/tool-repair-registry";
|
|
1
|
+
import { getToolExecutionAttemptMemory, getToolExecutionErrorPolicy, } from "@caupulican/pi-ai/tool-repair-registry";
|
|
2
2
|
import { sanitizeBinaryOutput } from "./utils/shell-output.js";
|
|
3
3
|
const TOOL_FAILURE_MEMORY_VERSION = 1;
|
|
4
4
|
const TOOL_FAILURE_DIRECTIVE_VERSION = 1;
|
|
@@ -253,16 +253,59 @@ export function classifyToolFailure(message, errorClass) {
|
|
|
253
253
|
return boundedFailureCode(`exit_${exitCode}`);
|
|
254
254
|
return boundedFailureCode(errorClass ?? "tool_error");
|
|
255
255
|
}
|
|
256
|
-
function
|
|
256
|
+
function isToolFailurePhase(value) {
|
|
257
|
+
return (value === "validation" ||
|
|
258
|
+
value === "policy" ||
|
|
259
|
+
value === "preflight" ||
|
|
260
|
+
value === "execution" ||
|
|
261
|
+
value === "timeout" ||
|
|
262
|
+
value === "cancelled" ||
|
|
263
|
+
value === "provisioning");
|
|
264
|
+
}
|
|
265
|
+
function inferToolFailurePhase(state, failureCode) {
|
|
266
|
+
if (failureCode === "malformed_call" || failureCode === "unknown_tool" || failureCode === "invalid_arguments") {
|
|
267
|
+
return "validation";
|
|
268
|
+
}
|
|
269
|
+
if (failureCode === "blocked" || failureCode === "permission_denied")
|
|
270
|
+
return "policy";
|
|
271
|
+
if (failureCode === "preflight_error")
|
|
272
|
+
return "preflight";
|
|
273
|
+
if (failureCode === "aborted" || failureCode === "cancelled")
|
|
274
|
+
return "cancelled";
|
|
275
|
+
if (failureCode === "timeout" || failureCode === "etimedout")
|
|
276
|
+
return "timeout";
|
|
277
|
+
if (failureCode === "provisioning_failed" || failureCode === "command_not_found")
|
|
278
|
+
return "provisioning";
|
|
279
|
+
return state === "rejected" ? "validation" : "execution";
|
|
280
|
+
}
|
|
281
|
+
function fallbackFailureGuidance(state, hasDiagnostic, phase) {
|
|
282
|
+
if (phase === "preflight") {
|
|
283
|
+
return hasDiagnostic
|
|
284
|
+
? "Tool arguments were valid, but preflight failed before execution; resolve the diagnostic or host condition before retrying."
|
|
285
|
+
: "Tool arguments were valid, but preflight failed before execution; inspect host policy and capability state before retrying.";
|
|
286
|
+
}
|
|
287
|
+
if (phase === "policy")
|
|
288
|
+
return "Resolve the authority or policy restriction, or choose an allowed approach before retrying.";
|
|
289
|
+
if (phase === "cancelled")
|
|
290
|
+
return "Retry only if the operation is still required and the cancellation condition has cleared.";
|
|
291
|
+
if (phase === "timeout")
|
|
292
|
+
return "Narrow or split the work, then retry once only when repeating it is safe.";
|
|
293
|
+
if (phase === "provisioning") {
|
|
294
|
+
return hasDiagnostic
|
|
295
|
+
? "Repair the provisioning diagnostic and retry only after the environment changes."
|
|
296
|
+
: "Inspect tool availability and request bounded provisioning diagnostics before retrying.";
|
|
297
|
+
}
|
|
257
298
|
return state === "rejected"
|
|
258
299
|
? "Re-read the current tool schema and change the invalid operation before retrying."
|
|
259
300
|
: hasDiagnostic
|
|
260
301
|
? "No safe repair inferred; use the diagnostic and tool contract for the next action."
|
|
261
302
|
: "No safe repair inferred because the tool returned no diagnostic; inspect its contract or request bounded diagnostics before retrying.";
|
|
262
303
|
}
|
|
263
|
-
export function toolFailureCorrection(message, state) {
|
|
304
|
+
export function toolFailureCorrection(message, state, phase = state === "rejected" ? "validation" : "execution") {
|
|
264
305
|
const policy = getToolExecutionErrorPolicy(message);
|
|
265
|
-
return policy
|
|
306
|
+
return policy
|
|
307
|
+
? truncate(policy.guidance, MAX_CORRECTION_CHARS)
|
|
308
|
+
: fallbackFailureGuidance(state, message.trim().length > 0, phase);
|
|
266
309
|
}
|
|
267
310
|
function extractFailureDiagnostic(message, allowUnclassifiedFallback) {
|
|
268
311
|
const lines = sanitizeBinaryOutput(message)
|
|
@@ -283,13 +326,17 @@ function extractFailureDiagnostic(message, allowUnclassifiedFallback) {
|
|
|
283
326
|
}
|
|
284
327
|
export function assessToolFailure(message, state, errorClass) {
|
|
285
328
|
const policy = getToolExecutionErrorPolicy(message);
|
|
286
|
-
const diagnostic = state === "failed" && !policy
|
|
329
|
+
const diagnostic = state === "failed" && (!policy || policy.retainDiagnostic)
|
|
330
|
+
? extractFailureDiagnostic(message, errorClass !== undefined || policy?.retainDiagnostic === true)
|
|
331
|
+
: undefined;
|
|
332
|
+
const failureCode = policy?.failureCode ?? classifyToolFailure(message, errorClass);
|
|
287
333
|
return {
|
|
288
|
-
failureCode
|
|
334
|
+
failureCode,
|
|
335
|
+
phase: policy?.phase ?? inferToolFailurePhase(state, failureCode),
|
|
289
336
|
...(diagnostic ? { diagnostic } : {}),
|
|
290
337
|
guidance: policy
|
|
291
338
|
? truncate(policy.guidance, MAX_CORRECTION_CHARS)
|
|
292
|
-
: fallbackFailureGuidance(state, diagnostic !== undefined),
|
|
339
|
+
: fallbackFailureGuidance(state, diagnostic !== undefined, inferToolFailurePhase(state, failureCode)),
|
|
293
340
|
...(policy?.attemptMemory === "discard" ? { attemptMemory: "discard" } : {}),
|
|
294
341
|
};
|
|
295
342
|
}
|
|
@@ -314,8 +361,11 @@ function readFailureRecord(details) {
|
|
|
314
361
|
const diagnostic = typeof candidate.diagnostic === "string" ? truncate(candidate.diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined;
|
|
315
362
|
const retainedCorrection = typeof candidate.correction === "string" ? truncate(candidate.correction, MAX_CORRECTION_CHARS) : undefined;
|
|
316
363
|
const correction = candidate.state === "failed" && retainedCorrection === LEGACY_GENERIC_EXECUTION_CORRECTION
|
|
317
|
-
? fallbackFailureGuidance("failed", diagnostic !== undefined)
|
|
364
|
+
? fallbackFailureGuidance("failed", diagnostic !== undefined, "execution")
|
|
318
365
|
: (retainedCorrection ?? toolFailureCorrection("", candidate.state));
|
|
366
|
+
const phase = isToolFailurePhase(candidate.phase)
|
|
367
|
+
? candidate.phase
|
|
368
|
+
: inferToolFailurePhase(candidate.state, candidate.failureCode);
|
|
319
369
|
return {
|
|
320
370
|
version: TOOL_FAILURE_MEMORY_VERSION,
|
|
321
371
|
failureKey: truncate(candidate.failureKey, MAX_TOOL_NAME_CHARS + 1 + TOOL_SIGNATURE_HEX_CHARS),
|
|
@@ -323,6 +373,7 @@ function readFailureRecord(details) {
|
|
|
323
373
|
operation: truncateMiddle(candidate.operation, MAX_OPERATION_CHARS),
|
|
324
374
|
occurrence: candidate.occurrence,
|
|
325
375
|
state: candidate.state,
|
|
376
|
+
phase,
|
|
326
377
|
failureCode: boundedFailureCode(candidate.failureCode),
|
|
327
378
|
diagnostic,
|
|
328
379
|
correction,
|
|
@@ -339,10 +390,38 @@ function readFailureDirective(details) {
|
|
|
339
390
|
}
|
|
340
391
|
return {
|
|
341
392
|
version: TOOL_FAILURE_DIRECTIVE_VERSION,
|
|
393
|
+
state: candidate.state === "rejected" ? "rejected" : "failed",
|
|
394
|
+
phase: isToolFailurePhase(candidate.phase)
|
|
395
|
+
? candidate.phase
|
|
396
|
+
: inferToolFailurePhase("failed", candidate.failureCode),
|
|
342
397
|
failureCode: boundedFailureCode(candidate.failureCode),
|
|
398
|
+
diagnostic: typeof candidate.diagnostic === "string" ? truncate(candidate.diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,
|
|
343
399
|
nextAction: truncate(candidate.nextAction, MAX_CORRECTION_CHARS),
|
|
344
400
|
};
|
|
345
401
|
}
|
|
402
|
+
/** Read only bounded failure identity and guidance; operation arguments never cross this telemetry boundary. */
|
|
403
|
+
export function readToolFailureTelemetry(details) {
|
|
404
|
+
const record = readFailureRecord(details);
|
|
405
|
+
if (record) {
|
|
406
|
+
return {
|
|
407
|
+
state: record.state,
|
|
408
|
+
phase: record.phase,
|
|
409
|
+
failureCode: record.failureCode,
|
|
410
|
+
...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),
|
|
411
|
+
nextAction: record.correction,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
const directive = readFailureDirective(details);
|
|
415
|
+
if (!directive)
|
|
416
|
+
return undefined;
|
|
417
|
+
return {
|
|
418
|
+
state: directive.state,
|
|
419
|
+
phase: directive.phase,
|
|
420
|
+
failureCode: directive.failureCode,
|
|
421
|
+
...(directive.diagnostic ? { diagnostic: directive.diagnostic } : {}),
|
|
422
|
+
nextAction: directive.nextAction,
|
|
423
|
+
};
|
|
424
|
+
}
|
|
346
425
|
function firstText(message) {
|
|
347
426
|
for (const block of message.content) {
|
|
348
427
|
if (block.type === "text")
|
|
@@ -407,9 +486,12 @@ function analyzeToolFailureContext(messages) {
|
|
|
407
486
|
operation,
|
|
408
487
|
occurrence,
|
|
409
488
|
state,
|
|
489
|
+
phase: retained?.phase ?? assessment?.phase ?? inferToolFailurePhase(state, "tool_error"),
|
|
410
490
|
failureCode: retained?.failureCode ?? assessment?.failureCode ?? "tool_error",
|
|
411
491
|
diagnostic: retained?.diagnostic ?? assessment?.diagnostic,
|
|
412
|
-
correction: retained?.correction ??
|
|
492
|
+
correction: retained?.correction ??
|
|
493
|
+
assessment?.guidance ??
|
|
494
|
+
fallbackFailureGuidance(state, false, inferToolFailurePhase(state, "tool_error")),
|
|
413
495
|
};
|
|
414
496
|
active.delete(failureKey);
|
|
415
497
|
active.set(failureKey, { record, sequence: sequence++ });
|
|
@@ -455,7 +537,7 @@ function analyzeToolFailureContext(messages) {
|
|
|
455
537
|
export function createToolFailureMemoryTracker(messages) {
|
|
456
538
|
return new Map(analyzeToolFailureContext(messages).activeRecords.map((record) => [record.failureKey, record]));
|
|
457
539
|
}
|
|
458
|
-
export function rememberToolFailure(tracker, tool, args, state, failureCode, correction, diagnostic) {
|
|
540
|
+
export function rememberToolFailure(tracker, tool, args, state, failureCode, correction, diagnostic, phase = inferToolFailurePhase(state, failureCode)) {
|
|
459
541
|
if (getToolExecutionAttemptMemory(failureCode) === "discard") {
|
|
460
542
|
for (const [failureKey, previous] of tracker) {
|
|
461
543
|
if (previous.tool === tool && previous.failureCode === failureCode)
|
|
@@ -468,6 +550,7 @@ export function rememberToolFailure(tracker, tool, args, state, failureCode, cor
|
|
|
468
550
|
operation: "[discarded]",
|
|
469
551
|
occurrence: 1,
|
|
470
552
|
state,
|
|
553
|
+
phase,
|
|
471
554
|
failureCode: boundedFailureCode(failureCode),
|
|
472
555
|
diagnostic: diagnostic ? truncate(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,
|
|
473
556
|
correction: truncate(correction, MAX_CORRECTION_CHARS),
|
|
@@ -481,6 +564,7 @@ export function rememberToolFailure(tracker, tool, args, state, failureCode, cor
|
|
|
481
564
|
...identity,
|
|
482
565
|
occurrence: (previous?.occurrence ?? 0) + 1,
|
|
483
566
|
state,
|
|
567
|
+
phase,
|
|
484
568
|
failureCode: boundedFailureCode(failureCode),
|
|
485
569
|
diagnostic: diagnostic ? truncate(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,
|
|
486
570
|
correction: truncate(correction, MAX_CORRECTION_CHARS),
|
|
@@ -513,6 +597,7 @@ export function createToolFailureResult(record, terminate) {
|
|
|
513
597
|
failure_key: record.failureKey,
|
|
514
598
|
occ: record.occurrence,
|
|
515
599
|
state: record.state,
|
|
600
|
+
phase: record.phase,
|
|
516
601
|
tool: record.tool,
|
|
517
602
|
failure_code: record.failureCode,
|
|
518
603
|
...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),
|
|
@@ -525,7 +610,10 @@ export function createToolFailureResult(record, terminate) {
|
|
|
525
610
|
? {
|
|
526
611
|
piToolFailureDirective: {
|
|
527
612
|
version: TOOL_FAILURE_DIRECTIVE_VERSION,
|
|
613
|
+
state: record.state,
|
|
614
|
+
phase: record.phase,
|
|
528
615
|
failureCode: record.failureCode,
|
|
616
|
+
...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),
|
|
529
617
|
nextAction: record.correction,
|
|
530
618
|
},
|
|
531
619
|
}
|
|
@@ -547,6 +635,7 @@ export function sanitizeToolFailureContext(messages, systemPrompt) {
|
|
|
547
635
|
failure_key: record.failureKey,
|
|
548
636
|
occ: record.occurrence,
|
|
549
637
|
state: record.state,
|
|
638
|
+
phase: record.phase,
|
|
550
639
|
tool: record.tool,
|
|
551
640
|
operation: record.operation,
|
|
552
641
|
failure_code: record.failureCode,
|
|
@@ -556,6 +645,7 @@ export function sanitizeToolFailureContext(messages, systemPrompt) {
|
|
|
556
645
|
for (const directive of analysis.activeDirectives) {
|
|
557
646
|
lines.push(escapePromptData(JSON.stringify({
|
|
558
647
|
failure_code: directive.failureCode,
|
|
648
|
+
...(directive.diagnostic ? { diagnostic: directive.diagnostic } : {}),
|
|
559
649
|
next_action: directive.nextAction,
|
|
560
650
|
attempt_memory: "discarded",
|
|
561
651
|
})));
|