@caupulican/pi-agent-core 0.93.7 → 0.93.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +22 -4
- package/dist/agent-loop.js.map +1 -1
- package/dist/tool-failure-memory.d.ts +9 -1
- package/dist/tool-failure-memory.d.ts.map +1 -1
- package/dist/tool-failure-memory.js +41 -3
- package/dist/tool-failure-memory.js.map +1 -1
- package/dist/tool-failure-recovery-gate.d.ts.map +1 -1
- package/dist/tool-failure-recovery-gate.js +22 -2
- package/dist/tool-failure-recovery-gate.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +14 -0
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-failure-recovery-gate.js","sourceRoot":"","sources":["../src/tool-failure-recovery-gate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,wCAAwC,CAAC;AAE7F,OAAO,EACN,uBAAuB,EACvB,mBAAmB,EACnB,4BAA4B,EAC5B,gCAAgC,EAChC,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC1B,wBAAwB,EACxB,2BAA2B,GAE3B,MAAM,0BAA0B,CAAC;AASlC,OAAO,EAAE,mCAAmC,EAAE,MAAM,YAAY,CAAC;AAEjE,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAC1C,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAChD,MAAM,iCAAiC,GAAG,CAAC,CAAC;AAC5C,MAAM,4BAA4B,GAAG,CAAC,CAAC;AACvC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,2BAA2B,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AA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4E;QAC9E,CAAC,CAAC,+DAA+D,CAAC;IACnE,OAAO,QAAQ,CACd,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,aAAa,GAAG,CAAC,CAAC,CAAC,EAAE,mBAAmB,SAAS,IAAI,SAAS,EAAE,EACtF,2BAA2B,CAC3B,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,KAAa,EAAE,QAAgB;IAChD,IAAI,KAAK,CAAC,MAAM,IAAI,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC3C,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,GAAG,CAAC,CAAC,GAAG,CAAC;AAC3C,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAoC,EAAE,KAAqC;IACtG,OAAO,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK,CAAC;AACrG,CAAC;AAED,SAAS,uBAAuB,CAC/B,IAA+C,EAC/C,KAAgD;IAEhD,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM;QAAE,OAAO,uBAAuB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC5E,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,kBAAkB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;AAChG,CAAC","sourcesContent":["import { getToolExecutionUnchangedRetryLimit } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai/types\";\nimport {\n\tforEachPairedToolResult,\n\tgetToolExecutionKey,\n\tgetToolExecutionKeyHashParts,\n\tgetToolFailureRecordExecutionKey,\n\tisClosedOperationFailureCode,\n\tisPromptScopedFailureCode,\n\treadVisibleToolFailureCode,\n\trestoreToolFailureRecord,\n\tsanitizeToolFailureEvidence,\n\ttype ToolFailureMemoryRecord,\n} from \"./tool-failure-memory.ts\";\nimport type {\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolFailureEvidenceContext,\n\tAgentToolFailureRecoveryAuthority,\n\tAgentToolFailureRecoveryTarget,\n\tAgentToolResult,\n} from \"./types.ts\";\nimport { isAgentToolFailureRecoveryAuthority } from \"./types.ts\";\n\nconst MAX_BLOCKED_REPLAYS_PER_FAILURE = 2;\nconst BASE_FAILURE_EXECUTIONS_PER_OPERATION = 1;\nconst MAX_RECOVERY_PROBES_PER_OPERATION = 1;\nconst MAX_REJECTIONS_PER_OPERATION = 4;\nconst MAX_HOT_RECOVERY_STATES = 64;\nconst SEEN_EXECUTION_FILTER_BYTES = 64 * 1024;\nconst MAX_RECOVERY_TARGETS = 8;\nconst MAX_RECOVERY_ACTIONS = 8;\nconst MAX_TARGET_KIND_CHARS = 64;\nconst MAX_TARGET_SCOPE_CHARS = 32_768;\nconst MAX_ACTION_INSTRUCTION_CHARS = 160;\nconst MAX_RECOVERY_GUIDANCE_CHARS = 320;\nconst TARGET_KIND_PATTERN = /^[a-z0-9][a-z0-9._:-]*$/;\n\nexport interface ToolFailureExecutionReservation {\n\texecutionKey: string;\n}\n\nexport interface ToolFailureRecoveryPlan {\n\ttargets: readonly AgentToolFailureRecoveryTarget[];\n\tguidance: string;\n\tevidence?: string;\n}\n\nexport type ToolFailureRecoveryGateEffect =\n\t| {\n\t\t\tkind: \"failure\";\n\t\t\ttool?: AgentTool<any>;\n\t\t\trecord: ToolFailureMemoryRecord;\n\t\t\targs: unknown;\n\t\t\ttargets?: readonly AgentToolFailureRecoveryTarget[];\n\t\t\treservation?: ToolFailureExecutionReservation;\n\t }\n\t| { kind: \"success\"; tool: AgentTool<any>; args: unknown; evidenceResult: AgentToolResult<any> };\n\nexport type ToolFailureRecoveryAdmission =\n\t| { kind: \"allowed\"; reservation?: ToolFailureExecutionReservation }\n\t| { kind: \"blocked\"; record: ToolFailureMemoryRecord; exhausted: false; diagnostic?: string }\n\t| {\n\t\t\tkind: \"blocked\";\n\t\t\trecord: ToolFailureMemoryRecord;\n\t\t\texhausted: true;\n\t\t\tscope: \"operation\" | \"run\";\n\t\t\tdiagnostic?: string;\n\t };\n\ninterface FailureRecoveryState {\n\trecord: ToolFailureMemoryRecord;\n\trecoveryTargets: readonly AgentToolFailureRecoveryTarget[];\n\treservedExecutions: number;\n\tfailures: number;\n\trecoveryProbes: number;\n\tblockedReplays: number;\n\trecoveryAvailable: boolean;\n\toperationCircuitOpen: boolean;\n}\n\ntype TranscriptRecoveryReduction =\n\t| { kind: \"resolved\" }\n\t| { kind: \"ignored\"; state: FailureRecoveryState | undefined }\n\t| { kind: \"failed\"; state: FailureRecoveryState };\n\ninterface AvailableRecoveryAction {\n\ttoolName: string;\n\tkind: \"correct\" | \"repair\";\n\tinstruction: string;\n}\n\ninterface ParsedRecoveryAction {\n\tkind: \"correct\" | \"repair\";\n\tauthority: AgentToolFailureRecoveryAuthority;\n\ttargetKind: string;\n\tinstruction: string;\n\tgetEvidence?: (params: unknown, result: AgentToolResult<unknown>) => unknown;\n}\n\nexport interface ToolFailureRecoveryHalt {\n\trecord: ToolFailureMemoryRecord;\n\tdiagnostic: string;\n}\n\n/**\n * Bounded negative lookup for exact execution identities.\n *\n * A miss proves the operation has not failed while this gate has been alive. A hit only means\n * \"possibly seen\" and must be verified against the transcript, so collisions can cost a scan but\n * can never deny an execution. Keeping this separate from the hot state cache lets old exact\n * circuits survive eviction without retaining one live object graph per historical operation.\n */\nclass SeenExecutionFilter {\n\tprivate readonly bits = new Uint8Array(SEEN_EXECUTION_FILTER_BYTES);\n\n\tadd(executionKey: string): void {\n\t\tfor (const hash of getToolExecutionKeyHashParts(executionKey)) this.set(hash);\n\t}\n\n\tmightContain(executionKey: string): boolean {\n\t\tfor (const hash of getToolExecutionKeyHashParts(executionKey)) {\n\t\t\tif (!this.has(hash)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate set(hash: number): void {\n\t\tconst bit = (hash >>> 0) % (SEEN_EXECUTION_FILTER_BYTES * 8);\n\t\tthis.bits[bit >>> 3] |= 1 << (bit & 7);\n\t}\n\n\tprivate has(hash: number): boolean {\n\t\tconst bit = (hash >>> 0) % (SEEN_EXECUTION_FILTER_BYTES * 8);\n\t\treturn (this.bits[bit >>> 3] & (1 << (bit & 7))) !== 0;\n\t}\n}\n\n/**\n * Owns execution admission and bounded unresolved-failure budgets.\n *\n * Recovery authority is exact and tool-owned. A failed tool declares opaque backend-specific targets;\n * a loaded recovery tool may teach actions only for the same authority and target kind. Only raw\n * successful repair evidence with byte-exact scope can reopen one probe. Argument text and hooks have\n * no recovery authority.\n *\n * Run-level halt stays on the current run, but admission is never denied because unrelated operations\n * happened to fail. A bounded hot cache carries active per-operation state. A fixed-size negative\n * lookup sends an evicted exact replay back to the transcript for authoritative reconstruction, so\n * cache pressure cannot either stop new work or reopen an already-exhausted operation.\n */\nexport class ToolFailureRecoveryGate {\n\tprivate readonly statesByExecutionKey = new Map<string, FailureRecoveryState>();\n\tprivate readonly seenFailedExecutions = new SeenExecutionFilter();\n\t/** Exact successes not yet present in the transcript snapshot consulted by admission. */\n\tprivate readonly resolvedBeforeTranscriptCommit = new Set<string>();\n\tprivate transcriptMessages: readonly AgentMessage[] = [];\n\tprivate transcriptLength = 0;\n\tprivate transcriptTail: AgentMessage | undefined;\n\tprivate restoredFromTranscript = false;\n\tprivate halted: ToolFailureRecoveryHalt | undefined;\n\n\tisEmpty(): boolean {\n\t\treturn this.statesByExecutionKey.size === 0 && this.halted === undefined;\n\t}\n\n\trestoreFromMessages(messages: readonly AgentMessage[]): void {\n\t\tthis.trackTranscript(messages);\n\t\tif (this.restoredFromTranscript || !this.isEmpty()) return;\n\t\tthis.restoredFromTranscript = true;\n\t\tforEachPairedToolResult(messages, ({ tool, args, executionKey, result }) => {\n\t\t\tconst reduction = this.reduceTranscriptResult(this.statesByExecutionKey.get(executionKey), tool, args, result);\n\t\t\tif (reduction.kind === \"resolved\") {\n\t\t\t\tthis.clearResolvedState(executionKey);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reduction.kind === \"ignored\") return;\n\t\t\tthis.seenFailedExecutions.add(executionKey);\n\t\t\tthis.retainHotState(executionKey, reduction.state);\n\t\t});\n\t}\n\n\tplanFailure(\n\t\tfailedTool: AgentTool<any>,\n\t\targs: unknown,\n\t\tfailure: AgentToolFailureEvidenceContext,\n\t\tavailableTools: readonly AgentTool<any>[],\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): ToolFailureRecoveryPlan {\n\t\tconst targets = readFailureTargets(failedTool, args, failure.failureCode);\n\t\tconst actions = readAvailableRecoveryActions(availableTools, targets);\n\t\tconst unchangedRetryRemaining = this.hasUnchangedRetryRemaining(\n\t\t\tfailedTool,\n\t\t\targs,\n\t\t\tfailure.failureCode,\n\t\t\treservation,\n\t\t);\n\t\tconst evidence = readFailureEvidence(failedTool, args, failure);\n\t\treturn {\n\t\t\ttargets,\n\t\t\tguidance: formatRecoveryGuidance(failure.failureCode, actions, unchangedRetryRemaining),\n\t\t\t...(evidence ? { evidence } : {}),\n\t\t};\n\t}\n\n\tadmit(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\trecord: ToolFailureMemoryRecord | undefined,\n\t\tmessages: readonly AgentMessage[] = this.transcriptMessages,\n\t): ToolFailureRecoveryAdmission {\n\t\tthis.trackTranscript(messages);\n\t\tconst runHalt = this.halted;\n\t\tif (runHalt) {\n\t\t\treturn {\n\t\t\t\tkind: \"blocked\",\n\t\t\t\trecord: runHalt.record,\n\t\t\t\texhausted: true,\n\t\t\t\tscope: \"run\",\n\t\t\t\tdiagnostic: runHalt.diagnostic,\n\t\t\t};\n\t\t}\n\n\t\tconst executionKey = getToolExecutionKey(tool.name, args);\n\t\tif (this.resolvedBeforeTranscriptCommit.has(executionKey)) return { kind: \"allowed\" };\n\t\tlet state = this.getHotState(executionKey);\n\t\tif (!state && this.seenFailedExecutions.mightContain(executionKey)) {\n\t\t\tstate = this.restoreOperationFromTranscript(executionKey);\n\t\t}\n\t\tif (!state && record && getToolFailureRecordExecutionKey(record) === executionKey) {\n\t\t\tstate = this.getOrCreateState(executionKey, record, readFailureTargets(tool, args, record.failureCode));\n\t\t}\n\t\tif (!state) return { kind: \"allowed\" };\n\n\t\tif (record && getToolFailureRecordExecutionKey(record) === executionKey) state.record = record;\n\t\tif (state.operationCircuitOpen) {\n\t\t\tif (state.recoveryAvailable && state.recoveryProbes < MAX_RECOVERY_PROBES_PER_OPERATION) {\n\t\t\t\tstate.operationCircuitOpen = false;\n\t\t\t\tstate.recoveryAvailable = false;\n\t\t\t\tstate.recoveryProbes++;\n\t\t\t\tstate.reservedExecutions++;\n\t\t\t\tstate.blockedReplays = 0;\n\t\t\t\treturn { kind: \"allowed\", reservation: { executionKey } };\n\t\t\t}\n\t\t\tif (usesOperationLocalExhaustion(tool)) {\n\t\t\t\tconst diagnostic = `Operation recovery circuit remains closed after replay of ${state.record.failureCode}.`;\n\t\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, scope: \"operation\", diagnostic };\n\t\t\t}\n\t\t\tconst diagnostic = `Run recovery circuit opened after replay of an operation whose local circuit was already open for ${state.record.failureCode}.`;\n\t\t\tthis.halted = { record: state.record, diagnostic };\n\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, scope: \"run\", diagnostic };\n\t\t}\n\t\tconst automaticExecutionLimit =\n\t\t\tBASE_FAILURE_EXECUTIONS_PER_OPERATION + getToolExecutionUnchangedRetryLimit(state.record.failureCode);\n\t\tif (state.reservedExecutions < automaticExecutionLimit) {\n\t\t\tstate.reservedExecutions++;\n\t\t\tstate.blockedReplays = 0;\n\t\t\treturn { kind: \"allowed\", reservation: { executionKey } };\n\t\t}\n\t\tif (state.recoveryAvailable && state.recoveryProbes < MAX_RECOVERY_PROBES_PER_OPERATION) {\n\t\t\tstate.recoveryAvailable = false;\n\t\t\tstate.recoveryProbes++;\n\t\t\tstate.reservedExecutions++;\n\t\t\tstate.blockedReplays = 0;\n\t\t\treturn { kind: \"allowed\", reservation: { executionKey } };\n\t\t}\n\n\t\tstate.blockedReplays++;\n\t\tif (state.blockedReplays >= MAX_BLOCKED_REPLAYS_PER_FAILURE) {\n\t\t\tstate.operationCircuitOpen = true;\n\t\t\tconst diagnostic = `Operation recovery circuit opened after ${state.blockedReplays} blocked replays of ${state.record.failureCode}.`;\n\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, scope: \"operation\", diagnostic };\n\t\t}\n\t\treturn { kind: \"blocked\", record: state.record, exhausted: false };\n\t}\n\n\tapply(effect: ToolFailureRecoveryGateEffect | undefined): ToolFailureRecoveryHalt | undefined {\n\t\tif (!effect || this.halted) return undefined;\n\t\tif (effect.kind === \"success\") {\n\t\t\tthis.observeSuccess(effect.tool, effect.args, effect.evidenceResult);\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.observeFailure(effect.tool, effect.record, effect.args, effect.targets ?? [], effect.reservation);\n\t\treturn this.halted;\n\t}\n\n\tisHalted(): boolean {\n\t\treturn this.halted !== undefined;\n\t}\n\n\tgetHalt(): ToolFailureRecoveryHalt | undefined {\n\t\treturn this.halted;\n\t}\n\n\tprivate hasUnchangedRetryRemaining(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\tfailureCode: string,\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): boolean {\n\t\tconst retryLimit = getToolExecutionUnchangedRetryLimit(failureCode);\n\t\tif (retryLimit === 0) return false;\n\t\tconst executionKey = getToolExecutionKey(tool.name, args);\n\t\tconst state = this.statesByExecutionKey.get(executionKey);\n\t\tconst executionsIncludingCurrent = state\n\t\t\t? state.reservedExecutions + (reservation?.executionKey === executionKey ? 0 : 1)\n\t\t\t: 1;\n\t\treturn executionsIncludingCurrent < BASE_FAILURE_EXECUTIONS_PER_OPERATION + retryLimit;\n\t}\n\n\tprivate getOrCreateState(\n\t\texecutionKey: string,\n\t\trecord: ToolFailureMemoryRecord,\n\t\ttargets: readonly AgentToolFailureRecoveryTarget[],\n\t): FailureRecoveryState {\n\t\tconst existing = this.getHotState(executionKey);\n\t\tif (existing) return existing;\n\t\tconst state = createFailureRecoveryState(record, targets);\n\t\tthis.retainHotState(executionKey, state);\n\t\treturn state;\n\t}\n\n\tprivate observeFailure(\n\t\ttool: AgentTool<any> | undefined,\n\t\trecord: ToolFailureMemoryRecord,\n\t\targs: unknown,\n\t\ttargets: readonly AgentToolFailureRecoveryTarget[],\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): void {\n\t\tconst executionKey = getToolExecutionKey(record.tool, args);\n\t\tthis.resolvedBeforeTranscriptCommit.delete(executionKey);\n\t\tthis.seenFailedExecutions.add(executionKey);\n\t\tconst state = this.getOrCreateState(executionKey, record, targets);\n\t\tif (this.halted) return;\n\t\tstate.record = record;\n\t\tstate.recoveryTargets = targets;\n\t\tstate.recoveryAvailable = false;\n\t\tstate.blockedReplays = 0;\n\t\tif (reservation?.executionKey !== executionKey) state.reservedExecutions++;\n\n\t\tstate.failures++;\n\n\t\tconst operationFailureLimit =\n\t\t\trecord.state === \"failed\"\n\t\t\t\t? BASE_FAILURE_EXECUTIONS_PER_OPERATION +\n\t\t\t\t\tgetToolExecutionUnchangedRetryLimit(record.failureCode) +\n\t\t\t\t\tMAX_RECOVERY_PROBES_PER_OPERATION\n\t\t\t\t: MAX_REJECTIONS_PER_OPERATION;\n\t\tif (state.failures >= operationFailureLimit) {\n\t\t\tif (usesOperationLocalExhaustion(tool)) {\n\t\t\t\tstate.operationCircuitOpen = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened after ${state.failures} failed outcomes for one operation.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate observeSuccess(tool: AgentTool<any>, args: unknown, result: AgentToolResult<any>): void {\n\t\tconst successfulExecutionKey = getToolExecutionKey(tool.name, args);\n\t\t// Tool results are appended to the transcript after the current execution batch completes.\n\t\t// Until then the last persisted failure is stale authority: remember the exact success so a\n\t\t// later sequential call in this same batch cannot resurrect that failure from the transcript.\n\t\tthis.resolvedBeforeTranscriptCommit.add(successfulExecutionKey);\n\t\tconst evidenceTargets = readRecoveryEvidenceTargets(tool, args, result);\n\t\tfor (const [executionKey, state] of this.statesByExecutionKey) {\n\t\t\tif (executionKey === successfulExecutionKey) {\n\t\t\t\tthis.clearResolvedState(executionKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tstate.recoveryProbes < MAX_RECOVERY_PROBES_PER_OPERATION &&\n\t\t\t\thasSharedRecoveryTarget(state.recoveryTargets, evidenceTargets)\n\t\t\t) {\n\t\t\t\tstate.recoveryAvailable = true;\n\t\t\t\tstate.blockedReplays = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate clearResolvedState(executionKey: string): void {\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t}\n\n\tprivate trackTranscript(messages: readonly AgentMessage[]): void {\n\t\tconst tail = messages[messages.length - 1];\n\t\tif (\n\t\t\tmessages !== this.transcriptMessages ||\n\t\t\tmessages.length !== this.transcriptLength ||\n\t\t\ttail !== this.transcriptTail\n\t\t) {\n\t\t\t// An advanced transcript now authoritatively records completed results. The temporary\n\t\t\t// exact-success overlay is bounded to one uncommitted execution batch.\n\t\t\tthis.resolvedBeforeTranscriptCommit.clear();\n\t\t}\n\t\tthis.transcriptMessages = messages;\n\t\tthis.transcriptLength = messages.length;\n\t\tthis.transcriptTail = tail;\n\t}\n\n\tprivate getHotState(executionKey: string): FailureRecoveryState | undefined {\n\t\tconst state = this.statesByExecutionKey.get(executionKey);\n\t\tif (!state) return undefined;\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t\tthis.statesByExecutionKey.set(executionKey, state);\n\t\treturn state;\n\t}\n\n\tprivate retainHotState(executionKey: string, state: FailureRecoveryState): void {\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t\tthis.statesByExecutionKey.set(executionKey, state);\n\t\twhile (this.statesByExecutionKey.size > MAX_HOT_RECOVERY_STATES) {\n\t\t\tconst oldest = this.statesByExecutionKey.keys().next().value;\n\t\t\tif (oldest === undefined) break;\n\t\t\tthis.statesByExecutionKey.delete(oldest);\n\t\t}\n\t}\n\n\tprivate restoreOperationFromTranscript(executionKey: string): FailureRecoveryState | undefined {\n\t\tlet restoredState: FailureRecoveryState | undefined;\n\t\tforEachPairedToolResult(this.transcriptMessages, ({ tool, args, executionKey: candidateKey, result }) => {\n\t\t\tif (candidateKey !== executionKey) return;\n\t\t\tconst reduction = this.reduceTranscriptResult(restoredState, tool, args, result);\n\t\t\tif (reduction.kind === \"resolved\") {\n\t\t\t\trestoredState = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reduction.kind === \"failed\") restoredState = reduction.state;\n\t\t});\n\t\tif (restoredState) this.retainHotState(executionKey, restoredState);\n\t\treturn restoredState;\n\t}\n\n\tprivate reduceTranscriptResult(\n\t\tstate: FailureRecoveryState | undefined,\n\t\ttool: string,\n\t\targs: unknown,\n\t\tresult: ToolResultMessage,\n\t): TranscriptRecoveryReduction {\n\t\tif (!result.isError) return { kind: \"resolved\" };\n\t\tconst record = restoreToolFailureRecord(result, tool, args);\n\t\tconst visibleCode = readVisibleToolFailureCode(result);\n\t\tif (isPromptScopedFailureCode(visibleCode) || isPromptScopedFailureCode(record.failureCode)) {\n\t\t\treturn { kind: \"ignored\", state };\n\t\t}\n\t\tconst next = state ?? createFailureRecoveryState(record, []);\n\t\tnext.record = record;\n\t\tif (isClosedOperationFailureCode(visibleCode)) {\n\t\t\tnext.operationCircuitOpen = true;\n\t\t\tnext.blockedReplays = MAX_BLOCKED_REPLAYS_PER_FAILURE;\n\t\t\tnext.recoveryAvailable = false;\n\t\t\treturn { kind: \"failed\", state: next };\n\t\t}\n\t\tif (visibleCode === \"repeated_failed_operation\") {\n\t\t\tnext.blockedReplays++;\n\t\t\treturn { kind: \"failed\", state: next };\n\t\t}\n\t\tnext.reservedExecutions++;\n\t\tnext.failures++;\n\t\treturn { kind: \"failed\", state: next };\n\t}\n}\n\nfunction usesOperationLocalExhaustion(tool: AgentTool<any> | undefined): boolean {\n\treturn tool?.failureRecovery?.exhaustionScope === \"operation\";\n}\n\nfunction readFailureEvidence(\n\ttool: AgentTool<any>,\n\targs: unknown,\n\tfailure: AgentToolFailureEvidenceContext,\n): string | undefined {\n\ttry {\n\t\tconst contract = tool.failureRecovery;\n\t\tconst getEvidence = contract?.getFailureEvidence;\n\t\tif (!getEvidence) return undefined;\n\t\tconst evidence = Reflect.apply(getEvidence, contract, [args, failure]);\n\t\treturn sanitizeToolFailureEvidence(evidence);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction createFailureRecoveryState(\n\trecord: ToolFailureMemoryRecord,\n\trecoveryTargets: readonly AgentToolFailureRecoveryTarget[],\n): FailureRecoveryState {\n\treturn {\n\t\trecord,\n\t\trecoveryTargets,\n\t\treservedExecutions: 0,\n\t\tfailures: 0,\n\t\trecoveryProbes: 0,\n\t\tblockedReplays: 0,\n\t\trecoveryAvailable: false,\n\t\toperationCircuitOpen: false,\n\t};\n}\n\nfunction readFailureTargets(\n\ttool: AgentTool<any>,\n\targs: unknown,\n\tfailureCode: string,\n): readonly AgentToolFailureRecoveryTarget[] {\n\ttry {\n\t\tconst contract = tool.failureRecovery;\n\t\tconst getTargets = contract?.getFailureTargets;\n\t\tif (!getTargets) return [];\n\t\tconst targets = Reflect.apply(getTargets, contract, [args, { failureCode }]);\n\t\treturn sanitizeRecoveryTargets(targets);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction sanitizeRecoveryTargets(value: unknown): readonly AgentToolFailureRecoveryTarget[] {\n\tif (!Array.isArray(value)) return [];\n\tconst targets: AgentToolFailureRecoveryTarget[] = [];\n\tfor (const candidate of value) {\n\t\tif (targets.length >= MAX_RECOVERY_TARGETS) break;\n\t\tif (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n\t\tconst { authority, kind, scope } = candidate as { authority?: unknown; kind?: unknown; scope?: unknown };\n\t\tif (!isAgentToolFailureRecoveryAuthority(authority) || !validTargetKind(kind) || !validTargetScope(scope)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (targets.some((target) => sameRecoveryTarget(target, { authority, kind, scope }))) continue;\n\t\ttargets.push({ authority, kind, scope });\n\t}\n\treturn targets;\n}\n\nfunction validTargetKind(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= MAX_TARGET_KIND_CHARS &&\n\t\tTARGET_KIND_PATTERN.test(value)\n\t);\n}\n\nfunction validTargetScope(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" && value.length > 0 && value.length <= MAX_TARGET_SCOPE_CHARS && !value.includes(\"\\0\")\n\t);\n}\n\nfunction readAvailableRecoveryActions(\n\ttools: readonly AgentTool<any>[],\n\ttargets: readonly AgentToolFailureRecoveryTarget[],\n): readonly AvailableRecoveryAction[] {\n\tif (targets.length === 0) return [];\n\tconst actions: AvailableRecoveryAction[] = [];\n\tconst seen = new Set<string>();\n\tfor (const tool of tools) {\n\t\tfor (const candidate of readDeclaredRecoveryActions(tool)) {\n\t\t\tif (actions.length >= MAX_RECOVERY_ACTIONS) return actions;\n\t\t\tconst action = parseRecoveryAction(candidate);\n\t\t\tif (\n\t\t\t\t!action ||\n\t\t\t\t!targets.some((target) => target.authority === action.authority && target.kind === action.targetKind)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst instruction = truncate(action.instruction.trim(), MAX_ACTION_INSTRUCTION_CHARS);\n\t\t\tif (!instruction) continue;\n\t\t\tconst key = `${tool.name}\\0${action.kind}\\0${instruction}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tactions.push({ toolName: tool.name, kind: action.kind, instruction });\n\t\t}\n\t}\n\treturn actions;\n}\n\nfunction readDeclaredRecoveryActions(tool: AgentTool<any>): readonly unknown[] {\n\ttry {\n\t\tconst declared = tool.failureRecovery?.actions;\n\t\tif (!Array.isArray(declared)) return [];\n\t\tconst actions: unknown[] = [];\n\t\tconst count = Math.min(declared.length, MAX_RECOVERY_ACTIONS);\n\t\tfor (let index = 0; index < count; index++) actions.push(declared[index]);\n\t\treturn actions;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction parseRecoveryAction(value: unknown): ParsedRecoveryAction | undefined {\n\ttry {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n\t\tconst candidate = value as {\n\t\t\tkind?: unknown;\n\t\t\tauthority?: unknown;\n\t\t\ttargetKind?: unknown;\n\t\t\tinstruction?: unknown;\n\t\t\tgetEvidence?: unknown;\n\t\t};\n\t\tif (\n\t\t\t!isAgentToolFailureRecoveryAuthority(candidate.authority) ||\n\t\t\t!validTargetKind(candidate.targetKind) ||\n\t\t\ttypeof candidate.instruction !== \"string\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (candidate.kind === \"correct\") {\n\t\t\treturn {\n\t\t\t\tkind: candidate.kind,\n\t\t\t\tauthority: candidate.authority,\n\t\t\t\ttargetKind: candidate.targetKind,\n\t\t\t\tinstruction: candidate.instruction,\n\t\t\t};\n\t\t}\n\t\tif (candidate.kind !== \"repair\" || typeof candidate.getEvidence !== \"function\") return undefined;\n\t\tconst getEvidence = candidate.getEvidence;\n\t\treturn {\n\t\t\tkind: candidate.kind,\n\t\t\tauthority: candidate.authority,\n\t\t\ttargetKind: candidate.targetKind,\n\t\t\tinstruction: candidate.instruction,\n\t\t\tgetEvidence: (params, result) => Reflect.apply(getEvidence, value, [params, result]),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction readRecoveryEvidenceTargets(\n\ttool: AgentTool<any>,\n\targs: unknown,\n\tresult: AgentToolResult<any>,\n): readonly AgentToolFailureRecoveryTarget[] {\n\tconst targets: AgentToolFailureRecoveryTarget[] = [];\n\tfor (const candidate of readDeclaredRecoveryActions(tool)) {\n\t\tconst action = parseRecoveryAction(candidate);\n\t\tif (targets.length >= MAX_RECOVERY_TARGETS || !action || action.kind !== \"repair\" || !action.getEvidence) {\n\t\t\tcontinue;\n\t\t}\n\t\tlet scopes: unknown;\n\t\ttry {\n\t\t\tscopes = action.getEvidence(args, result);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!Array.isArray(scopes)) continue;\n\t\tfor (const scope of scopes) {\n\t\t\tif (targets.length >= MAX_RECOVERY_TARGETS) break;\n\t\t\tif (!validTargetScope(scope)) continue;\n\t\t\tconst target = { authority: action.authority, kind: action.targetKind, scope };\n\t\t\tif (!targets.some((candidate) => sameRecoveryTarget(candidate, target))) targets.push(target);\n\t\t}\n\t}\n\treturn targets;\n}\n\nfunction formatRecoveryGuidance(\n\tfailureCode: string,\n\tactions: readonly AvailableRecoveryAction[],\n\tunchangedRetryRemaining: boolean,\n): string {\n\tconst hasTimeoutRetryPolicy = getToolExecutionUnchangedRetryLimit(failureCode) > 0;\n\tconst timeoutPolicy = hasTimeoutRetryPolicy\n\t\t? unchangedRetryRemaining\n\t\t\t? \"Timeout policy allows 1 unchanged retry; if it fails, never retry unchanged.\"\n\t\t\t: \"Timeout unchanged retry exhausted; never retry unchanged.\"\n\t\t: undefined;\n\tif (actions.length === 0) {\n\t\tif (timeoutPolicy) return `${timeoutPolicy} Change/narrow operation, or report blocker.`;\n\t\treturn \"No loaded tool declares recovery. Never retry unchanged. Use materially different operation justified by diagnostic/schema, or report blocker.\";\n\t}\n\tconst available = actions.map((action) => `${action.toolName} ${action.kind}: ${action.instruction}`).join(\" \");\n\tconst hasRepair = actions.some((action) => action.kind === \"repair\");\n\tconst authority = hasRepair\n\t\t? \"Only exact matching repair evidence grants 1 probe; else change operation.\"\n\t\t: \"Actions require changed operation; unchanged remains blocked.\";\n\treturn truncate(\n\t\t`${timeoutPolicy ? `${timeoutPolicy} ` : \"\"}Loaded actions: ${available} ${authority}`,\n\t\tMAX_RECOVERY_GUIDANCE_CHARS,\n\t);\n}\n\nfunction truncate(value: string, maxChars: number): string {\n\tif (value.length <= maxChars) return value;\n\treturn `${value.slice(0, maxChars - 1)}…`;\n}\n\nfunction sameRecoveryTarget(left: AgentToolFailureRecoveryTarget, right: AgentToolFailureRecoveryTarget): boolean {\n\treturn left.authority === right.authority && left.kind === right.kind && left.scope === right.scope;\n}\n\nfunction hasSharedRecoveryTarget(\n\tleft: readonly AgentToolFailureRecoveryTarget[],\n\tright: readonly AgentToolFailureRecoveryTarget[],\n): boolean {\n\tif (left.length > right.length) return hasSharedRecoveryTarget(right, left);\n\treturn left.some((target) => right.some((candidate) => sameRecoveryTarget(target, candidate)));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool-failure-recovery-gate.js","sourceRoot":"","sources":["../src/tool-failure-recovery-gate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,wCAAwC,CAAC;AAE7F,OAAO,EACN,uBAAuB,EACvB,mBAAmB,EACnB,4BAA4B,EAC5B,gCAAgC,EAChC,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC1B,wBAAwB,EACxB,2BAA2B,GAE3B,MAAM,0BAA0B,CAAC;AASlC,OAAO,EAAE,mCAAmC,EAAE,MAAM,YAAY,CAAC;AAEjE,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAC1C,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAChD,MAAM,iCAAiC,GAAG,CAAC,CAAC;AAC5C,MAAM,4BAA4B,GAAG,CAAC,CAAC;AACvC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,2BAA2B,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,qBAAqB,G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KAAK,CAAC;IAC3C,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,GAAG,CAAC,CAAC,GAAG,CAAC;AAC3C,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAoC,EAAE,KAAqC;IACtG,OAAO,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK,CAAC;AACrG,CAAC;AAED,SAAS,uBAAuB,CAC/B,IAA+C,EAC/C,KAAgD;IAEhD,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM;QAAE,OAAO,uBAAuB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC5E,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,kBAAkB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;AAChG,CAAC","sourcesContent":["import { getToolExecutionUnchangedRetryLimit } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai/types\";\nimport {\n\tforEachPairedToolResult,\n\tgetToolExecutionKey,\n\tgetToolExecutionKeyHashParts,\n\tgetToolFailureRecordExecutionKey,\n\tisClosedOperationFailureCode,\n\tisPromptScopedFailureCode,\n\treadVisibleToolFailureCode,\n\trestoreToolFailureRecord,\n\tsanitizeToolFailureEvidence,\n\ttype ToolFailureMemoryRecord,\n} from \"./tool-failure-memory.ts\";\nimport type {\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolFailureEvidenceContext,\n\tAgentToolFailureRecoveryAuthority,\n\tAgentToolFailureRecoveryTarget,\n\tAgentToolResult,\n} from \"./types.ts\";\nimport { isAgentToolFailureRecoveryAuthority } from \"./types.ts\";\n\nconst MAX_BLOCKED_REPLAYS_PER_FAILURE = 2;\nconst BASE_FAILURE_EXECUTIONS_PER_OPERATION = 1;\nconst MAX_RECOVERY_PROBES_PER_OPERATION = 1;\nconst MAX_REJECTIONS_PER_OPERATION = 4;\nconst MAX_HOT_RECOVERY_STATES = 64;\nconst SEEN_EXECUTION_FILTER_BYTES = 64 * 1024;\nconst MAX_RECOVERY_TARGETS = 8;\nconst MAX_RECOVERY_ACTIONS = 8;\nconst MAX_TARGET_KIND_CHARS = 64;\nconst MAX_TARGET_SCOPE_CHARS = 32_768;\nconst MAX_ACTION_INSTRUCTION_CHARS = 160;\nconst MAX_RECOVERY_GUIDANCE_CHARS = 320;\nconst TARGET_KIND_PATTERN = /^[a-z0-9][a-z0-9._:-]*$/;\n\nexport interface ToolFailureExecutionReservation {\n\texecutionKey: string;\n}\n\nexport interface ToolFailureRecoveryPlan {\n\ttargets: readonly AgentToolFailureRecoveryTarget[];\n\tguidance: string;\n\tevidence?: string;\n}\n\nexport type ToolFailureRecoveryGateEffect =\n\t| {\n\t\t\tkind: \"failure\";\n\t\t\ttool?: AgentTool<any>;\n\t\t\trecord: ToolFailureMemoryRecord;\n\t\t\targs: unknown;\n\t\t\ttargets?: readonly AgentToolFailureRecoveryTarget[];\n\t\t\treservation?: ToolFailureExecutionReservation;\n\t }\n\t| { kind: \"success\"; tool: AgentTool<any>; args: unknown; evidenceResult: AgentToolResult<any> };\n\nexport type ToolFailureRecoveryAdmission =\n\t| { kind: \"allowed\"; reservation?: ToolFailureExecutionReservation }\n\t| { kind: \"blocked\"; record: ToolFailureMemoryRecord; exhausted: false; diagnostic?: string }\n\t| {\n\t\t\tkind: \"blocked\";\n\t\t\trecord: ToolFailureMemoryRecord;\n\t\t\texhausted: true;\n\t\t\tscope: \"operation\" | \"run\";\n\t\t\tdiagnostic?: string;\n\t };\n\ninterface FailureRecoveryState {\n\trecord: ToolFailureMemoryRecord;\n\trecoveryTargets: readonly AgentToolFailureRecoveryTarget[];\n\treservedExecutions: number;\n\tfailures: number;\n\trecoveryProbes: number;\n\tblockedReplays: number;\n\trecoveryAvailable: boolean;\n\toperationCircuitOpen: boolean;\n}\n\ntype TranscriptRecoveryReduction =\n\t| { kind: \"resolved\" }\n\t| { kind: \"ignored\"; state: FailureRecoveryState | undefined }\n\t| { kind: \"failed\"; state: FailureRecoveryState };\n\ninterface AvailableRecoveryAction {\n\ttoolName: string;\n\tkind: \"correct\" | \"repair\";\n\tinstruction: string;\n}\n\ninterface ParsedRecoveryAction {\n\tkind: \"correct\" | \"repair\";\n\tauthority: AgentToolFailureRecoveryAuthority;\n\ttargetKind: string;\n\tinstruction: string;\n\tgetEvidence?: (params: unknown, result: AgentToolResult<unknown>) => unknown;\n}\n\nexport interface ToolFailureRecoveryHalt {\n\trecord: ToolFailureMemoryRecord;\n\tdiagnostic: string;\n}\n\n/**\n * Bounded negative lookup for exact execution identities.\n *\n * A miss proves the operation has not failed while this gate has been alive. A hit only means\n * \"possibly seen\" and must be verified against the transcript, so collisions can cost a scan but\n * can never deny an execution. Keeping this separate from the hot state cache lets old exact\n * circuits survive eviction without retaining one live object graph per historical operation.\n */\nclass SeenExecutionFilter {\n\tprivate readonly bits = new Uint8Array(SEEN_EXECUTION_FILTER_BYTES);\n\n\tadd(executionKey: string): void {\n\t\tfor (const hash of getToolExecutionKeyHashParts(executionKey)) this.set(hash);\n\t}\n\n\tmightContain(executionKey: string): boolean {\n\t\tfor (const hash of getToolExecutionKeyHashParts(executionKey)) {\n\t\t\tif (!this.has(hash)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate set(hash: number): void {\n\t\tconst bit = (hash >>> 0) % (SEEN_EXECUTION_FILTER_BYTES * 8);\n\t\tthis.bits[bit >>> 3] |= 1 << (bit & 7);\n\t}\n\n\tprivate has(hash: number): boolean {\n\t\tconst bit = (hash >>> 0) % (SEEN_EXECUTION_FILTER_BYTES * 8);\n\t\treturn (this.bits[bit >>> 3] & (1 << (bit & 7))) !== 0;\n\t}\n}\n\n/**\n * Owns execution admission and bounded unresolved-failure budgets.\n *\n * Recovery authority is exact and tool-owned. A failed tool declares opaque backend-specific targets;\n * a loaded recovery tool may teach actions only for the same authority and target kind. Only raw\n * successful repair evidence with byte-exact scope can reopen one probe. Argument text and hooks have\n * no recovery authority.\n *\n * Run-level halt stays on the current run, but admission is never denied because unrelated operations\n * happened to fail. A bounded hot cache carries active per-operation state. A fixed-size negative\n * lookup sends an evicted exact replay back to the transcript for authoritative reconstruction, so\n * cache pressure cannot either stop new work or reopen an already-exhausted operation.\n */\nexport class ToolFailureRecoveryGate {\n\tprivate readonly statesByExecutionKey = new Map<string, FailureRecoveryState>();\n\tprivate readonly seenFailedExecutions = new SeenExecutionFilter();\n\t/** Exact successes not yet present in the transcript snapshot consulted by admission. */\n\tprivate readonly resolvedBeforeTranscriptCommit = new Set<string>();\n\tprivate transcriptMessages: readonly AgentMessage[] = [];\n\tprivate transcriptLength = 0;\n\tprivate transcriptTail: AgentMessage | undefined;\n\tprivate restoredFromTranscript = false;\n\tprivate halted: ToolFailureRecoveryHalt | undefined;\n\n\tisEmpty(): boolean {\n\t\treturn this.statesByExecutionKey.size === 0 && this.halted === undefined;\n\t}\n\n\trestoreFromMessages(messages: readonly AgentMessage[]): void {\n\t\tthis.trackTranscript(messages);\n\t\tif (this.restoredFromTranscript || !this.isEmpty()) return;\n\t\tthis.restoredFromTranscript = true;\n\t\tforEachPairedToolResult(messages, ({ tool, args, executionKey, result }) => {\n\t\t\tconst reduction = this.reduceTranscriptResult(this.statesByExecutionKey.get(executionKey), tool, args, result);\n\t\t\tif (reduction.kind === \"resolved\") {\n\t\t\t\tthis.clearResolvedState(executionKey);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reduction.kind === \"ignored\") return;\n\t\t\tthis.seenFailedExecutions.add(executionKey);\n\t\t\tthis.retainHotState(executionKey, reduction.state);\n\t\t});\n\t}\n\n\tplanFailure(\n\t\tfailedTool: AgentTool<any>,\n\t\targs: unknown,\n\t\tfailure: AgentToolFailureEvidenceContext,\n\t\tavailableTools: readonly AgentTool<any>[],\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): ToolFailureRecoveryPlan {\n\t\tconst targets = readFailureTargets(failedTool, args, failure.failureCode);\n\t\tconst actions = readAvailableRecoveryActions(availableTools, targets);\n\t\tconst unchangedRetryRemaining = this.hasUnchangedRetryRemaining(\n\t\t\tfailedTool,\n\t\t\targs,\n\t\t\tfailure.failureCode,\n\t\t\treservation,\n\t\t);\n\t\tconst evidence = readFailureEvidence(failedTool, args, failure);\n\t\treturn {\n\t\t\ttargets,\n\t\t\tguidance: formatRecoveryGuidance(failure.failureCode, actions, unchangedRetryRemaining),\n\t\t\t...(evidence ? { evidence } : {}),\n\t\t};\n\t}\n\n\tadmit(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\trecord: ToolFailureMemoryRecord | undefined,\n\t\tmessages: readonly AgentMessage[] = this.transcriptMessages,\n\t): ToolFailureRecoveryAdmission {\n\t\tthis.trackTranscript(messages);\n\t\tconst runHalt = this.halted;\n\t\tif (runHalt) {\n\t\t\treturn {\n\t\t\t\tkind: \"blocked\",\n\t\t\t\trecord: runHalt.record,\n\t\t\t\texhausted: true,\n\t\t\t\tscope: \"run\",\n\t\t\t\tdiagnostic: runHalt.diagnostic,\n\t\t\t};\n\t\t}\n\n\t\tconst executionKey = getToolExecutionKey(tool.name, args);\n\t\tif (this.resolvedBeforeTranscriptCommit.has(executionKey)) return { kind: \"allowed\" };\n\t\tlet state = this.getHotState(executionKey);\n\t\tif (!state && this.seenFailedExecutions.mightContain(executionKey)) {\n\t\t\tstate = this.restoreOperationFromTranscript(executionKey);\n\t\t}\n\t\tif (!state && record && getToolFailureRecordExecutionKey(record) === executionKey) {\n\t\t\tstate = this.getOrCreateState(executionKey, record, readFailureTargets(tool, args, record.failureCode));\n\t\t}\n\t\tif (!state) return { kind: \"allowed\" };\n\n\t\tif (record && getToolFailureRecordExecutionKey(record) === executionKey) state.record = record;\n\t\tif (state.operationCircuitOpen) {\n\t\t\tif (state.recoveryAvailable && state.recoveryProbes < MAX_RECOVERY_PROBES_PER_OPERATION) {\n\t\t\t\tstate.operationCircuitOpen = false;\n\t\t\t\tstate.recoveryAvailable = false;\n\t\t\t\tstate.recoveryProbes++;\n\t\t\t\tstate.reservedExecutions++;\n\t\t\t\tstate.blockedReplays = 0;\n\t\t\t\treturn { kind: \"allowed\", reservation: { executionKey } };\n\t\t\t}\n\t\t\tif (usesOperationLocalExhaustion(tool)) {\n\t\t\t\tconst diagnostic = `Operation recovery circuit remains closed after replay of ${state.record.failureCode}.`;\n\t\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, scope: \"operation\", diagnostic };\n\t\t\t}\n\t\t\tconst diagnostic = `Run recovery circuit opened after replay of an operation whose local circuit was already open for ${state.record.failureCode}.`;\n\t\t\tthis.halted = { record: state.record, diagnostic };\n\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, scope: \"run\", diagnostic };\n\t\t}\n\t\tconst automaticExecutionLimit =\n\t\t\tBASE_FAILURE_EXECUTIONS_PER_OPERATION + getToolExecutionUnchangedRetryLimit(state.record.failureCode);\n\t\tif (state.reservedExecutions < automaticExecutionLimit) {\n\t\t\tstate.reservedExecutions++;\n\t\t\tstate.blockedReplays = 0;\n\t\t\treturn { kind: \"allowed\", reservation: { executionKey } };\n\t\t}\n\t\tif (state.recoveryAvailable && state.recoveryProbes < MAX_RECOVERY_PROBES_PER_OPERATION) {\n\t\t\tstate.recoveryAvailable = false;\n\t\t\tstate.recoveryProbes++;\n\t\t\tstate.reservedExecutions++;\n\t\t\tstate.blockedReplays = 0;\n\t\t\treturn { kind: \"allowed\", reservation: { executionKey } };\n\t\t}\n\n\t\tstate.blockedReplays++;\n\t\tif (state.blockedReplays >= MAX_BLOCKED_REPLAYS_PER_FAILURE) {\n\t\t\tstate.operationCircuitOpen = true;\n\t\t\tconst diagnostic = `Operation recovery circuit opened after ${state.blockedReplays} blocked replays of ${state.record.failureCode}.`;\n\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, scope: \"operation\", diagnostic };\n\t\t}\n\t\treturn { kind: \"blocked\", record: state.record, exhausted: false };\n\t}\n\n\tapply(effect: ToolFailureRecoveryGateEffect | undefined): ToolFailureRecoveryHalt | undefined {\n\t\tif (!effect || this.halted) return undefined;\n\t\tif (effect.kind === \"success\") {\n\t\t\tthis.observeSuccess(effect.tool, effect.args, effect.evidenceResult);\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.observeFailure(effect.tool, effect.record, effect.args, effect.targets ?? [], effect.reservation);\n\t\treturn this.halted;\n\t}\n\n\tisHalted(): boolean {\n\t\treturn this.halted !== undefined;\n\t}\n\n\tgetHalt(): ToolFailureRecoveryHalt | undefined {\n\t\treturn this.halted;\n\t}\n\n\tprivate hasUnchangedRetryRemaining(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\tfailureCode: string,\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): boolean {\n\t\tconst retryLimit = getToolExecutionUnchangedRetryLimit(failureCode);\n\t\tif (retryLimit === 0) return false;\n\t\tconst executionKey = getToolExecutionKey(tool.name, args);\n\t\tconst state = this.statesByExecutionKey.get(executionKey);\n\t\tconst executionsIncludingCurrent = state\n\t\t\t? state.reservedExecutions + (reservation?.executionKey === executionKey ? 0 : 1)\n\t\t\t: 1;\n\t\treturn executionsIncludingCurrent < BASE_FAILURE_EXECUTIONS_PER_OPERATION + retryLimit;\n\t}\n\n\tprivate getOrCreateState(\n\t\texecutionKey: string,\n\t\trecord: ToolFailureMemoryRecord,\n\t\ttargets: readonly AgentToolFailureRecoveryTarget[],\n\t): FailureRecoveryState {\n\t\tconst existing = this.getHotState(executionKey);\n\t\tif (existing) return existing;\n\t\tconst state = createFailureRecoveryState(record, targets);\n\t\tthis.retainHotState(executionKey, state);\n\t\treturn state;\n\t}\n\n\tprivate observeFailure(\n\t\ttool: AgentTool<any> | undefined,\n\t\trecord: ToolFailureMemoryRecord,\n\t\targs: unknown,\n\t\ttargets: readonly AgentToolFailureRecoveryTarget[],\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): void {\n\t\tconst executionKey = getToolExecutionKey(record.tool, args);\n\t\tthis.resolvedBeforeTranscriptCommit.delete(executionKey);\n\t\tthis.seenFailedExecutions.add(executionKey);\n\t\tconst state = this.getOrCreateState(executionKey, record, targets);\n\t\tif (this.halted) return;\n\t\tconst startsNewEpisode = state.failures > 0 && !sameFailureOutcome(state.record, record);\n\t\tif (startsNewEpisode) resetFailureEpisode(state);\n\t\tstate.record = record;\n\t\tstate.recoveryTargets = targets;\n\t\tstate.recoveryAvailable = false;\n\t\tstate.blockedReplays = 0;\n\t\tif (startsNewEpisode || reservation?.executionKey !== executionKey) state.reservedExecutions++;\n\n\t\tstate.failures++;\n\n\t\tconst operationFailureLimit =\n\t\t\trecord.state === \"failed\"\n\t\t\t\t? BASE_FAILURE_EXECUTIONS_PER_OPERATION +\n\t\t\t\t\tgetToolExecutionUnchangedRetryLimit(record.failureCode) +\n\t\t\t\t\tMAX_RECOVERY_PROBES_PER_OPERATION\n\t\t\t\t: MAX_REJECTIONS_PER_OPERATION;\n\t\tif (state.failures >= operationFailureLimit) {\n\t\t\tif (usesOperationLocalExhaustion(tool)) {\n\t\t\t\tstate.operationCircuitOpen = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened after ${state.failures} failed outcomes for one operation.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate observeSuccess(tool: AgentTool<any>, args: unknown, result: AgentToolResult<any>): void {\n\t\tconst successfulExecutionKey = getToolExecutionKey(tool.name, args);\n\t\t// Tool results are appended to the transcript after the current execution batch completes.\n\t\t// Until then the last persisted failure is stale authority: remember the exact success so a\n\t\t// later sequential call in this same batch cannot resurrect that failure from the transcript.\n\t\tthis.resolvedBeforeTranscriptCommit.add(successfulExecutionKey);\n\t\tconst evidenceTargets = readRecoveryEvidenceTargets(tool, args, result);\n\t\tfor (const [executionKey, state] of this.statesByExecutionKey) {\n\t\t\tif (executionKey === successfulExecutionKey) {\n\t\t\t\tthis.clearResolvedState(executionKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tstate.recoveryProbes < MAX_RECOVERY_PROBES_PER_OPERATION &&\n\t\t\t\thasSharedRecoveryTarget(state.recoveryTargets, evidenceTargets)\n\t\t\t) {\n\t\t\t\tstate.recoveryAvailable = true;\n\t\t\t\tstate.blockedReplays = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate clearResolvedState(executionKey: string): void {\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t}\n\n\tprivate trackTranscript(messages: readonly AgentMessage[]): void {\n\t\tconst tail = messages[messages.length - 1];\n\t\tif (\n\t\t\tmessages !== this.transcriptMessages ||\n\t\t\tmessages.length !== this.transcriptLength ||\n\t\t\ttail !== this.transcriptTail\n\t\t) {\n\t\t\t// An advanced transcript now authoritatively records completed results. The temporary\n\t\t\t// exact-success overlay is bounded to one uncommitted execution batch.\n\t\t\tthis.resolvedBeforeTranscriptCommit.clear();\n\t\t}\n\t\tthis.transcriptMessages = messages;\n\t\tthis.transcriptLength = messages.length;\n\t\tthis.transcriptTail = tail;\n\t}\n\n\tprivate getHotState(executionKey: string): FailureRecoveryState | undefined {\n\t\tconst state = this.statesByExecutionKey.get(executionKey);\n\t\tif (!state) return undefined;\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t\tthis.statesByExecutionKey.set(executionKey, state);\n\t\treturn state;\n\t}\n\n\tprivate retainHotState(executionKey: string, state: FailureRecoveryState): void {\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t\tthis.statesByExecutionKey.set(executionKey, state);\n\t\twhile (this.statesByExecutionKey.size > MAX_HOT_RECOVERY_STATES) {\n\t\t\tconst oldest = this.statesByExecutionKey.keys().next().value;\n\t\t\tif (oldest === undefined) break;\n\t\t\tthis.statesByExecutionKey.delete(oldest);\n\t\t}\n\t}\n\n\tprivate restoreOperationFromTranscript(executionKey: string): FailureRecoveryState | undefined {\n\t\tlet restoredState: FailureRecoveryState | undefined;\n\t\tforEachPairedToolResult(this.transcriptMessages, ({ tool, args, executionKey: candidateKey, result }) => {\n\t\t\tif (candidateKey !== executionKey) return;\n\t\t\tconst reduction = this.reduceTranscriptResult(restoredState, tool, args, result);\n\t\t\tif (reduction.kind === \"resolved\") {\n\t\t\t\trestoredState = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reduction.kind === \"failed\") restoredState = reduction.state;\n\t\t});\n\t\tif (restoredState) this.retainHotState(executionKey, restoredState);\n\t\treturn restoredState;\n\t}\n\n\tprivate reduceTranscriptResult(\n\t\tstate: FailureRecoveryState | undefined,\n\t\ttool: string,\n\t\targs: unknown,\n\t\tresult: ToolResultMessage,\n\t): TranscriptRecoveryReduction {\n\t\tif (!result.isError) return { kind: \"resolved\" };\n\t\tconst record = restoreToolFailureRecord(result, tool, args);\n\t\tconst visibleCode = readVisibleToolFailureCode(result);\n\t\tif (isPromptScopedFailureCode(visibleCode) || isPromptScopedFailureCode(record.failureCode)) {\n\t\t\treturn { kind: \"ignored\", state };\n\t\t}\n\t\tconst next = state ?? createFailureRecoveryState(record, []);\n\t\tif (isClosedOperationFailureCode(visibleCode)) {\n\t\t\tnext.record = record;\n\t\t\tnext.operationCircuitOpen = true;\n\t\t\tnext.blockedReplays = MAX_BLOCKED_REPLAYS_PER_FAILURE;\n\t\t\tnext.recoveryAvailable = false;\n\t\t\treturn { kind: \"failed\", state: next };\n\t\t}\n\t\tif (visibleCode === \"repeated_failed_operation\") {\n\t\t\tnext.record = record;\n\t\t\tnext.blockedReplays++;\n\t\t\treturn { kind: \"failed\", state: next };\n\t\t}\n\t\tif (next.failures > 0 && !sameFailureOutcome(next.record, record)) resetFailureEpisode(next);\n\t\tnext.record = record;\n\t\tnext.reservedExecutions++;\n\t\tnext.failures++;\n\t\treturn { kind: \"failed\", state: next };\n\t}\n}\n\nfunction usesOperationLocalExhaustion(tool: AgentTool<any> | undefined): boolean {\n\treturn tool?.failureRecovery?.exhaustionScope === \"operation\";\n}\n\nfunction sameFailureOutcome(left: ToolFailureMemoryRecord, right: ToolFailureMemoryRecord): boolean {\n\treturn (\n\t\tleft.failureCode === right.failureCode &&\n\t\tleft.outputSignature !== undefined &&\n\t\tleft.outputSignature === right.outputSignature\n\t);\n}\n\nfunction resetFailureEpisode(state: FailureRecoveryState): void {\n\tstate.reservedExecutions = 0;\n\tstate.failures = 0;\n\tstate.recoveryProbes = 0;\n\tstate.blockedReplays = 0;\n\tstate.recoveryAvailable = false;\n\tstate.operationCircuitOpen = false;\n}\n\nfunction readFailureEvidence(\n\ttool: AgentTool<any>,\n\targs: unknown,\n\tfailure: AgentToolFailureEvidenceContext,\n): string | undefined {\n\ttry {\n\t\tconst contract = tool.failureRecovery;\n\t\tconst getEvidence = contract?.getFailureEvidence;\n\t\tif (!getEvidence) return undefined;\n\t\tconst evidence = Reflect.apply(getEvidence, contract, [args, failure]);\n\t\treturn sanitizeToolFailureEvidence(evidence);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction createFailureRecoveryState(\n\trecord: ToolFailureMemoryRecord,\n\trecoveryTargets: readonly AgentToolFailureRecoveryTarget[],\n): FailureRecoveryState {\n\treturn {\n\t\trecord,\n\t\trecoveryTargets,\n\t\treservedExecutions: 0,\n\t\tfailures: 0,\n\t\trecoveryProbes: 0,\n\t\tblockedReplays: 0,\n\t\trecoveryAvailable: false,\n\t\toperationCircuitOpen: false,\n\t};\n}\n\nfunction readFailureTargets(\n\ttool: AgentTool<any>,\n\targs: unknown,\n\tfailureCode: string,\n): readonly AgentToolFailureRecoveryTarget[] {\n\ttry {\n\t\tconst contract = tool.failureRecovery;\n\t\tconst getTargets = contract?.getFailureTargets;\n\t\tif (!getTargets) return [];\n\t\tconst targets = Reflect.apply(getTargets, contract, [args, { failureCode }]);\n\t\treturn sanitizeRecoveryTargets(targets);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction sanitizeRecoveryTargets(value: unknown): readonly AgentToolFailureRecoveryTarget[] {\n\tif (!Array.isArray(value)) return [];\n\tconst targets: AgentToolFailureRecoveryTarget[] = [];\n\tfor (const candidate of value) {\n\t\tif (targets.length >= MAX_RECOVERY_TARGETS) break;\n\t\tif (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n\t\tconst { authority, kind, scope } = candidate as { authority?: unknown; kind?: unknown; scope?: unknown };\n\t\tif (!isAgentToolFailureRecoveryAuthority(authority) || !validTargetKind(kind) || !validTargetScope(scope)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (targets.some((target) => sameRecoveryTarget(target, { authority, kind, scope }))) continue;\n\t\ttargets.push({ authority, kind, scope });\n\t}\n\treturn targets;\n}\n\nfunction validTargetKind(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= MAX_TARGET_KIND_CHARS &&\n\t\tTARGET_KIND_PATTERN.test(value)\n\t);\n}\n\nfunction validTargetScope(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" && value.length > 0 && value.length <= MAX_TARGET_SCOPE_CHARS && !value.includes(\"\\0\")\n\t);\n}\n\nfunction readAvailableRecoveryActions(\n\ttools: readonly AgentTool<any>[],\n\ttargets: readonly AgentToolFailureRecoveryTarget[],\n): readonly AvailableRecoveryAction[] {\n\tif (targets.length === 0) return [];\n\tconst actions: AvailableRecoveryAction[] = [];\n\tconst seen = new Set<string>();\n\tfor (const tool of tools) {\n\t\tfor (const candidate of readDeclaredRecoveryActions(tool)) {\n\t\t\tif (actions.length >= MAX_RECOVERY_ACTIONS) return actions;\n\t\t\tconst action = parseRecoveryAction(candidate);\n\t\t\tif (\n\t\t\t\t!action ||\n\t\t\t\t!targets.some((target) => target.authority === action.authority && target.kind === action.targetKind)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst instruction = truncate(action.instruction.trim(), MAX_ACTION_INSTRUCTION_CHARS);\n\t\t\tif (!instruction) continue;\n\t\t\tconst key = `${tool.name}\\0${action.kind}\\0${instruction}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tactions.push({ toolName: tool.name, kind: action.kind, instruction });\n\t\t}\n\t}\n\treturn actions;\n}\n\nfunction readDeclaredRecoveryActions(tool: AgentTool<any>): readonly unknown[] {\n\ttry {\n\t\tconst declared = tool.failureRecovery?.actions;\n\t\tif (!Array.isArray(declared)) return [];\n\t\tconst actions: unknown[] = [];\n\t\tconst count = Math.min(declared.length, MAX_RECOVERY_ACTIONS);\n\t\tfor (let index = 0; index < count; index++) actions.push(declared[index]);\n\t\treturn actions;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction parseRecoveryAction(value: unknown): ParsedRecoveryAction | undefined {\n\ttry {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n\t\tconst candidate = value as {\n\t\t\tkind?: unknown;\n\t\t\tauthority?: unknown;\n\t\t\ttargetKind?: unknown;\n\t\t\tinstruction?: unknown;\n\t\t\tgetEvidence?: unknown;\n\t\t};\n\t\tif (\n\t\t\t!isAgentToolFailureRecoveryAuthority(candidate.authority) ||\n\t\t\t!validTargetKind(candidate.targetKind) ||\n\t\t\ttypeof candidate.instruction !== \"string\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (candidate.kind === \"correct\") {\n\t\t\treturn {\n\t\t\t\tkind: candidate.kind,\n\t\t\t\tauthority: candidate.authority,\n\t\t\t\ttargetKind: candidate.targetKind,\n\t\t\t\tinstruction: candidate.instruction,\n\t\t\t};\n\t\t}\n\t\tif (candidate.kind !== \"repair\" || typeof candidate.getEvidence !== \"function\") return undefined;\n\t\tconst getEvidence = candidate.getEvidence;\n\t\treturn {\n\t\t\tkind: candidate.kind,\n\t\t\tauthority: candidate.authority,\n\t\t\ttargetKind: candidate.targetKind,\n\t\t\tinstruction: candidate.instruction,\n\t\t\tgetEvidence: (params, result) => Reflect.apply(getEvidence, value, [params, result]),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction readRecoveryEvidenceTargets(\n\ttool: AgentTool<any>,\n\targs: unknown,\n\tresult: AgentToolResult<any>,\n): readonly AgentToolFailureRecoveryTarget[] {\n\tconst targets: AgentToolFailureRecoveryTarget[] = [];\n\tfor (const candidate of readDeclaredRecoveryActions(tool)) {\n\t\tconst action = parseRecoveryAction(candidate);\n\t\tif (targets.length >= MAX_RECOVERY_TARGETS || !action || action.kind !== \"repair\" || !action.getEvidence) {\n\t\t\tcontinue;\n\t\t}\n\t\tlet scopes: unknown;\n\t\ttry {\n\t\t\tscopes = action.getEvidence(args, result);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!Array.isArray(scopes)) continue;\n\t\tfor (const scope of scopes) {\n\t\t\tif (targets.length >= MAX_RECOVERY_TARGETS) break;\n\t\t\tif (!validTargetScope(scope)) continue;\n\t\t\tconst target = { authority: action.authority, kind: action.targetKind, scope };\n\t\t\tif (!targets.some((candidate) => sameRecoveryTarget(candidate, target))) targets.push(target);\n\t\t}\n\t}\n\treturn targets;\n}\n\nfunction formatRecoveryGuidance(\n\tfailureCode: string,\n\tactions: readonly AvailableRecoveryAction[],\n\tunchangedRetryRemaining: boolean,\n): string {\n\tconst hasTimeoutRetryPolicy = getToolExecutionUnchangedRetryLimit(failureCode) > 0;\n\tconst timeoutPolicy = hasTimeoutRetryPolicy\n\t\t? unchangedRetryRemaining\n\t\t\t? \"Timeout policy allows 1 unchanged retry; if it fails, never retry unchanged.\"\n\t\t\t: \"Timeout unchanged retry exhausted; never retry unchanged.\"\n\t\t: undefined;\n\tif (actions.length === 0) {\n\t\tif (timeoutPolicy) return `${timeoutPolicy} Change/narrow operation, or report blocker.`;\n\t\treturn \"No loaded tool declares recovery. Never retry unchanged. Use materially different operation justified by diagnostic/schema, or report blocker.\";\n\t}\n\tconst available = actions.map((action) => `${action.toolName} ${action.kind}: ${action.instruction}`).join(\" \");\n\tconst hasRepair = actions.some((action) => action.kind === \"repair\");\n\tconst authority = hasRepair\n\t\t? \"Only exact matching repair evidence grants 1 probe; else change operation.\"\n\t\t: \"Actions require changed operation; unchanged remains blocked.\";\n\treturn truncate(\n\t\t`${timeoutPolicy ? `${timeoutPolicy} ` : \"\"}Loaded actions: ${available} ${authority}`,\n\t\tMAX_RECOVERY_GUIDANCE_CHARS,\n\t);\n}\n\nfunction truncate(value: string, maxChars: number): string {\n\tif (value.length <= maxChars) return value;\n\treturn `${value.slice(0, maxChars - 1)}…`;\n}\n\nfunction sameRecoveryTarget(left: AgentToolFailureRecoveryTarget, right: AgentToolFailureRecoveryTarget): boolean {\n\treturn left.authority === right.authority && left.kind === right.kind && left.scope === right.scope;\n}\n\nfunction hasSharedRecoveryTarget(\n\tleft: readonly AgentToolFailureRecoveryTarget[],\n\tright: readonly AgentToolFailureRecoveryTarget[],\n): boolean {\n\tif (left.length > right.length) return hasSharedRecoveryTarget(right, left);\n\treturn left.some((target) => right.some((candidate) => sameRecoveryTarget(target, candidate)));\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -494,6 +494,17 @@ export interface AgentState {
|
|
|
494
494
|
}
|
|
495
495
|
/** Provenance marker for messages synthesized by the host instead of a provider transport. */
|
|
496
496
|
export type AgentMessageOrigin = "local";
|
|
497
|
+
/**
|
|
498
|
+
* Structured execution failure emitted by a tool when recovery identity must not depend on rendered diagnostics.
|
|
499
|
+
*
|
|
500
|
+
* `failureCode` identifies the tool-owned terminal outcome. `outputSignature` identifies the complete raw
|
|
501
|
+
* operation output, including bytes omitted from bounded model-facing previews.
|
|
502
|
+
*/
|
|
503
|
+
export declare class AgentToolExecutionError extends Error {
|
|
504
|
+
readonly failureCode: string;
|
|
505
|
+
readonly outputSignature: string;
|
|
506
|
+
constructor(message: string, failureCode: string, outputSignature: string);
|
|
507
|
+
}
|
|
497
508
|
/** Final or partial result produced by a tool. */
|
|
498
509
|
export interface AgentToolResult<T> {
|
|
499
510
|
/** Text or image content returned to the model. */
|
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,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;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,eAAe,CAAC;AAEhD,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAAE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAE/F;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACpC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,mBAAmB;IACnC,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,CAAC;IACzC,O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C,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAC;IAAC,MAAM,CAAC,EAAE,kBAAkB,CAAA;CAAE,GAC9G;IACA,IAAI,EAAE,uBAAuB,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,GAAG,CAAC;IACV,aAAa,EAAE,GAAG,CAAC;IACnB,MAAM,CAAC,EAAE,kBAAkB,CAAC;CAC3B,GACD;IACA,IAAI,EAAE,oBAAoB,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,kBAAkB,CAAC;CAC3B,CAAC"}
|
package/dist/types.js
CHANGED
|
@@ -6,6 +6,20 @@
|
|
|
6
6
|
export const DEFAULT_MAX_STALL_TURNS = 12;
|
|
7
7
|
/** Provider-turn fuse is opt-in; varied productive work has no implicit request-count ceiling. */
|
|
8
8
|
export const DEFAULT_MAX_PROVIDER_TURNS = 0;
|
|
9
|
+
/**
|
|
10
|
+
* Structured execution failure emitted by a tool when recovery identity must not depend on rendered diagnostics.
|
|
11
|
+
*
|
|
12
|
+
* `failureCode` identifies the tool-owned terminal outcome. `outputSignature` identifies the complete raw
|
|
13
|
+
* operation output, including bytes omitted from bounded model-facing previews.
|
|
14
|
+
*/
|
|
15
|
+
export class AgentToolExecutionError extends Error {
|
|
16
|
+
constructor(message, failureCode, outputSignature) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "AgentToolExecutionError";
|
|
19
|
+
this.failureCode = failureCode;
|
|
20
|
+
this.outputSignature = outputSignature;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
9
23
|
const AGENT_TOOL_FAILURE_RECOVERY_AUTHORITY = Symbol("AgentToolFailureRecoveryAuthority");
|
|
10
24
|
/** Create an unforgeable, process-local recovery authority for intentionally cooperating tools. */
|
|
11
25
|
export function createAgentToolFailureRecoveryAuthority() {
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAsPA;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAC1C,kGAAkG;AAClG,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAsV5C,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\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\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/** 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/** 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 `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\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 * 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 emits a local terminal diagnostic before another provider request. Positive\n\t * values explicitly enable the fuse; `0` disables it. Default: {@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/**\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/** 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/** 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 * A `correct` action teaches a materially changed operation and never unlocks an unchanged retry.\n * A `repair` action must emit exact evidence after success; only that evidence may unlock one probe.\n */\nexport type AgentToolFailureRecoveryAction<TParameters extends TSchema, TDetails> =\n\t| {\n\t\t\tkind: \"correct\";\n\t\t\tauthority: AgentToolFailureRecoveryAuthority;\n\t\t\ttargetKind: string;\n\t\t\tinstruction: string;\n\t }\n\t| {\n\t\t\tkind: \"repair\";\n\t\t\tauthority: AgentToolFailureRecoveryAuthority;\n\t\t\ttargetKind: string;\n\t\t\tinstruction: string;\n\t\t\tgetEvidence: (params: Static<TParameters>, result: AgentToolResult<TDetails>) => readonly string[];\n\t };\n\n/** Tool-owned failure targets and recovery actions. Undeclared behavior has no recovery authority. */\nexport interface AgentToolFailureRecoveryContract<TParameters extends TSchema, TDetails> {\n\t/** Keep exhaustion local to this operation when another operation can still correct it. Defaults to run. */\n\texhaustionScope?: \"operation\" | \"run\";\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<TParameters, TDetails>[];\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, TDetails>;\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":"AAsPA;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAC1C,kGAAkG;AAClG,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AA4T5C;;;;;GAKG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAIjD,YAAY,OAAe,EAAE,WAAmB,EAAE,eAAuB;QACxE,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;IACxC,CAAC;CACD;AA4BD,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\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\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/** 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/** 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 `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\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 * 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 emits a local terminal diagnostic before another provider request. Positive\n\t * values explicitly enable the fuse; `0` disables it. Default: {@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/**\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 * 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.\n */\nexport class AgentToolExecutionError extends Error {\n\treadonly failureCode: string;\n\treadonly outputSignature: string;\n\n\tconstructor(message: string, failureCode: string, outputSignature: string) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentToolExecutionError\";\n\t\tthis.failureCode = failureCode;\n\t\tthis.outputSignature = outputSignature;\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/** 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 * A `correct` action teaches a materially changed operation and never unlocks an unchanged retry.\n * A `repair` action must emit exact evidence after success; only that evidence may unlock one probe.\n */\nexport type AgentToolFailureRecoveryAction<TParameters extends TSchema, TDetails> =\n\t| {\n\t\t\tkind: \"correct\";\n\t\t\tauthority: AgentToolFailureRecoveryAuthority;\n\t\t\ttargetKind: string;\n\t\t\tinstruction: string;\n\t }\n\t| {\n\t\t\tkind: \"repair\";\n\t\t\tauthority: AgentToolFailureRecoveryAuthority;\n\t\t\ttargetKind: string;\n\t\t\tinstruction: string;\n\t\t\tgetEvidence: (params: Static<TParameters>, result: AgentToolResult<TDetails>) => readonly string[];\n\t };\n\n/** Tool-owned failure targets and recovery actions. Undeclared behavior has no recovery authority. */\nexport interface AgentToolFailureRecoveryContract<TParameters extends TSchema, TDetails> {\n\t/** Keep exhaustion local to this operation when another operation can still correct it. Defaults to run. */\n\texhaustionScope?: \"operation\" | \"run\";\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<TParameters, TDetails>[];\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, TDetails>;\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.93.
|
|
3
|
+
"version": "0.93.8",
|
|
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.93.
|
|
149
|
+
"@caupulican/pi-ai": "^0.93.8",
|
|
150
150
|
"ignore": "7.0.5",
|
|
151
151
|
"typebox": "1.1.38",
|
|
152
152
|
"yaml": "2.9.0"
|