@caupulican/pi-agent-core 0.90.7 → 0.90.11

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 (40) hide show
  1. package/dist/agent-loop.d.ts +1 -1
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +1 -1
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +2 -0
  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/compaction.d.ts.map +1 -1
  10. package/dist/compaction/compaction.js +1 -34
  11. package/dist/compaction/compaction.js.map +1 -1
  12. package/dist/compaction/extraction.d.ts +1 -0
  13. package/dist/compaction/extraction.d.ts.map +1 -1
  14. package/dist/compaction/extraction.js +1 -1
  15. package/dist/compaction/extraction.js.map +1 -1
  16. package/dist/compaction/utils.d.ts +13 -1
  17. package/dist/compaction/utils.d.ts.map +1 -1
  18. package/dist/compaction/utils.js +49 -1
  19. package/dist/compaction/utils.js.map +1 -1
  20. package/dist/compaction/verification.d.ts.map +1 -1
  21. package/dist/compaction/verification.js +154 -6
  22. package/dist/compaction/verification.js.map +1 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -0
  26. package/dist/index.js.map +1 -1
  27. package/dist/provider-request-planner.d.ts +8 -0
  28. package/dist/provider-request-planner.d.ts.map +1 -1
  29. package/dist/provider-request-planner.js +8 -1
  30. package/dist/provider-request-planner.js.map +1 -1
  31. package/dist/provider-tool-projection.d.ts.map +1 -1
  32. package/dist/provider-tool-projection.js +4 -11
  33. package/dist/provider-tool-projection.js.map +1 -1
  34. package/dist/tool-failure-memory.d.ts.map +1 -1
  35. package/dist/tool-failure-memory.js +27 -3
  36. package/dist/tool-failure-memory.js.map +1 -1
  37. package/dist/tool-protocol-residue.d.ts.map +1 -1
  38. package/dist/tool-protocol-residue.js +58 -18
  39. package/dist/tool-protocol-residue.js.map +1 -1
  40. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"tool-failure-memory.js","sourceRoot":"","sources":["../src/tool-failure-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,6BAA6B,EAC7B,2BAA2B,GAE3B,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EACN,+CAA+C,EAC/C,oCAAoC,GACpC,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D,MAAM,2BAA2B,GAAG,CAAC,CAAC;AACtC,MAAM,8BAA8B,GAAG,CAAC,CAAC;AACzC,MAAM,0BAA0B,GAAG,MAAM,CAAC,yBAAyB,CAAC,CAAC;AACrE,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAC9B,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,0BAA0B,GAAG,IAAI,GAAG,CAAC,CAAC,mBAAmB,EAAE,gBAAgB,EAAE,cAAc,CAAC,CAAC,CAAC;AACpG,MAAM,mCAAmC,GACxC,0FAA0F,CAAC;AAC5F,MAAM,iCAAiC,GACtC,yLAAyL,CAAC;AAC3L,MAAM,mCAAmC,GACxC,yRAAyR,CAAC;AA4D3R,SAAS,QAAQ,CAAC,KAAa,EAAE,QAAgB;IAChD,IAAI,KAAK,CAAC,MAAM,IAAI,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC3C,IAAI,GAAG,GAAG,QAAQ,GAAG,CAAC,CAAC;IACvB,MAAM,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,GAAG,GA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Memory,\n\tgetToolExecutionErrorPolicy,\n\ttype ToolFailurePhase,\n} from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type { AssistantMessage, ToolResultMessage } from \"@caupulican/pi-ai/types\";\nimport {\n\tMANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT,\n\tmandatoryToolFailureRecoveryMetadata,\n} from \"./tool-failure-recovery-protocol.ts\";\nimport type { AgentMessage, AgentToolCall, AgentToolResult } from \"./types.ts\";\nimport { sanitizeBinaryOutput } from \"./utils/shell-output.ts\";\n\nconst TOOL_FAILURE_MEMORY_VERSION = 1;\nconst TOOL_FAILURE_DIRECTIVE_VERSION = 1;\nconst TOOL_FAILURE_EXECUTION_KEY = Symbol(\"ToolFailureExecutionKey\");\nconst MAX_OPERATION_CHARS = 240;\nconst MAX_FAILURE_CODE_CHARS = 48;\nconst MAX_DIAGNOSTIC_CHARS = 240;\nconst MAX_CORRECTION_CHARS = 320;\nconst MAX_TOOL_NAME_CHARS = 64;\nconst TOOL_SIGNATURE_HEX_CHARS = 32;\nconst MAX_ACTIVE_FAILURES = 8;\nconst MAX_TRACKED_FAILURES = 64;\nconst REPAIRABLE_REJECTION_CODES = new Set([\"invalid_arguments\", \"malformed_call\", \"unknown_tool\"]);\nconst LEGACY_GENERIC_EXECUTION_CORRECTION =\n\t\"Change the arguments or approach before retrying; do not resend the unchanged operation.\";\nconst BLOCKED_REPLAY_CAVEMAN_CORRECTION =\n\t\"CAVEMAN MODE - MANDATORY. SAME OPERATION BLOCKED. Do not repeat an unchanged operation. NEVER call it again with the same arguments in this run. This is not a harness loop or failure.\";\nconst CLOSED_OPERATION_CAVEMAN_CORRECTION =\n\t\"CAVEMAN MODE - MANDATORY: OPERATION CLOSED; not executed. Do not repeat an unchanged operation. NEVER call it again with the same arguments in this run. Use a different operation/tool or continue independent work. The recovery guard prevented a loop; this is not harness failure.\";\n\nexport type ToolFailureState = \"failed\" | \"rejected\";\n\nexport interface ToolFailureMemoryRecord {\n\tversion: typeof TOOL_FAILURE_MEMORY_VERSION;\n\tfailureKey: string;\n\t/** Exact identity is process-internal and omitted from serialized failure memory. */\n\treadonly [TOOL_FAILURE_EXECUTION_KEY]?: string;\n\ttool: string;\n\toperation: string;\n\toccurrence: number;\n\tkindMistakes?: number;\n\tmistakeKind?: string;\n\tstate: ToolFailureState;\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tdiagnostic?: string;\n\tcorrection: string;\n\tattemptMemory?: \"discard\";\n}\n\nexport interface ToolFailureMemoryDetails {\n\tpiToolFailureMemory: ToolFailureMemoryRecord;\n}\n\nexport interface ToolFailureDirectiveDetails {\n\tpiToolFailureDirective: {\n\t\tversion: typeof TOOL_FAILURE_DIRECTIVE_VERSION;\n\t\tstate: ToolFailureState;\n\t\tphase: ToolFailurePhase;\n\t\tfailureCode: string;\n\t\tdiagnostic?: string;\n\t\tnextAction: string;\n\t};\n}\n\nexport type ToolFailureResultDetails = ToolFailureMemoryDetails | ToolFailureDirectiveDetails;\n\nexport type ToolFailureMemoryTracker = Map<string, ToolFailureMemoryRecord>;\n\ninterface ToolOperationIdentity {\n\tfailureKey: string;\n\texecutionKey: string;\n\ttool: string;\n\toperation: string;\n}\n\ninterface ActiveFailure {\n\trecord: ToolFailureMemoryRecord;\n\tsequence: number;\n}\n\ninterface FailureContextAnalysis {\n\tmessages: AgentMessage[];\n\tactiveRecords: ToolFailureMemoryRecord[];\n\tactiveDirectives: ToolFailureDirectiveDetails[\"piToolFailureDirective\"][];\n\tkindMistakesSummary: Record<string, number>;\n}\n\nfunction truncate(value: string, maxChars: number): string {\n\tif (value.length <= maxChars) return value;\n\tlet end = maxChars - 1;\n\tconst code = value.charCodeAt(end - 1);\n\tif (code >= 0xd800 && code <= 0xdbff) end--;\n\treturn `${value.slice(0, end)}…`;\n}\n\nfunction truncateMiddle(value: string, maxChars: number): string {\n\tif (value.length <= maxChars) return value;\n\tconst available = maxChars - 1;\n\tlet headEnd = Math.ceil(available / 2);\n\tlet tailStart = value.length - Math.floor(available / 2);\n\tconst headCode = value.charCodeAt(headEnd - 1);\n\tif (headCode >= 0xd800 && headCode <= 0xdbff) headEnd--;\n\tconst tailCode = value.charCodeAt(tailStart);\n\tif (tailCode >= 0xdc00 && tailCode <= 0xdfff) tailStart++;\n\treturn `${value.slice(0, headEnd)}…${value.slice(tailStart)}`;\n}\n\nfunction safeJson(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"null\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\ninterface SignatureHash {\n\tfirst: number;\n\tsecond: number;\n\tthird: number;\n\tfourth: number;\n}\n\nconst VOLATILE_SIGNATURE_PATTERN =\n\t/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})|(\\d{4}-\\d{2}-\\d{2}[tT][0-9:.]+(?:z|[+-]\\d{2}:?\\d{2})?)|(\\b[0-9a-f]{16,}\\b)|(\\d{10,})/gi;\nconst MAX_SIGNATURE_DEPTH = 128;\nconst MAX_PREVIEW_DEPTH = 6;\nconst MAX_PREVIEW_ITEMS = 8;\nconst MAX_PREVIEW_STRING_CHARS = 96;\n\nfunction updateHashCode(hash: SignatureHash, code: number): void {\n\thash.first = Math.imul(hash.first ^ code, 0x01000193);\n\thash.second = Math.imul(hash.second ^ code, 0x85ebca6b);\n\thash.third = Math.imul(hash.third ^ code, 0x27d4eb2d);\n\thash.fourth = Math.imul(hash.fourth ^ code, 0x165667b1);\n}\n\nfunction updateHashRange(hash: SignatureHash, value: string, start = 0, end = value.length): void {\n\tfor (let index = start; index < end; index++) updateHashCode(hash, value.charCodeAt(index));\n}\n\nfunction updateNormalizedHashString(hash: SignatureHash, value: string): void {\n\tif (value.length < 10) {\n\t\tupdateExactHashString(hash, value);\n\t\treturn;\n\t}\n\tVOLATILE_SIGNATURE_PATTERN.lastIndex = 0;\n\tlet offset = 0;\n\tlet normalizedLength = value.length;\n\tfor (const match of value.matchAll(VOLATILE_SIGNATURE_PATTERN)) {\n\t\tconst index = match.index;\n\t\tupdateHashRange(hash, value, offset, index);\n\t\tconst replacement = match[1] ? \"<uuid>\" : match[2] ? \"<ts>\" : match[3] ? \"<hex>\" : \"<num>\";\n\t\tupdateHashRange(hash, replacement);\n\t\tnormalizedLength += replacement.length - match[0].length;\n\t\toffset = index + match[0].length;\n\t}\n\tupdateHashRange(hash, value, offset);\n\tupdateHashRange(hash, `:${normalizedLength};`);\n}\n\nfunction updateExactHashString(hash: SignatureHash, value: string): void {\n\tupdateHashRange(hash, value);\n\tupdateHashRange(hash, `:${value.length};`);\n}\n\nfunction updateStructuredHash(\n\thash: SignatureHash,\n\tvalue: unknown,\n\tactive: Set<object>,\n\tdepth: number,\n\tupdateHashString: (hash: SignatureHash, value: string) => void,\n): void {\n\tif (depth > MAX_SIGNATURE_DEPTH) {\n\t\tupdateHashRange(hash, \"depth;\");\n\t\treturn;\n\t}\n\tif (value === null) {\n\t\tupdateHashRange(hash, \"null;\");\n\t\treturn;\n\t}\n\tswitch (typeof value) {\n\t\tcase \"string\":\n\t\t\tupdateHashRange(hash, \"string:\");\n\t\t\tupdateHashString(hash, value);\n\t\t\treturn;\n\t\tcase \"number\":\n\t\t\tupdateHashRange(hash, \"number:\");\n\t\t\tupdateHashString(hash, Object.is(value, -0) ? \"-0\" : String(value));\n\t\t\treturn;\n\t\tcase \"boolean\":\n\t\t\tupdateHashRange(hash, value ? \"true;\" : \"false;\");\n\t\t\treturn;\n\t\tcase \"undefined\":\n\t\t\tupdateHashRange(hash, \"undefined;\");\n\t\t\treturn;\n\t\tcase \"bigint\":\n\t\t\tupdateHashRange(hash, `bigint:${value.toString()};`);\n\t\t\treturn;\n\t\tcase \"symbol\":\n\t\t\tupdateHashRange(hash, `symbol:${String(value.description ?? \"\")};`);\n\t\t\treturn;\n\t\tcase \"function\":\n\t\t\tupdateHashRange(hash, `function:${value.name};`);\n\t\t\treturn;\n\t\tcase \"object\":\n\t\t\tbreak;\n\t}\n\n\tif (active.has(value)) {\n\t\tupdateHashRange(hash, \"circular;\");\n\t\treturn;\n\t}\n\tactive.add(value);\n\tif (Array.isArray(value)) {\n\t\tupdateHashRange(hash, `array:${value.length}[`);\n\t\tfor (const item of value) updateStructuredHash(hash, item, active, depth + 1, updateHashString);\n\t\tupdateHashRange(hash, \"];\");\n\t} else {\n\t\tconst keys = Object.keys(value).sort();\n\t\tupdateHashRange(hash, `object:${keys.length}{`);\n\t\tfor (const key of keys) {\n\t\t\tupdateHashString(hash, key);\n\t\t\tupdateStructuredHash(hash, (value as Record<string, unknown>)[key], active, depth + 1, updateHashString);\n\t\t}\n\t\tupdateHashRange(hash, \"};\");\n\t}\n\tactive.delete(value);\n}\n\nfunction createSignatureHash(): SignatureHash {\n\treturn {\n\t\tfirst: 0x811c9dc5,\n\t\tsecond: 0x9e3779b9,\n\t\tthird: 0x85ebca6b,\n\t\tfourth: 0xc2b2ae35,\n\t};\n}\n\nfunction renderSignatureHash(hash: SignatureHash): string {\n\treturn [hash.first, hash.second, hash.third, hash.fourth]\n\t\t.map((part) => (part >>> 0).toString(16).padStart(8, \"0\"))\n\t\t.join(\"\");\n}\n\nfunction structuredHash(value: unknown, normalizeVolatile: boolean): string {\n\tconst hash = createSignatureHash();\n\tupdateStructuredHash(\n\t\thash,\n\t\tvalue,\n\t\tnew Set(),\n\t\t0,\n\t\tnormalizeVolatile ? updateNormalizedHashString : updateExactHashString,\n\t);\n\treturn renderSignatureHash(hash);\n}\n\nfunction boundedJsonPreview(value: unknown, maxChars: number): string {\n\tlet output = \"\";\n\tlet exhausted = false;\n\tconst active = new Set<object>();\n\tconst append = (text: string): void => {\n\t\tif (exhausted) return;\n\t\tconst available = maxChars - output.length;\n\t\tif (text.length <= available) {\n\t\t\toutput += text;\n\t\t\treturn;\n\t\t}\n\t\tif (available > 1) output += `${text.slice(0, available - 1)}…`;\n\t\texhausted = true;\n\t};\n\tconst visit = (item: unknown, depth: number): void => {\n\t\tif (exhausted) return;\n\t\tif (depth > MAX_PREVIEW_DEPTH) {\n\t\t\tappend('\"[depth]\"');\n\t\t\treturn;\n\t\t}\n\t\tif (typeof item === \"string\") {\n\t\t\tappend(safeJson(truncateMiddle(item, MAX_PREVIEW_STRING_CHARS)));\n\t\t\treturn;\n\t\t}\n\t\tif (item === null || typeof item === \"number\" || typeof item === \"boolean\") {\n\t\t\tappend(String(item));\n\t\t\treturn;\n\t\t}\n\t\tif (typeof item !== \"object\") {\n\t\t\tappend(safeJson(`[${typeof item}]`));\n\t\t\treturn;\n\t\t}\n\t\tif (active.has(item)) {\n\t\t\tappend('\"[circular]\"');\n\t\t\treturn;\n\t\t}\n\t\tactive.add(item);\n\t\tif (Array.isArray(item)) {\n\t\t\tappend(\"[\");\n\t\t\tconst count = Math.min(item.length, MAX_PREVIEW_ITEMS);\n\t\t\tfor (let index = 0; index < count && !exhausted; index++) {\n\t\t\t\tif (index > 0) append(\",\");\n\t\t\t\tvisit(item[index], depth + 1);\n\t\t\t}\n\t\t\tif (item.length > count) append(`${count > 0 ? \",\" : \"\"}\"[+${item.length - count} items]\"`);\n\t\t\tappend(\"]\");\n\t\t} else {\n\t\t\tappend(\"{\");\n\t\t\tlet count = 0;\n\t\t\tlet omitted = 0;\n\t\t\tconst keys = Object.keys(item).sort();\n\t\t\tfor (const key of keys) {\n\t\t\t\tif (count >= MAX_PREVIEW_ITEMS) {\n\t\t\t\t\tomitted++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (count > 0) append(\",\");\n\t\t\t\tappend(safeJson(truncateMiddle(key, MAX_PREVIEW_STRING_CHARS)));\n\t\t\t\tappend(\":\");\n\t\t\t\tvisit((item as Record<string, unknown>)[key], depth + 1);\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tif (omitted > 0) append(`${count > 0 ? \",\" : \"\"}\"[omitted]\":${omitted}`);\n\t\t\tappend(\"}\");\n\t\t}\n\t\tactive.delete(item);\n\t};\n\tvisit(value, 0);\n\treturn truncateMiddle(output || \"null\", maxChars);\n}\n\n/**\n * Fingerprint a tool operation without materializing or retaining its serialized payload.\n * Volatile identifiers normalize before hashing; short numbers and ordinary paths remain significant.\n */\nexport function normalizeToolSignature(pairs: Array<[string, unknown]>): string {\n\treturn structuredHash(pairs, true);\n}\n\nfunction toolOperationKey(tool: string, args: unknown, normalizeVolatile: boolean): string {\n\tconst boundedTool = truncate(tool, MAX_TOOL_NAME_CHARS);\n\tconst hash = createSignatureHash();\n\tconst updateHashString = normalizeVolatile ? updateNormalizedHashString : updateExactHashString;\n\tconst active = new Set<object>();\n\t// Preserve the stable structured-hash wire identity without allocating the two synthetic arrays.\n\tupdateHashRange(hash, \"array:1[array:2[\");\n\tupdateStructuredHash(hash, tool, active, 2, updateHashString);\n\tupdateStructuredHash(hash, args, active, 2, updateHashString);\n\tupdateHashRange(hash, \"];];\");\n\tconst signature = renderSignatureHash(hash);\n\treturn `${boundedTool}:${signature}`;\n}\n\nfunction operationIdentity(tool: string, args: unknown): ToolOperationIdentity {\n\treturn {\n\t\tfailureKey: toolOperationKey(tool, args, true),\n\t\texecutionKey: toolOperationKey(tool, args, false),\n\t\ttool: truncate(tool, MAX_TOOL_NAME_CHARS),\n\t\toperation: boundedJsonPreview(args, MAX_OPERATION_CHARS),\n\t};\n}\n\nfunction getToolFailureKey(tool: string, args: unknown): string {\n\treturn toolOperationKey(tool, args, true);\n}\n\nexport function getToolExecutionKey(tool: string, args: unknown): string {\n\treturn toolOperationKey(tool, args, false);\n}\n\nexport function getToolFailureRecordExecutionKey(record: ToolFailureMemoryRecord): string | undefined {\n\treturn record[TOOL_FAILURE_EXECUTION_KEY];\n}\n\nexport function getUnresolvedToolFailure(\n\ttracker: ToolFailureMemoryTracker,\n\ttool: string,\n\targs: unknown,\n): ToolFailureMemoryRecord | undefined {\n\treturn tracker.get(getToolFailureKey(tool, args));\n}\n\nfunction boundedFailureCode(value: string): string {\n\tconst normalized = value\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_.:-]+/g, \"_\")\n\t\t.replace(/^_+|_+$/g, \"\");\n\treturn truncate(normalized || \"tool_error\", MAX_FAILURE_CODE_CHARS);\n}\n\nfunction processExitFailureCode(message: string): string | undefined {\n\tconst exitCode = /\\b(?:exit(?:ed)?(?: with)?(?: code)?|exitcode)\\s*[:=]?\\s*(-?\\d+)\\b/i.exec(message)?.[1];\n\treturn exitCode === undefined ? undefined : boundedFailureCode(`exit_${exitCode}`);\n}\n\nexport function classifyToolFailure(message: string, errorClass?: string): string {\n\t// A tool-owned terminal status is authoritative; stdout may contain arbitrary all-caps identifiers.\n\tconst exitFailureCode = processExitFailureCode(message);\n\tif (exitFailureCode) return exitFailureCode;\n\tconst errno = /\\b(E[A-Z][A-Z0-9_]{2,})\\b/.exec(message)?.[1];\n\tif (errno) return boundedFailureCode(errno);\n\treturn boundedFailureCode(errorClass ?? \"tool_error\");\n}\n\nfunction isToolFailurePhase(value: unknown): value is ToolFailurePhase {\n\treturn (\n\t\tvalue === \"validation\" ||\n\t\tvalue === \"policy\" ||\n\t\tvalue === \"preflight\" ||\n\t\tvalue === \"execution\" ||\n\t\tvalue === \"timeout\" ||\n\t\tvalue === \"cancelled\" ||\n\t\tvalue === \"provisioning\"\n\t);\n}\n\nfunction inferToolFailurePhase(state: ToolFailureState, failureCode: string): ToolFailurePhase {\n\tif (failureCode === \"malformed_call\" || failureCode === \"unknown_tool\" || failureCode === \"invalid_arguments\") {\n\t\treturn \"validation\";\n\t}\n\tif (failureCode === \"blocked\" || failureCode === \"permission_denied\") return \"policy\";\n\tif (failureCode === \"preflight_error\") return \"preflight\";\n\tif (failureCode === \"aborted\" || failureCode === \"cancelled\") return \"cancelled\";\n\tif (failureCode === \"timeout\" || failureCode === \"etimedout\") return \"timeout\";\n\tif (failureCode === \"provisioning_failed\" || failureCode === \"command_not_found\") return \"provisioning\";\n\treturn state === \"rejected\" ? \"validation\" : \"execution\";\n}\n\nfunction fallbackFailureGuidance(state: ToolFailureState, hasDiagnostic: boolean, phase: ToolFailurePhase): string {\n\tif (phase === \"preflight\") {\n\t\treturn hasDiagnostic\n\t\t\t? \"Arguments valid; preflight failed before execution. Resolve diagnostic/host condition before retry.\"\n\t\t\t: \"Arguments valid; preflight failed before execution. Inspect host policy/capability before retry.\";\n\t}\n\tif (phase === \"policy\") return \"Resolve authority/policy restriction or choose allowed approach before retry.\";\n\tif (phase === \"cancelled\") return \"Retry only when operation remains required, cancellation condition cleared.\";\n\tif (phase === \"timeout\") return \"Narrow/split work; retry once only when safe.\";\n\tif (phase === \"provisioning\") {\n\t\treturn hasDiagnostic\n\t\t\t? \"Fix provisioning diagnostic; retry only after environment changes.\"\n\t\t\t: \"Inspect tool availability; request bounded provisioning diagnostic before retry.\";\n\t}\n\treturn state === \"rejected\"\n\t\t? \"Re-read current tool schema; change invalid operation before retry.\"\n\t\t: hasDiagnostic\n\t\t\t? \"Read diagnostic; identify cause; repair parameters or corrective state before retry.\"\n\t\t\t: \"No diagnostic output. Inspect tool contract or request bounded diagnostic before retry.\";\n}\n\nexport function toolFailureCorrection(\n\tmessage: string,\n\tstate: ToolFailureState,\n\tphase: ToolFailurePhase = state === \"rejected\" ? \"validation\" : \"execution\",\n): string {\n\tconst policy = getToolExecutionErrorPolicy(message);\n\treturn policy\n\t\t? truncate(policy.guidance, MAX_CORRECTION_CHARS)\n\t\t: fallbackFailureGuidance(state, message.trim().length > 0, phase);\n}\n\nfunction extractFailureDiagnostic(\n\tmessage: string,\n\tallowUnclassifiedFallback: boolean,\n\trequireStrongSignal = false,\n): string | undefined {\n\tconst rawLines = sanitizeBinaryOutput(message).replaceAll(\"\\r\\n\", \"\\n\").split(\"\\n\");\n\tconst strongDiagnosticPattern =\n\t\t/^(?:(?:error(?:\\[[^\\]]+\\])?|fatal(?: error)?|panic|fail(?:ed|ure)?|invalid|unknown|unsupported|not found|no such|cannot|can't|missing|denied|refused|usage)(?:\\b|:)|[a-z][a-z0-9_.]*error(?::|$)|thread .+ panicked at\\b|--- fail:|\\[fail(?:ed)?\\]|not ok\\b|[×✗]\\s|.{1,160}:\\s+(?:error(?:\\[[^\\]]+\\])?|fatal(?: error)?)(?:\\b|:))/i;\n\tconst stderrMarkerIndex = rawLines.findLastIndex((line) => /^stderr:\\s*$/i.test(line.trim()));\n\tif (stderrMarkerIndex >= 0) {\n\t\tconst stderrLines = rawLines\n\t\t\t.slice(stderrMarkerIndex + 1)\n\t\t\t.map((line) => line.trim())\n\t\t\t.filter(\n\t\t\t\t(line) =>\n\t\t\t\t\tline.length > 0 && !/^command (?:exited with code|timed out after|aborted|killed after)\\b/i.test(line),\n\t\t\t);\n\t\tif (stderrLines.length > 0) {\n\t\t\tconst classified = stderrLines.find((line) => strongDiagnosticPattern.test(line));\n\t\t\treturn truncateMiddle(classified ?? stderrLines.slice(-4).join(\" | \"), MAX_DIAGNOSTIC_CHARS);\n\t\t}\n\t}\n\tconst lines = rawLines\n\t\t.map((line) => line.trim())\n\t\t.filter(\n\t\t\t(line) =>\n\t\t\t\tline.length > 0 &&\n\t\t\t\t!/^command (?:exited with code|timed out after|aborted|killed after)\\b/i.test(line) &&\n\t\t\t\t!/^outcome:\\s*(?:failed|aborted|timeout|output_limit)\\b/i.test(line) &&\n\t\t\t\t!/^exitcode:\\s*-?\\d+\\b/i.test(line) &&\n\t\t\t\t!/^(?:stdout|stderr):(?:\\s*\\(empty\\))?$/i.test(line),\n\t\t);\n\tif (lines.length === 0) return undefined;\n\tconst diagnosticPattern = requireStrongSignal\n\t\t? strongDiagnosticPattern\n\t\t: /(?:^|\\b)(?:error|fatal|fail(?:ed|ure)?|invalid|unknown|unsupported|not found|no such|cannot|can't|missing|denied|refused|usage)(?:\\b|:)/i;\n\tconst classified = requireStrongSignal\n\t\t? lines.find((line) => diagnosticPattern.test(line))\n\t\t: [...lines].reverse().find((line) => diagnosticPattern.test(line));\n\tconst diagnostic = classified ?? (allowUnclassifiedFallback ? lines.at(-1) : undefined);\n\treturn diagnostic ? truncateMiddle(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined;\n}\n\nexport interface ToolFailureAssessment {\n\tfailureCode: string;\n\tphase: ToolFailurePhase;\n\tdiagnostic?: string;\n\tguidance: string;\n\tattemptMemory?: \"discard\";\n}\n\nexport function assessToolFailure(\n\tmessage: string,\n\tstate: ToolFailureState,\n\terrorClass?: string,\n): ToolFailureAssessment {\n\tconst policy = getToolExecutionErrorPolicy(message);\n\tconst exitFailureCode = processExitFailureCode(message);\n\tconst retainPolicyDiagnostic = policy?.retainDiagnostic === true;\n\tconst diagnostic =\n\t\tstate === \"failed\" && (!policy || policy.retainDiagnostic)\n\t\t\t? extractFailureDiagnostic(\n\t\t\t\t\tmessage,\n\t\t\t\t\texitFailureCode === undefined && (errorClass !== undefined || retainPolicyDiagnostic),\n\t\t\t\t\texitFailureCode !== undefined && !retainPolicyDiagnostic,\n\t\t\t\t)\n\t\t\t: undefined;\n\tconst failureCode = policy?.failureCode ?? classifyToolFailure(message, errorClass);\n\treturn {\n\t\tfailureCode,\n\t\tphase: policy?.phase ?? inferToolFailurePhase(state, failureCode),\n\t\t...(diagnostic ? { diagnostic } : {}),\n\t\tguidance: policy\n\t\t\t? truncate(policy.guidance, MAX_CORRECTION_CHARS)\n\t\t\t: fallbackFailureGuidance(state, diagnostic !== undefined, inferToolFailurePhase(state, failureCode)),\n\t\t...(policy?.attemptMemory === \"discard\" ? { attemptMemory: \"discard\" as const } : {}),\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readFailureRecord(details: unknown): ToolFailureMemoryRecord | undefined {\n\tif (!isRecord(details) || !isRecord(details.piToolFailureMemory)) return undefined;\n\tconst candidate = details.piToolFailureMemory;\n\tif (\n\t\tcandidate.version !== TOOL_FAILURE_MEMORY_VERSION ||\n\t\ttypeof candidate.failureKey !== \"string\" ||\n\t\ttypeof candidate.tool !== \"string\" ||\n\t\ttypeof candidate.operation !== \"string\" ||\n\t\ttypeof candidate.occurrence !== \"number\" ||\n\t\t!Number.isSafeInteger(candidate.occurrence) ||\n\t\tcandidate.occurrence < 1 ||\n\t\t(candidate.state !== \"failed\" && candidate.state !== \"rejected\") ||\n\t\ttypeof candidate.failureCode !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\tconst diagnostic =\n\t\ttypeof candidate.diagnostic === \"string\" ? truncate(candidate.diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined;\n\tconst retainedCorrection =\n\t\ttypeof candidate.correction === \"string\" ? truncate(candidate.correction, MAX_CORRECTION_CHARS) : undefined;\n\tconst correction =\n\t\tcandidate.state === \"failed\" && retainedCorrection === LEGACY_GENERIC_EXECUTION_CORRECTION\n\t\t\t? fallbackFailureGuidance(\"failed\", diagnostic !== undefined, \"execution\")\n\t\t\t: (retainedCorrection ?? toolFailureCorrection(\"\", candidate.state));\n\tconst phase = isToolFailurePhase(candidate.phase)\n\t\t? candidate.phase\n\t\t: inferToolFailurePhase(candidate.state, candidate.failureCode);\n\tconst candidateExecutionKey: unknown = Reflect.get(candidate, TOOL_FAILURE_EXECUTION_KEY);\n\treturn {\n\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\tfailureKey: truncate(candidate.failureKey, MAX_TOOL_NAME_CHARS + 1 + TOOL_SIGNATURE_HEX_CHARS),\n\t\t...(typeof candidateExecutionKey === \"string\"\n\t\t\t? {\n\t\t\t\t\t[TOOL_FAILURE_EXECUTION_KEY]: truncate(\n\t\t\t\t\t\tcandidateExecutionKey,\n\t\t\t\t\t\tMAX_TOOL_NAME_CHARS + 1 + TOOL_SIGNATURE_HEX_CHARS,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\ttool: truncate(candidate.tool, MAX_TOOL_NAME_CHARS),\n\t\toperation: truncateMiddle(candidate.operation, MAX_OPERATION_CHARS),\n\t\toccurrence: candidate.occurrence,\n\t\tstate: candidate.state,\n\t\tphase,\n\t\tfailureCode: boundedFailureCode(candidate.failureCode),\n\t\tdiagnostic,\n\t\tcorrection,\n\t};\n}\n\nfunction readFailureDirective(details: unknown): ToolFailureDirectiveDetails[\"piToolFailureDirective\"] | undefined {\n\tif (!isRecord(details) || !isRecord(details.piToolFailureDirective)) return undefined;\n\tconst candidate = details.piToolFailureDirective;\n\tif (\n\t\tcandidate.version !== TOOL_FAILURE_DIRECTIVE_VERSION ||\n\t\ttypeof candidate.failureCode !== \"string\" ||\n\t\ttypeof candidate.nextAction !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tversion: TOOL_FAILURE_DIRECTIVE_VERSION,\n\t\tstate: candidate.state === \"rejected\" ? \"rejected\" : \"failed\",\n\t\tphase: isToolFailurePhase(candidate.phase)\n\t\t\t? candidate.phase\n\t\t\t: inferToolFailurePhase(\"failed\", candidate.failureCode),\n\t\tfailureCode: boundedFailureCode(candidate.failureCode),\n\t\tdiagnostic:\n\t\t\ttypeof candidate.diagnostic === \"string\" ? truncate(candidate.diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,\n\t\tnextAction: truncate(candidate.nextAction, MAX_CORRECTION_CHARS),\n\t};\n}\n\nexport interface ToolFailureTelemetry {\n\tstate: ToolFailureState;\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tdiagnostic?: string;\n\tnextAction: string;\n}\n\n/** Read only bounded failure identity and guidance; operation arguments never cross this telemetry boundary. */\nexport function readToolFailureTelemetry(details: unknown): ToolFailureTelemetry | undefined {\n\tconst record = readFailureRecord(details);\n\tif (record) {\n\t\treturn {\n\t\t\tstate: record.state,\n\t\t\tphase: record.phase,\n\t\t\tfailureCode: record.failureCode,\n\t\t\t...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),\n\t\t\tnextAction: record.correction,\n\t\t};\n\t}\n\tconst directive = readFailureDirective(details);\n\tif (!directive) return undefined;\n\treturn {\n\t\tstate: directive.state,\n\t\tphase: directive.phase,\n\t\tfailureCode: directive.failureCode,\n\t\t...(directive.diagnostic ? { diagnostic: directive.diagnostic } : {}),\n\t\tnextAction: directive.nextAction,\n\t};\n}\n\nfunction firstText(message: ToolResultMessage): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\tfor (let index = 0; index < content.length; index++) {\n\t\t\tconst block = content[index];\n\t\t\tif (block.type === \"text\") return block.text;\n\t\t}\n\t}\n\treturn \"\";\n}\n\nfunction fastTextSignature(text: string): string {\n\tif (text.length <= 128) return text;\n\treturn `${text.length}:${text.slice(0, 48)}:${text.slice(-48)}`;\n}\n\nfunction analyzeToolFailureContext(messages: AgentMessage[]): FailureContextAnalysis {\n\tconst callById = new Map<string, AgentToolCall>();\n\tconst omittedCallIds = new Set<string>();\n\tconst orphanFailedResults = new Set<ToolResultMessage>();\n\tconst active = new Map<string, ActiveFailure>();\n\tconst activeDirectives = new Map<string, ToolFailureDirectiveDetails[\"piToolFailureDirective\"]>();\n\tlet sequence = 0;\n\tconst kindMistakesMap = new Map<string, number>();\n\n\tconst latestSuccessfulByOpKey = new Map<string, string>();\n\tconst latestSuccessfulByPayloadKey = new Map<string, string>();\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (message.role === \"assistant\") {\n\t\t\tactiveDirectives.clear();\n\t\t\tconst content = message.content;\n\t\t\tfor (let blockIdx = 0; blockIdx < content.length; blockIdx++) {\n\t\t\t\tconst block = content[blockIdx];\n\t\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\t\tcallById.set(block.id, block);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"toolResult\") continue;\n\n\t\tconst call = callById.get(message.toolCallId);\n\t\tcallById.delete(message.toolCallId);\n\t\tconst textPayload = firstText(message);\n\t\tconst isFailure = message.isError === true || textPayload.startsWith(\"[harness] \");\n\t\tif (isFailure) {\n\t\t\tconst toolName = call?.name ?? message.toolName;\n\t\t\tconst kindCount = (kindMistakesMap.get(toolName) ?? 0) + 1;\n\t\t\tkindMistakesMap.set(toolName, kindCount);\n\n\t\t\tconst directive = readFailureDirective(message.details);\n\t\t\tif (directive) {\n\t\t\t\tactiveDirectives.delete(directive.failureCode);\n\t\t\t\tactiveDirectives.set(directive.failureCode, directive);\n\t\t\t\tif (call) omittedCallIds.add(call.id);\n\t\t\t\telse orphanFailedResults.add(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst retained = readFailureRecord(message.details);\n\t\t\tconst state = retained?.state ?? \"failed\";\n\t\t\tconst assessment = retained ? undefined : assessToolFailure(textPayload, state);\n\t\t\tlet failureKey: string;\n\t\t\tlet executionKey: string | undefined;\n\t\t\tlet tool: string;\n\t\t\tlet operation: string;\n\t\t\tif (retained) {\n\t\t\t\tfailureKey = retained.failureKey;\n\t\t\t\texecutionKey = call\n\t\t\t\t\t? getToolExecutionKey(call.name, call.arguments)\n\t\t\t\t\t: getToolFailureRecordExecutionKey(retained);\n\t\t\t\ttool = retained.tool;\n\t\t\t\toperation = retained.operation;\n\t\t\t} else {\n\t\t\t\tconst identity = operationIdentity(\n\t\t\t\t\tcall?.name ?? message.toolName,\n\t\t\t\t\tcall?.arguments ?? { toolCallId: message.toolCallId },\n\t\t\t\t);\n\t\t\t\tfailureKey = identity.failureKey;\n\t\t\t\texecutionKey = identity.executionKey;\n\t\t\t\ttool = identity.tool;\n\t\t\t\toperation = identity.operation;\n\t\t\t}\n\t\t\tconst previous = active.get(failureKey)?.record;\n\t\t\tconst occurrence = Math.max(retained?.occurrence ?? 0, (previous?.occurrence ?? 0) + 1);\n\t\t\tconst record: ToolFailureMemoryRecord = {\n\t\t\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\t\t\tfailureKey,\n\t\t\t\t...(executionKey ? { [TOOL_FAILURE_EXECUTION_KEY]: executionKey } : {}),\n\t\t\t\ttool,\n\t\t\t\toperation,\n\t\t\t\toccurrence,\n\t\t\t\tkindMistakes: kindCount,\n\t\t\t\tmistakeKind: toolName,\n\t\t\t\tstate,\n\t\t\t\tphase: retained?.phase ?? assessment?.phase ?? inferToolFailurePhase(state, \"tool_error\"),\n\t\t\t\tfailureCode: retained?.failureCode ?? assessment?.failureCode ?? \"tool_error\",\n\t\t\t\tdiagnostic: retained?.diagnostic ?? assessment?.diagnostic,\n\t\t\t\tcorrection:\n\t\t\t\t\tretained?.correction ??\n\t\t\t\t\tassessment?.guidance ??\n\t\t\t\t\tfallbackFailureGuidance(state, false, inferToolFailurePhase(state, \"tool_error\")),\n\t\t\t};\n\t\t\tactive.delete(failureKey);\n\t\t\tactive.set(failureKey, { record, sequence: sequence++ });\n\t\t\twhile (active.size > MAX_TRACKED_FAILURES) {\n\t\t\t\tconst oldest = active.keys().next().value;\n\t\t\t\tif (oldest === undefined) break;\n\t\t\t\tactive.delete(oldest);\n\t\t\t}\n\t\t\tif (call) omittedCallIds.add(call.id);\n\t\t\telse orphanFailedResults.add(message);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (call) {\n\t\t\tconst opKey = getToolFailureKey(call.name, call.arguments);\n\t\t\tactive.delete(opKey);\n\t\t\tconst previousOperationCallId = latestSuccessfulByOpKey.get(opKey);\n\t\t\tif (previousOperationCallId) omittedCallIds.add(previousOperationCallId);\n\t\t\tlatestSuccessfulByOpKey.set(opKey, call.id);\n\n\t\t\tconst textPayload = firstText(message);\n\t\t\tif (textPayload.length >= 64) {\n\t\t\t\tconst payloadKey = `payload:${fastTextSignature(textPayload)}`;\n\t\t\t\tconst previousPayloadCallId = latestSuccessfulByPayloadKey.get(payloadKey);\n\t\t\t\tif (previousPayloadCallId) omittedCallIds.add(previousPayloadCallId);\n\t\t\t\tlatestSuccessfulByPayloadKey.set(payloadKey, call.id);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst kindMistakesSummary = Object.fromEntries(kindMistakesMap);\n\n\tif (omittedCallIds.size === 0 && orphanFailedResults.size === 0) {\n\t\treturn { messages, activeRecords: [], activeDirectives: [], kindMistakesSummary };\n\t}\n\n\tconst filteredMessages: AgentMessage[] = [];\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (message.role === \"toolResult\") {\n\t\t\tif (omittedCallIds.has(message.toolCallId) || orphanFailedResults.has(message)) continue;\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"assistant\") {\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst content = message.content;\n\t\tif (content.length === 1) {\n\t\t\tconst block = content[0];\n\t\t\tif (block.type === \"toolCall\" && omittedCallIds.has(block.id)) continue;\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tlet hasOmitted = false;\n\t\tfor (let blockIdx = 0; blockIdx < content.length; blockIdx++) {\n\t\t\tconst block = content[blockIdx];\n\t\t\tif (block.type === \"toolCall\" && omittedCallIds.has(block.id)) {\n\t\t\t\thasOmitted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!hasOmitted) {\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst retainedContent = content.filter((block) => block.type !== \"toolCall\" || !omittedCallIds.has(block.id));\n\t\tif (retainedContent.length > 0) {\n\t\t\tfilteredMessages.push({ ...message, content: retainedContent } satisfies AssistantMessage);\n\t\t}\n\t}\n\tconst activeRecords = [...active.values()]\n\t\t.sort((left, right) => left.sequence - right.sequence)\n\t\t.map(({ record }) => record);\n\treturn {\n\t\tmessages: filteredMessages,\n\t\tactiveRecords,\n\t\tactiveDirectives: [...activeDirectives.values()],\n\t\tkindMistakesSummary,\n\t};\n}\n\nexport function createToolFailureMemoryTracker(messages: AgentMessage[]): ToolFailureMemoryTracker {\n\treturn new Map(analyzeToolFailureContext(messages).activeRecords.map((record) => [record.failureKey, record]));\n}\n\nexport function rememberToolFailure(\n\ttracker: ToolFailureMemoryTracker,\n\ttool: string,\n\targs: unknown,\n\tstate: ToolFailureState,\n\tfailureCode: string,\n\tcorrection: string,\n\tdiagnostic?: string,\n\tphase: ToolFailurePhase = inferToolFailurePhase(state, failureCode),\n): ToolFailureMemoryRecord {\n\tlet kindCount = 1;\n\tfor (const previous of tracker.values()) {\n\t\tif (previous.tool === tool) {\n\t\t\tkindCount = Math.max(kindCount, (previous.kindMistakes ?? previous.occurrence) + 1);\n\t\t}\n\t}\n\tif (getToolExecutionAttemptMemory(failureCode) === \"discard\") {\n\t\tfor (const [failureKey, previous] of tracker) {\n\t\t\tif (previous.tool === tool && previous.failureCode === failureCode) tracker.delete(failureKey);\n\t\t}\n\t\treturn {\n\t\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\t\tfailureKey: `directive:${boundedFailureCode(failureCode)}`,\n\t\t\t[TOOL_FAILURE_EXECUTION_KEY]: getToolExecutionKey(tool, args),\n\t\t\ttool: truncate(tool, MAX_TOOL_NAME_CHARS),\n\t\t\toperation: \"[discarded]\",\n\t\t\toccurrence: 1,\n\t\t\tkindMistakes: kindCount,\n\t\t\tmistakeKind: tool,\n\t\t\tstate,\n\t\t\tphase,\n\t\t\tfailureCode: boundedFailureCode(failureCode),\n\t\t\tdiagnostic: diagnostic ? truncate(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,\n\t\t\tcorrection: truncate(correction, MAX_CORRECTION_CHARS),\n\t\t\tattemptMemory: \"discard\",\n\t\t};\n\t}\n\tconst identity = operationIdentity(tool, args);\n\tconst previous = tracker.get(identity.failureKey);\n\tconst record: ToolFailureMemoryRecord = {\n\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\tfailureKey: identity.failureKey,\n\t\t[TOOL_FAILURE_EXECUTION_KEY]: identity.executionKey,\n\t\ttool: identity.tool,\n\t\toperation: identity.operation,\n\t\toccurrence: (previous?.occurrence ?? 0) + 1,\n\t\tkindMistakes: kindCount,\n\t\tmistakeKind: tool,\n\t\tstate,\n\t\tphase,\n\t\tfailureCode: boundedFailureCode(failureCode),\n\t\tdiagnostic: diagnostic ? truncate(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,\n\t\tcorrection: truncate(correction, MAX_CORRECTION_CHARS),\n\t};\n\ttracker.delete(identity.failureKey);\n\ttracker.set(identity.failureKey, record);\n\twhile (tracker.size > MAX_TRACKED_FAILURES) {\n\t\tconst oldest = tracker.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\ttracker.delete(oldest);\n\t}\n\treturn record;\n}\n\nexport function clearToolFailure(tracker: ToolFailureMemoryTracker, tool: string, args: unknown): void {\n\tconst failureKey = getToolFailureKey(tool, args);\n\tconst record = tracker.get(failureKey);\n\tconst executionKey = record ? getToolFailureRecordExecutionKey(record) : undefined;\n\tif (!executionKey || executionKey === getToolExecutionKey(tool, args)) tracker.delete(failureKey);\n}\n\nfunction failureGuidance(record: ToolFailureMemoryRecord): { repair: string } | { next_action: string } {\n\treturn record.state === \"rejected\" && REPAIRABLE_REJECTION_CODES.has(record.failureCode)\n\t\t? { repair: record.correction }\n\t\t: { next_action: record.correction };\n}\n\nfunction formatRecordJson(record: ToolFailureMemoryRecord, includeOperation = false): string {\n\tconst guidance = failureGuidance(record);\n\treturn JSON.stringify({\n\t\t...mandatoryToolFailureRecoveryMetadata(),\n\t\tfailure_key: record.failureKey,\n\t\tocc: record.occurrence,\n\t\tkind_mistakes: record.kindMistakes ?? record.occurrence,\n\t\tmistake_kind: record.mistakeKind ?? record.tool,\n\t\tstate: record.state,\n\t\tphase: record.phase,\n\t\ttool: record.tool,\n\t\t...(includeOperation ? { operation: record.operation } : {}),\n\t\tfailure_code: record.failureCode,\n\t\t...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),\n\t\t...guidance,\n\t\t...(record.attemptMemory === \"discard\" ? { attempt_memory: \"discarded\" } : {}),\n\t});\n}\n\nexport function createToolFailureResult(\n\trecord: ToolFailureMemoryRecord,\n\tterminate?: boolean,\n): AgentToolResult<ToolFailureResultDetails> {\n\tconst discardAttempt = record.attemptMemory === \"discard\";\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[harness] ${formatRecordJson(record, false)}`,\n\t\t\t},\n\t\t],\n\t\tdetails: discardAttempt\n\t\t\t? {\n\t\t\t\t\tpiToolFailureDirective: {\n\t\t\t\t\t\tversion: TOOL_FAILURE_DIRECTIVE_VERSION,\n\t\t\t\t\t\tstate: record.state,\n\t\t\t\t\t\tphase: record.phase,\n\t\t\t\t\t\tfailureCode: record.failureCode,\n\t\t\t\t\t\t...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),\n\t\t\t\t\t\tnextAction: record.correction,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: { piToolFailureMemory: record },\n\t\t...(terminate === undefined ? {} : { terminate }),\n\t};\n}\n\nexport function createRepeatedToolFailureResult(\n\trecord: ToolFailureMemoryRecord,\n): AgentToolResult<ToolFailureMemoryDetails> {\n\tconst retainedRecord = {\n\t\t...retainBlockedToolFailure(record),\n\t\tcorrection: BLOCKED_REPLAY_CAVEMAN_CORRECTION,\n\t};\n\tconst diagnostic = truncateMiddle(\n\t\t`The unchanged operation was not executed. Unchanged replay blocked after ${record.failureCode}`,\n\t\tMAX_DIAGNOSTIC_CHARS,\n\t);\n\tconst blockedResult = createToolFailureResult({\n\t\t...retainedRecord,\n\t\tstate: \"rejected\",\n\t\tfailureCode: \"repeated_failed_operation\",\n\t\tdiagnostic,\n\t\tcorrection: retainedRecord.correction,\n\t});\n\treturn {\n\t\t...blockedResult,\n\t\t// The visible result describes this rejected replay, while retained memory keeps the\n\t\t// authoritative cause so later blocks do not recursively wrap synthetic failures.\n\t\tdetails: { piToolFailureMemory: retainedRecord },\n\t};\n}\n\nexport function createToolFailureRecoveryExhaustedResult(\n\trecord: ToolFailureMemoryRecord,\n\tdiagnostic: string,\n): AgentToolResult<ToolFailureMemoryDetails> {\n\tconst retainedRecord = retainBlockedToolFailure(record);\n\tconst exhaustedResult = createToolFailureResult(\n\t\t{\n\t\t\t...retainedRecord,\n\t\t\tstate: \"rejected\",\n\t\t\tfailureCode: \"recovery_exhausted\",\n\t\t\tdiagnostic: truncateMiddle(diagnostic, MAX_DIAGNOSTIC_CHARS),\n\t\t\tcorrection:\n\t\t\t\t\"Stop retrying tools in this run. Report the unresolved failure and the user or environment action required to continue.\",\n\t\t},\n\t\ttrue,\n\t);\n\treturn {\n\t\t...exhaustedResult,\n\t\tdetails: { piToolFailureMemory: retainedRecord },\n\t};\n}\n\nexport function createToolFailureOperationExhaustedResult(\n\trecord: ToolFailureMemoryRecord,\n\tdiagnostic: string,\n): AgentToolResult<ToolFailureMemoryDetails> {\n\tconst retainedRecord = {\n\t\t...retainBlockedToolFailure(record),\n\t\tcorrection: CLOSED_OPERATION_CAVEMAN_CORRECTION,\n\t};\n\tconst exhaustedResult = createToolFailureResult(\n\t\t{\n\t\t\t...retainedRecord,\n\t\t\tstate: \"rejected\",\n\t\t\tfailureCode: \"operation_recovery_exhausted\",\n\t\t\tdiagnostic: truncateMiddle(diagnostic, MAX_DIAGNOSTIC_CHARS),\n\t\t},\n\t\tfalse,\n\t);\n\treturn {\n\t\t...exhaustedResult,\n\t\tdetails: { piToolFailureMemory: retainedRecord },\n\t};\n}\n\nfunction retainBlockedToolFailure(record: ToolFailureMemoryRecord): ToolFailureMemoryRecord {\n\treturn {\n\t\t...record,\n\t\toccurrence: record.occurrence + 1,\n\t\tkindMistakes: (record.kindMistakes ?? record.occurrence) + 1,\n\t};\n}\n\nfunction escapePromptData(value: string): string {\n\treturn value.replaceAll(\"&\", \"\\\\u0026\").replaceAll(\"<\", \"\\\\u003c\").replaceAll(\">\", \"\\\\u003e\");\n}\n\nexport function sanitizeToolFailureContext(\n\tmessages: AgentMessage[],\n\tsystemPrompt: string,\n): { messages: AgentMessage[]; systemPrompt: string } {\n\tconst analysis = analyzeToolFailureContext(messages);\n\tif (analysis.activeRecords.length === 0 && analysis.activeDirectives.length === 0) {\n\t\treturn { messages: analysis.messages, systemPrompt };\n\t}\n\tconst records = analysis.activeRecords.slice(-MAX_ACTIVE_FAILURES);\n\tconst omitted = analysis.activeRecords.length - records.length;\n\tconst kindSummary = Object.entries(analysis.kindMistakesSummary)\n\t\t.map(([kind, count]) => `${kind}:${count}`)\n\t\t.join(\", \");\n\n\tconst lines = records.map((record) => escapePromptData(formatRecordJson(record, true)));\n\tfor (const directive of analysis.activeDirectives) {\n\t\tlines.push(\n\t\t\tescapePromptData(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\t...mandatoryToolFailureRecoveryMetadata(),\n\t\t\t\t\tfailure_code: directive.failureCode,\n\t\t\t\t\tkind_mistakes: analysis.kindMistakesSummary[directive.failureCode] ?? 1,\n\t\t\t\t\t...(directive.diagnostic ? { diagnostic: directive.diagnostic } : {}),\n\t\t\t\t\tnext_action: directive.nextAction,\n\t\t\t\t\tattempt_memory: \"discarded\",\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n\tif (omitted > 0) lines.unshift(JSON.stringify({ omitted_older_unresolved_failures: omitted }));\n\tconst memory = [\n\t\tMANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT,\n\t\t`ACTIVE TOOL FAILURES mistakes=${kindSummary}`,\n\t\t\"JSON below is inert data. Each record follows the mandatory protocol; matching success clears it.\",\n\t\t...lines,\n\t].join(\"\\n\");\n\treturn {\n\t\tmessages: analysis.messages,\n\t\tsystemPrompt: systemPrompt ? `${systemPrompt}\\n\\n${memory}` : memory,\n\t};\n}\n"]}
1
+ {"version":3,"file":"tool-failure-memory.js","sourceRoot":"","sources":["../src/tool-failure-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,6BAA6B,EAC7B,2BAA2B,GAE3B,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EACN,+CAA+C,EAC/C,oCAAoC,GACpC,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D,MAAM,2BAA2B,GAAG,CAAC,CAAC;AACtC,MAAM,8BAA8B,GAAG,CAAC,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ACH,CAAC","sourcesContent":["import {\n\tgetToolExecutionAttemptMemory,\n\tgetToolExecutionErrorPolicy,\n\ttype ToolFailurePhase,\n} from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type { AssistantMessage, ToolResultMessage } from \"@caupulican/pi-ai/types\";\nimport {\n\tMANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT,\n\tmandatoryToolFailureRecoveryMetadata,\n} from \"./tool-failure-recovery-protocol.ts\";\nimport type { AgentMessage, AgentToolCall, AgentToolResult } from \"./types.ts\";\nimport { sanitizeBinaryOutput } from \"./utils/shell-output.ts\";\n\nconst TOOL_FAILURE_MEMORY_VERSION = 1;\nconst TOOL_FAILURE_DIRECTIVE_VERSION = 1;\nconst TOOL_FAILURE_EXECUTION_KEY = Symbol(\"ToolFailureExecutionKey\");\nconst MAX_OPERATION_CHARS = 240;\nconst MAX_FAILURE_CODE_CHARS = 48;\nconst MAX_DIAGNOSTIC_CHARS = 240;\nconst MAX_CORRECTION_CHARS = 320;\nconst MAX_TOOL_NAME_CHARS = 64;\nconst TOOL_SIGNATURE_HEX_CHARS = 32;\nconst MAX_ACTIVE_FAILURES = 8;\nconst MAX_TRACKED_FAILURES = 64;\nconst REPAIRABLE_REJECTION_CODES = new Set([\"invalid_arguments\", \"malformed_call\", \"unknown_tool\"]);\nconst LEGACY_GENERIC_EXECUTION_CORRECTION =\n\t\"Change the arguments or approach before retrying; do not resend the unchanged operation.\";\nconst BLOCKED_REPLAY_CAVEMAN_CORRECTION =\n\t\"CAVEMAN MODE - MANDATORY. SAME OPERATION BLOCKED. Do not repeat an unchanged operation. NEVER call it again with the same arguments in this run. This is not a harness loop or failure.\";\nconst CLOSED_OPERATION_CAVEMAN_CORRECTION =\n\t\"CAVEMAN MODE - MANDATORY: OPERATION CLOSED; not executed. Do not repeat an unchanged operation. NEVER call it again with the same arguments in this run. Use a different operation/tool or continue independent work. The recovery guard prevented a loop; this is not harness failure.\";\n\nexport type ToolFailureState = \"failed\" | \"rejected\";\n\nexport interface ToolFailureMemoryRecord {\n\tversion: typeof TOOL_FAILURE_MEMORY_VERSION;\n\tfailureKey: string;\n\t/** Exact identity is process-internal and omitted from serialized failure memory. */\n\treadonly [TOOL_FAILURE_EXECUTION_KEY]?: string;\n\ttool: string;\n\toperation: string;\n\toccurrence: number;\n\tkindMistakes?: number;\n\tmistakeKind?: string;\n\tstate: ToolFailureState;\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tdiagnostic?: string;\n\tcorrection: string;\n\tattemptMemory?: \"discard\";\n}\n\nexport interface ToolFailureMemoryDetails {\n\tpiToolFailureMemory: ToolFailureMemoryRecord;\n}\n\nexport interface ToolFailureDirectiveDetails {\n\tpiToolFailureDirective: {\n\t\tversion: typeof TOOL_FAILURE_DIRECTIVE_VERSION;\n\t\tstate: ToolFailureState;\n\t\tphase: ToolFailurePhase;\n\t\tfailureCode: string;\n\t\tdiagnostic?: string;\n\t\tnextAction: string;\n\t};\n}\n\nexport type ToolFailureResultDetails = ToolFailureMemoryDetails | ToolFailureDirectiveDetails;\n\nexport type ToolFailureMemoryTracker = Map<string, ToolFailureMemoryRecord>;\n\ninterface ToolOperationIdentity {\n\tfailureKey: string;\n\texecutionKey: string;\n\ttool: string;\n\toperation: string;\n}\n\ninterface ActiveFailure {\n\trecord: ToolFailureMemoryRecord;\n\tsequence: number;\n}\n\ninterface FailureContextAnalysis {\n\tmessages: AgentMessage[];\n\tactiveRecords: ToolFailureMemoryRecord[];\n\tactiveDirectives: ToolFailureDirectiveDetails[\"piToolFailureDirective\"][];\n\tkindMistakesSummary: Record<string, number>;\n}\n\nfunction truncate(value: string, maxChars: number): string {\n\tif (value.length <= maxChars) return value;\n\tlet end = maxChars - 1;\n\tconst code = value.charCodeAt(end - 1);\n\tif (code >= 0xd800 && code <= 0xdbff) end--;\n\treturn `${value.slice(0, end)}…`;\n}\n\nfunction truncateMiddle(value: string, maxChars: number): string {\n\tif (value.length <= maxChars) return value;\n\tconst available = maxChars - 1;\n\tlet headEnd = Math.ceil(available / 2);\n\tlet tailStart = value.length - Math.floor(available / 2);\n\tconst headCode = value.charCodeAt(headEnd - 1);\n\tif (headCode >= 0xd800 && headCode <= 0xdbff) headEnd--;\n\tconst tailCode = value.charCodeAt(tailStart);\n\tif (tailCode >= 0xdc00 && tailCode <= 0xdfff) tailStart++;\n\treturn `${value.slice(0, headEnd)}…${value.slice(tailStart)}`;\n}\n\nfunction safeJson(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"null\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\ninterface SignatureHash {\n\tfirst: number;\n\tsecond: number;\n\tthird: number;\n\tfourth: number;\n}\n\nconst VOLATILE_SIGNATURE_PATTERN =\n\t/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})|(\\d{4}-\\d{2}-\\d{2}[tT][0-9:.]+(?:z|[+-]\\d{2}:?\\d{2})?)|(\\b[0-9a-f]{16,}\\b)|(\\d{10,})/gi;\nconst MAX_SIGNATURE_DEPTH = 128;\nconst MAX_PREVIEW_DEPTH = 6;\nconst MAX_PREVIEW_ITEMS = 8;\nconst MAX_PREVIEW_STRING_CHARS = 96;\n\nfunction updateHashCode(hash: SignatureHash, code: number): void {\n\thash.first = Math.imul(hash.first ^ code, 0x01000193);\n\thash.second = Math.imul(hash.second ^ code, 0x85ebca6b);\n\thash.third = Math.imul(hash.third ^ code, 0x27d4eb2d);\n\thash.fourth = Math.imul(hash.fourth ^ code, 0x165667b1);\n}\n\nfunction updateHashRange(hash: SignatureHash, value: string, start = 0, end = value.length): void {\n\tfor (let index = start; index < end; index++) updateHashCode(hash, value.charCodeAt(index));\n}\n\nfunction updateNormalizedHashString(hash: SignatureHash, value: string): void {\n\tif (value.length < 10) {\n\t\tupdateExactHashString(hash, value);\n\t\treturn;\n\t}\n\tVOLATILE_SIGNATURE_PATTERN.lastIndex = 0;\n\tlet offset = 0;\n\tlet normalizedLength = value.length;\n\tfor (const match of value.matchAll(VOLATILE_SIGNATURE_PATTERN)) {\n\t\tconst index = match.index;\n\t\tupdateHashRange(hash, value, offset, index);\n\t\tconst replacement = match[1] ? \"<uuid>\" : match[2] ? \"<ts>\" : match[3] ? \"<hex>\" : \"<num>\";\n\t\tupdateHashRange(hash, replacement);\n\t\tnormalizedLength += replacement.length - match[0].length;\n\t\toffset = index + match[0].length;\n\t}\n\tupdateHashRange(hash, value, offset);\n\tupdateHashRange(hash, `:${normalizedLength};`);\n}\n\nfunction updateExactHashString(hash: SignatureHash, value: string): void {\n\tupdateHashRange(hash, value);\n\tupdateHashRange(hash, `:${value.length};`);\n}\n\nfunction updateStructuredHash(\n\thash: SignatureHash,\n\tvalue: unknown,\n\tactive: Set<object>,\n\tdepth: number,\n\tupdateHashString: (hash: SignatureHash, value: string) => void,\n): void {\n\tif (depth > MAX_SIGNATURE_DEPTH) {\n\t\tupdateHashRange(hash, \"depth;\");\n\t\treturn;\n\t}\n\tif (value === null) {\n\t\tupdateHashRange(hash, \"null;\");\n\t\treturn;\n\t}\n\tswitch (typeof value) {\n\t\tcase \"string\":\n\t\t\tupdateHashRange(hash, \"string:\");\n\t\t\tupdateHashString(hash, value);\n\t\t\treturn;\n\t\tcase \"number\":\n\t\t\tupdateHashRange(hash, \"number:\");\n\t\t\tupdateHashString(hash, Object.is(value, -0) ? \"-0\" : String(value));\n\t\t\treturn;\n\t\tcase \"boolean\":\n\t\t\tupdateHashRange(hash, value ? \"true;\" : \"false;\");\n\t\t\treturn;\n\t\tcase \"undefined\":\n\t\t\tupdateHashRange(hash, \"undefined;\");\n\t\t\treturn;\n\t\tcase \"bigint\":\n\t\t\tupdateHashRange(hash, `bigint:${value.toString()};`);\n\t\t\treturn;\n\t\tcase \"symbol\":\n\t\t\tupdateHashRange(hash, `symbol:${String(value.description ?? \"\")};`);\n\t\t\treturn;\n\t\tcase \"function\":\n\t\t\tupdateHashRange(hash, `function:${value.name};`);\n\t\t\treturn;\n\t\tcase \"object\":\n\t\t\tbreak;\n\t}\n\n\tif (active.has(value)) {\n\t\tupdateHashRange(hash, \"circular;\");\n\t\treturn;\n\t}\n\tactive.add(value);\n\tif (Array.isArray(value)) {\n\t\tupdateHashRange(hash, `array:${value.length}[`);\n\t\tfor (const item of value) updateStructuredHash(hash, item, active, depth + 1, updateHashString);\n\t\tupdateHashRange(hash, \"];\");\n\t} else {\n\t\tconst keys = Object.keys(value).sort();\n\t\tupdateHashRange(hash, `object:${keys.length}{`);\n\t\tfor (const key of keys) {\n\t\t\tupdateHashString(hash, key);\n\t\t\tupdateStructuredHash(hash, (value as Record<string, unknown>)[key], active, depth + 1, updateHashString);\n\t\t}\n\t\tupdateHashRange(hash, \"};\");\n\t}\n\tactive.delete(value);\n}\n\nfunction createSignatureHash(): SignatureHash {\n\treturn {\n\t\tfirst: 0x811c9dc5,\n\t\tsecond: 0x9e3779b9,\n\t\tthird: 0x85ebca6b,\n\t\tfourth: 0xc2b2ae35,\n\t};\n}\n\nfunction renderSignatureHash(hash: SignatureHash): string {\n\treturn [hash.first, hash.second, hash.third, hash.fourth]\n\t\t.map((part) => (part >>> 0).toString(16).padStart(8, \"0\"))\n\t\t.join(\"\");\n}\n\nfunction structuredHash(value: unknown, normalizeVolatile: boolean): string {\n\tconst hash = createSignatureHash();\n\tupdateStructuredHash(\n\t\thash,\n\t\tvalue,\n\t\tnew Set(),\n\t\t0,\n\t\tnormalizeVolatile ? updateNormalizedHashString : updateExactHashString,\n\t);\n\treturn renderSignatureHash(hash);\n}\n\nfunction boundedJsonPreview(value: unknown, maxChars: number): string {\n\tlet output = \"\";\n\tlet exhausted = false;\n\tconst active = new Set<object>();\n\tconst append = (text: string): void => {\n\t\tif (exhausted) return;\n\t\tconst available = maxChars - output.length;\n\t\tif (text.length <= available) {\n\t\t\toutput += text;\n\t\t\treturn;\n\t\t}\n\t\tif (available > 1) output += `${text.slice(0, available - 1)}…`;\n\t\texhausted = true;\n\t};\n\tconst visit = (item: unknown, depth: number): void => {\n\t\tif (exhausted) return;\n\t\tif (depth > MAX_PREVIEW_DEPTH) {\n\t\t\tappend('\"[depth]\"');\n\t\t\treturn;\n\t\t}\n\t\tif (typeof item === \"string\") {\n\t\t\tappend(safeJson(truncateMiddle(item, MAX_PREVIEW_STRING_CHARS)));\n\t\t\treturn;\n\t\t}\n\t\tif (item === null || typeof item === \"number\" || typeof item === \"boolean\") {\n\t\t\tappend(String(item));\n\t\t\treturn;\n\t\t}\n\t\tif (typeof item !== \"object\") {\n\t\t\tappend(safeJson(`[${typeof item}]`));\n\t\t\treturn;\n\t\t}\n\t\tif (active.has(item)) {\n\t\t\tappend('\"[circular]\"');\n\t\t\treturn;\n\t\t}\n\t\tactive.add(item);\n\t\tif (Array.isArray(item)) {\n\t\t\tappend(\"[\");\n\t\t\tconst count = Math.min(item.length, MAX_PREVIEW_ITEMS);\n\t\t\tfor (let index = 0; index < count && !exhausted; index++) {\n\t\t\t\tif (index > 0) append(\",\");\n\t\t\t\tvisit(item[index], depth + 1);\n\t\t\t}\n\t\t\tif (item.length > count) append(`${count > 0 ? \",\" : \"\"}\"[+${item.length - count} items]\"`);\n\t\t\tappend(\"]\");\n\t\t} else {\n\t\t\tappend(\"{\");\n\t\t\tlet count = 0;\n\t\t\tlet omitted = 0;\n\t\t\tconst keys = Object.keys(item).sort();\n\t\t\tfor (const key of keys) {\n\t\t\t\tif (count >= MAX_PREVIEW_ITEMS) {\n\t\t\t\t\tomitted++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (count > 0) append(\",\");\n\t\t\t\tappend(safeJson(truncateMiddle(key, MAX_PREVIEW_STRING_CHARS)));\n\t\t\t\tappend(\":\");\n\t\t\t\tvisit((item as Record<string, unknown>)[key], depth + 1);\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tif (omitted > 0) append(`${count > 0 ? \",\" : \"\"}\"[omitted]\":${omitted}`);\n\t\t\tappend(\"}\");\n\t\t}\n\t\tactive.delete(item);\n\t};\n\tvisit(value, 0);\n\treturn truncateMiddle(output || \"null\", maxChars);\n}\n\n/**\n * Fingerprint a tool operation without materializing or retaining its serialized payload.\n * Volatile identifiers normalize before hashing; short numbers and ordinary paths remain significant.\n */\nexport function normalizeToolSignature(pairs: Array<[string, unknown]>): string {\n\treturn structuredHash(pairs, true);\n}\n\nfunction toolOperationKey(tool: string, args: unknown, normalizeVolatile: boolean): string {\n\tconst boundedTool = truncate(tool, MAX_TOOL_NAME_CHARS);\n\tconst hash = createSignatureHash();\n\tconst updateHashString = normalizeVolatile ? updateNormalizedHashString : updateExactHashString;\n\tconst active = new Set<object>();\n\t// Preserve the stable structured-hash wire identity without allocating the two synthetic arrays.\n\tupdateHashRange(hash, \"array:1[array:2[\");\n\tupdateStructuredHash(hash, tool, active, 2, updateHashString);\n\tupdateStructuredHash(hash, args, active, 2, updateHashString);\n\tupdateHashRange(hash, \"];];\");\n\tconst signature = renderSignatureHash(hash);\n\treturn `${boundedTool}:${signature}`;\n}\n\nfunction operationIdentity(tool: string, args: unknown): ToolOperationIdentity {\n\treturn {\n\t\tfailureKey: toolOperationKey(tool, args, true),\n\t\texecutionKey: toolOperationKey(tool, args, false),\n\t\ttool: truncate(tool, MAX_TOOL_NAME_CHARS),\n\t\toperation: boundedJsonPreview(args, MAX_OPERATION_CHARS),\n\t};\n}\n\nfunction getToolFailureKey(tool: string, args: unknown): string {\n\treturn toolOperationKey(tool, args, true);\n}\n\nexport function getToolExecutionKey(tool: string, args: unknown): string {\n\treturn toolOperationKey(tool, args, false);\n}\n\nexport function getToolFailureRecordExecutionKey(record: ToolFailureMemoryRecord): string | undefined {\n\treturn record[TOOL_FAILURE_EXECUTION_KEY];\n}\n\nexport function getUnresolvedToolFailure(\n\ttracker: ToolFailureMemoryTracker,\n\ttool: string,\n\targs: unknown,\n): ToolFailureMemoryRecord | undefined {\n\treturn tracker.get(getToolFailureKey(tool, args));\n}\n\nfunction boundedFailureCode(value: string): string {\n\tconst normalized = value\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_.:-]+/g, \"_\")\n\t\t.replace(/^_+|_+$/g, \"\");\n\treturn truncate(normalized || \"tool_error\", MAX_FAILURE_CODE_CHARS);\n}\n\n/**\n * bash.ts's own trailer (`appendStatus`) always ends the message with a line like \"Command\n * exited with code 1\"; a structured result (e.g. run_process) instead puts \"exitCode: 1\" on its\n * own line near the top. Both are anchored to the START of their own line, with at most one\n * leading tool-name token (\"Command\"/\"Python\"/...) — ordinary stdout/stderr prose is never\n * anchored that way, so a captured line like \"container will exit 0 on SIGTERM\" can never be\n * read as the process exit status. Scan from the end of the message so the tool's own trailer —\n * always the last line it appends — outranks any earlier, non-authoritative line that matches.\n */\nconst EXIT_STATUS_LINE_PATTERN = /^(?:\\S+\\s+)?(?:exit(?:ed)?(?:\\s+with)?(?:\\s+code)?|exitcode)\\s*[:=]?\\s*(-?\\d+)\\b/i;\n\nfunction processExitFailureCode(message: string): string | undefined {\n\tconst lines = message.split(/\\r\\n|\\n/);\n\tfor (let index = lines.length - 1; index >= 0; index--) {\n\t\tconst match = EXIT_STATUS_LINE_PATTERN.exec(lines[index].trim());\n\t\tif (match) return boundedFailureCode(`exit_${match[1]}`);\n\t}\n\treturn undefined;\n}\n\nexport function classifyToolFailure(message: string, errorClass?: string): string {\n\t// A tool-owned terminal status is authoritative; stdout may contain arbitrary all-caps identifiers.\n\tconst exitFailureCode = processExitFailureCode(message);\n\tif (exitFailureCode) return exitFailureCode;\n\tconst errno = /\\b(E[A-Z][A-Z0-9_]{2,})\\b/.exec(message)?.[1];\n\tif (errno) return boundedFailureCode(errno);\n\treturn boundedFailureCode(errorClass ?? \"tool_error\");\n}\n\nfunction isToolFailurePhase(value: unknown): value is ToolFailurePhase {\n\treturn (\n\t\tvalue === \"validation\" ||\n\t\tvalue === \"policy\" ||\n\t\tvalue === \"preflight\" ||\n\t\tvalue === \"execution\" ||\n\t\tvalue === \"timeout\" ||\n\t\tvalue === \"cancelled\" ||\n\t\tvalue === \"provisioning\"\n\t);\n}\n\nfunction inferToolFailurePhase(state: ToolFailureState, failureCode: string): ToolFailurePhase {\n\tif (failureCode === \"malformed_call\" || failureCode === \"unknown_tool\" || failureCode === \"invalid_arguments\") {\n\t\treturn \"validation\";\n\t}\n\tif (failureCode === \"blocked\" || failureCode === \"permission_denied\") return \"policy\";\n\tif (failureCode === \"preflight_error\") return \"preflight\";\n\tif (failureCode === \"aborted\" || failureCode === \"cancelled\") return \"cancelled\";\n\tif (failureCode === \"timeout\" || failureCode === \"etimedout\") return \"timeout\";\n\tif (failureCode === \"provisioning_failed\" || failureCode === \"command_not_found\") return \"provisioning\";\n\treturn state === \"rejected\" ? \"validation\" : \"execution\";\n}\n\nfunction fallbackFailureGuidance(state: ToolFailureState, hasDiagnostic: boolean, phase: ToolFailurePhase): string {\n\tif (phase === \"preflight\") {\n\t\treturn hasDiagnostic\n\t\t\t? \"Arguments valid; preflight failed before execution. Resolve diagnostic/host condition before retry.\"\n\t\t\t: \"Arguments valid; preflight failed before execution. Inspect host policy/capability before retry.\";\n\t}\n\tif (phase === \"policy\") return \"Resolve authority/policy restriction or choose allowed approach before retry.\";\n\tif (phase === \"cancelled\") return \"Retry only when operation remains required, cancellation condition cleared.\";\n\tif (phase === \"timeout\") return \"Narrow/split work; retry once only when safe.\";\n\tif (phase === \"provisioning\") {\n\t\treturn hasDiagnostic\n\t\t\t? \"Fix provisioning diagnostic; retry only after environment changes.\"\n\t\t\t: \"Inspect tool availability; request bounded provisioning diagnostic before retry.\";\n\t}\n\treturn state === \"rejected\"\n\t\t? \"Re-read current tool schema; change invalid operation before retry.\"\n\t\t: hasDiagnostic\n\t\t\t? \"Read diagnostic; identify cause; repair parameters or corrective state before retry.\"\n\t\t\t: \"No diagnostic output. Inspect tool contract or request bounded diagnostic before retry.\";\n}\n\nexport function toolFailureCorrection(\n\tmessage: string,\n\tstate: ToolFailureState,\n\tphase: ToolFailurePhase = state === \"rejected\" ? \"validation\" : \"execution\",\n): string {\n\tconst policy = getToolExecutionErrorPolicy(message);\n\treturn policy\n\t\t? truncate(policy.guidance, MAX_CORRECTION_CHARS)\n\t\t: fallbackFailureGuidance(state, message.trim().length > 0, phase);\n}\n\nfunction extractFailureDiagnostic(\n\tmessage: string,\n\tallowUnclassifiedFallback: boolean,\n\trequireStrongSignal = false,\n): string | undefined {\n\tconst rawLines = sanitizeBinaryOutput(message).replaceAll(\"\\r\\n\", \"\\n\").split(\"\\n\");\n\tconst strongDiagnosticPattern =\n\t\t/^(?:(?:error(?:\\[[^\\]]+\\])?|fatal(?: error)?|panic|fail(?:ed|ure)?|invalid|unknown|unsupported|not found|no such|cannot|can't|missing|denied|refused|usage)(?:\\b|:)|[a-z][a-z0-9_.]*error(?::|$)|thread .+ panicked at\\b|--- fail:|\\[fail(?:ed)?\\]|not ok\\b|[×✗]\\s|.{1,160}:\\s+(?:error(?:\\[[^\\]]+\\])?|fatal(?: error)?)(?:\\b|:))/i;\n\tconst stderrMarkerIndex = rawLines.findLastIndex((line) => /^stderr:\\s*$/i.test(line.trim()));\n\tif (stderrMarkerIndex >= 0) {\n\t\tconst stderrLines = rawLines\n\t\t\t.slice(stderrMarkerIndex + 1)\n\t\t\t.map((line) => line.trim())\n\t\t\t.filter(\n\t\t\t\t(line) =>\n\t\t\t\t\tline.length > 0 && !/^command (?:exited with code|timed out after|aborted|killed after)\\b/i.test(line),\n\t\t\t);\n\t\tif (stderrLines.length > 0) {\n\t\t\tconst classified = stderrLines.find((line) => strongDiagnosticPattern.test(line));\n\t\t\tif (classified) return truncateMiddle(classified, MAX_DIAGNOSTIC_CHARS);\n\t\t\t// No stderr line carries a strong signal. Under requireStrongSignal, the caller has\n\t\t\t// already decided uncatalogued output must never be fabricated into a diagnostic (see\n\t\t\t// assessToolFailure) — falling back to the last raw stderr lines here would defeat that\n\t\t\t// guarantee for the common bash case, so fall through to the same allowUnclassifiedFallback\n\t\t\t// gate the no-stderr path below applies.\n\t\t\tif (!requireStrongSignal) {\n\t\t\t\treturn truncateMiddle(stderrLines.slice(-4).join(\" | \"), MAX_DIAGNOSTIC_CHARS);\n\t\t\t}\n\t\t}\n\t}\n\tconst lines = rawLines\n\t\t.map((line) => line.trim())\n\t\t.filter(\n\t\t\t(line) =>\n\t\t\t\tline.length > 0 &&\n\t\t\t\t!/^command (?:exited with code|timed out after|aborted|killed after)\\b/i.test(line) &&\n\t\t\t\t!/^outcome:\\s*(?:failed|aborted|timeout|output_limit)\\b/i.test(line) &&\n\t\t\t\t!/^exitcode:\\s*-?\\d+\\b/i.test(line) &&\n\t\t\t\t!/^(?:stdout|stderr):(?:\\s*\\(empty\\))?$/i.test(line),\n\t\t);\n\tif (lines.length === 0) return undefined;\n\tconst diagnosticPattern = requireStrongSignal\n\t\t? strongDiagnosticPattern\n\t\t: /(?:^|\\b)(?:error|fatal|fail(?:ed|ure)?|invalid|unknown|unsupported|not found|no such|cannot|can't|missing|denied|refused|usage)(?:\\b|:)/i;\n\tconst classified = requireStrongSignal\n\t\t? lines.find((line) => diagnosticPattern.test(line))\n\t\t: [...lines].reverse().find((line) => diagnosticPattern.test(line));\n\tconst diagnostic = classified ?? (allowUnclassifiedFallback ? lines.at(-1) : undefined);\n\treturn diagnostic ? truncateMiddle(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined;\n}\n\nexport interface ToolFailureAssessment {\n\tfailureCode: string;\n\tphase: ToolFailurePhase;\n\tdiagnostic?: string;\n\tguidance: string;\n\tattemptMemory?: \"discard\";\n}\n\nexport function assessToolFailure(\n\tmessage: string,\n\tstate: ToolFailureState,\n\terrorClass?: string,\n): ToolFailureAssessment {\n\tconst policy = getToolExecutionErrorPolicy(message);\n\tconst exitFailureCode = processExitFailureCode(message);\n\tconst retainPolicyDiagnostic = policy?.retainDiagnostic === true;\n\tconst diagnostic =\n\t\tstate === \"failed\" && (!policy || policy.retainDiagnostic)\n\t\t\t? extractFailureDiagnostic(\n\t\t\t\t\tmessage,\n\t\t\t\t\texitFailureCode === undefined && (errorClass !== undefined || retainPolicyDiagnostic),\n\t\t\t\t\texitFailureCode !== undefined && !retainPolicyDiagnostic,\n\t\t\t\t)\n\t\t\t: undefined;\n\tconst failureCode = policy?.failureCode ?? classifyToolFailure(message, errorClass);\n\treturn {\n\t\tfailureCode,\n\t\tphase: policy?.phase ?? inferToolFailurePhase(state, failureCode),\n\t\t...(diagnostic ? { diagnostic } : {}),\n\t\tguidance: policy\n\t\t\t? truncate(policy.guidance, MAX_CORRECTION_CHARS)\n\t\t\t: fallbackFailureGuidance(state, diagnostic !== undefined, inferToolFailurePhase(state, failureCode)),\n\t\t...(policy?.attemptMemory === \"discard\" ? { attemptMemory: \"discard\" as const } : {}),\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readFailureRecord(details: unknown): ToolFailureMemoryRecord | undefined {\n\tif (!isRecord(details) || !isRecord(details.piToolFailureMemory)) return undefined;\n\tconst candidate = details.piToolFailureMemory;\n\tif (\n\t\tcandidate.version !== TOOL_FAILURE_MEMORY_VERSION ||\n\t\ttypeof candidate.failureKey !== \"string\" ||\n\t\ttypeof candidate.tool !== \"string\" ||\n\t\ttypeof candidate.operation !== \"string\" ||\n\t\ttypeof candidate.occurrence !== \"number\" ||\n\t\t!Number.isSafeInteger(candidate.occurrence) ||\n\t\tcandidate.occurrence < 1 ||\n\t\t(candidate.state !== \"failed\" && candidate.state !== \"rejected\") ||\n\t\ttypeof candidate.failureCode !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\tconst diagnostic =\n\t\ttypeof candidate.diagnostic === \"string\" ? truncate(candidate.diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined;\n\tconst retainedCorrection =\n\t\ttypeof candidate.correction === \"string\" ? truncate(candidate.correction, MAX_CORRECTION_CHARS) : undefined;\n\tconst correction =\n\t\tcandidate.state === \"failed\" && retainedCorrection === LEGACY_GENERIC_EXECUTION_CORRECTION\n\t\t\t? fallbackFailureGuidance(\"failed\", diagnostic !== undefined, \"execution\")\n\t\t\t: (retainedCorrection ?? toolFailureCorrection(\"\", candidate.state));\n\tconst phase = isToolFailurePhase(candidate.phase)\n\t\t? candidate.phase\n\t\t: inferToolFailurePhase(candidate.state, candidate.failureCode);\n\tconst candidateExecutionKey: unknown = Reflect.get(candidate, TOOL_FAILURE_EXECUTION_KEY);\n\treturn {\n\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\tfailureKey: truncate(candidate.failureKey, MAX_TOOL_NAME_CHARS + 1 + TOOL_SIGNATURE_HEX_CHARS),\n\t\t...(typeof candidateExecutionKey === \"string\"\n\t\t\t? {\n\t\t\t\t\t[TOOL_FAILURE_EXECUTION_KEY]: truncate(\n\t\t\t\t\t\tcandidateExecutionKey,\n\t\t\t\t\t\tMAX_TOOL_NAME_CHARS + 1 + TOOL_SIGNATURE_HEX_CHARS,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\ttool: truncate(candidate.tool, MAX_TOOL_NAME_CHARS),\n\t\toperation: truncateMiddle(candidate.operation, MAX_OPERATION_CHARS),\n\t\toccurrence: candidate.occurrence,\n\t\tstate: candidate.state,\n\t\tphase,\n\t\tfailureCode: boundedFailureCode(candidate.failureCode),\n\t\tdiagnostic,\n\t\tcorrection,\n\t};\n}\n\nfunction readFailureDirective(details: unknown): ToolFailureDirectiveDetails[\"piToolFailureDirective\"] | undefined {\n\tif (!isRecord(details) || !isRecord(details.piToolFailureDirective)) return undefined;\n\tconst candidate = details.piToolFailureDirective;\n\tif (\n\t\tcandidate.version !== TOOL_FAILURE_DIRECTIVE_VERSION ||\n\t\ttypeof candidate.failureCode !== \"string\" ||\n\t\ttypeof candidate.nextAction !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tversion: TOOL_FAILURE_DIRECTIVE_VERSION,\n\t\tstate: candidate.state === \"rejected\" ? \"rejected\" : \"failed\",\n\t\tphase: isToolFailurePhase(candidate.phase)\n\t\t\t? candidate.phase\n\t\t\t: inferToolFailurePhase(\"failed\", candidate.failureCode),\n\t\tfailureCode: boundedFailureCode(candidate.failureCode),\n\t\tdiagnostic:\n\t\t\ttypeof candidate.diagnostic === \"string\" ? truncate(candidate.diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,\n\t\tnextAction: truncate(candidate.nextAction, MAX_CORRECTION_CHARS),\n\t};\n}\n\nexport interface ToolFailureTelemetry {\n\tstate: ToolFailureState;\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tdiagnostic?: string;\n\tnextAction: string;\n}\n\n/** Read only bounded failure identity and guidance; operation arguments never cross this telemetry boundary. */\nexport function readToolFailureTelemetry(details: unknown): ToolFailureTelemetry | undefined {\n\tconst record = readFailureRecord(details);\n\tif (record) {\n\t\treturn {\n\t\t\tstate: record.state,\n\t\t\tphase: record.phase,\n\t\t\tfailureCode: record.failureCode,\n\t\t\t...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),\n\t\t\tnextAction: record.correction,\n\t\t};\n\t}\n\tconst directive = readFailureDirective(details);\n\tif (!directive) return undefined;\n\treturn {\n\t\tstate: directive.state,\n\t\tphase: directive.phase,\n\t\tfailureCode: directive.failureCode,\n\t\t...(directive.diagnostic ? { diagnostic: directive.diagnostic } : {}),\n\t\tnextAction: directive.nextAction,\n\t};\n}\n\nfunction firstText(message: ToolResultMessage): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\tfor (let index = 0; index < content.length; index++) {\n\t\t\tconst block = content[index];\n\t\t\tif (block.type === \"text\") return block.text;\n\t\t}\n\t}\n\treturn \"\";\n}\n\nfunction fastTextSignature(text: string): string {\n\tif (text.length <= 128) return text;\n\treturn `${text.length}:${text.slice(0, 48)}:${text.slice(-48)}`;\n}\n\nfunction analyzeToolFailureContext(messages: AgentMessage[]): FailureContextAnalysis {\n\tconst callById = new Map<string, AgentToolCall>();\n\tconst omittedCallIds = new Set<string>();\n\tconst orphanFailedResults = new Set<ToolResultMessage>();\n\tconst active = new Map<string, ActiveFailure>();\n\tconst activeDirectives = new Map<string, ToolFailureDirectiveDetails[\"piToolFailureDirective\"]>();\n\tlet sequence = 0;\n\tconst kindMistakesMap = new Map<string, number>();\n\n\tconst latestSuccessfulByOpKey = new Map<string, string>();\n\tconst latestSuccessfulByPayloadKey = new Map<string, string>();\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (message.role === \"assistant\") {\n\t\t\tactiveDirectives.clear();\n\t\t\tconst content = message.content;\n\t\t\tfor (let blockIdx = 0; blockIdx < content.length; blockIdx++) {\n\t\t\t\tconst block = content[blockIdx];\n\t\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\t\tcallById.set(block.id, block);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"toolResult\") continue;\n\n\t\tconst call = callById.get(message.toolCallId);\n\t\tcallById.delete(message.toolCallId);\n\t\tconst textPayload = firstText(message);\n\t\tconst isFailure = message.isError === true || textPayload.startsWith(\"[harness] \");\n\t\tif (isFailure) {\n\t\t\tconst toolName = call?.name ?? message.toolName;\n\t\t\tconst kindCount = (kindMistakesMap.get(toolName) ?? 0) + 1;\n\t\t\tkindMistakesMap.set(toolName, kindCount);\n\n\t\t\tconst directive = readFailureDirective(message.details);\n\t\t\tif (directive) {\n\t\t\t\tactiveDirectives.delete(directive.failureCode);\n\t\t\t\tactiveDirectives.set(directive.failureCode, directive);\n\t\t\t\tif (call) omittedCallIds.add(call.id);\n\t\t\t\telse orphanFailedResults.add(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst retained = readFailureRecord(message.details);\n\t\t\tconst state = retained?.state ?? \"failed\";\n\t\t\tconst assessment = retained ? undefined : assessToolFailure(textPayload, state);\n\t\t\tlet failureKey: string;\n\t\t\tlet executionKey: string | undefined;\n\t\t\tlet tool: string;\n\t\t\tlet operation: string;\n\t\t\tif (retained) {\n\t\t\t\tfailureKey = retained.failureKey;\n\t\t\t\texecutionKey = call\n\t\t\t\t\t? getToolExecutionKey(call.name, call.arguments)\n\t\t\t\t\t: getToolFailureRecordExecutionKey(retained);\n\t\t\t\ttool = retained.tool;\n\t\t\t\toperation = retained.operation;\n\t\t\t} else {\n\t\t\t\tconst identity = operationIdentity(\n\t\t\t\t\tcall?.name ?? message.toolName,\n\t\t\t\t\tcall?.arguments ?? { toolCallId: message.toolCallId },\n\t\t\t\t);\n\t\t\t\tfailureKey = identity.failureKey;\n\t\t\t\texecutionKey = identity.executionKey;\n\t\t\t\ttool = identity.tool;\n\t\t\t\toperation = identity.operation;\n\t\t\t}\n\t\t\tconst previous = active.get(failureKey)?.record;\n\t\t\tconst occurrence = Math.max(retained?.occurrence ?? 0, (previous?.occurrence ?? 0) + 1);\n\t\t\tconst record: ToolFailureMemoryRecord = {\n\t\t\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\t\t\tfailureKey,\n\t\t\t\t...(executionKey ? { [TOOL_FAILURE_EXECUTION_KEY]: executionKey } : {}),\n\t\t\t\ttool,\n\t\t\t\toperation,\n\t\t\t\toccurrence,\n\t\t\t\tkindMistakes: kindCount,\n\t\t\t\tmistakeKind: toolName,\n\t\t\t\tstate,\n\t\t\t\tphase: retained?.phase ?? assessment?.phase ?? inferToolFailurePhase(state, \"tool_error\"),\n\t\t\t\tfailureCode: retained?.failureCode ?? assessment?.failureCode ?? \"tool_error\",\n\t\t\t\tdiagnostic: retained?.diagnostic ?? assessment?.diagnostic,\n\t\t\t\tcorrection:\n\t\t\t\t\tretained?.correction ??\n\t\t\t\t\tassessment?.guidance ??\n\t\t\t\t\tfallbackFailureGuidance(state, false, inferToolFailurePhase(state, \"tool_error\")),\n\t\t\t};\n\t\t\tactive.delete(failureKey);\n\t\t\tactive.set(failureKey, { record, sequence: sequence++ });\n\t\t\twhile (active.size > MAX_TRACKED_FAILURES) {\n\t\t\t\tconst oldest = active.keys().next().value;\n\t\t\t\tif (oldest === undefined) break;\n\t\t\t\tactive.delete(oldest);\n\t\t\t}\n\t\t\tif (call) omittedCallIds.add(call.id);\n\t\t\telse orphanFailedResults.add(message);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (call) {\n\t\t\tconst opKey = getToolFailureKey(call.name, call.arguments);\n\t\t\tactive.delete(opKey);\n\t\t\tconst previousOperationCallId = latestSuccessfulByOpKey.get(opKey);\n\t\t\tif (previousOperationCallId) omittedCallIds.add(previousOperationCallId);\n\t\t\tlatestSuccessfulByOpKey.set(opKey, call.id);\n\n\t\t\tconst textPayload = firstText(message);\n\t\t\tif (textPayload.length >= 64) {\n\t\t\t\tconst payloadKey = `payload:${fastTextSignature(textPayload)}`;\n\t\t\t\tconst previousPayloadCallId = latestSuccessfulByPayloadKey.get(payloadKey);\n\t\t\t\tif (previousPayloadCallId) omittedCallIds.add(previousPayloadCallId);\n\t\t\t\tlatestSuccessfulByPayloadKey.set(payloadKey, call.id);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst kindMistakesSummary = Object.fromEntries(kindMistakesMap);\n\n\tif (omittedCallIds.size === 0 && orphanFailedResults.size === 0) {\n\t\treturn { messages, activeRecords: [], activeDirectives: [], kindMistakesSummary };\n\t}\n\n\tconst filteredMessages: AgentMessage[] = [];\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (message.role === \"toolResult\") {\n\t\t\tif (omittedCallIds.has(message.toolCallId) || orphanFailedResults.has(message)) continue;\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"assistant\") {\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst content = message.content;\n\t\tif (content.length === 1) {\n\t\t\tconst block = content[0];\n\t\t\tif (block.type === \"toolCall\" && omittedCallIds.has(block.id)) continue;\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tlet hasOmitted = false;\n\t\tfor (let blockIdx = 0; blockIdx < content.length; blockIdx++) {\n\t\t\tconst block = content[blockIdx];\n\t\t\tif (block.type === \"toolCall\" && omittedCallIds.has(block.id)) {\n\t\t\t\thasOmitted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!hasOmitted) {\n\t\t\tfilteredMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst retainedContent = content.filter((block) => block.type !== \"toolCall\" || !omittedCallIds.has(block.id));\n\t\tif (retainedContent.length > 0) {\n\t\t\tfilteredMessages.push({ ...message, content: retainedContent } satisfies AssistantMessage);\n\t\t}\n\t}\n\tconst activeRecords = [...active.values()]\n\t\t.sort((left, right) => left.sequence - right.sequence)\n\t\t.map(({ record }) => record);\n\treturn {\n\t\tmessages: filteredMessages,\n\t\tactiveRecords,\n\t\tactiveDirectives: [...activeDirectives.values()],\n\t\tkindMistakesSummary,\n\t};\n}\n\nexport function createToolFailureMemoryTracker(messages: AgentMessage[]): ToolFailureMemoryTracker {\n\treturn new Map(analyzeToolFailureContext(messages).activeRecords.map((record) => [record.failureKey, record]));\n}\n\nexport function rememberToolFailure(\n\ttracker: ToolFailureMemoryTracker,\n\ttool: string,\n\targs: unknown,\n\tstate: ToolFailureState,\n\tfailureCode: string,\n\tcorrection: string,\n\tdiagnostic?: string,\n\tphase: ToolFailurePhase = inferToolFailurePhase(state, failureCode),\n): ToolFailureMemoryRecord {\n\tlet kindCount = 1;\n\tfor (const previous of tracker.values()) {\n\t\tif (previous.tool === tool) {\n\t\t\tkindCount = Math.max(kindCount, (previous.kindMistakes ?? previous.occurrence) + 1);\n\t\t}\n\t}\n\tif (getToolExecutionAttemptMemory(failureCode) === \"discard\") {\n\t\tfor (const [failureKey, previous] of tracker) {\n\t\t\tif (previous.tool === tool && previous.failureCode === failureCode) tracker.delete(failureKey);\n\t\t}\n\t\treturn {\n\t\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\t\tfailureKey: `directive:${boundedFailureCode(failureCode)}`,\n\t\t\t[TOOL_FAILURE_EXECUTION_KEY]: getToolExecutionKey(tool, args),\n\t\t\ttool: truncate(tool, MAX_TOOL_NAME_CHARS),\n\t\t\toperation: \"[discarded]\",\n\t\t\toccurrence: 1,\n\t\t\tkindMistakes: kindCount,\n\t\t\tmistakeKind: tool,\n\t\t\tstate,\n\t\t\tphase,\n\t\t\tfailureCode: boundedFailureCode(failureCode),\n\t\t\tdiagnostic: diagnostic ? truncate(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,\n\t\t\tcorrection: truncate(correction, MAX_CORRECTION_CHARS),\n\t\t\tattemptMemory: \"discard\",\n\t\t};\n\t}\n\tconst identity = operationIdentity(tool, args);\n\tconst previous = tracker.get(identity.failureKey);\n\tconst record: ToolFailureMemoryRecord = {\n\t\tversion: TOOL_FAILURE_MEMORY_VERSION,\n\t\tfailureKey: identity.failureKey,\n\t\t[TOOL_FAILURE_EXECUTION_KEY]: identity.executionKey,\n\t\ttool: identity.tool,\n\t\toperation: identity.operation,\n\t\toccurrence: (previous?.occurrence ?? 0) + 1,\n\t\tkindMistakes: kindCount,\n\t\tmistakeKind: tool,\n\t\tstate,\n\t\tphase,\n\t\tfailureCode: boundedFailureCode(failureCode),\n\t\tdiagnostic: diagnostic ? truncate(diagnostic, MAX_DIAGNOSTIC_CHARS) : undefined,\n\t\tcorrection: truncate(correction, MAX_CORRECTION_CHARS),\n\t};\n\ttracker.delete(identity.failureKey);\n\ttracker.set(identity.failureKey, record);\n\twhile (tracker.size > MAX_TRACKED_FAILURES) {\n\t\tconst oldest = tracker.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\ttracker.delete(oldest);\n\t}\n\treturn record;\n}\n\nexport function clearToolFailure(tracker: ToolFailureMemoryTracker, tool: string, args: unknown): void {\n\tconst failureKey = getToolFailureKey(tool, args);\n\tconst record = tracker.get(failureKey);\n\tconst executionKey = record ? getToolFailureRecordExecutionKey(record) : undefined;\n\tif (!executionKey || executionKey === getToolExecutionKey(tool, args)) tracker.delete(failureKey);\n}\n\nfunction failureGuidance(record: ToolFailureMemoryRecord): { repair: string } | { next_action: string } {\n\treturn record.state === \"rejected\" && REPAIRABLE_REJECTION_CODES.has(record.failureCode)\n\t\t? { repair: record.correction }\n\t\t: { next_action: record.correction };\n}\n\nfunction formatRecordJson(record: ToolFailureMemoryRecord, includeOperation = false): string {\n\tconst guidance = failureGuidance(record);\n\treturn JSON.stringify({\n\t\t...mandatoryToolFailureRecoveryMetadata(),\n\t\tfailure_key: record.failureKey,\n\t\tocc: record.occurrence,\n\t\tkind_mistakes: record.kindMistakes ?? record.occurrence,\n\t\tmistake_kind: record.mistakeKind ?? record.tool,\n\t\tstate: record.state,\n\t\tphase: record.phase,\n\t\ttool: record.tool,\n\t\t...(includeOperation ? { operation: record.operation } : {}),\n\t\tfailure_code: record.failureCode,\n\t\t...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),\n\t\t...guidance,\n\t\t...(record.attemptMemory === \"discard\" ? { attempt_memory: \"discarded\" } : {}),\n\t});\n}\n\nexport function createToolFailureResult(\n\trecord: ToolFailureMemoryRecord,\n\tterminate?: boolean,\n): AgentToolResult<ToolFailureResultDetails> {\n\tconst discardAttempt = record.attemptMemory === \"discard\";\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[harness] ${formatRecordJson(record, false)}`,\n\t\t\t},\n\t\t],\n\t\tdetails: discardAttempt\n\t\t\t? {\n\t\t\t\t\tpiToolFailureDirective: {\n\t\t\t\t\t\tversion: TOOL_FAILURE_DIRECTIVE_VERSION,\n\t\t\t\t\t\tstate: record.state,\n\t\t\t\t\t\tphase: record.phase,\n\t\t\t\t\t\tfailureCode: record.failureCode,\n\t\t\t\t\t\t...(record.diagnostic ? { diagnostic: record.diagnostic } : {}),\n\t\t\t\t\t\tnextAction: record.correction,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: { piToolFailureMemory: record },\n\t\t...(terminate === undefined ? {} : { terminate }),\n\t};\n}\n\nexport function createRepeatedToolFailureResult(\n\trecord: ToolFailureMemoryRecord,\n): AgentToolResult<ToolFailureMemoryDetails> {\n\tconst retainedRecord = {\n\t\t...retainBlockedToolFailure(record),\n\t\tcorrection: BLOCKED_REPLAY_CAVEMAN_CORRECTION,\n\t};\n\tconst diagnostic = truncateMiddle(\n\t\t`The unchanged operation was not executed. Unchanged replay blocked after ${record.failureCode}`,\n\t\tMAX_DIAGNOSTIC_CHARS,\n\t);\n\tconst blockedResult = createToolFailureResult({\n\t\t...retainedRecord,\n\t\tstate: \"rejected\",\n\t\tfailureCode: \"repeated_failed_operation\",\n\t\tdiagnostic,\n\t\tcorrection: retainedRecord.correction,\n\t});\n\treturn {\n\t\t...blockedResult,\n\t\t// The visible result describes this rejected replay, while retained memory keeps the\n\t\t// authoritative cause so later blocks do not recursively wrap synthetic failures.\n\t\tdetails: { piToolFailureMemory: retainedRecord },\n\t};\n}\n\nexport function createToolFailureRecoveryExhaustedResult(\n\trecord: ToolFailureMemoryRecord,\n\tdiagnostic: string,\n): AgentToolResult<ToolFailureMemoryDetails> {\n\tconst retainedRecord = retainBlockedToolFailure(record);\n\tconst exhaustedResult = createToolFailureResult(\n\t\t{\n\t\t\t...retainedRecord,\n\t\t\tstate: \"rejected\",\n\t\t\tfailureCode: \"recovery_exhausted\",\n\t\t\tdiagnostic: truncateMiddle(diagnostic, MAX_DIAGNOSTIC_CHARS),\n\t\t\tcorrection:\n\t\t\t\t\"Stop retrying tools in this run. Report the unresolved failure and the user or environment action required to continue.\",\n\t\t},\n\t\ttrue,\n\t);\n\treturn {\n\t\t...exhaustedResult,\n\t\tdetails: { piToolFailureMemory: retainedRecord },\n\t};\n}\n\nexport function createToolFailureOperationExhaustedResult(\n\trecord: ToolFailureMemoryRecord,\n\tdiagnostic: string,\n): AgentToolResult<ToolFailureMemoryDetails> {\n\tconst retainedRecord = {\n\t\t...retainBlockedToolFailure(record),\n\t\tcorrection: CLOSED_OPERATION_CAVEMAN_CORRECTION,\n\t};\n\tconst exhaustedResult = createToolFailureResult(\n\t\t{\n\t\t\t...retainedRecord,\n\t\t\tstate: \"rejected\",\n\t\t\tfailureCode: \"operation_recovery_exhausted\",\n\t\t\tdiagnostic: truncateMiddle(diagnostic, MAX_DIAGNOSTIC_CHARS),\n\t\t},\n\t\tfalse,\n\t);\n\treturn {\n\t\t...exhaustedResult,\n\t\tdetails: { piToolFailureMemory: retainedRecord },\n\t};\n}\n\nfunction retainBlockedToolFailure(record: ToolFailureMemoryRecord): ToolFailureMemoryRecord {\n\treturn {\n\t\t...record,\n\t\toccurrence: record.occurrence + 1,\n\t\tkindMistakes: (record.kindMistakes ?? record.occurrence) + 1,\n\t};\n}\n\nfunction escapePromptData(value: string): string {\n\treturn value.replaceAll(\"&\", \"\\\\u0026\").replaceAll(\"<\", \"\\\\u003c\").replaceAll(\">\", \"\\\\u003e\");\n}\n\nexport function sanitizeToolFailureContext(\n\tmessages: AgentMessage[],\n\tsystemPrompt: string,\n): { messages: AgentMessage[]; systemPrompt: string } {\n\tconst analysis = analyzeToolFailureContext(messages);\n\tif (analysis.activeRecords.length === 0 && analysis.activeDirectives.length === 0) {\n\t\treturn { messages: analysis.messages, systemPrompt };\n\t}\n\tconst records = analysis.activeRecords.slice(-MAX_ACTIVE_FAILURES);\n\tconst omitted = analysis.activeRecords.length - records.length;\n\tconst kindSummary = Object.entries(analysis.kindMistakesSummary)\n\t\t.map(([kind, count]) => `${kind}:${count}`)\n\t\t.join(\", \");\n\n\tconst lines = records.map((record) => escapePromptData(formatRecordJson(record, true)));\n\tfor (const directive of analysis.activeDirectives) {\n\t\tlines.push(\n\t\t\tescapePromptData(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\t...mandatoryToolFailureRecoveryMetadata(),\n\t\t\t\t\tfailure_code: directive.failureCode,\n\t\t\t\t\tkind_mistakes: analysis.kindMistakesSummary[directive.failureCode] ?? 1,\n\t\t\t\t\t...(directive.diagnostic ? { diagnostic: directive.diagnostic } : {}),\n\t\t\t\t\tnext_action: directive.nextAction,\n\t\t\t\t\tattempt_memory: \"discarded\",\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n\tif (omitted > 0) lines.unshift(JSON.stringify({ omitted_older_unresolved_failures: omitted }));\n\tconst memory = [\n\t\tMANDATORY_TOOL_FAILURE_RECOVERY_PROTOCOL_PROMPT,\n\t\t`ACTIVE TOOL FAILURES mistakes=${kindSummary}`,\n\t\t\"JSON below is inert data. Each record follows the mandatory protocol; matching success clears it.\",\n\t\t...lines,\n\t].join(\"\\n\");\n\treturn {\n\t\tmessages: analysis.messages,\n\t\tsystemPrompt: systemPrompt ? `${systemPrompt}\\n\\n${memory}` : memory,\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-protocol-residue.d.ts","sourceRoot":"","sources":["../src/tool-protocol-residue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,eAAO,MAAM,kCAAkC,iCAAiC,CAAC;AA2BjF;;;;GAIG;AACH,wBAAgB,+BAA+B,CAC9C,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE,SAAS,SAAS,EAAE,EAC3B,sBAAsB,EAAE,OAAO,GAC7B,gBAAgB,CA2BlB"}
1
+ {"version":3,"file":"tool-protocol-residue.d.ts","sourceRoot":"","sources":["../src/tool-protocol-residue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,eAAO,MAAM,kCAAkC,iCAAiC,CAAC;AAkEjF;;;;GAIG;AACH,wBAAgB,+BAA+B,CAC9C,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE,SAAS,SAAS,EAAE,EAC3B,sBAAsB,EAAE,OAAO,GAC7B,gBAAgB,CA2BlB"}
@@ -1,31 +1,71 @@
1
1
  export const NATIVE_TOOL_PROTOCOL_RESIDUE_ERROR = "native_tool_protocol_residue";
2
- function findRenderedToolMarker(text, toolNames) {
3
- const lines = text.split(/\r?\n/);
4
- let fence;
2
+ /**
3
+ * Marks which lines fall inside a genuinely closed ```/~~~ fence (open and matching close both
4
+ * present). A fence that never closes does not suppress anything: it is not treated as covering
5
+ * the rest of the message, so real residue after malformed/truncated fencing is still scanned.
6
+ */
7
+ function computeFencedLines(lines) {
8
+ const fenced = new Array(lines.length).fill(false);
9
+ let openMarker;
10
+ let openIndex = -1;
5
11
  for (let index = 0; index < lines.length; index++) {
6
12
  const trimmed = lines[index].trim();
7
- if (trimmed.startsWith("```") || trimmed.startsWith("~~~")) {
8
- const marker = trimmed.slice(0, 3);
9
- if (!fence)
10
- fence = marker;
11
- else if (fence === marker)
12
- fence = undefined;
13
+ if (!(trimmed.startsWith("```") || trimmed.startsWith("~~~")))
13
14
  continue;
15
+ const marker = trimmed.slice(0, 3);
16
+ if (!openMarker) {
17
+ openMarker = marker;
18
+ openIndex = index;
19
+ }
20
+ else if (openMarker === marker) {
21
+ for (let i = openIndex; i <= index; i++)
22
+ fenced[i] = true;
23
+ openMarker = undefined;
24
+ openIndex = -1;
14
25
  }
15
- if (fence)
26
+ }
27
+ return fenced;
28
+ }
29
+ function isJsonPayload(text) {
30
+ try {
31
+ JSON.parse(text);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ function findRenderedToolMarker(text, toolNames) {
39
+ const lines = text.split(/\r?\n/);
40
+ const fenced = computeFencedLines(lines);
41
+ for (let index = 0; index < lines.length; index++) {
42
+ if (fenced[index])
43
+ continue;
44
+ const trimmed = lines[index].trim();
45
+ if (trimmed.startsWith("```") || trimmed.startsWith("~~~"))
16
46
  continue;
17
47
  const match = /^to=functions\.([A-Za-z][A-Za-z0-9_-]{0,63})\s+code$/.exec(trimmed);
18
48
  const toolName = match?.[1];
19
49
  if (!toolName || !toolNames.has(toolName))
20
50
  continue;
21
- for (let payloadIndex = index + 1; payloadIndex < lines.length; payloadIndex++) {
22
- const payload = lines[payloadIndex].trim();
23
- if (!payload)
24
- continue;
25
- if (payload.startsWith("{") || payload.startsWith("["))
26
- return toolName;
27
- break;
28
- }
51
+ let payloadIndex = index + 1;
52
+ while (payloadIndex < lines.length && lines[payloadIndex].trim() === "")
53
+ payloadIndex++;
54
+ const payload = lines[payloadIndex]?.trim();
55
+ if (!payload || !(payload.startsWith("{") || payload.startsWith("[")))
56
+ continue;
57
+ if (!isJsonPayload(payload))
58
+ continue;
59
+ // Genuine residue is the terminal content of the turn: a provider that rendered a real tool
60
+ // call as plain text stops right there. Prose that merely quotes the marker syntax (this repo's
61
+ // own docs/tests discuss it) keeps explaining afterward, so trailing content after the payload
62
+ // is what tells a documentation example apart from an actual escaped tool call.
63
+ let trailingIndex = payloadIndex + 1;
64
+ while (trailingIndex < lines.length && lines[trailingIndex].trim() === "")
65
+ trailingIndex++;
66
+ if (trailingIndex < lines.length)
67
+ continue;
68
+ return toolName;
29
69
  }
30
70
  return undefined;
31
71
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tool-protocol-residue.js","sourceRoot":"","sources":["../src/tool-protocol-residue.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,kCAAkC,GAAG,8BAA8B,CAAC;AAEjF,SAAS,sBAAsB,CAAC,IAAY,EAAE,SAA8B;IAC3E,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAClC,IAAI,KAAgC,CAAC;IACrC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QACnD,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,OAAO,CAAC,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AC;IAChB,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO;SAC1B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC;SACxC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC;SAC1B,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,IAAI,CAAC,IAAI;QAAE,OAAO,OAAO,CAAC;IAC1B,MAAM,QAAQ,GAAG,sBAAsB,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACvF,IAAI,CAAC,QAAQ;QAAE,OAAO,OAAO,CAAC;IAC9B,OAAO;QACN,GAAG,OAAO;QACV,OAAO,EAAE;YACR;gBACC,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,uBAAuB,QAAQ,sDAAsD;aAC3F;SACD;QACD,UAAU,EAAE,OAAO;QACnB,YAAY,EAAE,GAAG,kCAAkC,eAAe,QAAQ,uBAAuB;KACjG,CAAC;AACH,CAAC","sourcesContent":["import type { AssistantMessage } from \"@caupulican/pi-ai/types\";\nimport type { AgentTool } from \"./types.ts\";\n\nexport const NATIVE_TOOL_PROTOCOL_RESIDUE_ERROR = \"native_tool_protocol_residue\";\n\nfunction findRenderedToolMarker(text: string, toolNames: ReadonlySet<string>): string | undefined {\n\tconst lines = text.split(/\\r?\\n/);\n\tlet fence: \"```\" | \"~~~\" | undefined;\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst trimmed = lines[index].trim();\n\t\tif (trimmed.startsWith(\"```\") || trimmed.startsWith(\"~~~\")) {\n\t\t\tconst marker = trimmed.slice(0, 3) as \"```\" | \"~~~\";\n\t\t\tif (!fence) fence = marker;\n\t\t\telse if (fence === marker) fence = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (fence) continue;\n\t\tconst match = /^to=functions\\.([A-Za-z][A-Za-z0-9_-]{0,63})\\s+code$/.exec(trimmed);\n\t\tconst toolName = match?.[1];\n\t\tif (!toolName || !toolNames.has(toolName)) continue;\n\t\tfor (let payloadIndex = index + 1; payloadIndex < lines.length; payloadIndex++) {\n\t\t\tconst payload = lines[payloadIndex].trim();\n\t\t\tif (!payload) continue;\n\t\t\tif (payload.startsWith(\"{\") || payload.startsWith(\"[\")) return toolName;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Refuse provider-internal native tool markup that escaped as assistant text. The detector is\n * intentionally narrow: a loaded tool name, a standalone unfenced marker, and an adjacent JSON\n * payload are all required. Nothing is parsed or executed from the rendered text.\n */\nexport function rejectNativeToolProtocolResidue(\n\tmessage: AssistantMessage,\n\ttools: readonly AgentTool[],\n\ttextToolProtocolActive: boolean,\n): AssistantMessage {\n\tif (\n\t\ttextToolProtocolActive ||\n\t\tmessage.stopReason === \"error\" ||\n\t\tmessage.stopReason === \"aborted\" ||\n\t\tmessage.content.some((block) => block.type === \"toolCall\")\n\t) {\n\t\treturn message;\n\t}\n\tconst text = message.content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tif (!text) return message;\n\tconst toolName = findRenderedToolMarker(text, new Set(tools.map((tool) => tool.name)));\n\tif (!toolName) return message;\n\treturn {\n\t\t...message,\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Provider rendered a ${toolName} tool call as plain text. No operation was executed.`,\n\t\t\t},\n\t\t],\n\t\tstopReason: \"error\",\n\t\terrorMessage: `${NATIVE_TOOL_PROTOCOL_RESIDUE_ERROR}: functions.${toolName} was rendered as text`,\n\t};\n}\n"]}
1
+ {"version":3,"file":"tool-protocol-residue.js","sourceRoot":"","sources":["../src/tool-protocol-residue.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,kCAAkC,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,UAAU,EAAE,OAAO;QACnB,YAAY,EAAE,GAAG,kCAAkC,eAAe,QAAQ,uBAAuB;KACjG,CAAC;AACH,CAAC","sourcesContent":["import type { AssistantMessage } from \"@caupulican/pi-ai/types\";\nimport type { AgentTool } from \"./types.ts\";\n\nexport const NATIVE_TOOL_PROTOCOL_RESIDUE_ERROR = \"native_tool_protocol_residue\";\n\n/**\n * Marks which lines fall inside a genuinely closed ```/~~~ fence (open and matching close both\n * present). A fence that never closes does not suppress anything: it is not treated as covering\n * the rest of the message, so real residue after malformed/truncated fencing is still scanned.\n */\nfunction computeFencedLines(lines: readonly string[]): boolean[] {\n\tconst fenced = new Array<boolean>(lines.length).fill(false);\n\tlet openMarker: \"```\" | \"~~~\" | undefined;\n\tlet openIndex = -1;\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst trimmed = lines[index].trim();\n\t\tif (!(trimmed.startsWith(\"```\") || trimmed.startsWith(\"~~~\"))) continue;\n\t\tconst marker = trimmed.slice(0, 3) as \"```\" | \"~~~\";\n\t\tif (!openMarker) {\n\t\t\topenMarker = marker;\n\t\t\topenIndex = index;\n\t\t} else if (openMarker === marker) {\n\t\t\tfor (let i = openIndex; i <= index; i++) fenced[i] = true;\n\t\t\topenMarker = undefined;\n\t\t\topenIndex = -1;\n\t\t}\n\t}\n\treturn fenced;\n}\n\nfunction isJsonPayload(text: string): boolean {\n\ttry {\n\t\tJSON.parse(text);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction findRenderedToolMarker(text: string, toolNames: ReadonlySet<string>): string | undefined {\n\tconst lines = text.split(/\\r?\\n/);\n\tconst fenced = computeFencedLines(lines);\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tif (fenced[index]) continue;\n\t\tconst trimmed = lines[index].trim();\n\t\tif (trimmed.startsWith(\"```\") || trimmed.startsWith(\"~~~\")) continue;\n\t\tconst match = /^to=functions\\.([A-Za-z][A-Za-z0-9_-]{0,63})\\s+code$/.exec(trimmed);\n\t\tconst toolName = match?.[1];\n\t\tif (!toolName || !toolNames.has(toolName)) continue;\n\n\t\tlet payloadIndex = index + 1;\n\t\twhile (payloadIndex < lines.length && lines[payloadIndex].trim() === \"\") payloadIndex++;\n\t\tconst payload = lines[payloadIndex]?.trim();\n\t\tif (!payload || !(payload.startsWith(\"{\") || payload.startsWith(\"[\"))) continue;\n\t\tif (!isJsonPayload(payload)) continue;\n\n\t\t// Genuine residue is the terminal content of the turn: a provider that rendered a real tool\n\t\t// call as plain text stops right there. Prose that merely quotes the marker syntax (this repo's\n\t\t// own docs/tests discuss it) keeps explaining afterward, so trailing content after the payload\n\t\t// is what tells a documentation example apart from an actual escaped tool call.\n\t\tlet trailingIndex = payloadIndex + 1;\n\t\twhile (trailingIndex < lines.length && lines[trailingIndex].trim() === \"\") trailingIndex++;\n\t\tif (trailingIndex < lines.length) continue;\n\n\t\treturn toolName;\n\t}\n\treturn undefined;\n}\n\n/**\n * Refuse provider-internal native tool markup that escaped as assistant text. The detector is\n * intentionally narrow: a loaded tool name, a standalone unfenced marker, and an adjacent JSON\n * payload are all required. Nothing is parsed or executed from the rendered text.\n */\nexport function rejectNativeToolProtocolResidue(\n\tmessage: AssistantMessage,\n\ttools: readonly AgentTool[],\n\ttextToolProtocolActive: boolean,\n): AssistantMessage {\n\tif (\n\t\ttextToolProtocolActive ||\n\t\tmessage.stopReason === \"error\" ||\n\t\tmessage.stopReason === \"aborted\" ||\n\t\tmessage.content.some((block) => block.type === \"toolCall\")\n\t) {\n\t\treturn message;\n\t}\n\tconst text = message.content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tif (!text) return message;\n\tconst toolName = findRenderedToolMarker(text, new Set(tools.map((tool) => tool.name)));\n\tif (!toolName) return message;\n\treturn {\n\t\t...message,\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Provider rendered a ${toolName} tool call as plain text. No operation was executed.`,\n\t\t\t},\n\t\t],\n\t\tstopReason: \"error\",\n\t\terrorMessage: `${NATIVE_TOOL_PROTOCOL_RESIDUE_ERROR}: functions.${toolName} was rendered as text`,\n\t};\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caupulican/pi-agent-core",
3
- "version": "0.90.7",
3
+ "version": "0.90.11",
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.90.7",
124
+ "@caupulican/pi-ai": "^0.90.11",
125
125
  "ignore": "7.0.5",
126
126
  "typebox": "1.1.38",
127
127
  "yaml": "2.9.0"