@caupulican/pi-agent-core 0.96.3 → 0.96.5
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 +2 -0
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +37 -2
- package/dist/agent-loop.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/dist/agent-loop.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
|
|
|
11
11
|
export interface AgentLoopContinuationState {
|
|
12
12
|
providerTurns: number;
|
|
13
13
|
stallWindow: string[];
|
|
14
|
+
/** Optional for compatibility with continuation snapshots created before result-aware cycle detection. */
|
|
15
|
+
stagnantResultWindow?: string[];
|
|
14
16
|
toolFailureRecoveryGate: ToolFailureRecoveryGate;
|
|
15
17
|
}
|
|
16
18
|
export declare function createAgentLoopContinuationState(): AgentLoopContinuationState;
|
package/dist/agent-loop.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAoC7D,OAAO,EAAE,uBAAuB,EAAsC,MAAM,iCAAiC,CAAC;AAE9G,OAAO,KAAK,EACX,YAAY,EACZ,UAAU,EACV,eAAe,EACf,YAAY,EAGZ,aAAa,EAGb,QAAQ,EACR,kBAAkB,EAElB,MAAM,YAAY,CAAC;AAIpB,OAAO,EACN,0BAA0B,EAC1B,sBAAsB,EACt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EAAE,QAAQ,EACnB,iBAAiB,GAAE,0BAA+D,GAChF,OAAO,CAAC,YAAY,EAAE,CAAC,CAezB;AAsaD;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAExC;AA6lCD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,aAAa,GAAG,kBAAkB,GAAG,SAAS,CAO7F"}
|
package/dist/agent-loop.js
CHANGED
|
@@ -7,7 +7,7 @@ import { formatToolRepairStandingRule, REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE, }
|
|
|
7
7
|
import { ToolArgumentValidationError, validateToolArguments, } from "@caupulican/pi-ai/validation";
|
|
8
8
|
import { assistantMessageText, collapseDegenerateAssistantMessage, shouldAbortDegenerateStream, } from "./degenerate-assistant-text.js";
|
|
9
9
|
import { startPlannedAgentProviderRequest, startPlannedAgentProviderRequestWithId, } from "./provider-request-planner.js";
|
|
10
|
-
import { assessToolFailure, clearToolFailure, createRepeatedToolFailureResult, createToolFailureMemoryTracker, createToolFailureResult, describeOperationOutcome, getUnresolvedToolFailure, normalizeToolSignature, rememberToolFailure, toolFailureCorrection, } from "./tool-failure-memory.js";
|
|
10
|
+
import { assessToolFailure, clearToolFailure, createRepeatedToolFailureResult, createToolFailureMemoryTracker, createToolFailureResult, describeOperationOutcome, getToolExecutionKey, getUnresolvedToolFailure, normalizeToolSignature, rememberToolFailure, toolFailureCorrection, } from "./tool-failure-memory.js";
|
|
11
11
|
import { ToolFailureRecoveryGate } from "./tool-failure-recovery-gate.js";
|
|
12
12
|
import { rejectNativeToolProtocolResidue, rejectToolCallsFromToolFreeResponse } from "./tool-protocol-residue.js";
|
|
13
13
|
import { AgentToolExecutionError, DEFAULT_MAX_PROVIDER_TURNS, DEFAULT_MAX_STALL_TURNS } from "./types.js";
|
|
@@ -16,7 +16,12 @@ export { composeRequestSystemPrompt, narrowRequestMaxTokens, resolveRequestPrefl
|
|
|
16
16
|
/** Bound simultaneous tool starts without imposing a failure-count or operation-count stop. */
|
|
17
17
|
const TOOL_EXECUTION_WAVE_SIZE = 4;
|
|
18
18
|
export function createAgentLoopContinuationState() {
|
|
19
|
-
return {
|
|
19
|
+
return {
|
|
20
|
+
providerTurns: 0,
|
|
21
|
+
stallWindow: [],
|
|
22
|
+
stagnantResultWindow: [],
|
|
23
|
+
toolFailureRecoveryGate: new ToolFailureRecoveryGate(),
|
|
24
|
+
};
|
|
20
25
|
}
|
|
21
26
|
/**
|
|
22
27
|
* Start an agent loop with a new prompt message.
|
|
@@ -130,6 +135,8 @@ async function emitProviderTurnLimitStop(config, continuationState, newMessages,
|
|
|
130
135
|
* operations therefore never look like a loop merely because one signature is frequent.
|
|
131
136
|
*/
|
|
132
137
|
const STALL_WINDOW_PERIODS = 4;
|
|
138
|
+
/** Identical observable results make a repeated cycle conclusive well before the coarse call-only fuse. */
|
|
139
|
+
const STAGNANT_RESULT_REPEAT_LIMIT = 3;
|
|
133
140
|
function repeatsToolCallPattern(stallWindow, stallLimit) {
|
|
134
141
|
if (stallLimit <= 0)
|
|
135
142
|
return false;
|
|
@@ -162,6 +169,14 @@ function textProtocolOperationArguments(toolCall) {
|
|
|
162
169
|
function textProtocolBatchSignature(toolCalls) {
|
|
163
170
|
return normalizeToolSignature(toolCalls.map((toolCall) => [toolCall.name, textProtocolOperationArguments(toolCall)]));
|
|
164
171
|
}
|
|
172
|
+
/** Hash only provider-visible result state; per-execution IDs/timestamps cannot hide a stagnant cycle. */
|
|
173
|
+
function toolResultBatchSignature(toolResults) {
|
|
174
|
+
return getToolExecutionKey("tool_result_batch", toolResults.map((result) => ({
|
|
175
|
+
toolName: result.toolName,
|
|
176
|
+
content: result.content,
|
|
177
|
+
isError: result.isError,
|
|
178
|
+
})));
|
|
179
|
+
}
|
|
165
180
|
function toolCallRecord(toolCall) {
|
|
166
181
|
const args = toolCall.arguments;
|
|
167
182
|
return args && typeof args === "object" && !Array.isArray(args) ? args : undefined;
|
|
@@ -213,6 +228,11 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
|
|
|
213
228
|
const stallLimit = config.maxStallTurns ?? DEFAULT_MAX_STALL_TURNS;
|
|
214
229
|
const providerTurnLimit = config.maxProviderTurns ?? DEFAULT_MAX_PROVIDER_TURNS;
|
|
215
230
|
const stallWindow = continuationState.stallWindow;
|
|
231
|
+
let stagnantResultWindow = continuationState.stagnantResultWindow;
|
|
232
|
+
if (stagnantResultWindow === undefined) {
|
|
233
|
+
stagnantResultWindow = [];
|
|
234
|
+
continuationState.stagnantResultWindow = stagnantResultWindow;
|
|
235
|
+
}
|
|
216
236
|
const validationFailureTracker = { repeats: 0 };
|
|
217
237
|
const repairTeachTracker = new Map();
|
|
218
238
|
let toolFailureMemory = createToolFailureMemoryTracker(currentContext.messages);
|
|
@@ -307,6 +327,21 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
|
|
|
307
327
|
// checks recurred among distinct edits, reads, and verification operations.
|
|
308
328
|
if (stallLimit > 0 && toolCalls.length > 0) {
|
|
309
329
|
const signature = normalizeToolSignature(toolCalls.map((c) => [c.name, c.arguments ?? null]));
|
|
330
|
+
const stagnantSignature = `${signature}:${toolResultBatchSignature(toolResults)}`;
|
|
331
|
+
stagnantResultWindow.push(stagnantSignature);
|
|
332
|
+
if (stagnantResultWindow.length > STAGNANT_RESULT_REPEAT_LIMIT * STALL_WINDOW_PERIODS) {
|
|
333
|
+
stagnantResultWindow.shift();
|
|
334
|
+
}
|
|
335
|
+
if (repeatsToolCallPattern(stagnantResultWindow, STAGNANT_RESULT_REPEAT_LIMIT)) {
|
|
336
|
+
config.onRunawayStop?.({
|
|
337
|
+
reason: "stagnant_tool_cycle",
|
|
338
|
+
signature,
|
|
339
|
+
repeats: STAGNANT_RESULT_REPEAT_LIMIT,
|
|
340
|
+
});
|
|
341
|
+
await streamToollessClosingTurn(currentContext, newMessages, config, continuationState, providerTurnLimit, signal, emit, streamFn);
|
|
342
|
+
await emit({ type: "agent_end", messages: newMessages });
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
310
345
|
stallWindow.push(signature);
|
|
311
346
|
if (stallWindow.length > stallLimit * STALL_WINDOW_PERIODS)
|
|
312
347
|
stallWindow.shift();
|
package/dist/agent-loop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EACN,4BAA4B,EAC5B,qCAAqC,GAErC,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAEN,2BAA2B,EAE3B,qBAAqB,GACrB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,oBAAoB,EACpB,kCAAkC,EAClC,2BAA2B,GAC3B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACN,gCAAgC,EAChC,sCAAsC,GACtC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,iBAAiB,EACjB,gBAAgB,EAChB,+BAA+B,EAC/B,8BAA8B,EAC9B,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,EACtB,mBAAmB,EAEnB,qBAAqB,GACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,uBAAuB,EAAsC,MAAM,iCAAiC,CAAC;AAC9G,OAAO,EAAE,+BAA+B,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AAelH,OAAO,EAAE,uBAAuB,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,EACN,0BAA0B,EAC1B,sBA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,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,IAAI;QACjC,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,OAAO;QACjC,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,OAAO;QACjC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK;QAC7B,OAAO,EAAE,SAAS,CAAC,OAAO;QAC1B,+FAA+F;QAC/F,kCAAkC;QAClC,GAAG,CAAC,SAAS,CAAC,OAAO,IAAI,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrG,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;AACH,CAAC;AAED,KAAK,UAAU,qBAAqB,CAAC,iBAAoC,EAAE,IAAoB;IAC9F,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;AACjE,CAAC","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport { EventStream } from \"@caupulican/pi-ai/event-stream\";\nimport {\n\tformatToolRepairStandingRule,\n\tREPEATED_SUCCESSFUL_TOOL_CALL_FAILURE,\n\ttype ToolFailurePhase,\n} from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type { AssistantMessage, ToolResultMessage } from \"@caupulican/pi-ai/types\";\nimport {\n\ttype ToolArgumentExecutionOutcome,\n\tToolArgumentValidationError,\n\ttype ToolArgumentValidationTelemetryEvent,\n\tvalidateToolArguments,\n} from \"@caupulican/pi-ai/validation\";\nimport {\n\tassistantMessageText,\n\tcollapseDegenerateAssistantMessage,\n\tshouldAbortDegenerateStream,\n} from \"./degenerate-assistant-text.ts\";\nimport {\n\tstartPlannedAgentProviderRequest,\n\tstartPlannedAgentProviderRequestWithId,\n} from \"./provider-request-planner.ts\";\nimport {\n\tassessToolFailure,\n\tclearToolFailure,\n\tcreateRepeatedToolFailureResult,\n\tcreateToolFailureMemoryTracker,\n\tcreateToolFailureResult,\n\tdescribeOperationOutcome,\n\tgetUnresolvedToolFailure,\n\tnormalizeToolSignature,\n\trememberToolFailure,\n\ttype ToolFailureMemoryTracker,\n\ttoolFailureCorrection,\n} from \"./tool-failure-memory.ts\";\nimport { ToolFailureRecoveryGate, type ToolFailureRecoveryGateEffect } from \"./tool-failure-recovery-gate.ts\";\nimport { rejectNativeToolProtocolResidue, rejectToolCallsFromToolFreeResponse } from \"./tool-protocol-residue.ts\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentRequestId,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolErrorKind,\n\tAgentToolResult,\n\tStreamFn,\n\tToolCallRepairInfo,\n\tToolCallStartContext,\n} from \"./types.ts\";\nimport { AgentToolExecutionError, DEFAULT_MAX_PROVIDER_TURNS, DEFAULT_MAX_STALL_TURNS } from \"./types.ts\";\nimport { createEmptyUsage } from \"./usage.ts\";\n\nexport {\n\tcomposeRequestSystemPrompt,\n\tnarrowRequestMaxTokens,\n\tresolveRequestPreflightMaxTokens,\n} from \"./provider-request-planner.ts\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\n/** Bound simultaneous tool starts without imposing a failure-count or operation-count stop. */\nconst TOOL_EXECUTION_WAVE_SIZE = 4;\n\n/** Bounded no-progress state retained across host-owned continuations of one logical prompt. */\nexport interface AgentLoopContinuationState {\n\tproviderTurns: number;\n\tstallWindow: string[];\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate;\n}\n\nexport function createAgentLoopContinuationState(): AgentLoopContinuationState {\n\treturn { providerTurns: 0, stallWindow: [], toolFailureRecoveryGate: new ToolFailureRecoveryGate() };\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\treturn streamAgentLoop(config, signal, (emit) => runAgentLoop(prompts, context, config, emit, signal, streamFn));\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tassertContinuableContext(context);\n\n\treturn streamAgentLoop(config, signal, (emit) => runAgentLoopContinue(context, config, emit, signal, streamFn));\n}\n\nfunction streamAgentLoop(\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\trun: (emit: AgentEventSink) => Promise<AgentMessage[]>,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\tvoid run(async (event) => {\n\t\tstream.push(event);\n\t})\n\t\t.catch(async (error) => {\n\t\t\tconst messages = [createLoopFailureMessage(error, config, signal?.aborted ?? false)];\n\t\t\tstream.push({ type: \"agent_end\", messages });\n\t\t\treturn messages;\n\t\t})\n\t\t.then((messages) => {\n\t\t\tstream.end(messages);\n\t\t});\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n\tcontinuationState: AgentLoopContinuationState = createAgentLoopContinuationState(),\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({ type: \"agent_start\" });\n\tif (providerTurnLimitReached(config, continuationState)) {\n\t\tfor (const prompt of prompts) {\n\t\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\t\tawait emit({ type: \"message_end\", message: prompt });\n\t\t}\n\t\tawait emitProviderTurnLimitStop(config, continuationState, newMessages, emit);\n\t\treturn newMessages;\n\t}\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn, continuationState);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n\tcontinuationState: AgentLoopContinuationState = createAgentLoopContinuationState(),\n): Promise<AgentMessage[]> {\n\tassertContinuableContext(context);\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context, messages: [...context.messages] };\n\n\tawait emit({ type: \"agent_start\" });\n\tif (providerTurnLimitReached(config, continuationState)) {\n\t\tawait emitProviderTurnLimitStop(config, continuationState, newMessages, emit);\n\t\treturn newMessages;\n\t}\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn, continuationState);\n\treturn newMessages;\n}\n\nfunction assertContinuableContext(context: AgentContext): void {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n}\n\nfunction createLoopFailureMessage(error: unknown, config: AgentLoopConfig, aborted: boolean): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: createEmptyUsage(),\n\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\nfunction providerTurnLimitReached(config: AgentLoopConfig, continuationState: AgentLoopContinuationState): boolean {\n\tconst limit = config.maxProviderTurns ?? DEFAULT_MAX_PROVIDER_TURNS;\n\treturn limit > 0 && continuationState.providerTurns >= limit;\n}\n\nasync function emitProviderTurnLimitStop(\n\tconfig: AgentLoopConfig,\n\tcontinuationState: AgentLoopContinuationState,\n\tnewMessages: AgentMessage[],\n\temit: AgentEventSink,\n): Promise<void> {\n\tconfig.onRunawayStop?.({\n\t\treason: \"provider_turn_limit\",\n\t\tsignature: \"provider_turn_limit\",\n\t\trepeats: continuationState.providerTurns,\n\t});\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/**\n * Maximum exact cycle width inspected by the runaway-loop backstop. Detection requires the complete\n * suffix pattern to repeat `stallLimit` times; recurring housekeeping calls among distinct productive\n * operations therefore never look like a loop merely because one signature is frequent.\n */\nconst STALL_WINDOW_PERIODS = 4;\n\nfunction repeatsToolCallPattern(stallWindow: readonly string[], stallLimit: number): boolean {\n\tif (stallLimit <= 0) return false;\n\tconst maxPeriod = Math.min(STALL_WINDOW_PERIODS, Math.floor(stallWindow.length / stallLimit));\n\tfor (let period = 1; period <= maxPeriod; period++) {\n\t\tconst requiredTurns = period * stallLimit;\n\t\tconst start = stallWindow.length - requiredTurns;\n\t\tlet matches = true;\n\t\tfor (let offset = period; offset < requiredTurns; offset++) {\n\t\t\tif (stallWindow[start + offset] !== stallWindow[start + (offset % period)]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (matches) return true;\n\t}\n\treturn false;\n}\n\nfunction textProtocolOperationArguments(toolCall: AgentToolCall): unknown {\n\tconst args: unknown = toolCall.arguments;\n\tif (!args || typeof args !== \"object\" || Array.isArray(args)) return args ?? null;\n\tconst record = args as Record<string, unknown>;\n\tif ((toolCall.name === \"write\" || toolCall.name === \"edit\") && typeof record.path === \"string\") {\n\t\treturn { path: record.path };\n\t}\n\treturn args;\n}\n\nfunction textProtocolBatchSignature(toolCalls: readonly AgentToolCall[]): string {\n\treturn normalizeToolSignature(\n\t\ttoolCalls.map((toolCall) => [toolCall.name, textProtocolOperationArguments(toolCall)]),\n\t);\n}\n\nfunction toolCallRecord(toolCall: AgentToolCall): Record<string, unknown> | undefined {\n\tconst args: unknown = toolCall.arguments;\n\treturn args && typeof args === \"object\" && !Array.isArray(args) ? (args as Record<string, unknown>) : undefined;\n}\n\nfunction toolResultPhase(result: ToolResultMessage): string | undefined {\n\tif (!result.details || typeof result.details !== \"object\" || Array.isArray(result.details)) return undefined;\n\tconst phase = (result.details as Record<string, unknown>).phase;\n\treturn typeof phase === \"string\" ? phase : undefined;\n}\n\nfunction repeatsSuccessfulTextProtocolBatch(\n\tincomingSignature: string,\n\ttoolCalls: readonly AgentToolCall[],\n\tprevious: SuccessfulTextProtocolBatch | undefined,\n): boolean {\n\tif (!previous) return false;\n\tif (incomingSignature === previous.signature) return true;\n\tif (toolCalls.length !== previous.calls.length || toolCalls.length !== previous.messages.length) return false;\n\treturn toolCalls.every((toolCall, index) => {\n\t\tconst previousCall = previous.calls[index];\n\t\tconst previousResult = previous.messages[index];\n\t\tif (!previousCall || !previousResult) return false;\n\t\tconst currentArgs = toolCallRecord(toolCall);\n\t\tconst previousArgs = toolCallRecord(previousCall);\n\t\tif (currentArgs?.path !== previousArgs?.path) return false;\n\t\tconst phase = toolResultPhase(previousResult);\n\t\tif (phase === \"written\") return toolCall.name === \"write\" && previousCall.name === \"write\";\n\t\treturn phase === \"edited\" && toolCall.name === \"edit\" && previousCall.name === \"edit\";\n\t});\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tinitialContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tinitialConfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tcontinuationState: AgentLoopContinuationState = createAgentLoopContinuationState(),\n): Promise<void> {\n\tlet currentContext = initialContext;\n\tlet config = initialConfig;\n\tlet firstTurn = true;\n\t// Runaway-loop backstop state: a sliding window of recent NORMALIZED tool-call signatures. A model\n\t// wedged repeating the same action makes no progress but keeps spending tokens; if one signature\n\t// recurs `stallLimit` times within the window we stop gracefully. Signatures are normalized so\n\t// volatile args (timestamps/UUIDs/nonces that change every call) can't disguise an otherwise-\n\t// identical call (bug #28). The window spans `stallLimit * STALL_WINDOW_PERIODS` turns so periodic\n\t// oscillation is caught too, not just back-to-back repeats: a cycle of period P repeats each\n\t// signature ~window/P times, so any P up to STALL_WINDOW_PERIODS reaches the threshold before the\n\t// window slides past it. Counts only turns that issued tool calls, so varied/long work never trips\n\t// it. `0` disables.\n\tconst stallLimit = config.maxStallTurns ?? DEFAULT_MAX_STALL_TURNS;\n\tconst providerTurnLimit = config.maxProviderTurns ?? DEFAULT_MAX_PROVIDER_TURNS;\n\tconst stallWindow = continuationState.stallWindow;\n\tconst validationFailureTracker: ToolValidationFailureTracker = { repeats: 0 };\n\tconst repairTeachTracker: ToolRepairTeachTracker = new Map();\n\tlet toolFailureMemory = createToolFailureMemoryTracker(currentContext.messages);\n\tconst toolFailureRecoveryGate = continuationState.toolFailureRecoveryGate;\n\ttoolFailureRecoveryGate.restoreFromMessages(currentContext.messages);\n\tlet lastSuccessfulTextProtocolBatch: SuccessfulTextProtocolBatch | undefined;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\tconst processPendingMessages = async (): Promise<void> => {\n\t\tif (pendingMessages.length === 0) return;\n\t\tlastSuccessfulTextProtocolBatch = undefined;\n\t\t// Only an owner/user turn can change authority or intent. Internal custom steering and\n\t\t// follow-up messages must not re-admit a known-bad unchanged operation. Count every owner\n\t\t// message so live admission stays byte-for-byte aligned with transcript restoration.\n\t\tfor (const message of pendingMessages) {\n\t\t\tif (message.role === \"user\") toolFailureRecoveryGate.noteWorldAdvance();\n\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\tcurrentContext.messages.push(message);\n\t\t\tnewMessages.push(message);\n\t\t}\n\t\tpendingMessages = [];\n\t};\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tif (providerTurnLimit > 0 && continuationState.providerTurns >= providerTurnLimit) {\n\t\t\t\t// Preserve already-dequeued steering, but do not announce an assistant turn that will\n\t\t\t\t// never start. A turn is one provider response plus its tools/results.\n\t\t\t\tawait processPendingMessages();\n\t\t\t\tawait emitProviderTurnLimitStop(config, continuationState, newMessages, emit);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Process pending messages (inject before next assistant response).\n\t\t\tawait processPendingMessages();\n\t\t\tcontinuationState.providerTurns++;\n\t\t\tconst response = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tconst message = response.message;\n\t\t\tnewMessages.push(message);\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tconst textProtocolBatch = toolCalls.every((toolCall) => toolCall.source === \"text-protocol\");\n\t\t\t\tconst incomingBatchSignature = textProtocolBatchSignature(toolCalls);\n\t\t\t\tconst previousSuccessfulTextProtocolResults =\n\t\t\t\t\ttextProtocolBatch &&\n\t\t\t\t\trepeatsSuccessfulTextProtocolBatch(incomingBatchSignature, toolCalls, lastSuccessfulTextProtocolBatch)\n\t\t\t\t\t\t? lastSuccessfulTextProtocolBatch?.messages\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst executedToolBatch = await executeToolCalls(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tmessage,\n\t\t\t\t\tresponse.requestId,\n\t\t\t\t\tconfig,\n\t\t\t\t\tvalidationFailureTracker,\n\t\t\t\t\trepairTeachTracker,\n\t\t\t\t\ttoolFailureMemory,\n\t\t\t\t\ttoolFailureRecoveryGate,\n\t\t\t\t\tpreviousSuccessfulTextProtocolResults,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\t\t\t\tif (!previousSuccessfulTextProtocolResults) {\n\t\t\t\t\tlastSuccessfulTextProtocolBatch =\n\t\t\t\t\t\ttextProtocolBatch &&\n\t\t\t\t\t\ttoolResults.length === toolCalls.length &&\n\t\t\t\t\t\ttoolResults.every((result) => !result.isError)\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tsignature: textProtocolBatchSignature(toolCalls),\n\t\t\t\t\t\t\t\t\tmessages: toolResults,\n\t\t\t\t\t\t\t\t\tcalls: toolCalls,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlastSuccessfulTextProtocolBatch = undefined;\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// Runaway-loop backstop (cost guard): detect only a repeated suffix cycle. Counting\n\t\t\t// signatures anywhere in the window falsely stopped progressing workflows whose status\n\t\t\t// checks recurred among distinct edits, reads, and verification operations.\n\t\t\tif (stallLimit > 0 && toolCalls.length > 0) {\n\t\t\t\tconst signature = normalizeToolSignature(toolCalls.map((c) => [c.name, c.arguments ?? null]));\n\t\t\t\tstallWindow.push(signature);\n\t\t\t\tif (stallWindow.length > stallLimit * STALL_WINDOW_PERIODS) stallWindow.shift();\n\t\t\t\tif (repeatsToolCallPattern(stallWindow, stallLimit)) {\n\t\t\t\t\tconfig.onRunawayStop?.({ reason: \"repeated_tool_call\", signature, repeats: stallLimit });\n\t\t\t\t\tawait streamToollessClosingTurn(\n\t\t\t\t\t\tcurrentContext,\n\t\t\t\t\t\tnewMessages,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tcontinuationState,\n\t\t\t\t\t\tproviderTurnLimit,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\temit,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t);\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst nextTurnContext = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\t\t\tconst nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);\n\t\t\tif (nextTurnSnapshot) {\n\t\t\t\tcurrentContext = nextTurnSnapshot.context ?? currentContext;\n\t\t\t\tif (nextTurnSnapshot.context) {\n\t\t\t\t\ttoolFailureMemory = createToolFailureMemoryTracker(currentContext.messages);\n\t\t\t\t}\n\t\t\t\tconfig = {\n\t\t\t\t\t...config,\n\t\t\t\t\tmodel: nextTurnSnapshot.model ?? config.model,\n\t\t\t\t\treasoning: nextTurnSnapshot.thinkingLevel ?? config.reasoning,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tawait config.shouldStopAfterTurn?.({\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\tnewMessages,\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tif (followUpMessages.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nconst RUNAWAY_STOP_CLOSING_SYSTEM_PROMPT = [\n\t\"RUNAWAY STOP CLOSING TURN\",\n\t\"The host stopped a repeated tool-call loop. No tools are available in this final request.\",\n\t\"Write one concise factual closing message for the user: completed work, the unresolved operation or blocker, and the safest next action.\",\n\t\"Do not claim unperformed work. Do not emit a tool call or tool-call markup.\",\n].join(\"\\n\");\n\n/**\n * Spend one final provider request, with no tools, so a stopped run closes in the model's own words.\n *\n * The harness never writes that message itself. Tools are removed from the request, so this request\n * cannot open another tool batch and cannot re-enter the loop; it runs through the same planned\n * provider boundary as every other request. If the run is aborted, or the configured provider-turn\n * limit leaves no budget, the run ends with no closing message rather than a fabricated one — and a\n * provider error keeps its own error message for the same reason.\n */\nasync function streamToollessClosingTurn(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tcontinuationState: AgentLoopContinuationState,\n\tproviderTurnLimit: number,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tif (signal?.aborted) return;\n\tif (providerTurnLimit > 0 && continuationState.providerTurns >= providerTurnLimit) return;\n\tcontinuationState.providerTurns++;\n\tawait emit({ type: \"turn_start\" });\n\tconst closingContext: AgentContext = {\n\t\t...currentContext,\n\t\tsystemPrompt: currentContext.systemPrompt\n\t\t\t? `${currentContext.systemPrompt}\\n\\n${RUNAWAY_STOP_CLOSING_SYSTEM_PROMPT}`\n\t\t\t: RUNAWAY_STOP_CLOSING_SYSTEM_PROMPT,\n\t\ttools: [],\n\t};\n\tconst response = await streamAssistantResponse(closingContext, config, signal, emit, streamFn, {\n\t\trejectToolCalls: true,\n\t});\n\tconst message = response.message;\n\tnewMessages.push(message);\n\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n}\n\n/**\n * Start one provider request through the canonical agent-loop boundary.\n *\n * All callers, including host-owned tool-free finalization, receive the same failure-context\n * sanitization, context transformation/conversion, dynamic authentication, request-local reasoning,\n * and request preflight immediately before transport.\n */\nexport async function startAgentProviderRequest(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\tstreamFn?: StreamFn,\n): Promise<Awaited<ReturnType<StreamFn>>> {\n\treturn startPlannedAgentProviderRequest(context, config, signal, streamFn);\n}\n\ntype StartedAssistantResponse = {\n\tmessage: AssistantMessage;\n\trequestId: AgentRequestId;\n};\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tpolicy?: { rejectToolCalls: boolean },\n): Promise<StartedAssistantResponse> {\n\tconst degenerationAbort = new AbortController();\n\tconst onOuterAbort = (): void => degenerationAbort.abort();\n\tif (signal?.aborted) degenerationAbort.abort();\n\telse signal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\tconst response = await startPlannedAgentProviderRequestWithId(context, config, degenerationAbort.signal, streamFn);\n\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\tlet abortedForDegeneration = false;\n\n\tresponseEvents: for await (const event of response.stream) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tawait emit({\n\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\t!abortedForDegeneration &&\n\t\t\t\t\t\t!signal?.aborted &&\n\t\t\t\t\t\t!partialMessage.content.some((block) => block.type === \"toolCall\") &&\n\t\t\t\t\t\tshouldAbortDegenerateStream(assistantMessageText(partialMessage))\n\t\t\t\t\t) {\n\t\t\t\t\t\tabortedForDegeneration = true;\n\t\t\t\t\t\tdegenerationAbort.abort();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\":\n\t\t\t\tbreak responseEvents;\n\t\t}\n\t}\n\n\tsignal?.removeEventListener(\"abort\", onOuterAbort);\n\tconst providerMessage = await response.stream.result();\n\tlet finalMessage = policy?.rejectToolCalls\n\t\t? rejectToolCallsFromToolFreeResponse(providerMessage)\n\t\t: rejectNativeToolProtocolResidue(providerMessage, context.tools ?? [], Boolean(config.textToolCallProtocol));\n\tif (abortedForDegeneration && !signal?.aborted && finalMessage.stopReason === \"aborted\") {\n\t\tfinalMessage = { ...finalMessage, stopReason: \"stop\" };\n\t\tdelete finalMessage.errorMessage;\n\t}\n\tfinalMessage = collapseDegenerateAssistantMessage(finalMessage);\n\tif (addedPartial) {\n\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t} else {\n\t\tcontext.messages.push(finalMessage);\n\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t}\n\tawait emit({ type: \"message_end\", message: finalMessage });\n\treturn { message: finalMessage, requestId: response.requestId };\n}\n\ninterface ToolExecutionContext {\n\tcontext: AgentContext;\n\tassistantMessage: AssistantMessage;\n\trequestId: AgentRequestId;\n\tconfig: AgentLoopConfig;\n\tvalidationFailureTracker: ToolValidationFailureTracker;\n\trepairTeachTracker: ToolRepairTeachTracker;\n\ttoolFailureMemory: ToolFailureMemoryTracker;\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate;\n\tpreviousSuccessfulResults?: readonly ToolResultMessage[];\n\tsignal?: AbortSignal;\n\temit: AgentEventSink;\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\trequestId: AgentRequestId,\n\tconfig: AgentLoopConfig,\n\tvalidationFailureTracker: ToolValidationFailureTracker,\n\trepairTeachTracker: ToolRepairTeachTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tpreviousSuccessfulTextProtocolResults: readonly ToolResultMessage[] | undefined,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t(tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === \"sequential\",\n\t);\n\tconst execCtx: ToolExecutionContext = {\n\t\tcontext: currentContext,\n\t\tassistantMessage,\n\t\trequestId,\n\t\tconfig,\n\t\tvalidationFailureTracker,\n\t\trepairTeachTracker,\n\t\ttoolFailureMemory,\n\t\ttoolFailureRecoveryGate,\n\t\tpreviousSuccessfulResults: previousSuccessfulTextProtocolResults,\n\t\tsignal,\n\t\temit,\n\t};\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\n\t\treturn executeToolCallsSequential(execCtx, toolCalls);\n\t}\n\treturn executeToolCallsParallel(execCtx, toolCalls);\n}\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\tterminate: boolean;\n};\n\ntype SuccessfulTextProtocolBatch = {\n\tsignature: string;\n\tmessages: readonly ToolResultMessage[];\n\tcalls: readonly AgentToolCall[];\n};\n\ntype StartedToolCall =\n\t| { kind: \"finalized\"; finalized: FinalizedToolCallOutcome }\n\t| { kind: \"prepared\"; preparation: PreparedToolCall };\n\nasync function prepareAndStartToolCall(\n\texecCtx: ToolExecutionContext,\n\ttoolCall: AgentToolCall,\n\tindex: number,\n): Promise<StartedToolCall> {\n\tconst preparation = execCtx.previousSuccessfulResults\n\t\t? createRepeatedSuccessfulToolCallOutcome(execCtx.previousSuccessfulResults[index])\n\t\t: await prepareToolCall(\n\t\t\t\texecCtx.context,\n\t\t\t\texecCtx.assistantMessage,\n\t\t\t\ttoolCall,\n\t\t\t\texecCtx.config,\n\t\t\t\texecCtx.validationFailureTracker,\n\t\t\t\texecCtx.toolFailureMemory,\n\t\t\t\texecCtx.toolFailureRecoveryGate,\n\t\t\t\texecCtx.signal,\n\t\t\t\texecCtx.requestId,\n\t\t\t);\n\tif (preparation.kind === \"immediate\") {\n\t\tawait emitToolExecutionStart(toolCall, execCtx.emit);\n\t\temitToolArgumentValidationTelemetry(execCtx.config, preparation.validationEvent, \"not_run\", \"none\");\n\t\treturn {\n\t\t\tkind: \"finalized\",\n\t\t\tfinalized: finalizeRejectedToolCall(\n\t\t\t\ttoolCall,\n\t\t\t\texecCtx.context.tools?.find((tool) => tool.name === toolCall.name),\n\t\t\t\tpreparation,\n\t\t\t\texecCtx.toolFailureMemory,\n\t\t\t),\n\t\t};\n\t}\n\treturn { kind: \"prepared\", preparation };\n}\n\nasync function finalizeStartedToolCall(\n\texecCtx: ToolExecutionContext,\n\tstarted: StartedToolCall,\n): Promise<FinalizedToolCallOutcome> {\n\tif (started.kind === \"finalized\") return started.finalized;\n\treturn executeAndFinalizePreparedToolCall(\n\t\texecCtx.context,\n\t\texecCtx.assistantMessage,\n\t\tstarted.preparation,\n\t\texecCtx.requestId,\n\t\texecCtx.config,\n\t\texecCtx.repairTeachTracker,\n\t\texecCtx.toolFailureMemory,\n\t\texecCtx.toolFailureRecoveryGate,\n\t\texecCtx.signal,\n\t\texecCtx.emit,\n\t);\n}\n\nasync function reservePreparedToolCalls(\n\texecCtx: ToolExecutionContext,\n\tpreparedCalls: readonly PreparedToolCall[],\n): Promise<void> {\n\tif (preparedCalls.length === 0) return;\n\texecCtx.signal?.throwIfAborted();\n\tif (execCtx.config.onToolCallStart) {\n\t\tconst calls: ToolCallStartContext[] = preparedCalls.map((prepared) => ({\n\t\t\trequestId: execCtx.requestId,\n\t\t\tcallId: prepared.toolCall.id,\n\t\t\ttoolName: prepared.toolCall.name,\n\t\t\tassistantMessage: execCtx.assistantMessage,\n\t\t\ttoolCall: prepared.toolCall,\n\t\t\targs: prepared.args,\n\t\t\tcontext: execCtx.context,\n\t\t}));\n\t\tawait execCtx.config.onToolCallStart(calls, execCtx.signal);\n\t}\n\texecCtx.signal?.throwIfAborted();\n\tfor (const prepared of preparedCalls) {\n\t\tawait emitToolExecutionStart(prepared.toolCall, execCtx.emit);\n\t}\n}\n\nasync function executeToolCallsSequential(\n\texecCtx: ToolExecutionContext,\n\ttoolCalls: AgentToolCall[],\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\n\tfor (const [index, toolCall] of toolCalls.entries()) {\n\t\tconst started = await prepareAndStartToolCall(execCtx, toolCall, index);\n\t\tif (started.kind === \"prepared\") {\n\t\t\tawait reservePreparedToolCalls(execCtx, [started.preparation]);\n\t\t}\n\t\tconst finalized = await finalizeStartedToolCall(execCtx, started);\n\t\texecCtx.toolFailureRecoveryGate.apply(finalized.executionGateEffect);\n\n\t\tawait emitToolExecutionEnd(finalized, execCtx.emit);\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tawait emitToolResultMessage(toolResultMessage, execCtx.emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(toolResultMessage);\n\n\t\tif (execCtx.signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn { messages, terminate: shouldTerminateToolBatch(finalizedCalls) };\n}\n\nasync function executeToolCallsParallel(\n\texecCtx: ToolExecutionContext,\n\ttoolCalls: AgentToolCall[],\n): Promise<ExecutedToolCallBatch> {\n\tconst orderedFinalizedCalls: FinalizedToolCallOutcome[] = [];\n\tlet nextIndex = 0;\n\t// Account each bounded concurrent wave before launching more calls. This controls concurrency;\n\t// admission remains operation-specific and does not stop unrelated work after failures.\n\twhile (nextIndex < toolCalls.length && !execCtx.signal?.aborted) {\n\t\tconst waveEnd = Math.min(nextIndex + TOOL_EXECUTION_WAVE_SIZE, toolCalls.length);\n\t\tconst wave: FinalizedToolCallEntry[] = [];\n\t\tconst preparedWave: PreparedToolCall[] = [];\n\t\tconst completionOrder: FinalizedToolCallOutcome[] = [];\n\t\tfor (; nextIndex < waveEnd; nextIndex++) {\n\t\t\tconst toolCall = toolCalls[nextIndex];\n\t\t\tconst started = await prepareAndStartToolCall(execCtx, toolCall, nextIndex);\n\t\t\tif (started.kind === \"finalized\") {\n\t\t\t\tawait emitToolExecutionEnd(started.finalized, execCtx.emit);\n\t\t\t\twave.push(started.finalized);\n\t\t\t} else {\n\t\t\t\tpreparedWave.push(started.preparation);\n\t\t\t\twave.push(async () => {\n\t\t\t\t\tconst finalized = await finalizeStartedToolCall(execCtx, started);\n\t\t\t\t\tcompletionOrder.push(finalized);\n\t\t\t\t\treturn finalized;\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (execCtx.signal?.aborted) {\n\t\t\t\tnextIndex++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tawait reservePreparedToolCalls(execCtx, preparedWave);\n\n\t\tconst finalizedWave = await Promise.all(\n\t\t\twave.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t\t);\n\t\tfor (const finalized of finalizedWave) execCtx.toolFailureRecoveryGate.apply(finalized.executionGateEffect);\n\t\tfor (const finalized of completionOrder) {\n\t\t\tawait emitToolExecutionEnd(finalized, execCtx.emit);\n\t\t}\n\t\torderedFinalizedCalls.push(...finalizedWave);\n\t}\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tawait emitToolResultMessage(toolResultMessage, execCtx.emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\treturn { messages, terminate: shouldTerminateToolBatch(orderedFinalizedCalls) };\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n\tvalidationEvent?: ToolArgumentValidationTelemetryEvent;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tcorrection: string;\n\tdiagnostic?: string;\n\trepeatedSuccessfulCall?: { previousToolCallId: string };\n\trepeatedToolFailure?: boolean;\n\tvalidationEvent?: ToolArgumentValidationTelemetryEvent;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\terrorClass?: string;\n\tfailureMessage?: string;\n\tfailureCode?: string;\n\toutputSignature?: string;\n\terrorKind?: AgentToolErrorKind;\n};\n\ntype FinalizedToolCallOutcome = {\n\ttoolCall: AgentToolCall;\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\texecutionGateEffect?: ToolFailureRecoveryGateEffect;\n};\n\ntype FinalizedToolCallEntry = FinalizedToolCallOutcome | (() => Promise<FinalizedToolCallOutcome>);\n\ntype ToolValidationFailureTracker = {\n\tsignature?: string;\n\trepeats: number;\n\tescalatedSignature?: string;\n};\n\ntype ToolRepairTeachTracker = Map<string, number>;\n\nconst DEFAULT_TOOL_VALIDATION_ESCALATION_THRESHOLD = 3;\nconst TOOL_REPAIR_TEACH_EVERY = 5;\nconst REPEATED_SUCCESS_RESULT_MAX_CHARS = 2_048;\n\nfunction createRepeatedSuccessfulToolCallOutcome(\n\tpreviousResult: ToolResultMessage | undefined,\n): ImmediateToolCallOutcome {\n\tconst previousText = previousResult?.content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\")\n\t\t.slice(0, REPEATED_SUCCESS_RESULT_MAX_CHARS);\n\tconst diagnostic = previousText\n\t\t? `${REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.diagnostic} Previous successful result: ${previousText}`\n\t\t: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.diagnostic;\n\treturn {\n\t\tkind: \"immediate\",\n\t\tresult: createErrorToolResult(diagnostic),\n\t\tisError: true,\n\t\tphase: \"execution\",\n\t\tfailureCode: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.failureCode,\n\t\tcorrection: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.guidance,\n\t\tdiagnostic,\n\t\t...(previousResult ? { repeatedSuccessfulCall: { previousToolCallId: previousResult.toolCallId } } : {}),\n\t};\n}\n\nfunction createAbortedToolCallOutcome(\n\tvalidationEvent: ToolArgumentValidationTelemetryEvent | undefined,\n): ImmediateToolCallOutcome {\n\treturn {\n\t\tkind: \"immediate\",\n\t\tresult: createErrorToolResult(\"Operation aborted\"),\n\t\tisError: true,\n\t\tphase: \"cancelled\",\n\t\tfailureCode: \"aborted\",\n\t\tcorrection: \"Retry only if the operation is still required.\",\n\t\tvalidationEvent,\n\t};\n}\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nfunction createValidationBounceTelemetry(\n\tconfig: AgentLoopConfig,\n\ttoolCall: AgentToolCall,\n\terrorKeyword: string,\n): ToolArgumentValidationTelemetryEvent {\n\treturn {\n\t\toutcome: \"bounced\",\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\ttool: toolCall.name,\n\t\tsource: toolCall.source,\n\t\tfailureModes: [\"other\"],\n\t\trepairsApplied: [],\n\t\terrorKeywords: [errorKeyword],\n\t\ttaught: \"none\",\n\t\texecutionOutcome: \"not_run\",\n\t};\n}\n\nfunction validationFailureCorrection(\n\tevent: ToolArgumentValidationTelemetryEvent | undefined,\n\ttoolName: string,\n): string {\n\tconst shape = event?.failureShape\n\t\t?.slice(0, 3)\n\t\t.map((entry) => `${entry.path}: expected ${entry.expectedType}, received ${entry.receivedType}`)\n\t\t.join(\"; \");\n\tconst rules = [\n\t\t...new Set(\n\t\t\t(event?.failureModes ?? [])\n\t\t\t\t.filter((mode) => mode !== \"other\")\n\t\t\t\t.map((mode) => formatToolRepairStandingRule(mode)),\n\t\t),\n\t];\n\treturn [`Match ${toolName} arguments to its current schema.`, shape ? `Fix ${shape}.` : undefined, ...rules]\n\t\t.filter((part): part is string => part !== undefined)\n\t\t.join(\" \");\n}\n\nfunction resetValidationFailureTracker(tracker: ToolValidationFailureTracker): void {\n\ttracker.signature = undefined;\n\ttracker.repeats = 0;\n}\n\nfunction emitToolArgumentValidationTelemetry(\n\tconfig: AgentLoopConfig,\n\tevent: ToolArgumentValidationTelemetryEvent | undefined,\n\texecutionOutcome: ToolArgumentExecutionOutcome,\n\ttaught: ToolArgumentValidationTelemetryEvent[\"taught\"],\n): void {\n\tif (!event) return;\n\tconfig.onToolArgumentValidation?.({ ...event, executionOutcome, taught });\n}\n\nfunction toolValidationEscalationThreshold(config: AgentLoopConfig): number {\n\treturn config.toolValidationEscalationThreshold ?? DEFAULT_TOOL_VALIDATION_ESCALATION_THRESHOLD;\n}\n\nfunction isToolArgumentRepairEmergencyDisabled(): boolean {\n\tconst env = typeof process === \"object\" && process ? process.env : undefined;\n\tconst value = env?.PI_TOOL_REPAIR_DISABLED;\n\tif (!value) return false;\n\treturn [\"1\", \"true\", \"yes\", \"on\"].includes(value.trim().toLowerCase());\n}\n\nfunction isToolArgumentValidationError(error: unknown): error is ToolArgumentValidationError {\n\treturn (\n\t\terror instanceof ToolArgumentValidationError ||\n\t\t(error instanceof Error &&\n\t\t\terror.name === \"ToolArgumentValidationError\" &&\n\t\t\ttypeof (error as { toolName?: unknown }).toolName === \"string\" &&\n\t\t\ttypeof (error as { signature?: unknown }).signature === \"string\" &&\n\t\t\ttypeof (error as { enrichment?: unknown }).enrichment === \"string\")\n\t);\n}\n\nfunction handleValidationFailure(\n\terror: ToolArgumentValidationError,\n\tconfig: AgentLoopConfig,\n\ttracker: ToolValidationFailureTracker,\n): string {\n\tif (tracker.signature === error.signature) {\n\t\ttracker.repeats++;\n\t} else {\n\t\ttracker.signature = error.signature;\n\t\ttracker.repeats = 1;\n\t\ttracker.escalatedSignature = undefined;\n\t}\n\n\tconst threshold = toolValidationEscalationThreshold(config);\n\tif (threshold <= 0 || tracker.repeats < threshold || tracker.escalatedSignature === error.signature) {\n\t\treturn error.message;\n\t}\n\n\ttracker.escalatedSignature = error.signature;\n\tconfig.onToolValidationEscalation?.({\n\t\ttool: error.toolName,\n\t\tsignature: error.signature,\n\t\trepeats: tracker.repeats,\n\t\tmodel: config.model.id,\n\t\tprovider: config.model.provider,\n\t});\n\treturn `${error.message}\\n\\nRepeated validation failure (${tracker.repeats} identical attempts). Use this full schema and example before retrying:\\n${error.enrichment}`;\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tvalidationFailureTracker: ToolValidationFailureTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tsignal: AbortSignal | undefined,\n\trequestId: AgentRequestId,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((candidate) => candidate.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t\tphase: \"validation\",\n\t\t\tfailureCode: \"unknown_tool\",\n\t\t\tcorrection: \"Choose a tool from the currently available tool list.\",\n\t\t\tvalidationEvent: createValidationBounceTelemetry(config, toolCall, \"unknown_tool\"),\n\t\t};\n\t}\n\n\tif (toolCall.errorMessage) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(toolCall.errorMessage),\n\t\t\tisError: true,\n\t\t\tphase: \"validation\",\n\t\t\tfailureCode: \"malformed_call\",\n\t\t\tcorrection: \"Resend one complete JSON argument object matching the current tool schema.\",\n\t\t\tvalidationEvent: createValidationBounceTelemetry(config, toolCall, \"malformed_call\"),\n\t\t};\n\t}\n\n\tlet validationEvent: ToolArgumentValidationTelemetryEvent | undefined;\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall, {\n\t\t\tmodel: config.model.id,\n\t\t\tprovider: config.model.provider,\n\t\t\trepairEnabled: !isToolArgumentRepairEmergencyDisabled(),\n\t\t\ttelemetry: (event) => {\n\t\t\t\tvalidationEvent = event;\n\t\t\t},\n\t\t});\n\t\tresetValidationFailureTracker(validationFailureTracker);\n\t\tif (preparedToolCall.repairNotes) {\n\t\t\ttoolCall.repairNotes = preparedToolCall.repairNotes;\n\t\t}\n\t\tif (validatedArgs !== toolCall.arguments) {\n\t\t\ttoolCall.rawArguments ??= toolCall.arguments;\n\t\t\ttoolCall.arguments = validatedArgs;\n\t\t}\n\t\tconst unresolvedRecord = getUnresolvedToolFailure(toolFailureMemory, toolCall.name, validatedArgs);\n\t\tconst admission = toolFailureRecoveryGate.admit(tool, validatedArgs, unresolvedRecord, currentContext.messages);\n\t\tif (admission.kind === \"blocked\") {\n\t\t\tconst result = createRepeatedToolFailureResult(admission.record);\n\t\t\tconst memoryRecord = result.details.piToolFailureMemory;\n\t\t\ttoolFailureMemory.set(admission.record.failureKey, memoryRecord);\n\t\t\treturn {\n\t\t\t\tkind: \"immediate\",\n\t\t\t\tresult,\n\t\t\t\tisError: true,\n\t\t\t\tphase: admission.record.phase,\n\t\t\t\tfailureCode: \"repeated_failed_operation\",\n\t\t\t\tcorrection: memoryRecord.correction,\n\t\t\t\tdiagnostic: memoryRecord.diagnostic,\n\t\t\t\trepeatedToolFailure: true,\n\t\t\t\tvalidationEvent: createValidationBounceTelemetry(config, toolCall, \"repeated_failed_operation\"),\n\t\t\t};\n\t\t}\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\trequestId,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (signal?.aborted) {\n\t\t\t\treturn createAbortedToolCallOutcome(validationEvent);\n\t\t\t}\n\t\t\tif (beforeResult?.block) {\n\t\t\t\tconst reason = beforeResult.reason || \"Tool execution was blocked\";\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(reason),\n\t\t\t\t\tisError: true,\n\t\t\t\t\tphase: \"policy\",\n\t\t\t\t\tfailureCode: \"blocked\",\n\t\t\t\t\tcorrection: \"Choose an allowed approach or request the required authority before retrying.\",\n\t\t\t\t\tdiagnostic: reason,\n\t\t\t\t\tvalidationEvent,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (signal?.aborted) {\n\t\t\treturn createAbortedToolCallOutcome(validationEvent);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t\tvalidationEvent,\n\t\t};\n\t} catch (error) {\n\t\tconst message = isToolArgumentValidationError(error)\n\t\t\t? handleValidationFailure(error, config, validationFailureTracker)\n\t\t\t: error instanceof Error\n\t\t\t\t? error.message\n\t\t\t\t: String(error);\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(message),\n\t\t\tisError: true,\n\t\t\tphase: isToolArgumentValidationError(error) ? \"validation\" : \"preflight\",\n\t\t\tfailureCode: isToolArgumentValidationError(error) ? \"invalid_arguments\" : \"preflight_error\",\n\t\t\tcorrection: isToolArgumentValidationError(error)\n\t\t\t\t? validationFailureCorrection(validationEvent, toolCall.name)\n\t\t\t\t: toolFailureCorrection(message, \"rejected\", \"preflight\"),\n\t\t\tdiagnostic: isToolArgumentValidationError(error) ? undefined : message,\n\t\t\tvalidationEvent,\n\t\t};\n\t}\n}\n\nfunction finalizeRejectedToolCall(\n\ttoolCall: AgentToolCall,\n\ttool: AgentTool<any> | undefined,\n\toutcome: ImmediateToolCallOutcome,\n\ttracker: ToolFailureMemoryTracker,\n): FinalizedToolCallOutcome {\n\tif (outcome.repeatedToolFailure) {\n\t\treturn {\n\t\t\ttoolCall,\n\t\t\tresult: outcome.result,\n\t\t\tisError: true,\n\t\t};\n\t}\n\tconst record = rememberToolFailure(\n\t\ttracker,\n\t\ttoolCall.name,\n\t\ttoolCall.arguments,\n\t\t\"rejected\",\n\t\toutcome.failureCode,\n\t\toutcome.correction,\n\t\toutcome.diagnostic,\n\t\toutcome.phase,\n\t\tundefined,\n\t\t{\n\t\t\toutput: outcome.result.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\"),\n\t\t},\n\t);\n\tconst failureResult = createToolFailureResult(record, outcome.result.terminate);\n\treturn {\n\t\ttoolCall,\n\t\tresult: outcome.repeatedSuccessfulCall\n\t\t\t? {\n\t\t\t\t\t...failureResult,\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\t...failureResult.details,\n\t\t\t\t\t\tpiRepeatedSuccessfulCall: outcome.repeatedSuccessfulCall,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: failureResult,\n\t\tisError: true,\n\t\texecutionGateEffect: {\n\t\t\tkind: \"unproductive\",\n\t\t\t...(tool ? { tool } : {}),\n\t\t\trecord,\n\t\t\targs: toolCall.arguments,\n\t\t},\n\t};\n}\n\ntype LinkedToolAbort = {\n\tsignal: AbortSignal;\n\tdetachForeground(): void;\n\tcancel(): void;\n};\n\nfunction createLinkedToolAbort(foregroundSignal: AbortSignal | undefined): LinkedToolAbort {\n\tconst controller = new AbortController();\n\tconst abortFromForeground = (): void => controller.abort(foregroundSignal?.reason);\n\tlet linked = false;\n\tif (foregroundSignal?.aborted) {\n\t\tabortFromForeground();\n\t} else if (foregroundSignal) {\n\t\tforegroundSignal.addEventListener(\"abort\", abortFromForeground, { once: true });\n\t\tlinked = true;\n\t}\n\treturn {\n\t\tsignal: controller.signal,\n\t\tdetachForeground: () => {\n\t\t\tif (!linked || !foregroundSignal) return;\n\t\t\tforegroundSignal.removeEventListener(\"abort\", abortFromForeground);\n\t\t\tlinked = false;\n\t\t},\n\t\tcancel: () => controller.abort(),\n\t};\n}\n\nfunction getBackgroundToolCallDelay(config: AgentLoopConfig): number | undefined {\n\tconst delay = config.backgroundToolCallAfterMs;\n\tif (delay === undefined || !Number.isFinite(delay) || delay <= 0) return undefined;\n\treturn delay;\n}\n\nasync function executeAndFinalizePreparedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\trequestId: AgentRequestId,\n\tconfig: AgentLoopConfig,\n\trepairTeachTracker: ToolRepairTeachTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tforegroundSignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<FinalizedToolCallOutcome> {\n\tconst backgroundDelay = getBackgroundToolCallDelay(config);\n\tif (\n\t\t!config.handoffToolCall ||\n\t\t(backgroundDelay === undefined && config.subscribeToolCallHandoffRequest === undefined)\n\t) {\n\t\tconst executed = await executePreparedToolCall(prepared, foregroundSignal, emit);\n\t\treturn finalizeExecutedToolCall(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\tprepared,\n\t\t\trequestId,\n\t\t\texecuted,\n\t\t\tconfig,\n\t\t\trepairTeachTracker,\n\t\t\ttoolFailureMemory,\n\t\t\ttoolFailureRecoveryGate,\n\t\t\tforegroundSignal,\n\t\t);\n\t}\n\n\tconst executionAbort = createLinkedToolAbort(foregroundSignal);\n\tconst startedAt = Date.now();\n\tlet emitForegroundUpdates = true;\n\tconst completion = (async (): Promise<FinalizedToolCallOutcome> => {\n\t\tconst executed = await executePreparedToolCall(prepared, executionAbort.signal, (event) => {\n\t\t\tif (emitForegroundUpdates) return emit(event);\n\t\t});\n\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\tprepared,\n\t\t\trequestId,\n\t\t\texecuted,\n\t\t\tconfig,\n\t\t\trepairTeachTracker,\n\t\t\ttoolFailureMemory,\n\t\t\ttoolFailureRecoveryGate,\n\t\t\texecutionAbort.signal,\n\t\t);\n\t\treturn finalized;\n\t})();\n\tcompletion.then(executionAbort.detachForeground, executionAbort.detachForeground);\n\n\tlet deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst triggers: Array<Promise<{ kind: \"deadline\" | \"manual\" }>> = [];\n\tif (backgroundDelay !== undefined) {\n\t\ttriggers.push(\n\t\t\tnew Promise<{ kind: \"deadline\" }>((resolve) => {\n\t\t\t\tdeadlineTimer = setTimeout(() => resolve({ kind: \"deadline\" }), backgroundDelay);\n\t\t\t\t(deadlineTimer as { unref?: () => void }).unref?.();\n\t\t\t}),\n\t\t);\n\t}\n\tlet unsubscribeHandoffRequest: (() => void) | undefined;\n\tif (config.subscribeToolCallHandoffRequest) {\n\t\tconst manual = new Promise<{ kind: \"manual\" }>((resolve) => {\n\t\t\ttry {\n\t\t\t\tunsubscribeHandoffRequest = config.subscribeToolCallHandoffRequest?.(prepared.toolCall.id, () =>\n\t\t\t\t\tresolve({ kind: \"manual\" }),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tunsubscribeHandoffRequest = undefined;\n\t\t\t}\n\t\t});\n\t\ttriggers.push(manual);\n\t}\n\tlet outcome: { kind: \"completed\"; value: FinalizedToolCallOutcome } | { kind: \"deadline\" | \"manual\" };\n\ttry {\n\t\toutcome = await Promise.race([completion.then((value) => ({ kind: \"completed\" as const, value })), ...triggers]);\n\t} finally {\n\t\tif (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n\t\tunsubscribeHandoffRequest?.();\n\t}\n\tif (outcome.kind === \"completed\") return outcome.value;\n\tif (executionAbort.signal.aborted) return completion;\n\n\tlet handoffAccepted = false;\n\t// A handed-off call leaves the batch, so the batch never applies its effect: the background\n\t// completion is the only place left that can tell the governor what this operation did.\n\tconst handedOffCompletion = completion.then((finalized) => {\n\t\tif (handoffAccepted) toolFailureRecoveryGate.apply(finalized.executionGateEffect);\n\t\treturn finalized;\n\t});\n\tvoid handedOffCompletion.catch(() => undefined);\n\tlet handoff: ReturnType<NonNullable<AgentLoopConfig[\"handoffToolCall\"]>>;\n\ttry {\n\t\thandoff = config.handoffToolCall({\n\t\t\trequestId,\n\t\t\tassistantMessage,\n\t\t\ttoolCall: prepared.toolCall,\n\t\t\targs: prepared.args,\n\t\t\tcontext: currentContext,\n\t\t\telapsedMs: Math.max(0, Date.now() - startedAt),\n\t\t\tcompletion: handedOffCompletion,\n\t\t\tcancel: executionAbort.cancel,\n\t\t});\n\t} catch {\n\t\treturn completion;\n\t}\n\thandoffAccepted = handoff !== undefined;\n\tif (!handoff) return completion;\n\n\temitForegroundUpdates = false;\n\texecutionAbort.detachForeground();\n\treturn {\n\t\ttoolCall: prepared.toolCall,\n\t\tresult: handoff.result,\n\t\tisError: handoff.isError ?? handoff.result.isError === true,\n\t};\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult,\n\t\t\t// Tool definitions can report an expected operation failure without\n\t\t\t// throwing. Keep the returned result intact through afterToolCall so\n\t\t\t// policy hooks can inspect its bounded diagnostics and metadata.\n\t\t\tisError: result.isError === true,\n\t\t\t...(result.isError === true\n\t\t\t\t? { errorClass: \"tool_result_error\", errorKind: result.errorKind ?? \"tool_failure\" }\n\t\t\t\t: {}),\n\t\t};\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst toolFailure = error instanceof AgentToolExecutionError ? error : undefined;\n\t\treturn {\n\t\t\tresult: createErrorToolResult(message),\n\t\t\tisError: true,\n\t\t\terrorClass: error instanceof Error ? error.name : typeof error,\n\t\t\tfailureMessage: message,\n\t\t\terrorKind: toolFailure?.errorKind ?? \"tool_failure\",\n\t\t\t...(toolFailure ? { failureCode: toolFailure.failureCode, outputSignature: toolFailure.outputSignature } : {}),\n\t\t};\n\t}\n}\n\nfunction repairTeachKey(toolName: string, note: string): string {\n\tconst repairName = /^\\[harness\\] ([^:]+):/.exec(note)?.[1] ?? note;\n\treturn `${toolName}\\0${repairName}`;\n}\n\nfunction shouldEmitRepairTeachNote(toolName: string, note: string, tracker: ToolRepairTeachTracker): boolean {\n\tconst key = repairTeachKey(toolName, note);\n\tconst count = (tracker.get(key) ?? 0) + 1;\n\ttracker.set(key, count);\n\treturn count === 1 || count % TOOL_REPAIR_TEACH_EVERY === 0;\n}\n\nfunction appendRepairTeachNotes(\n\tresult: AgentToolResult<any>,\n\ttoolCall: AgentToolCall,\n\ttracker: ToolRepairTeachTracker,\n\tconfig: AgentLoopConfig,\n): { result: AgentToolResult<any>; taught: boolean } {\n\tif (config.toolArgumentTeachEnabled === false) return { result, taught: false };\n\tconst notes = (toolCall.repairNotes ?? []).filter((note) => shouldEmitRepairTeachNote(toolCall.name, note, tracker));\n\tif (notes.length === 0) return { result, taught: false };\n\treturn {\n\t\tresult: {\n\t\t\t...result,\n\t\t\tcontent: [...result.content, { type: \"text\", text: notes.join(\"\\n\") }],\n\t\t},\n\t\ttaught: true,\n\t};\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\trequestId: AgentRequestId,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\trepairTeachTracker: ToolRepairTeachTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\tlet failureMessage = executed.failureMessage ?? \"\";\n\tlet errorClass = executed.errorClass;\n\tlet failureCode = executed.failureCode;\n\tlet outputSignature = executed.outputSignature;\n\tlet errorKind = executed.errorKind;\n\tlet executionGateEffect: ToolFailureRecoveryGateEffect | undefined;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await config.afterToolCall(\n\t\t\t\t{\n\t\t\t\t\trequestId,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\targs: prepared.args,\n\t\t\t\t\tresult,\n\t\t\t\t\tisError,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tusage: afterResult.usage ?? result.usage,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// The hook itself failed, so nothing about the tool's own completed operation survives.\n\t\t\tfailureMessage = error instanceof Error ? error.message : String(error);\n\t\t\terrorClass = error instanceof Error ? error.name : typeof error;\n\t\t\tfailureCode = undefined;\n\t\t\toutputSignature = undefined;\n\t\t\terrorKind = \"tool_failure\";\n\t\t\tresult = { ...createErrorToolResult(failureMessage), usage: result.usage };\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\tif (isError) {\n\t\tconst usage = result.usage;\n\t\tconst failureOutput =\n\t\t\tfailureMessage ||\n\t\t\tresult.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\"Tool execution failed\";\n\t\tconst effectiveFailureMessage =\n\t\t\tfailureMessage || result.content.find((block) => block.type === \"text\")?.text || \"Tool execution failed\";\n\t\tconst assessment = assessToolFailure(effectiveFailureMessage, \"failed\", errorClass);\n\t\tconst effectiveFailureCode = failureCode ?? assessment.failureCode;\n\t\tif (errorKind === \"operation_outcome\") {\n\t\t\t// The tool ran the operation to completion; the non-zero status is the observation the\n\t\t\t// agent asked for. Nothing here is a mistake, so no failure record is remembered and the\n\t\t\t// tool's own output stands exactly as written. The governor still notes that repeating\n\t\t\t// this identical operation cannot say anything new until something else changes.\n\t\t\tclearToolFailure(toolFailureMemory, prepared.toolCall.name, prepared.args);\n\t\t\tresult = { ...result, errorKind: \"operation_outcome\", usage };\n\t\t\texecutionGateEffect = {\n\t\t\t\tkind: \"unproductive\",\n\t\t\t\ttool: prepared.tool,\n\t\t\t\trecord: describeOperationOutcome(\n\t\t\t\t\tprepared.toolCall.name,\n\t\t\t\t\tprepared.args,\n\t\t\t\t\teffectiveFailureCode,\n\t\t\t\t\tassessment.diagnostic,\n\t\t\t\t),\n\t\t\t\targs: prepared.args,\n\t\t\t};\n\t\t} else {\n\t\t\tconst recoveryPlan = toolFailureRecoveryGate.planFailure(\n\t\t\t\tprepared.tool,\n\t\t\t\tprepared.args,\n\t\t\t\t{ failureCode: effectiveFailureCode, message: effectiveFailureMessage },\n\t\t\t\tcurrentContext.tools ?? [],\n\t\t\t);\n\t\t\tconst correction = assessment.policyGuidance\n\t\t\t\t? `${assessment.policyGuidance} ${recoveryPlan.guidance}`\n\t\t\t\t: recoveryPlan.guidance;\n\t\t\tconst record = rememberToolFailure(\n\t\t\t\ttoolFailureMemory,\n\t\t\t\tprepared.toolCall.name,\n\t\t\t\tprepared.args,\n\t\t\t\t\"failed\",\n\t\t\t\teffectiveFailureCode,\n\t\t\t\tcorrection,\n\t\t\t\tassessment.diagnostic,\n\t\t\t\tassessment.phase,\n\t\t\t\trecoveryPlan.evidence ?? assessment.evidence,\n\t\t\t\t{ output: failureOutput, outputSignature },\n\t\t\t);\n\t\t\texecutionGateEffect = {\n\t\t\t\tkind: \"unproductive\",\n\t\t\t\ttool: prepared.tool,\n\t\t\t\trecord,\n\t\t\t\targs: prepared.args,\n\t\t\t};\n\t\t\tresult = { ...createToolFailureResult(record, result.terminate), usage };\n\t\t}\n\t} else {\n\t\tclearToolFailure(toolFailureMemory, prepared.toolCall.name, prepared.args);\n\t\tif (!executed.isError) {\n\t\t\texecutionGateEffect = {\n\t\t\t\tkind: \"success\",\n\t\t\t\ttool: prepared.tool,\n\t\t\t\targs: prepared.args,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst repaired = isError\n\t\t? { result, taught: false }\n\t\t: appendRepairTeachNotes(result, prepared.toolCall, repairTeachTracker, config);\n\temitToolArgumentValidationTelemetry(\n\t\tconfig,\n\t\tprepared.validationEvent,\n\t\tisError ? \"failed\" : \"succeeded\",\n\t\trepaired.taught ? \"note\" : \"none\",\n\t);\n\n\treturn {\n\t\ttoolCall: prepared.toolCall,\n\t\tresult: repaired.result,\n\t\tisError,\n\t\texecutionGateEffect,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function emitToolExecutionStart(toolCall: AgentToolCall, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\targs: toolCall.arguments,\n\t\trepair: getToolCallRepairInfo(toolCall),\n\t});\n}\n\nexport function getToolCallRepairInfo(toolCall: AgentToolCall): ToolCallRepairInfo | undefined {\n\tif (!toolCall.rawArguments && !toolCall.repairNotes?.length) return undefined;\n\treturn {\n\t\trepaired: true,\n\t\t...(toolCall.rawArguments ? { rawArguments: toolCall.rawArguments } : {}),\n\t\t...(toolCall.repairNotes?.length ? { notes: toolCall.repairNotes } : {}),\n\t};\n}\n\nasync function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: finalized.result,\n\t\tisError: finalized.isError,\n\t\trepair: getToolCallRepairInfo(finalized.toolCall),\n\t});\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: finalized.result.details,\n\t\tusage: finalized.result.usage,\n\t\tisError: finalized.isError,\n\t\t// Persisted so a reloaded transcript still separates a completed operation's own status from a\n\t\t// tool that could not run at all.\n\t\t...(finalized.isError && finalized.result.errorKind ? { errorKind: finalized.result.errorKind } : {}),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EACN,4BAA4B,EAC5B,qCAAqC,GAErC,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAEN,2BAA2B,EAE3B,qBAAqB,GACrB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,oBAAoB,EACpB,kCAAkC,EAClC,2BAA2B,GAC3B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACN,gCAAgC,EAChC,sCAAsC,GACtC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,iBAAiB,EACjB,gBAAgB,EAChB,+BAA+B,EAC/B,8BAA8B,EAC9B,uBAAuB,EACvB,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,mBAAmB,EAEnB,qBAAqB,GACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,uBAAuB,EAAsC,MAAM,iCAAiC,CAAC;AAC9G,OAAO,EAAE,+BAA+B,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AAelH,OAAO,EAAE,uBAAuB,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,EACN,0BAA0B,EAC1B,sBAAsB,EACtB,gCAAgC,GAChC,MAAM,+BAA+B,CAAC;AAIvC,+FAA+F;AAC/F,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAWnC,MAAM,UAAU,gCAAgC;IAC/C,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C,OAAO;QACjC,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,OAAO;QACjC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK;QAC7B,OAAO,EAAE,SAAS,CAAC,OAAO;QAC1B,+FAA+F;QAC/F,kCAAkC;QAClC,GAAG,CAAC,SAAS,CAAC,OAAO,IAAI,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrG,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;AACH,CAAC;AAED,KAAK,UAAU,qBAAqB,CAAC,iBAAoC,EAAE,IAAoB;IAC9F,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;AACjE,CAAC","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport { EventStream } from \"@caupulican/pi-ai/event-stream\";\nimport {\n\tformatToolRepairStandingRule,\n\tREPEATED_SUCCESSFUL_TOOL_CALL_FAILURE,\n\ttype ToolFailurePhase,\n} from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type { AssistantMessage, ToolResultMessage } from \"@caupulican/pi-ai/types\";\nimport {\n\ttype ToolArgumentExecutionOutcome,\n\tToolArgumentValidationError,\n\ttype ToolArgumentValidationTelemetryEvent,\n\tvalidateToolArguments,\n} from \"@caupulican/pi-ai/validation\";\nimport {\n\tassistantMessageText,\n\tcollapseDegenerateAssistantMessage,\n\tshouldAbortDegenerateStream,\n} from \"./degenerate-assistant-text.ts\";\nimport {\n\tstartPlannedAgentProviderRequest,\n\tstartPlannedAgentProviderRequestWithId,\n} from \"./provider-request-planner.ts\";\nimport {\n\tassessToolFailure,\n\tclearToolFailure,\n\tcreateRepeatedToolFailureResult,\n\tcreateToolFailureMemoryTracker,\n\tcreateToolFailureResult,\n\tdescribeOperationOutcome,\n\tgetToolExecutionKey,\n\tgetUnresolvedToolFailure,\n\tnormalizeToolSignature,\n\trememberToolFailure,\n\ttype ToolFailureMemoryTracker,\n\ttoolFailureCorrection,\n} from \"./tool-failure-memory.ts\";\nimport { ToolFailureRecoveryGate, type ToolFailureRecoveryGateEffect } from \"./tool-failure-recovery-gate.ts\";\nimport { rejectNativeToolProtocolResidue, rejectToolCallsFromToolFreeResponse } from \"./tool-protocol-residue.ts\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentRequestId,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolErrorKind,\n\tAgentToolResult,\n\tStreamFn,\n\tToolCallRepairInfo,\n\tToolCallStartContext,\n} from \"./types.ts\";\nimport { AgentToolExecutionError, DEFAULT_MAX_PROVIDER_TURNS, DEFAULT_MAX_STALL_TURNS } from \"./types.ts\";\nimport { createEmptyUsage } from \"./usage.ts\";\n\nexport {\n\tcomposeRequestSystemPrompt,\n\tnarrowRequestMaxTokens,\n\tresolveRequestPreflightMaxTokens,\n} from \"./provider-request-planner.ts\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\n/** Bound simultaneous tool starts without imposing a failure-count or operation-count stop. */\nconst TOOL_EXECUTION_WAVE_SIZE = 4;\n\n/** Bounded no-progress state retained across host-owned continuations of one logical prompt. */\nexport interface AgentLoopContinuationState {\n\tproviderTurns: number;\n\tstallWindow: string[];\n\t/** Optional for compatibility with continuation snapshots created before result-aware cycle detection. */\n\tstagnantResultWindow?: string[];\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate;\n}\n\nexport function createAgentLoopContinuationState(): AgentLoopContinuationState {\n\treturn {\n\t\tproviderTurns: 0,\n\t\tstallWindow: [],\n\t\tstagnantResultWindow: [],\n\t\ttoolFailureRecoveryGate: new ToolFailureRecoveryGate(),\n\t};\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\treturn streamAgentLoop(config, signal, (emit) => runAgentLoop(prompts, context, config, emit, signal, streamFn));\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tassertContinuableContext(context);\n\n\treturn streamAgentLoop(config, signal, (emit) => runAgentLoopContinue(context, config, emit, signal, streamFn));\n}\n\nfunction streamAgentLoop(\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\trun: (emit: AgentEventSink) => Promise<AgentMessage[]>,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\tvoid run(async (event) => {\n\t\tstream.push(event);\n\t})\n\t\t.catch(async (error) => {\n\t\t\tconst messages = [createLoopFailureMessage(error, config, signal?.aborted ?? false)];\n\t\t\tstream.push({ type: \"agent_end\", messages });\n\t\t\treturn messages;\n\t\t})\n\t\t.then((messages) => {\n\t\t\tstream.end(messages);\n\t\t});\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n\tcontinuationState: AgentLoopContinuationState = createAgentLoopContinuationState(),\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({ type: \"agent_start\" });\n\tif (providerTurnLimitReached(config, continuationState)) {\n\t\tfor (const prompt of prompts) {\n\t\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\t\tawait emit({ type: \"message_end\", message: prompt });\n\t\t}\n\t\tawait emitProviderTurnLimitStop(config, continuationState, newMessages, emit);\n\t\treturn newMessages;\n\t}\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn, continuationState);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n\tcontinuationState: AgentLoopContinuationState = createAgentLoopContinuationState(),\n): Promise<AgentMessage[]> {\n\tassertContinuableContext(context);\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context, messages: [...context.messages] };\n\n\tawait emit({ type: \"agent_start\" });\n\tif (providerTurnLimitReached(config, continuationState)) {\n\t\tawait emitProviderTurnLimitStop(config, continuationState, newMessages, emit);\n\t\treturn newMessages;\n\t}\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn, continuationState);\n\treturn newMessages;\n}\n\nfunction assertContinuableContext(context: AgentContext): void {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n}\n\nfunction createLoopFailureMessage(error: unknown, config: AgentLoopConfig, aborted: boolean): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: createEmptyUsage(),\n\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\nfunction providerTurnLimitReached(config: AgentLoopConfig, continuationState: AgentLoopContinuationState): boolean {\n\tconst limit = config.maxProviderTurns ?? DEFAULT_MAX_PROVIDER_TURNS;\n\treturn limit > 0 && continuationState.providerTurns >= limit;\n}\n\nasync function emitProviderTurnLimitStop(\n\tconfig: AgentLoopConfig,\n\tcontinuationState: AgentLoopContinuationState,\n\tnewMessages: AgentMessage[],\n\temit: AgentEventSink,\n): Promise<void> {\n\tconfig.onRunawayStop?.({\n\t\treason: \"provider_turn_limit\",\n\t\tsignature: \"provider_turn_limit\",\n\t\trepeats: continuationState.providerTurns,\n\t});\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/**\n * Maximum exact cycle width inspected by the runaway-loop backstop. Detection requires the complete\n * suffix pattern to repeat `stallLimit` times; recurring housekeeping calls among distinct productive\n * operations therefore never look like a loop merely because one signature is frequent.\n */\nconst STALL_WINDOW_PERIODS = 4;\n\n/** Identical observable results make a repeated cycle conclusive well before the coarse call-only fuse. */\nconst STAGNANT_RESULT_REPEAT_LIMIT = 3;\n\nfunction repeatsToolCallPattern(stallWindow: readonly string[], stallLimit: number): boolean {\n\tif (stallLimit <= 0) return false;\n\tconst maxPeriod = Math.min(STALL_WINDOW_PERIODS, Math.floor(stallWindow.length / stallLimit));\n\tfor (let period = 1; period <= maxPeriod; period++) {\n\t\tconst requiredTurns = period * stallLimit;\n\t\tconst start = stallWindow.length - requiredTurns;\n\t\tlet matches = true;\n\t\tfor (let offset = period; offset < requiredTurns; offset++) {\n\t\t\tif (stallWindow[start + offset] !== stallWindow[start + (offset % period)]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (matches) return true;\n\t}\n\treturn false;\n}\n\nfunction textProtocolOperationArguments(toolCall: AgentToolCall): unknown {\n\tconst args: unknown = toolCall.arguments;\n\tif (!args || typeof args !== \"object\" || Array.isArray(args)) return args ?? null;\n\tconst record = args as Record<string, unknown>;\n\tif ((toolCall.name === \"write\" || toolCall.name === \"edit\") && typeof record.path === \"string\") {\n\t\treturn { path: record.path };\n\t}\n\treturn args;\n}\n\nfunction textProtocolBatchSignature(toolCalls: readonly AgentToolCall[]): string {\n\treturn normalizeToolSignature(\n\t\ttoolCalls.map((toolCall) => [toolCall.name, textProtocolOperationArguments(toolCall)]),\n\t);\n}\n\n/** Hash only provider-visible result state; per-execution IDs/timestamps cannot hide a stagnant cycle. */\nfunction toolResultBatchSignature(toolResults: readonly ToolResultMessage[]): string {\n\treturn getToolExecutionKey(\n\t\t\"tool_result_batch\",\n\t\ttoolResults.map((result) => ({\n\t\t\ttoolName: result.toolName,\n\t\t\tcontent: result.content,\n\t\t\tisError: result.isError,\n\t\t})),\n\t);\n}\n\nfunction toolCallRecord(toolCall: AgentToolCall): Record<string, unknown> | undefined {\n\tconst args: unknown = toolCall.arguments;\n\treturn args && typeof args === \"object\" && !Array.isArray(args) ? (args as Record<string, unknown>) : undefined;\n}\n\nfunction toolResultPhase(result: ToolResultMessage): string | undefined {\n\tif (!result.details || typeof result.details !== \"object\" || Array.isArray(result.details)) return undefined;\n\tconst phase = (result.details as Record<string, unknown>).phase;\n\treturn typeof phase === \"string\" ? phase : undefined;\n}\n\nfunction repeatsSuccessfulTextProtocolBatch(\n\tincomingSignature: string,\n\ttoolCalls: readonly AgentToolCall[],\n\tprevious: SuccessfulTextProtocolBatch | undefined,\n): boolean {\n\tif (!previous) return false;\n\tif (incomingSignature === previous.signature) return true;\n\tif (toolCalls.length !== previous.calls.length || toolCalls.length !== previous.messages.length) return false;\n\treturn toolCalls.every((toolCall, index) => {\n\t\tconst previousCall = previous.calls[index];\n\t\tconst previousResult = previous.messages[index];\n\t\tif (!previousCall || !previousResult) return false;\n\t\tconst currentArgs = toolCallRecord(toolCall);\n\t\tconst previousArgs = toolCallRecord(previousCall);\n\t\tif (currentArgs?.path !== previousArgs?.path) return false;\n\t\tconst phase = toolResultPhase(previousResult);\n\t\tif (phase === \"written\") return toolCall.name === \"write\" && previousCall.name === \"write\";\n\t\treturn phase === \"edited\" && toolCall.name === \"edit\" && previousCall.name === \"edit\";\n\t});\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tinitialContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tinitialConfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tcontinuationState: AgentLoopContinuationState = createAgentLoopContinuationState(),\n): Promise<void> {\n\tlet currentContext = initialContext;\n\tlet config = initialConfig;\n\tlet firstTurn = true;\n\t// Runaway-loop backstop state: a sliding window of recent NORMALIZED tool-call signatures. A model\n\t// wedged repeating the same action makes no progress but keeps spending tokens; if one signature\n\t// recurs `stallLimit` times within the window we stop gracefully. Signatures are normalized so\n\t// volatile args (timestamps/UUIDs/nonces that change every call) can't disguise an otherwise-\n\t// identical call (bug #28). The window spans `stallLimit * STALL_WINDOW_PERIODS` turns so periodic\n\t// oscillation is caught too, not just back-to-back repeats: a cycle of period P repeats each\n\t// signature ~window/P times, so any P up to STALL_WINDOW_PERIODS reaches the threshold before the\n\t// window slides past it. Counts only turns that issued tool calls, so varied/long work never trips\n\t// it. `0` disables.\n\tconst stallLimit = config.maxStallTurns ?? DEFAULT_MAX_STALL_TURNS;\n\tconst providerTurnLimit = config.maxProviderTurns ?? DEFAULT_MAX_PROVIDER_TURNS;\n\tconst stallWindow = continuationState.stallWindow;\n\tlet stagnantResultWindow = continuationState.stagnantResultWindow;\n\tif (stagnantResultWindow === undefined) {\n\t\tstagnantResultWindow = [];\n\t\tcontinuationState.stagnantResultWindow = stagnantResultWindow;\n\t}\n\tconst validationFailureTracker: ToolValidationFailureTracker = { repeats: 0 };\n\tconst repairTeachTracker: ToolRepairTeachTracker = new Map();\n\tlet toolFailureMemory = createToolFailureMemoryTracker(currentContext.messages);\n\tconst toolFailureRecoveryGate = continuationState.toolFailureRecoveryGate;\n\ttoolFailureRecoveryGate.restoreFromMessages(currentContext.messages);\n\tlet lastSuccessfulTextProtocolBatch: SuccessfulTextProtocolBatch | undefined;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\tconst processPendingMessages = async (): Promise<void> => {\n\t\tif (pendingMessages.length === 0) return;\n\t\tlastSuccessfulTextProtocolBatch = undefined;\n\t\t// Only an owner/user turn can change authority or intent. Internal custom steering and\n\t\t// follow-up messages must not re-admit a known-bad unchanged operation. Count every owner\n\t\t// message so live admission stays byte-for-byte aligned with transcript restoration.\n\t\tfor (const message of pendingMessages) {\n\t\t\tif (message.role === \"user\") toolFailureRecoveryGate.noteWorldAdvance();\n\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\tcurrentContext.messages.push(message);\n\t\t\tnewMessages.push(message);\n\t\t}\n\t\tpendingMessages = [];\n\t};\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tif (providerTurnLimit > 0 && continuationState.providerTurns >= providerTurnLimit) {\n\t\t\t\t// Preserve already-dequeued steering, but do not announce an assistant turn that will\n\t\t\t\t// never start. A turn is one provider response plus its tools/results.\n\t\t\t\tawait processPendingMessages();\n\t\t\t\tawait emitProviderTurnLimitStop(config, continuationState, newMessages, emit);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Process pending messages (inject before next assistant response).\n\t\t\tawait processPendingMessages();\n\t\t\tcontinuationState.providerTurns++;\n\t\t\tconst response = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tconst message = response.message;\n\t\t\tnewMessages.push(message);\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tconst textProtocolBatch = toolCalls.every((toolCall) => toolCall.source === \"text-protocol\");\n\t\t\t\tconst incomingBatchSignature = textProtocolBatchSignature(toolCalls);\n\t\t\t\tconst previousSuccessfulTextProtocolResults =\n\t\t\t\t\ttextProtocolBatch &&\n\t\t\t\t\trepeatsSuccessfulTextProtocolBatch(incomingBatchSignature, toolCalls, lastSuccessfulTextProtocolBatch)\n\t\t\t\t\t\t? lastSuccessfulTextProtocolBatch?.messages\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst executedToolBatch = await executeToolCalls(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tmessage,\n\t\t\t\t\tresponse.requestId,\n\t\t\t\t\tconfig,\n\t\t\t\t\tvalidationFailureTracker,\n\t\t\t\t\trepairTeachTracker,\n\t\t\t\t\ttoolFailureMemory,\n\t\t\t\t\ttoolFailureRecoveryGate,\n\t\t\t\t\tpreviousSuccessfulTextProtocolResults,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\t\t\t\tif (!previousSuccessfulTextProtocolResults) {\n\t\t\t\t\tlastSuccessfulTextProtocolBatch =\n\t\t\t\t\t\ttextProtocolBatch &&\n\t\t\t\t\t\ttoolResults.length === toolCalls.length &&\n\t\t\t\t\t\ttoolResults.every((result) => !result.isError)\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tsignature: textProtocolBatchSignature(toolCalls),\n\t\t\t\t\t\t\t\t\tmessages: toolResults,\n\t\t\t\t\t\t\t\t\tcalls: toolCalls,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlastSuccessfulTextProtocolBatch = undefined;\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// Runaway-loop backstop (cost guard): detect only a repeated suffix cycle. Counting\n\t\t\t// signatures anywhere in the window falsely stopped progressing workflows whose status\n\t\t\t// checks recurred among distinct edits, reads, and verification operations.\n\t\t\tif (stallLimit > 0 && toolCalls.length > 0) {\n\t\t\t\tconst signature = normalizeToolSignature(toolCalls.map((c) => [c.name, c.arguments ?? null]));\n\t\t\t\tconst stagnantSignature = `${signature}:${toolResultBatchSignature(toolResults)}`;\n\t\t\t\tstagnantResultWindow.push(stagnantSignature);\n\t\t\t\tif (stagnantResultWindow.length > STAGNANT_RESULT_REPEAT_LIMIT * STALL_WINDOW_PERIODS) {\n\t\t\t\t\tstagnantResultWindow.shift();\n\t\t\t\t}\n\t\t\t\tif (repeatsToolCallPattern(stagnantResultWindow, STAGNANT_RESULT_REPEAT_LIMIT)) {\n\t\t\t\t\tconfig.onRunawayStop?.({\n\t\t\t\t\t\treason: \"stagnant_tool_cycle\",\n\t\t\t\t\t\tsignature,\n\t\t\t\t\t\trepeats: STAGNANT_RESULT_REPEAT_LIMIT,\n\t\t\t\t\t});\n\t\t\t\t\tawait streamToollessClosingTurn(\n\t\t\t\t\t\tcurrentContext,\n\t\t\t\t\t\tnewMessages,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tcontinuationState,\n\t\t\t\t\t\tproviderTurnLimit,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\temit,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t);\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstallWindow.push(signature);\n\t\t\t\tif (stallWindow.length > stallLimit * STALL_WINDOW_PERIODS) stallWindow.shift();\n\t\t\t\tif (repeatsToolCallPattern(stallWindow, stallLimit)) {\n\t\t\t\t\tconfig.onRunawayStop?.({ reason: \"repeated_tool_call\", signature, repeats: stallLimit });\n\t\t\t\t\tawait streamToollessClosingTurn(\n\t\t\t\t\t\tcurrentContext,\n\t\t\t\t\t\tnewMessages,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tcontinuationState,\n\t\t\t\t\t\tproviderTurnLimit,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\temit,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t);\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst nextTurnContext = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\t\t\tconst nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);\n\t\t\tif (nextTurnSnapshot) {\n\t\t\t\tcurrentContext = nextTurnSnapshot.context ?? currentContext;\n\t\t\t\tif (nextTurnSnapshot.context) {\n\t\t\t\t\ttoolFailureMemory = createToolFailureMemoryTracker(currentContext.messages);\n\t\t\t\t}\n\t\t\t\tconfig = {\n\t\t\t\t\t...config,\n\t\t\t\t\tmodel: nextTurnSnapshot.model ?? config.model,\n\t\t\t\t\treasoning: nextTurnSnapshot.thinkingLevel ?? config.reasoning,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tawait config.shouldStopAfterTurn?.({\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\tnewMessages,\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tif (followUpMessages.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nconst RUNAWAY_STOP_CLOSING_SYSTEM_PROMPT = [\n\t\"RUNAWAY STOP CLOSING TURN\",\n\t\"The host stopped a repeated tool-call loop. No tools are available in this final request.\",\n\t\"Write one concise factual closing message for the user: completed work, the unresolved operation or blocker, and the safest next action.\",\n\t\"Do not claim unperformed work. Do not emit a tool call or tool-call markup.\",\n].join(\"\\n\");\n\n/**\n * Spend one final provider request, with no tools, so a stopped run closes in the model's own words.\n *\n * The harness never writes that message itself. Tools are removed from the request, so this request\n * cannot open another tool batch and cannot re-enter the loop; it runs through the same planned\n * provider boundary as every other request. If the run is aborted, or the configured provider-turn\n * limit leaves no budget, the run ends with no closing message rather than a fabricated one — and a\n * provider error keeps its own error message for the same reason.\n */\nasync function streamToollessClosingTurn(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tcontinuationState: AgentLoopContinuationState,\n\tproviderTurnLimit: number,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tif (signal?.aborted) return;\n\tif (providerTurnLimit > 0 && continuationState.providerTurns >= providerTurnLimit) return;\n\tcontinuationState.providerTurns++;\n\tawait emit({ type: \"turn_start\" });\n\tconst closingContext: AgentContext = {\n\t\t...currentContext,\n\t\tsystemPrompt: currentContext.systemPrompt\n\t\t\t? `${currentContext.systemPrompt}\\n\\n${RUNAWAY_STOP_CLOSING_SYSTEM_PROMPT}`\n\t\t\t: RUNAWAY_STOP_CLOSING_SYSTEM_PROMPT,\n\t\ttools: [],\n\t};\n\tconst response = await streamAssistantResponse(closingContext, config, signal, emit, streamFn, {\n\t\trejectToolCalls: true,\n\t});\n\tconst message = response.message;\n\tnewMessages.push(message);\n\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n}\n\n/**\n * Start one provider request through the canonical agent-loop boundary.\n *\n * All callers, including host-owned tool-free finalization, receive the same failure-context\n * sanitization, context transformation/conversion, dynamic authentication, request-local reasoning,\n * and request preflight immediately before transport.\n */\nexport async function startAgentProviderRequest(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\tstreamFn?: StreamFn,\n): Promise<Awaited<ReturnType<StreamFn>>> {\n\treturn startPlannedAgentProviderRequest(context, config, signal, streamFn);\n}\n\ntype StartedAssistantResponse = {\n\tmessage: AssistantMessage;\n\trequestId: AgentRequestId;\n};\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tpolicy?: { rejectToolCalls: boolean },\n): Promise<StartedAssistantResponse> {\n\tconst degenerationAbort = new AbortController();\n\tconst onOuterAbort = (): void => degenerationAbort.abort();\n\tif (signal?.aborted) degenerationAbort.abort();\n\telse signal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\tconst response = await startPlannedAgentProviderRequestWithId(context, config, degenerationAbort.signal, streamFn);\n\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\tlet abortedForDegeneration = false;\n\n\tresponseEvents: for await (const event of response.stream) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tawait emit({\n\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\t!abortedForDegeneration &&\n\t\t\t\t\t\t!signal?.aborted &&\n\t\t\t\t\t\t!partialMessage.content.some((block) => block.type === \"toolCall\") &&\n\t\t\t\t\t\tshouldAbortDegenerateStream(assistantMessageText(partialMessage))\n\t\t\t\t\t) {\n\t\t\t\t\t\tabortedForDegeneration = true;\n\t\t\t\t\t\tdegenerationAbort.abort();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\":\n\t\t\t\tbreak responseEvents;\n\t\t}\n\t}\n\n\tsignal?.removeEventListener(\"abort\", onOuterAbort);\n\tconst providerMessage = await response.stream.result();\n\tlet finalMessage = policy?.rejectToolCalls\n\t\t? rejectToolCallsFromToolFreeResponse(providerMessage)\n\t\t: rejectNativeToolProtocolResidue(providerMessage, context.tools ?? [], Boolean(config.textToolCallProtocol));\n\tif (abortedForDegeneration && !signal?.aborted && finalMessage.stopReason === \"aborted\") {\n\t\tfinalMessage = { ...finalMessage, stopReason: \"stop\" };\n\t\tdelete finalMessage.errorMessage;\n\t}\n\tfinalMessage = collapseDegenerateAssistantMessage(finalMessage);\n\tif (addedPartial) {\n\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t} else {\n\t\tcontext.messages.push(finalMessage);\n\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t}\n\tawait emit({ type: \"message_end\", message: finalMessage });\n\treturn { message: finalMessage, requestId: response.requestId };\n}\n\ninterface ToolExecutionContext {\n\tcontext: AgentContext;\n\tassistantMessage: AssistantMessage;\n\trequestId: AgentRequestId;\n\tconfig: AgentLoopConfig;\n\tvalidationFailureTracker: ToolValidationFailureTracker;\n\trepairTeachTracker: ToolRepairTeachTracker;\n\ttoolFailureMemory: ToolFailureMemoryTracker;\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate;\n\tpreviousSuccessfulResults?: readonly ToolResultMessage[];\n\tsignal?: AbortSignal;\n\temit: AgentEventSink;\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\trequestId: AgentRequestId,\n\tconfig: AgentLoopConfig,\n\tvalidationFailureTracker: ToolValidationFailureTracker,\n\trepairTeachTracker: ToolRepairTeachTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tpreviousSuccessfulTextProtocolResults: readonly ToolResultMessage[] | undefined,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t(tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === \"sequential\",\n\t);\n\tconst execCtx: ToolExecutionContext = {\n\t\tcontext: currentContext,\n\t\tassistantMessage,\n\t\trequestId,\n\t\tconfig,\n\t\tvalidationFailureTracker,\n\t\trepairTeachTracker,\n\t\ttoolFailureMemory,\n\t\ttoolFailureRecoveryGate,\n\t\tpreviousSuccessfulResults: previousSuccessfulTextProtocolResults,\n\t\tsignal,\n\t\temit,\n\t};\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\n\t\treturn executeToolCallsSequential(execCtx, toolCalls);\n\t}\n\treturn executeToolCallsParallel(execCtx, toolCalls);\n}\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\tterminate: boolean;\n};\n\ntype SuccessfulTextProtocolBatch = {\n\tsignature: string;\n\tmessages: readonly ToolResultMessage[];\n\tcalls: readonly AgentToolCall[];\n};\n\ntype StartedToolCall =\n\t| { kind: \"finalized\"; finalized: FinalizedToolCallOutcome }\n\t| { kind: \"prepared\"; preparation: PreparedToolCall };\n\nasync function prepareAndStartToolCall(\n\texecCtx: ToolExecutionContext,\n\ttoolCall: AgentToolCall,\n\tindex: number,\n): Promise<StartedToolCall> {\n\tconst preparation = execCtx.previousSuccessfulResults\n\t\t? createRepeatedSuccessfulToolCallOutcome(execCtx.previousSuccessfulResults[index])\n\t\t: await prepareToolCall(\n\t\t\t\texecCtx.context,\n\t\t\t\texecCtx.assistantMessage,\n\t\t\t\ttoolCall,\n\t\t\t\texecCtx.config,\n\t\t\t\texecCtx.validationFailureTracker,\n\t\t\t\texecCtx.toolFailureMemory,\n\t\t\t\texecCtx.toolFailureRecoveryGate,\n\t\t\t\texecCtx.signal,\n\t\t\t\texecCtx.requestId,\n\t\t\t);\n\tif (preparation.kind === \"immediate\") {\n\t\tawait emitToolExecutionStart(toolCall, execCtx.emit);\n\t\temitToolArgumentValidationTelemetry(execCtx.config, preparation.validationEvent, \"not_run\", \"none\");\n\t\treturn {\n\t\t\tkind: \"finalized\",\n\t\t\tfinalized: finalizeRejectedToolCall(\n\t\t\t\ttoolCall,\n\t\t\t\texecCtx.context.tools?.find((tool) => tool.name === toolCall.name),\n\t\t\t\tpreparation,\n\t\t\t\texecCtx.toolFailureMemory,\n\t\t\t),\n\t\t};\n\t}\n\treturn { kind: \"prepared\", preparation };\n}\n\nasync function finalizeStartedToolCall(\n\texecCtx: ToolExecutionContext,\n\tstarted: StartedToolCall,\n): Promise<FinalizedToolCallOutcome> {\n\tif (started.kind === \"finalized\") return started.finalized;\n\treturn executeAndFinalizePreparedToolCall(\n\t\texecCtx.context,\n\t\texecCtx.assistantMessage,\n\t\tstarted.preparation,\n\t\texecCtx.requestId,\n\t\texecCtx.config,\n\t\texecCtx.repairTeachTracker,\n\t\texecCtx.toolFailureMemory,\n\t\texecCtx.toolFailureRecoveryGate,\n\t\texecCtx.signal,\n\t\texecCtx.emit,\n\t);\n}\n\nasync function reservePreparedToolCalls(\n\texecCtx: ToolExecutionContext,\n\tpreparedCalls: readonly PreparedToolCall[],\n): Promise<void> {\n\tif (preparedCalls.length === 0) return;\n\texecCtx.signal?.throwIfAborted();\n\tif (execCtx.config.onToolCallStart) {\n\t\tconst calls: ToolCallStartContext[] = preparedCalls.map((prepared) => ({\n\t\t\trequestId: execCtx.requestId,\n\t\t\tcallId: prepared.toolCall.id,\n\t\t\ttoolName: prepared.toolCall.name,\n\t\t\tassistantMessage: execCtx.assistantMessage,\n\t\t\ttoolCall: prepared.toolCall,\n\t\t\targs: prepared.args,\n\t\t\tcontext: execCtx.context,\n\t\t}));\n\t\tawait execCtx.config.onToolCallStart(calls, execCtx.signal);\n\t}\n\texecCtx.signal?.throwIfAborted();\n\tfor (const prepared of preparedCalls) {\n\t\tawait emitToolExecutionStart(prepared.toolCall, execCtx.emit);\n\t}\n}\n\nasync function executeToolCallsSequential(\n\texecCtx: ToolExecutionContext,\n\ttoolCalls: AgentToolCall[],\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\n\tfor (const [index, toolCall] of toolCalls.entries()) {\n\t\tconst started = await prepareAndStartToolCall(execCtx, toolCall, index);\n\t\tif (started.kind === \"prepared\") {\n\t\t\tawait reservePreparedToolCalls(execCtx, [started.preparation]);\n\t\t}\n\t\tconst finalized = await finalizeStartedToolCall(execCtx, started);\n\t\texecCtx.toolFailureRecoveryGate.apply(finalized.executionGateEffect);\n\n\t\tawait emitToolExecutionEnd(finalized, execCtx.emit);\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tawait emitToolResultMessage(toolResultMessage, execCtx.emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(toolResultMessage);\n\n\t\tif (execCtx.signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn { messages, terminate: shouldTerminateToolBatch(finalizedCalls) };\n}\n\nasync function executeToolCallsParallel(\n\texecCtx: ToolExecutionContext,\n\ttoolCalls: AgentToolCall[],\n): Promise<ExecutedToolCallBatch> {\n\tconst orderedFinalizedCalls: FinalizedToolCallOutcome[] = [];\n\tlet nextIndex = 0;\n\t// Account each bounded concurrent wave before launching more calls. This controls concurrency;\n\t// admission remains operation-specific and does not stop unrelated work after failures.\n\twhile (nextIndex < toolCalls.length && !execCtx.signal?.aborted) {\n\t\tconst waveEnd = Math.min(nextIndex + TOOL_EXECUTION_WAVE_SIZE, toolCalls.length);\n\t\tconst wave: FinalizedToolCallEntry[] = [];\n\t\tconst preparedWave: PreparedToolCall[] = [];\n\t\tconst completionOrder: FinalizedToolCallOutcome[] = [];\n\t\tfor (; nextIndex < waveEnd; nextIndex++) {\n\t\t\tconst toolCall = toolCalls[nextIndex];\n\t\t\tconst started = await prepareAndStartToolCall(execCtx, toolCall, nextIndex);\n\t\t\tif (started.kind === \"finalized\") {\n\t\t\t\tawait emitToolExecutionEnd(started.finalized, execCtx.emit);\n\t\t\t\twave.push(started.finalized);\n\t\t\t} else {\n\t\t\t\tpreparedWave.push(started.preparation);\n\t\t\t\twave.push(async () => {\n\t\t\t\t\tconst finalized = await finalizeStartedToolCall(execCtx, started);\n\t\t\t\t\tcompletionOrder.push(finalized);\n\t\t\t\t\treturn finalized;\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (execCtx.signal?.aborted) {\n\t\t\t\tnextIndex++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tawait reservePreparedToolCalls(execCtx, preparedWave);\n\n\t\tconst finalizedWave = await Promise.all(\n\t\t\twave.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t\t);\n\t\tfor (const finalized of finalizedWave) execCtx.toolFailureRecoveryGate.apply(finalized.executionGateEffect);\n\t\tfor (const finalized of completionOrder) {\n\t\t\tawait emitToolExecutionEnd(finalized, execCtx.emit);\n\t\t}\n\t\torderedFinalizedCalls.push(...finalizedWave);\n\t}\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tawait emitToolResultMessage(toolResultMessage, execCtx.emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\treturn { messages, terminate: shouldTerminateToolBatch(orderedFinalizedCalls) };\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n\tvalidationEvent?: ToolArgumentValidationTelemetryEvent;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tcorrection: string;\n\tdiagnostic?: string;\n\trepeatedSuccessfulCall?: { previousToolCallId: string };\n\trepeatedToolFailure?: boolean;\n\tvalidationEvent?: ToolArgumentValidationTelemetryEvent;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\terrorClass?: string;\n\tfailureMessage?: string;\n\tfailureCode?: string;\n\toutputSignature?: string;\n\terrorKind?: AgentToolErrorKind;\n};\n\ntype FinalizedToolCallOutcome = {\n\ttoolCall: AgentToolCall;\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\texecutionGateEffect?: ToolFailureRecoveryGateEffect;\n};\n\ntype FinalizedToolCallEntry = FinalizedToolCallOutcome | (() => Promise<FinalizedToolCallOutcome>);\n\ntype ToolValidationFailureTracker = {\n\tsignature?: string;\n\trepeats: number;\n\tescalatedSignature?: string;\n};\n\ntype ToolRepairTeachTracker = Map<string, number>;\n\nconst DEFAULT_TOOL_VALIDATION_ESCALATION_THRESHOLD = 3;\nconst TOOL_REPAIR_TEACH_EVERY = 5;\nconst REPEATED_SUCCESS_RESULT_MAX_CHARS = 2_048;\n\nfunction createRepeatedSuccessfulToolCallOutcome(\n\tpreviousResult: ToolResultMessage | undefined,\n): ImmediateToolCallOutcome {\n\tconst previousText = previousResult?.content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\")\n\t\t.slice(0, REPEATED_SUCCESS_RESULT_MAX_CHARS);\n\tconst diagnostic = previousText\n\t\t? `${REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.diagnostic} Previous successful result: ${previousText}`\n\t\t: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.diagnostic;\n\treturn {\n\t\tkind: \"immediate\",\n\t\tresult: createErrorToolResult(diagnostic),\n\t\tisError: true,\n\t\tphase: \"execution\",\n\t\tfailureCode: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.failureCode,\n\t\tcorrection: REPEATED_SUCCESSFUL_TOOL_CALL_FAILURE.guidance,\n\t\tdiagnostic,\n\t\t...(previousResult ? { repeatedSuccessfulCall: { previousToolCallId: previousResult.toolCallId } } : {}),\n\t};\n}\n\nfunction createAbortedToolCallOutcome(\n\tvalidationEvent: ToolArgumentValidationTelemetryEvent | undefined,\n): ImmediateToolCallOutcome {\n\treturn {\n\t\tkind: \"immediate\",\n\t\tresult: createErrorToolResult(\"Operation aborted\"),\n\t\tisError: true,\n\t\tphase: \"cancelled\",\n\t\tfailureCode: \"aborted\",\n\t\tcorrection: \"Retry only if the operation is still required.\",\n\t\tvalidationEvent,\n\t};\n}\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nfunction createValidationBounceTelemetry(\n\tconfig: AgentLoopConfig,\n\ttoolCall: AgentToolCall,\n\terrorKeyword: string,\n): ToolArgumentValidationTelemetryEvent {\n\treturn {\n\t\toutcome: \"bounced\",\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\ttool: toolCall.name,\n\t\tsource: toolCall.source,\n\t\tfailureModes: [\"other\"],\n\t\trepairsApplied: [],\n\t\terrorKeywords: [errorKeyword],\n\t\ttaught: \"none\",\n\t\texecutionOutcome: \"not_run\",\n\t};\n}\n\nfunction validationFailureCorrection(\n\tevent: ToolArgumentValidationTelemetryEvent | undefined,\n\ttoolName: string,\n): string {\n\tconst shape = event?.failureShape\n\t\t?.slice(0, 3)\n\t\t.map((entry) => `${entry.path}: expected ${entry.expectedType}, received ${entry.receivedType}`)\n\t\t.join(\"; \");\n\tconst rules = [\n\t\t...new Set(\n\t\t\t(event?.failureModes ?? [])\n\t\t\t\t.filter((mode) => mode !== \"other\")\n\t\t\t\t.map((mode) => formatToolRepairStandingRule(mode)),\n\t\t),\n\t];\n\treturn [`Match ${toolName} arguments to its current schema.`, shape ? `Fix ${shape}.` : undefined, ...rules]\n\t\t.filter((part): part is string => part !== undefined)\n\t\t.join(\" \");\n}\n\nfunction resetValidationFailureTracker(tracker: ToolValidationFailureTracker): void {\n\ttracker.signature = undefined;\n\ttracker.repeats = 0;\n}\n\nfunction emitToolArgumentValidationTelemetry(\n\tconfig: AgentLoopConfig,\n\tevent: ToolArgumentValidationTelemetryEvent | undefined,\n\texecutionOutcome: ToolArgumentExecutionOutcome,\n\ttaught: ToolArgumentValidationTelemetryEvent[\"taught\"],\n): void {\n\tif (!event) return;\n\tconfig.onToolArgumentValidation?.({ ...event, executionOutcome, taught });\n}\n\nfunction toolValidationEscalationThreshold(config: AgentLoopConfig): number {\n\treturn config.toolValidationEscalationThreshold ?? DEFAULT_TOOL_VALIDATION_ESCALATION_THRESHOLD;\n}\n\nfunction isToolArgumentRepairEmergencyDisabled(): boolean {\n\tconst env = typeof process === \"object\" && process ? process.env : undefined;\n\tconst value = env?.PI_TOOL_REPAIR_DISABLED;\n\tif (!value) return false;\n\treturn [\"1\", \"true\", \"yes\", \"on\"].includes(value.trim().toLowerCase());\n}\n\nfunction isToolArgumentValidationError(error: unknown): error is ToolArgumentValidationError {\n\treturn (\n\t\terror instanceof ToolArgumentValidationError ||\n\t\t(error instanceof Error &&\n\t\t\terror.name === \"ToolArgumentValidationError\" &&\n\t\t\ttypeof (error as { toolName?: unknown }).toolName === \"string\" &&\n\t\t\ttypeof (error as { signature?: unknown }).signature === \"string\" &&\n\t\t\ttypeof (error as { enrichment?: unknown }).enrichment === \"string\")\n\t);\n}\n\nfunction handleValidationFailure(\n\terror: ToolArgumentValidationError,\n\tconfig: AgentLoopConfig,\n\ttracker: ToolValidationFailureTracker,\n): string {\n\tif (tracker.signature === error.signature) {\n\t\ttracker.repeats++;\n\t} else {\n\t\ttracker.signature = error.signature;\n\t\ttracker.repeats = 1;\n\t\ttracker.escalatedSignature = undefined;\n\t}\n\n\tconst threshold = toolValidationEscalationThreshold(config);\n\tif (threshold <= 0 || tracker.repeats < threshold || tracker.escalatedSignature === error.signature) {\n\t\treturn error.message;\n\t}\n\n\ttracker.escalatedSignature = error.signature;\n\tconfig.onToolValidationEscalation?.({\n\t\ttool: error.toolName,\n\t\tsignature: error.signature,\n\t\trepeats: tracker.repeats,\n\t\tmodel: config.model.id,\n\t\tprovider: config.model.provider,\n\t});\n\treturn `${error.message}\\n\\nRepeated validation failure (${tracker.repeats} identical attempts). Use this full schema and example before retrying:\\n${error.enrichment}`;\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tvalidationFailureTracker: ToolValidationFailureTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tsignal: AbortSignal | undefined,\n\trequestId: AgentRequestId,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((candidate) => candidate.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t\tphase: \"validation\",\n\t\t\tfailureCode: \"unknown_tool\",\n\t\t\tcorrection: \"Choose a tool from the currently available tool list.\",\n\t\t\tvalidationEvent: createValidationBounceTelemetry(config, toolCall, \"unknown_tool\"),\n\t\t};\n\t}\n\n\tif (toolCall.errorMessage) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(toolCall.errorMessage),\n\t\t\tisError: true,\n\t\t\tphase: \"validation\",\n\t\t\tfailureCode: \"malformed_call\",\n\t\t\tcorrection: \"Resend one complete JSON argument object matching the current tool schema.\",\n\t\t\tvalidationEvent: createValidationBounceTelemetry(config, toolCall, \"malformed_call\"),\n\t\t};\n\t}\n\n\tlet validationEvent: ToolArgumentValidationTelemetryEvent | undefined;\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall, {\n\t\t\tmodel: config.model.id,\n\t\t\tprovider: config.model.provider,\n\t\t\trepairEnabled: !isToolArgumentRepairEmergencyDisabled(),\n\t\t\ttelemetry: (event) => {\n\t\t\t\tvalidationEvent = event;\n\t\t\t},\n\t\t});\n\t\tresetValidationFailureTracker(validationFailureTracker);\n\t\tif (preparedToolCall.repairNotes) {\n\t\t\ttoolCall.repairNotes = preparedToolCall.repairNotes;\n\t\t}\n\t\tif (validatedArgs !== toolCall.arguments) {\n\t\t\ttoolCall.rawArguments ??= toolCall.arguments;\n\t\t\ttoolCall.arguments = validatedArgs;\n\t\t}\n\t\tconst unresolvedRecord = getUnresolvedToolFailure(toolFailureMemory, toolCall.name, validatedArgs);\n\t\tconst admission = toolFailureRecoveryGate.admit(tool, validatedArgs, unresolvedRecord, currentContext.messages);\n\t\tif (admission.kind === \"blocked\") {\n\t\t\tconst result = createRepeatedToolFailureResult(admission.record);\n\t\t\tconst memoryRecord = result.details.piToolFailureMemory;\n\t\t\ttoolFailureMemory.set(admission.record.failureKey, memoryRecord);\n\t\t\treturn {\n\t\t\t\tkind: \"immediate\",\n\t\t\t\tresult,\n\t\t\t\tisError: true,\n\t\t\t\tphase: admission.record.phase,\n\t\t\t\tfailureCode: \"repeated_failed_operation\",\n\t\t\t\tcorrection: memoryRecord.correction,\n\t\t\t\tdiagnostic: memoryRecord.diagnostic,\n\t\t\t\trepeatedToolFailure: true,\n\t\t\t\tvalidationEvent: createValidationBounceTelemetry(config, toolCall, \"repeated_failed_operation\"),\n\t\t\t};\n\t\t}\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\trequestId,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (signal?.aborted) {\n\t\t\t\treturn createAbortedToolCallOutcome(validationEvent);\n\t\t\t}\n\t\t\tif (beforeResult?.block) {\n\t\t\t\tconst reason = beforeResult.reason || \"Tool execution was blocked\";\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(reason),\n\t\t\t\t\tisError: true,\n\t\t\t\t\tphase: \"policy\",\n\t\t\t\t\tfailureCode: \"blocked\",\n\t\t\t\t\tcorrection: \"Choose an allowed approach or request the required authority before retrying.\",\n\t\t\t\t\tdiagnostic: reason,\n\t\t\t\t\tvalidationEvent,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (signal?.aborted) {\n\t\t\treturn createAbortedToolCallOutcome(validationEvent);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t\tvalidationEvent,\n\t\t};\n\t} catch (error) {\n\t\tconst message = isToolArgumentValidationError(error)\n\t\t\t? handleValidationFailure(error, config, validationFailureTracker)\n\t\t\t: error instanceof Error\n\t\t\t\t? error.message\n\t\t\t\t: String(error);\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(message),\n\t\t\tisError: true,\n\t\t\tphase: isToolArgumentValidationError(error) ? \"validation\" : \"preflight\",\n\t\t\tfailureCode: isToolArgumentValidationError(error) ? \"invalid_arguments\" : \"preflight_error\",\n\t\t\tcorrection: isToolArgumentValidationError(error)\n\t\t\t\t? validationFailureCorrection(validationEvent, toolCall.name)\n\t\t\t\t: toolFailureCorrection(message, \"rejected\", \"preflight\"),\n\t\t\tdiagnostic: isToolArgumentValidationError(error) ? undefined : message,\n\t\t\tvalidationEvent,\n\t\t};\n\t}\n}\n\nfunction finalizeRejectedToolCall(\n\ttoolCall: AgentToolCall,\n\ttool: AgentTool<any> | undefined,\n\toutcome: ImmediateToolCallOutcome,\n\ttracker: ToolFailureMemoryTracker,\n): FinalizedToolCallOutcome {\n\tif (outcome.repeatedToolFailure) {\n\t\treturn {\n\t\t\ttoolCall,\n\t\t\tresult: outcome.result,\n\t\t\tisError: true,\n\t\t};\n\t}\n\tconst record = rememberToolFailure(\n\t\ttracker,\n\t\ttoolCall.name,\n\t\ttoolCall.arguments,\n\t\t\"rejected\",\n\t\toutcome.failureCode,\n\t\toutcome.correction,\n\t\toutcome.diagnostic,\n\t\toutcome.phase,\n\t\tundefined,\n\t\t{\n\t\t\toutput: outcome.result.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\"),\n\t\t},\n\t);\n\tconst failureResult = createToolFailureResult(record, outcome.result.terminate);\n\treturn {\n\t\ttoolCall,\n\t\tresult: outcome.repeatedSuccessfulCall\n\t\t\t? {\n\t\t\t\t\t...failureResult,\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\t...failureResult.details,\n\t\t\t\t\t\tpiRepeatedSuccessfulCall: outcome.repeatedSuccessfulCall,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: failureResult,\n\t\tisError: true,\n\t\texecutionGateEffect: {\n\t\t\tkind: \"unproductive\",\n\t\t\t...(tool ? { tool } : {}),\n\t\t\trecord,\n\t\t\targs: toolCall.arguments,\n\t\t},\n\t};\n}\n\ntype LinkedToolAbort = {\n\tsignal: AbortSignal;\n\tdetachForeground(): void;\n\tcancel(): void;\n};\n\nfunction createLinkedToolAbort(foregroundSignal: AbortSignal | undefined): LinkedToolAbort {\n\tconst controller = new AbortController();\n\tconst abortFromForeground = (): void => controller.abort(foregroundSignal?.reason);\n\tlet linked = false;\n\tif (foregroundSignal?.aborted) {\n\t\tabortFromForeground();\n\t} else if (foregroundSignal) {\n\t\tforegroundSignal.addEventListener(\"abort\", abortFromForeground, { once: true });\n\t\tlinked = true;\n\t}\n\treturn {\n\t\tsignal: controller.signal,\n\t\tdetachForeground: () => {\n\t\t\tif (!linked || !foregroundSignal) return;\n\t\t\tforegroundSignal.removeEventListener(\"abort\", abortFromForeground);\n\t\t\tlinked = false;\n\t\t},\n\t\tcancel: () => controller.abort(),\n\t};\n}\n\nfunction getBackgroundToolCallDelay(config: AgentLoopConfig): number | undefined {\n\tconst delay = config.backgroundToolCallAfterMs;\n\tif (delay === undefined || !Number.isFinite(delay) || delay <= 0) return undefined;\n\treturn delay;\n}\n\nasync function executeAndFinalizePreparedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\trequestId: AgentRequestId,\n\tconfig: AgentLoopConfig,\n\trepairTeachTracker: ToolRepairTeachTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tforegroundSignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<FinalizedToolCallOutcome> {\n\tconst backgroundDelay = getBackgroundToolCallDelay(config);\n\tif (\n\t\t!config.handoffToolCall ||\n\t\t(backgroundDelay === undefined && config.subscribeToolCallHandoffRequest === undefined)\n\t) {\n\t\tconst executed = await executePreparedToolCall(prepared, foregroundSignal, emit);\n\t\treturn finalizeExecutedToolCall(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\tprepared,\n\t\t\trequestId,\n\t\t\texecuted,\n\t\t\tconfig,\n\t\t\trepairTeachTracker,\n\t\t\ttoolFailureMemory,\n\t\t\ttoolFailureRecoveryGate,\n\t\t\tforegroundSignal,\n\t\t);\n\t}\n\n\tconst executionAbort = createLinkedToolAbort(foregroundSignal);\n\tconst startedAt = Date.now();\n\tlet emitForegroundUpdates = true;\n\tconst completion = (async (): Promise<FinalizedToolCallOutcome> => {\n\t\tconst executed = await executePreparedToolCall(prepared, executionAbort.signal, (event) => {\n\t\t\tif (emitForegroundUpdates) return emit(event);\n\t\t});\n\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\tprepared,\n\t\t\trequestId,\n\t\t\texecuted,\n\t\t\tconfig,\n\t\t\trepairTeachTracker,\n\t\t\ttoolFailureMemory,\n\t\t\ttoolFailureRecoveryGate,\n\t\t\texecutionAbort.signal,\n\t\t);\n\t\treturn finalized;\n\t})();\n\tcompletion.then(executionAbort.detachForeground, executionAbort.detachForeground);\n\n\tlet deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst triggers: Array<Promise<{ kind: \"deadline\" | \"manual\" }>> = [];\n\tif (backgroundDelay !== undefined) {\n\t\ttriggers.push(\n\t\t\tnew Promise<{ kind: \"deadline\" }>((resolve) => {\n\t\t\t\tdeadlineTimer = setTimeout(() => resolve({ kind: \"deadline\" }), backgroundDelay);\n\t\t\t\t(deadlineTimer as { unref?: () => void }).unref?.();\n\t\t\t}),\n\t\t);\n\t}\n\tlet unsubscribeHandoffRequest: (() => void) | undefined;\n\tif (config.subscribeToolCallHandoffRequest) {\n\t\tconst manual = new Promise<{ kind: \"manual\" }>((resolve) => {\n\t\t\ttry {\n\t\t\t\tunsubscribeHandoffRequest = config.subscribeToolCallHandoffRequest?.(prepared.toolCall.id, () =>\n\t\t\t\t\tresolve({ kind: \"manual\" }),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tunsubscribeHandoffRequest = undefined;\n\t\t\t}\n\t\t});\n\t\ttriggers.push(manual);\n\t}\n\tlet outcome: { kind: \"completed\"; value: FinalizedToolCallOutcome } | { kind: \"deadline\" | \"manual\" };\n\ttry {\n\t\toutcome = await Promise.race([completion.then((value) => ({ kind: \"completed\" as const, value })), ...triggers]);\n\t} finally {\n\t\tif (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n\t\tunsubscribeHandoffRequest?.();\n\t}\n\tif (outcome.kind === \"completed\") return outcome.value;\n\tif (executionAbort.signal.aborted) return completion;\n\n\tlet handoffAccepted = false;\n\t// A handed-off call leaves the batch, so the batch never applies its effect: the background\n\t// completion is the only place left that can tell the governor what this operation did.\n\tconst handedOffCompletion = completion.then((finalized) => {\n\t\tif (handoffAccepted) toolFailureRecoveryGate.apply(finalized.executionGateEffect);\n\t\treturn finalized;\n\t});\n\tvoid handedOffCompletion.catch(() => undefined);\n\tlet handoff: ReturnType<NonNullable<AgentLoopConfig[\"handoffToolCall\"]>>;\n\ttry {\n\t\thandoff = config.handoffToolCall({\n\t\t\trequestId,\n\t\t\tassistantMessage,\n\t\t\ttoolCall: prepared.toolCall,\n\t\t\targs: prepared.args,\n\t\t\tcontext: currentContext,\n\t\t\telapsedMs: Math.max(0, Date.now() - startedAt),\n\t\t\tcompletion: handedOffCompletion,\n\t\t\tcancel: executionAbort.cancel,\n\t\t});\n\t} catch {\n\t\treturn completion;\n\t}\n\thandoffAccepted = handoff !== undefined;\n\tif (!handoff) return completion;\n\n\temitForegroundUpdates = false;\n\texecutionAbort.detachForeground();\n\treturn {\n\t\ttoolCall: prepared.toolCall,\n\t\tresult: handoff.result,\n\t\tisError: handoff.isError ?? handoff.result.isError === true,\n\t};\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult,\n\t\t\t// Tool definitions can report an expected operation failure without\n\t\t\t// throwing. Keep the returned result intact through afterToolCall so\n\t\t\t// policy hooks can inspect its bounded diagnostics and metadata.\n\t\t\tisError: result.isError === true,\n\t\t\t...(result.isError === true\n\t\t\t\t? { errorClass: \"tool_result_error\", errorKind: result.errorKind ?? \"tool_failure\" }\n\t\t\t\t: {}),\n\t\t};\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst toolFailure = error instanceof AgentToolExecutionError ? error : undefined;\n\t\treturn {\n\t\t\tresult: createErrorToolResult(message),\n\t\t\tisError: true,\n\t\t\terrorClass: error instanceof Error ? error.name : typeof error,\n\t\t\tfailureMessage: message,\n\t\t\terrorKind: toolFailure?.errorKind ?? \"tool_failure\",\n\t\t\t...(toolFailure ? { failureCode: toolFailure.failureCode, outputSignature: toolFailure.outputSignature } : {}),\n\t\t};\n\t}\n}\n\nfunction repairTeachKey(toolName: string, note: string): string {\n\tconst repairName = /^\\[harness\\] ([^:]+):/.exec(note)?.[1] ?? note;\n\treturn `${toolName}\\0${repairName}`;\n}\n\nfunction shouldEmitRepairTeachNote(toolName: string, note: string, tracker: ToolRepairTeachTracker): boolean {\n\tconst key = repairTeachKey(toolName, note);\n\tconst count = (tracker.get(key) ?? 0) + 1;\n\ttracker.set(key, count);\n\treturn count === 1 || count % TOOL_REPAIR_TEACH_EVERY === 0;\n}\n\nfunction appendRepairTeachNotes(\n\tresult: AgentToolResult<any>,\n\ttoolCall: AgentToolCall,\n\ttracker: ToolRepairTeachTracker,\n\tconfig: AgentLoopConfig,\n): { result: AgentToolResult<any>; taught: boolean } {\n\tif (config.toolArgumentTeachEnabled === false) return { result, taught: false };\n\tconst notes = (toolCall.repairNotes ?? []).filter((note) => shouldEmitRepairTeachNote(toolCall.name, note, tracker));\n\tif (notes.length === 0) return { result, taught: false };\n\treturn {\n\t\tresult: {\n\t\t\t...result,\n\t\t\tcontent: [...result.content, { type: \"text\", text: notes.join(\"\\n\") }],\n\t\t},\n\t\ttaught: true,\n\t};\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\trequestId: AgentRequestId,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\trepairTeachTracker: ToolRepairTeachTracker,\n\ttoolFailureMemory: ToolFailureMemoryTracker,\n\ttoolFailureRecoveryGate: ToolFailureRecoveryGate,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\tlet failureMessage = executed.failureMessage ?? \"\";\n\tlet errorClass = executed.errorClass;\n\tlet failureCode = executed.failureCode;\n\tlet outputSignature = executed.outputSignature;\n\tlet errorKind = executed.errorKind;\n\tlet executionGateEffect: ToolFailureRecoveryGateEffect | undefined;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await config.afterToolCall(\n\t\t\t\t{\n\t\t\t\t\trequestId,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\targs: prepared.args,\n\t\t\t\t\tresult,\n\t\t\t\t\tisError,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tusage: afterResult.usage ?? result.usage,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// The hook itself failed, so nothing about the tool's own completed operation survives.\n\t\t\tfailureMessage = error instanceof Error ? error.message : String(error);\n\t\t\terrorClass = error instanceof Error ? error.name : typeof error;\n\t\t\tfailureCode = undefined;\n\t\t\toutputSignature = undefined;\n\t\t\terrorKind = \"tool_failure\";\n\t\t\tresult = { ...createErrorToolResult(failureMessage), usage: result.usage };\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\tif (isError) {\n\t\tconst usage = result.usage;\n\t\tconst failureOutput =\n\t\t\tfailureMessage ||\n\t\t\tresult.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\"Tool execution failed\";\n\t\tconst effectiveFailureMessage =\n\t\t\tfailureMessage || result.content.find((block) => block.type === \"text\")?.text || \"Tool execution failed\";\n\t\tconst assessment = assessToolFailure(effectiveFailureMessage, \"failed\", errorClass);\n\t\tconst effectiveFailureCode = failureCode ?? assessment.failureCode;\n\t\tif (errorKind === \"operation_outcome\") {\n\t\t\t// The tool ran the operation to completion; the non-zero status is the observation the\n\t\t\t// agent asked for. Nothing here is a mistake, so no failure record is remembered and the\n\t\t\t// tool's own output stands exactly as written. The governor still notes that repeating\n\t\t\t// this identical operation cannot say anything new until something else changes.\n\t\t\tclearToolFailure(toolFailureMemory, prepared.toolCall.name, prepared.args);\n\t\t\tresult = { ...result, errorKind: \"operation_outcome\", usage };\n\t\t\texecutionGateEffect = {\n\t\t\t\tkind: \"unproductive\",\n\t\t\t\ttool: prepared.tool,\n\t\t\t\trecord: describeOperationOutcome(\n\t\t\t\t\tprepared.toolCall.name,\n\t\t\t\t\tprepared.args,\n\t\t\t\t\teffectiveFailureCode,\n\t\t\t\t\tassessment.diagnostic,\n\t\t\t\t),\n\t\t\t\targs: prepared.args,\n\t\t\t};\n\t\t} else {\n\t\t\tconst recoveryPlan = toolFailureRecoveryGate.planFailure(\n\t\t\t\tprepared.tool,\n\t\t\t\tprepared.args,\n\t\t\t\t{ failureCode: effectiveFailureCode, message: effectiveFailureMessage },\n\t\t\t\tcurrentContext.tools ?? [],\n\t\t\t);\n\t\t\tconst correction = assessment.policyGuidance\n\t\t\t\t? `${assessment.policyGuidance} ${recoveryPlan.guidance}`\n\t\t\t\t: recoveryPlan.guidance;\n\t\t\tconst record = rememberToolFailure(\n\t\t\t\ttoolFailureMemory,\n\t\t\t\tprepared.toolCall.name,\n\t\t\t\tprepared.args,\n\t\t\t\t\"failed\",\n\t\t\t\teffectiveFailureCode,\n\t\t\t\tcorrection,\n\t\t\t\tassessment.diagnostic,\n\t\t\t\tassessment.phase,\n\t\t\t\trecoveryPlan.evidence ?? assessment.evidence,\n\t\t\t\t{ output: failureOutput, outputSignature },\n\t\t\t);\n\t\t\texecutionGateEffect = {\n\t\t\t\tkind: \"unproductive\",\n\t\t\t\ttool: prepared.tool,\n\t\t\t\trecord,\n\t\t\t\targs: prepared.args,\n\t\t\t};\n\t\t\tresult = { ...createToolFailureResult(record, result.terminate), usage };\n\t\t}\n\t} else {\n\t\tclearToolFailure(toolFailureMemory, prepared.toolCall.name, prepared.args);\n\t\tif (!executed.isError) {\n\t\t\texecutionGateEffect = {\n\t\t\t\tkind: \"success\",\n\t\t\t\ttool: prepared.tool,\n\t\t\t\targs: prepared.args,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst repaired = isError\n\t\t? { result, taught: false }\n\t\t: appendRepairTeachNotes(result, prepared.toolCall, repairTeachTracker, config);\n\temitToolArgumentValidationTelemetry(\n\t\tconfig,\n\t\tprepared.validationEvent,\n\t\tisError ? \"failed\" : \"succeeded\",\n\t\trepaired.taught ? \"note\" : \"none\",\n\t);\n\n\treturn {\n\t\ttoolCall: prepared.toolCall,\n\t\tresult: repaired.result,\n\t\tisError,\n\t\texecutionGateEffect,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function emitToolExecutionStart(toolCall: AgentToolCall, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\targs: toolCall.arguments,\n\t\trepair: getToolCallRepairInfo(toolCall),\n\t});\n}\n\nexport function getToolCallRepairInfo(toolCall: AgentToolCall): ToolCallRepairInfo | undefined {\n\tif (!toolCall.rawArguments && !toolCall.repairNotes?.length) return undefined;\n\treturn {\n\t\trepaired: true,\n\t\t...(toolCall.rawArguments ? { rawArguments: toolCall.rawArguments } : {}),\n\t\t...(toolCall.repairNotes?.length ? { notes: toolCall.repairNotes } : {}),\n\t};\n}\n\nasync function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: finalized.result,\n\t\tisError: finalized.isError,\n\t\trepair: getToolCallRepairInfo(finalized.toolCall),\n\t});\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: finalized.result.details,\n\t\tusage: finalized.result.usage,\n\t\tisError: finalized.isError,\n\t\t// Persisted so a reloaded transcript still separates a completed operation's own status from a\n\t\t// tool that could not run at all.\n\t\t...(finalized.isError && finalized.result.errorKind ? { errorKind: finalized.result.errorKind } : {}),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -161,7 +161,7 @@ export interface AgentLoopTurnUpdate {
|
|
|
161
161
|
/** Thinking level for the next provider request. */
|
|
162
162
|
thinkingLevel?: ThinkingLevel;
|
|
163
163
|
}
|
|
164
|
-
export type AgentRunawayStopReason = "repeated_tool_call" | "provider_turn_limit";
|
|
164
|
+
export type AgentRunawayStopReason = "stagnant_tool_cycle" | "repeated_tool_call" | "provider_turn_limit";
|
|
165
165
|
/** Semantic cause and evidence for a host-enforced runaway/cost stop. */
|
|
166
166
|
export interface AgentRunawayStopInfo {
|
|
167
167
|
reason: AgentRunawayStopReason;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,qBAAqB,EACrB,OAAO,EACP,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,IAAI,EACJ,oCAAoC,EACpC,aAAa,EACb,iBAAiB,EACjB,KAAK,EACL,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;GAQG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KACpC,UAAU,CAAC,OAAO,YAAY,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC;AAEhF,OAAO,CAAC,MAAM,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AAO1F,mGAAmG;AACnG,MAAM,UAAU,uCAAuC;IACtD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,qCAAqC,CAAC,EAAE,IAAa,EAAE,CAAC,CAAC;AAClF,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,mCAAmC,CAAC,KAAc;IACjE,OAAO,CACN,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACpB,KAA+D,CAAC,qCAAqC,CAAC,KAAK,IAAI,CAChH,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolArgumentValidationTelemetryEvent,\n\tToolErrorKind,\n\tToolResultMessage,\n\tUsage,\n} from \"@caupulican/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\ndeclare const AGENT_REQUEST_ID: unique symbol;\n\n/** Opaque identity shared by one accepted provider request and its tool executions. */\nexport type AgentRequestId = string & { readonly [AGENT_REQUEST_ID]: true };\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared and executed in bounded concurrent accounting waves.\n * Each wave updates failure-recovery state before later calls launch. `tool_execution_end` is\n * emitted in completion order within each wave, while tool-result artifacts remain in source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `usage`: if provided, replaces provider usage reported by the tool\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tusage?: Usage;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** Opaque identity of the accepted provider request that produced this call. */\n\trequestId?: AgentRequestId;\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Opaque identity of the accepted provider request that produced this call. */\n\trequestId?: AgentRequestId;\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Policy-finalized result of a tool call that outlived its foreground turn. */\nexport interface BackgroundToolCallCompletion {\n\t/** Original tool call identity. */\n\ttoolCall: AgentToolCall;\n\t/** Result after the normal `afterToolCall` policy boundary has run. */\n\tresult: AgentToolResult<any>;\n\t/** Final error classification after policy overrides. */\n\tisError: boolean;\n}\n\n/** Context offered to a host when a prepared tool call crosses its foreground latency budget. */\nexport interface BackgroundToolCallContext extends BeforeToolCallContext {\n\t/** Configured foreground latency budget that elapsed. */\n\telapsedMs: number;\n\t/** Event-driven terminal signal for the real, policy-finalized execution. */\n\tcompletion: Promise<BackgroundToolCallCompletion>;\n\t/** Abort only this detached execution. */\n\tcancel(): void;\n}\n\n/** Immediate foreground result returned when the host accepts ownership of a slow tool call. */\nexport interface BackgroundToolCallHandoff {\n\t/** Bounded result telling the model how to address the session-owned task. */\n\tresult: AgentToolResult<any>;\n\t/** Optional foreground error classification. Defaults to `result.isError === true`. */\n\tisError?: boolean;\n}\n\n/** Context passed to the durable tool-start reservation boundary. */\nexport interface ToolCallStartContext extends BeforeToolCallContext {\n\t/** Accepted provider request identity is mandatory at the durable reservation boundary. */\n\trequestId: AgentRequestId;\n\t/** Stable tool-call identity within the assistant message. */\n\tcallId: string;\n\t/** Tool registry name used for this call. */\n\ttoolName: string;\n}\n\n/**\n * Reserve one or more prepared tool calls before their side effects begin.\n *\n * Sequential execution invokes this once with one prepared call. Parallel execution invokes it\n * once with the complete prepared wave, so a host can atomically persist the wave reservation before\n * any body starts. Immediate validation, policy, and replay outcomes are never offered here.\n */\nexport type ToolCallStartHook = (calls: readonly ToolCallStartContext[], signal?: AbortSignal) => void | Promise<void>;\n\n/** Context passed to `shouldStopAfterTurn`. */\nexport interface ShouldStopAfterTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages passed to the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport type AgentRunawayStopReason = \"repeated_tool_call\" | \"provider_turn_limit\";\n\n/** Semantic cause and evidence for a host-enforced runaway/cost stop. */\nexport interface AgentRunawayStopInfo {\n\treason: AgentRunawayStopReason;\n\tsignature: string;\n\trepeats: number;\n}\n\nexport interface ToolValidationEscalationEvent {\n\ttool: string;\n\tsignature: string;\n\trepeats: number;\n\tmodel: string;\n\tprovider: string;\n}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\n/** Input for one replay-safe context-planning attempt. */\nexport interface AgentContextPlanRequest {\n\t/** Sanitized durable history used as the compactable portion of this request. */\n\tmessages: AgentMessage[];\n\t/** Zero-based admission generation; freshness-only retries repeat the same value. */\n\tattempt: number;\n}\n\n/**\n * Replay-safe context plan. `messages` is compactable history. `transientMessages` and\n * `transientSystemPrompt` are mandatory request-local context that compaction must never summarize\n * or drop.\n */\nexport interface AgentContextPlan {\n\tmessages: AgentMessage[];\n\ttransientMessages?: AgentMessage[];\n\t/** Host-owned instructions appended to the system channel for this request only. */\n\ttransientSystemPrompt?: string;\n\t/** Cheap freshness check immediately before admission/commit. */\n\tisCurrent?: () => boolean;\n\t/**\n\t * Pure final validation for expensive projections. Return false to discard and replan; do not\n\t * mutate durable state here.\n\t */\n\tprepareCommit?: () => boolean;\n\t/**\n\t * Apply lifecycle side effects after every composed validator passed. Synchronous, infallible by\n\t * contract, and must not change the planned payload.\n\t */\n\tcommit?: () => void;\n\t/** Release request-local planning resources when a plan is not accepted. */\n\tdiscard?: () => void;\n}\n\n/** Provider-ready request inspected after full materialization and immediately before transport. */\nexport interface RequestPreflightContext {\n\tmodel: Model<Api>;\n\tcontext: Context;\n\t/** Current owner-selected output cap before request-local narrowing. */\n\tmaxTokens?: number;\n}\n\n/** Request-local limits. A returned output cap can only narrow the current owner/model limit. */\nexport interface RequestPreflightResult {\n\tmaxTokens?: number;\n}\n\n/** Exact materialization offered to the host-owned compaction/admission gate. */\nexport interface ProviderRequestAdmissionContext extends RequestPreflightContext {\n\t/** Agent-level request snapshot from which this materialization was planned. */\n\tsourceContext: AgentContext;\n\t/** Provider context containing only the non-compactable system/tool/transient envelope. */\n\tnonCompactableContext: Context;\n\t/** Zero-based admission generation; increments only after an accepted history replan. */\n\tattempt: number;\n}\n\n/** Exact accepted provider request offered to the host-owned durable lifecycle boundary. */\nexport interface ProviderRequestSnapshotContext extends ProviderRequestAdmissionContext {\n\t/** Opaque identity generated only after final plan validation and adoption. */\n\trequestId: AgentRequestId;\n\t/** Request-local reasoning value that will be sent to transport. */\n\treasoning: SimpleStreamOptions[\"reasoning\"];\n\t/** Zero-based admission generation for the accepted plan. */\n\tattempt: number;\n}\n\nexport type ProviderRequestAdmissionResult =\n\t| { action: \"send\"; maxTokens?: number }\n\t| { action: \"replan\"; context: AgentContext };\n\n/**\n * Default runaway-loop backstop: a single identical tool-call signature recurring this many times\n * within a sliding window (4×) stops the loop. Generous enough that legitimate long/varied work never\n * trips it, but bounds the cost of a model wedged repeating one failing call forever.\n */\nexport const DEFAULT_MAX_STALL_TURNS = 12;\n/** Provider-turn fuse is opt-in; varied productive work has no implicit request-count ceiling. */\nexport const DEFAULT_MAX_PROVIDER_TURNS = 0;\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Preferred two-phase replacement for `transformContext`. Planning is replay-safe and may run\n\t * again after compaction or invalidation; only the accepted plan's `commit` is invoked.\n\t */\n\tplanContext?: (request: AgentContextPlanRequest, signal?: AbortSignal) => Promise<AgentContextPlan>;\n\n\t/**\n\t * Host-owned admission gate over the complete provider-visible materialization. It may accept the\n\t * request or compact durable history and return a replacement source context for replanning.\n\t */\n\tadmitProviderRequest?: (\n\t\trequest: ProviderRequestAdmissionContext,\n\t\tsignal?: AbortSignal,\n\t) => ProviderRequestAdmissionResult | Promise<ProviderRequestAdmissionResult>;\n\n\t/**\n\t * Runs after admission against the exact transport-ready context, immediately before every provider request.\n\t *\n\t * Use this for request-local budget/authority checks whose state can change between tool turns.\n\t * Throwing prevents transport. A returned `maxTokens` must be a positive safe integer and can\n\t * only narrow the current owner/model output limit; it never mutates the persistent loop config.\n\t */\n\trequestPreflight?: (\n\t\tcontext: RequestPreflightContext,\n\t\tsignal?: AbortSignal,\n\t) => RequestPreflightResult | undefined | Promise<RequestPreflightResult | undefined>;\n\n\t/**\n\t * Persist or otherwise reserve the accepted provider request before transport begins.\n\t *\n\t * This runs after final plan validation, plan commit, and source-context adoption. It is awaited;\n\t * throwing prevents the provider stream from being created and leaves the accepted plan committed.\n\t */\n\tonProviderRequestSnapshot?: (context: ProviderRequestSnapshotContext, signal?: AbortSignal) => void | Promise<void>;\n\n\t/**\n\t * Resolve the reasoning effort after context transformation and immediately before the provider\n\t * request. This supports request-local policy decisions that must not mutate persisted agent state.\n\t */\n\tresolveRequestReasoning?: (\n\t\treasoning: SimpleStreamOptions[\"reasoning\"],\n\t\trequest: { model: Model<Api>; context: Context; maxTokens?: number },\n\t) => SimpleStreamOptions[\"reasoning\"];\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/**\n\t * Runaway-loop backstop. A model stuck repeating the SAME tool call (identical name + arguments) —\n\t * because a tool keeps erroring, or it is confused/oscillating — makes no progress yet keeps\n\t * consuming tokens indefinitely (history grows every turn). This bounds that cost: if one tool-call\n\t * signature recurs at least this many times within a sliding window (4×), the loop stops gracefully\n\t * (emits `agent_end`). It counts ONLY turns that issued tool calls and keys on exact name+arguments,\n\t * so legitimate long or varied agentic work never trips it. `0` disables the backstop.\n\t * Default: {@link DEFAULT_MAX_STALL_TURNS}.\n\t */\n\tmaxStallTurns?: number;\n\n\t/**\n\t * Optional provider-request fuse for one logical prompt, including host continuations.\n\t * Unlike {@link maxStallTurns}, this also catches varied tool churn that never repeats an exact\n\t * signature. The loop stops before another provider request without fabricating an assistant\n\t * message. Positive values explicitly enable the fuse; `0` disables it. Default:\n\t * {@link DEFAULT_MAX_PROVIDER_TURNS}.\n\t */\n\tmaxProviderTurns?: number;\n\n\t/**\n\t * Observability hook fired once if either the repeated-call backstop or explicit provider-turn fuse trips,\n\t * just before the loop stops. Lets the host surface/log the exact cause. Must not throw.\n\t */\n\tonRunawayStop?: (info: AgentRunawayStopInfo) => void;\n\n\t/**\n\t * Called after `turn_end` and before the loop decides whether another provider request should start.\n\t * Return replacement context/model/thinking state to affect the next turn in this run.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight and execute tool calls in bounded concurrent accounting waves;\n\t * update recovery state between waves, emit `tool_execution_end` in completion order within\n\t * each wave, then emit tool-result message artifacts in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/** Disable in-band tool repair teaching notes. Default: enabled. */\n\ttoolArgumentTeachEnabled?: boolean;\n\n\t/**\n\t * Observe tool argument validation outcomes. Events contain only shape metadata\n\t * (outcome, model/provider/tool, failure modes, repairs) and never argument values.\n\t */\n\tonToolArgumentValidation?: (event: ToolArgumentValidationTelemetryEvent) => void;\n\n\t/**\n\t * Number of consecutive identical validation bounces before adding full schema/example feedback\n\t * and notifying the host. Set to 0 to disable. Default: 3.\n\t */\n\ttoolValidationEscalationThreshold?: number;\n\n\t/**\n\t * Fired when a repeated identical tool validation failure reaches the escalation threshold.\n\t * Hosts with model routers can use this signal to move the next turn off a cheap route.\n\t */\n\tonToolValidationEscalation?: (event: ToolValidationEscalationEvent) => void;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/** Reserve prepared tool calls before execution. See {@link ToolCallStartHook}. */\n\tonToolCallStart?: ToolCallStartHook;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\n\t/**\n\t * Foreground latency budget for prepared tool calls. When it elapses, `handoffToolCall` may\n\t * transfer the still-running execution to a host-owned task. Disabled unless both fields exist.\n\t */\n\tbackgroundToolCallAfterMs?: number;\n\n\t/**\n\t * Synchronously accept ownership of a slow call. Returning a handoff lets the provider loop\n\t * continue with its bounded placeholder while `completion` still crosses `afterToolCall` once.\n\t * Returning `undefined` keeps waiting in the foreground.\n\t */\n\thandoffToolCall?: (context: BackgroundToolCallContext) => BackgroundToolCallHandoff | undefined;\n\n\t/**\n\t * Register a one-shot host request that asks an in-flight foreground call to cross the same\n\t * `handoffToolCall` boundary before its automatic latency budget elapses.\n\t */\n\tsubscribeToolCallHandoffRequest?: (toolCallId: string, request: () => void) => () => void;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\", \"max\", and \"ultra\" are only supported by selected model families. \"ultra\" maps\n * to the model's maximum provider effort. Delegation policy is provider- and reasoning-independent.\n * Use model thinking-level metadata from @caupulican/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | \"ultra\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Available tools. Assigning a new array copies the top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies the top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Provenance marker for messages synthesized by the host instead of a provider transport. */\nexport type AgentMessageOrigin = \"local\";\n\n/**\n * Why an errored tool result is an error. These are different events and the harness treats them differently.\n *\n * `tool_failure` — the tool could not perform the operation at all: rejected arguments, denied\n * authority, a timeout, a crash. The operation never happened, the harness owns the diagnostic it\n * shows the model, and it replaces the result with a bounded failure record.\n *\n * `operation_outcome` — the tool performed the operation completely and is reporting the\n * operation's own negative status: a process exit code, a search that matched nothing, a predicate\n * that answered false. Nothing failed; this is the observation the agent asked for. The harness\n * leaves the tool's own output exactly as returned and never rewrites it into a failure record.\n *\n * Both are unproductive to repeat while nothing else has changed, so both are observed by the\n * repetition governor in {@link \"./tool-failure-recovery-gate.ts\"}. Neither may ever end a run.\n */\nexport type AgentToolErrorKind = ToolErrorKind;\n\n/**\n * Structured execution failure emitted by a tool when recovery identity must not depend on rendered diagnostics.\n *\n * `failureCode` identifies the tool-owned terminal outcome. `outputSignature` identifies the complete raw\n * operation output, including bytes omitted from bounded model-facing previews. `errorKind` says whether the\n * tool failed or completed and reported a negative operation status; it defaults to `tool_failure` so a tool\n * that has not classified itself is never mistaken for a completed operation.\n */\nexport class AgentToolExecutionError extends Error {\n\treadonly failureCode: string;\n\treadonly outputSignature: string;\n\treadonly errorKind: AgentToolErrorKind;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tfailureCode: string,\n\t\toutputSignature: string,\n\t\terrorKind: AgentToolErrorKind = \"tool_failure\",\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentToolExecutionError\";\n\t\tthis.failureCode = failureCode;\n\t\tthis.outputSignature = outputSignature;\n\t\tthis.errorKind = errorKind;\n\t}\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Marks a completed execution as a failure without throwing.\n\t *\n\t * The agent loop preserves the result long enough for `afterToolCall` to\n\t * inspect it, then converts the bounded diagnostic into its durable failure\n\t * record. Throwing remains valid for exceptional execution failures.\n\t */\n\tisError?: boolean;\n\t/**\n\t * Classifies an errored result. Defaults to `tool_failure`; set `operation_outcome` when the tool\n\t * ran the operation to completion and `isError` only reports the operation's own negative status.\n\t */\n\terrorKind?: AgentToolErrorKind;\n\t/** Provider usage spent inside this tool, for durable budget and cost accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to stream partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\nconst AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY = Symbol(\"AgentToolFailureRecoveryAuthority\");\n\n/** Opaque identity shared only by tool instances that act on the same authoritative backend. */\nexport interface AgentToolFailureRecoveryAuthority {\n\treadonly [AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY]: true;\n}\n\n/** Create an unforgeable, process-local recovery authority for intentionally cooperating tools. */\nexport function createAgentToolFailureRecoveryAuthority(): AgentToolFailureRecoveryAuthority {\n\treturn Object.freeze({ [AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY]: true as const });\n}\n\n/** Validate recovery authority values supplied by tool-owned contracts. */\nexport function isAgentToolFailureRecoveryAuthority(value: unknown): value is AgentToolFailureRecoveryAuthority {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\t(value as { [AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY]?: unknown })[AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY] === true\n\t);\n}\n\n/** Exact, opaque state requirement shared only by tools that intentionally cooperate on recovery. */\nexport interface AgentToolFailureRecoveryTarget {\n\t/** Backend identity; equality is object identity and the harness never serializes it. */\n\tauthority: AgentToolFailureRecoveryAuthority;\n\t/** Stable semantic namespace owned by the declaring tools. The harness never interprets it. */\n\tkind: string;\n\t/** Exact resource/state identity within `kind`. The harness compares it byte-for-byte. */\n\tscope: string;\n}\n\n/** Bounded failure identity supplied to a failed tool's recovery contract. */\nexport interface AgentToolFailureRecoveryContext {\n\tfailureCode: string;\n}\n\n/** Ephemeral live failure context available only while tool-owned evidence is projected. */\nexport interface AgentToolFailureEvidenceContext extends AgentToolFailureRecoveryContext {\n\tmessage: string;\n}\n\n/**\n * One action a tool can actually perform for a declared failure target.\n *\n * Actions are teaching only: they name the corrective work that makes a retry worth attempting. They\n * do not grant execution budget — admission is governed solely by whether anything has succeeded\n * since the operation last ran (see `ToolFailureRecoveryGate`).\n *\n * A `correct` action teaches a materially changed operation. A `repair` action teaches corrective\n * work on the state the failed operation depends on, after which the same operation is worth rerunning.\n */\nexport type AgentToolFailureRecoveryAction = {\n\tkind: \"correct\" | \"repair\";\n\tauthority: AgentToolFailureRecoveryAuthority;\n\ttargetKind: string;\n\tinstruction: string;\n};\n\n/** Tool-owned failure targets and recovery actions. Undeclared behavior has no recovery authority. */\nexport interface AgentToolFailureRecoveryContract<TParameters extends TSchema> {\n\t/** Derive exact recovery requirements from validated arguments and a classified failure. */\n\tgetFailureTargets?: (\n\t\tparams: Static<TParameters>,\n\t\tfailure: AgentToolFailureRecoveryContext,\n\t) => readonly AgentToolFailureRecoveryTarget[];\n\t/**\n\t * Return tool-owned evidence needed to construct a changed operation. The harness sanitizes and\n\t * caps this text before exposing it beside the normalized failure record.\n\t */\n\tgetFailureEvidence?: (params: Static<TParameters>, failure: AgentToolFailureEvidenceContext) => string | undefined;\n\t/** Actions this tool can perform when it is present in the active tool surface. */\n\tactions?: readonly AgentToolFailureRecoveryAction[];\n}\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/** Compact provider-facing capability description. Execution keeps the full `description`. */\n\tproviderDescription?: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Explicit failure-recovery authority; the agent loop never infers recovery from argument text. */\n\tfailureRecovery?: AgentToolFailureRecoveryContract<TParameters>;\n\t/**\n\t * Execute the tool call. Throw for exceptional execution failures, or return\n\t * `{ isError: true }` with bounded diagnostic content for an expected\n\t * operation failure such as a non-zero subprocess exit.\n\t */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport interface ToolCallRepairInfo {\n\trepaired: true;\n\trawArguments?: Record<string, unknown>;\n\tnotes?: string[];\n}\n\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage; origin?: AgentMessageOrigin }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage; origin?: AgentMessageOrigin }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any; repair?: ToolCallRepairInfo }\n\t| {\n\t\t\ttype: \"tool_execution_update\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\targs: any;\n\t\t\tpartialResult: any;\n\t\t\trepair?: ToolCallRepairInfo;\n\t }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\trepair?: ToolCallRepairInfo;\n\t };\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA6RA;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAC1C,kGAAkG;AAClG,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAyV5C;;;;;;;GAOG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAKjD,YACC,OAAe,EACf,WAAmB,EACnB,eAAuB,EACvB,SAAS,GAAuB,cAAc;QAE9C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC5B,CAAC;CACD;AAiCD,MAAM,qCAAqC,GAAG,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAO1F,mGAAmG;AACnG,MAAM,UAAU,uCAAuC;IACtD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,qCAAqC,CAAC,EAAE,IAAa,EAAE,CAAC,CAAC;AAClF,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,mCAAmC,CAAC,KAAc;IACjE,OAAO,CACN,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACpB,KAA+D,CAAC,qCAAqC,CAAC,KAAK,IAAI,CAChH,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolArgumentValidationTelemetryEvent,\n\tToolErrorKind,\n\tToolResultMessage,\n\tUsage,\n} from \"@caupulican/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\ndeclare const AGENT_REQUEST_ID: unique symbol;\n\n/** Opaque identity shared by one accepted provider request and its tool executions. */\nexport type AgentRequestId = string & { readonly [AGENT_REQUEST_ID]: true };\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared and executed in bounded concurrent accounting waves.\n * Each wave updates failure-recovery state before later calls launch. `tool_execution_end` is\n * emitted in completion order within each wave, while tool-result artifacts remain in source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `usage`: if provided, replaces provider usage reported by the tool\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tusage?: Usage;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** Opaque identity of the accepted provider request that produced this call. */\n\trequestId?: AgentRequestId;\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Opaque identity of the accepted provider request that produced this call. */\n\trequestId?: AgentRequestId;\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Policy-finalized result of a tool call that outlived its foreground turn. */\nexport interface BackgroundToolCallCompletion {\n\t/** Original tool call identity. */\n\ttoolCall: AgentToolCall;\n\t/** Result after the normal `afterToolCall` policy boundary has run. */\n\tresult: AgentToolResult<any>;\n\t/** Final error classification after policy overrides. */\n\tisError: boolean;\n}\n\n/** Context offered to a host when a prepared tool call crosses its foreground latency budget. */\nexport interface BackgroundToolCallContext extends BeforeToolCallContext {\n\t/** Configured foreground latency budget that elapsed. */\n\telapsedMs: number;\n\t/** Event-driven terminal signal for the real, policy-finalized execution. */\n\tcompletion: Promise<BackgroundToolCallCompletion>;\n\t/** Abort only this detached execution. */\n\tcancel(): void;\n}\n\n/** Immediate foreground result returned when the host accepts ownership of a slow tool call. */\nexport interface BackgroundToolCallHandoff {\n\t/** Bounded result telling the model how to address the session-owned task. */\n\tresult: AgentToolResult<any>;\n\t/** Optional foreground error classification. Defaults to `result.isError === true`. */\n\tisError?: boolean;\n}\n\n/** Context passed to the durable tool-start reservation boundary. */\nexport interface ToolCallStartContext extends BeforeToolCallContext {\n\t/** Accepted provider request identity is mandatory at the durable reservation boundary. */\n\trequestId: AgentRequestId;\n\t/** Stable tool-call identity within the assistant message. */\n\tcallId: string;\n\t/** Tool registry name used for this call. */\n\ttoolName: string;\n}\n\n/**\n * Reserve one or more prepared tool calls before their side effects begin.\n *\n * Sequential execution invokes this once with one prepared call. Parallel execution invokes it\n * once with the complete prepared wave, so a host can atomically persist the wave reservation before\n * any body starts. Immediate validation, policy, and replay outcomes are never offered here.\n */\nexport type ToolCallStartHook = (calls: readonly ToolCallStartContext[], signal?: AbortSignal) => void | Promise<void>;\n\n/** Context passed to `shouldStopAfterTurn`. */\nexport interface ShouldStopAfterTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages passed to the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport type AgentRunawayStopReason = \"stagnant_tool_cycle\" | \"repeated_tool_call\" | \"provider_turn_limit\";\n\n/** Semantic cause and evidence for a host-enforced runaway/cost stop. */\nexport interface AgentRunawayStopInfo {\n\treason: AgentRunawayStopReason;\n\tsignature: string;\n\trepeats: number;\n}\n\nexport interface ToolValidationEscalationEvent {\n\ttool: string;\n\tsignature: string;\n\trepeats: number;\n\tmodel: string;\n\tprovider: string;\n}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\n/** Input for one replay-safe context-planning attempt. */\nexport interface AgentContextPlanRequest {\n\t/** Sanitized durable history used as the compactable portion of this request. */\n\tmessages: AgentMessage[];\n\t/** Zero-based admission generation; freshness-only retries repeat the same value. */\n\tattempt: number;\n}\n\n/**\n * Replay-safe context plan. `messages` is compactable history. `transientMessages` and\n * `transientSystemPrompt` are mandatory request-local context that compaction must never summarize\n * or drop.\n */\nexport interface AgentContextPlan {\n\tmessages: AgentMessage[];\n\ttransientMessages?: AgentMessage[];\n\t/** Host-owned instructions appended to the system channel for this request only. */\n\ttransientSystemPrompt?: string;\n\t/** Cheap freshness check immediately before admission/commit. */\n\tisCurrent?: () => boolean;\n\t/**\n\t * Pure final validation for expensive projections. Return false to discard and replan; do not\n\t * mutate durable state here.\n\t */\n\tprepareCommit?: () => boolean;\n\t/**\n\t * Apply lifecycle side effects after every composed validator passed. Synchronous, infallible by\n\t * contract, and must not change the planned payload.\n\t */\n\tcommit?: () => void;\n\t/** Release request-local planning resources when a plan is not accepted. */\n\tdiscard?: () => void;\n}\n\n/** Provider-ready request inspected after full materialization and immediately before transport. */\nexport interface RequestPreflightContext {\n\tmodel: Model<Api>;\n\tcontext: Context;\n\t/** Current owner-selected output cap before request-local narrowing. */\n\tmaxTokens?: number;\n}\n\n/** Request-local limits. A returned output cap can only narrow the current owner/model limit. */\nexport interface RequestPreflightResult {\n\tmaxTokens?: number;\n}\n\n/** Exact materialization offered to the host-owned compaction/admission gate. */\nexport interface ProviderRequestAdmissionContext extends RequestPreflightContext {\n\t/** Agent-level request snapshot from which this materialization was planned. */\n\tsourceContext: AgentContext;\n\t/** Provider context containing only the non-compactable system/tool/transient envelope. */\n\tnonCompactableContext: Context;\n\t/** Zero-based admission generation; increments only after an accepted history replan. */\n\tattempt: number;\n}\n\n/** Exact accepted provider request offered to the host-owned durable lifecycle boundary. */\nexport interface ProviderRequestSnapshotContext extends ProviderRequestAdmissionContext {\n\t/** Opaque identity generated only after final plan validation and adoption. */\n\trequestId: AgentRequestId;\n\t/** Request-local reasoning value that will be sent to transport. */\n\treasoning: SimpleStreamOptions[\"reasoning\"];\n\t/** Zero-based admission generation for the accepted plan. */\n\tattempt: number;\n}\n\nexport type ProviderRequestAdmissionResult =\n\t| { action: \"send\"; maxTokens?: number }\n\t| { action: \"replan\"; context: AgentContext };\n\n/**\n * Default runaway-loop backstop: a single identical tool-call signature recurring this many times\n * within a sliding window (4×) stops the loop. Generous enough that legitimate long/varied work never\n * trips it, but bounds the cost of a model wedged repeating one failing call forever.\n */\nexport const DEFAULT_MAX_STALL_TURNS = 12;\n/** Provider-turn fuse is opt-in; varied productive work has no implicit request-count ceiling. */\nexport const DEFAULT_MAX_PROVIDER_TURNS = 0;\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Preferred two-phase replacement for `transformContext`. Planning is replay-safe and may run\n\t * again after compaction or invalidation; only the accepted plan's `commit` is invoked.\n\t */\n\tplanContext?: (request: AgentContextPlanRequest, signal?: AbortSignal) => Promise<AgentContextPlan>;\n\n\t/**\n\t * Host-owned admission gate over the complete provider-visible materialization. It may accept the\n\t * request or compact durable history and return a replacement source context for replanning.\n\t */\n\tadmitProviderRequest?: (\n\t\trequest: ProviderRequestAdmissionContext,\n\t\tsignal?: AbortSignal,\n\t) => ProviderRequestAdmissionResult | Promise<ProviderRequestAdmissionResult>;\n\n\t/**\n\t * Runs after admission against the exact transport-ready context, immediately before every provider request.\n\t *\n\t * Use this for request-local budget/authority checks whose state can change between tool turns.\n\t * Throwing prevents transport. A returned `maxTokens` must be a positive safe integer and can\n\t * only narrow the current owner/model output limit; it never mutates the persistent loop config.\n\t */\n\trequestPreflight?: (\n\t\tcontext: RequestPreflightContext,\n\t\tsignal?: AbortSignal,\n\t) => RequestPreflightResult | undefined | Promise<RequestPreflightResult | undefined>;\n\n\t/**\n\t * Persist or otherwise reserve the accepted provider request before transport begins.\n\t *\n\t * This runs after final plan validation, plan commit, and source-context adoption. It is awaited;\n\t * throwing prevents the provider stream from being created and leaves the accepted plan committed.\n\t */\n\tonProviderRequestSnapshot?: (context: ProviderRequestSnapshotContext, signal?: AbortSignal) => void | Promise<void>;\n\n\t/**\n\t * Resolve the reasoning effort after context transformation and immediately before the provider\n\t * request. This supports request-local policy decisions that must not mutate persisted agent state.\n\t */\n\tresolveRequestReasoning?: (\n\t\treasoning: SimpleStreamOptions[\"reasoning\"],\n\t\trequest: { model: Model<Api>; context: Context; maxTokens?: number },\n\t) => SimpleStreamOptions[\"reasoning\"];\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/**\n\t * Runaway-loop backstop. A model stuck repeating the SAME tool call (identical name + arguments) —\n\t * because a tool keeps erroring, or it is confused/oscillating — makes no progress yet keeps\n\t * consuming tokens indefinitely (history grows every turn). This bounds that cost: if one tool-call\n\t * signature recurs at least this many times within a sliding window (4×), the loop stops gracefully\n\t * (emits `agent_end`). It counts ONLY turns that issued tool calls and keys on exact name+arguments,\n\t * so legitimate long or varied agentic work never trips it. `0` disables the backstop.\n\t * Default: {@link DEFAULT_MAX_STALL_TURNS}.\n\t */\n\tmaxStallTurns?: number;\n\n\t/**\n\t * Optional provider-request fuse for one logical prompt, including host continuations.\n\t * Unlike {@link maxStallTurns}, this also catches varied tool churn that never repeats an exact\n\t * signature. The loop stops before another provider request without fabricating an assistant\n\t * message. Positive values explicitly enable the fuse; `0` disables it. Default:\n\t * {@link DEFAULT_MAX_PROVIDER_TURNS}.\n\t */\n\tmaxProviderTurns?: number;\n\n\t/**\n\t * Observability hook fired once if either the repeated-call backstop or explicit provider-turn fuse trips,\n\t * just before the loop stops. Lets the host surface/log the exact cause. Must not throw.\n\t */\n\tonRunawayStop?: (info: AgentRunawayStopInfo) => void;\n\n\t/**\n\t * Called after `turn_end` and before the loop decides whether another provider request should start.\n\t * Return replacement context/model/thinking state to affect the next turn in this run.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight and execute tool calls in bounded concurrent accounting waves;\n\t * update recovery state between waves, emit `tool_execution_end` in completion order within\n\t * each wave, then emit tool-result message artifacts in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/** Disable in-band tool repair teaching notes. Default: enabled. */\n\ttoolArgumentTeachEnabled?: boolean;\n\n\t/**\n\t * Observe tool argument validation outcomes. Events contain only shape metadata\n\t * (outcome, model/provider/tool, failure modes, repairs) and never argument values.\n\t */\n\tonToolArgumentValidation?: (event: ToolArgumentValidationTelemetryEvent) => void;\n\n\t/**\n\t * Number of consecutive identical validation bounces before adding full schema/example feedback\n\t * and notifying the host. Set to 0 to disable. Default: 3.\n\t */\n\ttoolValidationEscalationThreshold?: number;\n\n\t/**\n\t * Fired when a repeated identical tool validation failure reaches the escalation threshold.\n\t * Hosts with model routers can use this signal to move the next turn off a cheap route.\n\t */\n\tonToolValidationEscalation?: (event: ToolValidationEscalationEvent) => void;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/** Reserve prepared tool calls before execution. See {@link ToolCallStartHook}. */\n\tonToolCallStart?: ToolCallStartHook;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\n\t/**\n\t * Foreground latency budget for prepared tool calls. When it elapses, `handoffToolCall` may\n\t * transfer the still-running execution to a host-owned task. Disabled unless both fields exist.\n\t */\n\tbackgroundToolCallAfterMs?: number;\n\n\t/**\n\t * Synchronously accept ownership of a slow call. Returning a handoff lets the provider loop\n\t * continue with its bounded placeholder while `completion` still crosses `afterToolCall` once.\n\t * Returning `undefined` keeps waiting in the foreground.\n\t */\n\thandoffToolCall?: (context: BackgroundToolCallContext) => BackgroundToolCallHandoff | undefined;\n\n\t/**\n\t * Register a one-shot host request that asks an in-flight foreground call to cross the same\n\t * `handoffToolCall` boundary before its automatic latency budget elapses.\n\t */\n\tsubscribeToolCallHandoffRequest?: (toolCallId: string, request: () => void) => () => void;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\", \"max\", and \"ultra\" are only supported by selected model families. \"ultra\" maps\n * to the model's maximum provider effort. Delegation policy is provider- and reasoning-independent.\n * Use model thinking-level metadata from @caupulican/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | \"ultra\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Available tools. Assigning a new array copies the top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies the top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Provenance marker for messages synthesized by the host instead of a provider transport. */\nexport type AgentMessageOrigin = \"local\";\n\n/**\n * Why an errored tool result is an error. These are different events and the harness treats them differently.\n *\n * `tool_failure` — the tool could not perform the operation at all: rejected arguments, denied\n * authority, a timeout, a crash. The operation never happened, the harness owns the diagnostic it\n * shows the model, and it replaces the result with a bounded failure record.\n *\n * `operation_outcome` — the tool performed the operation completely and is reporting the\n * operation's own negative status: a process exit code, a search that matched nothing, a predicate\n * that answered false. Nothing failed; this is the observation the agent asked for. The harness\n * leaves the tool's own output exactly as returned and never rewrites it into a failure record.\n *\n * Both are unproductive to repeat while nothing else has changed, so both are observed by the\n * repetition governor in {@link \"./tool-failure-recovery-gate.ts\"}. Neither may ever end a run.\n */\nexport type AgentToolErrorKind = ToolErrorKind;\n\n/**\n * Structured execution failure emitted by a tool when recovery identity must not depend on rendered diagnostics.\n *\n * `failureCode` identifies the tool-owned terminal outcome. `outputSignature` identifies the complete raw\n * operation output, including bytes omitted from bounded model-facing previews. `errorKind` says whether the\n * tool failed or completed and reported a negative operation status; it defaults to `tool_failure` so a tool\n * that has not classified itself is never mistaken for a completed operation.\n */\nexport class AgentToolExecutionError extends Error {\n\treadonly failureCode: string;\n\treadonly outputSignature: string;\n\treadonly errorKind: AgentToolErrorKind;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tfailureCode: string,\n\t\toutputSignature: string,\n\t\terrorKind: AgentToolErrorKind = \"tool_failure\",\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentToolExecutionError\";\n\t\tthis.failureCode = failureCode;\n\t\tthis.outputSignature = outputSignature;\n\t\tthis.errorKind = errorKind;\n\t}\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Marks a completed execution as a failure without throwing.\n\t *\n\t * The agent loop preserves the result long enough for `afterToolCall` to\n\t * inspect it, then converts the bounded diagnostic into its durable failure\n\t * record. Throwing remains valid for exceptional execution failures.\n\t */\n\tisError?: boolean;\n\t/**\n\t * Classifies an errored result. Defaults to `tool_failure`; set `operation_outcome` when the tool\n\t * ran the operation to completion and `isError` only reports the operation's own negative status.\n\t */\n\terrorKind?: AgentToolErrorKind;\n\t/** Provider usage spent inside this tool, for durable budget and cost accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to stream partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\nconst AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY = Symbol(\"AgentToolFailureRecoveryAuthority\");\n\n/** Opaque identity shared only by tool instances that act on the same authoritative backend. */\nexport interface AgentToolFailureRecoveryAuthority {\n\treadonly [AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY]: true;\n}\n\n/** Create an unforgeable, process-local recovery authority for intentionally cooperating tools. */\nexport function createAgentToolFailureRecoveryAuthority(): AgentToolFailureRecoveryAuthority {\n\treturn Object.freeze({ [AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY]: true as const });\n}\n\n/** Validate recovery authority values supplied by tool-owned contracts. */\nexport function isAgentToolFailureRecoveryAuthority(value: unknown): value is AgentToolFailureRecoveryAuthority {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\t(value as { [AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY]?: unknown })[AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY] === true\n\t);\n}\n\n/** Exact, opaque state requirement shared only by tools that intentionally cooperate on recovery. */\nexport interface AgentToolFailureRecoveryTarget {\n\t/** Backend identity; equality is object identity and the harness never serializes it. */\n\tauthority: AgentToolFailureRecoveryAuthority;\n\t/** Stable semantic namespace owned by the declaring tools. The harness never interprets it. */\n\tkind: string;\n\t/** Exact resource/state identity within `kind`. The harness compares it byte-for-byte. */\n\tscope: string;\n}\n\n/** Bounded failure identity supplied to a failed tool's recovery contract. */\nexport interface AgentToolFailureRecoveryContext {\n\tfailureCode: string;\n}\n\n/** Ephemeral live failure context available only while tool-owned evidence is projected. */\nexport interface AgentToolFailureEvidenceContext extends AgentToolFailureRecoveryContext {\n\tmessage: string;\n}\n\n/**\n * One action a tool can actually perform for a declared failure target.\n *\n * Actions are teaching only: they name the corrective work that makes a retry worth attempting. They\n * do not grant execution budget — admission is governed solely by whether anything has succeeded\n * since the operation last ran (see `ToolFailureRecoveryGate`).\n *\n * A `correct` action teaches a materially changed operation. A `repair` action teaches corrective\n * work on the state the failed operation depends on, after which the same operation is worth rerunning.\n */\nexport type AgentToolFailureRecoveryAction = {\n\tkind: \"correct\" | \"repair\";\n\tauthority: AgentToolFailureRecoveryAuthority;\n\ttargetKind: string;\n\tinstruction: string;\n};\n\n/** Tool-owned failure targets and recovery actions. Undeclared behavior has no recovery authority. */\nexport interface AgentToolFailureRecoveryContract<TParameters extends TSchema> {\n\t/** Derive exact recovery requirements from validated arguments and a classified failure. */\n\tgetFailureTargets?: (\n\t\tparams: Static<TParameters>,\n\t\tfailure: AgentToolFailureRecoveryContext,\n\t) => readonly AgentToolFailureRecoveryTarget[];\n\t/**\n\t * Return tool-owned evidence needed to construct a changed operation. The harness sanitizes and\n\t * caps this text before exposing it beside the normalized failure record.\n\t */\n\tgetFailureEvidence?: (params: Static<TParameters>, failure: AgentToolFailureEvidenceContext) => string | undefined;\n\t/** Actions this tool can perform when it is present in the active tool surface. */\n\tactions?: readonly AgentToolFailureRecoveryAction[];\n}\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/** Compact provider-facing capability description. Execution keeps the full `description`. */\n\tproviderDescription?: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Explicit failure-recovery authority; the agent loop never infers recovery from argument text. */\n\tfailureRecovery?: AgentToolFailureRecoveryContract<TParameters>;\n\t/**\n\t * Execute the tool call. Throw for exceptional execution failures, or return\n\t * `{ isError: true }` with bounded diagnostic content for an expected\n\t * operation failure such as a non-zero subprocess exit.\n\t */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport interface ToolCallRepairInfo {\n\trepaired: true;\n\trawArguments?: Record<string, unknown>;\n\tnotes?: string[];\n}\n\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage; origin?: AgentMessageOrigin }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage; origin?: AgentMessageOrigin }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any; repair?: ToolCallRepairInfo }\n\t| {\n\t\t\ttype: \"tool_execution_update\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\targs: any;\n\t\t\tpartialResult: any;\n\t\t\trepair?: ToolCallRepairInfo;\n\t }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\trepair?: ToolCallRepairInfo;\n\t };\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@caupulican/pi-agent-core",
|
|
3
|
-
"version": "0.96.
|
|
3
|
+
"version": "0.96.5",
|
|
4
4
|
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -146,7 +146,7 @@
|
|
|
146
146
|
"prepublishOnly": "npm run clean && npm run build"
|
|
147
147
|
},
|
|
148
148
|
"dependencies": {
|
|
149
|
-
"@caupulican/pi-ai": "^0.96.
|
|
149
|
+
"@caupulican/pi-ai": "^0.96.5",
|
|
150
150
|
"ignore": "7.0.5",
|
|
151
151
|
"typebox": "1.1.38",
|
|
152
152
|
"yaml": "2.9.0"
|