@draht/coding-agent 2026.10.4 → 2026.10.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +32 -6
  3. package/dist/bundle/chunks/anthropic.js +1 -1
  4. package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-2VAF4XJI.js} +1 -1
  5. package/dist/bundle/chunks/chunk-6APPDDHH.js +65 -0
  6. package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-JFDPOIUH.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-KU5HAKZL.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-MIUVNYYW.js} +292 -153
  9. package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-NHTOADU6.js} +2 -2
  10. package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-OWGSPJPZ.js} +4 -4
  11. package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
  12. package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
  13. package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-TJ3AW62W.js} +1 -1
  14. package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-U7Y4VNNI.js} +1 -1
  15. package/dist/bundle/chunks/execute-ZWB4PIQQ.js +18 -0
  16. package/dist/bundle/chunks/google-antigravity.js +1 -1
  17. package/dist/bundle/chunks/google-gemini-cli.js +1 -1
  18. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  19. package/dist/bundle/chunks/openai-codex.js +1 -1
  20. package/dist/bundle/chunks/openrouter.js +1 -1
  21. package/dist/bundle/chunks/radius.js +1 -1
  22. package/dist/bundle/chunks/runtime-363BOYEO.js +3 -0
  23. package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-PXJK4L7Y.js} +1 -1
  24. package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-GEOZJXFQ.js} +1 -1
  25. package/dist/bundle/chunks/virtual-modules-BEJ4ZJ3D.js +2 -0
  26. package/dist/bundle/chunks/xai.js +1 -1
  27. package/dist/bundle/cli-runtime.js +1 -1
  28. package/dist/bundle/index.js +1 -1
  29. package/dist/bundle/rpc-entry.js +1 -1
  30. package/dist/cli/args.js +3 -3
  31. package/dist/cli/args.js.map +1 -1
  32. package/dist/core/builtins/duet.d.ts +5 -2
  33. package/dist/core/builtins/duet.d.ts.map +1 -1
  34. package/dist/core/builtins/duet.js +65 -27
  35. package/dist/core/builtins/duet.js.map +1 -1
  36. package/dist/core/builtins/index.d.ts.map +1 -1
  37. package/dist/core/builtins/index.js +2 -0
  38. package/dist/core/builtins/index.js.map +1 -1
  39. package/dist/core/builtins/polyphase.d.ts +15 -0
  40. package/dist/core/builtins/polyphase.d.ts.map +1 -0
  41. package/dist/core/builtins/polyphase.js +196 -0
  42. package/dist/core/builtins/polyphase.js.map +1 -0
  43. package/dist/core/builtins/subagent.d.ts +44 -34
  44. package/dist/core/builtins/subagent.d.ts.map +1 -1
  45. package/dist/core/builtins/subagent.js +827 -560
  46. package/dist/core/builtins/subagent.js.map +1 -1
  47. package/dist/core/extensions/types.d.ts +17 -2
  48. package/dist/core/extensions/types.d.ts.map +1 -1
  49. package/dist/core/extensions/types.js.map +1 -1
  50. package/dist/core/keybindings.d.ts +30 -0
  51. package/dist/core/keybindings.d.ts.map +1 -1
  52. package/dist/core/keybindings.js +24 -0
  53. package/dist/core/keybindings.js.map +1 -1
  54. package/dist/core/model-resolver.js +4 -4
  55. package/dist/core/model-resolver.js.map +1 -1
  56. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  57. package/dist/core/multi-agent/permission-gate.js +4 -1
  58. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  59. package/dist/core/polyphase/approval.d.ts +35 -0
  60. package/dist/core/polyphase/approval.d.ts.map +1 -0
  61. package/dist/core/polyphase/approval.js +184 -0
  62. package/dist/core/polyphase/approval.js.map +1 -0
  63. package/dist/core/polyphase/child-events.d.ts +107 -0
  64. package/dist/core/polyphase/child-events.d.ts.map +1 -0
  65. package/dist/core/polyphase/child-events.js +862 -0
  66. package/dist/core/polyphase/child-events.js.map +1 -0
  67. package/dist/core/polyphase/child-process.d.ts +65 -0
  68. package/dist/core/polyphase/child-process.d.ts.map +1 -0
  69. package/dist/core/polyphase/child-process.js +361 -0
  70. package/dist/core/polyphase/child-process.js.map +1 -0
  71. package/dist/core/polyphase/commands.d.ts +44 -0
  72. package/dist/core/polyphase/commands.d.ts.map +1 -0
  73. package/dist/core/polyphase/commands.js +244 -0
  74. package/dist/core/polyphase/commands.js.map +1 -0
  75. package/dist/core/polyphase/details.d.ts +40 -0
  76. package/dist/core/polyphase/details.d.ts.map +1 -0
  77. package/dist/core/polyphase/details.js +538 -0
  78. package/dist/core/polyphase/details.js.map +1 -0
  79. package/dist/core/polyphase/emitter.d.ts +20 -0
  80. package/dist/core/polyphase/emitter.d.ts.map +1 -0
  81. package/dist/core/polyphase/emitter.js +90 -0
  82. package/dist/core/polyphase/emitter.js.map +1 -0
  83. package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
  84. package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
  85. package/dist/core/polyphase/jsonl-reader.js +161 -0
  86. package/dist/core/polyphase/jsonl-reader.js.map +1 -0
  87. package/dist/core/polyphase/keyword.d.ts +27 -0
  88. package/dist/core/polyphase/keyword.d.ts.map +1 -0
  89. package/dist/core/polyphase/keyword.js +97 -0
  90. package/dist/core/polyphase/keyword.js.map +1 -0
  91. package/dist/core/polyphase/limiter.d.ts +38 -0
  92. package/dist/core/polyphase/limiter.d.ts.map +1 -0
  93. package/dist/core/polyphase/limiter.js +129 -0
  94. package/dist/core/polyphase/limiter.js.map +1 -0
  95. package/dist/core/polyphase/model-selection.d.ts +35 -0
  96. package/dist/core/polyphase/model-selection.d.ts.map +1 -0
  97. package/dist/core/polyphase/model-selection.js +72 -0
  98. package/dist/core/polyphase/model-selection.js.map +1 -0
  99. package/dist/core/polyphase/render/format.d.ts +52 -0
  100. package/dist/core/polyphase/render/format.d.ts.map +1 -0
  101. package/dist/core/polyphase/render/format.js +169 -0
  102. package/dist/core/polyphase/render/format.js.map +1 -0
  103. package/dist/core/polyphase/render/renderers.d.ts +63 -0
  104. package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
  105. package/dist/core/polyphase/render/renderers.js +277 -0
  106. package/dist/core/polyphase/render/renderers.js.map +1 -0
  107. package/dist/core/polyphase/render/run-block.d.ts +45 -0
  108. package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
  109. package/dist/core/polyphase/render/run-block.js +843 -0
  110. package/dist/core/polyphase/render/run-block.js.map +1 -0
  111. package/dist/core/polyphase/render/snapshot.d.ts +106 -0
  112. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
  113. package/dist/core/polyphase/render/snapshot.js +292 -0
  114. package/dist/core/polyphase/render/snapshot.js.map +1 -0
  115. package/dist/core/polyphase/result-text.d.ts +41 -0
  116. package/dist/core/polyphase/result-text.d.ts.map +1 -0
  117. package/dist/core/polyphase/result-text.js +326 -0
  118. package/dist/core/polyphase/result-text.js.map +1 -0
  119. package/dist/core/polyphase/session.d.ts +33 -0
  120. package/dist/core/polyphase/session.d.ts.map +1 -0
  121. package/dist/core/polyphase/session.js +106 -0
  122. package/dist/core/polyphase/session.js.map +1 -0
  123. package/dist/core/polyphase/settings.d.ts +18 -0
  124. package/dist/core/polyphase/settings.d.ts.map +1 -0
  125. package/dist/core/polyphase/settings.js +93 -0
  126. package/dist/core/polyphase/settings.js.map +1 -0
  127. package/dist/core/polyphase/store.d.ts +197 -0
  128. package/dist/core/polyphase/store.d.ts.map +1 -0
  129. package/dist/core/polyphase/store.js +558 -0
  130. package/dist/core/polyphase/store.js.map +1 -0
  131. package/dist/core/polyphase/types.d.ts +371 -0
  132. package/dist/core/polyphase/types.d.ts.map +1 -0
  133. package/dist/core/polyphase/types.js +36 -0
  134. package/dist/core/polyphase/types.js.map +1 -0
  135. package/dist/core/polyphase/ui/controller.d.ts +28 -0
  136. package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
  137. package/dist/core/polyphase/ui/controller.js +150 -0
  138. package/dist/core/polyphase/ui/controller.js.map +1 -0
  139. package/dist/core/polyphase/ui/dock.d.ts +27 -0
  140. package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
  141. package/dist/core/polyphase/ui/dock.js +121 -0
  142. package/dist/core/polyphase/ui/dock.js.map +1 -0
  143. package/dist/core/polyphase/ui/inspector.d.ts +117 -0
  144. package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
  145. package/dist/core/polyphase/ui/inspector.js +1016 -0
  146. package/dist/core/polyphase/ui/inspector.js.map +1 -0
  147. package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
  148. package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
  149. package/dist/core/polyphase/ui/transcript-layout.js +210 -0
  150. package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
  151. package/dist/core/polyphase/update-pump.d.ts +18 -0
  152. package/dist/core/polyphase/update-pump.d.ts.map +1 -0
  153. package/dist/core/polyphase/update-pump.js +132 -0
  154. package/dist/core/polyphase/update-pump.js.map +1 -0
  155. package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
  156. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
  157. package/dist/core/polyphase/workflow/agent-host.js +187 -0
  158. package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
  159. package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
  160. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
  161. package/dist/core/polyphase/workflow/guidance.js +119 -0
  162. package/dist/core/polyphase/workflow/guidance.js.map +1 -0
  163. package/dist/core/polyphase/workflow/launch.d.ts +41 -0
  164. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
  165. package/dist/core/polyphase/workflow/launch.js +173 -0
  166. package/dist/core/polyphase/workflow/launch.js.map +1 -0
  167. package/dist/core/polyphase/workflow/meta.d.ts +43 -0
  168. package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
  169. package/dist/core/polyphase/workflow/meta.js +529 -0
  170. package/dist/core/polyphase/workflow/meta.js.map +1 -0
  171. package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
  172. package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
  173. package/dist/core/polyphase/workflow/prelude.js +93 -0
  174. package/dist/core/polyphase/workflow/prelude.js.map +1 -0
  175. package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
  176. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
  177. package/dist/core/polyphase/workflow/runtime.js +217 -0
  178. package/dist/core/polyphase/workflow/runtime.js.map +1 -0
  179. package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
  180. package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
  181. package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
  182. package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
  183. package/dist/core/polyphase/workflow/saved.d.ts +55 -0
  184. package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
  185. package/dist/core/polyphase/workflow/saved.js +299 -0
  186. package/dist/core/polyphase/workflow/saved.js.map +1 -0
  187. package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
  188. package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
  189. package/dist/core/polyphase/workflow/structured-output.js +66 -0
  190. package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
  191. package/dist/core/polyphase/workflow/tool.d.ts +24 -0
  192. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
  193. package/dist/core/polyphase/workflow/tool.js +139 -0
  194. package/dist/core/polyphase/workflow/tool.js.map +1 -0
  195. package/dist/core/sdk.d.ts +1 -1
  196. package/dist/core/sdk.js +1 -1
  197. package/dist/core/sdk.js.map +1 -1
  198. package/dist/core/settings-manager.d.ts +27 -0
  199. package/dist/core/settings-manager.d.ts.map +1 -1
  200. package/dist/core/settings-manager.js.map +1 -1
  201. package/dist/core/socket-server/permission-relay.js +4 -0
  202. package/dist/core/socket-server/permission-relay.js.map +1 -1
  203. package/dist/core/trust-manager.d.ts +3 -2
  204. package/dist/core/trust-manager.d.ts.map +1 -1
  205. package/dist/core/trust-manager.js +5 -2
  206. package/dist/core/trust-manager.js.map +1 -1
  207. package/dist/experimental/micro/runtime.js +1 -1
  208. package/dist/experimental/micro/runtime.js.map +1 -1
  209. package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
  210. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  211. package/dist/modes/interactive/components/keybinding-hints.js +18 -0
  212. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  213. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  214. package/dist/modes/interactive/interactive-mode.js +11 -2
  215. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  216. package/dist/modes/rpc/rpc-types.d.ts +9 -0
  217. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  218. package/dist/modes/rpc/rpc-types.js.map +1 -1
  219. package/dist/prompts/commands/orchestrate.md +1 -1
  220. package/dist/utils/shell.d.ts.map +1 -1
  221. package/dist/utils/shell.js +7 -1
  222. package/dist/utils/shell.js.map +1 -1
  223. package/docs/docs.json +4 -0
  224. package/docs/duet.md +3 -3
  225. package/docs/environment-variables.md +11 -0
  226. package/docs/json.md +7 -0
  227. package/docs/keybindings.md +20 -0
  228. package/docs/polyphase.md +391 -0
  229. package/docs/rpc-commands.md +9 -9
  230. package/docs/settings.md +12 -0
  231. package/docs/virtual-models.md +3 -3
  232. package/examples/extensions/preset.ts +3 -3
  233. package/examples/extensions/subagent/README.md +1 -1
  234. package/examples/extensions/subagent/agents/planner.md +1 -1
  235. package/examples/extensions/subagent/agents/reviewer.md +1 -1
  236. package/examples/extensions/subagent/agents/scout.md +1 -1
  237. package/examples/extensions/subagent/agents/worker.md +1 -1
  238. package/examples/extensions/summarize.ts +3 -3
  239. package/examples/sdk/02-custom-model.ts +1 -1
  240. package/examples/sdk/12-full-control.ts +1 -1
  241. package/examples/sdk/README.md +1 -1
  242. package/package.json +10 -10
  243. package/prompts/commands/orchestrate.md +1 -1
  244. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
  245. package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
  246. package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
@@ -0,0 +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,CAAU,CAAC;AAC9F,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAC3C;;6E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AAK,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"]}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Spawns and supervises one child draht process for a subagent/workflow run (§7.1-7.4).
3
+ *
4
+ * `buildChildInvocation` and `resolveDrahtCommand` are pure; `runChildAgent` owns every
5
+ * side effect (temp files, spawn, line reading, abort escalation) and never rejects.
6
+ */
7
+ import type { JsonObject } from "@draht/ai";
8
+ import { ChildEventReducer } from "./child-events.ts";
9
+ import { type AgentConfig, type AgentRunContext, type AgentRunner, type ProgressFn, type RunResult } from "./types.ts";
10
+ export interface ChildCommand {
11
+ bin: string;
12
+ argsPrefix: readonly string[];
13
+ }
14
+ /**
15
+ * Bun binary: `{execPath, []}`. Otherwise `{execPath, [...execArgv without --inspect*
16
+ * and --debug*, argv[1]]}`, which keeps tsx (and other loader-based dev runs) working in children.
17
+ */
18
+ export declare function resolveDrahtCommand(): ChildCommand;
19
+ export interface ChildSpawnSpec {
20
+ cwd: string;
21
+ agent: AgentConfig;
22
+ task: string;
23
+ step?: number;
24
+ run?: AgentRunContext;
25
+ signal?: AbortSignal;
26
+ onProgress?: ProgressFn;
27
+ command?: ChildCommand;
28
+ /** Grace period between SIGTERM and SIGKILL-via-tree on abort. Default 5000. */
29
+ killGraceMs?: number;
30
+ baseEnv?: NodeJS.ProcessEnv;
31
+ }
32
+ /** Pure: computes argv and env for one spawn. `files` are temp paths already written by the caller. */
33
+ export declare function buildChildInvocation(spec: ChildSpawnSpec, files: {
34
+ systemPromptFile?: string;
35
+ schemaFile?: string;
36
+ }, options?: {
37
+ omitModel?: boolean;
38
+ }): {
39
+ args: string[];
40
+ env: NodeJS.ProcessEnv;
41
+ };
42
+ /**
43
+ * §7.4: extracts the per-field errors from `validateToolArguments`'s formatted message (one
44
+ * ` - path: message` line per failing field, then a blank line and "Received arguments:"),
45
+ * joins them onto one line, and caps the result. Any other error (e.g. "structured output must
46
+ * be a JSON object") has no such lines and is passed through as its own (single-line) message.
47
+ */
48
+ export declare function formatStructuredOutputError(rawMessage: string): string;
49
+ /**
50
+ * ChildEventReducer exposes no public "add a notice" API (pushNotice and bump are private, with
51
+ * no exported hook for callers outside the class). This pushes the item directly, then reuses
52
+ * the public `trimForRetention` pass with an unreachable budget, which recomputes
53
+ * `transcriptChars` from scratch and bumps `version`/`coarseVersion` without evicting anything,
54
+ * so version-keyed consumers (render caches, store) observe the change. Passing the run's
55
+ * post-finish budget here would trim the whole live transcript down to that size as a side
56
+ * effect, which is the store's job at `finish()` (§8.3 retention), not this mid-run notice's.
57
+ * Always "coarse", since `trimForRetention` always bumps coarse.
58
+ */
59
+ export declare function recordReducerNotice(reducer: ChildEventReducer, level: "info" | "warning" | "error", text: string): "coarse";
60
+ /** §7.4: validate `state.structured` against `run.schema`, mutating the reducer's public state in place. */
61
+ export declare function validateStructuredOutput(reducer: ChildEventReducer, schema: JsonObject, onChange?: (change: "fine" | "coarse") => void): void;
62
+ /** Never rejects: spawn and runtime failures resolve as a failed `RunResult`. */
63
+ export declare function runChildAgent(spec: ChildSpawnSpec): Promise<RunResult>;
64
+ export declare function createProcessAgentRunner(command?: ChildCommand): AgentRunner;
65
+ //# sourceMappingURL=child-process.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"child-process.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/child-process.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,KAAK,EAAE,U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,iBAAiB,EAC1B,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,EACnC,IAAI,EAAE,MAAM,GACV,QAAQ,CAKV;AA0BD,4GAA4G;AAC5G,wBAAgB,wBAAwB,CACvC,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,UAAU,EAClB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,KAAK,IAAI,GAC5C,IAAI,CAkBN;AAsED,iFAAiF;AACjF,wBAAsB,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,CAiC5E;AAED,wBAAgB,wBAAwB,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,WAAW,CAG5E"}
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Spawns and supervises one child draht process for a subagent/workflow run (§7.1-7.4).
3
+ *
4
+ * `buildChildInvocation` and `resolveDrahtCommand` are pure; `runChildAgent` owns every
5
+ * side effect (temp files, spawn, line reading, abort escalation) and never rejects.
6
+ */
7
+ import { spawn } from "node:child_process";
8
+ import * as fs from "node:fs";
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import { validateToolArguments } from "@draht/ai";
12
+ import { isBunBinary } from "../../config.js";
13
+ import { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from "../../utils/shell.js";
14
+ import { ChildEventReducer, parseChildLine, summarizeToolArgs, toRunResult, } from "./child-events.js";
15
+ import { attachChildLineReader } from "./jsonl-reader.js";
16
+ import { currentPolyphaseDepth, DUET_DELEGATE_TOOL_NAME, POLYPHASE_DEPTH_ENV, POLYPHASE_RESULT_TOOL_NAME, POLYPHASE_SCHEMA_FILE_ENV, WORKFLOW_TOOL_NAME, } from "./types.js";
17
+ const DEFAULT_KILL_GRACE_MS = 5000;
18
+ const LEGACY_TOOL_SUMMARY_MAX_CHARS = 60;
19
+ const LEGACY_TEXT_PROGRESS_MAX_CHARS = 80;
20
+ const INSPECT_OR_DEBUG_FLAG = /^--(?:inspect|debug)/;
21
+ const STRUCTURED_OUTPUT_NOTICE_MAX_CHARS = 200;
22
+ /**
23
+ * Bun binary: `{execPath, []}`. Otherwise `{execPath, [...execArgv without --inspect*
24
+ * and --debug*, argv[1]]}`, which keeps tsx (and other loader-based dev runs) working in children.
25
+ */
26
+ export function resolveDrahtCommand() {
27
+ if (isBunBinary)
28
+ return { bin: process.execPath, argsPrefix: [] };
29
+ const execArgv = process.execArgv.filter((arg) => !INSPECT_OR_DEBUG_FLAG.test(arg));
30
+ return { bin: process.execPath, argsPrefix: [...execArgv, process.argv[1]] };
31
+ }
32
+ /** Pure: computes argv and env for one spawn. `files` are temp paths already written by the caller. */
33
+ export function buildChildInvocation(spec, files, options) {
34
+ const { agent, run } = spec;
35
+ const omitModel = options?.omitModel ?? false;
36
+ const args = ["--mode", "json", "-p", "--no-session"];
37
+ const model = run?.model ?? agent.model;
38
+ if (!omitModel && model)
39
+ args.push("--model", model);
40
+ if (!omitModel && run?.thinking)
41
+ args.push("--thinking", run.thinking);
42
+ if (agent.tools?.length) {
43
+ const tools = [...agent.tools, ...(run?.extraTools ?? [])];
44
+ args.push("--tools", tools.join(","));
45
+ }
46
+ if (agent.disableExtensions)
47
+ args.push("--no-extensions");
48
+ const excludeTools = [WORKFLOW_TOOL_NAME, DUET_DELEGATE_TOOL_NAME, ...(run?.excludeTools ?? [])];
49
+ args.push("--exclude-tools", [...new Set(excludeTools)].join(","));
50
+ if (files.systemPromptFile)
51
+ args.push("--append-system-prompt", files.systemPromptFile);
52
+ const baseEnv = spec.baseEnv ?? process.env;
53
+ const env = { ...baseEnv, ...(run?.env ?? {}) };
54
+ env[POLYPHASE_DEPTH_ENV] = String(currentPolyphaseDepth(baseEnv) + 1);
55
+ if (files.schemaFile) {
56
+ env[POLYPHASE_SCHEMA_FILE_ENV] = files.schemaFile;
57
+ }
58
+ else {
59
+ delete env[POLYPHASE_SCHEMA_FILE_ENV];
60
+ }
61
+ return { args, env };
62
+ }
63
+ function truncateProgress(text, max) {
64
+ return text.length > max ? `${text.slice(0, max)}...` : text;
65
+ }
66
+ /**
67
+ * Legacy `onProgress` strings duet relies on: a short line on every tool start, and one line for
68
+ * the first delta of each new text item (a cheap "what is it writing" signal, not a transcript).
69
+ */
70
+ function legacyProgressText(record, pendingFirstDelta) {
71
+ if (record.type === "tool_execution_start") {
72
+ const summary = truncateProgress(summarizeToolArgs(record.toolName, record.args), LEGACY_TOOL_SUMMARY_MAX_CHARS);
73
+ return summary ? `${record.toolName} ${summary}` : record.toolName;
74
+ }
75
+ if (record.type === "message_update") {
76
+ const event = record.assistantMessageEvent;
77
+ if (event.type === "text_start") {
78
+ pendingFirstDelta.add(event.contentIndex);
79
+ return undefined;
80
+ }
81
+ if (event.type === "text_delta" && pendingFirstDelta.delete(event.contentIndex)) {
82
+ const firstLine = event.delta.split("\n")[0] ?? "";
83
+ return truncateProgress(firstLine, LEGACY_TEXT_PROGRESS_MAX_CHARS);
84
+ }
85
+ }
86
+ return undefined;
87
+ }
88
+ /** One spawn: wires the line reader, stderr tail, abort escalation, and resolves via `reducer.finish`. */
89
+ function spawnAttempt(spec, command, reducer, files, options) {
90
+ const killGraceMs = spec.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
91
+ const { args, env } = buildChildInvocation(spec, files, options);
92
+ return new Promise((resolve) => {
93
+ let settled = false;
94
+ let closed = false;
95
+ let killTimer;
96
+ let proc;
97
+ const finishOnce = (exit) => {
98
+ if (settled)
99
+ return;
100
+ settled = true;
101
+ if (killTimer)
102
+ clearTimeout(killTimer);
103
+ if (spec.signal)
104
+ spec.signal.removeEventListener("abort", onAbort);
105
+ resolve({ exit, finish: reducer.finish(exit) });
106
+ };
107
+ function onAbort() {
108
+ if (settled)
109
+ return;
110
+ try {
111
+ proc.kill("SIGTERM");
112
+ }
113
+ catch { }
114
+ killTimer = setTimeout(() => {
115
+ if (!closed && proc.pid !== undefined)
116
+ killProcessTree(proc.pid);
117
+ }, killGraceMs);
118
+ killTimer.unref();
119
+ }
120
+ try {
121
+ proc = spawn(command.bin, [...command.argsPrefix, ...args], {
122
+ cwd: spec.cwd,
123
+ env,
124
+ shell: false,
125
+ stdio: ["pipe", "pipe", "pipe"],
126
+ });
127
+ }
128
+ catch (error) {
129
+ finishOnce({
130
+ code: null,
131
+ signal: null,
132
+ cancelled: spec.signal?.aborted === true,
133
+ spawnError: error instanceof Error ? error.message : String(error),
134
+ });
135
+ return;
136
+ }
137
+ const pid = proc.pid;
138
+ if (pid !== undefined)
139
+ trackDetachedChildPid(pid);
140
+ try {
141
+ spec.run?.onStart?.({ pid, argv: args });
142
+ }
143
+ catch {
144
+ // A throwing onStart must not cut this executor short: the stdin/stdout/stderr wiring and
145
+ // close/error handlers below still need to run, or this child would keep running with
146
+ // nothing left to supervise it (never settling, never killed on abort).
147
+ }
148
+ proc.stdin.on("error", () => { });
149
+ proc.stdin.end(`Task: ${spec.task}`);
150
+ const forward = (change) => {
151
+ if (change !== "none")
152
+ spec.run?.onChange?.(change);
153
+ };
154
+ const pendingFirstDelta = new Set();
155
+ attachChildLineReader(proc.stdout, (line) => {
156
+ const record = parseChildLine(line);
157
+ if (!record)
158
+ return;
159
+ forward(reducer.apply(record));
160
+ const progress = legacyProgressText(record, pendingFirstDelta);
161
+ if (progress)
162
+ spec.onProgress?.(progress);
163
+ }, {
164
+ onSkipped: (prefix) => {
165
+ if (prefix.includes("tool_execution_update"))
166
+ forward(reducer.noteHeartbeat());
167
+ },
168
+ });
169
+ proc.stderr.setEncoding("utf8");
170
+ proc.stderr.on("data", (chunk) => reducer.noteStderr(chunk));
171
+ if (spec.signal) {
172
+ if (spec.signal.aborted)
173
+ onAbort();
174
+ else
175
+ spec.signal.addEventListener("abort", onAbort, { once: true });
176
+ }
177
+ proc.on("error", (error) => {
178
+ closed = true;
179
+ finishOnce({
180
+ code: null,
181
+ signal: null,
182
+ cancelled: spec.signal?.aborted === true,
183
+ spawnError: error.message,
184
+ });
185
+ });
186
+ proc.on("close", (code, signal) => {
187
+ closed = true;
188
+ if (pid !== undefined)
189
+ untrackDetachedChildPid(pid);
190
+ finishOnce({ code, signal, cancelled: spec.signal?.aborted === true });
191
+ });
192
+ });
193
+ }
194
+ function isJsonObjectValue(value) {
195
+ return typeof value === "object" && value !== null && !Array.isArray(value);
196
+ }
197
+ /**
198
+ * §7.4: extracts the per-field errors from `validateToolArguments`'s formatted message (one
199
+ * ` - path: message` line per failing field, then a blank line and "Received arguments:"),
200
+ * joins them onto one line, and caps the result. Any other error (e.g. "structured output must
201
+ * be a JSON object") has no such lines and is passed through as its own (single-line) message.
202
+ */
203
+ export function formatStructuredOutputError(rawMessage) {
204
+ const [body] = rawMessage.split("\n\nReceived arguments:");
205
+ const lines = (body ?? rawMessage).split("\n");
206
+ const fieldErrors = lines
207
+ .slice(1)
208
+ .map((line) => line.replace(/^\s*-\s*/, "").trim())
209
+ .filter((line) => line.length > 0);
210
+ const detail = fieldErrors.length > 0 ? fieldErrors.join("; ") : (lines[0] ?? rawMessage);
211
+ return truncateProgress(detail.replace(/\s+/g, " ").trim(), STRUCTURED_OUTPUT_NOTICE_MAX_CHARS);
212
+ }
213
+ /**
214
+ * ChildEventReducer exposes no public "add a notice" API (pushNotice and bump are private, with
215
+ * no exported hook for callers outside the class). This pushes the item directly, then reuses
216
+ * the public `trimForRetention` pass with an unreachable budget, which recomputes
217
+ * `transcriptChars` from scratch and bumps `version`/`coarseVersion` without evicting anything,
218
+ * so version-keyed consumers (render caches, store) observe the change. Passing the run's
219
+ * post-finish budget here would trim the whole live transcript down to that size as a side
220
+ * effect, which is the store's job at `finish()` (§8.3 retention), not this mid-run notice's.
221
+ * Always "coarse", since `trimForRetention` always bumps coarse.
222
+ */
223
+ export function recordReducerNotice(reducer, level, text) {
224
+ const item = { kind: "notice", seq: reducer.state.nextSeq++, rev: 1, level, text, at: Date.now() };
225
+ reducer.state.transcript.push(item);
226
+ reducer.trimForRetention(Number.POSITIVE_INFINITY);
227
+ return "coarse";
228
+ }
229
+ const REDOS_SCHEMA_KEYWORDS = new Set(["pattern", "patternProperties"]);
230
+ /**
231
+ * Deep-clones `schema`, dropping every `pattern`/`patternProperties` keyword at any depth. A
232
+ * workflow script controls `schema` end to end (§guardAgentRequest only caps its JSON size), so a
233
+ * crafted `pattern` such as `"^(a+)+$"` paired with a near-matching structured-output value makes
234
+ * `validateToolArguments` backtrack exponentially. The child already validated the same value
235
+ * against the *full* schema (including any `pattern`) before this parent-side re-validation runs,
236
+ * so dropping regex keywords here only removes a redundant, attacker-triggerable check — it does
237
+ * not let a value through the child missed.
238
+ */
239
+ function stripRegexSchemaKeywords(value) {
240
+ if (Array.isArray(value))
241
+ return value.map(stripRegexSchemaKeywords);
242
+ if (typeof value === "object" && value !== null) {
243
+ const result = {};
244
+ for (const [key, child] of Object.entries(value)) {
245
+ if (REDOS_SCHEMA_KEYWORDS.has(key))
246
+ continue;
247
+ result[key] = stripRegexSchemaKeywords(child);
248
+ }
249
+ return result;
250
+ }
251
+ return value;
252
+ }
253
+ /** §7.4: validate `state.structured` against `run.schema`, mutating the reducer's public state in place. */
254
+ export function validateStructuredOutput(reducer, schema, onChange) {
255
+ const pending = reducer.state.structured;
256
+ if (!pending)
257
+ return;
258
+ try {
259
+ if (!isJsonObjectValue(pending.value))
260
+ throw new Error("structured output must be a JSON object");
261
+ const safeSchema = stripRegexSchemaKeywords(schema);
262
+ const validated = validateToolArguments({ name: POLYPHASE_RESULT_TOOL_NAME, description: "", parameters: safeSchema }, { type: "toolCall", id: "result", name: POLYPHASE_RESULT_TOOL_NAME, arguments: pending.value });
263
+ reducer.state.structured = { value: validated };
264
+ }
265
+ catch (error) {
266
+ reducer.state.structured = undefined;
267
+ const rawMessage = error instanceof Error ? error.message : String(error);
268
+ const message = formatStructuredOutputError(rawMessage);
269
+ const change = recordReducerNotice(reducer, "warning", `structured output invalid: ${message}`);
270
+ onChange?.(change);
271
+ }
272
+ }
273
+ /** §7.3: re-spawn once without `--model`/`--thinking` when the inherited model could not be resolved. */
274
+ function shouldFallbackToChildDefault(spec, reducer, result) {
275
+ return (spec.run?.fallbackToChildDefaultModel === true &&
276
+ !result.exit.cancelled &&
277
+ result.finish.exitCode !== 0 &&
278
+ reducer.state.recordsSeen === 0 &&
279
+ /model/i.test(reducer.state.stderrTail));
280
+ }
281
+ /** Writes the appended-system-prompt and polyphase_result schema temp files, then runs §7.2-7.4. */
282
+ async function runInTempDir(spec, tempDir, reducer) {
283
+ const combinedPrompt = `${spec.agent.systemPrompt}\n\n${spec.run?.extraSystemPrompt ?? ""}`;
284
+ let systemPromptFile;
285
+ if (combinedPrompt.trim().length > 0) {
286
+ systemPromptFile = path.join(tempDir, "prompt.md");
287
+ fs.writeFileSync(systemPromptFile, combinedPrompt, { encoding: "utf-8", mode: 0o600 });
288
+ }
289
+ let schemaFile;
290
+ if (spec.run?.schema) {
291
+ schemaFile = path.join(tempDir, "schema.json");
292
+ fs.writeFileSync(schemaFile, JSON.stringify(spec.run.schema), { encoding: "utf-8", mode: 0o600 });
293
+ }
294
+ const files = { systemPromptFile, schemaFile };
295
+ const command = spec.command ?? resolveDrahtCommand();
296
+ reducer.markSpawning();
297
+ const start = Date.now();
298
+ let result = await spawnAttempt(spec, command, reducer, files, {});
299
+ if (shouldFallbackToChildDefault(spec, reducer, result)) {
300
+ const requested = spec.run?.model ?? spec.agent.model ?? "";
301
+ reducer.resetForRetry({ source: "child-default", confirmed: false }, `inherited model ${requested} is unavailable in the child; using the child's default model`);
302
+ result = await spawnAttempt(spec, command, reducer, files, { omitModel: true });
303
+ }
304
+ if (spec.run?.schema)
305
+ validateStructuredOutput(reducer, spec.run.schema, spec.run?.onChange);
306
+ return toRunResult(reducer.state, { agent: spec.agent.name, task: spec.task, step: spec.step }, result.finish, {
307
+ cancelled: result.exit.cancelled,
308
+ structured: reducer.state.structured,
309
+ durationMs: Date.now() - start,
310
+ });
311
+ }
312
+ function createReducerForSpec(spec) {
313
+ return (spec.run?.reducer ??
314
+ new ChildEventReducer({
315
+ model: spec.run?.modelInfo ?? {
316
+ source: spec.agent.model ? "frontmatter" : "child-default",
317
+ requested: spec.agent.model,
318
+ confirmed: false,
319
+ },
320
+ }));
321
+ }
322
+ /** Never rejects: spawn and runtime failures resolve as a failed `RunResult`. */
323
+ export async function runChildAgent(spec) {
324
+ const reducer = createReducerForSpec(spec);
325
+ const base = { agent: spec.agent.name, task: spec.task, step: spec.step };
326
+ const attemptStart = Date.now();
327
+ if (spec.signal?.aborted) {
328
+ const finish = reducer.finish({ code: null, signal: null, cancelled: true });
329
+ return toRunResult(reducer.state, base, finish, {
330
+ cancelled: true,
331
+ durationMs: Date.now() - attemptStart,
332
+ });
333
+ }
334
+ let tempDir;
335
+ try {
336
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "draht-polyphase-"));
337
+ return await runInTempDir(spec, tempDir, reducer);
338
+ }
339
+ catch (error) {
340
+ const cancelled = spec.signal?.aborted === true;
341
+ const finish = reducer.finish({
342
+ code: null,
343
+ signal: null,
344
+ cancelled,
345
+ spawnError: error instanceof Error ? error.message : String(error),
346
+ });
347
+ return toRunResult(reducer.state, base, finish, { cancelled, durationMs: Date.now() - attemptStart });
348
+ }
349
+ finally {
350
+ if (tempDir) {
351
+ try {
352
+ fs.rmSync(tempDir, { recursive: true, force: true });
353
+ }
354
+ catch { }
355
+ }
356
+ }
357
+ }
358
+ export function createProcessAgentRunner(command) {
359
+ return (cwd, agent, task, signal, step, onProgress, run) => runChildAgent({ cwd, agent, task, step, run, signal, onProgress, command });
360
+ }
361
+ //# sourceMappingURL=child-process.js.map