@caupulican/pi-agent-core 0.86.17 → 0.90.0

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.
Files changed (56) hide show
  1. package/dist/agent-loop.d.ts +2 -13
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +99 -77
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +5 -1
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +4 -0
  8. package/dist/agent.js.map +1 -1
  9. package/dist/compaction/branch-summarization.d.ts.map +1 -1
  10. package/dist/compaction/branch-summarization.js +11 -15
  11. package/dist/compaction/branch-summarization.js.map +1 -1
  12. package/dist/compaction/compaction.d.ts +3 -0
  13. package/dist/compaction/compaction.d.ts.map +1 -1
  14. package/dist/compaction/compaction.js +37 -46
  15. package/dist/compaction/compaction.js.map +1 -1
  16. package/dist/compaction/loop.d.ts +4 -0
  17. package/dist/compaction/loop.d.ts.map +1 -1
  18. package/dist/compaction/loop.js +7 -2
  19. package/dist/compaction/loop.js.map +1 -1
  20. package/dist/compaction/utils.d.ts +1 -1
  21. package/dist/compaction/utils.d.ts.map +1 -1
  22. package/dist/compaction/utils.js +13 -41
  23. package/dist/compaction/utils.js.map +1 -1
  24. package/dist/compaction/verification.js +2 -2
  25. package/dist/compaction/verification.js.map +1 -1
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +4 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/provider-request-estimator.d.ts +6 -0
  31. package/dist/provider-request-estimator.d.ts.map +1 -0
  32. package/dist/provider-request-estimator.js +105 -0
  33. package/dist/provider-request-estimator.js.map +1 -0
  34. package/dist/provider-request-planner.d.ts +15 -0
  35. package/dist/provider-request-planner.d.ts.map +1 -0
  36. package/dist/provider-request-planner.js +168 -0
  37. package/dist/provider-request-planner.js.map +1 -0
  38. package/dist/provider-tool-projection.d.ts +7 -0
  39. package/dist/provider-tool-projection.d.ts.map +1 -0
  40. package/dist/provider-tool-projection.js +140 -0
  41. package/dist/provider-tool-projection.js.map +1 -0
  42. package/dist/tool-failure-memory.d.ts.map +1 -1
  43. package/dist/tool-failure-memory.js +73 -61
  44. package/dist/tool-failure-memory.js.map +1 -1
  45. package/dist/tool-failure-recovery-gate.d.ts +1 -1
  46. package/dist/tool-failure-recovery-gate.d.ts.map +1 -1
  47. package/dist/tool-failure-recovery-gate.js +8 -8
  48. package/dist/tool-failure-recovery-gate.js.map +1 -1
  49. package/dist/tool-failure-recovery-protocol.d.ts +15 -0
  50. package/dist/tool-failure-recovery-protocol.d.ts.map +1 -0
  51. package/dist/tool-failure-recovery-protocol.js +43 -0
  52. package/dist/tool-failure-recovery-protocol.js.map +1 -0
  53. package/dist/types.d.ts +59 -2
  54. package/dist/types.d.ts.map +1 -1
  55. package/dist/types.js.map +1 -1
  56. package/package.json +2 -2
@@ -50,7 +50,7 @@ export declare class ToolFailureRecoveryGate {
50
50
  admit(tool: AgentTool<any>, args: unknown, record: ToolFailureMemoryRecord | undefined): ToolFailureRecoveryAdmission;
51
51
  apply(effect: ToolFailureRecoveryGateEffect | undefined): ToolFailureRecoveryHalt | undefined;
52
52
  isHalted(): boolean;
53
- private currentHalt;
53
+ getHalt(): ToolFailureRecoveryHalt | undefined;
54
54
  private hasUnchangedRetryRemaining;
55
55
  private getOrCreateState;
56
56
  private observeFailure;
@@ -1 +1 @@
1
- {"version":3,"file":"tool-failure-recovery-gate.d.ts","sourceRoot":"","sources":["../src/tool-failure-recovery-gate.ts"],"names":[],"mappings":"AACA,OAAO,EAGN,KAAK,uBAAuB,EAC5B,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EACX,SAAS,EAET,8BAA8B,EAC9B,eAAe,EACf,MAAM,YAAY,CAAC;AAOpB,eAAO,MAAM,0CAA0C,IAAI,CAAC;AAY5D,MAAM,WAAW,+BAA+B;IAC/C,YAAY,EAAE,MAAM,CAAC;C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AAO,CAAC,kBAAkB;CAS1B"}
@@ -40,7 +40,7 @@ export class ToolFailureRecoveryGate {
40
40
  };
41
41
  }
42
42
  admit(tool, args, record) {
43
- const stateCapacityHalt = this.currentHalt();
43
+ const stateCapacityHalt = this.halted;
44
44
  if (stateCapacityHalt) {
45
45
  return {
46
46
  kind: "blocked",
@@ -100,7 +100,7 @@ export class ToolFailureRecoveryGate {
100
100
  isHalted() {
101
101
  return this.halted !== undefined;
102
102
  }
103
- currentHalt() {
103
+ getHalt() {
104
104
  return this.halted;
105
105
  }
106
106
  hasUnchangedRetryRemaining(tool, args, failureCode, reservation) {
@@ -355,19 +355,19 @@ function formatRecoveryGuidance(failureCode, actions, unchangedRetryRemaining) {
355
355
  const hasTimeoutRetryPolicy = getToolExecutionUnchangedRetryLimit(failureCode) > 0;
356
356
  const timeoutPolicy = hasTimeoutRetryPolicy
357
357
  ? unchangedRetryRemaining
358
- ? "The timeout policy permits one unchanged retry. If it fails, do not retry unchanged again."
359
- : "The timeout policy's unchanged retry is exhausted. Do not retry unchanged."
358
+ ? "Timeout policy allows 1 unchanged retry; if it fails, never retry unchanged."
359
+ : "Timeout unchanged retry exhausted; never retry unchanged."
360
360
  : undefined;
361
361
  if (actions.length === 0) {
362
362
  if (timeoutPolicy)
363
- return `${timeoutPolicy} Change or narrow the operation, or report the blocker.`;
364
- return "No currently loaded tool declares a recovery action for this failure. Do not retry unchanged. Submit only a materially different operation justified by the diagnostic and current tool schema, or report the blocker.";
363
+ return `${timeoutPolicy} Change/narrow operation, or report blocker.`;
364
+ return "No loaded tool declares recovery. Never retry unchanged. Use materially different operation justified by diagnostic/schema, or report blocker.";
365
365
  }
366
366
  const available = actions.map((action) => `${action.toolName} ${action.kind}: ${action.instruction}`).join(" ");
367
367
  const hasRepair = actions.some((action) => action.kind === "repair");
368
368
  const authority = hasRepair
369
- ? "Only exact matching repair evidence permits one probe; otherwise change the operation."
370
- : "These actions require a changed operation and never reopen the unchanged call.";
369
+ ? "Only exact matching repair evidence grants 1 probe; else change operation."
370
+ : "Actions require changed operation; unchanged remains blocked.";
371
371
  return truncate(`${timeoutPolicy ? `${timeoutPolicy} ` : ""}Loaded actions: ${available} ${authority}`, MAX_RECOVERY_GUIDANCE_CHARS);
372
372
  }
373
373
  function truncate(value, maxChars) {
@@ -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;AAC7F,OAAO,EACN,mBAAmB,EACnB,gCAAgC,GAEhC,MAAM,0BAA0B,CAAC;AAOlC,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,CAAC,MAAM,0CAA0C,GAAG,CAAC,CAAC;AAC5D,MAAM,uBAAuB,GAAG,0CAA0C,CAAC;AAC3E,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACjC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AACtC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AACzC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AACxC,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AAuDtD;;;;;;;GAOG;AACH,MAAM,OAAO,uBAAuB;IAApC;QACkB,yBAAoB,GAAG,IAAI,GAAG,EAAgC,CAAC;QAC/D,qBAAgB,GAAG,IAAI,GAAG,EAAkB,CAAC;QACtD,kBAAa,GAAG,CAAC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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 {\n\tgetToolExecutionKey,\n\tgetToolFailureRecordExecutionKey,\n\ttype ToolFailureMemoryRecord,\n} from \"./tool-failure-memory.ts\";\nimport type {\n\tAgentTool,\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;\nexport const TOOL_FAILURE_RECOVERY_ACCOUNTING_WAVE_SIZE = 4;\nconst MAX_FAILURES_PER_FAMILY = TOOL_FAILURE_RECOVERY_ACCOUNTING_WAVE_SIZE;\nconst MAX_FAILURES_PER_RUN = 12;\nconst MAX_RECOVERY_STATES = 64;\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}\n\nexport type ToolFailureRecoveryGateEffect =\n\t| {\n\t\t\tkind: \"failure\";\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: boolean; diagnostic?: string };\n\ninterface FailureRecoveryState {\n\trecord: ToolFailureMemoryRecord;\n\trecoveryTargets: readonly AgentToolFailureRecoveryTarget[];\n\treservedExecutions: number;\n\tfailures: number;\n\tfailureFamilyCounts: Map<string, number>;\n\trecoveryProbes: number;\n\tblockedReplays: number;\n\trecoveryAvailable: boolean;\n}\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 * Owns run-scoped 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 */\nexport class ToolFailureRecoveryGate {\n\tprivate readonly statesByExecutionKey = new Map<string, FailureRecoveryState>();\n\tprivate readonly failuresByFamily = new Map<string, number>();\n\tprivate totalFailures = 0;\n\tprivate halted: ToolFailureRecoveryHalt | undefined;\n\n\tplanFailure(\n\t\tfailedTool: AgentTool<any>,\n\t\targs: unknown,\n\t\tfailureCode: string,\n\t\tavailableTools: readonly AgentTool<any>[],\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): ToolFailureRecoveryPlan {\n\t\tconst targets = readFailureTargets(failedTool, args, failureCode);\n\t\tconst actions = readAvailableRecoveryActions(availableTools, targets);\n\t\tconst unchangedRetryRemaining = this.hasUnchangedRetryRemaining(failedTool, args, failureCode, reservation);\n\t\treturn {\n\t\t\ttargets,\n\t\t\tguidance: formatRecoveryGuidance(failureCode, actions, unchangedRetryRemaining),\n\t\t};\n\t}\n\n\tadmit(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\trecord: ToolFailureMemoryRecord | undefined,\n\t): ToolFailureRecoveryAdmission {\n\t\tconst stateCapacityHalt = this.currentHalt();\n\t\tif (stateCapacityHalt) {\n\t\t\treturn {\n\t\t\t\tkind: \"blocked\",\n\t\t\t\trecord: stateCapacityHalt.record,\n\t\t\t\texhausted: true,\n\t\t\t\tdiagnostic: stateCapacityHalt.diagnostic,\n\t\t\t};\n\t\t}\n\n\t\tconst executionKey = getToolExecutionKey(tool.name, args);\n\t\tlet state = this.statesByExecutionKey.get(executionKey);\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 (this.halted) {\n\t\t\treturn {\n\t\t\t\tkind: \"blocked\",\n\t\t\t\trecord: this.halted.record,\n\t\t\t\texhausted: true,\n\t\t\t\tdiagnostic: this.halted.diagnostic,\n\t\t\t};\n\t\t}\n\t\tif (!state) return { kind: \"allowed\" };\n\n\t\tif (record) state.record = record;\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\tconst diagnostic = `Recovery circuit opened after ${state.blockedReplays} blocked replays of ${state.record.failureCode}.`;\n\t\t\tthis.halted = { record: state.record, diagnostic };\n\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, 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.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\tprivate currentHalt(): 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.statesByExecutionKey.get(executionKey);\n\t\tif (existing) return existing;\n\t\tconst state: FailureRecoveryState = {\n\t\t\trecord,\n\t\t\trecoveryTargets: targets,\n\t\t\treservedExecutions: 0,\n\t\t\tfailures: 0,\n\t\t\tfailureFamilyCounts: new Map(),\n\t\t\trecoveryProbes: 0,\n\t\t\tblockedReplays: 0,\n\t\t\trecoveryAvailable: false,\n\t\t};\n\t\tif (this.statesByExecutionKey.size >= MAX_RECOVERY_STATES) {\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened at the ${MAX_RECOVERY_STATES}-operation state bound.`,\n\t\t\t};\n\t\t\treturn state;\n\t\t}\n\t\tthis.statesByExecutionKey.set(executionKey, state);\n\t\treturn state;\n\t}\n\n\tprivate observeFailure(\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\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\t\tthis.totalFailures++;\n\t\tconst familyKey = `${record.tool}\\0${record.failureCode}`;\n\t\tconst familyFailures = (this.failuresByFamily.get(familyKey) ?? 0) + 1;\n\t\tthis.failuresByFamily.set(familyKey, familyFailures);\n\t\tstate.failureFamilyCounts.set(familyKey, (state.failureFamilyCounts.get(familyKey) ?? 0) + 1);\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\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\treturn;\n\t\t}\n\t\tif (familyFailures >= MAX_FAILURES_PER_FAMILY) {\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened after ${familyFailures} failures in one tool failure family.`,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.totalFailures >= MAX_FAILURES_PER_RUN) {\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened after ${this.totalFailures} tool failures in one run.`,\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\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, state);\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, state: FailureRecoveryState): void {\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t\tthis.totalFailures = Math.max(0, this.totalFailures - state.failures);\n\t\tfor (const [familyKey, stateFailures] of state.failureFamilyCounts) {\n\t\t\tconst remaining = (this.failuresByFamily.get(familyKey) ?? 0) - stateFailures;\n\t\t\tif (remaining > 0) this.failuresByFamily.set(familyKey, remaining);\n\t\t\telse this.failuresByFamily.delete(familyKey);\n\t\t}\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? \"The timeout policy permits one unchanged retry. If it fails, do not retry unchanged again.\"\n\t\t\t: \"The timeout policy's unchanged retry is exhausted. Do not retry unchanged.\"\n\t\t: undefined;\n\tif (actions.length === 0) {\n\t\tif (timeoutPolicy) return `${timeoutPolicy} Change or narrow the operation, or report the blocker.`;\n\t\treturn \"No currently loaded tool declares a recovery action for this failure. Do not retry unchanged. Submit only a materially different operation justified by the diagnostic and current tool schema, or report the 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 permits one probe; otherwise change the operation.\"\n\t\t: \"These actions require a changed operation and never reopen the unchanged call.\";\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;AAC7F,OAAO,EACN,mBAAmB,EACnB,gCAAgC,GAEhC,MAAM,0BAA0B,CAAC;AAOlC,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,CAAC,MAAM,0CAA0C,GAAG,CAAC,CAAC;AAC5D,MAAM,uBAAuB,GAAG,0CAA0C,CAAC;AAC3E,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,oBAA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E,MAAM,SAAS,GAAG,SAAS;QAC1B,CAAC,CAAC,4EAA4E;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 {\n\tgetToolExecutionKey,\n\tgetToolFailureRecordExecutionKey,\n\ttype ToolFailureMemoryRecord,\n} from \"./tool-failure-memory.ts\";\nimport type {\n\tAgentTool,\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;\nexport const TOOL_FAILURE_RECOVERY_ACCOUNTING_WAVE_SIZE = 4;\nconst MAX_FAILURES_PER_FAMILY = TOOL_FAILURE_RECOVERY_ACCOUNTING_WAVE_SIZE;\nconst MAX_FAILURES_PER_RUN = 12;\nconst MAX_RECOVERY_STATES = 64;\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}\n\nexport type ToolFailureRecoveryGateEffect =\n\t| {\n\t\t\tkind: \"failure\";\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: boolean; diagnostic?: string };\n\ninterface FailureRecoveryState {\n\trecord: ToolFailureMemoryRecord;\n\trecoveryTargets: readonly AgentToolFailureRecoveryTarget[];\n\treservedExecutions: number;\n\tfailures: number;\n\tfailureFamilyCounts: Map<string, number>;\n\trecoveryProbes: number;\n\tblockedReplays: number;\n\trecoveryAvailable: boolean;\n}\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 * Owns run-scoped 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 */\nexport class ToolFailureRecoveryGate {\n\tprivate readonly statesByExecutionKey = new Map<string, FailureRecoveryState>();\n\tprivate readonly failuresByFamily = new Map<string, number>();\n\tprivate totalFailures = 0;\n\tprivate halted: ToolFailureRecoveryHalt | undefined;\n\n\tplanFailure(\n\t\tfailedTool: AgentTool<any>,\n\t\targs: unknown,\n\t\tfailureCode: string,\n\t\tavailableTools: readonly AgentTool<any>[],\n\t\treservation: ToolFailureExecutionReservation | undefined,\n\t): ToolFailureRecoveryPlan {\n\t\tconst targets = readFailureTargets(failedTool, args, failureCode);\n\t\tconst actions = readAvailableRecoveryActions(availableTools, targets);\n\t\tconst unchangedRetryRemaining = this.hasUnchangedRetryRemaining(failedTool, args, failureCode, reservation);\n\t\treturn {\n\t\t\ttargets,\n\t\t\tguidance: formatRecoveryGuidance(failureCode, actions, unchangedRetryRemaining),\n\t\t};\n\t}\n\n\tadmit(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\trecord: ToolFailureMemoryRecord | undefined,\n\t): ToolFailureRecoveryAdmission {\n\t\tconst stateCapacityHalt = this.halted;\n\t\tif (stateCapacityHalt) {\n\t\t\treturn {\n\t\t\t\tkind: \"blocked\",\n\t\t\t\trecord: stateCapacityHalt.record,\n\t\t\t\texhausted: true,\n\t\t\t\tdiagnostic: stateCapacityHalt.diagnostic,\n\t\t\t};\n\t\t}\n\n\t\tconst executionKey = getToolExecutionKey(tool.name, args);\n\t\tlet state = this.statesByExecutionKey.get(executionKey);\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 (this.halted) {\n\t\t\treturn {\n\t\t\t\tkind: \"blocked\",\n\t\t\t\trecord: this.halted.record,\n\t\t\t\texhausted: true,\n\t\t\t\tdiagnostic: this.halted.diagnostic,\n\t\t\t};\n\t\t}\n\t\tif (!state) return { kind: \"allowed\" };\n\n\t\tif (record) state.record = record;\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\tconst diagnostic = `Recovery circuit opened after ${state.blockedReplays} blocked replays of ${state.record.failureCode}.`;\n\t\t\tthis.halted = { record: state.record, diagnostic };\n\t\t\treturn { kind: \"blocked\", record: state.record, exhausted: true, 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.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.statesByExecutionKey.get(executionKey);\n\t\tif (existing) return existing;\n\t\tconst state: FailureRecoveryState = {\n\t\t\trecord,\n\t\t\trecoveryTargets: targets,\n\t\t\treservedExecutions: 0,\n\t\t\tfailures: 0,\n\t\t\tfailureFamilyCounts: new Map(),\n\t\t\trecoveryProbes: 0,\n\t\t\tblockedReplays: 0,\n\t\t\trecoveryAvailable: false,\n\t\t};\n\t\tif (this.statesByExecutionKey.size >= MAX_RECOVERY_STATES) {\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened at the ${MAX_RECOVERY_STATES}-operation state bound.`,\n\t\t\t};\n\t\t\treturn state;\n\t\t}\n\t\tthis.statesByExecutionKey.set(executionKey, state);\n\t\treturn state;\n\t}\n\n\tprivate observeFailure(\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\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\t\tthis.totalFailures++;\n\t\tconst familyKey = `${record.tool}\\0${record.failureCode}`;\n\t\tconst familyFailures = (this.failuresByFamily.get(familyKey) ?? 0) + 1;\n\t\tthis.failuresByFamily.set(familyKey, familyFailures);\n\t\tstate.failureFamilyCounts.set(familyKey, (state.failureFamilyCounts.get(familyKey) ?? 0) + 1);\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\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\treturn;\n\t\t}\n\t\tif (familyFailures >= MAX_FAILURES_PER_FAMILY) {\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened after ${familyFailures} failures in one tool failure family.`,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.totalFailures >= MAX_FAILURES_PER_RUN) {\n\t\t\tthis.halted = {\n\t\t\t\trecord,\n\t\t\t\tdiagnostic: `Recovery circuit opened after ${this.totalFailures} tool failures in one run.`,\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\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, state);\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, state: FailureRecoveryState): void {\n\t\tthis.statesByExecutionKey.delete(executionKey);\n\t\tthis.totalFailures = Math.max(0, this.totalFailures - state.failures);\n\t\tfor (const [familyKey, stateFailures] of state.failureFamilyCounts) {\n\t\t\tconst remaining = (this.failuresByFamily.get(familyKey) ?? 0) - stateFailures;\n\t\t\tif (remaining > 0) this.failuresByFamily.set(familyKey, remaining);\n\t\t\telse this.failuresByFamily.delete(familyKey);\n\t\t}\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"]}
@@ -0,0 +1,15 @@
1
+ export declare const TOOL_FAILURE_RECOVERY_PROTOCOL_NAME = "mandatory_tool_failure_recovery";
2
+ export declare const TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION = 1;
3
+ export declare const MANDATORY_TOOL_FAILURE_RECOVERY_RULE = "MANDATORY AND NON-NEGOTIABLE.";
4
+ export declare function mandatoryToolFailureRecoveryMetadata(): {
5
+ MUST: true;
6
+ };
7
+ export declare const MANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT: string;
8
+ export interface MandatoryToolFailureDeliveryData {
9
+ tool: string;
10
+ failureCode: string;
11
+ diagnostic: string;
12
+ requiredAction: string;
13
+ }
14
+ export declare function appendMandatoryToolFailureDeliveryPrompt(systemPrompt: string, failure: MandatoryToolFailureDeliveryData): string;
15
+ //# sourceMappingURL=tool-failure-recovery-protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-failure-recovery-protocol.d.ts","sourceRoot":"","sources":["../src/tool-failure-recovery-protocol.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mCAAmC,oCAAoC,CAAC;AACrF,eAAO,MAAM,sCAAsC,IAAI,CAAC;AACxD,eAAO,MAAM,oCAAoC,kCAAkC,CAAC;AAEpF,wBAAgB,oCAAoC,IAAI;IACvD,IAAI,EAAE,IAAI,CAAC;CACX,CAIA;AAED,eAAO,MAAM,+CAA+C,QAShD,CAAC;AASb,MAAM,WAAW,gCAAgC;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;CACvB;AAED,wBAAgB,wCAAwC,CACvD,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,gCAAgC,GACvC,MAAM,CAiBR"}
@@ -0,0 +1,43 @@
1
+ export const TOOL_FAILURE_RECOVERY_PROTOCOL_NAME = "mandatory_tool_failure_recovery";
2
+ export const TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION = 1;
3
+ export const MANDATORY_TOOL_FAILURE_RECOVERY_RULE = "MANDATORY AND NON-NEGOTIABLE.";
4
+ export function mandatoryToolFailureRecoveryMetadata() {
5
+ return {
6
+ MUST: true,
7
+ };
8
+ }
9
+ export const MANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT = [
10
+ `MANDATORY TOOL FAILURE RECOVERY v${TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION}`,
11
+ MANDATORY_TOOL_FAILURE_RECOVERY_RULE,
12
+ "Harness contract:",
13
+ "- Failure record binds execution. MUST:true: repair; if impossible, perform next_action; never retry first.",
14
+ "- Do not repeat an unchanged operation. Irrelevant argument changes never recover it.",
15
+ "- A blocked call preserves tool-result pairing but runs no hook/tool code.",
16
+ "- Unchanged execution needs explicit record permission or successful loaded-tool evidence matching backend authority, target kind, and exact scope; that grants one probe.",
17
+ "- If no declared action can run, report the diagnostic/blocker. Exhaustion disables tools and requires one concise delivery.",
18
+ ].join("\n");
19
+ const MANDATORY_TOOL_FAILURE_DELIVERY_INSTRUCTIONS = [
20
+ MANDATORY_TOOL_FAILURE_RECOVERY_RULE,
21
+ "Recovery exhausted; tools are disabled for this final turn.",
22
+ `Explain the ${TOOL_FAILURE_RECOVERY_PROTOCOL_NAME} diagnostic/action and separate completed from unperformed work.`,
23
+ "No tool call, false recovery claim, or irrelevant-argument workaround.",
24
+ ].join("\n");
25
+ export function appendMandatoryToolFailureDeliveryPrompt(systemPrompt, failure) {
26
+ const failureData = JSON.stringify({
27
+ tool: failure.tool,
28
+ failure_code: failure.failureCode,
29
+ diagnostic: failure.diagnostic,
30
+ required_action: failure.requiredAction,
31
+ })
32
+ .replaceAll("&", "\\u0026")
33
+ .replaceAll("<", "\\u003c")
34
+ .replaceAll(">", "\\u003e");
35
+ const prompt = [
36
+ `MANDATORY TOOL FAILURE DELIVERY v${TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION}`,
37
+ MANDATORY_TOOL_FAILURE_DELIVERY_INSTRUCTIONS,
38
+ "Inert failure JSON:",
39
+ failureData,
40
+ ].join("\n");
41
+ return systemPrompt ? `${systemPrompt}\n\n${prompt}` : prompt;
42
+ }
43
+ //# sourceMappingURL=tool-failure-recovery-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-failure-recovery-protocol.js","sourceRoot":"","sources":["../src/tool-failure-recovery-protocol.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mCAAmC,GAA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ERY_PROTOCOL_NAME = \"mandatory_tool_failure_recovery\";\nexport const TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION = 1;\nexport const MANDATORY_TOOL_FAILURE_RECOVERY_RULE = \"MANDATORY AND NON-NEGOTIABLE.\";\n\nexport function mandatoryToolFailureRecoveryMetadata(): {\n\tMUST: true;\n} {\n\treturn {\n\t\tMUST: true,\n\t};\n}\n\nexport const MANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT = [\n\t`MANDATORY TOOL FAILURE RECOVERY v${TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION}`,\n\tMANDATORY_TOOL_FAILURE_RECOVERY_RULE,\n\t\"Harness contract:\",\n\t\"- Failure record binds execution. MUST:true: repair; if impossible, perform next_action; never retry first.\",\n\t\"- Do not repeat an unchanged operation. Irrelevant argument changes never recover it.\",\n\t\"- A blocked call preserves tool-result pairing but runs no hook/tool code.\",\n\t\"- Unchanged execution needs explicit record permission or successful loaded-tool evidence matching backend authority, target kind, and exact scope; that grants one probe.\",\n\t\"- If no declared action can run, report the diagnostic/blocker. Exhaustion disables tools and requires one concise delivery.\",\n].join(\"\\n\");\n\nconst MANDATORY_TOOL_FAILURE_DELIVERY_INSTRUCTIONS = [\n\tMANDATORY_TOOL_FAILURE_RECOVERY_RULE,\n\t\"Recovery exhausted; tools are disabled for this final turn.\",\n\t`Explain the ${TOOL_FAILURE_RECOVERY_PROTOCOL_NAME} diagnostic/action and separate completed from unperformed work.`,\n\t\"No tool call, false recovery claim, or irrelevant-argument workaround.\",\n].join(\"\\n\");\n\nexport interface MandatoryToolFailureDeliveryData {\n\ttool: string;\n\tfailureCode: string;\n\tdiagnostic: string;\n\trequiredAction: string;\n}\n\nexport function appendMandatoryToolFailureDeliveryPrompt(\n\tsystemPrompt: string,\n\tfailure: MandatoryToolFailureDeliveryData,\n): string {\n\tconst failureData = JSON.stringify({\n\t\ttool: failure.tool,\n\t\tfailure_code: failure.failureCode,\n\t\tdiagnostic: failure.diagnostic,\n\t\trequired_action: failure.requiredAction,\n\t})\n\t\t.replaceAll(\"&\", \"\\\\u0026\")\n\t\t.replaceAll(\"<\", \"\\\\u003c\")\n\t\t.replaceAll(\">\", \"\\\\u003e\");\n\tconst prompt = [\n\t\t`MANDATORY TOOL FAILURE DELIVERY v${TOOL_FAILURE_RECOVERY_PROTOCOL_VERSION}`,\n\t\tMANDATORY_TOOL_FAILURE_DELIVERY_INSTRUCTIONS,\n\t\t\"Inert failure JSON:\",\n\t\tfailureData,\n\t].join(\"\\n\");\n\treturn systemPrompt ? `${systemPrompt}\\n\\n${prompt}` : prompt;\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -144,7 +144,36 @@ export interface ToolValidationEscalationEvent {
144
144
  }
145
145
  export interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {
146
146
  }
147
- /** Provider-ready request inspected after context transformation and immediately before transport. */
147
+ /** Input for one replay-safe context-planning attempt. */
148
+ export interface AgentContextPlanRequest {
149
+ /** Sanitized durable history used as the compactable portion of this request. */
150
+ messages: AgentMessage[];
151
+ /** Zero-based admission generation; freshness-only retries repeat the same value. */
152
+ attempt: number;
153
+ }
154
+ /**
155
+ * Replay-safe context plan. `messages` is compactable history; `transientMessages` is mandatory,
156
+ * request-local context that compaction must never summarize or drop.
157
+ */
158
+ export interface AgentContextPlan {
159
+ messages: AgentMessage[];
160
+ transientMessages?: AgentMessage[];
161
+ /** Cheap freshness check immediately before admission/commit. */
162
+ isCurrent?: () => boolean;
163
+ /**
164
+ * Pure final validation for expensive projections. Return false to discard and replan; do not
165
+ * mutate durable state here.
166
+ */
167
+ prepareCommit?: () => boolean;
168
+ /**
169
+ * Apply lifecycle side effects after every composed validator passed. Synchronous, infallible by
170
+ * contract, and must not change the planned payload.
171
+ */
172
+ commit?: () => void;
173
+ /** Release request-local planning resources when a plan is not accepted. */
174
+ discard?: () => void;
175
+ }
176
+ /** Provider-ready request inspected after full materialization and immediately before transport. */
148
177
  export interface RequestPreflightContext {
149
178
  model: Model<Api>;
150
179
  context: Context;
@@ -155,6 +184,22 @@ export interface RequestPreflightContext {
155
184
  export interface RequestPreflightResult {
156
185
  maxTokens?: number;
157
186
  }
187
+ /** Exact materialization offered to the host-owned compaction/admission gate. */
188
+ export interface ProviderRequestAdmissionContext extends RequestPreflightContext {
189
+ /** Agent-level request snapshot from which this materialization was planned. */
190
+ sourceContext: AgentContext;
191
+ /** Provider context containing only the non-compactable system/tool/transient envelope. */
192
+ nonCompactableContext: Context;
193
+ /** Zero-based admission generation; increments only after an accepted history replan. */
194
+ attempt: number;
195
+ }
196
+ export type ProviderRequestAdmissionResult = {
197
+ action: "send";
198
+ maxTokens?: number;
199
+ } | {
200
+ action: "replan";
201
+ context: AgentContext;
202
+ };
158
203
  /**
159
204
  * Default runaway-loop backstop: a single identical tool-call signature recurring this many times
160
205
  * within a sliding window (2×) stops the loop. Generous enough that legitimate long/varied work never
@@ -212,7 +257,17 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
212
257
  */
213
258
  transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
214
259
  /**
215
- * Runs after context transformation and conversion, immediately before every provider request.
260
+ * Preferred two-phase replacement for `transformContext`. Planning is replay-safe and may run
261
+ * again after compaction or invalidation; only the accepted plan's `commit` is invoked.
262
+ */
263
+ planContext?: (request: AgentContextPlanRequest, signal?: AbortSignal) => Promise<AgentContextPlan>;
264
+ /**
265
+ * Host-owned admission gate over the complete provider-visible materialization. It may accept the
266
+ * request or compact durable history and return a replacement source context for replanning.
267
+ */
268
+ admitProviderRequest?: (request: ProviderRequestAdmissionContext, signal?: AbortSignal) => ProviderRequestAdmissionResult | Promise<ProviderRequestAdmissionResult>;
269
+ /**
270
+ * Runs after admission against the exact transport-ready context, immediately before every provider request.
216
271
  *
217
272
  * Use this for request-local budget/authority checks whose state can change between tool turns.
218
273
  * Throwing prevents transport. A returned `maxTokens` must be a positive safe integer and can
@@ -497,6 +552,8 @@ export interface AgentToolFailureRecoveryContract<TParameters extends TSchema, T
497
552
  export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {
498
553
  /** Human-readable label for UI display. */
499
554
  label: string;
555
+ /** Compact provider-facing capability description. Execution keeps the full `description`. */
556
+ providerDescription?: string;
500
557
  /**
501
558
  * Optional compatibility shim for raw tool-call arguments before schema validation.
502
559
  * Must return an object that matches `TParameters`.
@@ -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;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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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA6LA;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AA6T1C,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 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/** Provider-ready request inspected after context transformation 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/**\n * Default runaway-loop backstop: a single identical tool-call signature recurring this many times\n * within a sliding window (2×) 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\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 * Runs after context transformation and conversion, 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 (2×), 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 * Observability hook fired once if the {@link maxStallTurns} runaway backstop trips, just before the\n\t * loop stops. Lets the host surface/log why the run ended. Must not throw.\n\t */\n\tonRunawayStop?: (info: { signature: string; repeats: number }) => 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 and reinforces proactive orchestration in capable hosts;\n * delegation can remain available at lower levels. Use model thinking-level metadata from\n * @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/** 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/**\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/** 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/** 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/**\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 }\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 }\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":"AA0OA;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AA4U1C,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 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` is mandatory,\n * request-local context that compaction must never summarize or drop.\n */\nexport interface AgentContextPlan {\n\tmessages: AgentMessage[];\n\ttransientMessages?: AgentMessage[];\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 (2×) 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\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 (2×), 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 * Observability hook fired once if the {@link maxStallTurns} runaway backstop trips, just before the\n\t * loop stops. Lets the host surface/log why the run ended. Must not throw.\n\t */\n\tonRunawayStop?: (info: { signature: string; repeats: number }) => 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 and reinforces proactive orchestration in capable hosts;\n * delegation can remain available at lower levels. Use model thinking-level metadata from\n * @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/** 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/**\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/** 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/** 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 }\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 }\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.86.17",
3
+ "version": "0.90.0",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -121,7 +121,7 @@
121
121
  "prepublishOnly": "npm run clean && npm run build"
122
122
  },
123
123
  "dependencies": {
124
- "@caupulican/pi-ai": "^0.86.17",
124
+ "@caupulican/pi-ai": "^0.90.0",
125
125
  "ignore": "7.0.5",
126
126
  "typebox": "1.1.38",
127
127
  "yaml": "2.9.0"