@caupulican/pi-adaptative 0.85.0 → 0.85.3

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 (88) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/bundled-resources/runtimes/pi-shell-engine/arithmetic.py +364 -0
  3. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +2 -1
  4. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +16 -0
  5. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +137 -14
  6. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +23 -2
  7. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +134 -6
  8. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +25 -2
  9. package/dist/core/agent-session.d.ts.map +1 -1
  10. package/dist/core/agent-session.js +8 -0
  11. package/dist/core/agent-session.js.map +1 -1
  12. package/dist/core/compaction-controller.d.ts +2 -0
  13. package/dist/core/compaction-controller.d.ts.map +1 -1
  14. package/dist/core/compaction-controller.js +35 -13
  15. package/dist/core/compaction-controller.js.map +1 -1
  16. package/dist/core/failure-corpus.d.ts +26 -1
  17. package/dist/core/failure-corpus.d.ts.map +1 -1
  18. package/dist/core/failure-corpus.js +17 -0
  19. package/dist/core/failure-corpus.js.map +1 -1
  20. package/dist/core/model-tool-protocol.d.ts +3 -2
  21. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  22. package/dist/core/model-tool-protocol.js +5 -1
  23. package/dist/core/model-tool-protocol.js.map +1 -1
  24. package/dist/core/models/runtime-process.d.ts +7 -1
  25. package/dist/core/models/runtime-process.d.ts.map +1 -1
  26. package/dist/core/models/runtime-process.js +4 -2
  27. package/dist/core/models/runtime-process.js.map +1 -1
  28. package/dist/core/process-matrix/runtime.js +43 -11
  29. package/dist/core/process-matrix/runtime.js.map +1 -1
  30. package/dist/core/resource-loader.d.ts +2 -0
  31. package/dist/core/resource-loader.d.ts.map +1 -1
  32. package/dist/core/resource-loader.js +18 -6
  33. package/dist/core/resource-loader.js.map +1 -1
  34. package/dist/core/tool-recovery-log-records.d.ts +33 -1
  35. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  36. package/dist/core/tool-recovery-log-records.js +59 -12
  37. package/dist/core/tool-recovery-log-records.js.map +1 -1
  38. package/dist/core/tool-recovery-logger.d.ts +12 -1
  39. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  40. package/dist/core/tool-recovery-logger.js +24 -1
  41. package/dist/core/tool-recovery-logger.js.map +1 -1
  42. package/dist/core/tool-repair-health.d.ts.map +1 -1
  43. package/dist/core/tool-repair-health.js +6 -0
  44. package/dist/core/tool-repair-health.js.map +1 -1
  45. package/dist/core/tools/bash.d.ts +2 -2
  46. package/dist/core/tools/bash.d.ts.map +1 -1
  47. package/dist/core/tools/bash.js +2 -2
  48. package/dist/core/tools/bash.js.map +1 -1
  49. package/dist/core/tools/find.d.ts +2 -1
  50. package/dist/core/tools/find.d.ts.map +1 -1
  51. package/dist/core/tools/find.js +2 -6
  52. package/dist/core/tools/find.js.map +1 -1
  53. package/dist/core/tools/grep.d.ts +2 -1
  54. package/dist/core/tools/grep.d.ts.map +1 -1
  55. package/dist/core/tools/grep.js +2 -6
  56. package/dist/core/tools/grep.js.map +1 -1
  57. package/dist/core/tools/managed-search-tool.d.ts +8 -0
  58. package/dist/core/tools/managed-search-tool.d.ts.map +1 -0
  59. package/dist/core/tools/managed-search-tool.js +10 -0
  60. package/dist/core/tools/managed-search-tool.js.map +1 -0
  61. package/dist/core/tools/shell-command-parser.d.ts +4 -3
  62. package/dist/core/tools/shell-command-parser.d.ts.map +1 -1
  63. package/dist/core/tools/shell-command-parser.js +32 -7
  64. package/dist/core/tools/shell-command-parser.js.map +1 -1
  65. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  66. package/dist/core/tools/shell-contract-router.js +23 -1
  67. package/dist/core/tools/shell-contract-router.js.map +1 -1
  68. package/dist/core/tools/windows-shell-engine.js +1 -1
  69. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  70. package/dist/utils/paths.js +1 -1
  71. package/dist/utils/paths.js.map +1 -1
  72. package/dist/utils/tools-manager.d.ts +18 -1
  73. package/dist/utils/tools-manager.d.ts.map +1 -1
  74. package/dist/utils/tools-manager.js +73 -43
  75. package/dist/utils/tools-manager.js.map +1 -1
  76. package/docs/models.md +1 -1
  77. package/docs/settings.md +1 -1
  78. package/docs/tool-repair.md +3 -3
  79. package/docs/windows.md +7 -5
  80. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  81. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  82. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  83. package/examples/extensions/sandbox/package-lock.json +2 -2
  84. package/examples/extensions/sandbox/package.json +1 -1
  85. package/examples/extensions/with-deps/package-lock.json +2 -2
  86. package/examples/extensions/with-deps/package.json +1 -1
  87. package/npm-shrinkwrap.json +12 -12
  88. package/package.json +4 -4
@@ -1,6 +1,8 @@
1
1
  import type { ToolArgumentValidationTelemetryEvent } from "@caupulican/pi-ai";
2
+ import type { ToolFailurePhase } from "@caupulican/pi-ai/tool-repair-registry";
2
3
  export declare const TOOL_RECOVERY_EVENT_LOG_FILE = "tool-recovery-events.jsonl";
3
4
  export declare const TOOL_ARGUMENT_VALIDATION_LOG_KIND = "tool_argument_validation";
5
+ export declare const TOOL_EXECUTION_FAILURE_LOG_KIND = "tool_execution_failure";
4
6
  export interface ToolArgumentValidationLogRecord extends ToolArgumentValidationTelemetryEvent {
5
7
  kind: typeof TOOL_ARGUMENT_VALIDATION_LOG_KIND;
6
8
  version: 1;
@@ -8,10 +10,26 @@ export interface ToolArgumentValidationLogRecord extends ToolArgumentValidationT
8
10
  ts: string;
9
11
  sessionId: string;
10
12
  }
13
+ export interface ToolExecutionFailureLogRecord {
14
+ kind: typeof TOOL_EXECUTION_FAILURE_LOG_KIND;
15
+ version: 1;
16
+ recordId: string;
17
+ ts: string;
18
+ sessionId: string;
19
+ provider?: string;
20
+ model?: string;
21
+ tool: string;
22
+ state: "failed" | "rejected";
23
+ phase: ToolFailurePhase;
24
+ failureCode: string;
25
+ diagnostic?: string;
26
+ nextAction: string;
27
+ }
28
+ export type ToolRecoveryLogRecord = ToolArgumentValidationLogRecord | ToolExecutionFailureLogRecord;
11
29
  export interface ToolRecoveryLogWorkerRecord {
12
30
  eventLogPath: string;
13
31
  failureCorpusPath: string;
14
- record: ToolArgumentValidationLogRecord;
32
+ record: ToolRecoveryLogRecord;
15
33
  }
16
34
  export declare function createToolArgumentValidationLogRecord(args: {
17
35
  event: ToolArgumentValidationTelemetryEvent;
@@ -19,7 +37,21 @@ export declare function createToolArgumentValidationLogRecord(args: {
19
37
  sessionId: string;
20
38
  ts: string;
21
39
  }): ToolArgumentValidationLogRecord;
40
+ export declare function createToolExecutionFailureLogRecord(args: {
41
+ provider?: string;
42
+ model?: string;
43
+ tool: string;
44
+ state: "failed" | "rejected";
45
+ phase: ToolFailurePhase;
46
+ failureCode: string;
47
+ diagnostic?: string;
48
+ nextAction: string;
49
+ recordId: string;
50
+ sessionId: string;
51
+ ts: string;
52
+ }): ToolExecutionFailureLogRecord;
22
53
  export declare function isToolArgumentValidationLogRecord(value: unknown): value is ToolArgumentValidationLogRecord;
54
+ export declare function isToolExecutionFailureLogRecord(value: unknown): value is ToolExecutionFailureLogRecord;
23
55
  /**
24
56
  * Append + rotate under a single exclusive lock on `eventLogPath`. Without the lock, a concurrent
25
57
  * writer (e.g. another session's tool-recovery worker) could append between this call's read and its
@@ -1 +1 @@
1
- {"version":3,"file":"tool-recovery-log-records.d.ts","sourceRoot":"","sources":["../../src/core/tool-recovery-log-records.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAS9E,eAAO,MAAM,4BAA4B,+BAA+B,CAAC;AACzE,eAAO,MAAM,iCAAiC,6BAA6B,CAAC;AAU5E,MAAM,WAAW,+B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EAAE,MAAM,CAAC;CACX,GAAG,6BAA6B,CAgBhC;AAED,wBAAgB,iCAAiC,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,+BAA+B,CAc1G;AAED,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,6BAA6B,CAetG;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,2BAA2B,GAAG,IAAI,CAqCnF"}
@@ -1,8 +1,9 @@
1
- import { createToolValidationFailureCorpusRecord, writeFailureCorpusRecord, } from "./failure-corpus.js";
1
+ import { createToolExecutionFailureCorpusRecord, createToolValidationFailureCorpusRecord, redactSecrets, writeFailureCorpusRecord, } from "./failure-corpus.js";
2
2
  import { updatePersistedToolRecoveryStats } from "./tool-recovery-stats.js";
3
3
  import { appendBoundedJsonLineSync } from "./util/bounded-jsonl.js";
4
4
  export const TOOL_RECOVERY_EVENT_LOG_FILE = "tool-recovery-events.jsonl";
5
5
  export const TOOL_ARGUMENT_VALIDATION_LOG_KIND = "tool_argument_validation";
6
+ export const TOOL_EXECUTION_FAILURE_LOG_KIND = "tool_execution_failure";
6
7
  const TOOL_RECOVERY_EVENT_LIMITS = {
7
8
  maxBytes: 4 * 1024 * 1024,
8
9
  targetBytes: Math.floor(4 * 1024 * 1024 * 0.75),
@@ -47,6 +48,23 @@ export function createToolArgumentValidationLogRecord(args) {
47
48
  executionOutcome: args.event.executionOutcome,
48
49
  };
49
50
  }
51
+ export function createToolExecutionFailureLogRecord(args) {
52
+ return {
53
+ kind: TOOL_EXECUTION_FAILURE_LOG_KIND,
54
+ version: 1,
55
+ recordId: boundedText(args.recordId),
56
+ ts: boundedText(args.ts),
57
+ sessionId: boundedText(args.sessionId),
58
+ provider: args.provider ? boundedText(args.provider) : undefined,
59
+ model: args.model ? boundedText(args.model) : undefined,
60
+ tool: boundedText(args.tool),
61
+ state: args.state,
62
+ phase: args.phase,
63
+ failureCode: boundedText(args.failureCode),
64
+ ...(args.diagnostic ? { diagnostic: boundedText(redactSecrets(args.diagnostic)) } : {}),
65
+ nextAction: boundedText(redactSecrets(args.nextAction)),
66
+ };
67
+ }
50
68
  export function isToolArgumentValidationLogRecord(value) {
51
69
  if (!value || typeof value !== "object")
52
70
  return false;
@@ -61,6 +79,21 @@ export function isToolArgumentValidationLogRecord(value) {
61
79
  Array.isArray(record.failureModes) &&
62
80
  Array.isArray(record.repairsApplied));
63
81
  }
82
+ export function isToolExecutionFailureLogRecord(value) {
83
+ if (!value || typeof value !== "object")
84
+ return false;
85
+ const record = value;
86
+ return (record.kind === TOOL_EXECUTION_FAILURE_LOG_KIND &&
87
+ record.version === 1 &&
88
+ typeof record.recordId === "string" &&
89
+ typeof record.ts === "string" &&
90
+ typeof record.sessionId === "string" &&
91
+ typeof record.tool === "string" &&
92
+ (record.state === "failed" || record.state === "rejected") &&
93
+ typeof record.phase === "string" &&
94
+ typeof record.failureCode === "string" &&
95
+ typeof record.nextAction === "string");
96
+ }
64
97
  /**
65
98
  * Append + rotate under a single exclusive lock on `eventLogPath`. Without the lock, a concurrent
66
99
  * writer (e.g. another session's tool-recovery worker) could append between this call's read and its
@@ -69,22 +102,36 @@ export function isToolArgumentValidationLogRecord(value) {
69
102
  */
70
103
  export function writeToolRecoveryLogRecord(entry) {
71
104
  appendBoundedJsonLineSync(entry.eventLogPath, entry.record, TOOL_RECOVERY_EVENT_LIMITS);
72
- try {
73
- updatePersistedToolRecoveryStats(entry.eventLogPath, entry.record);
74
- }
75
- catch {
76
- // The bounded event log remains the recovery source if the cumulative summary cannot be updated.
77
- }
78
- if (entry.record.outcome !== "bounced")
105
+ if (entry.record.kind === TOOL_ARGUMENT_VALIDATION_LOG_KIND) {
106
+ try {
107
+ updatePersistedToolRecoveryStats(entry.eventLogPath, entry.record);
108
+ }
109
+ catch {
110
+ // The bounded event log remains the recovery source if the cumulative summary cannot be updated.
111
+ }
112
+ if (entry.record.outcome !== "bounced")
113
+ return;
114
+ writeFailureCorpusRecord(entry.failureCorpusPath, createToolValidationFailureCorpusRecord({
115
+ ts: entry.record.ts,
116
+ provider: entry.record.provider,
117
+ modelId: entry.record.model,
118
+ tool: entry.record.tool,
119
+ failureModes: entry.record.failureModes,
120
+ shape: copyFailureShape(entry.record.failureShape),
121
+ errorKeywords: entry.record.errorKeywords,
122
+ }));
79
123
  return;
80
- writeFailureCorpusRecord(entry.failureCorpusPath, createToolValidationFailureCorpusRecord({
124
+ }
125
+ writeFailureCorpusRecord(entry.failureCorpusPath, createToolExecutionFailureCorpusRecord({
81
126
  ts: entry.record.ts,
82
127
  provider: entry.record.provider,
83
128
  modelId: entry.record.model,
84
129
  tool: entry.record.tool,
85
- failureModes: entry.record.failureModes,
86
- shape: copyFailureShape(entry.record.failureShape),
87
- errorKeywords: entry.record.errorKeywords,
130
+ state: entry.record.state,
131
+ phase: entry.record.phase,
132
+ failureCode: entry.record.failureCode,
133
+ diagnostic: entry.record.diagnostic,
134
+ nextAction: entry.record.nextAction,
88
135
  }));
89
136
  }
90
137
  //# sourceMappingURL=tool-recovery-log-records.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-recovery-log-records.js","sourceRoot":"","sources":["../../src/core/tool-recovery-log-records.ts"],"names":[],"mappings":"AACA,OAAO,EACN,uCAAuC,EAEvC,wBAAwB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EAAE,yBAAyB,EAA2B,MAAM,yBAAyB,CAAC;AAE7F,MAAM,CAAC,MAAM,4BAA4B,GAAG,4BAA4B,CAAC;AACzE,MAAM,CAAC,MAAM,iCAAiC,GAAG,0BAA0B,CAAC;AAE5E,MAAM,0BAA0B,GAAuB;IACtD,QAAQ,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IACzB,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC/C,UAAU,E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C,CACpC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CAAC,KAAkC;IAC5E,yBAAyB,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,CAAC,MAAM,EAAE,0BAA0B,CAAC,CAAC;IACxF,IAAI,CAAC;QACJ,gCAAgC,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACpE,CAAC;IAAC,MAAM,CAAC;QACR,iGAAiG;IAClG,CAAC;IACD,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO;IAC/C,wBAAwB,CACvB,KAAK,CAAC,iBAAiB,EACvB,uCAAuC,CAAC;QACvC,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE;QACnB,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,QAAQ;QAC/B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK;QAC3B,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI;QACvB,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;QACvC,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC;QAClD,aAAa,EAAE,KAAK,CAAC,MAAM,CAAC,aAAa;KACzC,CAAC,CACF,CAAC;AACH,CAAC","sourcesContent":["import type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport {\n\tcreateToolValidationFailureCorpusRecord,\n\ttype ToolValidationFailureShapeEntry,\n\twriteFailureCorpusRecord,\n} from \"./failure-corpus.ts\";\nimport { updatePersistedToolRecoveryStats } from \"./tool-recovery-stats.ts\";\nimport { appendBoundedJsonLineSync, type BoundedJsonlLimits } from \"./util/bounded-jsonl.ts\";\n\nexport const TOOL_RECOVERY_EVENT_LOG_FILE = \"tool-recovery-events.jsonl\";\nexport const TOOL_ARGUMENT_VALIDATION_LOG_KIND = \"tool_argument_validation\";\n\nconst TOOL_RECOVERY_EVENT_LIMITS: BoundedJsonlLimits = {\n\tmaxBytes: 4 * 1024 * 1024,\n\ttargetBytes: Math.floor(4 * 1024 * 1024 * 0.75),\n\tmaxRecords: 5_000,\n};\nconst MAX_TELEMETRY_LIST_ITEMS = 50;\nconst MAX_TELEMETRY_TEXT_CHARS = 256;\n\nexport interface ToolArgumentValidationLogRecord extends ToolArgumentValidationTelemetryEvent {\n\tkind: typeof TOOL_ARGUMENT_VALIDATION_LOG_KIND;\n\tversion: 1;\n\trecordId: string;\n\tts: string;\n\tsessionId: string;\n}\n\nexport interface ToolRecoveryLogWorkerRecord {\n\teventLogPath: string;\n\tfailureCorpusPath: string;\n\trecord: ToolArgumentValidationLogRecord;\n}\n\nfunction boundedText(value: string): string {\n\treturn value.slice(0, MAX_TELEMETRY_TEXT_CHARS);\n}\n\nfunction boundedList<T extends string>(values: readonly T[] | undefined): T[] | undefined {\n\treturn values?.slice(0, MAX_TELEMETRY_LIST_ITEMS);\n}\n\nfunction boundedTextList(values: readonly string[] | undefined): string[] | undefined {\n\treturn values?.slice(0, MAX_TELEMETRY_LIST_ITEMS).map(boundedText);\n}\n\nfunction copyFailureShape(\n\tshape: readonly ToolValidationFailureShapeEntry[] | undefined,\n): ToolValidationFailureShapeEntry[] {\n\treturn (shape ?? []).slice(0, MAX_TELEMETRY_LIST_ITEMS).map((entry) => ({\n\t\tpath: boundedText(entry.path),\n\t\texpectedType: boundedText(entry.expectedType),\n\t\treceivedType: boundedText(entry.receivedType),\n\t\t...(entry.keyword ? { keyword: boundedText(entry.keyword) } : {}),\n\t}));\n}\n\nexport function createToolArgumentValidationLogRecord(args: {\n\tevent: ToolArgumentValidationTelemetryEvent;\n\trecordId: string;\n\tsessionId: string;\n\tts: string;\n}): ToolArgumentValidationLogRecord {\n\treturn {\n\t\tkind: TOOL_ARGUMENT_VALIDATION_LOG_KIND,\n\t\tversion: 1,\n\t\trecordId: args.recordId,\n\t\tts: args.ts,\n\t\tsessionId: args.sessionId,\n\t\toutcome: args.event.outcome,\n\t\tprovider: args.event.provider,\n\t\tmodel: args.event.model,\n\t\ttool: args.event.tool,\n\t\tsource: args.event.source,\n\t\tfailureModes: boundedList(args.event.failureModes) ?? [],\n\t\trepairsApplied: boundedList(args.event.repairsApplied) ?? [],\n\t\tfailureShape: copyFailureShape(args.event.failureShape),\n\t\terrorKeywords: boundedTextList(args.event.errorKeywords),\n\t\ttaught: args.event.taught,\n\t\texecutionOutcome: args.event.executionOutcome,\n\t};\n}\n\nexport function isToolArgumentValidationLogRecord(value: unknown): value is ToolArgumentValidationLogRecord {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Partial<ToolArgumentValidationLogRecord>;\n\treturn (\n\t\trecord.kind === TOOL_ARGUMENT_VALIDATION_LOG_KIND &&\n\t\trecord.version === 1 &&\n\t\ttypeof record.recordId === \"string\" &&\n\t\ttypeof record.ts === \"string\" &&\n\t\ttypeof record.sessionId === \"string\" &&\n\t\t(record.outcome === \"repaired\" || record.outcome === \"bounced\") &&\n\t\ttypeof record.tool === \"string\" &&\n\t\tArray.isArray(record.failureModes) &&\n\t\tArray.isArray(record.repairsApplied)\n\t);\n}\n\n/**\n * Append + rotate under a single exclusive lock on `eventLogPath`. Without the lock, a concurrent\n * writer (e.g. another session's tool-recovery worker) could append between this call's read and its\n * rotated rewrite, and that append would be silently discarded when the rewrite lands. The shared\n * bounded JSONL sink also uses atomic tmp+rename rotation so readers never observe torn log files.\n */\nexport function writeToolRecoveryLogRecord(entry: ToolRecoveryLogWorkerRecord): void {\n\tappendBoundedJsonLineSync(entry.eventLogPath, entry.record, TOOL_RECOVERY_EVENT_LIMITS);\n\ttry {\n\t\tupdatePersistedToolRecoveryStats(entry.eventLogPath, entry.record);\n\t} catch {\n\t\t// The bounded event log remains the recovery source if the cumulative summary cannot be updated.\n\t}\n\tif (entry.record.outcome !== \"bounced\") return;\n\twriteFailureCorpusRecord(\n\t\tentry.failureCorpusPath,\n\t\tcreateToolValidationFailureCorpusRecord({\n\t\t\tts: entry.record.ts,\n\t\t\tprovider: entry.record.provider,\n\t\t\tmodelId: entry.record.model,\n\t\t\ttool: entry.record.tool,\n\t\t\tfailureModes: entry.record.failureModes,\n\t\t\tshape: copyFailureShape(entry.record.failureShape),\n\t\t\terrorKeywords: entry.record.errorKeywords,\n\t\t}),\n\t);\n}\n"]}
1
+ {"version":3,"file":"tool-recovery-log-records.js","sourceRoot":"","sources":["../../src/core/tool-recovery-log-records.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,sCAAsC,EACtC,uCAAuC,EACvC,aAAa,EAEb,wBAAwB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EAAE,yBAAyB,EAA2B,MAAM,yBAAyB,CAAC;AAE7F,MAAM,CAAC,MAAM,4BAA4B,GAAG,4BAA4B,CAAC;AACzE,MAAM,CAAC,MAAM,iCAAiC,GAAG,0BAA0B,CAAC;AAC5E,MAAM,CAAC,MAAM,+BAA+B,GAAG,wBAAwB,CAAC;AAExE,MAAM,0BAA0B,GAAuB;IACtD,QAAQ,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IACzB,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC/C,UAAU,EAAE,KAAK;CACjB,CAAC;AACF,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAkCrC,SAAS,WAAW,CAAC,KAAa;IACjC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,wBAAwB,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,WAAW,CAAmB,MAAgC;IACtE,OAAO,MAAM,EAAE,KAAK,CAAC,CAAC,EAAE,wBAAwB,CAAC,CAAC;AACnD,CAAC;AAED,SAAS,eAAe,CAAC,MAAqC;IAC7D,OAAO,MAAM,EAAE,KAA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AAC,MAAM,CAAC,KAAK;QACzB,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,WAAW;QACrC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;QACnC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;KACnC,CAAC,CACF,CAAC;AACH,CAAC","sourcesContent":["import type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport type { ToolFailurePhase } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport {\n\tcreateToolExecutionFailureCorpusRecord,\n\tcreateToolValidationFailureCorpusRecord,\n\tredactSecrets,\n\ttype ToolValidationFailureShapeEntry,\n\twriteFailureCorpusRecord,\n} from \"./failure-corpus.ts\";\nimport { updatePersistedToolRecoveryStats } from \"./tool-recovery-stats.ts\";\nimport { appendBoundedJsonLineSync, type BoundedJsonlLimits } from \"./util/bounded-jsonl.ts\";\n\nexport const TOOL_RECOVERY_EVENT_LOG_FILE = \"tool-recovery-events.jsonl\";\nexport const TOOL_ARGUMENT_VALIDATION_LOG_KIND = \"tool_argument_validation\";\nexport const TOOL_EXECUTION_FAILURE_LOG_KIND = \"tool_execution_failure\";\n\nconst TOOL_RECOVERY_EVENT_LIMITS: BoundedJsonlLimits = {\n\tmaxBytes: 4 * 1024 * 1024,\n\ttargetBytes: Math.floor(4 * 1024 * 1024 * 0.75),\n\tmaxRecords: 5_000,\n};\nconst MAX_TELEMETRY_LIST_ITEMS = 50;\nconst MAX_TELEMETRY_TEXT_CHARS = 256;\n\nexport interface ToolArgumentValidationLogRecord extends ToolArgumentValidationTelemetryEvent {\n\tkind: typeof TOOL_ARGUMENT_VALIDATION_LOG_KIND;\n\tversion: 1;\n\trecordId: string;\n\tts: string;\n\tsessionId: string;\n}\n\nexport interface ToolExecutionFailureLogRecord {\n\tkind: typeof TOOL_EXECUTION_FAILURE_LOG_KIND;\n\tversion: 1;\n\trecordId: string;\n\tts: string;\n\tsessionId: string;\n\tprovider?: string;\n\tmodel?: string;\n\ttool: string;\n\tstate: \"failed\" | \"rejected\";\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tdiagnostic?: string;\n\tnextAction: string;\n}\n\nexport type ToolRecoveryLogRecord = ToolArgumentValidationLogRecord | ToolExecutionFailureLogRecord;\n\nexport interface ToolRecoveryLogWorkerRecord {\n\teventLogPath: string;\n\tfailureCorpusPath: string;\n\trecord: ToolRecoveryLogRecord;\n}\n\nfunction boundedText(value: string): string {\n\treturn value.slice(0, MAX_TELEMETRY_TEXT_CHARS);\n}\n\nfunction boundedList<T extends string>(values: readonly T[] | undefined): T[] | undefined {\n\treturn values?.slice(0, MAX_TELEMETRY_LIST_ITEMS);\n}\n\nfunction boundedTextList(values: readonly string[] | undefined): string[] | undefined {\n\treturn values?.slice(0, MAX_TELEMETRY_LIST_ITEMS).map(boundedText);\n}\n\nfunction copyFailureShape(\n\tshape: readonly ToolValidationFailureShapeEntry[] | undefined,\n): ToolValidationFailureShapeEntry[] {\n\treturn (shape ?? []).slice(0, MAX_TELEMETRY_LIST_ITEMS).map((entry) => ({\n\t\tpath: boundedText(entry.path),\n\t\texpectedType: boundedText(entry.expectedType),\n\t\treceivedType: boundedText(entry.receivedType),\n\t\t...(entry.keyword ? { keyword: boundedText(entry.keyword) } : {}),\n\t}));\n}\n\nexport function createToolArgumentValidationLogRecord(args: {\n\tevent: ToolArgumentValidationTelemetryEvent;\n\trecordId: string;\n\tsessionId: string;\n\tts: string;\n}): ToolArgumentValidationLogRecord {\n\treturn {\n\t\tkind: TOOL_ARGUMENT_VALIDATION_LOG_KIND,\n\t\tversion: 1,\n\t\trecordId: args.recordId,\n\t\tts: args.ts,\n\t\tsessionId: args.sessionId,\n\t\toutcome: args.event.outcome,\n\t\tprovider: args.event.provider,\n\t\tmodel: args.event.model,\n\t\ttool: args.event.tool,\n\t\tsource: args.event.source,\n\t\tfailureModes: boundedList(args.event.failureModes) ?? [],\n\t\trepairsApplied: boundedList(args.event.repairsApplied) ?? [],\n\t\tfailureShape: copyFailureShape(args.event.failureShape),\n\t\terrorKeywords: boundedTextList(args.event.errorKeywords),\n\t\ttaught: args.event.taught,\n\t\texecutionOutcome: args.event.executionOutcome,\n\t};\n}\n\nexport function createToolExecutionFailureLogRecord(args: {\n\tprovider?: string;\n\tmodel?: string;\n\ttool: string;\n\tstate: \"failed\" | \"rejected\";\n\tphase: ToolFailurePhase;\n\tfailureCode: string;\n\tdiagnostic?: string;\n\tnextAction: string;\n\trecordId: string;\n\tsessionId: string;\n\tts: string;\n}): ToolExecutionFailureLogRecord {\n\treturn {\n\t\tkind: TOOL_EXECUTION_FAILURE_LOG_KIND,\n\t\tversion: 1,\n\t\trecordId: boundedText(args.recordId),\n\t\tts: boundedText(args.ts),\n\t\tsessionId: boundedText(args.sessionId),\n\t\tprovider: args.provider ? boundedText(args.provider) : undefined,\n\t\tmodel: args.model ? boundedText(args.model) : undefined,\n\t\ttool: boundedText(args.tool),\n\t\tstate: args.state,\n\t\tphase: args.phase,\n\t\tfailureCode: boundedText(args.failureCode),\n\t\t...(args.diagnostic ? { diagnostic: boundedText(redactSecrets(args.diagnostic)) } : {}),\n\t\tnextAction: boundedText(redactSecrets(args.nextAction)),\n\t};\n}\n\nexport function isToolArgumentValidationLogRecord(value: unknown): value is ToolArgumentValidationLogRecord {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Partial<ToolArgumentValidationLogRecord>;\n\treturn (\n\t\trecord.kind === TOOL_ARGUMENT_VALIDATION_LOG_KIND &&\n\t\trecord.version === 1 &&\n\t\ttypeof record.recordId === \"string\" &&\n\t\ttypeof record.ts === \"string\" &&\n\t\ttypeof record.sessionId === \"string\" &&\n\t\t(record.outcome === \"repaired\" || record.outcome === \"bounced\") &&\n\t\ttypeof record.tool === \"string\" &&\n\t\tArray.isArray(record.failureModes) &&\n\t\tArray.isArray(record.repairsApplied)\n\t);\n}\n\nexport function isToolExecutionFailureLogRecord(value: unknown): value is ToolExecutionFailureLogRecord {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Partial<ToolExecutionFailureLogRecord>;\n\treturn (\n\t\trecord.kind === TOOL_EXECUTION_FAILURE_LOG_KIND &&\n\t\trecord.version === 1 &&\n\t\ttypeof record.recordId === \"string\" &&\n\t\ttypeof record.ts === \"string\" &&\n\t\ttypeof record.sessionId === \"string\" &&\n\t\ttypeof record.tool === \"string\" &&\n\t\t(record.state === \"failed\" || record.state === \"rejected\") &&\n\t\ttypeof record.phase === \"string\" &&\n\t\ttypeof record.failureCode === \"string\" &&\n\t\ttypeof record.nextAction === \"string\"\n\t);\n}\n\n/**\n * Append + rotate under a single exclusive lock on `eventLogPath`. Without the lock, a concurrent\n * writer (e.g. another session's tool-recovery worker) could append between this call's read and its\n * rotated rewrite, and that append would be silently discarded when the rewrite lands. The shared\n * bounded JSONL sink also uses atomic tmp+rename rotation so readers never observe torn log files.\n */\nexport function writeToolRecoveryLogRecord(entry: ToolRecoveryLogWorkerRecord): void {\n\tappendBoundedJsonLineSync(entry.eventLogPath, entry.record, TOOL_RECOVERY_EVENT_LIMITS);\n\tif (entry.record.kind === TOOL_ARGUMENT_VALIDATION_LOG_KIND) {\n\t\ttry {\n\t\t\tupdatePersistedToolRecoveryStats(entry.eventLogPath, entry.record);\n\t\t} catch {\n\t\t\t// The bounded event log remains the recovery source if the cumulative summary cannot be updated.\n\t\t}\n\t\tif (entry.record.outcome !== \"bounced\") return;\n\t\twriteFailureCorpusRecord(\n\t\t\tentry.failureCorpusPath,\n\t\t\tcreateToolValidationFailureCorpusRecord({\n\t\t\t\tts: entry.record.ts,\n\t\t\t\tprovider: entry.record.provider,\n\t\t\t\tmodelId: entry.record.model,\n\t\t\t\ttool: entry.record.tool,\n\t\t\t\tfailureModes: entry.record.failureModes,\n\t\t\t\tshape: copyFailureShape(entry.record.failureShape),\n\t\t\t\terrorKeywords: entry.record.errorKeywords,\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\twriteFailureCorpusRecord(\n\t\tentry.failureCorpusPath,\n\t\tcreateToolExecutionFailureCorpusRecord({\n\t\t\tts: entry.record.ts,\n\t\t\tprovider: entry.record.provider,\n\t\t\tmodelId: entry.record.model,\n\t\t\ttool: entry.record.tool,\n\t\t\tstate: entry.record.state,\n\t\t\tphase: entry.record.phase,\n\t\t\tfailureCode: entry.record.failureCode,\n\t\t\tdiagnostic: entry.record.diagnostic,\n\t\t\tnextAction: entry.record.nextAction,\n\t\t}),\n\t);\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { ToolArgumentValidationTelemetryEvent } from "@caupulican/pi-ai";
2
- import { type ToolArgumentValidationLogRecord } from "./tool-recovery-log-records.ts";
2
+ import type { ToolFailurePhase } from "@caupulican/pi-ai/tool-repair-registry";
3
+ import { type ToolArgumentValidationLogRecord, type ToolExecutionFailureLogRecord } from "./tool-recovery-log-records.ts";
3
4
  export interface ToolRecoveryLoggerStats {
4
5
  enabled: boolean;
5
6
  queued: number;
@@ -9,6 +10,8 @@ export interface ToolRecoveryLoggerStats {
9
10
  workerStarts: number;
10
11
  workerCrashes: number;
11
12
  respawns: number;
13
+ executionFailures: number;
14
+ failurePhases: Partial<Record<ToolFailurePhase, number>>;
12
15
  }
13
16
  export interface ToolRecoveryLoggerOptions {
14
17
  enabled: boolean;
@@ -44,10 +47,18 @@ export declare class ToolRecoveryLogger {
44
47
  private workerStarts;
45
48
  private workerCrashes;
46
49
  private respawns;
50
+ private executionFailures;
51
+ private readonly failurePhases;
47
52
  private respawnAttempted;
48
53
  private shuttingDown;
49
54
  constructor(options: ToolRecoveryLoggerOptions);
50
55
  recordToolArgumentValidation(event: ToolArgumentValidationTelemetryEvent): ToolArgumentValidationLogRecord | undefined;
56
+ recordToolExecutionFailure(args: {
57
+ provider?: string;
58
+ model?: string;
59
+ tool: string;
60
+ details: unknown;
61
+ }): ToolExecutionFailureLogRecord | undefined;
51
62
  getStats(): ToolRecoveryLoggerStats;
52
63
  flush(timeoutMs?: number): Promise<void>;
53
64
  shutdown(timeoutMs?: number): Prom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AC,mBAAmB;IAgB3B,OAAO,CAAC,mBAAmB;IAoB3B,OAAO,CAAC,yBAAyB;CAKjC"}
@@ -1,5 +1,6 @@
1
1
  import { Worker } from "node:worker_threads";
2
- import { createToolArgumentValidationLogRecord, } from "./tool-recovery-log-records.js";
2
+ import { readToolFailureTelemetry } from "@caupulican/pi-agent-core";
3
+ import { createToolArgumentValidationLogRecord, createToolExecutionFailureLogRecord, } from "./tool-recovery-log-records.js";
3
4
  const DEFAULT_MAX_QUEUE = 1000;
4
5
  const DEFAULT_BATCH_SIZE = 50;
5
6
  const DEFAULT_FLUSH_TIMEOUT_MS = 200;
@@ -28,6 +29,8 @@ export class ToolRecoveryLogger {
28
29
  this.workerStarts = 0;
29
30
  this.workerCrashes = 0;
30
31
  this.respawns = 0;
32
+ this.executionFailures = 0;
33
+ this.failurePhases = {};
31
34
  this.respawnAttempted = false;
32
35
  this.shuttingDown = false;
33
36
  this.enabled = options.enabled;
@@ -52,6 +55,24 @@ export class ToolRecoveryLogger {
52
55
  this.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });
53
56
  return record;
54
57
  }
58
+ recordToolExecutionFailure(args) {
59
+ if (!this.enabled)
60
+ return undefined;
61
+ const failure = readToolFailureTelemetry(args.details);
62
+ if (!failure)
63
+ return undefined;
64
+ const record = createToolExecutionFailureLogRecord({
65
+ ...args,
66
+ ...failure,
67
+ recordId: `${this.sessionId}:${this.recordSequence++}`,
68
+ sessionId: this.sessionId,
69
+ ts: this.now().toISOString(),
70
+ });
71
+ this.executionFailures++;
72
+ this.failurePhases[failure.phase] = (this.failurePhases[failure.phase] ?? 0) + 1;
73
+ this.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });
74
+ return record;
75
+ }
55
76
  getStats() {
56
77
  return {
57
78
  enabled: this.enabled,
@@ -62,6 +83,8 @@ export class ToolRecoveryLogger {
62
83
  workerStarts: this.workerStarts,
63
84
  workerCrashes: this.workerCrashes,
64
85
  respawns: this.respawns,
86
+ executionFailures: this.executionFailures,
87
+ failurePhases: { ...this.failurePhases },
65
88
  };
66
89
  }
67
90
  flush(timeoutMs = DEFAULT_FLUSH_TIMEOUT_MS) {
@@ -1 +1 @@
1
- {"version":3,"file":"tool-recovery-logger.js","sourceRoot":"","sources":["../../src/core/tool-recovery-logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EACN,qCAAqC,GAGrC,MAAM,gCAAgC,CAAC;AAgCxC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC,SAAS,2BAA2B,CAAC,KAAc;IAClD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,OAAO,GAAG,KAA2C,CAAC;IAC5D,OAAO,CACN,OAAO,CAAC,IAAI,KAAK,KAAK;QACtB,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QACnC,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QACnC,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,CAClC,CAAC;AACH,CAAC;AAED,SAAS,4BAA4B;IACpC,MAAM,mBAAmB,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5D,OAAO,IAAI,GAAG,CACb,mBAAmB,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,+BAA+B,EACvF,OAAO,IAAI,CAAC,GAAG,CACf,CAAC;AACH,CAAC;AAED,MAAM,OAAO,kBAAkB;IA0B9B,YAAY,OAAkC;QAhB7B,UAAK,GAAkC,EAAE,CAAC;QAC1C,iBAAY,GAAsB,EAAE,CAAC;QAE9C,aAAQ,GAAkC,EAAE,CAAC;QAG7C,YAAO,GAAG,CAAC,C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yBAAyB,EAAE,CAAC;IAClC,CAAC;IAEO,yBAAyB;QAChC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO;QAC9D,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,EAAE,CAAC;IACxC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport {\n\tcreateToolArgumentValidationLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n\ttype ToolRecoveryLogWorkerRecord,\n} from \"./tool-recovery-log-records.ts\";\n\ninterface ToolRecoveryLogAckMessage {\n\ttype: \"ack\";\n\tbatchId: number;\n\twritten: number;\n\tfailed: number;\n}\n\nexport interface ToolRecoveryLoggerStats {\n\tenabled: boolean;\n\tqueued: number;\n\tinFlight: number;\n\tdropped: number;\n\tfailures: number;\n\tworkerStarts: number;\n\tworkerCrashes: number;\n\trespawns: number;\n}\n\nexport interface ToolRecoveryLoggerOptions {\n\tenabled: boolean;\n\tsessionId: string;\n\teventLogPath: string;\n\tfailureCorpusPath: string;\n\tmaxQueue?: number;\n\tbatchSize?: number;\n\tnow?: () => Date;\n\tdebug?: (message: string) => void;\n\tworkerSpecifier?: string | URL;\n}\n\nconst DEFAULT_MAX_QUEUE = 1000;\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_FLUSH_TIMEOUT_MS = 200;\n\nfunction isToolRecoveryLogAckMessage(value: unknown): value is ToolRecoveryLogAckMessage {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst message = value as Partial<ToolRecoveryLogAckMessage>;\n\treturn (\n\t\tmessage.type === \"ack\" &&\n\t\ttypeof message.batchId === \"number\" &&\n\t\ttypeof message.written === \"number\" &&\n\t\ttypeof message.failed === \"number\"\n\t);\n}\n\nfunction createDefaultWorkerSpecifier(): URL {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\treturn new URL(\n\t\tisTypeScriptRuntime ? \"./tool-recovery-log-worker.ts\" : \"./tool-recovery-log-worker.js\",\n\t\timport.meta.url,\n\t);\n}\n\nexport class ToolRecoveryLogger {\n\tprivate readonly enabled: boolean;\n\tprivate readonly sessionId: string;\n\tprivate readonly eventLogPath: string;\n\tprivate readonly failureCorpusPath: string;\n\tprivate readonly maxQueue: number;\n\tprivate readonly batchSize: number;\n\tprivate readonly now: () => Date;\n\tprivate readonly debug: (message: string) => void;\n\tprivate readonly workerSpecifier: string | URL;\n\tprivate readonly queue: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate readonly flushWaiters: Array<() => void> = [];\n\tprivate worker: Worker | undefined;\n\tprivate inFlight: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate inFlightBatchId: number | undefined;\n\tprivate inFlightWorker: Worker | undefined;\n\tprivate batchId = 0;\n\tprivate recordSequence = 0;\n\tprivate dropped = 0;\n\tprivate failures = 0;\n\tprivate workerStarts = 0;\n\tprivate workerCrashes = 0;\n\tprivate respawns = 0;\n\tprivate respawnAttempted = false;\n\tprivate shuttingDown = false;\n\n\tconstructor(options: ToolRecoveryLoggerOptions) {\n\t\tthis.enabled = options.enabled;\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.eventLogPath = options.eventLogPath;\n\t\tthis.failureCorpusPath = options.failureCorpusPath;\n\t\tthis.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;\n\t\tthis.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.debug = options.debug ?? (() => {});\n\t\tthis.workerSpecifier = options.workerSpecifier ?? createDefaultWorkerSpecifier();\n\t}\n\n\trecordToolArgumentValidation(\n\t\tevent: ToolArgumentValidationTelemetryEvent,\n\t): ToolArgumentValidationLogRecord | undefined {\n\t\tif (!this.enabled || event.outcome === \"clean\") return undefined;\n\t\tconst record = createToolArgumentValidationLogRecord({\n\t\t\tevent,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\tgetStats(): ToolRecoveryLoggerStats {\n\t\treturn {\n\t\t\tenabled: this.enabled,\n\t\t\tqueued: this.queue.length,\n\t\t\tinFlight: this.inFlight.length,\n\t\t\tdropped: this.dropped,\n\t\t\tfailures: this.failures,\n\t\t\tworkerStarts: this.workerStarts,\n\t\t\tworkerCrashes: this.workerCrashes,\n\t\t\trespawns: this.respawns,\n\t\t};\n\t}\n\n\tflush(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tif (!this.enabled || (!this.worker && this.queue.length === 0 && this.inFlight.length === 0)) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tthis.pump();\n\t\treturn new Promise((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tlet timeout: NodeJS.Timeout;\n\t\t\tconst finish = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst waiter = (): void => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tfinish();\n\t\t\t};\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tconst index = this.flushWaiters.indexOf(waiter);\n\t\t\t\tif (index !== -1) this.flushWaiters.splice(index, 1);\n\t\t\t\tfinish();\n\t\t\t}, timeoutMs);\n\t\t\tthis.flushWaiters.push(waiter);\n\t\t\tthis.resolveFlushWaitersIfIdle();\n\t\t});\n\t}\n\n\tasync shutdown(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tawait this.flush(timeoutMs);\n\t\tthis.shuttingDown = true;\n\t\tconst worker = this.worker;\n\t\tthis.worker = undefined;\n\t\tif (!worker) return;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"shutdown\" });\n\t\t} catch {}\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n\n\tprivate enqueue(record: ToolRecoveryLogWorkerRecord): void {\n\t\tif (!this.enabled) return;\n\t\tthis.queue.push(record);\n\t\twhile (this.queue.length > this.maxQueue) {\n\t\t\tthis.queue.shift();\n\t\t\tthis.dropped++;\n\t\t}\n\t\tthis.pump();\n\t}\n\n\tprivate pump(): void {\n\t\tif (!this.enabled || this.shuttingDown || this.inFlight.length > 0 || this.queue.length === 0) return;\n\t\tconst worker = this.ensureWorker();\n\t\tif (!worker) return;\n\t\tconst records = this.queue.splice(0, this.batchSize);\n\t\tthis.inFlight = records;\n\t\tconst batchId = this.batchId++;\n\t\tthis.inFlightBatchId = batchId;\n\t\tthis.inFlightWorker = worker;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"records\", batchId, records });\n\t\t} catch (error) {\n\t\t\tthis.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.handleWorkerFailure(worker, error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n\n\tprivate ensureWorker(): Worker | undefined {\n\t\tif (this.worker) return this.worker;\n\t\ttry {\n\t\t\tconst worker = new Worker(this.workerSpecifier);\n\t\t\tworker.unref();\n\t\t\tthis.worker = worker;\n\t\t\tthis.workerStarts++;\n\t\t\tworker.on(\"message\", (message: unknown) => this.handleWorkerMessage(worker, message));\n\t\t\tworker.on(\"error\", (error) => this.handleWorkerFailure(worker, error));\n\t\t\tworker.on(\"exit\", (code) => {\n\t\t\t\tif (this.shuttingDown || this.worker !== worker) return;\n\t\t\t\tthis.handleWorkerFailure(worker, new Error(`tool recovery logger worker exited with code ${code}`));\n\t\t\t});\n\t\t\treturn worker;\n\t\t} catch (error) {\n\t\t\tthis.failures++;\n\t\t\tthis.debug(\n\t\t\t\t`tool recovery logger worker start failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate handleWorkerMessage(worker: Worker, message: unknown): void {\n\t\tif (!isToolRecoveryLogAckMessage(message)) return;\n\t\tif (this.worker !== worker || this.inFlightWorker !== worker || this.inFlightBatchId !== message.batchId) {\n\t\t\treturn;\n\t\t}\n\t\tif (message.failed > 0) {\n\t\t\tthis.failures += message.failed;\n\t\t}\n\t\tthis.inFlight = [];\n\t\tthis.inFlightBatchId = undefined;\n\t\tthis.inFlightWorker = undefined;\n\t\tthis.respawnAttempted = false;\n\t\tthis.pump();\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate handleWorkerFailure(worker: Worker, error: Error): void {\n\t\tif (this.worker !== worker) return;\n\t\tthis.failures++;\n\t\tthis.workerCrashes++;\n\t\tif (this.inFlightWorker === worker) {\n\t\t\tthis.dropped += this.inFlight.length;\n\t\t\tthis.inFlight = [];\n\t\t\tthis.inFlightBatchId = undefined;\n\t\t\tthis.inFlightWorker = undefined;\n\t\t}\n\t\tthis.worker = undefined;\n\t\tthis.debug(`tool recovery logger worker failed: ${error.message}`);\n\t\tif (!this.respawnAttempted && !this.shuttingDown) {\n\t\t\tthis.respawnAttempted = true;\n\t\t\tthis.respawns++;\n\t\t\tthis.pump();\n\t\t}\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate resolveFlushWaitersIfIdle(): void {\n\t\tif (this.queue.length > 0 || this.inFlight.length > 0) return;\n\t\tconst waiters = this.flushWaiters.splice(0);\n\t\tfor (const waiter of waiters) waiter();\n\t}\n}\n"]}
1
+ {"version":3,"file":"tool-recovery-logger.js","sourceRoot":"","sources":["../../src/core/tool-recovery-logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B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,IAAI,IAAI,CAAC,MAAM,KAAK,MAAM;YAAE,OAAO;QACnC,IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,cAAc,KAAK,MAAM,EAAE,CAAC;YACpC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;YACrC,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;YACnB,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;YACjC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QACjC,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,KAAK,CAAC,uCAAuC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACnE,IAAI,CAAC,IAAI,CAAC,gBAAgB,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YAClD,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAC7B,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,IAAI,CAAC,IAAI,EAAE,CAAC;QACb,CAAC;QACD,IAAI,CAAC,yBAAyB,EAAE,CAAC;IAClC,CAAC;IAEO,yBAAyB;QAChC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO;QAC9D,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,EAAE,CAAC;IACxC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { readToolFailureTelemetry } from \"@caupulican/pi-agent-core\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport type { ToolFailurePhase } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport {\n\tcreateToolArgumentValidationLogRecord,\n\tcreateToolExecutionFailureLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n\ttype ToolExecutionFailureLogRecord,\n\ttype ToolRecoveryLogWorkerRecord,\n} from \"./tool-recovery-log-records.ts\";\n\ninterface ToolRecoveryLogAckMessage {\n\ttype: \"ack\";\n\tbatchId: number;\n\twritten: number;\n\tfailed: number;\n}\n\nexport interface ToolRecoveryLoggerStats {\n\tenabled: boolean;\n\tqueued: number;\n\tinFlight: number;\n\tdropped: number;\n\tfailures: number;\n\tworkerStarts: number;\n\tworkerCrashes: number;\n\trespawns: number;\n\texecutionFailures: number;\n\tfailurePhases: Partial<Record<ToolFailurePhase, number>>;\n}\n\nexport interface ToolRecoveryLoggerOptions {\n\tenabled: boolean;\n\tsessionId: string;\n\teventLogPath: string;\n\tfailureCorpusPath: string;\n\tmaxQueue?: number;\n\tbatchSize?: number;\n\tnow?: () => Date;\n\tdebug?: (message: string) => void;\n\tworkerSpecifier?: string | URL;\n}\n\nconst DEFAULT_MAX_QUEUE = 1000;\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_FLUSH_TIMEOUT_MS = 200;\n\nfunction isToolRecoveryLogAckMessage(value: unknown): value is ToolRecoveryLogAckMessage {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst message = value as Partial<ToolRecoveryLogAckMessage>;\n\treturn (\n\t\tmessage.type === \"ack\" &&\n\t\ttypeof message.batchId === \"number\" &&\n\t\ttypeof message.written === \"number\" &&\n\t\ttypeof message.failed === \"number\"\n\t);\n}\n\nfunction createDefaultWorkerSpecifier(): URL {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\treturn new URL(\n\t\tisTypeScriptRuntime ? \"./tool-recovery-log-worker.ts\" : \"./tool-recovery-log-worker.js\",\n\t\timport.meta.url,\n\t);\n}\n\nexport class ToolRecoveryLogger {\n\tprivate readonly enabled: boolean;\n\tprivate readonly sessionId: string;\n\tprivate readonly eventLogPath: string;\n\tprivate readonly failureCorpusPath: string;\n\tprivate readonly maxQueue: number;\n\tprivate readonly batchSize: number;\n\tprivate readonly now: () => Date;\n\tprivate readonly debug: (message: string) => void;\n\tprivate readonly workerSpecifier: string | URL;\n\tprivate readonly queue: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate readonly flushWaiters: Array<() => void> = [];\n\tprivate worker: Worker | undefined;\n\tprivate inFlight: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate inFlightBatchId: number | undefined;\n\tprivate inFlightWorker: Worker | undefined;\n\tprivate batchId = 0;\n\tprivate recordSequence = 0;\n\tprivate dropped = 0;\n\tprivate failures = 0;\n\tprivate workerStarts = 0;\n\tprivate workerCrashes = 0;\n\tprivate respawns = 0;\n\tprivate executionFailures = 0;\n\tprivate readonly failurePhases: Partial<Record<ToolFailurePhase, number>> = {};\n\tprivate respawnAttempted = false;\n\tprivate shuttingDown = false;\n\n\tconstructor(options: ToolRecoveryLoggerOptions) {\n\t\tthis.enabled = options.enabled;\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.eventLogPath = options.eventLogPath;\n\t\tthis.failureCorpusPath = options.failureCorpusPath;\n\t\tthis.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;\n\t\tthis.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.debug = options.debug ?? (() => {});\n\t\tthis.workerSpecifier = options.workerSpecifier ?? createDefaultWorkerSpecifier();\n\t}\n\n\trecordToolArgumentValidation(\n\t\tevent: ToolArgumentValidationTelemetryEvent,\n\t): ToolArgumentValidationLogRecord | undefined {\n\t\tif (!this.enabled || event.outcome === \"clean\") return undefined;\n\t\tconst record = createToolArgumentValidationLogRecord({\n\t\t\tevent,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\trecordToolExecutionFailure(args: {\n\t\tprovider?: string;\n\t\tmodel?: string;\n\t\ttool: string;\n\t\tdetails: unknown;\n\t}): ToolExecutionFailureLogRecord | undefined {\n\t\tif (!this.enabled) return undefined;\n\t\tconst failure = readToolFailureTelemetry(args.details);\n\t\tif (!failure) return undefined;\n\t\tconst record = createToolExecutionFailureLogRecord({\n\t\t\t...args,\n\t\t\t...failure,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.executionFailures++;\n\t\tthis.failurePhases[failure.phase] = (this.failurePhases[failure.phase] ?? 0) + 1;\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\tgetStats(): ToolRecoveryLoggerStats {\n\t\treturn {\n\t\t\tenabled: this.enabled,\n\t\t\tqueued: this.queue.length,\n\t\t\tinFlight: this.inFlight.length,\n\t\t\tdropped: this.dropped,\n\t\t\tfailures: this.failures,\n\t\t\tworkerStarts: this.workerStarts,\n\t\t\tworkerCrashes: this.workerCrashes,\n\t\t\trespawns: this.respawns,\n\t\t\texecutionFailures: this.executionFailures,\n\t\t\tfailurePhases: { ...this.failurePhases },\n\t\t};\n\t}\n\n\tflush(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tif (!this.enabled || (!this.worker && this.queue.length === 0 && this.inFlight.length === 0)) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tthis.pump();\n\t\treturn new Promise((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tlet timeout: NodeJS.Timeout;\n\t\t\tconst finish = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst waiter = (): void => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tfinish();\n\t\t\t};\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tconst index = this.flushWaiters.indexOf(waiter);\n\t\t\t\tif (index !== -1) this.flushWaiters.splice(index, 1);\n\t\t\t\tfinish();\n\t\t\t}, timeoutMs);\n\t\t\tthis.flushWaiters.push(waiter);\n\t\t\tthis.resolveFlushWaitersIfIdle();\n\t\t});\n\t}\n\n\tasync shutdown(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tawait this.flush(timeoutMs);\n\t\tthis.shuttingDown = true;\n\t\tconst worker = this.worker;\n\t\tthis.worker = undefined;\n\t\tif (!worker) return;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"shutdown\" });\n\t\t} catch {}\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n\n\tprivate enqueue(record: ToolRecoveryLogWorkerRecord): void {\n\t\tif (!this.enabled) return;\n\t\tthis.queue.push(record);\n\t\twhile (this.queue.length > this.maxQueue) {\n\t\t\tthis.queue.shift();\n\t\t\tthis.dropped++;\n\t\t}\n\t\tthis.pump();\n\t}\n\n\tprivate pump(): void {\n\t\tif (!this.enabled || this.shuttingDown || this.inFlight.length > 0 || this.queue.length === 0) return;\n\t\tconst worker = this.ensureWorker();\n\t\tif (!worker) return;\n\t\tconst records = this.queue.splice(0, this.batchSize);\n\t\tthis.inFlight = records;\n\t\tconst batchId = this.batchId++;\n\t\tthis.inFlightBatchId = batchId;\n\t\tthis.inFlightWorker = worker;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"records\", batchId, records });\n\t\t} catch (error) {\n\t\t\tthis.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.handleWorkerFailure(worker, error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n\n\tprivate ensureWorker(): Worker | undefined {\n\t\tif (this.worker) return this.worker;\n\t\ttry {\n\t\t\tconst worker = new Worker(this.workerSpecifier);\n\t\t\tworker.unref();\n\t\t\tthis.worker = worker;\n\t\t\tthis.workerStarts++;\n\t\t\tworker.on(\"message\", (message: unknown) => this.handleWorkerMessage(worker, message));\n\t\t\tworker.on(\"error\", (error) => this.handleWorkerFailure(worker, error));\n\t\t\tworker.on(\"exit\", (code) => {\n\t\t\t\tif (this.shuttingDown || this.worker !== worker) return;\n\t\t\t\tthis.handleWorkerFailure(worker, new Error(`tool recovery logger worker exited with code ${code}`));\n\t\t\t});\n\t\t\treturn worker;\n\t\t} catch (error) {\n\t\t\tthis.failures++;\n\t\t\tthis.debug(\n\t\t\t\t`tool recovery logger worker start failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate handleWorkerMessage(worker: Worker, message: unknown): void {\n\t\tif (!isToolRecoveryLogAckMessage(message)) return;\n\t\tif (this.worker !== worker || this.inFlightWorker !== worker || this.inFlightBatchId !== message.batchId) {\n\t\t\treturn;\n\t\t}\n\t\tif (message.failed > 0) {\n\t\t\tthis.failures += message.failed;\n\t\t}\n\t\tthis.inFlight = [];\n\t\tthis.inFlightBatchId = undefined;\n\t\tthis.inFlightWorker = undefined;\n\t\tthis.respawnAttempted = false;\n\t\tthis.pump();\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate handleWorkerFailure(worker: Worker, error: Error): void {\n\t\tif (this.worker !== worker) return;\n\t\tthis.failures++;\n\t\tthis.workerCrashes++;\n\t\tif (this.inFlightWorker === worker) {\n\t\t\tthis.dropped += this.inFlight.length;\n\t\t\tthis.inFlight = [];\n\t\t\tthis.inFlightBatchId = undefined;\n\t\t\tthis.inFlightWorker = undefined;\n\t\t}\n\t\tthis.worker = undefined;\n\t\tthis.debug(`tool recovery logger worker failed: ${error.message}`);\n\t\tif (!this.respawnAttempted && !this.shuttingDown) {\n\t\t\tthis.respawnAttempted = true;\n\t\t\tthis.respawns++;\n\t\t\tthis.pump();\n\t\t}\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate resolveFlushWaitersIfIdle(): void {\n\t\tif (this.queue.length > 0 || this.inFlight.length > 0) return;\n\t\tconst waiters = this.flushWaiters.splice(0);\n\t\tfor (const waiter of waiters) waiter();\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-repair-health.d.ts","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAyB,MAAM,8BAA8B,CAAC;AAChG,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAoBzE,wBAAgB,4BAA4B,CAC3C,KAAK,EAAE,oBAAoB,EAC3B,GAAG,GAAE,IAAiB,EACtB,WAAW,CAAC,EAAE,uBAAuB,GACnC,MAAM,CAwDR"}
1
+ {"version":3,"file":"tool-repair-health.d.ts","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAyB,MAAM,8BAA8B,CAAC;AAChG,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AA0BzE,wBAAgB,4BAA4B,CAC3C,KAAK,EAAE,oBAAoB,EAC3B,GAAG,GAAE,IAAiB,EACtB,WAAW,CAAC,EAAE,uBAAuB,GACnC,MAAM,CAwDR"}
@@ -12,8 +12,14 @@ function sortProfiles(profiles) {
12
12
  function formatLoggerStats(stats) {
13
13
  if (!stats)
14
14
  return [];
15
+ const phaseCounts = Object.entries(stats.failurePhases)
16
+ .filter((entry) => entry[1] !== undefined && entry[1] > 0)
17
+ .sort(([left], [right]) => left.localeCompare(right))
18
+ .map(([phase, count]) => `${phase}=${count}`)
19
+ .join(" ");
15
20
  return [
16
21
  `recovery logging: ${stats.enabled ? "enabled" : "disabled"} queued=${stats.queued} inFlight=${stats.inFlight} dropped=${stats.dropped} failures=${stats.failures} workerStarts=${stats.workerStarts} crashes=${stats.workerCrashes} respawns=${stats.respawns}`,
22
+ `execution failures: total=${stats.executionFailures}${phaseCounts ? ` ${phaseCounts}` : ""}`,
17
23
  ];
18
24
  }
19
25
  export function formatToolRepairHealthReport(store, now = new Date(), loggerStats) {
@@ -1 +1 @@
1
- {"version":3,"file":"tool-repair-health.js","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAI1B,SAAS,aAAa,CAAC,GAAW,EAAE,GAAS;IAC5C,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,aAAa,CAAC;IAC/C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACnF,OAAO,GAAG,IAAI,OAAO,CAAC;AACvB,CAAC;AAED,SAAS,YAAY,CAAC,QAAiC;IACtD,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,iBAAiB,CAAC,KAA0C;IACpE,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,OAAO;QACN,qBAAqB,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU,WAAW,KAAK,CAAC,MAAM,aAAa,KAAK,CAAC,QAAQ,YAAY,KAAK,CAAC,OAAO,aAAa,KAAK,CAAC,QAAQ,iBAAiB,KAAK,CAAC,YAAY,YAAY,KAAK,CAAC,aAAa,aA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AC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;gBACxG,KAAK,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1F,CAAC;QACF,CAAC;QACD,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,EAAE,CACtF,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CACzB,CAAC;QACF,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACnC,CAAC;aAAM,CAAC;YACP,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YAC7B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,YAAY,EAAE,CAAC;gBAC1C,KAAK,CAAC,IAAI,CACT,SAAS,IAAI,YAAY,KAAK,CAAC,MAAM,WAAW,KAAK,CAAC,gBAAgB,UAAU,KAAK,CAAC,eAAe,EAAE,CACvG,CAAC;YACH,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import chalk from \"chalk\";\nimport type { ModelAdaptationStore, StoredModelAdaptation } from \"./models/adaptation-store.ts\";\nimport type { ToolRecoveryLoggerStats } from \"./tool-recovery-logger.ts\";\n\nfunction formatAgeDays(iso: string, now: Date): string {\n\tconst ms = Date.parse(iso);\n\tif (!Number.isFinite(ms)) return \"age unknown\";\n\tconst days = Math.max(0, Math.floor((now.getTime() - ms) / (24 * 60 * 60 * 1000)));\n\treturn `${days}d ago`;\n}\n\nfunction sortProfiles(profiles: StoredModelAdaptation[]): StoredModelAdaptation[] {\n\treturn [...profiles].sort((left, right) => left.model.localeCompare(right.model));\n}\n\nfunction formatLoggerStats(stats: ToolRecoveryLoggerStats | undefined): string[] {\n\tif (!stats) return [];\n\treturn [\n\t\t`recovery logging: ${stats.enabled ? \"enabled\" : \"disabled\"} queued=${stats.queued} inFlight=${stats.inFlight} dropped=${stats.dropped} failures=${stats.failures} workerStarts=${stats.workerStarts} crashes=${stats.workerCrashes} respawns=${stats.respawns}`,\n\t];\n}\n\nexport function formatToolRepairHealthReport(\n\tstore: ModelAdaptationStore,\n\tnow: Date = new Date(),\n\tloggerStats?: ToolRecoveryLoggerStats,\n): string {\n\tconst profiles = sortProfiles(store.getForHost());\n\tif (profiles.length === 0) {\n\t\tconst loggerLines = formatLoggerStats(loggerStats);\n\t\treturn [\"Tool repair health: no model adaptation records for this host.\", ...loggerLines].join(\"\\n\");\n\t}\n\n\tconst lines = [chalk.bold(\"Tool repair health\"), ...formatLoggerStats(loggerStats)];\n\tfor (const entry of profiles) {\n\t\tlines.push(`${entry.model}`);\n\t\tconst toolProbe = entry.profile.toolProbe;\n\t\tif (!toolProbe) {\n\t\t\tlines.push(\" tool probe: none\");\n\t\t} else {\n\t\t\tconst variant = toolProbe.variant ? ` (${toolProbe.variant})` : \"\";\n\t\t\tconst nativeGrade = toolProbe.nativeGrade ? ` native=${toolProbe.nativeGrade}` : \"\";\n\t\t\tlines.push(\n\t\t\t\t` tool probe: v${toolProbe.version} ${toolProbe.status}${variant}${nativeGrade} ${formatAgeDays(toolProbe.probedAt, now)}`,\n\t\t\t);\n\t\t\tif (toolProbe.diagnostic) lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);\n\t\t}\n\t\tconst protocol = entry.profile.protocol;\n\t\tif (!protocol) {\n\t\t\tlines.push(\" protocol: none\");\n\t\t} else if (protocol.status === \"failed\") {\n\t\t\tlines.push(` protocol: v${protocol.version} failed ${formatAgeDays(protocol.attemptedAt, now)}`);\n\t\t\tlines.push(` variants tried: ${protocol.variantsTried.join(\", \")}`);\n\t\t\tlines.push(` reset: /toolprotocol-reset ${entry.model}`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t` protocol: v${protocol.version} ${protocol.variant} calibrated ${formatAgeDays(protocol.calibratedAt, now)}`,\n\t\t\t);\n\t\t}\n\t\tif (entry.profile.rules.length === 0) {\n\t\t\tlines.push(\" rules: none\");\n\t\t} else {\n\t\t\tlines.push(\" rules:\");\n\t\t\tfor (const rule of [...entry.profile.rules].sort((left, right) => left.mode.localeCompare(right.mode))) {\n\t\t\t\tlines.push(` - ${rule.mode} (${formatAgeDays(rule.lastFiredAt, now)}): ${rule.text}`);\n\t\t\t}\n\t\t}\n\t\tconst teachEntries = Object.entries(entry.profile.teachStats).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t);\n\t\tif (teachEntries.length === 0) {\n\t\t\tlines.push(\" teach stats: none\");\n\t\t} else {\n\t\t\tlines.push(\" teach stats:\");\n\t\t\tfor (const [mode, stats] of teachEntries) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` - ${mode}: taught=${stats.taught} before=${stats.recurrenceBefore} after=${stats.recurrenceAfter}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"tool-repair-health.js","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAI1B,SAAS,aAAa,CAAC,GAAW,EAAE,GAAS;IAC5C,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,aAAa,CAAC;IAC/C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,EA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AAE,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;gBACxG,KAAK,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1F,CAAC;QACF,CAAC;QACD,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,EAAE,CACtF,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CACzB,CAAC;QACF,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACnC,CAAC;aAAM,CAAC;YACP,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YAC7B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,YAAY,EAAE,CAAC;gBAC1C,KAAK,CAAC,IAAI,CACT,SAAS,IAAI,YAAY,KAAK,CAAC,MAAM,WAAW,KAAK,CAAC,gBAAgB,UAAU,KAAK,CAAC,eAAe,EAAE,CACvG,CAAC;YACH,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import chalk from \"chalk\";\nimport type { ModelAdaptationStore, StoredModelAdaptation } from \"./models/adaptation-store.ts\";\nimport type { ToolRecoveryLoggerStats } from \"./tool-recovery-logger.ts\";\n\nfunction formatAgeDays(iso: string, now: Date): string {\n\tconst ms = Date.parse(iso);\n\tif (!Number.isFinite(ms)) return \"age unknown\";\n\tconst days = Math.max(0, Math.floor((now.getTime() - ms) / (24 * 60 * 60 * 1000)));\n\treturn `${days}d ago`;\n}\n\nfunction sortProfiles(profiles: StoredModelAdaptation[]): StoredModelAdaptation[] {\n\treturn [...profiles].sort((left, right) => left.model.localeCompare(right.model));\n}\n\nfunction formatLoggerStats(stats: ToolRecoveryLoggerStats | undefined): string[] {\n\tif (!stats) return [];\n\tconst phaseCounts = Object.entries(stats.failurePhases)\n\t\t.filter((entry): entry is [string, number] => entry[1] !== undefined && entry[1] > 0)\n\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t.map(([phase, count]) => `${phase}=${count}`)\n\t\t.join(\" \");\n\treturn [\n\t\t`recovery logging: ${stats.enabled ? \"enabled\" : \"disabled\"} queued=${stats.queued} inFlight=${stats.inFlight} dropped=${stats.dropped} failures=${stats.failures} workerStarts=${stats.workerStarts} crashes=${stats.workerCrashes} respawns=${stats.respawns}`,\n\t\t`execution failures: total=${stats.executionFailures}${phaseCounts ? ` ${phaseCounts}` : \"\"}`,\n\t];\n}\n\nexport function formatToolRepairHealthReport(\n\tstore: ModelAdaptationStore,\n\tnow: Date = new Date(),\n\tloggerStats?: ToolRecoveryLoggerStats,\n): string {\n\tconst profiles = sortProfiles(store.getForHost());\n\tif (profiles.length === 0) {\n\t\tconst loggerLines = formatLoggerStats(loggerStats);\n\t\treturn [\"Tool repair health: no model adaptation records for this host.\", ...loggerLines].join(\"\\n\");\n\t}\n\n\tconst lines = [chalk.bold(\"Tool repair health\"), ...formatLoggerStats(loggerStats)];\n\tfor (const entry of profiles) {\n\t\tlines.push(`${entry.model}`);\n\t\tconst toolProbe = entry.profile.toolProbe;\n\t\tif (!toolProbe) {\n\t\t\tlines.push(\" tool probe: none\");\n\t\t} else {\n\t\t\tconst variant = toolProbe.variant ? ` (${toolProbe.variant})` : \"\";\n\t\t\tconst nativeGrade = toolProbe.nativeGrade ? ` native=${toolProbe.nativeGrade}` : \"\";\n\t\t\tlines.push(\n\t\t\t\t` tool probe: v${toolProbe.version} ${toolProbe.status}${variant}${nativeGrade} ${formatAgeDays(toolProbe.probedAt, now)}`,\n\t\t\t);\n\t\t\tif (toolProbe.diagnostic) lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);\n\t\t}\n\t\tconst protocol = entry.profile.protocol;\n\t\tif (!protocol) {\n\t\t\tlines.push(\" protocol: none\");\n\t\t} else if (protocol.status === \"failed\") {\n\t\t\tlines.push(` protocol: v${protocol.version} failed ${formatAgeDays(protocol.attemptedAt, now)}`);\n\t\t\tlines.push(` variants tried: ${protocol.variantsTried.join(\", \")}`);\n\t\t\tlines.push(` reset: /toolprotocol-reset ${entry.model}`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t` protocol: v${protocol.version} ${protocol.variant} calibrated ${formatAgeDays(protocol.calibratedAt, now)}`,\n\t\t\t);\n\t\t}\n\t\tif (entry.profile.rules.length === 0) {\n\t\t\tlines.push(\" rules: none\");\n\t\t} else {\n\t\t\tlines.push(\" rules:\");\n\t\t\tfor (const rule of [...entry.profile.rules].sort((left, right) => left.mode.localeCompare(right.mode))) {\n\t\t\t\tlines.push(` - ${rule.mode} (${formatAgeDays(rule.lastFiredAt, now)}): ${rule.text}`);\n\t\t\t}\n\t\t}\n\t\tconst teachEntries = Object.entries(entry.profile.teachStats).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t);\n\t\tif (teachEntries.length === 0) {\n\t\t\tlines.push(\" teach stats: none\");\n\t\t} else {\n\t\t\tlines.push(\" teach stats:\");\n\t\t\tfor (const [mode, stats] of teachEntries) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` - ${mode}: taught=${stats.taught} before=${stats.recurrenceBefore} after=${stats.recurrenceAfter}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -72,7 +72,7 @@ export declare function createLocalPlatformShellOperations(options?: {
72
72
  commandPrefix?: string;
73
73
  operations?: BashOperations;
74
74
  sessionKey?: string;
75
- /** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */
75
+ /** Route complex/state-mutating Bash constructs and portable builtins to the Python engine on Windows. Default: true. */
76
76
  pythonEngine?: boolean;
77
77
  /** Test/embedding hook: overrides the engine tier's runtime/spawn/state resolution. */
78
78
  engineOptions?: WindowsShellEngineOptions;
@@ -100,7 +100,7 @@ export interface BashToolOptions {
100
100
  * tool instances (subagents) auto-generate their own key and stay isolated.
101
101
  */
102
102
  sessionKey?: string;
103
- /** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */
103
+ /** Route complex/state-mutating Bash constructs and portable builtins to the Python engine on Windows. Default: true. */
104
104
  windowsShellPythonEngine?: boolean;
105
105
  /** Test/embedding hook: overrides the engine tier's runtime/spawn/state resolution. */
106
106
  windowsShellEngineOptions?: WindowsShellEngineOptions;
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,SAAS,EAAyB,MAAM,2BAA2B,CAAC;AAClF,OAAO,EAIN,KAAK,gBAAgB,EACrB,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAc5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAOtF,OAAO,EAGN,KAAK,4BAA4B,EACjC,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAsC,KAAK,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAK/G,qGAAqG;AACrG,eAAO,MAAM,+BAA+B,MAAM,CAAC;AACnD,eAAO,MAAM,2BAA2B,OAAO,CAAC;AAKhD,kGAAkG;AAClG,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAExE;AAED,mGAAmG;AACnG,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAExE;AAED,wBAAgB,4BAA4B,CAAC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AuChB;AAED,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;CACvB;AAED,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,gBAAgB,KAAK,gBAAgB,CAAC;AAO5E,MAAM,WAAW,eAAe;IAC/B,qGAAqG;IACrG,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,6EAA6E;IAC7E,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yHAAyH;IACzH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,uFAAuF;IACvF,yBAAyB,CAAC,EAAE,yBAAyB,CAAC;IACtD,4FAA4F;IAC5F,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAggBD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAGhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG"}
@@ -315,7 +315,7 @@ function createShellToolDefinition(cwd, backendShell, contractPlatform, options)
315
315
  ? createWindowsShellEngineOperations(sessionKey, options?.windowsShellEngineOptions)
316
316
  : undefined;
317
317
  const contractDescription = routesWindowsContract
318
- ? "Execute Pi's stable Bash-like command contract in a persistent per-agent shell session (current directory and environment variables persist across calls, including across the PowerShell and Python engine tiers). On Windows, a deterministic router converts simple commands directly to PowerShell and routes pipelines, redirection, expansion, chaining, and state-mutating commands (cd/export/unset) through a bundled Python engine that implements the supported Bash grammar; named unsupported constructs (job control, process substitution, heredocs, nested shells, and similar) fail closed instead of being guessed."
318
+ ? "Execute Pi's stable Bash-like command contract in a persistent per-agent shell session (current directory and environment variables persist across calls, including across the PowerShell and Python engine tiers). On Windows, a deterministic router converts simple commands directly to PowerShell and routes word-list and arithmetic for loops, break/continue, portable builtins such as printf, pipelines, redirection, expansion, chaining, and state-mutating commands (cd/export/unset) through a bundled Python engine that implements the supported Bash grammar; named unsupported constructs (job control, process substitution, heredocs, nested shells, and similar) fail closed instead of being guessed."
319
319
  : "Execute a Bash command in a persistent per-agent shell session: the current directory and environment variables persist across calls, and a timed-out or aborted command resets the session.";
320
320
  return {
321
321
  name: toolName,
@@ -327,7 +327,7 @@ function createShellToolDefinition(cwd, backendShell, contractPlatform, options)
327
327
  promptGuidelines: routesWindowsContract
328
328
  ? [
329
329
  "Use ordinary Bash-like commands on Windows; do not write PowerShell or ask the user to choose a shell.",
330
- "Pipelines, redirection, expansion (variables, command substitution, globs), chaining (&&/||/;), and cd/export/unset are supported and routed to a bundled Python engine; a fixed set of named constructs (job control, process substitution, heredocs, arithmetic expansion, nested shells, and similar) fail closed with an actionable message instead of being guessed.",
330
+ "Word-list and arithmetic for loops, nested break/continue, printf and the documented portable builtins, pipelines, redirection, expansion (variables, command substitution, globs), chaining (&&/||/;), and cd/export/unset are supported and routed to a bundled Python engine; shell arithmetic expansion outside a for header, job control, process substitution, heredocs, nested shells, and other named constructs fail closed with an actionable message instead of being guessed.",
331
331
  "Working directory and environment changes from cd/export/unset persist across subsequent bash calls, including calls that route to the PowerShell tier.",
332
332
  "Supported Bash-like file commands are converted with literal-path operations; verify targets before recursive rm, cp, or mv calls.",
333
333
  `Keep searches scoped and purpose-driven: discover paths first, pass an explicit root and filters, and prefer the bounded grep/find tools. Broad shell searches are rejected; use broadSearch="${BROAD_SEARCH_OUTPUT_ROUTE}" only for an unavoidable exhaustive scan, then inspect the returned file with bounded reads or narrower searches.`,