@caupulican/pi-agent-core 0.81.26 → 0.81.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +9 -5
- package/dist/agent-loop.js.map +1 -1
- package/dist/agent.d.ts +2 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +4 -1
- package/dist/agent.js.map +1 -1
- package/dist/compaction/compaction.d.ts +1 -1
- package/dist/compaction/compaction.d.ts.map +1 -1
- package/dist/compaction/compaction.js +10 -1
- package/dist/compaction/compaction.js.map +1 -1
- package/dist/compaction/extraction.d.ts +8 -0
- package/dist/compaction/extraction.d.ts.map +1 -1
- package/dist/compaction/extraction.js +49 -0
- package/dist/compaction/extraction.js.map +1 -1
- package/dist/reliability/watchdogs.d.ts.map +1 -1
- package/dist/reliability/watchdogs.js +107 -21
- package/dist/reliability/watchdogs.js.map +1 -1
- package/dist/types.d.ts +15 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -13,6 +13,9 @@ const MAX_WORKING_SET_FILES = 8;
|
|
|
13
13
|
const MAX_ERROR_FACTS = 5;
|
|
14
14
|
const ERROR_LINE_MAX_CHARS = 160;
|
|
15
15
|
const COMMAND_PREFIX_MAX_CHARS = 80;
|
|
16
|
+
const MAX_DELEGATED_WORKER_FACTS = 4;
|
|
17
|
+
const DELEGATED_WORKER_TASK_MAX_CHARS = 240;
|
|
18
|
+
const DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;
|
|
16
19
|
/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */
|
|
17
20
|
export const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;
|
|
18
21
|
const FILE_KIND_PRIORITY = {
|
|
@@ -73,6 +76,49 @@ function assistantToolCallTarget(name, rawArgs) {
|
|
|
73
76
|
function clampText(text, maxLen) {
|
|
74
77
|
return text.length > maxLen ? text.slice(0, maxLen) : text;
|
|
75
78
|
}
|
|
79
|
+
function isPlainRecord(value) {
|
|
80
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
81
|
+
return false;
|
|
82
|
+
const prototype = Object.getPrototypeOf(value);
|
|
83
|
+
return prototype === Object.prototype || prototype === null;
|
|
84
|
+
}
|
|
85
|
+
function normalizeDelegatedWorkerText(text, maxLen) {
|
|
86
|
+
return clampText(text.replace(/\s+/g, " ").trim(), maxLen);
|
|
87
|
+
}
|
|
88
|
+
function extractDelegatedWorkerFact(entry) {
|
|
89
|
+
if (entry.type !== "custom" || entry.customType !== "worker_result" || !isPlainRecord(entry.data)) {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
if (entry.data.version !== 1 || !isPlainRecord(entry.data.result))
|
|
93
|
+
return undefined;
|
|
94
|
+
const result = entry.data.result;
|
|
95
|
+
if (typeof result.requestId !== "string" || typeof result.summary !== "string")
|
|
96
|
+
return undefined;
|
|
97
|
+
if (typeof result.status !== "string" || !["completed", "blocked", "failed", "cancelled"].includes(result.status)) {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
if (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === "string")) {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
const request = entry.data.request;
|
|
104
|
+
const instructions = isPlainRecord(request) && typeof request.instructions === "string" ? request.instructions : undefined;
|
|
105
|
+
const task = normalizeDelegatedWorkerText(instructions ?? `Worker request ${result.requestId}`, DELEGATED_WORKER_TASK_MAX_CHARS);
|
|
106
|
+
const summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);
|
|
107
|
+
return {
|
|
108
|
+
trust: "UNTRUSTED",
|
|
109
|
+
task: task || "(empty task)",
|
|
110
|
+
summary: summary || "(empty summary)",
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function extractDelegatedWorkerFacts(entries, start, end) {
|
|
114
|
+
const facts = [];
|
|
115
|
+
for (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {
|
|
116
|
+
const fact = extractDelegatedWorkerFact(entries[i]);
|
|
117
|
+
if (fact)
|
|
118
|
+
facts.push(fact);
|
|
119
|
+
}
|
|
120
|
+
return facts;
|
|
121
|
+
}
|
|
76
122
|
function appearsCreated(message) {
|
|
77
123
|
if (message.role !== "toolResult") {
|
|
78
124
|
return false;
|
|
@@ -220,8 +266,10 @@ export function extractCompactionFacts(entries, start, end) {
|
|
|
220
266
|
prohibitions: [],
|
|
221
267
|
cancelledText: "",
|
|
222
268
|
activeTaskSource: "",
|
|
269
|
+
delegatedWorkerFacts: [],
|
|
223
270
|
};
|
|
224
271
|
}
|
|
272
|
+
const delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);
|
|
225
273
|
const filesByPath = new Map();
|
|
226
274
|
const filesNotes = new Map();
|
|
227
275
|
const seenProhibitions = new Set();
|
|
@@ -429,6 +477,7 @@ export function extractCompactionFacts(entries, start, end) {
|
|
|
429
477
|
prohibitions: prohibitions.slice(-MAX_PROHIBITIONS),
|
|
430
478
|
cancelledText: cancelledParts.join("\n"),
|
|
431
479
|
activeTaskSource,
|
|
480
|
+
delegatedWorkerFacts,
|
|
432
481
|
};
|
|
433
482
|
}
|
|
434
483
|
function dedupeMostRecent(values) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extraction.js","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AAmCA,MAAM,mBAAmB,GAAG,iEAAiE,CAAC;AAC9F,+FAA+F;AAC/F,uFAAqF;AACrF,oEAAoE;AACpE,MAAM,gBAAgB,GACrB,mHAAmH,CAAC;AAErH,oFAAoF;AACpF,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAC3C,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,mGAAmG;AACnG,MAAM,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,IAAI,CAAC,IAAI,QAAM,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACxD,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,uDAAuD,CAAC,CAAC;IACpE,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;QACtC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;IAClD,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAC;IACvD,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QACpC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,8DAA8D,CAAC,CAAC;IAC3E,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzB,CAAC;IACD,2FAA2F;IAC3F,0FAAwF;IACxF,+EAA+E;IAC/E,KAAK,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;QAC5B,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,gBAAgB,EAAE,4BAA4B,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,uEAAuE,CAAC,CAAC;IACpF,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn parts.join(\" \").trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t};\n\t}\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, 160);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear in ## Files, containment threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"extraction.js","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AA4CA,MAAM,mBAAmB,GAAG,iEAAiE,CAAC;AAC9F,+FAA+F;AAC/F,uFAAqF;AACrF,oEAAoE;AACpE,MAAM,gBAAgB,GACrB,mHAAmH,CAAC;AAErH,oFAAoF;AACpF,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAC3C,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,mGAAmG;AACnG,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,2GAA2G;AAC3G,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAElD,MAAM,kBAAkB,GAA2D;IAClF,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;CACX,CAAC;AAEF,MAAM,iBAAiB,GAA2D;IACjF,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,UAAU;IACjB,IAAI,EAAE,UAAU;IAChB,IAAI,EAAE,IAAI;CACV,CAAC;AAEF,MAAM,iBAAiB,GAA2B;IACjD,KAAK,EAAE,OAAO;IACd,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CAAC,8DAA8D,CAAC,CAAC;IAC3E,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzB,CAAC;IACD,2FAA2F;IAC3F,0FAAwF;IACxF,+EAA+E;IAC/E,KAAK,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;QAC5B,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,gBAAgB,EAAE,4BAA4B,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,uEAAuE,CAAC,CAAC;IACpF,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn parts.join(\" \").trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\treturn clampText(text.replace(/\\s+/g, \" \").trim(), maxLen);\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, 160);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear in ## Files, containment threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watchdogs.d.ts","sourceRoot":"","sources":["../../src/reliability/watchdogs.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,eAAe;IAC/B;sFACkF;IAClF,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,wDAAwD;IACxD,MAAM,IAAI,IAAI,CAAC;CACf;AAED,MAAM,WAAW,sBAAsB;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,SAAS,EAAE,MAAM,IAAI,CAAC;CACtB;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,eAAe,CA8BnF;AAYD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,QAAQ,CAAC;AAExD,MAAM,WAAW,iBAAiB;IACjC,6EAA6E;IAC7E,SAAS,EAAE,MAAM,CAAC;IAClB;0FACsF;IACtF,YAAY,EAAE,MAAM,CAAC;IACrB;;;oEAGgE;IAChE,WAAW,EAAE,MAAM,CAAC;IACpB,gFAAgF;IAChF,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,UAAU,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CACnE;AAED;;8FAE8F;AAC9F,eAAO,MAAM,mBAAmB,EAAE,iBAIjC,CAAC;AAEF,0FAA0F;AAC1F,MAAM,MAAM,yBAAyB,GAAG,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAStG;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,sBAAsB,CACrC,QAAQ,EAAE,QAAQ,EAClB,OAAO,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,yBAAyB,GAC9D,QAAQ,CAuJV","sourcesContent":["/**\n * Silence/idle watchdogs for the reliability kernel.\n *\n * A silence watchdog bounds \"running but mute\" — it never bounds total runtime,\n * so long tasks that produce output are never killed (autonomy constraint).\n */\n\nexport interface SilenceWatchdog {\n\t/** Report activity (output chunk / stream event); resets the countdown.\n\t * Pass silenceMs to also change the bound for this and subsequent countdowns. */\n\ttouch(silenceMs?: number): void;\n\t/** Stop permanently (normal completion). Idempotent. */\n\tdisarm(): void;\n}\n\nexport interface SilenceWatchdogOptions {\n\tsilenceMs: number;\n\t/** Fired at most once, after silenceMs with no touch(). The watchdog self-disarms. */\n\tonSilence: () => void;\n}\n\nexport function createSilenceWatchdog(opts: SilenceWatchdogOptions): SilenceWatchdog {\n\tlet timer: NodeJS.Timeout | undefined;\n\tlet disarmed = false;\n\tlet currentSilenceMs = opts.silenceMs;\n\n\tconst arm = () => {\n\t\ttimer = setTimeout(() => {\n\t\t\tdisarmed = true;\n\t\t\ttimer = undefined;\n\t\t\topts.onSilence();\n\t\t}, currentSilenceMs);\n\t\t// Never keep the host process alive just for a watchdog.\n\t\ttimer.unref?.();\n\t};\n\n\tarm();\n\n\treturn {\n\t\ttouch(silenceMs?: number): void {\n\t\t\tif (disarmed) return;\n\t\t\tif (silenceMs !== undefined) currentSilenceMs = silenceMs;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tarm();\n\t\t},\n\t\tdisarm(): void {\n\t\t\tdisarmed = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t},\n\t};\n}\n\n// --- Stream-idle watchdog (wraps a StreamFn) -------------------------------\n\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\ttype ProviderResponse,\n} from \"@caupulican/pi-ai\";\nimport type { StreamFn } from \"../types.ts\";\n\nexport type StallPhase = \"connect\" | \"quiet\" | \"active\";\n\nexport interface StreamIdleOptions {\n\t/** Max ms to wait for the FIRST event (connection/first-token allowance). */\n\tconnectMs: number;\n\t/** Max ms between events while content is flowing — the latest content block is\n\t * text or toolCall. A flowing stream that goes silent this long is presumed dead. */\n\tactiveIdleMs: number;\n\t/** Max ms between events while the model is quietly working — no content blocks\n\t * yet (provider queue / prompt prefill / unstreamed reasoning) or the latest block\n\t * is thinking. Deep-thinking models and huge compaction prompts legitimately sit\n\t * here for minutes, so this bound is deliberately generous. */\n\tquietIdleMs: number;\n\t/** Fired once when a stall is detected, before the inner request is aborted. */\n\tonStall?: (info: { phase: StallPhase; elapsedMs: number }) => void;\n}\n\n/** User-locked defaults: connect 120s / active 180s / quiet 600s. The quiet bound must stay\n * below the HTTP dispatcher idle timeout (see coding-agent http-dispatcher.ts, 660s) or the\n * HTTP layer would kill quiet-but-healthy streams before this watchdog ever sees the gap. */\nexport const DEFAULT_STREAM_IDLE: StreamIdleOptions = {\n\tconnectMs: 120_000,\n\tactiveIdleMs: 180_000,\n\tquietIdleMs: 600_000,\n};\n\n/** Re-resolved at the start of every request, so hosts can wire live-tunable settings. */\nexport type StreamIdleOptionsResolver = (...args: Parameters<StreamFn>) => Partial<StreamIdleOptions>;\n\n/** Extracts the current AssistantMessage snapshot carried by any stream event variant. */\nfunction partialFromEvent(event: AssistantMessageEvent): AssistantMessage {\n\tif (event.type === \"done\") return event.message;\n\tif (event.type === \"error\") return event.error;\n\treturn event.partial;\n}\n\n/**\n * Wrap a StreamFn so a silently dead connection cannot wedge a turn forever.\n *\n * Phase-aware: `connectMs` bounds the wait for the first event; after that the\n * inter-event bound adapts to what the stream is doing — `quietIdleMs` while the\n * model is quietly working (no content blocks yet, or the latest block is thinking:\n * prefill, provider queues, unstreamed reasoning) and `activeIdleMs` once content is\n * flowing (latest block is text/toolCall). This keeps detection fast where silence is\n * anomalous without killing healthy deep-thinking or compaction-sized requests.\n * No bound ever limits total runtime (autonomy constraint).\n *\n * On stall, the inner request is aborted and the returned stream resolves immediately\n * with a synthetic `AssistantMessage` (`stopReason: \"error\"`, `errorMessage: \"stream\n * stalled: no events for <n>ms (<phase> phase)\"`) — the `stream stalled` phrasing is\n * what `classifyFailure` maps to a retryable `stream_stall`, so the host's\n * retry/failover path takes it from there.\n *\n * Options may be a resolver function; it is re-invoked at the start of every request,\n * so settings changes apply without rewrapping.\n *\n * A caller-initiated abort (via the options `signal`) is never treated as a stall: it\n * is chained into the wrapper's own controller. The inner stream's abort result is\n * forwarded untouched when it provides one; if it just ends, the wrapper synthesizes\n * an aborted terminal event so the returned stream always settles.\n */\nexport function withStreamIdleWatchdog(\n\tstreamFn: StreamFn,\n\toptions?: Partial<StreamIdleOptions> | StreamIdleOptionsResolver,\n): StreamFn {\n\treturn async (model, context, streamOptions) => {\n\t\tconst resolved = typeof options === \"function\" ? options(model, context, streamOptions) : options;\n\t\tconst cleaned: Partial<StreamIdleOptions> = {};\n\t\tif (resolved) {\n\t\t\tfor (const [key, val] of Object.entries(resolved)) {\n\t\t\t\tif (val !== undefined) {\n\t\t\t\t\t(cleaned as any)[key] = val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst opts = { ...DEFAULT_STREAM_IDLE, ...cleaned };\n\n\t\tconst controller = new AbortController();\n\t\tconst callerSignal = streamOptions?.signal;\n\t\tlet callerAborted = callerSignal?.aborted ?? false;\n\t\tconst onCallerAbort = () => {\n\t\t\tcallerAborted = true;\n\t\t\tcontroller.abort(callerSignal?.reason);\n\t\t};\n\t\tif (callerAborted) controller.abort(callerSignal?.reason);\n\t\telse callerSignal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n\n\t\tconst outer = createAssistantMessageEventStream();\n\n\t\t// Seeded so a connect-phase stall (no event ever arrived) still has a base message\n\t\t// to report on; overwritten with the latest real snapshot once events start flowing.\n\t\tlet latest: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tlet stalled = false;\n\t\tlet firstEventSeen = false;\n\t\tlet transportConfirmed = false;\n\n\t\t// The idle bound adapts per event: quiet while nothing/thinking, active while\n\t\t// text/toolCall content is flowing. Mutable so the onSilence closure always\n\t\t// reports the phase/bound that actually elapsed.\n\t\tlet currentPhase: StallPhase = \"connect\";\n\t\tlet currentBoundMs = opts.connectMs;\n\t\tconst idleBoundFor = (message: AssistantMessage): { phase: StallPhase; ms: number } => {\n\t\t\tconst lastBlock = message.content[message.content.length - 1];\n\t\t\treturn !lastBlock || lastBlock.type === \"thinking\"\n\t\t\t\t? { phase: \"quiet\", ms: opts.quietIdleMs }\n\t\t\t\t: { phase: \"active\", ms: opts.activeIdleMs };\n\t\t};\n\n\t\t// Emits the stall result directly (rather than after the inner loop finishes) so a\n\t\t// connection that never resolves at all still yields a result promptly — providers\n\t\t// are contractually expected to end their stream after abort, but the watchdog does\n\t\t// not depend on that to report the stall itself.\n\t\tconst stall = (phase: StallPhase, elapsedMs: number) => {\n\t\t\tif (callerAborted || stalled) return;\n\t\t\tstalled = true;\n\t\t\topts.onStall?.({ phase, elapsedMs });\n\t\t\tconst description = `stream stalled: no events for ${elapsedMs}ms (${phase} phase)`;\n\t\t\tcontroller.abort(new Error(description));\n\t\t\tconst message: AssistantMessage = {\n\t\t\t\t...latest,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: description,\n\t\t\t};\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t};\n\n\t\tlet watchdog = createSilenceWatchdog({\n\t\t\tsilenceMs: opts.connectMs,\n\t\t\tonSilence: () => stall(currentPhase, currentBoundMs),\n\t\t});\n\t\tconst markTransportConfirmed = () => {\n\t\t\tif (callerAborted || stalled || firstEventSeen || transportConfirmed) return;\n\t\t\ttransportConfirmed = true;\n\t\t\tcurrentPhase = \"quiet\";\n\t\t\tcurrentBoundMs = opts.quietIdleMs;\n\t\t\twatchdog.touch(opts.quietIdleMs);\n\t\t};\n\t\tconst originalOnResponse = streamOptions?.onResponse;\n\t\tconst inner = await streamFn(model, context, {\n\t\t\t...streamOptions,\n\t\t\tsignal: controller.signal,\n\t\t\tonResponse: async (response: ProviderResponse, responseModel: Model<Api>) => {\n\t\t\t\tmarkTransportConfirmed();\n\t\t\t\tawait originalOnResponse?.(response, responseModel);\n\t\t\t},\n\t\t});\n\t\tlet terminalPushed = false;\n\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor await (const event of inner) {\n\t\t\t\t\tif (stalled) break;\n\t\t\t\t\tlatest = partialFromEvent(event);\n\t\t\t\t\tconst bound = idleBoundFor(latest);\n\t\t\t\t\tcurrentPhase = bound.phase;\n\t\t\t\t\tcurrentBoundMs = bound.ms;\n\t\t\t\t\tif (!firstEventSeen) {\n\t\t\t\t\t\tfirstEventSeen = true;\n\t\t\t\t\t\twatchdog.disarm();\n\t\t\t\t\t\twatchdog = createSilenceWatchdog({\n\t\t\t\t\t\t\tsilenceMs: bound.ms,\n\t\t\t\t\t\t\tonSilence: () => stall(currentPhase, currentBoundMs),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\twatchdog.touch(bound.ms);\n\t\t\t\t\t}\n\t\t\t\t\t// A terminal event ends the turn: disarm synchronously, in the same tick as\n\t\t\t\t\t// the push below, so no watchdog can fire after the consumer's `result()`\n\t\t\t\t\t// promise resolves — a disarm that only happened once the loop later notices\n\t\t\t\t\t// `inner` is done would race with that resolution (it runs a tick or more\n\t\t\t\t\t// later) and could fire a spurious stall on an already-finished stream.\n\t\t\t\t\tconst terminal = event.type === \"done\" || event.type === \"error\";\n\t\t\t\t\tif (terminal) {\n\t\t\t\t\t\tterminalPushed = true;\n\t\t\t\t\t\twatchdog.disarm();\n\t\t\t\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t\t\t\t}\n\t\t\t\t\touter.push(event);\n\t\t\t\t\tif (terminal) return;\n\t\t\t\t}\n\t\t\t\tif (!terminalPushed && !stalled) {\n\t\t\t\t\tconst stopReason = callerAborted ? \"aborted\" : \"error\";\n\t\t\t\t\tconst description = callerAborted\n\t\t\t\t\t\t? \"stream aborted before terminal event\"\n\t\t\t\t\t\t: \"stream ended before terminal event\";\n\t\t\t\t\touter.push({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\treason: stopReason,\n\t\t\t\t\t\terror: { ...latest, stopReason, errorMessage: description },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\twatchdog.disarm();\n\t\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t\t}\n\t\t})();\n\n\t\treturn outer;\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"watchdogs.d.ts","sourceRoot":"","sources":["../../src/reliability/watchdogs.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,eAAe;IAC/B;sFACkF;IAClF,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,wDAAwD;IACxD,MAAM,IAAI,IAAI,CAAC;CACf;AAED,MAAM,WAAW,sBAAsB;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,SAAS,EAAE,MAAM,IAAI,CAAC;CACtB;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,eAAe,CA8BnF;AAYD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,QAAQ,CAAC;AAExD,MAAM,WAAW,iBAAiB;IACjC,6EAA6E;IAC7E,SAAS,EAAE,MAAM,CAAC;IAClB;0FACsF;IACtF,YAAY,EAAE,MAAM,CAAC;IACrB;;;oEAGgE;IAChE,WAAW,EAAE,MAAM,CAAC;IACpB,gFAAgF;IAChF,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,UAAU,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CACnE;AAED;;8FAE8F;AAC9F,eAAO,MAAM,mBAAmB,EAAE,iBAIjC,CAAC;AAEF,0FAA0F;AAC1F,MAAM,MAAM,yBAAyB,GAAG,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAStG;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,sBAAsB,CACrC,QAAQ,EAAE,QAAQ,EAClB,OAAO,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,yBAAyB,GAC9D,QAAQ,CAyOV","sourcesContent":["/**\n * Silence/idle watchdogs for the reliability kernel.\n *\n * A silence watchdog bounds \"running but mute\" — it never bounds total runtime,\n * so long tasks that produce output are never killed (autonomy constraint).\n */\n\nexport interface SilenceWatchdog {\n\t/** Report activity (output chunk / stream event); resets the countdown.\n\t * Pass silenceMs to also change the bound for this and subsequent countdowns. */\n\ttouch(silenceMs?: number): void;\n\t/** Stop permanently (normal completion). Idempotent. */\n\tdisarm(): void;\n}\n\nexport interface SilenceWatchdogOptions {\n\tsilenceMs: number;\n\t/** Fired at most once, after silenceMs with no touch(). The watchdog self-disarms. */\n\tonSilence: () => void;\n}\n\nexport function createSilenceWatchdog(opts: SilenceWatchdogOptions): SilenceWatchdog {\n\tlet timer: NodeJS.Timeout | undefined;\n\tlet disarmed = false;\n\tlet currentSilenceMs = opts.silenceMs;\n\n\tconst arm = () => {\n\t\ttimer = setTimeout(() => {\n\t\t\tdisarmed = true;\n\t\t\ttimer = undefined;\n\t\t\topts.onSilence();\n\t\t}, currentSilenceMs);\n\t\t// Never keep the host process alive just for a watchdog.\n\t\ttimer.unref?.();\n\t};\n\n\tarm();\n\n\treturn {\n\t\ttouch(silenceMs?: number): void {\n\t\t\tif (disarmed) return;\n\t\t\tif (silenceMs !== undefined) currentSilenceMs = silenceMs;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tarm();\n\t\t},\n\t\tdisarm(): void {\n\t\t\tdisarmed = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t},\n\t};\n}\n\n// --- Stream-idle watchdog (wraps a StreamFn) -------------------------------\n\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\ttype ProviderResponse,\n} from \"@caupulican/pi-ai\";\nimport type { StreamFn } from \"../types.ts\";\n\nexport type StallPhase = \"connect\" | \"quiet\" | \"active\";\n\nexport interface StreamIdleOptions {\n\t/** Max ms to wait for the FIRST event (connection/first-token allowance). */\n\tconnectMs: number;\n\t/** Max ms between events while content is flowing — the latest content block is\n\t * text or toolCall. A flowing stream that goes silent this long is presumed dead. */\n\tactiveIdleMs: number;\n\t/** Max ms between events while the model is quietly working — no content blocks\n\t * yet (provider queue / prompt prefill / unstreamed reasoning) or the latest block\n\t * is thinking. Deep-thinking models and huge compaction prompts legitimately sit\n\t * here for minutes, so this bound is deliberately generous. */\n\tquietIdleMs: number;\n\t/** Fired once when a stall is detected, before the inner request is aborted. */\n\tonStall?: (info: { phase: StallPhase; elapsedMs: number }) => void;\n}\n\n/** User-locked defaults: connect 120s / active 180s / quiet 600s. The quiet bound must stay\n * below the HTTP dispatcher idle timeout (see coding-agent http-dispatcher.ts, 660s) or the\n * HTTP layer would kill quiet-but-healthy streams before this watchdog ever sees the gap. */\nexport const DEFAULT_STREAM_IDLE: StreamIdleOptions = {\n\tconnectMs: 120_000,\n\tactiveIdleMs: 180_000,\n\tquietIdleMs: 600_000,\n};\n\n/** Re-resolved at the start of every request, so hosts can wire live-tunable settings. */\nexport type StreamIdleOptionsResolver = (...args: Parameters<StreamFn>) => Partial<StreamIdleOptions>;\n\n/** Extracts the current AssistantMessage snapshot carried by any stream event variant. */\nfunction partialFromEvent(event: AssistantMessageEvent): AssistantMessage {\n\tif (event.type === \"done\") return event.message;\n\tif (event.type === \"error\") return event.error;\n\treturn event.partial;\n}\n\n/**\n * Wrap a StreamFn so a silently dead connection cannot wedge a turn forever.\n *\n * Phase-aware: `connectMs` bounds the wait for the first event; after that the\n * inter-event bound adapts to what the stream is doing — `quietIdleMs` while the\n * model is quietly working (no content blocks yet, or the latest block is thinking:\n * prefill, provider queues, unstreamed reasoning) and `activeIdleMs` once content is\n * flowing (latest block is text/toolCall). This keeps detection fast where silence is\n * anomalous without killing healthy deep-thinking or compaction-sized requests.\n * No bound ever limits total runtime (autonomy constraint).\n *\n * On stall, the inner request is aborted and the returned stream resolves immediately\n * with a synthetic `AssistantMessage` (`stopReason: \"error\"`, `errorMessage: \"stream\n * stalled: no events for <n>ms (<phase> phase)\"`) — the `stream stalled` phrasing is\n * what `classifyFailure` maps to a retryable `stream_stall`, so the host's\n * retry/failover path takes it from there.\n *\n * Options may be a resolver function; it is re-invoked at the start of every request,\n * so settings changes apply without rewrapping.\n *\n * A caller-initiated abort (via the options `signal`) is never treated as a stall: it\n * is chained into the wrapper's own controller. The inner stream's abort result is\n * forwarded untouched when it provides one; if it just ends, the wrapper synthesizes\n * an aborted terminal event so the returned stream always settles.\n */\nexport function withStreamIdleWatchdog(\n\tstreamFn: StreamFn,\n\toptions?: Partial<StreamIdleOptions> | StreamIdleOptionsResolver,\n): StreamFn {\n\treturn (model, context, streamOptions) => {\n\t\tconst resolved = typeof options === \"function\" ? options(model, context, streamOptions) : options;\n\t\tconst cleaned: Partial<StreamIdleOptions> = {};\n\t\tif (resolved) {\n\t\t\tfor (const [key, val] of Object.entries(resolved)) {\n\t\t\t\tif (val !== undefined) {\n\t\t\t\t\t(cleaned as any)[key] = val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst opts = { ...DEFAULT_STREAM_IDLE, ...cleaned };\n\n\t\tconst controller = new AbortController();\n\t\tconst callerSignal = streamOptions?.signal;\n\t\tlet callerAborted = callerSignal?.aborted ?? false;\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tlet readySettled = false;\n\t\tlet resolveReady: (stream: typeof outer) => void = () => {};\n\t\tconst ready = new Promise<typeof outer>((resolve) => {\n\t\t\tresolveReady = resolve;\n\t\t});\n\t\tconst settleReady = () => {\n\t\t\tif (readySettled) return;\n\t\t\treadySettled = true;\n\t\t\tresolveReady(outer);\n\t\t};\n\n\t\t// Seeded so a connect-phase stall (no event ever arrived) still has a base message\n\t\t// to report on; overwritten with the latest real snapshot once events start flowing.\n\t\tlet latest: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tlet stalled = false;\n\t\tlet firstEventSeen = false;\n\t\tlet transportConfirmed = false;\n\t\tlet streamSetupSettled = false;\n\t\tlet terminalPushed = false;\n\n\t\t// The idle bound adapts per event: quiet while nothing/thinking, active while\n\t\t// text/toolCall content is flowing. Mutable so the onSilence closure always\n\t\t// reports the phase/bound that actually elapsed.\n\t\tlet currentPhase: StallPhase = \"connect\";\n\t\tlet currentBoundMs = opts.connectMs;\n\t\tconst idleBoundFor = (message: AssistantMessage): { phase: StallPhase; ms: number } => {\n\t\t\tconst lastBlock = message.content[message.content.length - 1];\n\t\t\treturn !lastBlock || lastBlock.type === \"thinking\"\n\t\t\t\t? { phase: \"quiet\", ms: opts.quietIdleMs }\n\t\t\t\t: { phase: \"active\", ms: opts.activeIdleMs };\n\t\t};\n\n\t\t// Emits the stall result directly (rather than after the inner loop finishes) so a\n\t\t// connection that never resolves at all still yields a result promptly — providers\n\t\t// are contractually expected to end their stream after abort, but the watchdog does\n\t\t// not depend on that to report the stall itself.\n\t\tconst stall = (phase: StallPhase, elapsedMs: number) => {\n\t\t\tif (callerAborted || stalled || terminalPushed) return;\n\t\t\tstalled = true;\n\t\t\topts.onStall?.({ phase, elapsedMs });\n\t\t\tconst description = `stream stalled: no events for ${elapsedMs}ms (${phase} phase)`;\n\t\t\tcontroller.abort(new Error(description));\n\t\t\tconst message: AssistantMessage = {\n\t\t\t\t...latest,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: description,\n\t\t\t};\n\t\t\tterminalPushed = true;\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\tsettleReady();\n\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t};\n\n\t\tlet watchdog = createSilenceWatchdog({\n\t\t\tsilenceMs: opts.connectMs,\n\t\t\tonSilence: () => stall(currentPhase, currentBoundMs),\n\t\t});\n\t\tconst markTransportConfirmed = () => {\n\t\t\tif (callerAborted || stalled || firstEventSeen || transportConfirmed) return;\n\t\t\ttransportConfirmed = true;\n\t\t\tcurrentPhase = \"quiet\";\n\t\t\tcurrentBoundMs = opts.quietIdleMs;\n\t\t\twatchdog.touch(opts.quietIdleMs);\n\t\t};\n\t\tconst originalOnResponse = streamOptions?.onResponse;\n\t\tconst pushSetupAbort = () => {\n\t\t\tif (streamSetupSettled || terminalPushed || stalled) return;\n\t\t\tterminalPushed = true;\n\t\t\twatchdog.disarm();\n\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t\touter.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason: \"aborted\",\n\t\t\t\terror: {\n\t\t\t\t\t...latest,\n\t\t\t\t\tstopReason: \"aborted\",\n\t\t\t\t\terrorMessage: \"stream aborted before terminal event during stream setup\",\n\t\t\t\t},\n\t\t\t});\n\t\t\tsettleReady();\n\t\t};\n\t\tconst onCallerAbort = () => {\n\t\t\tcallerAborted = true;\n\t\t\tcontroller.abort(callerSignal?.reason);\n\t\t\tpushSetupAbort();\n\t\t};\n\t\tif (callerAborted) {\n\t\t\tonCallerAbort();\n\t\t\treturn ready;\n\t\t}\n\t\tcallerSignal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tlet inner: Awaited<ReturnType<StreamFn>>;\n\t\t\t\ttry {\n\t\t\t\t\tinner = await streamFn(model, context, {\n\t\t\t\t\t\t...streamOptions,\n\t\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\t\tonResponse: async (response: ProviderResponse, responseModel: Model<Api>) => {\n\t\t\t\t\t\t\tmarkTransportConfirmed();\n\t\t\t\t\t\t\tawait originalOnResponse?.(response, responseModel);\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tstreamSetupSettled = true;\n\t\t\t\t\tsettleReady();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tstreamSetupSettled = true;\n\t\t\t\t\tif (terminalPushed || stalled) return;\n\t\t\t\t\twatchdog.disarm();\n\t\t\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t\t\t\tconst stopReason = callerAborted ? \"aborted\" : \"error\";\n\t\t\t\t\tconst detail = error instanceof Error ? `: ${error.message}` : `: ${String(error)}`;\n\t\t\t\t\tterminalPushed = true;\n\t\t\t\t\touter.push({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\treason: stopReason,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t...latest,\n\t\t\t\t\t\t\tstopReason,\n\t\t\t\t\t\t\terrorMessage: callerAborted\n\t\t\t\t\t\t\t\t? `stream aborted before terminal event${detail}`\n\t\t\t\t\t\t\t\t: `stream ended without terminal event${detail}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tsettleReady();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// A setup promise may resolve after a connect stall or caller abort. The outer\n\t\t\t\t// stream is already terminal in that case, so never attach a late event pump.\n\t\t\t\tif (terminalPushed || stalled || callerAborted) return;\n\t\t\t\tfor await (const event of inner) {\n\t\t\t\t\tif (stalled) break;\n\t\t\t\t\tlatest = partialFromEvent(event);\n\t\t\t\t\tconst bound = idleBoundFor(latest);\n\t\t\t\t\tcurrentPhase = bound.phase;\n\t\t\t\t\tcurrentBoundMs = bound.ms;\n\t\t\t\t\tif (!firstEventSeen) {\n\t\t\t\t\t\tfirstEventSeen = true;\n\t\t\t\t\t\twatchdog.disarm();\n\t\t\t\t\t\twatchdog = createSilenceWatchdog({\n\t\t\t\t\t\t\tsilenceMs: bound.ms,\n\t\t\t\t\t\t\tonSilence: () => stall(currentPhase, currentBoundMs),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\twatchdog.touch(bound.ms);\n\t\t\t\t\t}\n\t\t\t\t\t// A terminal event ends the turn: disarm synchronously, in the same tick as\n\t\t\t\t\t// the push below, so no watchdog can fire after the consumer's `result()`\n\t\t\t\t\t// promise resolves — a disarm that only happened once the loop later notices\n\t\t\t\t\t// `inner` is done would race with that resolution (it runs a tick or more\n\t\t\t\t\t// later) and could fire a spurious stall on an already-finished stream.\n\t\t\t\t\tconst terminal = event.type === \"done\" || event.type === \"error\";\n\t\t\t\t\tif (terminal) {\n\t\t\t\t\t\tterminalPushed = true;\n\t\t\t\t\t\twatchdog.disarm();\n\t\t\t\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t\t\t\t}\n\t\t\t\t\touter.push(event);\n\t\t\t\t\tif (terminal) return;\n\t\t\t\t}\n\t\t\t\tif (!terminalPushed && !stalled) {\n\t\t\t\t\tconst stopReason = callerAborted ? \"aborted\" : \"error\";\n\t\t\t\t\tconst description = callerAborted\n\t\t\t\t\t\t? \"stream aborted before terminal event\"\n\t\t\t\t\t\t: \"stream ended without terminal event\";\n\t\t\t\t\tterminalPushed = true;\n\t\t\t\t\touter.push({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\treason: stopReason,\n\t\t\t\t\t\terror: { ...latest, stopReason, errorMessage: description },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (!terminalPushed && !stalled) {\n\t\t\t\t\tconst stopReason = callerAborted ? \"aborted\" : \"error\";\n\t\t\t\t\tconst detail = error instanceof Error ? `: ${error.message}` : `: ${String(error)}`;\n\t\t\t\t\tterminalPushed = true;\n\t\t\t\t\touter.push({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\treason: stopReason,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t...latest,\n\t\t\t\t\t\t\tstopReason,\n\t\t\t\t\t\t\terrorMessage: callerAborted\n\t\t\t\t\t\t\t\t? `stream aborted before terminal event${detail}`\n\t\t\t\t\t\t\t\t: `stream ended without terminal event${detail}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tsettleReady();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\twatchdog.disarm();\n\t\t\t\tcallerSignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t\t}\n\t\t})();\n\n\t\treturn ready;\n\t};\n}\n"]}
|
|
@@ -80,7 +80,7 @@ function partialFromEvent(event) {
|
|
|
80
80
|
* an aborted terminal event so the returned stream always settles.
|
|
81
81
|
*/
|
|
82
82
|
export function withStreamIdleWatchdog(streamFn, options) {
|
|
83
|
-
return
|
|
83
|
+
return (model, context, streamOptions) => {
|
|
84
84
|
const resolved = typeof options === "function" ? options(model, context, streamOptions) : options;
|
|
85
85
|
const cleaned = {};
|
|
86
86
|
if (resolved) {
|
|
@@ -94,15 +94,18 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
94
94
|
const controller = new AbortController();
|
|
95
95
|
const callerSignal = streamOptions?.signal;
|
|
96
96
|
let callerAborted = callerSignal?.aborted ?? false;
|
|
97
|
-
const onCallerAbort = () => {
|
|
98
|
-
callerAborted = true;
|
|
99
|
-
controller.abort(callerSignal?.reason);
|
|
100
|
-
};
|
|
101
|
-
if (callerAborted)
|
|
102
|
-
controller.abort(callerSignal?.reason);
|
|
103
|
-
else
|
|
104
|
-
callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
105
97
|
const outer = createAssistantMessageEventStream();
|
|
98
|
+
let readySettled = false;
|
|
99
|
+
let resolveReady = () => { };
|
|
100
|
+
const ready = new Promise((resolve) => {
|
|
101
|
+
resolveReady = resolve;
|
|
102
|
+
});
|
|
103
|
+
const settleReady = () => {
|
|
104
|
+
if (readySettled)
|
|
105
|
+
return;
|
|
106
|
+
readySettled = true;
|
|
107
|
+
resolveReady(outer);
|
|
108
|
+
};
|
|
106
109
|
// Seeded so a connect-phase stall (no event ever arrived) still has a base message
|
|
107
110
|
// to report on; overwritten with the latest real snapshot once events start flowing.
|
|
108
111
|
let latest = {
|
|
@@ -125,6 +128,8 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
125
128
|
let stalled = false;
|
|
126
129
|
let firstEventSeen = false;
|
|
127
130
|
let transportConfirmed = false;
|
|
131
|
+
let streamSetupSettled = false;
|
|
132
|
+
let terminalPushed = false;
|
|
128
133
|
// The idle bound adapts per event: quiet while nothing/thinking, active while
|
|
129
134
|
// text/toolCall content is flowing. Mutable so the onSilence closure always
|
|
130
135
|
// reports the phase/bound that actually elapsed.
|
|
@@ -141,7 +146,7 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
141
146
|
// are contractually expected to end their stream after abort, but the watchdog does
|
|
142
147
|
// not depend on that to report the stall itself.
|
|
143
148
|
const stall = (phase, elapsedMs) => {
|
|
144
|
-
if (callerAborted || stalled)
|
|
149
|
+
if (callerAborted || stalled || terminalPushed)
|
|
145
150
|
return;
|
|
146
151
|
stalled = true;
|
|
147
152
|
opts.onStall?.({ phase, elapsedMs });
|
|
@@ -152,7 +157,10 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
152
157
|
stopReason: "error",
|
|
153
158
|
errorMessage: description,
|
|
154
159
|
};
|
|
160
|
+
terminalPushed = true;
|
|
155
161
|
outer.push({ type: "error", reason: "error", error: message });
|
|
162
|
+
settleReady();
|
|
163
|
+
callerSignal?.removeEventListener("abort", onCallerAbort);
|
|
156
164
|
};
|
|
157
165
|
let watchdog = createSilenceWatchdog({
|
|
158
166
|
silenceMs: opts.connectMs,
|
|
@@ -167,17 +175,75 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
167
175
|
watchdog.touch(opts.quietIdleMs);
|
|
168
176
|
};
|
|
169
177
|
const originalOnResponse = streamOptions?.onResponse;
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
178
|
+
const pushSetupAbort = () => {
|
|
179
|
+
if (streamSetupSettled || terminalPushed || stalled)
|
|
180
|
+
return;
|
|
181
|
+
terminalPushed = true;
|
|
182
|
+
watchdog.disarm();
|
|
183
|
+
callerSignal?.removeEventListener("abort", onCallerAbort);
|
|
184
|
+
outer.push({
|
|
185
|
+
type: "error",
|
|
186
|
+
reason: "aborted",
|
|
187
|
+
error: {
|
|
188
|
+
...latest,
|
|
189
|
+
stopReason: "aborted",
|
|
190
|
+
errorMessage: "stream aborted before terminal event during stream setup",
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
settleReady();
|
|
194
|
+
};
|
|
195
|
+
const onCallerAbort = () => {
|
|
196
|
+
callerAborted = true;
|
|
197
|
+
controller.abort(callerSignal?.reason);
|
|
198
|
+
pushSetupAbort();
|
|
199
|
+
};
|
|
200
|
+
if (callerAborted) {
|
|
201
|
+
onCallerAbort();
|
|
202
|
+
return ready;
|
|
203
|
+
}
|
|
204
|
+
callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
179
205
|
void (async () => {
|
|
180
206
|
try {
|
|
207
|
+
let inner;
|
|
208
|
+
try {
|
|
209
|
+
inner = await streamFn(model, context, {
|
|
210
|
+
...streamOptions,
|
|
211
|
+
signal: controller.signal,
|
|
212
|
+
onResponse: async (response, responseModel) => {
|
|
213
|
+
markTransportConfirmed();
|
|
214
|
+
await originalOnResponse?.(response, responseModel);
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
streamSetupSettled = true;
|
|
218
|
+
settleReady();
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
streamSetupSettled = true;
|
|
222
|
+
if (terminalPushed || stalled)
|
|
223
|
+
return;
|
|
224
|
+
watchdog.disarm();
|
|
225
|
+
callerSignal?.removeEventListener("abort", onCallerAbort);
|
|
226
|
+
const stopReason = callerAborted ? "aborted" : "error";
|
|
227
|
+
const detail = error instanceof Error ? `: ${error.message}` : `: ${String(error)}`;
|
|
228
|
+
terminalPushed = true;
|
|
229
|
+
outer.push({
|
|
230
|
+
type: "error",
|
|
231
|
+
reason: stopReason,
|
|
232
|
+
error: {
|
|
233
|
+
...latest,
|
|
234
|
+
stopReason,
|
|
235
|
+
errorMessage: callerAborted
|
|
236
|
+
? `stream aborted before terminal event${detail}`
|
|
237
|
+
: `stream ended without terminal event${detail}`,
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
settleReady();
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
// A setup promise may resolve after a connect stall or caller abort. The outer
|
|
244
|
+
// stream is already terminal in that case, so never attach a late event pump.
|
|
245
|
+
if (terminalPushed || stalled || callerAborted)
|
|
246
|
+
return;
|
|
181
247
|
for await (const event of inner) {
|
|
182
248
|
if (stalled)
|
|
183
249
|
break;
|
|
@@ -215,7 +281,8 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
215
281
|
const stopReason = callerAborted ? "aborted" : "error";
|
|
216
282
|
const description = callerAborted
|
|
217
283
|
? "stream aborted before terminal event"
|
|
218
|
-
: "stream ended
|
|
284
|
+
: "stream ended without terminal event";
|
|
285
|
+
terminalPushed = true;
|
|
219
286
|
outer.push({
|
|
220
287
|
type: "error",
|
|
221
288
|
reason: stopReason,
|
|
@@ -223,12 +290,31 @@ export function withStreamIdleWatchdog(streamFn, options) {
|
|
|
223
290
|
});
|
|
224
291
|
}
|
|
225
292
|
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
if (!terminalPushed && !stalled) {
|
|
295
|
+
const stopReason = callerAborted ? "aborted" : "error";
|
|
296
|
+
const detail = error instanceof Error ? `: ${error.message}` : `: ${String(error)}`;
|
|
297
|
+
terminalPushed = true;
|
|
298
|
+
outer.push({
|
|
299
|
+
type: "error",
|
|
300
|
+
reason: stopReason,
|
|
301
|
+
error: {
|
|
302
|
+
...latest,
|
|
303
|
+
stopReason,
|
|
304
|
+
errorMessage: callerAborted
|
|
305
|
+
? `stream aborted before terminal event${detail}`
|
|
306
|
+
: `stream ended without terminal event${detail}`,
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
settleReady();
|
|
310
|
+
}
|
|
311
|
+
}
|
|
226
312
|
finally {
|
|
227
313
|
watchdog.disarm();
|
|
228
314
|
callerSignal?.removeEventListener("abort", onCallerAbort);
|
|
229
315
|
}
|
|
230
316
|
})();
|
|
231
|
-
return
|
|
317
|
+
return ready;
|
|
232
318
|
};
|
|
233
319
|
}
|
|
234
320
|
//# sourceMappingURL=watchdogs.js.map
|