@draht/coding-agent 2026.10.16 → 2026.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/{chunk-OWGSPJPZ.js → chunk-7TYCZN4Z.js} +4 -4
  4. package/dist/bundle/chunks/{chunk-TJ3AW62W.js → chunk-KEUN2Y6B.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-JFDPOIUH.js → chunk-MO3SCGBN.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-6APPDDHH.js → chunk-N2QZNJT6.js} +3 -3
  7. package/dist/bundle/chunks/{chunk-MIUVNYYW.js → chunk-VOODMGI3.js} +103 -91
  8. package/dist/bundle/chunks/{chunk-NHTOADU6.js → chunk-ZA4QNPJY.js} +1 -1
  9. package/dist/bundle/chunks/{cli-U7Y4VNNI.js → cli-PYJB6AQ3.js} +1 -1
  10. package/dist/bundle/chunks/{execute-ZWB4PIQQ.js → execute-6N7T7VLY.js} +1 -1
  11. package/dist/bundle/chunks/{runtime-PXJK4L7Y.js → runtime-D3KV73AE.js} +1 -1
  12. package/dist/bundle/chunks/{virtual-modules-BEJ4ZJ3D.js → virtual-modules-GSNL3MCU.js} +1 -1
  13. package/dist/bundle/cli-runtime.js +1 -1
  14. package/dist/bundle/index.js +1 -1
  15. package/dist/bundle/rpc-entry.js +1 -1
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +4 -0
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/builtins/duet.d.ts +7 -1
  20. package/dist/core/builtins/duet.d.ts.map +1 -1
  21. package/dist/core/builtins/duet.js +83 -14
  22. package/dist/core/builtins/duet.js.map +1 -1
  23. package/dist/core/builtins/polyphase.d.ts.map +1 -1
  24. package/dist/core/builtins/polyphase.js +21 -2
  25. package/dist/core/builtins/polyphase.js.map +1 -1
  26. package/dist/core/builtins/subagent.d.ts +59 -2
  27. package/dist/core/builtins/subagent.d.ts.map +1 -1
  28. package/dist/core/builtins/subagent.js +258 -62
  29. package/dist/core/builtins/subagent.js.map +1 -1
  30. package/dist/core/extensions/loader.d.ts.map +1 -1
  31. package/dist/core/extensions/loader.js +23 -0
  32. package/dist/core/extensions/loader.js.map +1 -1
  33. package/dist/core/extensions/runner.d.ts.map +1 -1
  34. package/dist/core/extensions/runner.js +2 -0
  35. package/dist/core/extensions/runner.js.map +1 -1
  36. package/dist/core/extensions/types.d.ts +12 -0
  37. package/dist/core/extensions/types.d.ts.map +1 -1
  38. package/dist/core/extensions/types.js.map +1 -1
  39. package/dist/core/keybindings.d.ts +5 -0
  40. package/dist/core/keybindings.d.ts.map +1 -1
  41. package/dist/core/keybindings.js +4 -0
  42. package/dist/core/keybindings.js.map +1 -1
  43. package/dist/core/multi-agent/permission-gate.d.ts +18 -6
  44. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  45. package/dist/core/multi-agent/permission-gate.js +867 -59
  46. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  47. package/dist/core/polyphase/approval.d.ts +6 -2
  48. package/dist/core/polyphase/approval.d.ts.map +1 -1
  49. package/dist/core/polyphase/approval.js +23 -35
  50. package/dist/core/polyphase/approval.js.map +1 -1
  51. package/dist/core/polyphase/child-events.js +1 -1
  52. package/dist/core/polyphase/child-events.js.map +1 -1
  53. package/dist/core/polyphase/child-process.d.ts.map +1 -1
  54. package/dist/core/polyphase/child-process.js +65 -7
  55. package/dist/core/polyphase/child-process.js.map +1 -1
  56. package/dist/core/polyphase/commands.d.ts.map +1 -1
  57. package/dist/core/polyphase/commands.js +46 -5
  58. package/dist/core/polyphase/commands.js.map +1 -1
  59. package/dist/core/polyphase/details.d.ts.map +1 -1
  60. package/dist/core/polyphase/details.js +5 -0
  61. package/dist/core/polyphase/details.js.map +1 -1
  62. package/dist/core/polyphase/permission-bridge.d.ts +128 -0
  63. package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
  64. package/dist/core/polyphase/permission-bridge.js +357 -0
  65. package/dist/core/polyphase/permission-bridge.js.map +1 -0
  66. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  67. package/dist/core/polyphase/render/run-block.js +13 -4
  68. package/dist/core/polyphase/render/run-block.js.map +1 -1
  69. package/dist/core/polyphase/render/snapshot.d.ts +4 -0
  70. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  71. package/dist/core/polyphase/render/snapshot.js +4 -0
  72. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  73. package/dist/core/polyphase/result-text.d.ts.map +1 -1
  74. package/dist/core/polyphase/result-text.js +23 -3
  75. package/dist/core/polyphase/result-text.js.map +1 -1
  76. package/dist/core/polyphase/session.d.ts +15 -1
  77. package/dist/core/polyphase/session.d.ts.map +1 -1
  78. package/dist/core/polyphase/session.js +36 -1
  79. package/dist/core/polyphase/session.js.map +1 -1
  80. package/dist/core/polyphase/settings.d.ts +1 -0
  81. package/dist/core/polyphase/settings.d.ts.map +1 -1
  82. package/dist/core/polyphase/settings.js +1 -1
  83. package/dist/core/polyphase/settings.js.map +1 -1
  84. package/dist/core/polyphase/store.d.ts +18 -0
  85. package/dist/core/polyphase/store.d.ts.map +1 -1
  86. package/dist/core/polyphase/store.js +38 -0
  87. package/dist/core/polyphase/store.js.map +1 -1
  88. package/dist/core/polyphase/types.d.ts +60 -3
  89. package/dist/core/polyphase/types.d.ts.map +1 -1
  90. package/dist/core/polyphase/types.js.map +1 -1
  91. package/dist/core/polyphase/ui/inspector.js +1 -1
  92. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  93. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
  94. package/dist/core/polyphase/workflow/agent-host.js +17 -3
  95. package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
  96. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
  97. package/dist/core/polyphase/workflow/guidance.js +16 -5
  98. package/dist/core/polyphase/workflow/guidance.js.map +1 -1
  99. package/dist/core/polyphase/workflow/launch.d.ts +2 -1
  100. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
  101. package/dist/core/polyphase/workflow/launch.js +22 -3
  102. package/dist/core/polyphase/workflow/launch.js.map +1 -1
  103. package/dist/core/polyphase/workflow/limits.d.ts +80 -0
  104. package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
  105. package/dist/core/polyphase/workflow/limits.js +234 -0
  106. package/dist/core/polyphase/workflow/limits.js.map +1 -0
  107. package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
  108. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
  109. package/dist/core/polyphase/workflow/runtime.js.map +1 -1
  110. package/dist/core/polyphase/workflow/tool.d.ts +1 -0
  111. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
  112. package/dist/core/polyphase/workflow/tool.js +23 -2
  113. package/dist/core/polyphase/workflow/tool.js.map +1 -1
  114. package/dist/core/usage-totals.d.ts +5 -0
  115. package/dist/core/usage-totals.d.ts.map +1 -1
  116. package/dist/core/usage-totals.js +16 -0
  117. package/dist/core/usage-totals.js.map +1 -1
  118. package/dist/main.d.ts.map +1 -1
  119. package/dist/main.js +4 -0
  120. package/dist/main.js.map +1 -1
  121. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  122. package/dist/modes/interactive/interactive-mode.js +2 -0
  123. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  124. package/dist/utils/shell.d.ts.map +1 -1
  125. package/dist/utils/shell.js +3 -0
  126. package/dist/utils/shell.js.map +1 -1
  127. package/docs/duet.md +1 -1
  128. package/docs/environment-variables.md +3 -1
  129. package/docs/extensions.md +2 -1
  130. package/docs/keybindings.md +1 -0
  131. package/docs/polyphase.md +97 -33
  132. package/docs/settings.md +2 -2
  133. package/package.json +10 -10
@@ -3,6 +3,7 @@
3
3
  * See DESIGN.md §15.1.
4
4
  */
5
5
  import type { WorkflowSource } from "./types.ts";
6
+ import { type ParsedDirectives, type ResolvedWorkflowLimits } from "./workflow/limits.ts";
6
7
  import { type WorkflowMeta } from "./workflow/meta.ts";
7
8
  export interface ApprovalDescription {
8
9
  title: string;
@@ -12,13 +13,17 @@ export interface ApprovalDescription {
12
13
  export interface ApprovalLimits {
13
14
  concurrency: number;
14
15
  maxAgents: number;
16
+ /** Config fallback for the token budget / time limit precedence (D-B): prompt > tool > this. */
15
17
  budgetTokens: number | null;
18
+ timeLimitMs: number | null;
16
19
  }
17
20
  export interface ApprovalContext {
18
21
  cwd: string;
19
22
  projectTrusted: boolean;
20
23
  agentDir: string;
21
24
  limits: ApprovalLimits;
25
+ /** The enabling/requesting prompt's directives, when known (D-B precedence's top tier). */
26
+ promptDirectives?: ParsedDirectives;
22
27
  }
23
28
  export interface WorkflowApprovalInfo {
24
29
  source: WorkflowSource;
@@ -26,9 +31,8 @@ export interface WorkflowApprovalInfo {
26
31
  path?: string;
27
32
  scriptLines?: number;
28
33
  args?: string;
29
- budgetTokens?: number | null;
30
34
  }
31
- export declare function describeWorkflowForApproval(meta: WorkflowMeta, info: WorkflowApprovalInfo, limits: ApprovalLimits): ApprovalDescription;
35
+ export declare function describeWorkflowForApproval(meta: WorkflowMeta, info: WorkflowApprovalInfo, limits: ApprovalLimits, resolvedLimits: ResolvedWorkflowLimits): ApprovalDescription;
32
36
  export declare function describeInvalidWorkflow(message: string, info: WorkflowApprovalInfo): ApprovalDescription;
33
37
  /** Only "workflow" (inline script or saved name); undefined for every other tool and for unknown saved names. Never throws. */
34
38
  export declare function describeToolCallForApproval(toolName: string, input: Record<string, unknown>, context: ApprovalContext): ApprovalDescription | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"approval.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/approval.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAuB,KAAK,YAAY,EAA0B,MAAM,oBAAoB,CAAC;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6 +6,7 @@ import * as os from "node:os";
6
6
  import * as path from "node:path";
7
7
  import { realPathStrict } from "../../utils/canonical-path.js";
8
8
  import { WORKFLOW_TOOL_NAME } from "./types.js";
9
+ import { formatWorkflowLimitsLine, parseDurationMs, resolveWorkflowLimits, } from "./workflow/limits.js";
9
10
  import { extractWorkflowMeta } from "./workflow/meta.js";
10
11
  import { findSavedWorkflow } from "./workflow/saved.js";
11
12
  const MAX_ARG_CHARS = 120;
@@ -26,21 +27,6 @@ function truncateArgs(args) {
26
27
  function quoteArgs(args) {
27
28
  return JSON.stringify(sanitizeArgsForQuoting(truncateArgs(args)));
28
29
  }
29
- function formatApproxTokens(tokens) {
30
- if (tokens >= 1_000_000)
31
- return `${trimDecimal(tokens / 1_000_000)}m`;
32
- if (tokens >= 1_000) {
33
- const kilos = trimDecimal(tokens / 1_000);
34
- // toFixed(1) can round up to "1000.0", which would display as "1000k" instead of "1m".
35
- if (Number(kilos) >= 1000)
36
- return `${trimDecimal(tokens / 1_000_000)}m`;
37
- return `${kilos}k`;
38
- }
39
- return `${tokens}`;
40
- }
41
- function trimDecimal(value) {
42
- return Number(value.toFixed(1)).toString();
43
- }
44
30
  // C0/C1 controls, the Unicode line/paragraph separators, and the bidi embedding/override/isolate
45
31
  // controls. None of these are escaped by `JSON.stringify`, and a line separator or bidi override
46
32
  // can visually relocate or hide text in a terminal even where a literal "\n" can't.
@@ -64,11 +50,8 @@ function sanitizeArgsForQuoting(value) {
64
50
  function oneLine(value) {
65
51
  return sanitizeInline(value).replace(/ {2,}/g, " ").trim();
66
52
  }
67
- function formatBudgetText(budgetTokens) {
68
- return budgetTokens === null ? "no budget" : `budget ${formatApproxTokens(budgetTokens)} tokens`;
69
- }
70
- function formatLimitsLine(limits, budgetTokens) {
71
- return `Limits: ${limits.concurrency} agents at once · up to ${limits.maxAgents} agents · ${formatBudgetText(budgetTokens)}`;
53
+ function formatLimitsLine(limits, resolved) {
54
+ return `Limits: ${limits.concurrency} agents at once · up to ${limits.maxAgents} agents · ${formatWorkflowLimitsLine(resolved)}`;
72
55
  }
73
56
  function countScriptLines(script) {
74
57
  if (script.length === 0)
@@ -79,9 +62,20 @@ function countScriptLines(script) {
79
62
  newlineCount++;
80
63
  return script.endsWith("\n") ? newlineCount : newlineCount + 1;
81
64
  }
82
- function resolveBudgetTokens(input, limits) {
83
- const budget = input.budgetTokens;
84
- return typeof budget === "number" && Number.isFinite(budget) ? budget : limits.budgetTokens;
65
+ /** D-B precedence (prompt directive > tool parameter > config > none), from the raw tool-call
66
+ * input (or the `/<name>`/`/workflow` command's `{name, args}` input, which never carries
67
+ * `budgetTokens`/`timeLimit` of its own). */
68
+ function resolveApprovalLimits(input, context) {
69
+ const toolBudget = input.budgetTokens;
70
+ const toolTimeLimit = input.timeLimit;
71
+ return resolveWorkflowLimits({
72
+ prompt: context.promptDirectives,
73
+ tool: {
74
+ budgetTokens: typeof toolBudget === "number" && Number.isFinite(toolBudget) ? toolBudget : undefined,
75
+ timeLimitMs: typeof toolTimeLimit === "string" ? parseDurationMs(toolTimeLimit) : undefined,
76
+ },
77
+ config: { budgetTokens: context.limits.budgetTokens, timeLimitMs: context.limits.timeLimitMs },
78
+ });
85
79
  }
86
80
  function formatMessagePhases(phases) {
87
81
  return phases
@@ -98,7 +92,7 @@ function formatSourceText(info) {
98
92
  }
99
93
  return `${info.source} ${info.path ?? ""}`.trim();
100
94
  }
101
- export function describeWorkflowForApproval(meta, info, limits) {
95
+ export function describeWorkflowForApproval(meta, info, limits, resolvedLimits) {
102
96
  const lines = [
103
97
  oneLine(meta.description),
104
98
  `Phases: ${formatMessagePhases(meta.phases)}`,
@@ -106,8 +100,7 @@ export function describeWorkflowForApproval(meta, info, limits) {
106
100
  ];
107
101
  if (info.args)
108
102
  lines.push(`Args: ${quoteArgs(info.args)}`);
109
- const budgetTokens = info.budgetTokens !== undefined ? info.budgetTokens : limits.budgetTokens;
110
- lines.push(formatLimitsLine(limits, budgetTokens));
103
+ lines.push(formatLimitsLine(limits, resolvedLimits));
111
104
  lines.push("Each agent is a separate paid model session. Tool calls inside agents still follow permission rules.");
112
105
  const operation = `workflow ${meta.name}: ${formatOperationPhases(meta.phases)}${info.args ? `; args ${quoteArgs(info.args)}` : ""}`;
113
106
  return { title: `Run workflow "${meta.name}"?`, message: lines.join("\n"), operation };
@@ -140,19 +133,15 @@ export function describeToolCallForApproval(toolName, input, context) {
140
133
  if (toolName !== WORKFLOW_TOOL_NAME)
141
134
  return undefined;
142
135
  const args = readStringField(input, "args") ?? "";
136
+ const resolvedLimits = resolveApprovalLimits(input, context);
143
137
  const script = readStringField(input, "script");
144
138
  if (script !== undefined) {
145
- const info = {
146
- source: "inline",
147
- scriptLines: countScriptLines(script),
148
- args,
149
- budgetTokens: resolveBudgetTokens(input, context.limits),
150
- };
139
+ const info = { source: "inline", scriptLines: countScriptLines(script), args };
151
140
  const extraction = extractWorkflowMeta(script);
152
141
  if (!extraction.ok) {
153
142
  return describeInvalidWorkflow(`${extraction.error.message} (line ${extraction.error.line})`, info);
154
143
  }
155
- return describeWorkflowForApproval(extraction.meta, info, context.limits);
144
+ return describeWorkflowForApproval(extraction.meta, info, context.limits, resolvedLimits);
156
145
  }
157
146
  const name = readStringField(input, "name");
158
147
  if (name === undefined)
@@ -168,14 +157,13 @@ export function describeToolCallForApproval(toolName, input, context) {
168
157
  source: workflow.source,
169
158
  path: formatSavedWorkflowPath(workflow.path, workflow.source, context.cwd),
170
159
  args,
171
- budgetTokens: resolveBudgetTokens(input, context.limits),
172
160
  };
173
161
  if (!workflow.valid)
174
162
  return describeInvalidWorkflow(workflow.error ?? "invalid meta block", info);
175
163
  const meta = { name: workflow.name, description: workflow.description, phases: workflow.phases };
176
164
  if (workflow.whenToUse !== undefined)
177
165
  meta.whenToUse = workflow.whenToUse;
178
- return describeWorkflowForApproval(meta, info, context.limits);
166
+ return describeWorkflowForApproval(meta, info, context.limits, resolvedLimits);
179
167
  }
180
168
  catch {
181
169
  return undefined;
@@ -1 +1 @@
1
- {"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AAI,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC;YAC1E,IAAI;YACJ,YAAY,EAAE,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC;SACxD,CAAC;QACF,IAAI,CAAC,QAAQ,CAAC,KAAK;YAAE,OAAO,uBAAuB,CAAC,QAAQ,CAAC,KAAK,IAAI,oBAAoB,EAAE,IAAI,CAAC,CAAC;QAElG,MAAM,IAAI,GAAiB,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC/G,IAAI,QAAQ,CAAC,SAAS,KAAK,SAAS;YAAE,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QAC1E,OAAO,2BAA2B,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAChE,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC","sourcesContent":["/**\n * Approval descriptions for the `workflow` tool and the `/workflow`, `/<name>` command path.\n * See DESIGN.md §15.1.\n */\n\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { realPathStrict } from \"../../utils/canonical-path.ts\";\nimport type { WorkflowSource } from \"./types.ts\";\nimport { WORKFLOW_TOOL_NAME } from \"./types.ts\";\nimport { extractWorkflowMeta, type WorkflowMeta, type WorkflowPhaseMeta } from \"./workflow/meta.ts\";\nimport { findSavedWorkflow } from \"./workflow/saved.ts\";\n\nexport interface ApprovalDescription {\n\ttitle: string;\n\tmessage: string;\n\toperation: string;\n}\n\nexport interface ApprovalLimits {\n\tconcurrency: number;\n\tmaxAgents: number;\n\tbudgetTokens: number | null;\n}\n\nexport interface ApprovalContext {\n\tcwd: string;\n\tprojectTrusted: boolean;\n\tagentDir: string;\n\tlimits: ApprovalLimits;\n}\n\nexport interface WorkflowApprovalInfo {\n\tsource: WorkflowSource;\n\t/** Display path for \"project\"/\"user\" sources, already relative to cwd or home. */\n\tpath?: string;\n\tscriptLines?: number;\n\targs?: string;\n\tbudgetTokens?: number | null;\n}\n\nconst MAX_ARG_CHARS = 120;\n\nfunction truncateArgs(args: string): string {\n\tconst codePoints = Array.from(args);\n\tif (codePoints.length <= MAX_ARG_CHARS) return args;\n\treturn `${codePoints.slice(0, MAX_ARG_CHARS - 1).join(\"\")}…`;\n}\n\n/**\n * Sanitizes, then JSON-quotes, args so model-controlled text can't break the surrounding dialog.\n * `JSON.stringify` already escapes quotes, backslashes and C0 controls (including newlines and\n * tabs) as visible `\\n`/`\\t`-style sequences, so only the characters it leaves unescaped — C1\n * controls (U+0080-U+009F, including U+009B, the 8-bit CSI), U+2028/U+2029 and bidi overrides —\n * are replaced with spaces first. Unlike `oneLine`'s full C0 sweep (used for prose that must\n * collapse to one row), this must not touch C0 or args would lose their visible escapes.\n */\nfunction quoteArgs(args: string): string {\n\treturn JSON.stringify(sanitizeArgsForQuoting(truncateArgs(args)));\n}\n\nfunction formatApproxTokens(tokens: number): string {\n\tif (tokens >= 1_000_000) return `${trimDecimal(tokens / 1_000_000)}m`;\n\tif (tokens >= 1_000) {\n\t\tconst kilos = trimDecimal(tokens / 1_000);\n\t\t// toFixed(1) can round up to \"1000.0\", which would display as \"1000k\" instead of \"1m\".\n\t\tif (Number(kilos) >= 1000) return `${trimDecimal(tokens / 1_000_000)}m`;\n\t\treturn `${kilos}k`;\n\t}\n\treturn `${tokens}`;\n}\n\nfunction trimDecimal(value: number): string {\n\treturn Number(value.toFixed(1)).toString();\n}\n\n// C0/C1 controls, the Unicode line/paragraph separators, and the bidi embedding/override/isolate\n// controls. None of these are escaped by `JSON.stringify`, and a line separator or bidi override\n// can visually relocate or hide text in a terminal even where a literal \"\\n\" can't.\nconst UNSAFE_INLINE_PATTERN = /[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]+/g;\n\nfunction sanitizeInline(value: string): string {\n\treturn value.replace(UNSAFE_INLINE_PATTERN, \" \");\n}\n\n// Same as UNSAFE_INLINE_PATTERN minus C0 (\\u0000-\\u001f): JSON.stringify already escapes those\n// visibly (e.g. \"\\n\", \"\\t\"), so quoteArgs must leave them for it instead of collapsing them here.\nconst UNSAFE_QUOTED_PATTERN = /[\\u007f-\\u009f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]+/g;\n\nfunction sanitizeArgsForQuoting(value: string): string {\n\treturn value.replace(UNSAFE_QUOTED_PATTERN, \" \");\n}\n\n/**\n * Collapses newlines and other unsafe characters to spaces so model-controlled text (a workflow's\n * `meta.description`, phase titles, phase models) can't inject extra lines into the approval\n * message. `boundDialogText` treats every \"\\n\" in the message as a deliberate row break, so an\n * unsanitized multi-line description could push the trust-relevant Source/Limits lines past its\n * row cap.\n */\nfunction oneLine(value: string): string {\n\treturn sanitizeInline(value).replace(/ {2,}/g, \" \").trim();\n}\n\nfunction formatBudgetText(budgetTokens: number | null): string {\n\treturn budgetTokens === null ? \"no budget\" : `budget ${formatApproxTokens(budgetTokens)} tokens`;\n}\n\nfunction formatLimitsLine(limits: ApprovalLimits, budgetTokens: number | null): string {\n\treturn `Limits: ${limits.concurrency} agents at once · up to ${limits.maxAgents} agents · ${formatBudgetText(budgetTokens)}`;\n}\n\nfunction countScriptLines(script: string): number {\n\tif (script.length === 0) return 0;\n\tlet newlineCount = 0;\n\tfor (let i = 0; i < script.length; i++) if (script.charCodeAt(i) === 10) newlineCount++;\n\treturn script.endsWith(\"\\n\") ? newlineCount : newlineCount + 1;\n}\n\nfunction resolveBudgetTokens(input: Record<string, unknown>, limits: ApprovalLimits): number | null {\n\tconst budget = input.budgetTokens;\n\treturn typeof budget === \"number\" && Number.isFinite(budget) ? budget : limits.budgetTokens;\n}\n\nfunction formatMessagePhases(phases: readonly WorkflowPhaseMeta[]): string {\n\treturn phases\n\t\t.map((phase, index) => `${index + 1} ${oneLine(phase.title)}${phase.model ? ` (${oneLine(phase.model)})` : \"\"}`)\n\t\t.join(\" · \");\n}\n\nfunction formatOperationPhases(phases: readonly WorkflowPhaseMeta[]): string {\n\treturn phases.map((phase) => oneLine(phase.title)).join(\" → \");\n}\n\nfunction formatSourceText(info: WorkflowApprovalInfo): string {\n\tif (info.source === \"inline\") {\n\t\tconst lines = info.scriptLines ?? 0;\n\t\treturn `inline script written by the model (${lines} ${lines === 1 ? \"line\" : \"lines\"})`;\n\t}\n\treturn `${info.source} ${info.path ?? \"\"}`.trim();\n}\n\nexport function describeWorkflowForApproval(\n\tmeta: WorkflowMeta,\n\tinfo: WorkflowApprovalInfo,\n\tlimits: ApprovalLimits,\n): ApprovalDescription {\n\tconst lines = [\n\t\toneLine(meta.description),\n\t\t`Phases: ${formatMessagePhases(meta.phases)}`,\n\t\t`Source: ${formatSourceText(info)}`,\n\t];\n\tif (info.args) lines.push(`Args: ${quoteArgs(info.args)}`);\n\tconst budgetTokens = info.budgetTokens !== undefined ? info.budgetTokens : limits.budgetTokens;\n\tlines.push(formatLimitsLine(limits, budgetTokens));\n\tlines.push(\"Each agent is a separate paid model session. Tool calls inside agents still follow permission rules.\");\n\n\tconst operation = `workflow ${meta.name}: ${formatOperationPhases(meta.phases)}${\n\t\tinfo.args ? `; args ${quoteArgs(info.args)}` : \"\"\n\t}`;\n\n\treturn { title: `Run workflow \"${meta.name}\"?`, message: lines.join(\"\\n\"), operation };\n}\n\nexport function describeInvalidWorkflow(message: string, info: WorkflowApprovalInfo): ApprovalDescription {\n\treturn {\n\t\ttitle: \"Run workflow (invalid meta)?\",\n\t\tmessage: `The meta block is invalid: ${oneLine(message)}. Approving fails before any agent starts.`,\n\t\toperation: `workflow (invalid meta): ${formatSourceText(info)}`,\n\t};\n}\n\nfunction formatSavedWorkflowPath(filePath: string, source: \"project\" | \"user\", cwd: string): string {\n\tif (source === \"project\") {\n\t\tconst baseCwd = realPathStrict(cwd) ?? cwd;\n\t\tconst rel = path.relative(baseCwd, filePath);\n\t\treturn path.isAbsolute(rel) ? filePath : rel;\n\t}\n\tconst home = os.homedir();\n\tif (filePath === home || filePath.startsWith(`${home}${path.sep}`)) return `~${filePath.slice(home.length)}`;\n\treturn filePath;\n}\n\nfunction readStringField(input: Record<string, unknown>, field: string): string | undefined {\n\tconst value = input[field];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\n/** Only \"workflow\" (inline script or saved name); undefined for every other tool and for unknown saved names. Never throws. */\nexport function describeToolCallForApproval(\n\ttoolName: string,\n\tinput: Record<string, unknown>,\n\tcontext: ApprovalContext,\n): ApprovalDescription | undefined {\n\ttry {\n\t\tif (toolName !== WORKFLOW_TOOL_NAME) return undefined;\n\n\t\tconst args = readStringField(input, \"args\") ?? \"\";\n\t\tconst script = readStringField(input, \"script\");\n\t\tif (script !== undefined) {\n\t\t\tconst info: WorkflowApprovalInfo = {\n\t\t\t\tsource: \"inline\",\n\t\t\t\tscriptLines: countScriptLines(script),\n\t\t\t\targs,\n\t\t\t\tbudgetTokens: resolveBudgetTokens(input, context.limits),\n\t\t\t};\n\t\t\tconst extraction = extractWorkflowMeta(script);\n\t\t\tif (!extraction.ok) {\n\t\t\t\treturn describeInvalidWorkflow(`${extraction.error.message} (line ${extraction.error.line})`, info);\n\t\t\t}\n\t\t\treturn describeWorkflowForApproval(extraction.meta, info, context.limits);\n\t\t}\n\n\t\tconst name = readStringField(input, \"name\");\n\t\tif (name === undefined) return undefined;\n\n\t\tconst workflow = findSavedWorkflow(name, {\n\t\t\tcwd: context.cwd,\n\t\t\tagentDir: context.agentDir,\n\t\t\tprojectTrusted: context.projectTrusted,\n\t\t});\n\t\tif (workflow === undefined) return undefined;\n\n\t\tconst info: WorkflowApprovalInfo = {\n\t\t\tsource: workflow.source,\n\t\t\tpath: formatSavedWorkflowPath(workflow.path, workflow.source, context.cwd),\n\t\t\targs,\n\t\t\tbudgetTokens: resolveBudgetTokens(input, context.limits),\n\t\t};\n\t\tif (!workflow.valid) return describeInvalidWorkflow(workflow.error ?? \"invalid meta block\", info);\n\n\t\tconst meta: WorkflowMeta = { name: workflow.name, description: workflow.description, phases: workflow.phases };\n\t\tif (workflow.whenToUse !== undefined) meta.whenToUse = workflow.whenToUse;\n\t\treturn describeWorkflowForApproval(meta, info, context.limits);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"approval.js","sourceRoot":"","sources":["../../../src/core/polyphase/approval.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EACN,wBAAwB,EAExB,eAAe,EAEf,qBAAqB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAA6C,MAAM,oBAAoB,CAAC;AACpG,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAiCxD,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B,SAAS,YAAY,CAAC,IAAY;IACjC,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,UAAU,CAAC,MAAM,IAAI,aAAa;QAAE,OAAO,IAAI,CAAC;IACpD,OAAO,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC;AAC9D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,SAAS,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,SAAS,CAAC,sBAAsB,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,iGAAiG;AACjG,iGAAiG;AACjG,oFAAoF;AACpF,MAAM,q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,IAAI,oBAAoB,EAAE,IAAI,CAAC,CAAC;QAElG,MAAM,IAAI,GAAiB,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC/G,IAAI,QAAQ,CAAC,SAAS,KAAK,SAAS;YAAE,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QAC1E,OAAO,2BAA2B,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAChF,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC","sourcesContent":["/**\n * Approval descriptions for the `workflow` tool and the `/workflow`, `/<name>` command path.\n * See DESIGN.md §15.1.\n */\n\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { realPathStrict } from \"../../utils/canonical-path.ts\";\nimport type { WorkflowSource } from \"./types.ts\";\nimport { WORKFLOW_TOOL_NAME } from \"./types.ts\";\nimport {\n\tformatWorkflowLimitsLine,\n\ttype ParsedDirectives,\n\tparseDurationMs,\n\ttype ResolvedWorkflowLimits,\n\tresolveWorkflowLimits,\n} from \"./workflow/limits.ts\";\nimport { extractWorkflowMeta, type WorkflowMeta, type WorkflowPhaseMeta } from \"./workflow/meta.ts\";\nimport { findSavedWorkflow } from \"./workflow/saved.ts\";\n\nexport interface ApprovalDescription {\n\ttitle: string;\n\tmessage: string;\n\toperation: string;\n}\n\nexport interface ApprovalLimits {\n\tconcurrency: number;\n\tmaxAgents: number;\n\t/** Config fallback for the token budget / time limit precedence (D-B): prompt > tool > this. */\n\tbudgetTokens: number | null;\n\ttimeLimitMs: number | null;\n}\n\nexport interface ApprovalContext {\n\tcwd: string;\n\tprojectTrusted: boolean;\n\tagentDir: string;\n\tlimits: ApprovalLimits;\n\t/** The enabling/requesting prompt's directives, when known (D-B precedence's top tier). */\n\tpromptDirectives?: ParsedDirectives;\n}\n\nexport interface WorkflowApprovalInfo {\n\tsource: WorkflowSource;\n\t/** Display path for \"project\"/\"user\" sources, already relative to cwd or home. */\n\tpath?: string;\n\tscriptLines?: number;\n\targs?: string;\n}\n\nconst MAX_ARG_CHARS = 120;\n\nfunction truncateArgs(args: string): string {\n\tconst codePoints = Array.from(args);\n\tif (codePoints.length <= MAX_ARG_CHARS) return args;\n\treturn `${codePoints.slice(0, MAX_ARG_CHARS - 1).join(\"\")}…`;\n}\n\n/**\n * Sanitizes, then JSON-quotes, args so model-controlled text can't break the surrounding dialog.\n * `JSON.stringify` already escapes quotes, backslashes and C0 controls (including newlines and\n * tabs) as visible `\\n`/`\\t`-style sequences, so only the characters it leaves unescaped — C1\n * controls (U+0080-U+009F, including U+009B, the 8-bit CSI), U+2028/U+2029 and bidi overrides —\n * are replaced with spaces first. Unlike `oneLine`'s full C0 sweep (used for prose that must\n * collapse to one row), this must not touch C0 or args would lose their visible escapes.\n */\nfunction quoteArgs(args: string): string {\n\treturn JSON.stringify(sanitizeArgsForQuoting(truncateArgs(args)));\n}\n\n// C0/C1 controls, the Unicode line/paragraph separators, and the bidi embedding/override/isolate\n// controls. None of these are escaped by `JSON.stringify`, and a line separator or bidi override\n// can visually relocate or hide text in a terminal even where a literal \"\\n\" can't.\nconst UNSAFE_INLINE_PATTERN = /[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]+/g;\n\nfunction sanitizeInline(value: string): string {\n\treturn value.replace(UNSAFE_INLINE_PATTERN, \" \");\n}\n\n// Same as UNSAFE_INLINE_PATTERN minus C0 (\\u0000-\\u001f): JSON.stringify already escapes those\n// visibly (e.g. \"\\n\", \"\\t\"), so quoteArgs must leave them for it instead of collapsing them here.\nconst UNSAFE_QUOTED_PATTERN = /[\\u007f-\\u009f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]+/g;\n\nfunction sanitizeArgsForQuoting(value: string): string {\n\treturn value.replace(UNSAFE_QUOTED_PATTERN, \" \");\n}\n\n/**\n * Collapses newlines and other unsafe characters to spaces so model-controlled text (a workflow's\n * `meta.description`, phase titles, phase models) can't inject extra lines into the approval\n * message. `boundDialogText` treats every \"\\n\" in the message as a deliberate row break, so an\n * unsanitized multi-line description could push the trust-relevant Source/Limits lines past its\n * row cap.\n */\nfunction oneLine(value: string): string {\n\treturn sanitizeInline(value).replace(/ {2,}/g, \" \").trim();\n}\n\nfunction formatLimitsLine(limits: ApprovalLimits, resolved: ResolvedWorkflowLimits): string {\n\treturn `Limits: ${limits.concurrency} agents at once · up to ${limits.maxAgents} agents · ${formatWorkflowLimitsLine(resolved)}`;\n}\n\nfunction countScriptLines(script: string): number {\n\tif (script.length === 0) return 0;\n\tlet newlineCount = 0;\n\tfor (let i = 0; i < script.length; i++) if (script.charCodeAt(i) === 10) newlineCount++;\n\treturn script.endsWith(\"\\n\") ? newlineCount : newlineCount + 1;\n}\n\n/** D-B precedence (prompt directive > tool parameter > config > none), from the raw tool-call\n * input (or the `/<name>`/`/workflow` command's `{name, args}` input, which never carries\n * `budgetTokens`/`timeLimit` of its own). */\nfunction resolveApprovalLimits(input: Record<string, unknown>, context: ApprovalContext): ResolvedWorkflowLimits {\n\tconst toolBudget = input.budgetTokens;\n\tconst toolTimeLimit = input.timeLimit;\n\treturn resolveWorkflowLimits({\n\t\tprompt: context.promptDirectives,\n\t\ttool: {\n\t\t\tbudgetTokens: typeof toolBudget === \"number\" && Number.isFinite(toolBudget) ? toolBudget : undefined,\n\t\t\ttimeLimitMs: typeof toolTimeLimit === \"string\" ? parseDurationMs(toolTimeLimit) : undefined,\n\t\t},\n\t\tconfig: { budgetTokens: context.limits.budgetTokens, timeLimitMs: context.limits.timeLimitMs },\n\t});\n}\n\nfunction formatMessagePhases(phases: readonly WorkflowPhaseMeta[]): string {\n\treturn phases\n\t\t.map((phase, index) => `${index + 1} ${oneLine(phase.title)}${phase.model ? ` (${oneLine(phase.model)})` : \"\"}`)\n\t\t.join(\" · \");\n}\n\nfunction formatOperationPhases(phases: readonly WorkflowPhaseMeta[]): string {\n\treturn phases.map((phase) => oneLine(phase.title)).join(\" → \");\n}\n\nfunction formatSourceText(info: WorkflowApprovalInfo): string {\n\tif (info.source === \"inline\") {\n\t\tconst lines = info.scriptLines ?? 0;\n\t\treturn `inline script written by the model (${lines} ${lines === 1 ? \"line\" : \"lines\"})`;\n\t}\n\treturn `${info.source} ${info.path ?? \"\"}`.trim();\n}\n\nexport function describeWorkflowForApproval(\n\tmeta: WorkflowMeta,\n\tinfo: WorkflowApprovalInfo,\n\tlimits: ApprovalLimits,\n\tresolvedLimits: ResolvedWorkflowLimits,\n): ApprovalDescription {\n\tconst lines = [\n\t\toneLine(meta.description),\n\t\t`Phases: ${formatMessagePhases(meta.phases)}`,\n\t\t`Source: ${formatSourceText(info)}`,\n\t];\n\tif (info.args) lines.push(`Args: ${quoteArgs(info.args)}`);\n\tlines.push(formatLimitsLine(limits, resolvedLimits));\n\tlines.push(\"Each agent is a separate paid model session. Tool calls inside agents still follow permission rules.\");\n\n\tconst operation = `workflow ${meta.name}: ${formatOperationPhases(meta.phases)}${\n\t\tinfo.args ? `; args ${quoteArgs(info.args)}` : \"\"\n\t}`;\n\n\treturn { title: `Run workflow \"${meta.name}\"?`, message: lines.join(\"\\n\"), operation };\n}\n\nexport function describeInvalidWorkflow(message: string, info: WorkflowApprovalInfo): ApprovalDescription {\n\treturn {\n\t\ttitle: \"Run workflow (invalid meta)?\",\n\t\tmessage: `The meta block is invalid: ${oneLine(message)}. Approving fails before any agent starts.`,\n\t\toperation: `workflow (invalid meta): ${formatSourceText(info)}`,\n\t};\n}\n\nfunction formatSavedWorkflowPath(filePath: string, source: \"project\" | \"user\", cwd: string): string {\n\tif (source === \"project\") {\n\t\tconst baseCwd = realPathStrict(cwd) ?? cwd;\n\t\tconst rel = path.relative(baseCwd, filePath);\n\t\treturn path.isAbsolute(rel) ? filePath : rel;\n\t}\n\tconst home = os.homedir();\n\tif (filePath === home || filePath.startsWith(`${home}${path.sep}`)) return `~${filePath.slice(home.length)}`;\n\treturn filePath;\n}\n\nfunction readStringField(input: Record<string, unknown>, field: string): string | undefined {\n\tconst value = input[field];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\n/** Only \"workflow\" (inline script or saved name); undefined for every other tool and for unknown saved names. Never throws. */\nexport function describeToolCallForApproval(\n\ttoolName: string,\n\tinput: Record<string, unknown>,\n\tcontext: ApprovalContext,\n): ApprovalDescription | undefined {\n\ttry {\n\t\tif (toolName !== WORKFLOW_TOOL_NAME) return undefined;\n\n\t\tconst args = readStringField(input, \"args\") ?? \"\";\n\t\tconst resolvedLimits = resolveApprovalLimits(input, context);\n\t\tconst script = readStringField(input, \"script\");\n\t\tif (script !== undefined) {\n\t\t\tconst info: WorkflowApprovalInfo = { source: \"inline\", scriptLines: countScriptLines(script), args };\n\t\t\tconst extraction = extractWorkflowMeta(script);\n\t\t\tif (!extraction.ok) {\n\t\t\t\treturn describeInvalidWorkflow(`${extraction.error.message} (line ${extraction.error.line})`, info);\n\t\t\t}\n\t\t\treturn describeWorkflowForApproval(extraction.meta, info, context.limits, resolvedLimits);\n\t\t}\n\n\t\tconst name = readStringField(input, \"name\");\n\t\tif (name === undefined) return undefined;\n\n\t\tconst workflow = findSavedWorkflow(name, {\n\t\t\tcwd: context.cwd,\n\t\t\tagentDir: context.agentDir,\n\t\t\tprojectTrusted: context.projectTrusted,\n\t\t});\n\t\tif (workflow === undefined) return undefined;\n\n\t\tconst info: WorkflowApprovalInfo = {\n\t\t\tsource: workflow.source,\n\t\t\tpath: formatSavedWorkflowPath(workflow.path, workflow.source, context.cwd),\n\t\t\targs,\n\t\t};\n\t\tif (!workflow.valid) return describeInvalidWorkflow(workflow.error ?? \"invalid meta block\", info);\n\n\t\tconst meta: WorkflowMeta = { name: workflow.name, description: workflow.description, phases: workflow.phases };\n\t\tif (workflow.whenToUse !== undefined) meta.whenToUse = workflow.whenToUse;\n\t\treturn describeWorkflowForApproval(meta, info, context.limits, resolvedLimits);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -642,7 +642,7 @@ export class ChildEventReducer {
642
642
  this.state.blockedCount++;
643
643
  const entry = { toolName: event.toolName, summary: item.summary, reason: text };
644
644
  this.state.blocked = [...this.state.blocked, entry].slice(-20);
645
- this.pushNotice("warning", `${event.toolName} blocked: needs approval (subagents cannot ask)`);
645
+ this.pushNotice("warning", `${event.toolName} blocked: needs approval, nobody could be asked`);
646
646
  this.blockedPending = event.toolName;
647
647
  }
648
648
  if (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {
@@ -1 +1 @@
1
- {"version":3,"file":"child-events.js","sourceRoot":"","sources":["../../../src/core/polyphase/child-events.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAMN,0BAA0B,EAC1B,eAAe,EAEf,qBAAqB,EACrB,0BAA0B,GAG1B,MAAM,YAAY,CAAC;AAYpB,wGAAwG;AACxG,MAAM,UAAU,cAAc,CAAC,IAAY;IAC1C,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACJ,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAC7F,IAAI,OAAQ,MAAkC,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACnF,OAAO,MAAyB,CAAC;AAClC,CAAC;AAED,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,CA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ClB,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC;QAC7B,aAAa,EAAE,KAAK,CAAC,KAAK,CAAC,aAAa;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,gBAAgB,EAAE,KAAK,CAAC,YAAY;QACpC,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,UAAU,EAAE,MAAM,CAAC,UAAU;KAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { JsonObject, JsonValue, TextContent, Usage } from \"@draht/ai\";\nimport type { JsonAgentSessionEvent } from \"../../modes/json-event.ts\";\nimport { combineUsage } from \"../usage-totals.ts\";\nimport {\n\ttype AgentModelInfo,\n\ttype BlockedToolCall,\n\ttype ChildAgentState,\n\ttype ChildStateChange,\n\ttype ChildStateLimits,\n\tDEFAULT_CHILD_STATE_LIMITS,\n\tisThinkingLevel,\n\ttype ModelRef,\n\tNO_UI_APPROVAL_SUFFIX,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\ttype RunResult,\n\ttype TranscriptItem,\n} from \"./types.ts\";\n\nexport interface SessionHeaderRecord {\n\ttype: \"session\";\n\tid: string;\n\tcwd?: string;\n\ttimestamp?: string;\n\tversion?: number;\n}\n\nexport type ChildWireRecord = SessionHeaderRecord | JsonAgentSessionEvent;\n\n/** JSON.parse in try/catch; returns undefined for malformed lines or values without a string `type`. */\nexport function parseChildLine(line: string): ChildWireRecord | undefined {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\tif (typeof (parsed as Record<string, unknown>).type !== \"string\") return undefined;\n\treturn parsed as ChildWireRecord;\n}\n\nconst SUMMARY_MAX_CHARS = 120;\nconst SUMMARY_ARG_KEYS = [\"command\", \"path\", \"file_path\", \"pattern\", \"query\", \"url\"] as const;\nconst TOOLCALL_ARG_BUFFER_MAX_CHARS = 2048;\n/** Single line, collapsed and ellipsised: a child-supplied error/finalError can be arbitrarily\n * long, and an uncapped notice is the one item kind that can grow larger than a whole run's\n * retention budget on its own (see trimForRetention/evictIfNeeded below). */\nconst NOTICE_MAX_CHARS = 1000;\n\nfunction truncate(value: string, max: number): string {\n\treturn value.length <= max ? value : `${value.slice(0, max - 1)}…`;\n}\n\n/** Collapses newlines and runs of whitespace so single-line contracts (summaries, nowLine) hold. */\nfunction collapseWhitespace(value: string): string {\n\treturn value.replace(/\\s+/g, \" \").trim();\n}\n\n/** One line ≤ 120 chars: command | path | file_path | pattern | query | url, else compact JSON. */\nexport function summarizeToolArgs(_toolName: string, args: JsonValue | undefined): string {\n\tif (args && typeof args === \"object\" && !Array.isArray(args)) {\n\t\tconst record = args as JsonObject;\n\t\tfor (const key of SUMMARY_ARG_KEYS) {\n\t\t\tconst value = record[key];\n\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\treturn truncate(collapseWhitespace(value), SUMMARY_MAX_CHARS);\n\t\t\t}\n\t\t}\n\t}\n\treturn truncate(collapseWhitespace(args === undefined ? \"\" : JSON.stringify(args)), SUMMARY_MAX_CHARS);\n}\n\nconst STATUS_LINE_PATTERN = /^STATUS:\\s*\\S.*$/gm;\n\n/** Last line matching /^STATUS:\\s*\\S.*$/m, trimmed. */\nexport function extractStatusLine(text: string): string | undefined {\n\tconst matches = text.match(STATUS_LINE_PATTERN);\n\tif (!matches || matches.length === 0) return undefined;\n\treturn matches[matches.length - 1]?.trim();\n}\n\n/** input + output + cacheWrite (cache reads excluded); 0 for undefined. */\nexport function billableTokens(usage: Usage | undefined): number {\n\tif (!usage) return 0;\n\treturn usage.input + usage.output + usage.cacheWrite;\n}\n\nexport function createChildAgentState(model: AgentModelInfo): ChildAgentState {\n\treturn {\n\t\tlifecycle: \"pending\",\n\t\tactivity: \"idle\",\n\t\tmodel,\n\t\tturns: 0,\n\t\ttoolCalls: 0,\n\t\ttoolErrors: 0,\n\t\ttoolCounts: {},\n\t\tblocked: [],\n\t\tblockedCount: 0,\n\t\ttranscript: [],\n\t\ttranscriptChars: 0,\n\t\tdroppedItems: 0,\n\t\tnextSeq: 0,\n\t\tnowLine: \"\",\n\t\tfinalText: \"\",\n\t\tstderrTail: \"\",\n\t\tmalformedLines: 0,\n\t\tdroppedLines: 0,\n\t\trecordsSeen: 0,\n\t\tversion: 0,\n\t\tcoarseVersion: 0,\n\t};\n}\n\nexport interface ChildExit {\n\tcode: number | null;\n\tsignal: NodeJS.Signals | null;\n\tcancelled: boolean;\n\tspawnError?: string;\n}\n\nexport interface ChildFinish {\n\texitCode: number;\n\tfailure?: string;\n}\n\ntype ThinkingItem = Extract<TranscriptItem, { kind: \"thinking\" }>;\ntype TextItem = Extract<TranscriptItem, { kind: \"text\" }>;\ntype ToolItem = Extract<TranscriptItem, { kind: \"tool\" }>;\n\nfunction isTextContent(value: unknown): value is TextContent {\n\treturn !!value && typeof value === \"object\" && (value as { type?: unknown }).type === \"text\";\n}\n\n/** Shallow guard against a well-typed-looking `message_update`/`message_end` record whose `usage`\n * field is not actually an object (e.g. a string or number from a malformed wire record). */\nfunction isUsageLike(value: unknown): value is Usage {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction extractResultText(result: unknown): string {\n\tif (typeof result !== \"object\" || result === null) return \"\";\n\tconst content = (result as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return \"\";\n\tconst parts: string[] = [];\n\tfor (const block of content) {\n\t\tif (isTextContent(block)) parts.push(block.text);\n\t}\n\treturn parts.join(\"\");\n}\n\nfunction capHeadTail(text: string, max: number): string {\n\tif (text.length <= max) return text;\n\tconst marker = `\\n[... ${text.length - max} characters omitted ...]\\n`;\n\tconst keep = Math.max(0, max - marker.length);\n\tconst headLen = Math.floor(keep * 0.4);\n\tconst tailLen = keep - headLen;\n\treturn text.slice(0, headLen) + marker + text.slice(text.length - tailLen);\n}\n\n/** Last non-empty line of `text`: a streamed thinking/text delta often ends with one or more\n * trailing newlines (a paragraph break), which would otherwise make `nowLine` blank between\n * paragraphs even though the agent is still working. */\nfunction lastLine(text: string): string {\n\tconst trimmed = text.replace(/\\s+$/, \"\");\n\tconst nl = trimmed.lastIndexOf(\"\\n\");\n\treturn nl === -1 ? trimmed : trimmed.slice(nl + 1);\n}\n\n/** `prefix` plus the collapsed tail of `text`'s last line, kept on one line within `max` chars. */\nfunction clampTail(prefix: string, text: string, max = 160): string {\n\tconst collapsed = collapseWhitespace(lastLine(text));\n\tconst budget = Math.max(0, max - prefix.length);\n\tconst tail = collapsed.length <= budget ? collapsed : collapsed.slice(collapsed.length - budget);\n\treturn `${prefix}${tail}`;\n}\n\n/** `head` plus as much of the collapsed `rest` as fits within `max` chars, single line. */\nfunction clampHead(head: string, rest: string, max = 160): string {\n\tconst collapsed = collapseWhitespace(rest);\n\t// -1 reserves the separator space added below so the result never exceeds `max`.\n\tconst budget = Math.max(0, max - head.length - 1);\n\t// `truncate` itself slices to `budget`, so pre-slicing to `budget` first (as before) made it a\n\t// no-op and the ellipsis never appeared; budget === 0 is left empty rather than calling\n\t// `truncate` with it, since `truncate`'s own minimum output is one char plus an ellipsis.\n\tconst kept = budget > 0 ? truncate(collapsed, budget) : \"\";\n\treturn kept.length > 0 ? `${head} ${kept}` : head;\n}\n\nexport class ChildEventReducer {\n\treadonly state: ChildAgentState;\n\tprivate readonly limits: ChildStateLimits;\n\tprivate readonly now: () => number;\n\n\tprivate toolItemsById = new Map<string, ToolItem>();\n\tprivate openThinking: ThinkingItem | undefined;\n\tprivate openText: TextItem | undefined;\n\t/** Last thinking/text item, kept past `*_end` so `nowLine` shows its final content instead of going blank. */\n\tprivate lastThinking: ThinkingItem | undefined;\n\tprivate lastText: TextItem | undefined;\n\tprivate lastToolItem: ToolItem | undefined;\n\tprivate blockedPending: string | undefined;\n\tprivate pendingStructuredById = new Map<string, JsonValue>();\n\t/** Buffered `toolcall_delta` argument JSON per content index, up to `TOOLCALL_ARG_BUFFER_MAX_CHARS` (not surfaced). */\n\tprivate toolcallArgBuffers = new Map<number, string>();\n\tprivate lastHeartbeatAt = Number.NEGATIVE_INFINITY;\n\n\tconstructor(init: { model: AgentModelInfo; limits?: Partial<ChildStateLimits>; now?: () => number }) {\n\t\tthis.limits = { ...DEFAULT_CHILD_STATE_LIMITS, ...init.limits };\n\t\tthis.now = init.now ?? Date.now;\n\t\tthis.state = createChildAgentState(init.model);\n\t}\n\n\tmarkQueued(): ChildStateChange {\n\t\tthis.state.lifecycle = \"queued\";\n\t\tthis.state.queuedAt = this.now();\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tmarkSpawning(): ChildStateChange {\n\t\tthis.state.lifecycle = \"spawning\";\n\t\tthis.state.startedAt = this.now();\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tapply(record: ChildWireRecord): ChildStateChange {\n\t\ttry {\n\t\t\treturn this.applyRecord(record);\n\t\t} catch {\n\t\t\tthis.state.malformedLines++;\n\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\t/** For skipped tool_execution_update lines: \"fine\" at most once per second, else \"none\". */\n\tnoteHeartbeat(): ChildStateChange {\n\t\tconst now = this.now();\n\t\tif (now - this.lastHeartbeatAt < 1000) return \"none\";\n\t\tthis.lastHeartbeatAt = now;\n\t\treturn this.bump(\"fine\");\n\t}\n\n\tnoteStderr(chunk: string): void {\n\t\tthis.state.stderrTail = (this.state.stderrTail + chunk).slice(-this.limits.maxStderrChars);\n\t}\n\n\t/** Fallback re-spawn: reset everything except queuedAt/startedAt; add an info notice. */\n\tresetForRetry(model: AgentModelInfo, notice: string): void {\n\t\tconst queuedAt = this.state.queuedAt;\n\t\tconst startedAt = this.state.startedAt;\n\t\t// version/coarseVersion/nextSeq are monotonic cache keys for pump/store/renderer caches and must\n\t\t// never go backwards; everything else from the failed attempt is dropped.\n\t\tconst version = this.state.version;\n\t\tconst coarseVersion = this.state.coarseVersion;\n\t\tconst nextSeq = this.state.nextSeq;\n\t\tObject.assign(this.state, createChildAgentState(model));\n\t\t// createChildAgentState omits these optional fields rather than setting them to undefined, so\n\t\t// Object.assign leaves a stale value behind; clear them explicitly.\n\t\tthis.state.sessionId = undefined;\n\t\tthis.state.usage = undefined;\n\t\tthis.state.liveUsage = undefined;\n\t\tthis.state.stopReason = undefined;\n\t\tthis.state.errorMessage = undefined;\n\t\tthis.state.structured = undefined;\n\t\tthis.state.retry = undefined;\n\t\tthis.state.currentTool = undefined;\n\t\tthis.state.endedAt = undefined;\n\t\tthis.state.lastEventAt = undefined;\n\t\tthis.state.queuedAt = queuedAt;\n\t\tthis.state.startedAt = startedAt;\n\t\tthis.state.version = version;\n\t\tthis.state.coarseVersion = coarseVersion;\n\t\tthis.state.nextSeq = nextSeq;\n\t\t// Not in the design's \"reset everything except queuedAt/startedAt\": createChildAgentState's\n\t\t// default (\"pending\") would otherwise briefly misreport a retry as not-yet-asked-to-run, when\n\t\t// a new child process is in fact already being spawned for it.\n\t\tthis.state.lifecycle = \"spawning\";\n\t\tthis.toolItemsById.clear();\n\t\tthis.openThinking = undefined;\n\t\tthis.openText = undefined;\n\t\tthis.lastThinking = undefined;\n\t\tthis.lastText = undefined;\n\t\tthis.lastToolItem = undefined;\n\t\tthis.blockedPending = undefined;\n\t\tthis.pendingStructuredById.clear();\n\t\tthis.toolcallArgBuffers.clear();\n\t\tthis.lastHeartbeatAt = Number.NEGATIVE_INFINITY;\n\t\tthis.pushNotice(\"info\", notice);\n\t\tthis.bump(\"coarse\");\n\t}\n\n\tfinish(exit: ChildExit): ChildFinish {\n\t\tconst wasSettled = this.state.lifecycle === \"settled\";\n\t\tthis.state.lifecycle = \"exited\";\n\t\tthis.state.endedAt = this.now();\n\t\tthis.blockedPending = undefined;\n\n\t\t// The child stopped sending deltas (cancelled, crashed, or SIGTERM'd mid-stream), but the\n\t\t// last-open thinking/text item is still `done: false`. Left alone, the transcript renderer\n\t\t// keeps drawing its live cursor (`▌`) on an agent that has already exited.\n\t\tif (this.openThinking) {\n\t\t\tthis.mutateItem(this.openThinking, (item) => {\n\t\t\t\titem.done = true;\n\t\t\t});\n\t\t\tthis.openThinking = undefined;\n\t\t}\n\t\tif (this.openText) {\n\t\t\tthis.mutateItem(this.openText, (item) => {\n\t\t\t\titem.done = true;\n\t\t\t});\n\t\t\tthis.openText = undefined;\n\t\t}\n\n\t\tlet exitCode: number;\n\t\tlet failure: string | undefined;\n\t\tif (exit.cancelled) {\n\t\t\texitCode = 1;\n\t\t\tfailure = \"cancelled\";\n\t\t} else if (exit.spawnError) {\n\t\t\texitCode = 1;\n\t\t\tfailure = `failed to start: ${exit.spawnError}`;\n\t\t} else if (exit.code === 0 && this.state.stopReason !== \"error\" && this.state.stopReason !== \"aborted\") {\n\t\t\texitCode = 0;\n\t\t} else {\n\t\t\texitCode = 1;\n\t\t\t// §6.4 gives \"child exited (code X) before producing output\" verbatim for rule 1 and\n\t\t\t// omits a signal from rule 2's wording too; both messages add it here when present,\n\t\t\t// since a SIGTERM/SIGKILL is exactly the kind of detail worth keeping in a failure a\n\t\t\t// user may have to debug, and neither message is pattern-matched downstream.\n\t\t\tconst signalSuffix = exit.signal ? `, signal ${exit.signal}` : \"\";\n\t\t\tif (this.state.recordsSeen === 0) {\n\t\t\t\tfailure = `child exited (code ${exit.code}${signalSuffix}) before producing output`;\n\t\t\t} else if (!wasSettled) {\n\t\t\t\tfailure = `child exited (code ${exit.code}${signalSuffix}) before settling`;\n\t\t\t} else {\n\t\t\t\tconst stopReasonIsFailure = this.state.stopReason === \"error\" || this.state.stopReason === \"aborted\";\n\t\t\t\tfailure =\n\t\t\t\t\tthis.state.errorMessage ??\n\t\t\t\t\t(stopReasonIsFailure ? this.state.stopReason : `child exited (code ${exit.code}${signalSuffix})`);\n\t\t\t}\n\t\t}\n\n\t\tthis.bump(\"coarse\");\n\t\treturn { exitCode, failure };\n\t}\n\n\t/** After the run finished: keep the newest `maxChars` transcript chars. */\n\ttrimForRetention(maxChars: number): void {\n\t\tconst transcript = this.state.transcript;\n\t\tif (transcript.length === 0) {\n\t\t\tthis.state.transcriptChars = 0;\n\t\t\tthis.bump(\"coarse\");\n\t\t\treturn;\n\t\t}\n\n\t\t// The newest item is kept unconditionally, even if it alone is larger than `maxChars`:\n\t\t// tail-trimming it still loses only its oldest content, whereas dropping it (the previous\n\t\t// behaviour, when `total + size > maxChars` was already true on the first iteration) could\n\t\t// empty the whole transcript right after a run whose last item was one huge notice or error.\n\t\tconst lastIndex = transcript.length - 1;\n\t\tconst last = transcript[lastIndex] as TranscriptItem;\n\t\tthis.tailTrimToFit(last, maxChars);\n\n\t\tlet total = this.measure(last);\n\t\tlet cutIndex = lastIndex;\n\t\tfor (let i = lastIndex - 1; i >= 0; i--) {\n\t\t\tconst item = transcript[i];\n\t\t\tif (!item) continue;\n\t\t\tconst size = this.measure(item);\n\t\t\tif (total + size > maxChars) {\n\t\t\t\tcutIndex = i + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttotal += size;\n\t\t\tcutIndex = i;\n\t\t}\n\n\t\tif (cutIndex > 0) {\n\t\t\tconst removed = transcript.splice(0, cutIndex);\n\t\t\tthis.state.droppedItems += removed.length;\n\t\t\tfor (const item of removed) {\n\t\t\t\tif (item.kind === \"tool\") this.toolItemsById.delete(item.toolCallId);\n\t\t\t}\n\t\t\tthis.clearRefsTo(removed);\n\t\t}\n\t\tthis.state.transcriptChars = total;\n\t\tthis.bump(\"coarse\");\n\t}\n\n\tdropTranscript(): void {\n\t\tthis.state.droppedItems += this.state.transcript.length;\n\t\tthis.state.transcript = [];\n\t\tthis.state.transcriptChars = 0;\n\t\tthis.toolItemsById.clear();\n\t\tthis.openThinking = undefined;\n\t\tthis.openText = undefined;\n\t\tthis.lastThinking = undefined;\n\t\tthis.lastText = undefined;\n\t\tthis.lastToolItem = undefined;\n\t\tthis.bump(\"coarse\");\n\t}\n\n\t/** Clears open/last item refs that point at an item removed from the transcript. */\n\tprivate clearRefsTo(removed: readonly TranscriptItem[]): void {\n\t\tconst removedSet = new Set<TranscriptItem>(removed);\n\t\tif (this.openThinking && removedSet.has(this.openThinking)) this.openThinking = undefined;\n\t\tif (this.openText && removedSet.has(this.openText)) this.openText = undefined;\n\t\tif (this.lastThinking && removedSet.has(this.lastThinking)) this.lastThinking = undefined;\n\t\tif (this.lastText && removedSet.has(this.lastText)) this.lastText = undefined;\n\t\tif (this.lastToolItem && removedSet.has(this.lastToolItem)) this.lastToolItem = undefined;\n\t}\n\n\tprivate applyRecord(record: ChildWireRecord): ChildStateChange {\n\t\tswitch (record.type) {\n\t\t\tcase \"session\":\n\t\t\t\tthis.state.sessionId = record.id;\n\t\t\t\tthis.state.recordsSeen++;\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.state.lifecycle = \"running\";\n\t\t\t\tthis.state.activity = \"waiting\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"message_start\":\n\t\t\t\treturn this.handleMessageStart(record.message);\n\t\t\tcase \"message_update\":\n\t\t\t\treturn this.handleMessageUpdate(record);\n\t\t\tcase \"message_end\":\n\t\t\t\treturn this.handleMessageEnd(record.message);\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\treturn this.handleToolExecutionStart(record);\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\treturn this.handleToolExecutionEnd(record);\n\t\t\tcase \"auto_retry_start\":\n\t\t\t\tthis.state.retry = {\n\t\t\t\t\tattempt: record.attempt,\n\t\t\t\t\tmaxAttempts: record.maxAttempts,\n\t\t\t\t\tdelayMs: record.delayMs,\n\t\t\t\t\terrorMessage: record.errorMessage,\n\t\t\t\t};\n\t\t\t\tthis.pushNotice(\"warning\", `retrying ${record.attempt}/${record.maxAttempts}: ${record.errorMessage}`);\n\t\t\t\tthis.state.activity = \"retrying\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"auto_retry_end\":\n\t\t\t\tthis.state.retry = undefined;\n\t\t\t\tthis.pushNotice(\n\t\t\t\t\trecord.success ? \"info\" : \"error\",\n\t\t\t\t\trecord.success ? \"retry succeeded\" : `retry failed: ${record.finalError ?? \"\"}`,\n\t\t\t\t);\n\t\t\t\tthis.state.activity = \"idle\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"compaction_start\":\n\t\t\t\tthis.pushNotice(\"info\", `compacting context (${record.reason})`);\n\t\t\t\tthis.state.activity = \"compacting\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"compaction_end\":\n\t\t\t\tthis.pushNotice(\n\t\t\t\t\trecord.errorMessage ? \"warning\" : \"info\",\n\t\t\t\t\trecord.errorMessage ? `compaction failed: ${record.errorMessage}` : \"compaction finished\",\n\t\t\t\t);\n\t\t\t\tthis.state.activity = \"idle\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"thinking_level_changed\":\n\t\t\t\tif (!isThinkingLevel(record.level)) return \"none\";\n\t\t\t\tthis.state.model = { ...this.state.model, thinkingLevel: record.level };\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"agent_settled\":\n\t\t\t\tthis.state.lifecycle = \"settled\";\n\t\t\t\tthis.state.activity = \"idle\";\n\t\t\t\tthis.state.currentTool = undefined;\n\t\t\t\tthis.blockedPending = undefined;\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tdefault:\n\t\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\tprivate handleMessageStart(\n\t\tmessage: Extract<JsonAgentSessionEvent, { type: \"message_start\" }>[\"message\"],\n\t): ChildStateChange {\n\t\tif (message.role !== \"assistant\") return \"none\";\n\t\tthis.state.turns++;\n\t\tif (!this.state.model.confirmed) {\n\t\t\tthis.state.model = { ...this.state.model, provider: message.provider, id: message.model, confirmed: true };\n\t\t} else if (this.state.model.provider !== message.provider || this.state.model.id !== message.model) {\n\t\t\tthis.pushNotice(\"info\", `model switched to ${message.provider}/${message.model}`);\n\t\t\tthis.state.model = { ...this.state.model, provider: message.provider, id: message.model, confirmed: true };\n\t\t}\n\t\tthis.state.activity = \"waiting\";\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate handleMessageEnd(\n\t\tmessage: Extract<JsonAgentSessionEvent, { type: \"message_end\" }>[\"message\"],\n\t): ChildStateChange {\n\t\tif (message.role !== \"assistant\") return \"none\";\n\t\t// Read and validate every field that could throw or be the wrong type before mutating\n\t\t// anything: a malformed `content` (not an array) must not leave usage/stopReason/errorMessage\n\t\t// already written with no version bump, as it would if `.find` threw straight out of this\n\t\t// function partway through.\n\t\tconst content = Array.isArray(message.content) ? message.content : [];\n\t\tconst textPart = content.find(isTextContent);\n\t\t// §6.3 says `model.thinkingLevel = message.thinkingLevel` verbatim; this keeps the previous\n\t\t// level instead when the field is absent (or, after hardening, not a valid level), since the\n\t\t// child only ever reports it on a subset of messages and overwriting with undefined would\n\t\t// otherwise make the live/last-known thinking level flicker to unset between turns.\n\t\tconst thinkingLevel = isThinkingLevel(message.thinkingLevel)\n\t\t\t? message.thinkingLevel\n\t\t\t: this.state.model.thinkingLevel;\n\t\tconst usage = isUsageLike(message.usage) ? message.usage : undefined;\n\n\t\tthis.state.usage =\n\t\t\tusage === undefined ? this.state.usage : this.state.usage ? combineUsage(this.state.usage, usage) : usage;\n\t\tthis.state.liveUsage = undefined;\n\t\tthis.state.model = { ...this.state.model, thinkingLevel };\n\t\tthis.state.stopReason = message.stopReason;\n\t\tthis.state.errorMessage = message.errorMessage;\n\t\tif (textPart) {\n\t\t\tthis.state.finalText = capHeadTail(textPart.text, this.limits.maxFinalTextChars);\n\t\t}\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\tthis.pushNotice(\n\t\t\t\t\"error\",\n\t\t\t\t`assistant turn ${message.stopReason}${message.errorMessage ? `: ${message.errorMessage}` : \"\"}`,\n\t\t\t);\n\t\t}\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate handleMessageUpdate(record: Extract<JsonAgentSessionEvent, { type: \"message_update\" }>): ChildStateChange {\n\t\t// Dispatched before `liveUsage` is touched: a bad delta/content type throws out of\n\t\t// `applyAssistantMessageEvent` (via appendCapped/replaceCapped below), and that throw must\n\t\t// not leave `liveUsage` mutated with no accompanying version bump.\n\t\tconst change = this.applyAssistantMessageEvent(record.assistantMessageEvent);\n\t\tif (isUsageLike(record.usage)) this.state.liveUsage = record.usage;\n\t\treturn change;\n\t}\n\n\tprivate applyAssistantMessageEvent(\n\t\tevent: Extract<JsonAgentSessionEvent, { type: \"message_update\" }>[\"assistantMessageEvent\"],\n\t): ChildStateChange {\n\t\tswitch (event.type) {\n\t\t\tcase \"thinking_start\": {\n\t\t\t\tconst item: ThinkingItem = {\n\t\t\t\t\tkind: \"thinking\",\n\t\t\t\t\tseq: this.nextSeq(),\n\t\t\t\t\trev: 1,\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tdroppedChars: 0,\n\t\t\t\t\tdone: false,\n\t\t\t\t\tredacted: false,\n\t\t\t\t};\n\t\t\t\tthis.pushItem(item);\n\t\t\t\tthis.openThinking = item;\n\t\t\t\tthis.lastThinking = item;\n\t\t\t\tthis.state.activity = \"thinking\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\t}\n\t\t\tcase \"thinking_delta\": {\n\t\t\t\tconst item = this.openThinking;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => this.appendCapped(i, event.delta));\n\t\t\t\tthis.state.activity = \"thinking\";\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"thinking_end\": {\n\t\t\t\tconst item = this.openThinking;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => {\n\t\t\t\t\tthis.replaceCapped(i, event.content);\n\t\t\t\t\ti.done = true;\n\t\t\t\t\ti.redacted = event.content === \"[Reasoning redacted]\";\n\t\t\t\t});\n\t\t\t\tthis.openThinking = undefined;\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"text_start\": {\n\t\t\t\tconst item: TextItem = {\n\t\t\t\t\tkind: \"text\",\n\t\t\t\t\tseq: this.nextSeq(),\n\t\t\t\t\trev: 1,\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tdroppedChars: 0,\n\t\t\t\t\tdone: false,\n\t\t\t\t};\n\t\t\t\tthis.pushItem(item);\n\t\t\t\tthis.openText = item;\n\t\t\t\tthis.lastText = item;\n\t\t\t\tthis.state.activity = \"writing\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\t}\n\t\t\tcase \"text_delta\": {\n\t\t\t\tconst item = this.openText;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => this.appendCapped(i, event.delta));\n\t\t\t\tthis.state.activity = \"writing\";\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"text_end\": {\n\t\t\t\tconst item = this.openText;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => {\n\t\t\t\t\tthis.replaceCapped(i, event.content);\n\t\t\t\t\ti.done = true;\n\t\t\t\t});\n\t\t\t\tthis.openText = undefined;\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"toolcall_start\": {\n\t\t\t\tconst item: ToolItem = {\n\t\t\t\t\tkind: \"tool\",\n\t\t\t\t\tseq: this.nextSeq(),\n\t\t\t\t\trev: 1,\n\t\t\t\t\ttoolCallId: event.id,\n\t\t\t\t\tname: event.toolName,\n\t\t\t\t\tsummary: \"\",\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t};\n\t\t\t\tthis.pushItem(item);\n\t\t\t\tthis.toolItemsById.set(event.id, item);\n\t\t\t\tthis.lastToolItem = item;\n\t\t\t\tthis.blockedPending = undefined;\n\t\t\t\tthis.toolcallArgBuffers.set(event.contentIndex, \"\");\n\t\t\t\tthis.state.activity = \"tool\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\t}\n\t\t\tcase \"toolcall_delta\": {\n\t\t\t\tconst buffered = this.toolcallArgBuffers.get(event.contentIndex);\n\t\t\t\tif (buffered !== undefined) {\n\t\t\t\t\tthis.toolcallArgBuffers.set(\n\t\t\t\t\t\tevent.contentIndex,\n\t\t\t\t\t\t(buffered + event.delta).slice(0, TOOLCALL_ARG_BUFFER_MAX_CHARS),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn \"none\";\n\t\t\t}\n\t\t\tcase \"toolcall_end\": {\n\t\t\t\tthis.toolcallArgBuffers.delete(event.contentIndex);\n\t\t\t\tconst item = this.toolItemsById.get(event.toolCall.id);\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => {\n\t\t\t\t\ti.summary = summarizeToolArgs(event.toolCall.name, event.toolCall.arguments);\n\t\t\t\t});\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\tprivate handleToolExecutionStart(\n\t\tevent: Extract<JsonAgentSessionEvent, { type: \"tool_execution_start\" }>,\n\t): ChildStateChange {\n\t\tlet item = this.toolItemsById.get(event.toolCallId);\n\t\tif (!item) {\n\t\t\titem = {\n\t\t\t\tkind: \"tool\",\n\t\t\t\tseq: this.nextSeq(),\n\t\t\t\trev: 1,\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\tname: event.toolName,\n\t\t\t\tsummary: summarizeToolArgs(event.toolName, event.args as JsonValue | undefined),\n\t\t\t\tstatus: \"pending\",\n\t\t\t};\n\t\t\tthis.pushItem(item);\n\t\t\tthis.toolItemsById.set(event.toolCallId, item);\n\t\t}\n\t\tthis.lastToolItem = item;\n\t\tconst startedAt = this.now();\n\t\tthis.mutateItem(item, (i) => {\n\t\t\ti.status = \"running\";\n\t\t\ti.startedAt = startedAt;\n\t\t});\n\t\tthis.state.toolCalls++;\n\t\tconst counts = this.state.toolCounts;\n\t\tconst prevCount = Object.hasOwn(counts, event.toolName) ? counts[event.toolName] : 0;\n\t\tcounts[event.toolName] = (prevCount ?? 0) + 1;\n\t\tthis.state.currentTool = { toolCallId: event.toolCallId, name: event.toolName, summary: item.summary, startedAt };\n\t\tthis.state.activity = \"tool\";\n\t\tthis.blockedPending = undefined;\n\t\tif (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {\n\t\t\tthis.pendingStructuredById.set(event.toolCallId, event.args as JsonValue);\n\t\t}\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate handleToolExecutionEnd(\n\t\tevent: Extract<JsonAgentSessionEvent, { type: \"tool_execution_end\" }>,\n\t): ChildStateChange {\n\t\tlet item = this.toolItemsById.get(event.toolCallId);\n\t\tif (!item) {\n\t\t\titem = {\n\t\t\t\tkind: \"tool\",\n\t\t\t\tseq: this.nextSeq(),\n\t\t\t\trev: 1,\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\tname: event.toolName,\n\t\t\t\tsummary: \"\",\n\t\t\t\tstatus: \"pending\",\n\t\t\t};\n\t\t\tthis.pushItem(item);\n\t\t\tthis.toolItemsById.set(event.toolCallId, item);\n\t\t}\n\t\tconst text = extractResultText(event.result);\n\t\tconst preview = text.slice(0, 200);\n\t\tconst blocked = event.isError && text.endsWith(NO_UI_APPROVAL_SUFFIX);\n\t\tthis.mutateItem(item, (i) => {\n\t\t\ti.status = blocked ? \"blocked\" : event.isError ? \"error\" : \"ok\";\n\t\t\ti.endedAt = this.now();\n\t\t\ti.resultPreview = preview;\n\t\t\tif (blocked) i.blockedReason = text;\n\t\t});\n\t\tif (event.isError) this.state.toolErrors++;\n\t\tif (blocked) {\n\t\t\tthis.state.blockedCount++;\n\t\t\tconst entry: BlockedToolCall = { toolName: event.toolName, summary: item.summary, reason: text };\n\t\t\tthis.state.blocked = [...this.state.blocked, entry].slice(-20);\n\t\t\tthis.pushNotice(\"warning\", `${event.toolName} blocked: needs approval (subagents cannot ask)`);\n\t\t\tthis.blockedPending = event.toolName;\n\t\t}\n\t\tif (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {\n\t\t\tconst pending = this.pendingStructuredById.get(event.toolCallId);\n\t\t\tthis.pendingStructuredById.delete(event.toolCallId);\n\t\t\tif (!event.isError && pending !== undefined) {\n\t\t\t\tthis.state.structured = { value: pending };\n\t\t\t}\n\t\t}\n\t\tthis.state.currentTool = undefined;\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate nextSeq(): number {\n\t\treturn this.state.nextSeq++;\n\t}\n\n\tprivate pushNotice(level: \"info\" | \"warning\" | \"error\", text: string): void {\n\t\tconst capped = truncate(collapseWhitespace(text), NOTICE_MAX_CHARS);\n\t\tthis.pushItem({ kind: \"notice\", seq: this.nextSeq(), rev: 1, level, text: capped, at: this.now() });\n\t}\n\n\tprivate pushItem(item: TranscriptItem): void {\n\t\tthis.state.transcript.push(item);\n\t\tthis.adjustChars(this.measure(item));\n\t\tthis.evictIfNeeded();\n\t}\n\n\tprivate mutateItem<T extends TranscriptItem>(item: T, mutate: (item: T) => void): void {\n\t\tconst before = this.measure(item);\n\t\tmutate(item);\n\t\titem.rev++;\n\t\tconst after = this.measure(item);\n\t\tthis.adjustChars(after - before);\n\t\tthis.evictIfNeeded();\n\t}\n\n\t/** `addition` is typed `unknown`, not `string`, on purpose: a well-typed-looking wire record can\n\t * still carry a non-string `delta` at runtime (`parseChildLine` only checks `type`), and this\n\t * must throw before touching `item.text` rather than let a non-string silently become part of\n\t * the transcript or poison `transcriptChars` with a NaN-producing `.length` on a non-string. */\n\tprivate appendCapped(item: ThinkingItem | TextItem, addition: unknown): void {\n\t\tif (typeof addition !== \"string\") throw new TypeError(\"expected a string delta\");\n\t\tconst combined = item.text + addition;\n\t\tif (combined.length > this.limits.maxItemChars) {\n\t\t\tconst removed = combined.length - this.limits.maxItemChars;\n\t\t\titem.droppedChars += removed;\n\t\t\titem.text = combined.slice(removed);\n\t\t} else {\n\t\t\titem.text = combined;\n\t\t}\n\t}\n\n\t/** The full item content replaces the accumulated (already tail-capped) text; droppedChars reflects\n\t * this final content, not the sum of every delta's cap, so it is assigned rather than accumulated.\n\t * `content` is `unknown`, not `string`, for the same reason as {@link appendCapped}'s `addition`. */\n\tprivate replaceCapped(item: ThinkingItem | TextItem, content: unknown): void {\n\t\tif (typeof content !== \"string\") throw new TypeError(\"expected a string content\");\n\t\tif (content.length > this.limits.maxItemChars) {\n\t\t\tconst removed = content.length - this.limits.maxItemChars;\n\t\t\titem.droppedChars = removed;\n\t\t\titem.text = content.slice(removed);\n\t\t} else {\n\t\t\titem.droppedChars = 0;\n\t\t\titem.text = content;\n\t\t}\n\t}\n\n\tprivate measure(item: TranscriptItem): number {\n\t\tswitch (item.kind) {\n\t\t\tcase \"thinking\":\n\t\t\tcase \"text\":\n\t\t\t\treturn item.text.length;\n\t\t\tcase \"tool\":\n\t\t\t\treturn item.summary.length + (item.resultPreview?.length ?? 0);\n\t\t\tcase \"notice\":\n\t\t\t\treturn item.text.length;\n\t\t}\n\t}\n\n\t/** Shrinks `item` in place, keeping its tail (most recent content), until `measure(item) <=\n\t * maxChars`. Used only to keep the newest transcript item instead of evicting it outright. */\n\tprivate tailTrimToFit(item: TranscriptItem, maxChars: number): void {\n\t\tconst over = this.measure(item) - Math.max(0, maxChars);\n\t\tif (over <= 0) return;\n\t\tswitch (item.kind) {\n\t\t\tcase \"thinking\":\n\t\t\tcase \"text\":\n\t\t\t\titem.droppedChars += over;\n\t\t\t\titem.text = item.text.slice(over);\n\t\t\t\tbreak;\n\t\t\tcase \"notice\":\n\t\t\t\titem.text = item.text.slice(over);\n\t\t\t\tbreak;\n\t\t\tcase \"tool\": {\n\t\t\t\tlet remaining = over;\n\t\t\t\tif (item.resultPreview) {\n\t\t\t\t\tconst trimmed = Math.min(remaining, item.resultPreview.length);\n\t\t\t\t\titem.resultPreview = item.resultPreview.slice(trimmed);\n\t\t\t\t\tremaining -= trimmed;\n\t\t\t\t}\n\t\t\t\tif (remaining > 0) item.summary = item.summary.slice(remaining);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\titem.rev++;\n\t}\n\n\tprivate adjustChars(delta: number): void {\n\t\tconst next = this.state.transcriptChars + delta;\n\t\t// A NaN delta (impossible for a string's `.length`, but transcriptChars is otherwise an\n\t\t// unguarded running total) must not permanently poison the count: Number.isFinite rejects it\n\t\t// and leaves the previous value in place instead of letting Math.max(0, NaN) propagate NaN.\n\t\tif (Number.isFinite(next)) this.state.transcriptChars = Math.max(0, next);\n\t}\n\n\tprivate evictIfNeeded(): void {\n\t\tconst removed: TranscriptItem[] = [];\n\t\twhile (this.state.transcript.length > this.limits.maxItems || this.state.transcriptChars > this.limits.maxChars) {\n\t\t\tconst idx = this.state.transcript.findIndex((item) => !this.isOpenItem(item));\n\t\t\tif (idx === -1) break;\n\t\t\tif (idx === this.state.transcript.length - 1) {\n\t\t\t\t// This is the only evictable item left (every open item is already exempt, and\n\t\t\t\t// everything else has already been dropped): tail-trim it instead of dropping it, so\n\t\t\t\t// one huge item (one notice with a child-supplied error message, say) cannot empty the\n\t\t\t\t// whole live transcript. Nothing else is left to evict either way, so stop here.\n\t\t\t\tconst item = this.state.transcript[idx] as TranscriptItem;\n\t\t\t\tconst before = this.measure(item);\n\t\t\t\tthis.tailTrimToFit(item, this.limits.maxChars);\n\t\t\t\tthis.adjustChars(this.measure(item) - before);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst item = this.state.transcript.splice(idx, 1)[0];\n\t\t\tif (!item) break;\n\t\t\tthis.adjustChars(-this.measure(item));\n\t\t\tthis.state.droppedItems++;\n\t\t\tif (item.kind === \"tool\") this.toolItemsById.delete(item.toolCallId);\n\t\t\tremoved.push(item);\n\t\t}\n\t\tif (removed.length > 0) this.clearRefsTo(removed);\n\t}\n\n\tprivate isOpenItem(item: TranscriptItem): boolean {\n\t\treturn item === this.openThinking || item === this.openText;\n\t}\n\n\tprivate bump(change: ChildStateChange): ChildStateChange {\n\t\tif (change === \"none\") return change;\n\t\tthis.state.version++;\n\t\tif (change === \"coarse\") this.state.coarseVersion++;\n\t\tthis.state.lastEventAt = this.now();\n\t\tthis.state.nowLine = this.computeNowLine();\n\t\treturn change;\n\t}\n\n\tprivate computeNowLine(): string {\n\t\tif (this.blockedPending) {\n\t\t\treturn clampHead(\"⚠\", `${this.blockedPending} blocked: needs approval`);\n\t\t}\n\t\tswitch (this.state.activity) {\n\t\t\tcase \"thinking\":\n\t\t\t\treturn clampTail(\"thinking · \", (this.openThinking ?? this.lastThinking)?.text ?? \"\");\n\t\t\tcase \"writing\":\n\t\t\t\treturn clampTail(\"writing · \", (this.openText ?? this.lastText)?.text ?? \"\");\n\t\t\tcase \"tool\": {\n\t\t\t\tconst item = this.lastToolItem;\n\t\t\t\treturn item ? clampHead(item.name, item.summary) : \"\";\n\t\t\t}\n\t\t\tcase \"waiting\":\n\t\t\t\treturn \"waiting for model\";\n\t\t\tcase \"retrying\": {\n\t\t\t\tconst retry = this.state.retry;\n\t\t\t\treturn retry\n\t\t\t\t\t? clampHead(`retrying ${retry.attempt}/${retry.maxAttempts} ·`, retry.errorMessage)\n\t\t\t\t\t: \"retrying\";\n\t\t\t}\n\t\t\tcase \"compacting\":\n\t\t\t\treturn \"compacting context\";\n\t\t\tcase \"idle\":\n\t\t\t\treturn this.state.lifecycle === \"settled\" ? \"finished\" : \"\";\n\t\t\tdefault:\n\t\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nfunction resolveModelRef(state: Readonly<ChildAgentState>): ModelRef | undefined {\n\tif (!state.model.confirmed || !state.model.provider || !state.model.id) return undefined;\n\treturn { provider: state.model.provider, id: state.model.id };\n}\n\nexport function toRunResult(\n\tstate: Readonly<ChildAgentState>,\n\tbase: { agent: string; task: string; step?: number },\n\tfinish: ChildFinish,\n\textras: { cancelled: boolean; structured?: { value: JsonValue }; durationMs: number },\n): RunResult {\n\tconst failedResponse = state.stopReason === \"error\" || state.stopReason === \"aborted\";\n\tconst stderr =\n\t\tstate.stderrTail.length > 0\n\t\t\t? state.stderrTail\n\t\t\t: failedResponse\n\t\t\t\t? (state.errorMessage ?? state.stopReason ?? \"\")\n\t\t\t\t: (finish.failure ?? \"\");\n\n\treturn {\n\t\tagent: base.agent,\n\t\ttask: base.task,\n\t\tstep: base.step,\n\t\texitCode: finish.exitCode,\n\t\toutput: state.finalText,\n\t\tstderr,\n\t\tusage: state.usage,\n\t\tmodel: resolveModelRef(state),\n\t\tthinkingLevel: state.model.thinkingLevel,\n\t\tstopReason: state.stopReason,\n\t\tturns: state.turns,\n\t\ttoolCalls: state.toolCalls,\n\t\tblockedToolCalls: state.blockedCount,\n\t\tstructured: extras.structured,\n\t\tcancelled: extras.cancelled,\n\t\tdurationMs: extras.durationMs,\n\t};\n}\n"]}
1
+ {"version":3,"file":"child-events.js","sourceRoot":"","sources":["../../../src/core/polyphase/child-events.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAMN,0BAA0B,EAC1B,eAAe,EAEf,qBAAqB,EACrB,0BAA0B,GAG1B,MAAM,YAAY,CAAC;AAYpB,wGAAwG;AACxG,MAAM,UAAU,cAAc,CAAC,IAAY;IAC1C,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACJ,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAC7F,IAAI,OAAQ,MAAkC,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACnF,OAAO,MAAyB,CAAC;AAClC,CAAC;AAED,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,MAA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AS;QACvB,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC;QAC7B,aAAa,EAAE,KAAK,CAAC,KAAK,CAAC,aAAa;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,gBAAgB,EAAE,KAAK,CAAC,YAAY;QACpC,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,UAAU,EAAE,MAAM,CAAC,UAAU;KAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { JsonObject, JsonValue, TextContent, Usage } from \"@draht/ai\";\nimport type { JsonAgentSessionEvent } from \"../../modes/json-event.ts\";\nimport { combineUsage } from \"../usage-totals.ts\";\nimport {\n\ttype AgentModelInfo,\n\ttype BlockedToolCall,\n\ttype ChildAgentState,\n\ttype ChildStateChange,\n\ttype ChildStateLimits,\n\tDEFAULT_CHILD_STATE_LIMITS,\n\tisThinkingLevel,\n\ttype ModelRef,\n\tNO_UI_APPROVAL_SUFFIX,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\ttype RunResult,\n\ttype TranscriptItem,\n} from \"./types.ts\";\n\nexport interface SessionHeaderRecord {\n\ttype: \"session\";\n\tid: string;\n\tcwd?: string;\n\ttimestamp?: string;\n\tversion?: number;\n}\n\nexport type ChildWireRecord = SessionHeaderRecord | JsonAgentSessionEvent;\n\n/** JSON.parse in try/catch; returns undefined for malformed lines or values without a string `type`. */\nexport function parseChildLine(line: string): ChildWireRecord | undefined {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\tif (typeof (parsed as Record<string, unknown>).type !== \"string\") return undefined;\n\treturn parsed as ChildWireRecord;\n}\n\nconst SUMMARY_MAX_CHARS = 120;\nconst SUMMARY_ARG_KEYS = [\"command\", \"path\", \"file_path\", \"pattern\", \"query\", \"url\"] as const;\nconst TOOLCALL_ARG_BUFFER_MAX_CHARS = 2048;\n/** Single line, collapsed and ellipsised: a child-supplied error/finalError can be arbitrarily\n * long, and an uncapped notice is the one item kind that can grow larger than a whole run's\n * retention budget on its own (see trimForRetention/evictIfNeeded below). */\nconst NOTICE_MAX_CHARS = 1000;\n\nfunction truncate(value: string, max: number): string {\n\treturn value.length <= max ? value : `${value.slice(0, max - 1)}…`;\n}\n\n/** Collapses newlines and runs of whitespace so single-line contracts (summaries, nowLine) hold. */\nfunction collapseWhitespace(value: string): string {\n\treturn value.replace(/\\s+/g, \" \").trim();\n}\n\n/** One line ≤ 120 chars: command | path | file_path | pattern | query | url, else compact JSON. */\nexport function summarizeToolArgs(_toolName: string, args: JsonValue | undefined): string {\n\tif (args && typeof args === \"object\" && !Array.isArray(args)) {\n\t\tconst record = args as JsonObject;\n\t\tfor (const key of SUMMARY_ARG_KEYS) {\n\t\t\tconst value = record[key];\n\t\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\t\treturn truncate(collapseWhitespace(value), SUMMARY_MAX_CHARS);\n\t\t\t}\n\t\t}\n\t}\n\treturn truncate(collapseWhitespace(args === undefined ? \"\" : JSON.stringify(args)), SUMMARY_MAX_CHARS);\n}\n\nconst STATUS_LINE_PATTERN = /^STATUS:\\s*\\S.*$/gm;\n\n/** Last line matching /^STATUS:\\s*\\S.*$/m, trimmed. */\nexport function extractStatusLine(text: string): string | undefined {\n\tconst matches = text.match(STATUS_LINE_PATTERN);\n\tif (!matches || matches.length === 0) return undefined;\n\treturn matches[matches.length - 1]?.trim();\n}\n\n/** input + output + cacheWrite (cache reads excluded); 0 for undefined. */\nexport function billableTokens(usage: Usage | undefined): number {\n\tif (!usage) return 0;\n\treturn usage.input + usage.output + usage.cacheWrite;\n}\n\nexport function createChildAgentState(model: AgentModelInfo): ChildAgentState {\n\treturn {\n\t\tlifecycle: \"pending\",\n\t\tactivity: \"idle\",\n\t\tmodel,\n\t\tturns: 0,\n\t\ttoolCalls: 0,\n\t\ttoolErrors: 0,\n\t\ttoolCounts: {},\n\t\tblocked: [],\n\t\tblockedCount: 0,\n\t\ttranscript: [],\n\t\ttranscriptChars: 0,\n\t\tdroppedItems: 0,\n\t\tnextSeq: 0,\n\t\tnowLine: \"\",\n\t\tfinalText: \"\",\n\t\tstderrTail: \"\",\n\t\tmalformedLines: 0,\n\t\tdroppedLines: 0,\n\t\trecordsSeen: 0,\n\t\tversion: 0,\n\t\tcoarseVersion: 0,\n\t};\n}\n\nexport interface ChildExit {\n\tcode: number | null;\n\tsignal: NodeJS.Signals | null;\n\tcancelled: boolean;\n\tspawnError?: string;\n}\n\nexport interface ChildFinish {\n\texitCode: number;\n\tfailure?: string;\n}\n\ntype ThinkingItem = Extract<TranscriptItem, { kind: \"thinking\" }>;\ntype TextItem = Extract<TranscriptItem, { kind: \"text\" }>;\ntype ToolItem = Extract<TranscriptItem, { kind: \"tool\" }>;\n\nfunction isTextContent(value: unknown): value is TextContent {\n\treturn !!value && typeof value === \"object\" && (value as { type?: unknown }).type === \"text\";\n}\n\n/** Shallow guard against a well-typed-looking `message_update`/`message_end` record whose `usage`\n * field is not actually an object (e.g. a string or number from a malformed wire record). */\nfunction isUsageLike(value: unknown): value is Usage {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction extractResultText(result: unknown): string {\n\tif (typeof result !== \"object\" || result === null) return \"\";\n\tconst content = (result as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return \"\";\n\tconst parts: string[] = [];\n\tfor (const block of content) {\n\t\tif (isTextContent(block)) parts.push(block.text);\n\t}\n\treturn parts.join(\"\");\n}\n\nfunction capHeadTail(text: string, max: number): string {\n\tif (text.length <= max) return text;\n\tconst marker = `\\n[... ${text.length - max} characters omitted ...]\\n`;\n\tconst keep = Math.max(0, max - marker.length);\n\tconst headLen = Math.floor(keep * 0.4);\n\tconst tailLen = keep - headLen;\n\treturn text.slice(0, headLen) + marker + text.slice(text.length - tailLen);\n}\n\n/** Last non-empty line of `text`: a streamed thinking/text delta often ends with one or more\n * trailing newlines (a paragraph break), which would otherwise make `nowLine` blank between\n * paragraphs even though the agent is still working. */\nfunction lastLine(text: string): string {\n\tconst trimmed = text.replace(/\\s+$/, \"\");\n\tconst nl = trimmed.lastIndexOf(\"\\n\");\n\treturn nl === -1 ? trimmed : trimmed.slice(nl + 1);\n}\n\n/** `prefix` plus the collapsed tail of `text`'s last line, kept on one line within `max` chars. */\nfunction clampTail(prefix: string, text: string, max = 160): string {\n\tconst collapsed = collapseWhitespace(lastLine(text));\n\tconst budget = Math.max(0, max - prefix.length);\n\tconst tail = collapsed.length <= budget ? collapsed : collapsed.slice(collapsed.length - budget);\n\treturn `${prefix}${tail}`;\n}\n\n/** `head` plus as much of the collapsed `rest` as fits within `max` chars, single line. */\nfunction clampHead(head: string, rest: string, max = 160): string {\n\tconst collapsed = collapseWhitespace(rest);\n\t// -1 reserves the separator space added below so the result never exceeds `max`.\n\tconst budget = Math.max(0, max - head.length - 1);\n\t// `truncate` itself slices to `budget`, so pre-slicing to `budget` first (as before) made it a\n\t// no-op and the ellipsis never appeared; budget === 0 is left empty rather than calling\n\t// `truncate` with it, since `truncate`'s own minimum output is one char plus an ellipsis.\n\tconst kept = budget > 0 ? truncate(collapsed, budget) : \"\";\n\treturn kept.length > 0 ? `${head} ${kept}` : head;\n}\n\nexport class ChildEventReducer {\n\treadonly state: ChildAgentState;\n\tprivate readonly limits: ChildStateLimits;\n\tprivate readonly now: () => number;\n\n\tprivate toolItemsById = new Map<string, ToolItem>();\n\tprivate openThinking: ThinkingItem | undefined;\n\tprivate openText: TextItem | undefined;\n\t/** Last thinking/text item, kept past `*_end` so `nowLine` shows its final content instead of going blank. */\n\tprivate lastThinking: ThinkingItem | undefined;\n\tprivate lastText: TextItem | undefined;\n\tprivate lastToolItem: ToolItem | undefined;\n\tprivate blockedPending: string | undefined;\n\tprivate pendingStructuredById = new Map<string, JsonValue>();\n\t/** Buffered `toolcall_delta` argument JSON per content index, up to `TOOLCALL_ARG_BUFFER_MAX_CHARS` (not surfaced). */\n\tprivate toolcallArgBuffers = new Map<number, string>();\n\tprivate lastHeartbeatAt = Number.NEGATIVE_INFINITY;\n\n\tconstructor(init: { model: AgentModelInfo; limits?: Partial<ChildStateLimits>; now?: () => number }) {\n\t\tthis.limits = { ...DEFAULT_CHILD_STATE_LIMITS, ...init.limits };\n\t\tthis.now = init.now ?? Date.now;\n\t\tthis.state = createChildAgentState(init.model);\n\t}\n\n\tmarkQueued(): ChildStateChange {\n\t\tthis.state.lifecycle = \"queued\";\n\t\tthis.state.queuedAt = this.now();\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tmarkSpawning(): ChildStateChange {\n\t\tthis.state.lifecycle = \"spawning\";\n\t\tthis.state.startedAt = this.now();\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tapply(record: ChildWireRecord): ChildStateChange {\n\t\ttry {\n\t\t\treturn this.applyRecord(record);\n\t\t} catch {\n\t\t\tthis.state.malformedLines++;\n\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\t/** For skipped tool_execution_update lines: \"fine\" at most once per second, else \"none\". */\n\tnoteHeartbeat(): ChildStateChange {\n\t\tconst now = this.now();\n\t\tif (now - this.lastHeartbeatAt < 1000) return \"none\";\n\t\tthis.lastHeartbeatAt = now;\n\t\treturn this.bump(\"fine\");\n\t}\n\n\tnoteStderr(chunk: string): void {\n\t\tthis.state.stderrTail = (this.state.stderrTail + chunk).slice(-this.limits.maxStderrChars);\n\t}\n\n\t/** Fallback re-spawn: reset everything except queuedAt/startedAt; add an info notice. */\n\tresetForRetry(model: AgentModelInfo, notice: string): void {\n\t\tconst queuedAt = this.state.queuedAt;\n\t\tconst startedAt = this.state.startedAt;\n\t\t// version/coarseVersion/nextSeq are monotonic cache keys for pump/store/renderer caches and must\n\t\t// never go backwards; everything else from the failed attempt is dropped.\n\t\tconst version = this.state.version;\n\t\tconst coarseVersion = this.state.coarseVersion;\n\t\tconst nextSeq = this.state.nextSeq;\n\t\tObject.assign(this.state, createChildAgentState(model));\n\t\t// createChildAgentState omits these optional fields rather than setting them to undefined, so\n\t\t// Object.assign leaves a stale value behind; clear them explicitly.\n\t\tthis.state.sessionId = undefined;\n\t\tthis.state.usage = undefined;\n\t\tthis.state.liveUsage = undefined;\n\t\tthis.state.stopReason = undefined;\n\t\tthis.state.errorMessage = undefined;\n\t\tthis.state.structured = undefined;\n\t\tthis.state.retry = undefined;\n\t\tthis.state.currentTool = undefined;\n\t\tthis.state.endedAt = undefined;\n\t\tthis.state.lastEventAt = undefined;\n\t\tthis.state.queuedAt = queuedAt;\n\t\tthis.state.startedAt = startedAt;\n\t\tthis.state.version = version;\n\t\tthis.state.coarseVersion = coarseVersion;\n\t\tthis.state.nextSeq = nextSeq;\n\t\t// Not in the design's \"reset everything except queuedAt/startedAt\": createChildAgentState's\n\t\t// default (\"pending\") would otherwise briefly misreport a retry as not-yet-asked-to-run, when\n\t\t// a new child process is in fact already being spawned for it.\n\t\tthis.state.lifecycle = \"spawning\";\n\t\tthis.toolItemsById.clear();\n\t\tthis.openThinking = undefined;\n\t\tthis.openText = undefined;\n\t\tthis.lastThinking = undefined;\n\t\tthis.lastText = undefined;\n\t\tthis.lastToolItem = undefined;\n\t\tthis.blockedPending = undefined;\n\t\tthis.pendingStructuredById.clear();\n\t\tthis.toolcallArgBuffers.clear();\n\t\tthis.lastHeartbeatAt = Number.NEGATIVE_INFINITY;\n\t\tthis.pushNotice(\"info\", notice);\n\t\tthis.bump(\"coarse\");\n\t}\n\n\tfinish(exit: ChildExit): ChildFinish {\n\t\tconst wasSettled = this.state.lifecycle === \"settled\";\n\t\tthis.state.lifecycle = \"exited\";\n\t\tthis.state.endedAt = this.now();\n\t\tthis.blockedPending = undefined;\n\n\t\t// The child stopped sending deltas (cancelled, crashed, or SIGTERM'd mid-stream), but the\n\t\t// last-open thinking/text item is still `done: false`. Left alone, the transcript renderer\n\t\t// keeps drawing its live cursor (`▌`) on an agent that has already exited.\n\t\tif (this.openThinking) {\n\t\t\tthis.mutateItem(this.openThinking, (item) => {\n\t\t\t\titem.done = true;\n\t\t\t});\n\t\t\tthis.openThinking = undefined;\n\t\t}\n\t\tif (this.openText) {\n\t\t\tthis.mutateItem(this.openText, (item) => {\n\t\t\t\titem.done = true;\n\t\t\t});\n\t\t\tthis.openText = undefined;\n\t\t}\n\n\t\tlet exitCode: number;\n\t\tlet failure: string | undefined;\n\t\tif (exit.cancelled) {\n\t\t\texitCode = 1;\n\t\t\tfailure = \"cancelled\";\n\t\t} else if (exit.spawnError) {\n\t\t\texitCode = 1;\n\t\t\tfailure = `failed to start: ${exit.spawnError}`;\n\t\t} else if (exit.code === 0 && this.state.stopReason !== \"error\" && this.state.stopReason !== \"aborted\") {\n\t\t\texitCode = 0;\n\t\t} else {\n\t\t\texitCode = 1;\n\t\t\t// §6.4 gives \"child exited (code X) before producing output\" verbatim for rule 1 and\n\t\t\t// omits a signal from rule 2's wording too; both messages add it here when present,\n\t\t\t// since a SIGTERM/SIGKILL is exactly the kind of detail worth keeping in a failure a\n\t\t\t// user may have to debug, and neither message is pattern-matched downstream.\n\t\t\tconst signalSuffix = exit.signal ? `, signal ${exit.signal}` : \"\";\n\t\t\tif (this.state.recordsSeen === 0) {\n\t\t\t\tfailure = `child exited (code ${exit.code}${signalSuffix}) before producing output`;\n\t\t\t} else if (!wasSettled) {\n\t\t\t\tfailure = `child exited (code ${exit.code}${signalSuffix}) before settling`;\n\t\t\t} else {\n\t\t\t\tconst stopReasonIsFailure = this.state.stopReason === \"error\" || this.state.stopReason === \"aborted\";\n\t\t\t\tfailure =\n\t\t\t\t\tthis.state.errorMessage ??\n\t\t\t\t\t(stopReasonIsFailure ? this.state.stopReason : `child exited (code ${exit.code}${signalSuffix})`);\n\t\t\t}\n\t\t}\n\n\t\tthis.bump(\"coarse\");\n\t\treturn { exitCode, failure };\n\t}\n\n\t/** After the run finished: keep the newest `maxChars` transcript chars. */\n\ttrimForRetention(maxChars: number): void {\n\t\tconst transcript = this.state.transcript;\n\t\tif (transcript.length === 0) {\n\t\t\tthis.state.transcriptChars = 0;\n\t\t\tthis.bump(\"coarse\");\n\t\t\treturn;\n\t\t}\n\n\t\t// The newest item is kept unconditionally, even if it alone is larger than `maxChars`:\n\t\t// tail-trimming it still loses only its oldest content, whereas dropping it (the previous\n\t\t// behaviour, when `total + size > maxChars` was already true on the first iteration) could\n\t\t// empty the whole transcript right after a run whose last item was one huge notice or error.\n\t\tconst lastIndex = transcript.length - 1;\n\t\tconst last = transcript[lastIndex] as TranscriptItem;\n\t\tthis.tailTrimToFit(last, maxChars);\n\n\t\tlet total = this.measure(last);\n\t\tlet cutIndex = lastIndex;\n\t\tfor (let i = lastIndex - 1; i >= 0; i--) {\n\t\t\tconst item = transcript[i];\n\t\t\tif (!item) continue;\n\t\t\tconst size = this.measure(item);\n\t\t\tif (total + size > maxChars) {\n\t\t\t\tcutIndex = i + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttotal += size;\n\t\t\tcutIndex = i;\n\t\t}\n\n\t\tif (cutIndex > 0) {\n\t\t\tconst removed = transcript.splice(0, cutIndex);\n\t\t\tthis.state.droppedItems += removed.length;\n\t\t\tfor (const item of removed) {\n\t\t\t\tif (item.kind === \"tool\") this.toolItemsById.delete(item.toolCallId);\n\t\t\t}\n\t\t\tthis.clearRefsTo(removed);\n\t\t}\n\t\tthis.state.transcriptChars = total;\n\t\tthis.bump(\"coarse\");\n\t}\n\n\tdropTranscript(): void {\n\t\tthis.state.droppedItems += this.state.transcript.length;\n\t\tthis.state.transcript = [];\n\t\tthis.state.transcriptChars = 0;\n\t\tthis.toolItemsById.clear();\n\t\tthis.openThinking = undefined;\n\t\tthis.openText = undefined;\n\t\tthis.lastThinking = undefined;\n\t\tthis.lastText = undefined;\n\t\tthis.lastToolItem = undefined;\n\t\tthis.bump(\"coarse\");\n\t}\n\n\t/** Clears open/last item refs that point at an item removed from the transcript. */\n\tprivate clearRefsTo(removed: readonly TranscriptItem[]): void {\n\t\tconst removedSet = new Set<TranscriptItem>(removed);\n\t\tif (this.openThinking && removedSet.has(this.openThinking)) this.openThinking = undefined;\n\t\tif (this.openText && removedSet.has(this.openText)) this.openText = undefined;\n\t\tif (this.lastThinking && removedSet.has(this.lastThinking)) this.lastThinking = undefined;\n\t\tif (this.lastText && removedSet.has(this.lastText)) this.lastText = undefined;\n\t\tif (this.lastToolItem && removedSet.has(this.lastToolItem)) this.lastToolItem = undefined;\n\t}\n\n\tprivate applyRecord(record: ChildWireRecord): ChildStateChange {\n\t\tswitch (record.type) {\n\t\t\tcase \"session\":\n\t\t\t\tthis.state.sessionId = record.id;\n\t\t\t\tthis.state.recordsSeen++;\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.state.lifecycle = \"running\";\n\t\t\t\tthis.state.activity = \"waiting\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"message_start\":\n\t\t\t\treturn this.handleMessageStart(record.message);\n\t\t\tcase \"message_update\":\n\t\t\t\treturn this.handleMessageUpdate(record);\n\t\t\tcase \"message_end\":\n\t\t\t\treturn this.handleMessageEnd(record.message);\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\treturn this.handleToolExecutionStart(record);\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\treturn this.handleToolExecutionEnd(record);\n\t\t\tcase \"auto_retry_start\":\n\t\t\t\tthis.state.retry = {\n\t\t\t\t\tattempt: record.attempt,\n\t\t\t\t\tmaxAttempts: record.maxAttempts,\n\t\t\t\t\tdelayMs: record.delayMs,\n\t\t\t\t\terrorMessage: record.errorMessage,\n\t\t\t\t};\n\t\t\t\tthis.pushNotice(\"warning\", `retrying ${record.attempt}/${record.maxAttempts}: ${record.errorMessage}`);\n\t\t\t\tthis.state.activity = \"retrying\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"auto_retry_end\":\n\t\t\t\tthis.state.retry = undefined;\n\t\t\t\tthis.pushNotice(\n\t\t\t\t\trecord.success ? \"info\" : \"error\",\n\t\t\t\t\trecord.success ? \"retry succeeded\" : `retry failed: ${record.finalError ?? \"\"}`,\n\t\t\t\t);\n\t\t\t\tthis.state.activity = \"idle\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"compaction_start\":\n\t\t\t\tthis.pushNotice(\"info\", `compacting context (${record.reason})`);\n\t\t\t\tthis.state.activity = \"compacting\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"compaction_end\":\n\t\t\t\tthis.pushNotice(\n\t\t\t\t\trecord.errorMessage ? \"warning\" : \"info\",\n\t\t\t\t\trecord.errorMessage ? `compaction failed: ${record.errorMessage}` : \"compaction finished\",\n\t\t\t\t);\n\t\t\t\tthis.state.activity = \"idle\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"thinking_level_changed\":\n\t\t\t\tif (!isThinkingLevel(record.level)) return \"none\";\n\t\t\t\tthis.state.model = { ...this.state.model, thinkingLevel: record.level };\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tcase \"agent_settled\":\n\t\t\t\tthis.state.lifecycle = \"settled\";\n\t\t\t\tthis.state.activity = \"idle\";\n\t\t\t\tthis.state.currentTool = undefined;\n\t\t\t\tthis.blockedPending = undefined;\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\tdefault:\n\t\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\tprivate handleMessageStart(\n\t\tmessage: Extract<JsonAgentSessionEvent, { type: \"message_start\" }>[\"message\"],\n\t): ChildStateChange {\n\t\tif (message.role !== \"assistant\") return \"none\";\n\t\tthis.state.turns++;\n\t\tif (!this.state.model.confirmed) {\n\t\t\tthis.state.model = { ...this.state.model, provider: message.provider, id: message.model, confirmed: true };\n\t\t} else if (this.state.model.provider !== message.provider || this.state.model.id !== message.model) {\n\t\t\tthis.pushNotice(\"info\", `model switched to ${message.provider}/${message.model}`);\n\t\t\tthis.state.model = { ...this.state.model, provider: message.provider, id: message.model, confirmed: true };\n\t\t}\n\t\tthis.state.activity = \"waiting\";\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate handleMessageEnd(\n\t\tmessage: Extract<JsonAgentSessionEvent, { type: \"message_end\" }>[\"message\"],\n\t): ChildStateChange {\n\t\tif (message.role !== \"assistant\") return \"none\";\n\t\t// Read and validate every field that could throw or be the wrong type before mutating\n\t\t// anything: a malformed `content` (not an array) must not leave usage/stopReason/errorMessage\n\t\t// already written with no version bump, as it would if `.find` threw straight out of this\n\t\t// function partway through.\n\t\tconst content = Array.isArray(message.content) ? message.content : [];\n\t\tconst textPart = content.find(isTextContent);\n\t\t// §6.3 says `model.thinkingLevel = message.thinkingLevel` verbatim; this keeps the previous\n\t\t// level instead when the field is absent (or, after hardening, not a valid level), since the\n\t\t// child only ever reports it on a subset of messages and overwriting with undefined would\n\t\t// otherwise make the live/last-known thinking level flicker to unset between turns.\n\t\tconst thinkingLevel = isThinkingLevel(message.thinkingLevel)\n\t\t\t? message.thinkingLevel\n\t\t\t: this.state.model.thinkingLevel;\n\t\tconst usage = isUsageLike(message.usage) ? message.usage : undefined;\n\n\t\tthis.state.usage =\n\t\t\tusage === undefined ? this.state.usage : this.state.usage ? combineUsage(this.state.usage, usage) : usage;\n\t\tthis.state.liveUsage = undefined;\n\t\tthis.state.model = { ...this.state.model, thinkingLevel };\n\t\tthis.state.stopReason = message.stopReason;\n\t\tthis.state.errorMessage = message.errorMessage;\n\t\tif (textPart) {\n\t\t\tthis.state.finalText = capHeadTail(textPart.text, this.limits.maxFinalTextChars);\n\t\t}\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\tthis.pushNotice(\n\t\t\t\t\"error\",\n\t\t\t\t`assistant turn ${message.stopReason}${message.errorMessage ? `: ${message.errorMessage}` : \"\"}`,\n\t\t\t);\n\t\t}\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate handleMessageUpdate(record: Extract<JsonAgentSessionEvent, { type: \"message_update\" }>): ChildStateChange {\n\t\t// Dispatched before `liveUsage` is touched: a bad delta/content type throws out of\n\t\t// `applyAssistantMessageEvent` (via appendCapped/replaceCapped below), and that throw must\n\t\t// not leave `liveUsage` mutated with no accompanying version bump.\n\t\tconst change = this.applyAssistantMessageEvent(record.assistantMessageEvent);\n\t\tif (isUsageLike(record.usage)) this.state.liveUsage = record.usage;\n\t\treturn change;\n\t}\n\n\tprivate applyAssistantMessageEvent(\n\t\tevent: Extract<JsonAgentSessionEvent, { type: \"message_update\" }>[\"assistantMessageEvent\"],\n\t): ChildStateChange {\n\t\tswitch (event.type) {\n\t\t\tcase \"thinking_start\": {\n\t\t\t\tconst item: ThinkingItem = {\n\t\t\t\t\tkind: \"thinking\",\n\t\t\t\t\tseq: this.nextSeq(),\n\t\t\t\t\trev: 1,\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tdroppedChars: 0,\n\t\t\t\t\tdone: false,\n\t\t\t\t\tredacted: false,\n\t\t\t\t};\n\t\t\t\tthis.pushItem(item);\n\t\t\t\tthis.openThinking = item;\n\t\t\t\tthis.lastThinking = item;\n\t\t\t\tthis.state.activity = \"thinking\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\t}\n\t\t\tcase \"thinking_delta\": {\n\t\t\t\tconst item = this.openThinking;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => this.appendCapped(i, event.delta));\n\t\t\t\tthis.state.activity = \"thinking\";\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"thinking_end\": {\n\t\t\t\tconst item = this.openThinking;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => {\n\t\t\t\t\tthis.replaceCapped(i, event.content);\n\t\t\t\t\ti.done = true;\n\t\t\t\t\ti.redacted = event.content === \"[Reasoning redacted]\";\n\t\t\t\t});\n\t\t\t\tthis.openThinking = undefined;\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"text_start\": {\n\t\t\t\tconst item: TextItem = {\n\t\t\t\t\tkind: \"text\",\n\t\t\t\t\tseq: this.nextSeq(),\n\t\t\t\t\trev: 1,\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\tdroppedChars: 0,\n\t\t\t\t\tdone: false,\n\t\t\t\t};\n\t\t\t\tthis.pushItem(item);\n\t\t\t\tthis.openText = item;\n\t\t\t\tthis.lastText = item;\n\t\t\t\tthis.state.activity = \"writing\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\t}\n\t\t\tcase \"text_delta\": {\n\t\t\t\tconst item = this.openText;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => this.appendCapped(i, event.delta));\n\t\t\t\tthis.state.activity = \"writing\";\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"text_end\": {\n\t\t\t\tconst item = this.openText;\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => {\n\t\t\t\t\tthis.replaceCapped(i, event.content);\n\t\t\t\t\ti.done = true;\n\t\t\t\t});\n\t\t\t\tthis.openText = undefined;\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tcase \"toolcall_start\": {\n\t\t\t\tconst item: ToolItem = {\n\t\t\t\t\tkind: \"tool\",\n\t\t\t\t\tseq: this.nextSeq(),\n\t\t\t\t\trev: 1,\n\t\t\t\t\ttoolCallId: event.id,\n\t\t\t\t\tname: event.toolName,\n\t\t\t\t\tsummary: \"\",\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t};\n\t\t\t\tthis.pushItem(item);\n\t\t\t\tthis.toolItemsById.set(event.id, item);\n\t\t\t\tthis.lastToolItem = item;\n\t\t\t\tthis.blockedPending = undefined;\n\t\t\t\tthis.toolcallArgBuffers.set(event.contentIndex, \"\");\n\t\t\t\tthis.state.activity = \"tool\";\n\t\t\t\treturn this.bump(\"coarse\");\n\t\t\t}\n\t\t\tcase \"toolcall_delta\": {\n\t\t\t\tconst buffered = this.toolcallArgBuffers.get(event.contentIndex);\n\t\t\t\tif (buffered !== undefined) {\n\t\t\t\t\tthis.toolcallArgBuffers.set(\n\t\t\t\t\t\tevent.contentIndex,\n\t\t\t\t\t\t(buffered + event.delta).slice(0, TOOLCALL_ARG_BUFFER_MAX_CHARS),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn \"none\";\n\t\t\t}\n\t\t\tcase \"toolcall_end\": {\n\t\t\t\tthis.toolcallArgBuffers.delete(event.contentIndex);\n\t\t\t\tconst item = this.toolItemsById.get(event.toolCall.id);\n\t\t\t\tif (!item) return \"none\";\n\t\t\t\tthis.mutateItem(item, (i) => {\n\t\t\t\t\ti.summary = summarizeToolArgs(event.toolCall.name, event.toolCall.arguments);\n\t\t\t\t});\n\t\t\t\treturn this.bump(\"fine\");\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\tprivate handleToolExecutionStart(\n\t\tevent: Extract<JsonAgentSessionEvent, { type: \"tool_execution_start\" }>,\n\t): ChildStateChange {\n\t\tlet item = this.toolItemsById.get(event.toolCallId);\n\t\tif (!item) {\n\t\t\titem = {\n\t\t\t\tkind: \"tool\",\n\t\t\t\tseq: this.nextSeq(),\n\t\t\t\trev: 1,\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\tname: event.toolName,\n\t\t\t\tsummary: summarizeToolArgs(event.toolName, event.args as JsonValue | undefined),\n\t\t\t\tstatus: \"pending\",\n\t\t\t};\n\t\t\tthis.pushItem(item);\n\t\t\tthis.toolItemsById.set(event.toolCallId, item);\n\t\t}\n\t\tthis.lastToolItem = item;\n\t\tconst startedAt = this.now();\n\t\tthis.mutateItem(item, (i) => {\n\t\t\ti.status = \"running\";\n\t\t\ti.startedAt = startedAt;\n\t\t});\n\t\tthis.state.toolCalls++;\n\t\tconst counts = this.state.toolCounts;\n\t\tconst prevCount = Object.hasOwn(counts, event.toolName) ? counts[event.toolName] : 0;\n\t\tcounts[event.toolName] = (prevCount ?? 0) + 1;\n\t\tthis.state.currentTool = { toolCallId: event.toolCallId, name: event.toolName, summary: item.summary, startedAt };\n\t\tthis.state.activity = \"tool\";\n\t\tthis.blockedPending = undefined;\n\t\tif (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {\n\t\t\tthis.pendingStructuredById.set(event.toolCallId, event.args as JsonValue);\n\t\t}\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate handleToolExecutionEnd(\n\t\tevent: Extract<JsonAgentSessionEvent, { type: \"tool_execution_end\" }>,\n\t): ChildStateChange {\n\t\tlet item = this.toolItemsById.get(event.toolCallId);\n\t\tif (!item) {\n\t\t\titem = {\n\t\t\t\tkind: \"tool\",\n\t\t\t\tseq: this.nextSeq(),\n\t\t\t\trev: 1,\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\tname: event.toolName,\n\t\t\t\tsummary: \"\",\n\t\t\t\tstatus: \"pending\",\n\t\t\t};\n\t\t\tthis.pushItem(item);\n\t\t\tthis.toolItemsById.set(event.toolCallId, item);\n\t\t}\n\t\tconst text = extractResultText(event.result);\n\t\tconst preview = text.slice(0, 200);\n\t\tconst blocked = event.isError && text.endsWith(NO_UI_APPROVAL_SUFFIX);\n\t\tthis.mutateItem(item, (i) => {\n\t\t\ti.status = blocked ? \"blocked\" : event.isError ? \"error\" : \"ok\";\n\t\t\ti.endedAt = this.now();\n\t\t\ti.resultPreview = preview;\n\t\t\tif (blocked) i.blockedReason = text;\n\t\t});\n\t\tif (event.isError) this.state.toolErrors++;\n\t\tif (blocked) {\n\t\t\tthis.state.blockedCount++;\n\t\t\tconst entry: BlockedToolCall = { toolName: event.toolName, summary: item.summary, reason: text };\n\t\t\tthis.state.blocked = [...this.state.blocked, entry].slice(-20);\n\t\t\tthis.pushNotice(\"warning\", `${event.toolName} blocked: needs approval, nobody could be asked`);\n\t\t\tthis.blockedPending = event.toolName;\n\t\t}\n\t\tif (event.toolName === POLYPHASE_RESULT_TOOL_NAME) {\n\t\t\tconst pending = this.pendingStructuredById.get(event.toolCallId);\n\t\t\tthis.pendingStructuredById.delete(event.toolCallId);\n\t\t\tif (!event.isError && pending !== undefined) {\n\t\t\t\tthis.state.structured = { value: pending };\n\t\t\t}\n\t\t}\n\t\tthis.state.currentTool = undefined;\n\t\treturn this.bump(\"coarse\");\n\t}\n\n\tprivate nextSeq(): number {\n\t\treturn this.state.nextSeq++;\n\t}\n\n\tprivate pushNotice(level: \"info\" | \"warning\" | \"error\", text: string): void {\n\t\tconst capped = truncate(collapseWhitespace(text), NOTICE_MAX_CHARS);\n\t\tthis.pushItem({ kind: \"notice\", seq: this.nextSeq(), rev: 1, level, text: capped, at: this.now() });\n\t}\n\n\tprivate pushItem(item: TranscriptItem): void {\n\t\tthis.state.transcript.push(item);\n\t\tthis.adjustChars(this.measure(item));\n\t\tthis.evictIfNeeded();\n\t}\n\n\tprivate mutateItem<T extends TranscriptItem>(item: T, mutate: (item: T) => void): void {\n\t\tconst before = this.measure(item);\n\t\tmutate(item);\n\t\titem.rev++;\n\t\tconst after = this.measure(item);\n\t\tthis.adjustChars(after - before);\n\t\tthis.evictIfNeeded();\n\t}\n\n\t/** `addition` is typed `unknown`, not `string`, on purpose: a well-typed-looking wire record can\n\t * still carry a non-string `delta` at runtime (`parseChildLine` only checks `type`), and this\n\t * must throw before touching `item.text` rather than let a non-string silently become part of\n\t * the transcript or poison `transcriptChars` with a NaN-producing `.length` on a non-string. */\n\tprivate appendCapped(item: ThinkingItem | TextItem, addition: unknown): void {\n\t\tif (typeof addition !== \"string\") throw new TypeError(\"expected a string delta\");\n\t\tconst combined = item.text + addition;\n\t\tif (combined.length > this.limits.maxItemChars) {\n\t\t\tconst removed = combined.length - this.limits.maxItemChars;\n\t\t\titem.droppedChars += removed;\n\t\t\titem.text = combined.slice(removed);\n\t\t} else {\n\t\t\titem.text = combined;\n\t\t}\n\t}\n\n\t/** The full item content replaces the accumulated (already tail-capped) text; droppedChars reflects\n\t * this final content, not the sum of every delta's cap, so it is assigned rather than accumulated.\n\t * `content` is `unknown`, not `string`, for the same reason as {@link appendCapped}'s `addition`. */\n\tprivate replaceCapped(item: ThinkingItem | TextItem, content: unknown): void {\n\t\tif (typeof content !== \"string\") throw new TypeError(\"expected a string content\");\n\t\tif (content.length > this.limits.maxItemChars) {\n\t\t\tconst removed = content.length - this.limits.maxItemChars;\n\t\t\titem.droppedChars = removed;\n\t\t\titem.text = content.slice(removed);\n\t\t} else {\n\t\t\titem.droppedChars = 0;\n\t\t\titem.text = content;\n\t\t}\n\t}\n\n\tprivate measure(item: TranscriptItem): number {\n\t\tswitch (item.kind) {\n\t\t\tcase \"thinking\":\n\t\t\tcase \"text\":\n\t\t\t\treturn item.text.length;\n\t\t\tcase \"tool\":\n\t\t\t\treturn item.summary.length + (item.resultPreview?.length ?? 0);\n\t\t\tcase \"notice\":\n\t\t\t\treturn item.text.length;\n\t\t}\n\t}\n\n\t/** Shrinks `item` in place, keeping its tail (most recent content), until `measure(item) <=\n\t * maxChars`. Used only to keep the newest transcript item instead of evicting it outright. */\n\tprivate tailTrimToFit(item: TranscriptItem, maxChars: number): void {\n\t\tconst over = this.measure(item) - Math.max(0, maxChars);\n\t\tif (over <= 0) return;\n\t\tswitch (item.kind) {\n\t\t\tcase \"thinking\":\n\t\t\tcase \"text\":\n\t\t\t\titem.droppedChars += over;\n\t\t\t\titem.text = item.text.slice(over);\n\t\t\t\tbreak;\n\t\t\tcase \"notice\":\n\t\t\t\titem.text = item.text.slice(over);\n\t\t\t\tbreak;\n\t\t\tcase \"tool\": {\n\t\t\t\tlet remaining = over;\n\t\t\t\tif (item.resultPreview) {\n\t\t\t\t\tconst trimmed = Math.min(remaining, item.resultPreview.length);\n\t\t\t\t\titem.resultPreview = item.resultPreview.slice(trimmed);\n\t\t\t\t\tremaining -= trimmed;\n\t\t\t\t}\n\t\t\t\tif (remaining > 0) item.summary = item.summary.slice(remaining);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\titem.rev++;\n\t}\n\n\tprivate adjustChars(delta: number): void {\n\t\tconst next = this.state.transcriptChars + delta;\n\t\t// A NaN delta (impossible for a string's `.length`, but transcriptChars is otherwise an\n\t\t// unguarded running total) must not permanently poison the count: Number.isFinite rejects it\n\t\t// and leaves the previous value in place instead of letting Math.max(0, NaN) propagate NaN.\n\t\tif (Number.isFinite(next)) this.state.transcriptChars = Math.max(0, next);\n\t}\n\n\tprivate evictIfNeeded(): void {\n\t\tconst removed: TranscriptItem[] = [];\n\t\twhile (this.state.transcript.length > this.limits.maxItems || this.state.transcriptChars > this.limits.maxChars) {\n\t\t\tconst idx = this.state.transcript.findIndex((item) => !this.isOpenItem(item));\n\t\t\tif (idx === -1) break;\n\t\t\tif (idx === this.state.transcript.length - 1) {\n\t\t\t\t// This is the only evictable item left (every open item is already exempt, and\n\t\t\t\t// everything else has already been dropped): tail-trim it instead of dropping it, so\n\t\t\t\t// one huge item (one notice with a child-supplied error message, say) cannot empty the\n\t\t\t\t// whole live transcript. Nothing else is left to evict either way, so stop here.\n\t\t\t\tconst item = this.state.transcript[idx] as TranscriptItem;\n\t\t\t\tconst before = this.measure(item);\n\t\t\t\tthis.tailTrimToFit(item, this.limits.maxChars);\n\t\t\t\tthis.adjustChars(this.measure(item) - before);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst item = this.state.transcript.splice(idx, 1)[0];\n\t\t\tif (!item) break;\n\t\t\tthis.adjustChars(-this.measure(item));\n\t\t\tthis.state.droppedItems++;\n\t\t\tif (item.kind === \"tool\") this.toolItemsById.delete(item.toolCallId);\n\t\t\tremoved.push(item);\n\t\t}\n\t\tif (removed.length > 0) this.clearRefsTo(removed);\n\t}\n\n\tprivate isOpenItem(item: TranscriptItem): boolean {\n\t\treturn item === this.openThinking || item === this.openText;\n\t}\n\n\tprivate bump(change: ChildStateChange): ChildStateChange {\n\t\tif (change === \"none\") return change;\n\t\tthis.state.version++;\n\t\tif (change === \"coarse\") this.state.coarseVersion++;\n\t\tthis.state.lastEventAt = this.now();\n\t\tthis.state.nowLine = this.computeNowLine();\n\t\treturn change;\n\t}\n\n\tprivate computeNowLine(): string {\n\t\tif (this.blockedPending) {\n\t\t\treturn clampHead(\"⚠\", `${this.blockedPending} blocked: needs approval`);\n\t\t}\n\t\tswitch (this.state.activity) {\n\t\t\tcase \"thinking\":\n\t\t\t\treturn clampTail(\"thinking · \", (this.openThinking ?? this.lastThinking)?.text ?? \"\");\n\t\t\tcase \"writing\":\n\t\t\t\treturn clampTail(\"writing · \", (this.openText ?? this.lastText)?.text ?? \"\");\n\t\t\tcase \"tool\": {\n\t\t\t\tconst item = this.lastToolItem;\n\t\t\t\treturn item ? clampHead(item.name, item.summary) : \"\";\n\t\t\t}\n\t\t\tcase \"waiting\":\n\t\t\t\treturn \"waiting for model\";\n\t\t\tcase \"retrying\": {\n\t\t\t\tconst retry = this.state.retry;\n\t\t\t\treturn retry\n\t\t\t\t\t? clampHead(`retrying ${retry.attempt}/${retry.maxAttempts} ·`, retry.errorMessage)\n\t\t\t\t\t: \"retrying\";\n\t\t\t}\n\t\t\tcase \"compacting\":\n\t\t\t\treturn \"compacting context\";\n\t\t\tcase \"idle\":\n\t\t\t\treturn this.state.lifecycle === \"settled\" ? \"finished\" : \"\";\n\t\t\tdefault:\n\t\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nfunction resolveModelRef(state: Readonly<ChildAgentState>): ModelRef | undefined {\n\tif (!state.model.confirmed || !state.model.provider || !state.model.id) return undefined;\n\treturn { provider: state.model.provider, id: state.model.id };\n}\n\nexport function toRunResult(\n\tstate: Readonly<ChildAgentState>,\n\tbase: { agent: string; task: string; step?: number },\n\tfinish: ChildFinish,\n\textras: { cancelled: boolean; structured?: { value: JsonValue }; durationMs: number },\n): RunResult {\n\tconst failedResponse = state.stopReason === \"error\" || state.stopReason === \"aborted\";\n\tconst stderr =\n\t\tstate.stderrTail.length > 0\n\t\t\t? state.stderrTail\n\t\t\t: failedResponse\n\t\t\t\t? (state.errorMessage ?? state.stopReason ?? \"\")\n\t\t\t\t: (finish.failure ?? \"\");\n\n\treturn {\n\t\tagent: base.agent,\n\t\ttask: base.task,\n\t\tstep: base.step,\n\t\texitCode: finish.exitCode,\n\t\toutput: state.finalText,\n\t\tstderr,\n\t\tusage: state.usage,\n\t\tmodel: resolveModelRef(state),\n\t\tthinkingLevel: state.model.thinkingLevel,\n\t\tstopReason: state.stopReason,\n\t\tturns: state.turns,\n\t\ttoolCalls: state.toolCalls,\n\t\tblockedToolCalls: state.blockedCount,\n\t\tstructured: extras.structured,\n\t\tcancelled: extras.cancelled,\n\t\tdurationMs: extras.durationMs,\n\t};\n}\n"]}