@caupulican/pi-adaptative 0.81.29 → 0.81.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
- package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
- package/dist/core/agent-session.d.ts +11 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +16 -14
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +5 -1
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +31 -4
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/lane-tracker.d.ts +1 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +11 -0
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +1 -1
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +12 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +114 -19
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +7 -6
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +12 -0
- package/dist/core/context/context-store-retention.d.ts.map +1 -0
- package/dist/core/context/context-store-retention.js +161 -0
- package/dist/core/context/context-store-retention.js.map +1 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +19 -4
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +13 -12
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +128 -33
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +7 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +28 -17
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts +7 -3
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +10 -5
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +25 -9
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/export-html/template.js +2 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +52 -2
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +21 -19
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +36 -13
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +20 -2
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory-controller.d.ts +2 -0
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +18 -0
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +15 -10
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +3 -1
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +8 -5
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +2 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-analytics.d.ts +13 -7
- package/dist/core/session-analytics.d.ts.map +1 -1
- package/dist/core/session-analytics.js +155 -112
- package/dist/core/session-analytics.js.map +1 -1
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +54 -9
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-recovery-logger.d.ts +2 -0
- package/dist/core/tool-recovery-logger.d.ts.map +1 -1
- package/dist/core/tool-recovery-logger.js +32 -13
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tool-recovery-stats.d.ts +15 -0
- package/dist/core/tool-recovery-stats.d.ts.map +1 -0
- package/dist/core/tool-recovery-stats.js +206 -0
- package/dist/core/tool-recovery-stats.js.map +1 -0
- package/dist/core/tools/delegate-status.d.ts.map +1 -1
- package/dist/core/tools/delegate-status.js +15 -6
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +3 -0
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +7 -2
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +12 -1
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +19 -9
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
- package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
- package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +9 -3
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.js +9 -28
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/utils/streaming-lines.d.ts +20 -0
- package/dist/utils/streaming-lines.d.ts.map +1 -0
- package/dist/utils/streaming-lines.js +79 -0
- package/dist/utils/streaming-lines.js.map +1 -0
- package/docs/extensions.md +2 -0
- package/docs/index.md +1 -1
- package/docs/self-adaptation.md +7 -0
- package/docs/settings.md +5 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1,14 +1,29 @@
|
|
|
1
|
-
import { appendFileSync, mkdirSync } from "node:fs";
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname } from "node:path";
|
|
3
3
|
import { createToolValidationFailureCorpusRecord, writeFailureCorpusRecord, } from "./failure-corpus.js";
|
|
4
|
+
import { updatePersistedToolRecoveryStats } from "./tool-recovery-stats.js";
|
|
4
5
|
export const TOOL_RECOVERY_EVENT_LOG_FILE = "tool-recovery-events.jsonl";
|
|
5
6
|
export const TOOL_ARGUMENT_VALIDATION_LOG_KIND = "tool_argument_validation";
|
|
7
|
+
const MAX_EVENT_LOG_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
const ROTATED_EVENT_LOG_TARGET_BYTES = Math.floor(MAX_EVENT_LOG_BYTES * 0.75);
|
|
9
|
+
const MAX_ROTATED_EVENT_LOG_RECORDS = 5_000;
|
|
10
|
+
const MAX_TELEMETRY_LIST_ITEMS = 50;
|
|
11
|
+
const MAX_TELEMETRY_TEXT_CHARS = 256;
|
|
12
|
+
function boundedText(value) {
|
|
13
|
+
return value.slice(0, MAX_TELEMETRY_TEXT_CHARS);
|
|
14
|
+
}
|
|
15
|
+
function boundedList(values) {
|
|
16
|
+
return values?.slice(0, MAX_TELEMETRY_LIST_ITEMS);
|
|
17
|
+
}
|
|
18
|
+
function boundedTextList(values) {
|
|
19
|
+
return values?.slice(0, MAX_TELEMETRY_LIST_ITEMS).map(boundedText);
|
|
20
|
+
}
|
|
6
21
|
function copyFailureShape(shape) {
|
|
7
|
-
return (shape ?? []).map((entry) => ({
|
|
8
|
-
path: entry.path,
|
|
9
|
-
expectedType: entry.expectedType,
|
|
10
|
-
receivedType: entry.receivedType,
|
|
11
|
-
...(entry.keyword ? { keyword: entry.keyword } : {}),
|
|
22
|
+
return (shape ?? []).slice(0, MAX_TELEMETRY_LIST_ITEMS).map((entry) => ({
|
|
23
|
+
path: boundedText(entry.path),
|
|
24
|
+
expectedType: boundedText(entry.expectedType),
|
|
25
|
+
receivedType: boundedText(entry.receivedType),
|
|
26
|
+
...(entry.keyword ? { keyword: boundedText(entry.keyword) } : {}),
|
|
12
27
|
}));
|
|
13
28
|
}
|
|
14
29
|
export function createToolArgumentValidationLogRecord(args) {
|
|
@@ -23,10 +38,10 @@ export function createToolArgumentValidationLogRecord(args) {
|
|
|
23
38
|
model: args.event.model,
|
|
24
39
|
tool: args.event.tool,
|
|
25
40
|
source: args.event.source,
|
|
26
|
-
failureModes:
|
|
27
|
-
repairsApplied:
|
|
41
|
+
failureModes: boundedList(args.event.failureModes) ?? [],
|
|
42
|
+
repairsApplied: boundedList(args.event.repairsApplied) ?? [],
|
|
28
43
|
failureShape: copyFailureShape(args.event.failureShape),
|
|
29
|
-
errorKeywords: args.event.errorKeywords
|
|
44
|
+
errorKeywords: boundedTextList(args.event.errorKeywords),
|
|
30
45
|
taught: args.event.taught,
|
|
31
46
|
executionOutcome: args.event.executionOutcome,
|
|
32
47
|
};
|
|
@@ -45,9 +60,39 @@ export function isToolArgumentValidationLogRecord(value) {
|
|
|
45
60
|
Array.isArray(record.failureModes) &&
|
|
46
61
|
Array.isArray(record.repairsApplied));
|
|
47
62
|
}
|
|
63
|
+
function rotateToolRecoveryEventLogIfNeeded(filePath) {
|
|
64
|
+
if (!existsSync(filePath) || statSync(filePath).size <= MAX_EVENT_LOG_BYTES)
|
|
65
|
+
return;
|
|
66
|
+
const lines = readFileSync(filePath, "utf-8")
|
|
67
|
+
.split("\n")
|
|
68
|
+
.filter((line) => line.trim().length > 0);
|
|
69
|
+
const retained = [];
|
|
70
|
+
let retainedBytes = 0;
|
|
71
|
+
for (let index = lines.length - 1; index >= 0 && retained.length < MAX_ROTATED_EVENT_LOG_RECORDS; index--) {
|
|
72
|
+
const line = lines[index];
|
|
73
|
+
const lineBytes = Buffer.byteLength(line, "utf-8") + 1;
|
|
74
|
+
if (lineBytes > MAX_EVENT_LOG_BYTES)
|
|
75
|
+
continue;
|
|
76
|
+
if (retained.length > 0 && retainedBytes + lineBytes > ROTATED_EVENT_LOG_TARGET_BYTES)
|
|
77
|
+
break;
|
|
78
|
+
retained.push(line);
|
|
79
|
+
retainedBytes += lineBytes;
|
|
80
|
+
if (retainedBytes >= ROTATED_EVENT_LOG_TARGET_BYTES)
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
retained.reverse();
|
|
84
|
+
writeFileSync(filePath, retained.length > 0 ? `${retained.join("\n")}\n` : "", "utf-8");
|
|
85
|
+
}
|
|
48
86
|
export function writeToolRecoveryLogRecord(entry) {
|
|
49
87
|
mkdirSync(dirname(entry.eventLogPath), { recursive: true });
|
|
50
88
|
appendFileSync(entry.eventLogPath, `${JSON.stringify(entry.record)}\n`, "utf-8");
|
|
89
|
+
rotateToolRecoveryEventLogIfNeeded(entry.eventLogPath);
|
|
90
|
+
try {
|
|
91
|
+
updatePersistedToolRecoveryStats(entry.eventLogPath, entry.record);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// The bounded event log remains the recovery source if the cumulative summary cannot be updated.
|
|
95
|
+
}
|
|
51
96
|
if (entry.record.outcome !== "bounced")
|
|
52
97
|
return;
|
|
53
98
|
writeFailureCorpusRecord(entry.failureCorpusPath, createToolValidationFailureCorpusRecord({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-recovery-log-records.js","sourceRoot":"","sources":["../../src/core/tool-recovery-log-records.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EACN,uCAAuC,EAEvC,wBAAwB,GACxB,MAAM,qBAAqB,CAAC;AAE7B,MAAM,CAAC,MAAM,4BAA4B,GAAG,4BAA4B,CAAC;AACzE,MAAM,CAAC,MAAM,iCAAiC,GAAG,0BAA0B,CAAC;AAgB5E,SAAS,gBAAgB,CACxB,KAA6D,EACzB;IACpC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACpC,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,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AC,YAAY,CAAC;QAClD,aAAa,EAAE,KAAK,CAAC,MAAM,CAAC,aAAa;KACzC,CAAC,CACF,CAAC;AAAA,CACF","sourcesContent":["import { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport {\n\tcreateToolValidationFailureCorpusRecord,\n\ttype ToolValidationFailureShapeEntry,\n\twriteFailureCorpusRecord,\n} from \"./failure-corpus.ts\";\n\nexport const TOOL_RECOVERY_EVENT_LOG_FILE = \"tool-recovery-events.jsonl\";\nexport const TOOL_ARGUMENT_VALIDATION_LOG_KIND = \"tool_argument_validation\";\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 copyFailureShape(\n\tshape: readonly ToolValidationFailureShapeEntry[] | undefined,\n): ToolValidationFailureShapeEntry[] {\n\treturn (shape ?? []).map((entry) => ({\n\t\tpath: entry.path,\n\t\texpectedType: entry.expectedType,\n\t\treceivedType: entry.receivedType,\n\t\t...(entry.keyword ? { keyword: 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: [...args.event.failureModes],\n\t\trepairsApplied: [...args.event.repairsApplied],\n\t\tfailureShape: copyFailureShape(args.event.failureShape),\n\t\terrorKeywords: args.event.errorKeywords ? [...args.event.errorKeywords] : undefined,\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\nexport function writeToolRecoveryLogRecord(entry: ToolRecoveryLogWorkerRecord): void {\n\tmkdirSync(dirname(entry.eventLogPath), { recursive: true });\n\tappendFileSync(entry.eventLogPath, `${JSON.stringify(entry.record)}\\n`, \"utf-8\");\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":"AAAA,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,SAAS,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,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;AAAA,CACF","sourcesContent":["import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport 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\";\n\nexport const TOOL_RECOVERY_EVENT_LOG_FILE = \"tool-recovery-events.jsonl\";\nexport const TOOL_ARGUMENT_VALIDATION_LOG_KIND = \"tool_argument_validation\";\n\nconst MAX_EVENT_LOG_BYTES = 4 * 1024 * 1024;\nconst ROTATED_EVENT_LOG_TARGET_BYTES = Math.floor(MAX_EVENT_LOG_BYTES * 0.75);\nconst MAX_ROTATED_EVENT_LOG_RECORDS = 5_000;\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\nfunction rotateToolRecoveryEventLogIfNeeded(filePath: string): void {\n\tif (!existsSync(filePath) || statSync(filePath).size <= MAX_EVENT_LOG_BYTES) return;\n\tconst lines = readFileSync(filePath, \"utf-8\")\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.trim().length > 0);\n\tconst retained: string[] = [];\n\tlet retainedBytes = 0;\n\tfor (let index = lines.length - 1; index >= 0 && retained.length < MAX_ROTATED_EVENT_LOG_RECORDS; index--) {\n\t\tconst line = lines[index];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + 1;\n\t\tif (lineBytes > MAX_EVENT_LOG_BYTES) continue;\n\t\tif (retained.length > 0 && retainedBytes + lineBytes > ROTATED_EVENT_LOG_TARGET_BYTES) break;\n\t\tretained.push(line);\n\t\tretainedBytes += lineBytes;\n\t\tif (retainedBytes >= ROTATED_EVENT_LOG_TARGET_BYTES) break;\n\t}\n\tretained.reverse();\n\twriteFileSync(filePath, retained.length > 0 ? `${retained.join(\"\\n\")}\\n` : \"\", \"utf-8\");\n}\n\nexport function writeToolRecoveryLogRecord(entry: ToolRecoveryLogWorkerRecord): void {\n\tmkdirSync(dirname(entry.eventLogPath), { recursive: true });\n\tappendFileSync(entry.eventLogPath, `${JSON.stringify(entry.record)}\\n`, \"utf-8\");\n\trotateToolRecoveryEventLogIfNeeded(entry.eventLogPath);\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-recovery-logger.d.ts","sourceRoot":"","sources":["../../src/core/tool-recovery-logger.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAEN,KAAK,+BAA+B,EAEpC,MAAM,gCAAgC,CAAC;AASxC,MAAM,WAAW,uBAAuB;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,yBAAyB;IACzC,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,eAAe,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAC/B;AAyBD,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,QAA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AmB;IAe3B,OAAO,CAAC,yBAAyB;CAKjC","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 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\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 timeout = setTimeout(finish, timeoutMs);\n\t\t\tconst waiter = (): void => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tfinish();\n\t\t\t};\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\ttry {\n\t\t\tworker.postMessage({ type: \"records\", batchId, records });\n\t\t} catch (error) {\n\t\t\tthis.failures++;\n\t\t\tthis.dropped += records.length;\n\t\t\tthis.inFlight = [];\n\t\t\tthis.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.resolveFlushWaitersIfIdle();\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(message));\n\t\t\tworker.on(\"error\", (error) => this.handleWorkerFailure(error));\n\t\t\tworker.on(\"exit\", (code) => {\n\t\t\t\tif (this.shuttingDown || code === 0) return;\n\t\t\t\tthis.handleWorkerFailure(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(message: unknown): void {\n\t\tif (!isToolRecoveryLogAckMessage(message)) return;\n\t\tif (message.failed > 0) {\n\t\t\tthis.failures += message.failed;\n\t\t}\n\t\tthis.inFlight = [];\n\t\tthis.pump();\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate handleWorkerFailure(error: Error): void {\n\t\tthis.failures++;\n\t\tthis.workerCrashes++;\n\t\tthis.dropped += this.inFlight.length;\n\t\tthis.inFlight = [];\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.d.ts","sourceRoot":"","sources":["../../src/core/tool-recovery-logger.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAEN,KAAK,+BAA+B,EAEpC,MAAM,gCAAgC,CAAC;AASxC,MAAM,WAAW,uBAAuB;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,yBAAyB;IACzC,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,eAAe,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAC/B;AAyBD,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAU;IAClC,OAAO,CAAC,QAAQ,CA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,OAAO,CAAC,mBAAmB;IAoB3B,OAAO,CAAC,yBAAyB;CAKjC","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"]}
|
|
@@ -30,6 +30,8 @@ export class ToolRecoveryLogger {
|
|
|
30
30
|
flushWaiters = [];
|
|
31
31
|
worker;
|
|
32
32
|
inFlight = [];
|
|
33
|
+
inFlightBatchId;
|
|
34
|
+
inFlightWorker;
|
|
33
35
|
batchId = 0;
|
|
34
36
|
recordSequence = 0;
|
|
35
37
|
dropped = 0;
|
|
@@ -81,17 +83,23 @@ export class ToolRecoveryLogger {
|
|
|
81
83
|
this.pump();
|
|
82
84
|
return new Promise((resolve) => {
|
|
83
85
|
let settled = false;
|
|
86
|
+
let timeout;
|
|
84
87
|
const finish = () => {
|
|
85
88
|
if (settled)
|
|
86
89
|
return;
|
|
87
90
|
settled = true;
|
|
88
91
|
resolve();
|
|
89
92
|
};
|
|
90
|
-
const timeout = setTimeout(finish, timeoutMs);
|
|
91
93
|
const waiter = () => {
|
|
92
94
|
clearTimeout(timeout);
|
|
93
95
|
finish();
|
|
94
96
|
};
|
|
97
|
+
timeout = setTimeout(() => {
|
|
98
|
+
const index = this.flushWaiters.indexOf(waiter);
|
|
99
|
+
if (index !== -1)
|
|
100
|
+
this.flushWaiters.splice(index, 1);
|
|
101
|
+
finish();
|
|
102
|
+
}, timeoutMs);
|
|
95
103
|
this.flushWaiters.push(waiter);
|
|
96
104
|
this.resolveFlushWaitersIfIdle();
|
|
97
105
|
});
|
|
@@ -128,15 +136,14 @@ export class ToolRecoveryLogger {
|
|
|
128
136
|
const records = this.queue.splice(0, this.batchSize);
|
|
129
137
|
this.inFlight = records;
|
|
130
138
|
const batchId = this.batchId++;
|
|
139
|
+
this.inFlightBatchId = batchId;
|
|
140
|
+
this.inFlightWorker = worker;
|
|
131
141
|
try {
|
|
132
142
|
worker.postMessage({ type: "records", batchId, records });
|
|
133
143
|
}
|
|
134
144
|
catch (error) {
|
|
135
|
-
this.failures++;
|
|
136
|
-
this.dropped += records.length;
|
|
137
|
-
this.inFlight = [];
|
|
138
145
|
this.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
139
|
-
this.
|
|
146
|
+
this.handleWorkerFailure(worker, error instanceof Error ? error : new Error(String(error)));
|
|
140
147
|
}
|
|
141
148
|
}
|
|
142
149
|
ensureWorker() {
|
|
@@ -147,12 +154,12 @@ export class ToolRecoveryLogger {
|
|
|
147
154
|
worker.unref();
|
|
148
155
|
this.worker = worker;
|
|
149
156
|
this.workerStarts++;
|
|
150
|
-
worker.on("message", (message) => this.handleWorkerMessage(message));
|
|
151
|
-
worker.on("error", (error) => this.handleWorkerFailure(error));
|
|
157
|
+
worker.on("message", (message) => this.handleWorkerMessage(worker, message));
|
|
158
|
+
worker.on("error", (error) => this.handleWorkerFailure(worker, error));
|
|
152
159
|
worker.on("exit", (code) => {
|
|
153
|
-
if (this.shuttingDown ||
|
|
160
|
+
if (this.shuttingDown || this.worker !== worker)
|
|
154
161
|
return;
|
|
155
|
-
this.handleWorkerFailure(new Error(`tool recovery logger worker exited with code ${code}`));
|
|
162
|
+
this.handleWorkerFailure(worker, new Error(`tool recovery logger worker exited with code ${code}`));
|
|
156
163
|
});
|
|
157
164
|
return worker;
|
|
158
165
|
}
|
|
@@ -162,21 +169,33 @@ export class ToolRecoveryLogger {
|
|
|
162
169
|
return undefined;
|
|
163
170
|
}
|
|
164
171
|
}
|
|
165
|
-
handleWorkerMessage(message) {
|
|
172
|
+
handleWorkerMessage(worker, message) {
|
|
166
173
|
if (!isToolRecoveryLogAckMessage(message))
|
|
167
174
|
return;
|
|
175
|
+
if (this.worker !== worker || this.inFlightWorker !== worker || this.inFlightBatchId !== message.batchId) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
168
178
|
if (message.failed > 0) {
|
|
169
179
|
this.failures += message.failed;
|
|
170
180
|
}
|
|
171
181
|
this.inFlight = [];
|
|
182
|
+
this.inFlightBatchId = undefined;
|
|
183
|
+
this.inFlightWorker = undefined;
|
|
184
|
+
this.respawnAttempted = false;
|
|
172
185
|
this.pump();
|
|
173
186
|
this.resolveFlushWaitersIfIdle();
|
|
174
187
|
}
|
|
175
|
-
handleWorkerFailure(error) {
|
|
188
|
+
handleWorkerFailure(worker, error) {
|
|
189
|
+
if (this.worker !== worker)
|
|
190
|
+
return;
|
|
176
191
|
this.failures++;
|
|
177
192
|
this.workerCrashes++;
|
|
178
|
-
this.
|
|
179
|
-
|
|
193
|
+
if (this.inFlightWorker === worker) {
|
|
194
|
+
this.dropped += this.inFlight.length;
|
|
195
|
+
this.inFlight = [];
|
|
196
|
+
this.inFlightBatchId = undefined;
|
|
197
|
+
this.inFlightWorker = undefined;
|
|
198
|
+
}
|
|
180
199
|
this.worker = undefined;
|
|
181
200
|
this.debug(`tool recovery logger worker failed: ${error.message}`);
|
|
182
201
|
if (!this.respawnAttempted && !this.shuttingDown) {
|
|
@@ -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,EAAsC;IACxF,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;AAAA,CACF;AAED,SAAS,4BAA4B,GAAQ;IAC5C,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;AAAA,CACF;AAED,MAAM,OAAO,kBAAkB;IACb,OAAO,CAAU;IACjB,SAAS,CAAS;IAClB,YAAY,CAAS;IACrB,iBAAiB,CAAS;IAC1B,QAAQ,CAAS;IACjB,SAAS,CAAS;IAClB,GAAG,CAAa;IAChB,KAAK,CAA4B;IACjC,eAAe,CAAe;IAC9B,KAAK,GAAkC,EAAE,CAAC;IAC1C,YAAY,GAAsB,EAAE,CAAC;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,KAAY,EAAQ;QAC/C,IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;QACrC,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,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;IAAA,CACjC;IAEO,yBAAyB,GAAS;QACzC,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;IAAA,CACvC;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 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\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 timeout = setTimeout(finish, timeoutMs);\n\t\t\tconst waiter = (): void => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tfinish();\n\t\t\t};\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\ttry {\n\t\t\tworker.postMessage({ type: \"records\", batchId, records });\n\t\t} catch (error) {\n\t\t\tthis.failures++;\n\t\t\tthis.dropped += records.length;\n\t\t\tthis.inFlight = [];\n\t\t\tthis.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.resolveFlushWaitersIfIdle();\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(message));\n\t\t\tworker.on(\"error\", (error) => this.handleWorkerFailure(error));\n\t\t\tworker.on(\"exit\", (code) => {\n\t\t\t\tif (this.shuttingDown || code === 0) return;\n\t\t\t\tthis.handleWorkerFailure(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(message: unknown): void {\n\t\tif (!isToolRecoveryLogAckMessage(message)) return;\n\t\tif (message.failed > 0) {\n\t\t\tthis.failures += message.failed;\n\t\t}\n\t\tthis.inFlight = [];\n\t\tthis.pump();\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate handleWorkerFailure(error: Error): void {\n\t\tthis.failures++;\n\t\tthis.workerCrashes++;\n\t\tthis.dropped += this.inFlight.length;\n\t\tthis.inFlight = [];\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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;YAChB,IAAI,CAAC,IAAI,EAAE,CAAC;QACb,CAAC;QACD,IAAI,CAAC,yBAAyB,EAAE,CAAC;IAAA,CACjC;IAEO,yBAAyB,GAAS;QACzC,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;IAAA,CACvC;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"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ToolArgumentValidationRecord, ToolArgumentValidationStats } from "./session-analytics.ts";
|
|
2
|
+
import { type ToolArgumentValidationLogRecord } from "./tool-recovery-log-records.ts";
|
|
3
|
+
interface PersistedToolRecoveryStats {
|
|
4
|
+
version: 1;
|
|
5
|
+
sessionId: string;
|
|
6
|
+
lastRecordSequence: number;
|
|
7
|
+
stats: ToolArgumentValidationStats;
|
|
8
|
+
}
|
|
9
|
+
export declare function createEmptyToolArgumentValidationStats(): ToolArgumentValidationStats;
|
|
10
|
+
export declare function consumeToolArgumentValidationRecord(stats: ToolArgumentValidationStats, record: ToolArgumentValidationRecord): void;
|
|
11
|
+
export declare function getToolRecoveryRecordSequence(record: Pick<ToolArgumentValidationLogRecord, "recordId" | "sessionId">): number;
|
|
12
|
+
export declare function readPersistedToolRecoveryStats(eventLogPath: string, sessionId: string): PersistedToolRecoveryStats | undefined;
|
|
13
|
+
export declare function updatePersistedToolRecoveryStats(eventLogPath: string, record: ToolArgumentValidationLogRecord): void;
|
|
14
|
+
export {};
|
|
15
|
+
//# sourceMappingURL=tool-recovery-stats.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-recovery-stats.d.ts","sourceRoot":"","sources":["../../src/core/tool-recovery-stats.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,4BAA4B,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AACxG,OAAO,EAEN,KAAK,+BAA+B,EACpC,MAAM,gCAAgC,CAAC;AAOxC,UAAU,0BAA0B;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,KAAK,EAAE,2BAA2B,CAAC;CACnC;AAED,wBAAgB,sCAAsC,IAAI,2BAA2B,CAWpF;AAOD,wBAAgB,mCAAmC,CAClD,KAAK,EAAE,2BAA2B,EAClC,MAAM,EAAE,4BAA4B,GAClC,IAAI,CAwDN;AAED,wBAAgB,6BAA6B,CAC5C,MAAM,EAAE,IAAI,CAAC,+BAA+B,EAAE,UAAU,GAAG,WAAW,CAAC,GACrE,MAAM,CAKR;AA4CD,wBAAgB,8BAA8B,CAC7C,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,GACf,0BAA0B,GAAG,SAAS,CASxC;AAiCD,wBAAgB,gCAAgC,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,IAAI,CA6BpH","sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { ToolArgumentValidationRecord, ToolArgumentValidationStats } from \"./session-analytics.ts\";\nimport {\n\tisToolArgumentValidationLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n} from \"./tool-recovery-log-records.ts\";\n\nconst MAX_DETAIL_KEYS = 1_000;\nconst MAX_STATS_FILES = 1_000;\nconst MAX_STATS_FILE_AGE_MS = 90 * 24 * 60 * 60 * 1000;\nconst OTHER_DETAIL_KEY = \"__other__\";\n\ninterface PersistedToolRecoveryStats {\n\tversion: 1;\n\tsessionId: string;\n\tlastRecordSequence: number;\n\tstats: ToolArgumentValidationStats;\n}\n\nexport function createEmptyToolArgumentValidationStats(): ToolArgumentValidationStats {\n\treturn {\n\t\tclean: 0,\n\t\trepaired: 0,\n\t\tbounced: 0,\n\t\tfailureModes: {},\n\t\trepairsApplied: {},\n\t\ttaught: { none: 0, note: 0, rule: 0 },\n\t\texecutionOutcome: { not_run: 0, succeeded: 0, failed: 0 },\n\t\tteachEfficacy: {},\n\t};\n}\n\nfunction boundedDetailKey(record: Record<string, unknown>, key: string): string {\n\tif (record[key] !== undefined || Object.keys(record).length < MAX_DETAIL_KEYS - 1) return key;\n\treturn OTHER_DETAIL_KEY;\n}\n\nexport function consumeToolArgumentValidationRecord(\n\tstats: ToolArgumentValidationStats,\n\trecord: ToolArgumentValidationRecord,\n): void {\n\tstats[record.outcome] += 1;\n\tconst taught = record.taught ?? \"none\";\n\tconst executionOutcome = record.executionOutcome ?? \"not_run\";\n\tstats.taught[taught] += 1;\n\tstats.executionOutcome[executionOutcome] += 1;\n\tconst modes = new Set([...record.failureModes, ...record.repairsApplied]);\n\tfor (const mode of record.failureModes) {\n\t\tconst key = boundedDetailKey(stats.failureModes, mode);\n\t\tstats.failureModes[key] = (stats.failureModes[key] ?? 0) + 1;\n\t}\n\tfor (const repair of record.repairsApplied) {\n\t\tconst key = boundedDetailKey(stats.repairsApplied, repair);\n\t\tstats.repairsApplied[key] = (stats.repairsApplied[key] ?? 0) + 1;\n\t}\n\tfor (const mode of modes) {\n\t\tconst key = boundedDetailKey(\n\t\t\tstats.teachEfficacy,\n\t\t\t`${record.provider ?? \"unknown\"}/${record.model ?? \"unknown\"}:${mode}`,\n\t\t);\n\t\tlet efficacy = stats.teachEfficacy[key];\n\t\tif (!efficacy) {\n\t\t\tefficacy = {\n\t\t\t\trecurrenceBefore: 0,\n\t\t\t\trecurrenceAfter: 0,\n\t\t\t\trepairedThenSucceeded: 0,\n\t\t\t\trepairedThenFailed: 0,\n\t\t\t\trepairedThenNotRun: 0,\n\t\t\t};\n\t\t\tstats.teachEfficacy[key] = efficacy;\n\t\t}\n\t\tif (taught === \"none\") efficacy.recurrenceBefore++;\n\t\telse efficacy.recurrenceAfter++;\n\t}\n\tif (record.outcome === \"repaired\") {\n\t\tfor (const repair of record.repairsApplied) {\n\t\t\tconst key = boundedDetailKey(\n\t\t\t\tstats.teachEfficacy,\n\t\t\t\t`${record.provider ?? \"unknown\"}/${record.model ?? \"unknown\"}:${repair}`,\n\t\t\t);\n\t\t\tlet efficacy = stats.teachEfficacy[key];\n\t\t\tif (!efficacy) {\n\t\t\t\tefficacy = {\n\t\t\t\t\trecurrenceBefore: 0,\n\t\t\t\t\trecurrenceAfter: 0,\n\t\t\t\t\trepairedThenSucceeded: 0,\n\t\t\t\t\trepairedThenFailed: 0,\n\t\t\t\t\trepairedThenNotRun: 0,\n\t\t\t\t};\n\t\t\t\tstats.teachEfficacy[key] = efficacy;\n\t\t\t}\n\t\t\tif (executionOutcome === \"succeeded\") efficacy.repairedThenSucceeded++;\n\t\t\tif (executionOutcome === \"failed\") efficacy.repairedThenFailed++;\n\t\t\tif (executionOutcome === \"not_run\") efficacy.repairedThenNotRun++;\n\t\t}\n\t}\n}\n\nexport function getToolRecoveryRecordSequence(\n\trecord: Pick<ToolArgumentValidationLogRecord, \"recordId\" | \"sessionId\">,\n): number {\n\tconst prefix = `${record.sessionId}:`;\n\tif (!record.recordId.startsWith(prefix)) return -1;\n\tconst sequence = Number(record.recordId.slice(prefix.length));\n\treturn Number.isSafeInteger(sequence) && sequence >= 0 ? sequence : -1;\n}\n\nfunction statsPath(eventLogPath: string, sessionId: string): string {\n\tconst id = createHash(\"sha256\").update(sessionId).digest(\"hex\").slice(0, 24);\n\treturn join(dirname(eventLogPath), \"tool-recovery-stats\", `${id}.json`);\n}\n\nfunction isFiniteCount(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nfunction isCountRecord(value: unknown): value is Record<string, number> {\n\treturn !!value && typeof value === \"object\" && Object.values(value).every(isFiniteCount);\n}\n\nfunction isStatsShape(value: unknown): value is ToolArgumentValidationStats {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst stats = value as Partial<ToolArgumentValidationStats>;\n\tif (!isFiniteCount(stats.clean) || !isFiniteCount(stats.repaired) || !isFiniteCount(stats.bounced)) return false;\n\tif (!isCountRecord(stats.failureModes) || !isCountRecord(stats.repairsApplied)) return false;\n\tif (!isCountRecord(stats.taught) || !isCountRecord(stats.executionOutcome)) return false;\n\tif (!stats.teachEfficacy || typeof stats.teachEfficacy !== \"object\") return false;\n\treturn Object.values(stats.teachEfficacy).every(\n\t\t(value) =>\n\t\t\t!!value &&\n\t\t\tisFiniteCount(value.recurrenceBefore) &&\n\t\t\tisFiniteCount(value.recurrenceAfter) &&\n\t\t\tisFiniteCount(value.repairedThenSucceeded) &&\n\t\t\tisFiniteCount(value.repairedThenFailed) &&\n\t\t\tisFiniteCount(value.repairedThenNotRun),\n\t);\n}\n\nfunction isPersistedStats(value: unknown, sessionId: string): value is PersistedToolRecoveryStats {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Partial<PersistedToolRecoveryStats>;\n\treturn (\n\t\trecord.version === 1 &&\n\t\trecord.sessionId === sessionId &&\n\t\tisFiniteCount(record.lastRecordSequence) &&\n\t\tisStatsShape(record.stats)\n\t);\n}\n\nexport function readPersistedToolRecoveryStats(\n\teventLogPath: string,\n\tsessionId: string,\n): PersistedToolRecoveryStats | undefined {\n\tconst path = statsPath(eventLogPath, sessionId);\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n\t\treturn isPersistedStats(parsed, sessionId) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction pruneStatsFiles(directory: string, currentPath: string): void {\n\tconst now = Date.now();\n\tconst files = readdirSync(directory)\n\t\t.filter((name) => name.endsWith(\".json\"))\n\t\t.map((name) => {\n\t\t\tconst path = join(directory, name);\n\t\t\treturn { path, mtimeMs: statSync(path).mtimeMs };\n\t\t})\n\t\t.sort((left, right) => left.mtimeMs - right.mtimeMs);\n\tlet retained = files.length;\n\tfor (const file of files) {\n\t\tif (file.path === currentPath) continue;\n\t\tif (retained <= MAX_STATS_FILES && now - file.mtimeMs <= MAX_STATS_FILE_AGE_MS) continue;\n\t\ttry {\n\t\t\tunlinkSync(file.path);\n\t\t\tretained--;\n\t\t} catch {}\n\t}\n}\n\nfunction writePersistedToolRecoveryStats(eventLogPath: string, summary: PersistedToolRecoveryStats): void {\n\tconst path = statsPath(eventLogPath, summary.sessionId);\n\tconst directory = dirname(path);\n\tmkdirSync(directory, { recursive: true });\n\tconst isNewSummary = !existsSync(path);\n\tconst temporaryPath = `${path}.${process.pid}.tmp`;\n\twriteFileSync(temporaryPath, JSON.stringify(summary), \"utf-8\");\n\trenameSync(temporaryPath, path);\n\tif (isNewSummary) pruneStatsFiles(directory, path);\n}\n\nexport function updatePersistedToolRecoveryStats(eventLogPath: string, record: ToolArgumentValidationLogRecord): void {\n\tlet summary = readPersistedToolRecoveryStats(eventLogPath, record.sessionId);\n\tif (!summary) {\n\t\tsummary = {\n\t\t\tversion: 1,\n\t\t\tsessionId: record.sessionId,\n\t\t\tlastRecordSequence: -1,\n\t\t\tstats: createEmptyToolArgumentValidationStats(),\n\t\t};\n\t\ttry {\n\t\t\tfor (const line of readFileSync(eventLogPath, \"utf-8\").split(\"\\n\")) {\n\t\t\t\tif (line.trim().length === 0) continue;\n\t\t\t\tconst parsed: unknown = JSON.parse(line);\n\t\t\t\tif (!isToolArgumentValidationLogRecord(parsed) || parsed.sessionId !== record.sessionId) continue;\n\t\t\t\tconst sequence = getToolRecoveryRecordSequence(parsed);\n\t\t\t\tif (sequence <= summary.lastRecordSequence) continue;\n\t\t\t\tconsumeToolArgumentValidationRecord(summary.stats, parsed);\n\t\t\t\tsummary.lastRecordSequence = sequence;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through and at least account for the current record.\n\t\t}\n\t}\n\tconst sequence = getToolRecoveryRecordSequence(record);\n\tif (sequence > summary.lastRecordSequence) {\n\t\tconsumeToolArgumentValidationRecord(summary.stats, record);\n\t\tsummary.lastRecordSequence = sequence;\n\t}\n\twritePersistedToolRecoveryStats(eventLogPath, summary);\n}\n"]}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { isToolArgumentValidationLogRecord, } from "./tool-recovery-log-records.js";
|
|
5
|
+
const MAX_DETAIL_KEYS = 1_000;
|
|
6
|
+
const MAX_STATS_FILES = 1_000;
|
|
7
|
+
const MAX_STATS_FILE_AGE_MS = 90 * 24 * 60 * 60 * 1000;
|
|
8
|
+
const OTHER_DETAIL_KEY = "__other__";
|
|
9
|
+
export function createEmptyToolArgumentValidationStats() {
|
|
10
|
+
return {
|
|
11
|
+
clean: 0,
|
|
12
|
+
repaired: 0,
|
|
13
|
+
bounced: 0,
|
|
14
|
+
failureModes: {},
|
|
15
|
+
repairsApplied: {},
|
|
16
|
+
taught: { none: 0, note: 0, rule: 0 },
|
|
17
|
+
executionOutcome: { not_run: 0, succeeded: 0, failed: 0 },
|
|
18
|
+
teachEfficacy: {},
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function boundedDetailKey(record, key) {
|
|
22
|
+
if (record[key] !== undefined || Object.keys(record).length < MAX_DETAIL_KEYS - 1)
|
|
23
|
+
return key;
|
|
24
|
+
return OTHER_DETAIL_KEY;
|
|
25
|
+
}
|
|
26
|
+
export function consumeToolArgumentValidationRecord(stats, record) {
|
|
27
|
+
stats[record.outcome] += 1;
|
|
28
|
+
const taught = record.taught ?? "none";
|
|
29
|
+
const executionOutcome = record.executionOutcome ?? "not_run";
|
|
30
|
+
stats.taught[taught] += 1;
|
|
31
|
+
stats.executionOutcome[executionOutcome] += 1;
|
|
32
|
+
const modes = new Set([...record.failureModes, ...record.repairsApplied]);
|
|
33
|
+
for (const mode of record.failureModes) {
|
|
34
|
+
const key = boundedDetailKey(stats.failureModes, mode);
|
|
35
|
+
stats.failureModes[key] = (stats.failureModes[key] ?? 0) + 1;
|
|
36
|
+
}
|
|
37
|
+
for (const repair of record.repairsApplied) {
|
|
38
|
+
const key = boundedDetailKey(stats.repairsApplied, repair);
|
|
39
|
+
stats.repairsApplied[key] = (stats.repairsApplied[key] ?? 0) + 1;
|
|
40
|
+
}
|
|
41
|
+
for (const mode of modes) {
|
|
42
|
+
const key = boundedDetailKey(stats.teachEfficacy, `${record.provider ?? "unknown"}/${record.model ?? "unknown"}:${mode}`);
|
|
43
|
+
let efficacy = stats.teachEfficacy[key];
|
|
44
|
+
if (!efficacy) {
|
|
45
|
+
efficacy = {
|
|
46
|
+
recurrenceBefore: 0,
|
|
47
|
+
recurrenceAfter: 0,
|
|
48
|
+
repairedThenSucceeded: 0,
|
|
49
|
+
repairedThenFailed: 0,
|
|
50
|
+
repairedThenNotRun: 0,
|
|
51
|
+
};
|
|
52
|
+
stats.teachEfficacy[key] = efficacy;
|
|
53
|
+
}
|
|
54
|
+
if (taught === "none")
|
|
55
|
+
efficacy.recurrenceBefore++;
|
|
56
|
+
else
|
|
57
|
+
efficacy.recurrenceAfter++;
|
|
58
|
+
}
|
|
59
|
+
if (record.outcome === "repaired") {
|
|
60
|
+
for (const repair of record.repairsApplied) {
|
|
61
|
+
const key = boundedDetailKey(stats.teachEfficacy, `${record.provider ?? "unknown"}/${record.model ?? "unknown"}:${repair}`);
|
|
62
|
+
let efficacy = stats.teachEfficacy[key];
|
|
63
|
+
if (!efficacy) {
|
|
64
|
+
efficacy = {
|
|
65
|
+
recurrenceBefore: 0,
|
|
66
|
+
recurrenceAfter: 0,
|
|
67
|
+
repairedThenSucceeded: 0,
|
|
68
|
+
repairedThenFailed: 0,
|
|
69
|
+
repairedThenNotRun: 0,
|
|
70
|
+
};
|
|
71
|
+
stats.teachEfficacy[key] = efficacy;
|
|
72
|
+
}
|
|
73
|
+
if (executionOutcome === "succeeded")
|
|
74
|
+
efficacy.repairedThenSucceeded++;
|
|
75
|
+
if (executionOutcome === "failed")
|
|
76
|
+
efficacy.repairedThenFailed++;
|
|
77
|
+
if (executionOutcome === "not_run")
|
|
78
|
+
efficacy.repairedThenNotRun++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export function getToolRecoveryRecordSequence(record) {
|
|
83
|
+
const prefix = `${record.sessionId}:`;
|
|
84
|
+
if (!record.recordId.startsWith(prefix))
|
|
85
|
+
return -1;
|
|
86
|
+
const sequence = Number(record.recordId.slice(prefix.length));
|
|
87
|
+
return Number.isSafeInteger(sequence) && sequence >= 0 ? sequence : -1;
|
|
88
|
+
}
|
|
89
|
+
function statsPath(eventLogPath, sessionId) {
|
|
90
|
+
const id = createHash("sha256").update(sessionId).digest("hex").slice(0, 24);
|
|
91
|
+
return join(dirname(eventLogPath), "tool-recovery-stats", `${id}.json`);
|
|
92
|
+
}
|
|
93
|
+
function isFiniteCount(value) {
|
|
94
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
95
|
+
}
|
|
96
|
+
function isCountRecord(value) {
|
|
97
|
+
return !!value && typeof value === "object" && Object.values(value).every(isFiniteCount);
|
|
98
|
+
}
|
|
99
|
+
function isStatsShape(value) {
|
|
100
|
+
if (!value || typeof value !== "object")
|
|
101
|
+
return false;
|
|
102
|
+
const stats = value;
|
|
103
|
+
if (!isFiniteCount(stats.clean) || !isFiniteCount(stats.repaired) || !isFiniteCount(stats.bounced))
|
|
104
|
+
return false;
|
|
105
|
+
if (!isCountRecord(stats.failureModes) || !isCountRecord(stats.repairsApplied))
|
|
106
|
+
return false;
|
|
107
|
+
if (!isCountRecord(stats.taught) || !isCountRecord(stats.executionOutcome))
|
|
108
|
+
return false;
|
|
109
|
+
if (!stats.teachEfficacy || typeof stats.teachEfficacy !== "object")
|
|
110
|
+
return false;
|
|
111
|
+
return Object.values(stats.teachEfficacy).every((value) => !!value &&
|
|
112
|
+
isFiniteCount(value.recurrenceBefore) &&
|
|
113
|
+
isFiniteCount(value.recurrenceAfter) &&
|
|
114
|
+
isFiniteCount(value.repairedThenSucceeded) &&
|
|
115
|
+
isFiniteCount(value.repairedThenFailed) &&
|
|
116
|
+
isFiniteCount(value.repairedThenNotRun));
|
|
117
|
+
}
|
|
118
|
+
function isPersistedStats(value, sessionId) {
|
|
119
|
+
if (!value || typeof value !== "object")
|
|
120
|
+
return false;
|
|
121
|
+
const record = value;
|
|
122
|
+
return (record.version === 1 &&
|
|
123
|
+
record.sessionId === sessionId &&
|
|
124
|
+
isFiniteCount(record.lastRecordSequence) &&
|
|
125
|
+
isStatsShape(record.stats));
|
|
126
|
+
}
|
|
127
|
+
export function readPersistedToolRecoveryStats(eventLogPath, sessionId) {
|
|
128
|
+
const path = statsPath(eventLogPath, sessionId);
|
|
129
|
+
if (!existsSync(path))
|
|
130
|
+
return undefined;
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
133
|
+
return isPersistedStats(parsed, sessionId) ? parsed : undefined;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function pruneStatsFiles(directory, currentPath) {
|
|
140
|
+
const now = Date.now();
|
|
141
|
+
const files = readdirSync(directory)
|
|
142
|
+
.filter((name) => name.endsWith(".json"))
|
|
143
|
+
.map((name) => {
|
|
144
|
+
const path = join(directory, name);
|
|
145
|
+
return { path, mtimeMs: statSync(path).mtimeMs };
|
|
146
|
+
})
|
|
147
|
+
.sort((left, right) => left.mtimeMs - right.mtimeMs);
|
|
148
|
+
let retained = files.length;
|
|
149
|
+
for (const file of files) {
|
|
150
|
+
if (file.path === currentPath)
|
|
151
|
+
continue;
|
|
152
|
+
if (retained <= MAX_STATS_FILES && now - file.mtimeMs <= MAX_STATS_FILE_AGE_MS)
|
|
153
|
+
continue;
|
|
154
|
+
try {
|
|
155
|
+
unlinkSync(file.path);
|
|
156
|
+
retained--;
|
|
157
|
+
}
|
|
158
|
+
catch { }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function writePersistedToolRecoveryStats(eventLogPath, summary) {
|
|
162
|
+
const path = statsPath(eventLogPath, summary.sessionId);
|
|
163
|
+
const directory = dirname(path);
|
|
164
|
+
mkdirSync(directory, { recursive: true });
|
|
165
|
+
const isNewSummary = !existsSync(path);
|
|
166
|
+
const temporaryPath = `${path}.${process.pid}.tmp`;
|
|
167
|
+
writeFileSync(temporaryPath, JSON.stringify(summary), "utf-8");
|
|
168
|
+
renameSync(temporaryPath, path);
|
|
169
|
+
if (isNewSummary)
|
|
170
|
+
pruneStatsFiles(directory, path);
|
|
171
|
+
}
|
|
172
|
+
export function updatePersistedToolRecoveryStats(eventLogPath, record) {
|
|
173
|
+
let summary = readPersistedToolRecoveryStats(eventLogPath, record.sessionId);
|
|
174
|
+
if (!summary) {
|
|
175
|
+
summary = {
|
|
176
|
+
version: 1,
|
|
177
|
+
sessionId: record.sessionId,
|
|
178
|
+
lastRecordSequence: -1,
|
|
179
|
+
stats: createEmptyToolArgumentValidationStats(),
|
|
180
|
+
};
|
|
181
|
+
try {
|
|
182
|
+
for (const line of readFileSync(eventLogPath, "utf-8").split("\n")) {
|
|
183
|
+
if (line.trim().length === 0)
|
|
184
|
+
continue;
|
|
185
|
+
const parsed = JSON.parse(line);
|
|
186
|
+
if (!isToolArgumentValidationLogRecord(parsed) || parsed.sessionId !== record.sessionId)
|
|
187
|
+
continue;
|
|
188
|
+
const sequence = getToolRecoveryRecordSequence(parsed);
|
|
189
|
+
if (sequence <= summary.lastRecordSequence)
|
|
190
|
+
continue;
|
|
191
|
+
consumeToolArgumentValidationRecord(summary.stats, parsed);
|
|
192
|
+
summary.lastRecordSequence = sequence;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
// Fall through and at least account for the current record.
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const sequence = getToolRecoveryRecordSequence(record);
|
|
200
|
+
if (sequence > summary.lastRecordSequence) {
|
|
201
|
+
consumeToolArgumentValidationRecord(summary.stats, record);
|
|
202
|
+
summary.lastRecordSequence = sequence;
|
|
203
|
+
}
|
|
204
|
+
writePersistedToolRecoveryStats(eventLogPath, summary);
|
|
205
|
+
}
|
|
206
|
+
//# sourceMappingURL=tool-recovery-stats.js.map
|