@draht/coding-agent 2026.10.4 → 2026.10.8
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 +13 -0
- package/README.md +32 -6
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-2VAF4XJI.js} +1 -1
- package/dist/bundle/chunks/chunk-6APPDDHH.js +65 -0
- package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-JFDPOIUH.js} +1 -1
- package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-KU5HAKZL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-MIUVNYYW.js} +292 -153
- package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-NHTOADU6.js} +2 -2
- package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-OWGSPJPZ.js} +4 -4
- package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
- package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
- package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-TJ3AW62W.js} +1 -1
- package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-U7Y4VNNI.js} +1 -1
- package/dist/bundle/chunks/execute-ZWB4PIQQ.js +18 -0
- package/dist/bundle/chunks/google-antigravity.js +1 -1
- package/dist/bundle/chunks/google-gemini-cli.js +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-363BOYEO.js +3 -0
- package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-PXJK4L7Y.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-GEOZJXFQ.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-BEJ4ZJ3D.js +2 -0
- package/dist/bundle/chunks/xai.js +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +3 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +5 -2
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +65 -27
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/index.d.ts.map +1 -1
- package/dist/core/builtins/index.js +2 -0
- package/dist/core/builtins/index.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts +15 -0
- package/dist/core/builtins/polyphase.d.ts.map +1 -0
- package/dist/core/builtins/polyphase.js +196 -0
- package/dist/core/builtins/polyphase.js.map +1 -0
- package/dist/core/builtins/subagent.d.ts +44 -34
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +827 -560
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/types.d.ts +17 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +30 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-resolver.js +4 -4
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +4 -1
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +35 -0
- package/dist/core/polyphase/approval.d.ts.map +1 -0
- package/dist/core/polyphase/approval.js +184 -0
- package/dist/core/polyphase/approval.js.map +1 -0
- package/dist/core/polyphase/child-events.d.ts +107 -0
- package/dist/core/polyphase/child-events.d.ts.map +1 -0
- package/dist/core/polyphase/child-events.js +862 -0
- package/dist/core/polyphase/child-events.js.map +1 -0
- package/dist/core/polyphase/child-process.d.ts +65 -0
- package/dist/core/polyphase/child-process.d.ts.map +1 -0
- package/dist/core/polyphase/child-process.js +361 -0
- package/dist/core/polyphase/child-process.js.map +1 -0
- package/dist/core/polyphase/commands.d.ts +44 -0
- package/dist/core/polyphase/commands.d.ts.map +1 -0
- package/dist/core/polyphase/commands.js +244 -0
- package/dist/core/polyphase/commands.js.map +1 -0
- package/dist/core/polyphase/details.d.ts +40 -0
- package/dist/core/polyphase/details.d.ts.map +1 -0
- package/dist/core/polyphase/details.js +538 -0
- package/dist/core/polyphase/details.js.map +1 -0
- package/dist/core/polyphase/emitter.d.ts +20 -0
- package/dist/core/polyphase/emitter.d.ts.map +1 -0
- package/dist/core/polyphase/emitter.js +90 -0
- package/dist/core/polyphase/emitter.js.map +1 -0
- package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
- package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
- package/dist/core/polyphase/jsonl-reader.js +161 -0
- package/dist/core/polyphase/jsonl-reader.js.map +1 -0
- package/dist/core/polyphase/keyword.d.ts +27 -0
- package/dist/core/polyphase/keyword.d.ts.map +1 -0
- package/dist/core/polyphase/keyword.js +97 -0
- package/dist/core/polyphase/keyword.js.map +1 -0
- package/dist/core/polyphase/limiter.d.ts +38 -0
- package/dist/core/polyphase/limiter.d.ts.map +1 -0
- package/dist/core/polyphase/limiter.js +129 -0
- package/dist/core/polyphase/limiter.js.map +1 -0
- package/dist/core/polyphase/model-selection.d.ts +35 -0
- package/dist/core/polyphase/model-selection.d.ts.map +1 -0
- package/dist/core/polyphase/model-selection.js +72 -0
- package/dist/core/polyphase/model-selection.js.map +1 -0
- package/dist/core/polyphase/render/format.d.ts +52 -0
- package/dist/core/polyphase/render/format.d.ts.map +1 -0
- package/dist/core/polyphase/render/format.js +169 -0
- package/dist/core/polyphase/render/format.js.map +1 -0
- package/dist/core/polyphase/render/renderers.d.ts +63 -0
- package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
- package/dist/core/polyphase/render/renderers.js +277 -0
- package/dist/core/polyphase/render/renderers.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts +45 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
- package/dist/core/polyphase/render/run-block.js +843 -0
- package/dist/core/polyphase/render/run-block.js.map +1 -0
- package/dist/core/polyphase/render/snapshot.d.ts +106 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
- package/dist/core/polyphase/render/snapshot.js +292 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -0
- package/dist/core/polyphase/result-text.d.ts +41 -0
- package/dist/core/polyphase/result-text.d.ts.map +1 -0
- package/dist/core/polyphase/result-text.js +326 -0
- package/dist/core/polyphase/result-text.js.map +1 -0
- package/dist/core/polyphase/session.d.ts +33 -0
- package/dist/core/polyphase/session.d.ts.map +1 -0
- package/dist/core/polyphase/session.js +106 -0
- package/dist/core/polyphase/session.js.map +1 -0
- package/dist/core/polyphase/settings.d.ts +18 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -0
- package/dist/core/polyphase/settings.js +93 -0
- package/dist/core/polyphase/settings.js.map +1 -0
- package/dist/core/polyphase/store.d.ts +197 -0
- package/dist/core/polyphase/store.d.ts.map +1 -0
- package/dist/core/polyphase/store.js +558 -0
- package/dist/core/polyphase/store.js.map +1 -0
- package/dist/core/polyphase/types.d.ts +371 -0
- package/dist/core/polyphase/types.d.ts.map +1 -0
- package/dist/core/polyphase/types.js +36 -0
- package/dist/core/polyphase/types.js.map +1 -0
- package/dist/core/polyphase/ui/controller.d.ts +28 -0
- package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
- package/dist/core/polyphase/ui/controller.js +150 -0
- package/dist/core/polyphase/ui/controller.js.map +1 -0
- package/dist/core/polyphase/ui/dock.d.ts +27 -0
- package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
- package/dist/core/polyphase/ui/dock.js +121 -0
- package/dist/core/polyphase/ui/dock.js.map +1 -0
- package/dist/core/polyphase/ui/inspector.d.ts +117 -0
- package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
- package/dist/core/polyphase/ui/inspector.js +1016 -0
- package/dist/core/polyphase/ui/inspector.js.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.js +210 -0
- package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
- package/dist/core/polyphase/update-pump.d.ts +18 -0
- package/dist/core/polyphase/update-pump.d.ts.map +1 -0
- package/dist/core/polyphase/update-pump.js +132 -0
- package/dist/core/polyphase/update-pump.js.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.js +187 -0
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
- package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/guidance.js +119 -0
- package/dist/core/polyphase/workflow/guidance.js.map +1 -0
- package/dist/core/polyphase/workflow/launch.d.ts +41 -0
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/launch.js +173 -0
- package/dist/core/polyphase/workflow/launch.js.map +1 -0
- package/dist/core/polyphase/workflow/meta.d.ts +43 -0
- package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/meta.js +529 -0
- package/dist/core/polyphase/workflow/meta.js.map +1 -0
- package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
- package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/prelude.js +93 -0
- package/dist/core/polyphase/workflow/prelude.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.js +217 -0
- package/dist/core/polyphase/workflow/runtime.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
- package/dist/core/polyphase/workflow/saved.d.ts +55 -0
- package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/saved.js +299 -0
- package/dist/core/polyphase/workflow/saved.js.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.js +66 -0
- package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts +24 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/tool.js +139 -0
- package/dist/core/polyphase/workflow/tool.js.map +1 -0
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +27 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/socket-server/permission-relay.js +4 -0
- package/dist/core/socket-server/permission-relay.js.map +1 -1
- package/dist/core/trust-manager.d.ts +3 -2
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +5 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/experimental/micro/runtime.js +1 -1
- package/dist/experimental/micro/runtime.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +18 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +11 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +9 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/prompts/commands/orchestrate.md +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +7 -1
- package/dist/utils/shell.js.map +1 -1
- package/docs/docs.json +4 -0
- package/docs/duet.md +3 -3
- package/docs/environment-variables.md +11 -0
- package/docs/json.md +7 -0
- package/docs/keybindings.md +20 -0
- package/docs/polyphase.md +391 -0
- package/docs/rpc-commands.md +9 -9
- package/docs/settings.md +12 -0
- package/docs/virtual-models.md +3 -3
- package/examples/extensions/preset.ts +3 -3
- package/examples/extensions/subagent/README.md +1 -1
- package/examples/extensions/subagent/agents/planner.md +1 -1
- package/examples/extensions/subagent/agents/reviewer.md +1 -1
- package/examples/extensions/subagent/agents/scout.md +1 -1
- package/examples/extensions/subagent/agents/worker.md +1 -1
- package/examples/extensions/summarize.ts +3 -3
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/package.json +10 -10
- package/prompts/commands/orchestrate.md +1 -1
- package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
- package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
- package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
|
@@ -0,0 +1,862 @@
|
|
|
1
|
+
import { combineUsage } from "../usage-totals.js";
|
|
2
|
+
import { DEFAULT_CHILD_STATE_LIMITS, isThinkingLevel, NO_UI_APPROVAL_SUFFIX, POLYPHASE_RESULT_TOOL_NAME, } from "./types.js";
|
|
3
|
+
/** JSON.parse in try/catch; returns undefined for malformed lines or values without a string `type`. */
|
|
4
|
+
export function parseChildLine(line) {
|
|
5
|
+
let parsed;
|
|
6
|
+
try {
|
|
7
|
+
parsed = JSON.parse(line);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
13
|
+
return undefined;
|
|
14
|
+
if (typeof parsed.type !== "string")
|
|
15
|
+
return undefined;
|
|
16
|
+
return parsed;
|
|
17
|
+
}
|
|
18
|
+
const SUMMARY_MAX_CHARS = 120;
|
|
19
|
+
const SUMMARY_ARG_KEYS = ["command", "path", "file_path", "pattern", "query", "url"];
|
|
20
|
+
const TOOLCALL_ARG_BUFFER_MAX_CHARS = 2048;
|
|
21
|
+
/** Single line, collapsed and ellipsised: a child-supplied error/finalError can be arbitrarily
|
|
22
|
+
* long, and an uncapped notice is the one item kind that can grow larger than a whole run's
|
|
23
|
+
* retention budget on its own (see trimForRetention/evictIfNeeded below). */
|
|
24
|
+
const NOTICE_MAX_CHARS = 1000;
|
|
25
|
+
function truncate(value, max) {
|
|
26
|
+
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
|
|
27
|
+
}
|
|
28
|
+
/** Collapses newlines and runs of whitespace so single-line contracts (summaries, nowLine) hold. */
|
|
29
|
+
function collapseWhitespace(value) {
|
|
30
|
+
return value.replace(/\s+/g, " ").trim();
|
|
31
|
+
}
|
|
32
|
+
/** One line ≤ 120 chars: command | path | file_path | pattern | query | url, else compact JSON. */
|
|
33
|
+
export function summarizeToolArgs(_toolName, args) {
|
|
34
|
+
if (args && typeof args === "object" && !Array.isArray(args)) {
|
|
35
|
+
const record = args;
|
|
36
|
+
for (const key of SUMMARY_ARG_KEYS) {
|
|
37
|
+
const value = record[key];
|
|
38
|
+
if (typeof value === "string" && value.length > 0) {
|
|
39
|
+
return truncate(collapseWhitespace(value), SUMMARY_MAX_CHARS);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return truncate(collapseWhitespace(args === undefined ? "" : JSON.stringify(args)), SUMMARY_MAX_CHARS);
|
|
44
|
+
}
|
|
45
|
+
const STATUS_LINE_PATTERN = /^STATUS:\s*\S.*$/gm;
|
|
46
|
+
/** Last line matching /^STATUS:\s*\S.*$/m, trimmed. */
|
|
47
|
+
export function extractStatusLine(text) {
|
|
48
|
+
const matches = text.match(STATUS_LINE_PATTERN);
|
|
49
|
+
if (!matches || matches.length === 0)
|
|
50
|
+
return undefined;
|
|
51
|
+
return matches[matches.length - 1]?.trim();
|
|
52
|
+
}
|
|
53
|
+
/** input + output + cacheWrite (cache reads excluded); 0 for undefined. */
|
|
54
|
+
export function billableTokens(usage) {
|
|
55
|
+
if (!usage)
|
|
56
|
+
return 0;
|
|
57
|
+
return usage.input + usage.output + usage.cacheWrite;
|
|
58
|
+
}
|
|
59
|
+
export function createChildAgentState(model) {
|
|
60
|
+
return {
|
|
61
|
+
lifecycle: "pending",
|
|
62
|
+
activity: "idle",
|
|
63
|
+
model,
|
|
64
|
+
turns: 0,
|
|
65
|
+
toolCalls: 0,
|
|
66
|
+
toolErrors: 0,
|
|
67
|
+
toolCounts: {},
|
|
68
|
+
blocked: [],
|
|
69
|
+
blockedCount: 0,
|
|
70
|
+
transcript: [],
|
|
71
|
+
transcriptChars: 0,
|
|
72
|
+
droppedItems: 0,
|
|
73
|
+
nextSeq: 0,
|
|
74
|
+
nowLine: "",
|
|
75
|
+
finalText: "",
|
|
76
|
+
stderrTail: "",
|
|
77
|
+
malformedLines: 0,
|
|
78
|
+
droppedLines: 0,
|
|
79
|
+
recordsSeen: 0,
|
|
80
|
+
version: 0,
|
|
81
|
+
coarseVersion: 0,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function isTextContent(value) {
|
|
85
|
+
return !!value && typeof value === "object" && value.type === "text";
|
|
86
|
+
}
|
|
87
|
+
/** Shallow guard against a well-typed-looking `message_update`/`message_end` record whose `usage`
|
|
88
|
+
* field is not actually an object (e.g. a string or number from a malformed wire record). */
|
|
89
|
+
function isUsageLike(value) {
|
|
90
|
+
return typeof value === "object" && value !== null;
|
|
91
|
+
}
|
|
92
|
+
function extractResultText(result) {
|
|
93
|
+
if (typeof result !== "object" || result === null)
|
|
94
|
+
return "";
|
|
95
|
+
const content = result.content;
|
|
96
|
+
if (!Array.isArray(content))
|
|
97
|
+
return "";
|
|
98
|
+
const parts = [];
|
|
99
|
+
for (const block of content) {
|
|
100
|
+
if (isTextContent(block))
|
|
101
|
+
parts.push(block.text);
|
|
102
|
+
}
|
|
103
|
+
return parts.join("");
|
|
104
|
+
}
|
|
105
|
+
function capHeadTail(text, max) {
|
|
106
|
+
if (text.length <= max)
|
|
107
|
+
return text;
|
|
108
|
+
const marker = `\n[... ${text.length - max} characters omitted ...]\n`;
|
|
109
|
+
const keep = Math.max(0, max - marker.length);
|
|
110
|
+
const headLen = Math.floor(keep * 0.4);
|
|
111
|
+
const tailLen = keep - headLen;
|
|
112
|
+
return text.slice(0, headLen) + marker + text.slice(text.length - tailLen);
|
|
113
|
+
}
|
|
114
|
+
/** Last non-empty line of `text`: a streamed thinking/text delta often ends with one or more
|
|
115
|
+
* trailing newlines (a paragraph break), which would otherwise make `nowLine` blank between
|
|
116
|
+
* paragraphs even though the agent is still working. */
|
|
117
|
+
function lastLine(text) {
|
|
118
|
+
const trimmed = text.replace(/\s+$/, "");
|
|
119
|
+
const nl = trimmed.lastIndexOf("\n");
|
|
120
|
+
return nl === -1 ? trimmed : trimmed.slice(nl + 1);
|
|
121
|
+
}
|
|
122
|
+
/** `prefix` plus the collapsed tail of `text`'s last line, kept on one line within `max` chars. */
|
|
123
|
+
function clampTail(prefix, text, max = 160) {
|
|
124
|
+
const collapsed = collapseWhitespace(lastLine(text));
|
|
125
|
+
const budget = Math.max(0, max - prefix.length);
|
|
126
|
+
const tail = collapsed.length <= budget ? collapsed : collapsed.slice(collapsed.length - budget);
|
|
127
|
+
return `${prefix}${tail}`;
|
|
128
|
+
}
|
|
129
|
+
/** `head` plus as much of the collapsed `rest` as fits within `max` chars, single line. */
|
|
130
|
+
function clampHead(head, rest, max = 160) {
|
|
131
|
+
const collapsed = collapseWhitespace(rest);
|
|
132
|
+
// -1 reserves the separator space added below so the result never exceeds `max`.
|
|
133
|
+
const budget = Math.max(0, max - head.length - 1);
|
|
134
|
+
// `truncate` itself slices to `budget`, so pre-slicing to `budget` first (as before) made it a
|
|
135
|
+
// no-op and the ellipsis never appeared; budget === 0 is left empty rather than calling
|
|
136
|
+
// `truncate` with it, since `truncate`'s own minimum output is one char plus an ellipsis.
|
|
137
|
+
const kept = budget > 0 ? truncate(collapsed, budget) : "";
|
|
138
|
+
return kept.length > 0 ? `${head} ${kept}` : head;
|
|
139
|
+
}
|
|
140
|
+
export class ChildEventReducer {
|
|
141
|
+
state;
|
|
142
|
+
limits;
|
|
143
|
+
now;
|
|
144
|
+
toolItemsById = new Map();
|
|
145
|
+
openThinking;
|
|
146
|
+
openText;
|
|
147
|
+
/** Last thinking/text item, kept past `*_end` so `nowLine` shows its final content instead of going blank. */
|
|
148
|
+
lastThinking;
|
|
149
|
+
lastText;
|
|
150
|
+
lastToolItem;
|
|
151
|
+
blockedPending;
|
|
152
|
+
pendingStructuredById = new Map();
|
|
153
|
+
/** Buffered `toolcall_delta` argument JSON per content index, up to `TOOLCALL_ARG_BUFFER_MAX_CHARS` (not surfaced). */
|
|
154
|
+
toolcallArgBuffers = new Map();
|
|
155
|
+
lastHeartbeatAt = Number.NEGATIVE_INFINITY;
|
|
156
|
+
constructor(init) {
|
|
157
|
+
this.limits = { ...DEFAULT_CHILD_STATE_LIMITS, ...init.limits };
|
|
158
|
+
this.now = init.now ?? Date.now;
|
|
159
|
+
this.state = createChildAgentState(init.model);
|
|
160
|
+
}
|
|
161
|
+
markQueued() {
|
|
162
|
+
this.state.lifecycle = "queued";
|
|
163
|
+
this.state.queuedAt = this.now();
|
|
164
|
+
return this.bump("coarse");
|
|
165
|
+
}
|
|
166
|
+
markSpawning() {
|
|
167
|
+
this.state.lifecycle = "spawning";
|
|
168
|
+
this.state.startedAt = this.now();
|
|
169
|
+
return this.bump("coarse");
|
|
170
|
+
}
|
|
171
|
+
apply(record) {
|
|
172
|
+
try {
|
|
173
|
+
return this.applyRecord(record);
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
this.state.malformedLines++;
|
|
177
|
+
return "none";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/** For skipped tool_execution_update lines: "fine" at most once per second, else "none". */
|
|
181
|
+
noteHeartbeat() {
|
|
182
|
+
const now = this.now();
|
|
183
|
+
if (now - this.lastHeartbeatAt < 1000)
|
|
184
|
+
return "none";
|
|
185
|
+
this.lastHeartbeatAt = now;
|
|
186
|
+
return this.bump("fine");
|
|
187
|
+
}
|
|
188
|
+
noteStderr(chunk) {
|
|
189
|
+
this.state.stderrTail = (this.state.stderrTail + chunk).slice(-this.limits.maxStderrChars);
|
|
190
|
+
}
|
|
191
|
+
/** Fallback re-spawn: reset everything except queuedAt/startedAt; add an info notice. */
|
|
192
|
+
resetForRetry(model, notice) {
|
|
193
|
+
const queuedAt = this.state.queuedAt;
|
|
194
|
+
const startedAt = this.state.startedAt;
|
|
195
|
+
// version/coarseVersion/nextSeq are monotonic cache keys for pump/store/renderer caches and must
|
|
196
|
+
// never go backwards; everything else from the failed attempt is dropped.
|
|
197
|
+
const version = this.state.version;
|
|
198
|
+
const coarseVersion = this.state.coarseVersion;
|
|
199
|
+
const nextSeq = this.state.nextSeq;
|
|
200
|
+
Object.assign(this.state, createChildAgentState(model));
|
|
201
|
+
// createChildAgentState omits these optional fields rather than setting them to undefined, so
|
|
202
|
+
// Object.assign leaves a stale value behind; clear them explicitly.
|
|
203
|
+
this.state.sessionId = undefined;
|
|
204
|
+
this.state.usage = undefined;
|
|
205
|
+
this.state.liveUsage = undefined;
|
|
206
|
+
this.state.stopReason = undefined;
|
|
207
|
+
this.state.errorMessage = undefined;
|
|
208
|
+
this.state.structured = undefined;
|
|
209
|
+
this.state.retry = undefined;
|
|
210
|
+
this.state.currentTool = undefined;
|
|
211
|
+
this.state.endedAt = undefined;
|
|
212
|
+
this.state.lastEventAt = undefined;
|
|
213
|
+
this.state.queuedAt = queuedAt;
|
|
214
|
+
this.state.startedAt = startedAt;
|
|
215
|
+
this.state.version = version;
|
|
216
|
+
this.state.coarseVersion = coarseVersion;
|
|
217
|
+
this.state.nextSeq = nextSeq;
|
|
218
|
+
// Not in the design's "reset everything except queuedAt/startedAt": createChildAgentState's
|
|
219
|
+
// default ("pending") would otherwise briefly misreport a retry as not-yet-asked-to-run, when
|
|
220
|
+
// a new child process is in fact already being spawned for it.
|
|
221
|
+
this.state.lifecycle = "spawning";
|
|
222
|
+
this.toolItemsById.clear();
|
|
223
|
+
this.openThinking = undefined;
|
|
224
|
+
this.openText = undefined;
|
|
225
|
+
this.lastThinking = undefined;
|
|
226
|
+
this.lastText = undefined;
|
|
227
|
+
this.lastToolItem = undefined;
|
|
228
|
+
this.blockedPending = undefined;
|
|
229
|
+
this.pendingStructuredById.clear();
|
|
230
|
+
this.toolcallArgBuffers.clear();
|
|
231
|
+
this.lastHeartbeatAt = Number.NEGATIVE_INFINITY;
|
|
232
|
+
this.pushNotice("info", notice);
|
|
233
|
+
this.bump("coarse");
|
|
234
|
+
}
|
|
235
|
+
finish(exit) {
|
|
236
|
+
const wasSettled = this.state.lifecycle === "settled";
|
|
237
|
+
this.state.lifecycle = "exited";
|
|
238
|
+
this.state.endedAt = this.now();
|
|
239
|
+
this.blockedPending = undefined;
|
|
240
|
+
// The child stopped sending deltas (cancelled, crashed, or SIGTERM'd mid-stream), but the
|
|
241
|
+
// last-open thinking/text item is still `done: false`. Left alone, the transcript renderer
|
|
242
|
+
// keeps drawing its live cursor (`▌`) on an agent that has already exited.
|
|
243
|
+
if (this.openThinking) {
|
|
244
|
+
this.mutateItem(this.openThinking, (item) => {
|
|
245
|
+
item.done = true;
|
|
246
|
+
});
|
|
247
|
+
this.openThinking = undefined;
|
|
248
|
+
}
|
|
249
|
+
if (this.openText) {
|
|
250
|
+
this.mutateItem(this.openText, (item) => {
|
|
251
|
+
item.done = true;
|
|
252
|
+
});
|
|
253
|
+
this.openText = undefined;
|
|
254
|
+
}
|
|
255
|
+
let exitCode;
|
|
256
|
+
let failure;
|
|
257
|
+
if (exit.cancelled) {
|
|
258
|
+
exitCode = 1;
|
|
259
|
+
failure = "cancelled";
|
|
260
|
+
}
|
|
261
|
+
else if (exit.spawnError) {
|
|
262
|
+
exitCode = 1;
|
|
263
|
+
failure = `failed to start: ${exit.spawnError}`;
|
|
264
|
+
}
|
|
265
|
+
else if (exit.code === 0 && this.state.stopReason !== "error" && this.state.stopReason !== "aborted") {
|
|
266
|
+
exitCode = 0;
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
exitCode = 1;
|
|
270
|
+
// §6.4 gives "child exited (code X) before producing output" verbatim for rule 1 and
|
|
271
|
+
// omits a signal from rule 2's wording too; both messages add it here when present,
|
|
272
|
+
// since a SIGTERM/SIGKILL is exactly the kind of detail worth keeping in a failure a
|
|
273
|
+
// user may have to debug, and neither message is pattern-matched downstream.
|
|
274
|
+
const signalSuffix = exit.signal ? `, signal ${exit.signal}` : "";
|
|
275
|
+
if (this.state.recordsSeen === 0) {
|
|
276
|
+
failure = `child exited (code ${exit.code}${signalSuffix}) before producing output`;
|
|
277
|
+
}
|
|
278
|
+
else if (!wasSettled) {
|
|
279
|
+
failure = `child exited (code ${exit.code}${signalSuffix}) before settling`;
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
const stopReasonIsFailure = this.state.stopReason === "error" || this.state.stopReason === "aborted";
|
|
283
|
+
failure =
|
|
284
|
+
this.state.errorMessage ??
|
|
285
|
+
(stopReasonIsFailure ? this.state.stopReason : `child exited (code ${exit.code}${signalSuffix})`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
this.bump("coarse");
|
|
289
|
+
return { exitCode, failure };
|
|
290
|
+
}
|
|
291
|
+
/** After the run finished: keep the newest `maxChars` transcript chars. */
|
|
292
|
+
trimForRetention(maxChars) {
|
|
293
|
+
const transcript = this.state.transcript;
|
|
294
|
+
if (transcript.length === 0) {
|
|
295
|
+
this.state.transcriptChars = 0;
|
|
296
|
+
this.bump("coarse");
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
// The newest item is kept unconditionally, even if it alone is larger than `maxChars`:
|
|
300
|
+
// tail-trimming it still loses only its oldest content, whereas dropping it (the previous
|
|
301
|
+
// behaviour, when `total + size > maxChars` was already true on the first iteration) could
|
|
302
|
+
// empty the whole transcript right after a run whose last item was one huge notice or error.
|
|
303
|
+
const lastIndex = transcript.length - 1;
|
|
304
|
+
const last = transcript[lastIndex];
|
|
305
|
+
this.tailTrimToFit(last, maxChars);
|
|
306
|
+
let total = this.measure(last);
|
|
307
|
+
let cutIndex = lastIndex;
|
|
308
|
+
for (let i = lastIndex - 1; i >= 0; i--) {
|
|
309
|
+
const item = transcript[i];
|
|
310
|
+
if (!item)
|
|
311
|
+
continue;
|
|
312
|
+
const size = this.measure(item);
|
|
313
|
+
if (total + size > maxChars) {
|
|
314
|
+
cutIndex = i + 1;
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
total += size;
|
|
318
|
+
cutIndex = i;
|
|
319
|
+
}
|
|
320
|
+
if (cutIndex > 0) {
|
|
321
|
+
const removed = transcript.splice(0, cutIndex);
|
|
322
|
+
this.state.droppedItems += removed.length;
|
|
323
|
+
for (const item of removed) {
|
|
324
|
+
if (item.kind === "tool")
|
|
325
|
+
this.toolItemsById.delete(item.toolCallId);
|
|
326
|
+
}
|
|
327
|
+
this.clearRefsTo(removed);
|
|
328
|
+
}
|
|
329
|
+
this.state.transcriptChars = total;
|
|
330
|
+
this.bump("coarse");
|
|
331
|
+
}
|
|
332
|
+
dropTranscript() {
|
|
333
|
+
this.state.droppedItems += this.state.transcript.length;
|
|
334
|
+
this.state.transcript = [];
|
|
335
|
+
this.state.transcriptChars = 0;
|
|
336
|
+
this.toolItemsById.clear();
|
|
337
|
+
this.openThinking = undefined;
|
|
338
|
+
this.openText = undefined;
|
|
339
|
+
this.lastThinking = undefined;
|
|
340
|
+
this.lastText = undefined;
|
|
341
|
+
this.lastToolItem = undefined;
|
|
342
|
+
this.bump("coarse");
|
|
343
|
+
}
|
|
344
|
+
/** Clears open/last item refs that point at an item removed from the transcript. */
|
|
345
|
+
clearRefsTo(removed) {
|
|
346
|
+
const removedSet = new Set(removed);
|
|
347
|
+
if (this.openThinking && removedSet.has(this.openThinking))
|
|
348
|
+
this.openThinking = undefined;
|
|
349
|
+
if (this.openText && removedSet.has(this.openText))
|
|
350
|
+
this.openText = undefined;
|
|
351
|
+
if (this.lastThinking && removedSet.has(this.lastThinking))
|
|
352
|
+
this.lastThinking = undefined;
|
|
353
|
+
if (this.lastText && removedSet.has(this.lastText))
|
|
354
|
+
this.lastText = undefined;
|
|
355
|
+
if (this.lastToolItem && removedSet.has(this.lastToolItem))
|
|
356
|
+
this.lastToolItem = undefined;
|
|
357
|
+
}
|
|
358
|
+
applyRecord(record) {
|
|
359
|
+
switch (record.type) {
|
|
360
|
+
case "session":
|
|
361
|
+
this.state.sessionId = record.id;
|
|
362
|
+
this.state.recordsSeen++;
|
|
363
|
+
return this.bump("coarse");
|
|
364
|
+
case "agent_start":
|
|
365
|
+
this.state.lifecycle = "running";
|
|
366
|
+
this.state.activity = "waiting";
|
|
367
|
+
return this.bump("coarse");
|
|
368
|
+
case "message_start":
|
|
369
|
+
return this.handleMessageStart(record.message);
|
|
370
|
+
case "message_update":
|
|
371
|
+
return this.handleMessageUpdate(record);
|
|
372
|
+
case "message_end":
|
|
373
|
+
return this.handleMessageEnd(record.message);
|
|
374
|
+
case "tool_execution_start":
|
|
375
|
+
return this.handleToolExecutionStart(record);
|
|
376
|
+
case "tool_execution_end":
|
|
377
|
+
return this.handleToolExecutionEnd(record);
|
|
378
|
+
case "auto_retry_start":
|
|
379
|
+
this.state.retry = {
|
|
380
|
+
attempt: record.attempt,
|
|
381
|
+
maxAttempts: record.maxAttempts,
|
|
382
|
+
delayMs: record.delayMs,
|
|
383
|
+
errorMessage: record.errorMessage,
|
|
384
|
+
};
|
|
385
|
+
this.pushNotice("warning", `retrying ${record.attempt}/${record.maxAttempts}: ${record.errorMessage}`);
|
|
386
|
+
this.state.activity = "retrying";
|
|
387
|
+
return this.bump("coarse");
|
|
388
|
+
case "auto_retry_end":
|
|
389
|
+
this.state.retry = undefined;
|
|
390
|
+
this.pushNotice(record.success ? "info" : "error", record.success ? "retry succeeded" : `retry failed: ${record.finalError ?? ""}`);
|
|
391
|
+
this.state.activity = "idle";
|
|
392
|
+
return this.bump("coarse");
|
|
393
|
+
case "compaction_start":
|
|
394
|
+
this.pushNotice("info", `compacting context (${record.reason})`);
|
|
395
|
+
this.state.activity = "compacting";
|
|
396
|
+
return this.bump("coarse");
|
|
397
|
+
case "compaction_end":
|
|
398
|
+
this.pushNotice(record.errorMessage ? "warning" : "info", record.errorMessage ? `compaction failed: ${record.errorMessage}` : "compaction finished");
|
|
399
|
+
this.state.activity = "idle";
|
|
400
|
+
return this.bump("coarse");
|
|
401
|
+
case "thinking_level_changed":
|
|
402
|
+
if (!isThinkingLevel(record.level))
|
|
403
|
+
return "none";
|
|
404
|
+
this.state.model = { ...this.state.model, thinkingLevel: record.level };
|
|
405
|
+
return this.bump("coarse");
|
|
406
|
+
case "agent_settled":
|
|
407
|
+
this.state.lifecycle = "settled";
|
|
408
|
+
this.state.activity = "idle";
|
|
409
|
+
this.state.currentTool = undefined;
|
|
410
|
+
this.blockedPending = undefined;
|
|
411
|
+
return this.bump("coarse");
|
|
412
|
+
default:
|
|
413
|
+
return "none";
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
handleMessageStart(message) {
|
|
417
|
+
if (message.role !== "assistant")
|
|
418
|
+
return "none";
|
|
419
|
+
this.state.turns++;
|
|
420
|
+
if (!this.state.model.confirmed) {
|
|
421
|
+
this.state.model = { ...this.state.model, provider: message.provider, id: message.model, confirmed: true };
|
|
422
|
+
}
|
|
423
|
+
else if (this.state.model.provider !== message.provider || this.state.model.id !== message.model) {
|
|
424
|
+
this.pushNotice("info", `model switched to ${message.provider}/${message.model}`);
|
|
425
|
+
this.state.model = { ...this.state.model, provider: message.provider, id: message.model, confirmed: true };
|
|
426
|
+
}
|
|
427
|
+
this.state.activity = "waiting";
|
|
428
|
+
return this.bump("coarse");
|
|
429
|
+
}
|
|
430
|
+
handleMessageEnd(message) {
|
|
431
|
+
if (message.role !== "assistant")
|
|
432
|
+
return "none";
|
|
433
|
+
// Read and validate every field that could throw or be the wrong type before mutating
|
|
434
|
+
// anything: a malformed `content` (not an array) must not leave usage/stopReason/errorMessage
|
|
435
|
+
// already written with no version bump, as it would if `.find` threw straight out of this
|
|
436
|
+
// function partway through.
|
|
437
|
+
const content = Array.isArray(message.content) ? message.content : [];
|
|
438
|
+
const textPart = content.find(isTextContent);
|
|
439
|
+
// §6.3 says `model.thinkingLevel = message.thinkingLevel` verbatim; this keeps the previous
|
|
440
|
+
// level instead when the field is absent (or, after hardening, not a valid level), since the
|
|
441
|
+
// child only ever reports it on a subset of messages and overwriting with undefined would
|
|
442
|
+
// otherwise make the live/last-known thinking level flicker to unset between turns.
|
|
443
|
+
const thinkingLevel = isThinkingLevel(message.thinkingLevel)
|
|
444
|
+
? message.thinkingLevel
|
|
445
|
+
: this.state.model.thinkingLevel;
|
|
446
|
+
const usage = isUsageLike(message.usage) ? message.usage : undefined;
|
|
447
|
+
this.state.usage =
|
|
448
|
+
usage === undefined ? this.state.usage : this.state.usage ? combineUsage(this.state.usage, usage) : usage;
|
|
449
|
+
this.state.liveUsage = undefined;
|
|
450
|
+
this.state.model = { ...this.state.model, thinkingLevel };
|
|
451
|
+
this.state.stopReason = message.stopReason;
|
|
452
|
+
this.state.errorMessage = message.errorMessage;
|
|
453
|
+
if (textPart) {
|
|
454
|
+
this.state.finalText = capHeadTail(textPart.text, this.limits.maxFinalTextChars);
|
|
455
|
+
}
|
|
456
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") {
|
|
457
|
+
this.pushNotice("error", `assistant turn ${message.stopReason}${message.errorMessage ? `: ${message.errorMessage}` : ""}`);
|
|
458
|
+
}
|
|
459
|
+
return this.bump("coarse");
|
|
460
|
+
}
|
|
461
|
+
handleMessageUpdate(record) {
|
|
462
|
+
// Dispatched before `liveUsage` is touched: a bad delta/content type throws out of
|
|
463
|
+
// `applyAssistantMessageEvent` (via appendCapped/replaceCapped below), and that throw must
|
|
464
|
+
// not leave `liveUsage` mutated with no accompanying version bump.
|
|
465
|
+
const change = this.applyAssistantMessageEvent(record.assistantMessageEvent);
|
|
466
|
+
if (isUsageLike(record.usage))
|
|
467
|
+
this.state.liveUsage = record.usage;
|
|
468
|
+
return change;
|
|
469
|
+
}
|
|
470
|
+
applyAssistantMessageEvent(event) {
|
|
471
|
+
switch (event.type) {
|
|
472
|
+
case "thinking_start": {
|
|
473
|
+
const item = {
|
|
474
|
+
kind: "thinking",
|
|
475
|
+
seq: this.nextSeq(),
|
|
476
|
+
rev: 1,
|
|
477
|
+
text: "",
|
|
478
|
+
droppedChars: 0,
|
|
479
|
+
done: false,
|
|
480
|
+
redacted: false,
|
|
481
|
+
};
|
|
482
|
+
this.pushItem(item);
|
|
483
|
+
this.openThinking = item;
|
|
484
|
+
this.lastThinking = item;
|
|
485
|
+
this.state.activity = "thinking";
|
|
486
|
+
return this.bump("coarse");
|
|
487
|
+
}
|
|
488
|
+
case "thinking_delta": {
|
|
489
|
+
const item = this.openThinking;
|
|
490
|
+
if (!item)
|
|
491
|
+
return "none";
|
|
492
|
+
this.mutateItem(item, (i) => this.appendCapped(i, event.delta));
|
|
493
|
+
this.state.activity = "thinking";
|
|
494
|
+
return this.bump("fine");
|
|
495
|
+
}
|
|
496
|
+
case "thinking_end": {
|
|
497
|
+
const item = this.openThinking;
|
|
498
|
+
if (!item)
|
|
499
|
+
return "none";
|
|
500
|
+
this.mutateItem(item, (i) => {
|
|
501
|
+
this.replaceCapped(i, event.content);
|
|
502
|
+
i.done = true;
|
|
503
|
+
i.redacted = event.content === "[Reasoning redacted]";
|
|
504
|
+
});
|
|
505
|
+
this.openThinking = undefined;
|
|
506
|
+
return this.bump("fine");
|
|
507
|
+
}
|
|
508
|
+
case "text_start": {
|
|
509
|
+
const item = {
|
|
510
|
+
kind: "text",
|
|
511
|
+
seq: this.nextSeq(),
|
|
512
|
+
rev: 1,
|
|
513
|
+
text: "",
|
|
514
|
+
droppedChars: 0,
|
|
515
|
+
done: false,
|
|
516
|
+
};
|
|
517
|
+
this.pushItem(item);
|
|
518
|
+
this.openText = item;
|
|
519
|
+
this.lastText = item;
|
|
520
|
+
this.state.activity = "writing";
|
|
521
|
+
return this.bump("coarse");
|
|
522
|
+
}
|
|
523
|
+
case "text_delta": {
|
|
524
|
+
const item = this.openText;
|
|
525
|
+
if (!item)
|
|
526
|
+
return "none";
|
|
527
|
+
this.mutateItem(item, (i) => this.appendCapped(i, event.delta));
|
|
528
|
+
this.state.activity = "writing";
|
|
529
|
+
return this.bump("fine");
|
|
530
|
+
}
|
|
531
|
+
case "text_end": {
|
|
532
|
+
const item = this.openText;
|
|
533
|
+
if (!item)
|
|
534
|
+
return "none";
|
|
535
|
+
this.mutateItem(item, (i) => {
|
|
536
|
+
this.replaceCapped(i, event.content);
|
|
537
|
+
i.done = true;
|
|
538
|
+
});
|
|
539
|
+
this.openText = undefined;
|
|
540
|
+
return this.bump("fine");
|
|
541
|
+
}
|
|
542
|
+
case "toolcall_start": {
|
|
543
|
+
const item = {
|
|
544
|
+
kind: "tool",
|
|
545
|
+
seq: this.nextSeq(),
|
|
546
|
+
rev: 1,
|
|
547
|
+
toolCallId: event.id,
|
|
548
|
+
name: event.toolName,
|
|
549
|
+
summary: "",
|
|
550
|
+
status: "pending",
|
|
551
|
+
};
|
|
552
|
+
this.pushItem(item);
|
|
553
|
+
this.toolItemsById.set(event.id, item);
|
|
554
|
+
this.lastToolItem = item;
|
|
555
|
+
this.blockedPending = undefined;
|
|
556
|
+
this.toolcallArgBuffers.set(event.contentIndex, "");
|
|
557
|
+
this.state.activity = "tool";
|
|
558
|
+
return this.bump("coarse");
|
|
559
|
+
}
|
|
560
|
+
case "toolcall_delta": {
|
|
561
|
+
const buffered = this.toolcallArgBuffers.get(event.contentIndex);
|
|
562
|
+
if (buffered !== undefined) {
|
|
563
|
+
this.toolcallArgBuffers.set(event.contentIndex, (buffered + event.delta).slice(0, TOOLCALL_ARG_BUFFER_MAX_CHARS));
|
|
564
|
+
}
|
|
565
|
+
return "none";
|
|
566
|
+
}
|
|
567
|
+
case "toolcall_end": {
|
|
568
|
+
this.toolcallArgBuffers.delete(event.contentIndex);
|
|
569
|
+
const item = this.toolItemsById.get(event.toolCall.id);
|
|
570
|
+
if (!item)
|
|
571
|
+
return "none";
|
|
572
|
+
this.mutateItem(item, (i) => {
|
|
573
|
+
i.summary = summarizeToolArgs(event.toolCall.name, event.toolCall.arguments);
|
|
574
|
+
});
|
|
575
|
+
return this.bump("fine");
|
|
576
|
+
}
|
|
577
|
+
default:
|
|
578
|
+
return "none";
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
handleToolExecutionStart(event) {
|
|
582
|
+
let item = this.toolItemsById.get(event.toolCallId);
|
|
583
|
+
if (!item) {
|
|
584
|
+
item = {
|
|
585
|
+
kind: "tool",
|
|
586
|
+
seq: this.nextSeq(),
|
|
587
|
+
rev: 1,
|
|
588
|
+
toolCallId: event.toolCallId,
|
|
589
|
+
name: event.toolName,
|
|
590
|
+
summary: summarizeToolArgs(event.toolName, event.args),
|
|
591
|
+
status: "pending",
|
|
592
|
+
};
|
|
593
|
+
this.pushItem(item);
|
|
594
|
+
this.toolItemsById.set(event.toolCallId, item);
|
|
595
|
+
}
|
|
596
|
+
this.lastToolItem = item;
|
|
597
|
+
const startedAt = this.now();
|
|
598
|
+
this.mutateItem(item, (i) => {
|
|
599
|
+
i.status = "running";
|
|
600
|
+
i.startedAt = startedAt;
|
|
601
|
+
});
|
|
602
|
+
this.state.toolCalls++;
|
|
603
|
+
const counts = this.state.toolCounts;
|
|
604
|
+
const prevCount = Object.hasOwn(counts, event.toolName) ? counts[event.toolName] : 0;
|
|
605
|
+
counts[event.toolName] = (prevCount ?? 0) + 1;
|
|
606
|
+
this.state.currentTool = { toolCallId: event.toolCallId, name: event.toolName, summary: item.summary, startedAt };
|
|
607
|
+
this.state.activity = "tool";
|
|
608
|
+
this.blockedPending = undefined;
|
|
609
|
+
if (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {
|
|
610
|
+
this.pendingStructuredById.set(event.toolCallId, event.args);
|
|
611
|
+
}
|
|
612
|
+
return this.bump("coarse");
|
|
613
|
+
}
|
|
614
|
+
handleToolExecutionEnd(event) {
|
|
615
|
+
let item = this.toolItemsById.get(event.toolCallId);
|
|
616
|
+
if (!item) {
|
|
617
|
+
item = {
|
|
618
|
+
kind: "tool",
|
|
619
|
+
seq: this.nextSeq(),
|
|
620
|
+
rev: 1,
|
|
621
|
+
toolCallId: event.toolCallId,
|
|
622
|
+
name: event.toolName,
|
|
623
|
+
summary: "",
|
|
624
|
+
status: "pending",
|
|
625
|
+
};
|
|
626
|
+
this.pushItem(item);
|
|
627
|
+
this.toolItemsById.set(event.toolCallId, item);
|
|
628
|
+
}
|
|
629
|
+
const text = extractResultText(event.result);
|
|
630
|
+
const preview = text.slice(0, 200);
|
|
631
|
+
const blocked = event.isError && text.endsWith(NO_UI_APPROVAL_SUFFIX);
|
|
632
|
+
this.mutateItem(item, (i) => {
|
|
633
|
+
i.status = blocked ? "blocked" : event.isError ? "error" : "ok";
|
|
634
|
+
i.endedAt = this.now();
|
|
635
|
+
i.resultPreview = preview;
|
|
636
|
+
if (blocked)
|
|
637
|
+
i.blockedReason = text;
|
|
638
|
+
});
|
|
639
|
+
if (event.isError)
|
|
640
|
+
this.state.toolErrors++;
|
|
641
|
+
if (blocked) {
|
|
642
|
+
this.state.blockedCount++;
|
|
643
|
+
const entry = { toolName: event.toolName, summary: item.summary, reason: text };
|
|
644
|
+
this.state.blocked = [...this.state.blocked, entry].slice(-20);
|
|
645
|
+
this.pushNotice("warning", `${event.toolName} blocked: needs approval (subagents cannot ask)`);
|
|
646
|
+
this.blockedPending = event.toolName;
|
|
647
|
+
}
|
|
648
|
+
if (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {
|
|
649
|
+
const pending = this.pendingStructuredById.get(event.toolCallId);
|
|
650
|
+
this.pendingStructuredById.delete(event.toolCallId);
|
|
651
|
+
if (!event.isError && pending !== undefined) {
|
|
652
|
+
this.state.structured = { value: pending };
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
this.state.currentTool = undefined;
|
|
656
|
+
return this.bump("coarse");
|
|
657
|
+
}
|
|
658
|
+
nextSeq() {
|
|
659
|
+
return this.state.nextSeq++;
|
|
660
|
+
}
|
|
661
|
+
pushNotice(level, text) {
|
|
662
|
+
const capped = truncate(collapseWhitespace(text), NOTICE_MAX_CHARS);
|
|
663
|
+
this.pushItem({ kind: "notice", seq: this.nextSeq(), rev: 1, level, text: capped, at: this.now() });
|
|
664
|
+
}
|
|
665
|
+
pushItem(item) {
|
|
666
|
+
this.state.transcript.push(item);
|
|
667
|
+
this.adjustChars(this.measure(item));
|
|
668
|
+
this.evictIfNeeded();
|
|
669
|
+
}
|
|
670
|
+
mutateItem(item, mutate) {
|
|
671
|
+
const before = this.measure(item);
|
|
672
|
+
mutate(item);
|
|
673
|
+
item.rev++;
|
|
674
|
+
const after = this.measure(item);
|
|
675
|
+
this.adjustChars(after - before);
|
|
676
|
+
this.evictIfNeeded();
|
|
677
|
+
}
|
|
678
|
+
/** `addition` is typed `unknown`, not `string`, on purpose: a well-typed-looking wire record can
|
|
679
|
+
* still carry a non-string `delta` at runtime (`parseChildLine` only checks `type`), and this
|
|
680
|
+
* must throw before touching `item.text` rather than let a non-string silently become part of
|
|
681
|
+
* the transcript or poison `transcriptChars` with a NaN-producing `.length` on a non-string. */
|
|
682
|
+
appendCapped(item, addition) {
|
|
683
|
+
if (typeof addition !== "string")
|
|
684
|
+
throw new TypeError("expected a string delta");
|
|
685
|
+
const combined = item.text + addition;
|
|
686
|
+
if (combined.length > this.limits.maxItemChars) {
|
|
687
|
+
const removed = combined.length - this.limits.maxItemChars;
|
|
688
|
+
item.droppedChars += removed;
|
|
689
|
+
item.text = combined.slice(removed);
|
|
690
|
+
}
|
|
691
|
+
else {
|
|
692
|
+
item.text = combined;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/** The full item content replaces the accumulated (already tail-capped) text; droppedChars reflects
|
|
696
|
+
* this final content, not the sum of every delta's cap, so it is assigned rather than accumulated.
|
|
697
|
+
* `content` is `unknown`, not `string`, for the same reason as {@link appendCapped}'s `addition`. */
|
|
698
|
+
replaceCapped(item, content) {
|
|
699
|
+
if (typeof content !== "string")
|
|
700
|
+
throw new TypeError("expected a string content");
|
|
701
|
+
if (content.length > this.limits.maxItemChars) {
|
|
702
|
+
const removed = content.length - this.limits.maxItemChars;
|
|
703
|
+
item.droppedChars = removed;
|
|
704
|
+
item.text = content.slice(removed);
|
|
705
|
+
}
|
|
706
|
+
else {
|
|
707
|
+
item.droppedChars = 0;
|
|
708
|
+
item.text = content;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
measure(item) {
|
|
712
|
+
switch (item.kind) {
|
|
713
|
+
case "thinking":
|
|
714
|
+
case "text":
|
|
715
|
+
return item.text.length;
|
|
716
|
+
case "tool":
|
|
717
|
+
return item.summary.length + (item.resultPreview?.length ?? 0);
|
|
718
|
+
case "notice":
|
|
719
|
+
return item.text.length;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/** Shrinks `item` in place, keeping its tail (most recent content), until `measure(item) <=
|
|
723
|
+
* maxChars`. Used only to keep the newest transcript item instead of evicting it outright. */
|
|
724
|
+
tailTrimToFit(item, maxChars) {
|
|
725
|
+
const over = this.measure(item) - Math.max(0, maxChars);
|
|
726
|
+
if (over <= 0)
|
|
727
|
+
return;
|
|
728
|
+
switch (item.kind) {
|
|
729
|
+
case "thinking":
|
|
730
|
+
case "text":
|
|
731
|
+
item.droppedChars += over;
|
|
732
|
+
item.text = item.text.slice(over);
|
|
733
|
+
break;
|
|
734
|
+
case "notice":
|
|
735
|
+
item.text = item.text.slice(over);
|
|
736
|
+
break;
|
|
737
|
+
case "tool": {
|
|
738
|
+
let remaining = over;
|
|
739
|
+
if (item.resultPreview) {
|
|
740
|
+
const trimmed = Math.min(remaining, item.resultPreview.length);
|
|
741
|
+
item.resultPreview = item.resultPreview.slice(trimmed);
|
|
742
|
+
remaining -= trimmed;
|
|
743
|
+
}
|
|
744
|
+
if (remaining > 0)
|
|
745
|
+
item.summary = item.summary.slice(remaining);
|
|
746
|
+
break;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
item.rev++;
|
|
750
|
+
}
|
|
751
|
+
adjustChars(delta) {
|
|
752
|
+
const next = this.state.transcriptChars + delta;
|
|
753
|
+
// A NaN delta (impossible for a string's `.length`, but transcriptChars is otherwise an
|
|
754
|
+
// unguarded running total) must not permanently poison the count: Number.isFinite rejects it
|
|
755
|
+
// and leaves the previous value in place instead of letting Math.max(0, NaN) propagate NaN.
|
|
756
|
+
if (Number.isFinite(next))
|
|
757
|
+
this.state.transcriptChars = Math.max(0, next);
|
|
758
|
+
}
|
|
759
|
+
evictIfNeeded() {
|
|
760
|
+
const removed = [];
|
|
761
|
+
while (this.state.transcript.length > this.limits.maxItems || this.state.transcriptChars > this.limits.maxChars) {
|
|
762
|
+
const idx = this.state.transcript.findIndex((item) => !this.isOpenItem(item));
|
|
763
|
+
if (idx === -1)
|
|
764
|
+
break;
|
|
765
|
+
if (idx === this.state.transcript.length - 1) {
|
|
766
|
+
// This is the only evictable item left (every open item is already exempt, and
|
|
767
|
+
// everything else has already been dropped): tail-trim it instead of dropping it, so
|
|
768
|
+
// one huge item (one notice with a child-supplied error message, say) cannot empty the
|
|
769
|
+
// whole live transcript. Nothing else is left to evict either way, so stop here.
|
|
770
|
+
const item = this.state.transcript[idx];
|
|
771
|
+
const before = this.measure(item);
|
|
772
|
+
this.tailTrimToFit(item, this.limits.maxChars);
|
|
773
|
+
this.adjustChars(this.measure(item) - before);
|
|
774
|
+
break;
|
|
775
|
+
}
|
|
776
|
+
const item = this.state.transcript.splice(idx, 1)[0];
|
|
777
|
+
if (!item)
|
|
778
|
+
break;
|
|
779
|
+
this.adjustChars(-this.measure(item));
|
|
780
|
+
this.state.droppedItems++;
|
|
781
|
+
if (item.kind === "tool")
|
|
782
|
+
this.toolItemsById.delete(item.toolCallId);
|
|
783
|
+
removed.push(item);
|
|
784
|
+
}
|
|
785
|
+
if (removed.length > 0)
|
|
786
|
+
this.clearRefsTo(removed);
|
|
787
|
+
}
|
|
788
|
+
isOpenItem(item) {
|
|
789
|
+
return item === this.openThinking || item === this.openText;
|
|
790
|
+
}
|
|
791
|
+
bump(change) {
|
|
792
|
+
if (change === "none")
|
|
793
|
+
return change;
|
|
794
|
+
this.state.version++;
|
|
795
|
+
if (change === "coarse")
|
|
796
|
+
this.state.coarseVersion++;
|
|
797
|
+
this.state.lastEventAt = this.now();
|
|
798
|
+
this.state.nowLine = this.computeNowLine();
|
|
799
|
+
return change;
|
|
800
|
+
}
|
|
801
|
+
computeNowLine() {
|
|
802
|
+
if (this.blockedPending) {
|
|
803
|
+
return clampHead("⚠", `${this.blockedPending} blocked: needs approval`);
|
|
804
|
+
}
|
|
805
|
+
switch (this.state.activity) {
|
|
806
|
+
case "thinking":
|
|
807
|
+
return clampTail("thinking · ", (this.openThinking ?? this.lastThinking)?.text ?? "");
|
|
808
|
+
case "writing":
|
|
809
|
+
return clampTail("writing · ", (this.openText ?? this.lastText)?.text ?? "");
|
|
810
|
+
case "tool": {
|
|
811
|
+
const item = this.lastToolItem;
|
|
812
|
+
return item ? clampHead(item.name, item.summary) : "";
|
|
813
|
+
}
|
|
814
|
+
case "waiting":
|
|
815
|
+
return "waiting for model";
|
|
816
|
+
case "retrying": {
|
|
817
|
+
const retry = this.state.retry;
|
|
818
|
+
return retry
|
|
819
|
+
? clampHead(`retrying ${retry.attempt}/${retry.maxAttempts} ·`, retry.errorMessage)
|
|
820
|
+
: "retrying";
|
|
821
|
+
}
|
|
822
|
+
case "compacting":
|
|
823
|
+
return "compacting context";
|
|
824
|
+
case "idle":
|
|
825
|
+
return this.state.lifecycle === "settled" ? "finished" : "";
|
|
826
|
+
default:
|
|
827
|
+
return "";
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
function resolveModelRef(state) {
|
|
832
|
+
if (!state.model.confirmed || !state.model.provider || !state.model.id)
|
|
833
|
+
return undefined;
|
|
834
|
+
return { provider: state.model.provider, id: state.model.id };
|
|
835
|
+
}
|
|
836
|
+
export function toRunResult(state, base, finish, extras) {
|
|
837
|
+
const failedResponse = state.stopReason === "error" || state.stopReason === "aborted";
|
|
838
|
+
const stderr = state.stderrTail.length > 0
|
|
839
|
+
? state.stderrTail
|
|
840
|
+
: failedResponse
|
|
841
|
+
? (state.errorMessage ?? state.stopReason ?? "")
|
|
842
|
+
: (finish.failure ?? "");
|
|
843
|
+
return {
|
|
844
|
+
agent: base.agent,
|
|
845
|
+
task: base.task,
|
|
846
|
+
step: base.step,
|
|
847
|
+
exitCode: finish.exitCode,
|
|
848
|
+
output: state.finalText,
|
|
849
|
+
stderr,
|
|
850
|
+
usage: state.usage,
|
|
851
|
+
model: resolveModelRef(state),
|
|
852
|
+
thinkingLevel: state.model.thinkingLevel,
|
|
853
|
+
stopReason: state.stopReason,
|
|
854
|
+
turns: state.turns,
|
|
855
|
+
toolCalls: state.toolCalls,
|
|
856
|
+
blockedToolCalls: state.blockedCount,
|
|
857
|
+
structured: extras.structured,
|
|
858
|
+
cancelled: extras.cancelled,
|
|
859
|
+
durationMs: extras.durationMs,
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
//# sourceMappingURL=child-events.js.map
|