@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,90 @@
1
+ /**
2
+ * Throttled partial-update emitter (§10.7): turns a run's `onFlush` notifications into
3
+ * `AgentToolUpdateCallback` invocations, coalesced to at most once per `liveUpdateMs` (TUI) or
4
+ * 1000 ms (every other mode), with a fast path for coarse changes so the row shows a blocked or
5
+ * finished agent without waiting out the full throttle.
6
+ */
7
+ import { buildDetails } from "./details.js";
8
+ import { formatPartialStatusText } from "./result-text.js";
9
+ /** A coarse change (e.g. a tool blocked, an agent finished) emits once at least this long has
10
+ * passed since the last emission, rather than waiting out the full throttle interval. */
11
+ const COARSE_FAST_PATH_MS = 50;
12
+ const NON_TUI_INTERVAL_MS = 1000;
13
+ export function createPartialUpdateEmitter(run, onUpdate, options) {
14
+ if (!onUpdate)
15
+ return { flush() { }, dispose() { } };
16
+ const emit = onUpdate;
17
+ const minIntervalMs = options.mode === "tui" ? options.liveUpdateMs : NON_TUI_INTERVAL_MS;
18
+ let lastEmitAt = Number.NEGATIVE_INFINITY;
19
+ let trailingTimer;
20
+ let trailingDeadline;
21
+ let disposed = false;
22
+ function clearTrailing() {
23
+ if (trailingTimer === undefined)
24
+ return;
25
+ clearTimeout(trailingTimer);
26
+ trailingTimer = undefined;
27
+ trailingDeadline = undefined;
28
+ }
29
+ function emitNow() {
30
+ if (disposed)
31
+ return;
32
+ clearTrailing();
33
+ lastEmitAt = Date.now();
34
+ emit({
35
+ content: [{ type: "text", text: formatPartialStatusText(run) }],
36
+ details: buildDetails(run, { final: false }),
37
+ });
38
+ }
39
+ // Re-arms the timer only when the new deadline is sooner than the one already pending, so a
40
+ // coarse flush can shorten an existing fine deadline instead of waiting it out.
41
+ function armTrailing(delayMs) {
42
+ const deadline = Date.now() + delayMs;
43
+ if (trailingTimer !== undefined) {
44
+ if (trailingDeadline !== undefined && deadline >= trailingDeadline)
45
+ return;
46
+ clearTrailing();
47
+ }
48
+ const timer = setTimeout(() => {
49
+ trailingTimer = undefined;
50
+ trailingDeadline = undefined;
51
+ try {
52
+ emitNow();
53
+ }
54
+ catch {
55
+ // Partial updates are best-effort: a throw here must not escape a Node timer as an
56
+ // uncaughtException and kill the host process.
57
+ }
58
+ }, delayMs);
59
+ timer.unref?.();
60
+ trailingTimer = timer;
61
+ trailingDeadline = deadline;
62
+ }
63
+ function onRunFlush(_run, coarse) {
64
+ if (disposed)
65
+ return;
66
+ const elapsed = Date.now() - lastEmitAt;
67
+ if ((coarse && elapsed >= COARSE_FAST_PATH_MS) || elapsed >= minIntervalMs) {
68
+ emitNow();
69
+ return;
70
+ }
71
+ armTrailing((coarse ? COARSE_FAST_PATH_MS : minIntervalMs) - elapsed);
72
+ }
73
+ // Emit before subscribing: if the first emission throws (e.g. `onUpdate` or `buildDetails`),
74
+ // the caller never gets a dispose handle and must not be left with a listener on `run`.
75
+ emitNow();
76
+ const unsubscribe = run.onFlush(onRunFlush);
77
+ return {
78
+ flush() {
79
+ emitNow();
80
+ },
81
+ dispose() {
82
+ if (disposed)
83
+ return;
84
+ disposed = true;
85
+ clearTrailing();
86
+ unsubscribe();
87
+ },
88
+ };
89
+ }
90
+ //# sourceMappingURL=emitter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../../src/core/polyphase/emitter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC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;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Throttled partial-update emitter (§10.7): turns a run's `onFlush` notifications into\n * `AgentToolUpdateCallback` invocations, coalesced to at most once per `liveUpdateMs` (TUI) or\n * 1000 ms (every other mode), with a fast path for coarse changes so the row shows a blocked or\n * finished agent without waiting out the full throttle.\n */\n\nimport type { AgentToolUpdateCallback, ExtensionMode } from \"../extensions/types.ts\";\nimport { buildDetails } from \"./details.ts\";\nimport { formatPartialStatusText } from \"./result-text.ts\";\nimport type { PolyphaseRun } from \"./store.ts\";\nimport type { PolyphaseDetails } from \"./types.ts\";\n\nexport interface PartialUpdateEmitter {\n\t/** Emits immediately, bypassing the throttle. */\n\tflush(): void;\n\tdispose(): void;\n}\n\nexport interface PartialUpdateEmitterOptions {\n\tmode: ExtensionMode;\n\tliveUpdateMs: number;\n}\n\n/** A coarse change (e.g. a tool blocked, an agent finished) emits once at least this long has\n * passed since the last emission, rather than waiting out the full throttle interval. */\nconst COARSE_FAST_PATH_MS = 50;\nconst NON_TUI_INTERVAL_MS = 1000;\n\nexport function createPartialUpdateEmitter(\n\trun: PolyphaseRun,\n\tonUpdate: AgentToolUpdateCallback<PolyphaseDetails> | undefined,\n\toptions: PartialUpdateEmitterOptions,\n): PartialUpdateEmitter {\n\tif (!onUpdate) return { flush() {}, dispose() {} };\n\tconst emit = onUpdate;\n\n\tconst minIntervalMs = options.mode === \"tui\" ? options.liveUpdateMs : NON_TUI_INTERVAL_MS;\n\tlet lastEmitAt = Number.NEGATIVE_INFINITY;\n\tlet trailingTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet trailingDeadline: number | undefined;\n\tlet disposed = false;\n\n\tfunction clearTrailing(): void {\n\t\tif (trailingTimer === undefined) return;\n\t\tclearTimeout(trailingTimer);\n\t\ttrailingTimer = undefined;\n\t\ttrailingDeadline = undefined;\n\t}\n\n\tfunction emitNow(): void {\n\t\tif (disposed) return;\n\t\tclearTrailing();\n\t\tlastEmitAt = Date.now();\n\t\temit({\n\t\t\tcontent: [{ type: \"text\", text: formatPartialStatusText(run) }],\n\t\t\tdetails: buildDetails(run, { final: false }),\n\t\t});\n\t}\n\n\t// Re-arms the timer only when the new deadline is sooner than the one already pending, so a\n\t// coarse flush can shorten an existing fine deadline instead of waiting it out.\n\tfunction armTrailing(delayMs: number): void {\n\t\tconst deadline = Date.now() + delayMs;\n\t\tif (trailingTimer !== undefined) {\n\t\t\tif (trailingDeadline !== undefined && deadline >= trailingDeadline) return;\n\t\t\tclearTrailing();\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\ttrailingTimer = undefined;\n\t\t\ttrailingDeadline = undefined;\n\t\t\ttry {\n\t\t\t\temitNow();\n\t\t\t} catch {\n\t\t\t\t// Partial updates are best-effort: a throw here must not escape a Node timer as an\n\t\t\t\t// uncaughtException and kill the host process.\n\t\t\t}\n\t\t}, delayMs);\n\t\ttimer.unref?.();\n\t\ttrailingTimer = timer;\n\t\ttrailingDeadline = deadline;\n\t}\n\n\tfunction onRunFlush(_run: PolyphaseRun, coarse: boolean): void {\n\t\tif (disposed) return;\n\t\tconst elapsed = Date.now() - lastEmitAt;\n\t\tif ((coarse && elapsed >= COARSE_FAST_PATH_MS) || elapsed >= minIntervalMs) {\n\t\t\temitNow();\n\t\t\treturn;\n\t\t}\n\t\tarmTrailing((coarse ? COARSE_FAST_PATH_MS : minIntervalMs) - elapsed);\n\t}\n\n\t// Emit before subscribing: if the first emission throws (e.g. `onUpdate` or `buildDetails`),\n\t// the caller never gets a dispose handle and must not be left with a listener on `run`.\n\temitNow();\n\tconst unsubscribe = run.onFlush(onRunFlush);\n\n\treturn {\n\t\tflush() {\n\t\t\temitNow();\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tclearTrailing();\n\t\t\tunsubscribe();\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,31 @@
1
+ import type { Readable } from "node:stream";
2
+ /**
3
+ * Bounded LF-only line reader for child JSON streams.
4
+ *
5
+ * Unlike `modes/rpc/jsonl.ts` (which buffers whole lines and is not reused here), this
6
+ * reader discards known-noisy record prefixes before they are fully buffered, so a
7
+ * multi-megabyte `agent_end`/`tool_execution_update` line never grows the retained
8
+ * buffer past a small, bounded size.
9
+ */
10
+ export interface ChildLineReaderOptions {
11
+ /** Lines longer than this (chars) enter discard mode and call `onOversize`. Default 8 MiB. */
12
+ maxLineChars: number;
13
+ /** Known-noisy prefixes that are dropped without ever being handed to `onLine`. */
14
+ skipPrefixes: readonly string[];
15
+ onSkipped?: (prefix: string) => void;
16
+ onOversize?: () => void;
17
+ }
18
+ export declare const DEFAULT_SKIP_PREFIXES: readonly string[];
19
+ export interface ChildLineReader {
20
+ detach(): void;
21
+ readonly maxBufferedChars: number;
22
+ readonly skippedLines: number;
23
+ }
24
+ /**
25
+ * Attach a bounded LF-only line reader to a child process stream.
26
+ *
27
+ * Framing is LF-only; a single trailing `\r` is stripped. U+2028/U+2029 are left
28
+ * untouched inside lines. Handlers run synchronously and this function never throws.
29
+ */
30
+ export declare function attachChildLineReader(stream: Readable, onLine: (line: string) => void, options?: Partial<ChildLineReaderOptions>): ChildLineReader;
31
+ //# sourceMappingURL=jsonl-reader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonl-reader.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/jsonl-reader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACtC,8FAA8F;IAC9F,YAAY,EAAE,MAAM,CAAC;IACrB,mFAAmF;IACnF,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;CACxB;AAED,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAWlD,CAAC;AAOF,MAAM,WAAW,eAAe;IAC/B,MAAM,IAAI,IAAI,CAAC;IACf,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACpC,MAAM,EAAE,QAAQ,EAChB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAC9B,OAAO,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,GACvC,eAAe,CAiJjB"}
@@ -0,0 +1,161 @@
1
+ import { StringDecoder } from "node:string_decoder";
2
+ export const DEFAULT_SKIP_PREFIXES = [
3
+ '{"type":"agent_end"',
4
+ '{"type":"turn_end"',
5
+ '{"type":"tool_execution_update"',
6
+ '{"type":"entry_appended"',
7
+ '{"type":"message_start","message":{"role":"toolResult"',
8
+ '{"type":"message_end","message":{"role":"toolResult"',
9
+ '{"type":"message_start","message":{"role":"user"',
10
+ '{"type":"message_end","message":{"role":"user"',
11
+ '{"type":"message_start","message":{"role":"system"',
12
+ '{"type":"message_end","message":{"role":"system"',
13
+ ];
14
+ const DEFAULT_MAX_LINE_CHARS = 8 * 1024 * 1024;
15
+ /** Chars of a still-open line needed before a skip-prefix match is attempted. */
16
+ const PREFIX_CHECK_THRESHOLD = 64;
17
+ /**
18
+ * Attach a bounded LF-only line reader to a child process stream.
19
+ *
20
+ * Framing is LF-only; a single trailing `\r` is stripped. U+2028/U+2029 are left
21
+ * untouched inside lines. Handlers run synchronously and this function never throws.
22
+ */
23
+ export function attachChildLineReader(stream, onLine, options) {
24
+ const maxLineChars = options?.maxLineChars ?? DEFAULT_MAX_LINE_CHARS;
25
+ const skipPrefixes = options?.skipPrefixes ?? DEFAULT_SKIP_PREFIXES;
26
+ const onSkipped = options?.onSkipped;
27
+ const onOversize = options?.onOversize;
28
+ // A caller-supplied prefix longer than the default threshold would otherwise never match while
29
+ // the line is still streaming (the check only runs once the buffer reaches this many chars).
30
+ const prefixCheckThreshold = skipPrefixes.reduce((max, prefix) => Math.max(max, prefix.length), PREFIX_CHECK_THRESHOLD);
31
+ const decoder = new StringDecoder("utf8");
32
+ let buffer = "";
33
+ let discarding = false;
34
+ let skippedLines = 0;
35
+ let maxBufferedChars = 0;
36
+ function matchSkipPrefix(line) {
37
+ for (const prefix of skipPrefixes) {
38
+ if (line.startsWith(prefix))
39
+ return prefix;
40
+ }
41
+ return undefined;
42
+ }
43
+ function recordBufferSize() {
44
+ if (buffer.length > maxBufferedChars)
45
+ maxBufferedChars = buffer.length;
46
+ }
47
+ function callHandler(handler) {
48
+ if (!handler)
49
+ return;
50
+ try {
51
+ handler();
52
+ }
53
+ catch {
54
+ // A bad onSkipped/onOversize/onLine handler must never break framing of the rest of the chunk.
55
+ }
56
+ }
57
+ function enterDiscard(prefix) {
58
+ discarding = true;
59
+ buffer = "";
60
+ if (prefix !== undefined) {
61
+ skippedLines++;
62
+ callHandler(onSkipped ? () => onSkipped(prefix) : undefined);
63
+ }
64
+ else {
65
+ callHandler(onOversize);
66
+ }
67
+ }
68
+ function emit(rawLine) {
69
+ const prefix = matchSkipPrefix(rawLine);
70
+ if (prefix !== undefined) {
71
+ skippedLines++;
72
+ callHandler(onSkipped ? () => onSkipped(prefix) : undefined);
73
+ return;
74
+ }
75
+ if (rawLine.length > maxLineChars) {
76
+ callHandler(onOversize);
77
+ return;
78
+ }
79
+ callHandler(() => onLine(rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine));
80
+ }
81
+ // Amortised O(bytes): each incoming chunk is scanned once with index arithmetic into
82
+ // the chunk itself. The persisted `buffer` only ever holds an in-progress partial line,
83
+ // and while that partial line is being grown toward the skip-prefix check threshold we
84
+ // slice the chunk in small increments so a long skip-prefixed line never buffers more
85
+ // than `prefixCheckThreshold` chars before `discarding` kicks in.
86
+ function processChunk(chunk) {
87
+ let idx = 0;
88
+ while (idx <= chunk.length) {
89
+ if (discarding) {
90
+ const nl = chunk.indexOf("\n", idx);
91
+ if (nl === -1)
92
+ return;
93
+ discarding = false;
94
+ idx = nl + 1;
95
+ continue;
96
+ }
97
+ const nl = chunk.indexOf("\n", idx);
98
+ if (nl === -1) {
99
+ if (buffer.length < prefixCheckThreshold) {
100
+ const need = prefixCheckThreshold - buffer.length;
101
+ const take = Math.min(need, chunk.length - idx);
102
+ if (take > 0) {
103
+ buffer += chunk.slice(idx, idx + take);
104
+ idx += take;
105
+ recordBufferSize();
106
+ }
107
+ if (buffer.length >= prefixCheckThreshold) {
108
+ const prefix = matchSkipPrefix(buffer);
109
+ if (prefix !== undefined) {
110
+ enterDiscard(prefix);
111
+ continue;
112
+ }
113
+ }
114
+ }
115
+ if (idx < chunk.length) {
116
+ buffer += chunk.slice(idx);
117
+ idx = chunk.length;
118
+ recordBufferSize();
119
+ if (buffer.length > maxLineChars) {
120
+ enterDiscard(undefined);
121
+ }
122
+ }
123
+ return;
124
+ }
125
+ const rawLine = buffer + chunk.slice(idx, nl);
126
+ buffer = "";
127
+ emit(rawLine);
128
+ idx = nl + 1;
129
+ }
130
+ }
131
+ const onData = (chunk) => {
132
+ const decoded = typeof chunk === "string" ? chunk : decoder.write(chunk);
133
+ if (decoded.length > 0)
134
+ processChunk(decoded);
135
+ };
136
+ const onEnd = () => {
137
+ const tail = decoder.end();
138
+ if (tail.length > 0)
139
+ processChunk(tail);
140
+ if (!discarding && buffer.length > 0) {
141
+ const rawLine = buffer;
142
+ buffer = "";
143
+ emit(rawLine);
144
+ }
145
+ };
146
+ stream.on("data", onData);
147
+ stream.on("end", onEnd);
148
+ return {
149
+ detach() {
150
+ stream.off("data", onData);
151
+ stream.off("end", onEnd);
152
+ },
153
+ get maxBufferedChars() {
154
+ return maxBufferedChars;
155
+ },
156
+ get skippedLines() {
157
+ return skippedLines;
158
+ },
159
+ };
160
+ }
161
+ //# sourceMappingURL=jsonl-reader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonl-reader.js","sourceRoot":"","sources":["../../../src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OAAO,GAAG,MAAM,CAAC;YACvB,MAAM,GAAG,EAAE,CAAC;YACZ,IAAI,CAAC,OAAO,CAAC,CAAC;QACf,CAAC;IACF,CAAC,CAAC;IAEF,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAExB,OAAO;QACN,MAAM;YACL,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YAC3B,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAC1B,CAAC;QACD,IAAI,gBAAgB;YACnB,OAAO,gBAAgB,CAAC;QACzB,CAAC;QACD,IAAI,YAAY;YACf,OAAO,YAAY,CAAC;QACrB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { Readable } from \"node:stream\";\nimport { StringDecoder } from \"node:string_decoder\";\n\n/**\n * Bounded LF-only line reader for child JSON streams.\n *\n * Unlike `modes/rpc/jsonl.ts` (which buffers whole lines and is not reused here), this\n * reader discards known-noisy record prefixes before they are fully buffered, so a\n * multi-megabyte `agent_end`/`tool_execution_update` line never grows the retained\n * buffer past a small, bounded size.\n */\nexport interface ChildLineReaderOptions {\n\t/** Lines longer than this (chars) enter discard mode and call `onOversize`. Default 8 MiB. */\n\tmaxLineChars: number;\n\t/** Known-noisy prefixes that are dropped without ever being handed to `onLine`. */\n\tskipPrefixes: readonly string[];\n\tonSkipped?: (prefix: string) => void;\n\tonOversize?: () => void;\n}\n\nexport const DEFAULT_SKIP_PREFIXES: readonly string[] = [\n\t'{\"type\":\"agent_end\"',\n\t'{\"type\":\"turn_end\"',\n\t'{\"type\":\"tool_execution_update\"',\n\t'{\"type\":\"entry_appended\"',\n\t'{\"type\":\"message_start\",\"message\":{\"role\":\"toolResult\"',\n\t'{\"type\":\"message_end\",\"message\":{\"role\":\"toolResult\"',\n\t'{\"type\":\"message_start\",\"message\":{\"role\":\"user\"',\n\t'{\"type\":\"message_end\",\"message\":{\"role\":\"user\"',\n\t'{\"type\":\"message_start\",\"message\":{\"role\":\"system\"',\n\t'{\"type\":\"message_end\",\"message\":{\"role\":\"system\"',\n];\n\nconst DEFAULT_MAX_LINE_CHARS = 8 * 1024 * 1024;\n\n/** Chars of a still-open line needed before a skip-prefix match is attempted. */\nconst PREFIX_CHECK_THRESHOLD = 64;\n\nexport interface ChildLineReader {\n\tdetach(): void;\n\treadonly maxBufferedChars: number;\n\treadonly skippedLines: number;\n}\n\n/**\n * Attach a bounded LF-only line reader to a child process stream.\n *\n * Framing is LF-only; a single trailing `\\r` is stripped. U+2028/U+2029 are left\n * untouched inside lines. Handlers run synchronously and this function never throws.\n */\nexport function attachChildLineReader(\n\tstream: Readable,\n\tonLine: (line: string) => void,\n\toptions?: Partial<ChildLineReaderOptions>,\n): ChildLineReader {\n\tconst maxLineChars = options?.maxLineChars ?? DEFAULT_MAX_LINE_CHARS;\n\tconst skipPrefixes = options?.skipPrefixes ?? DEFAULT_SKIP_PREFIXES;\n\tconst onSkipped = options?.onSkipped;\n\tconst onOversize = options?.onOversize;\n\t// A caller-supplied prefix longer than the default threshold would otherwise never match while\n\t// the line is still streaming (the check only runs once the buffer reaches this many chars).\n\tconst prefixCheckThreshold = skipPrefixes.reduce(\n\t\t(max, prefix) => Math.max(max, prefix.length),\n\t\tPREFIX_CHECK_THRESHOLD,\n\t);\n\n\tconst decoder = new StringDecoder(\"utf8\");\n\tlet buffer = \"\";\n\tlet discarding = false;\n\tlet skippedLines = 0;\n\tlet maxBufferedChars = 0;\n\n\tfunction matchSkipPrefix(line: string): string | undefined {\n\t\tfor (const prefix of skipPrefixes) {\n\t\t\tif (line.startsWith(prefix)) return prefix;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tfunction recordBufferSize(): void {\n\t\tif (buffer.length > maxBufferedChars) maxBufferedChars = buffer.length;\n\t}\n\n\tfunction callHandler(handler: (() => void) | undefined): void {\n\t\tif (!handler) return;\n\t\ttry {\n\t\t\thandler();\n\t\t} catch {\n\t\t\t// A bad onSkipped/onOversize/onLine handler must never break framing of the rest of the chunk.\n\t\t}\n\t}\n\n\tfunction enterDiscard(prefix: string | undefined): void {\n\t\tdiscarding = true;\n\t\tbuffer = \"\";\n\t\tif (prefix !== undefined) {\n\t\t\tskippedLines++;\n\t\t\tcallHandler(onSkipped ? () => onSkipped(prefix) : undefined);\n\t\t} else {\n\t\t\tcallHandler(onOversize);\n\t\t}\n\t}\n\n\tfunction emit(rawLine: string): void {\n\t\tconst prefix = matchSkipPrefix(rawLine);\n\t\tif (prefix !== undefined) {\n\t\t\tskippedLines++;\n\t\t\tcallHandler(onSkipped ? () => onSkipped(prefix) : undefined);\n\t\t\treturn;\n\t\t}\n\t\tif (rawLine.length > maxLineChars) {\n\t\t\tcallHandler(onOversize);\n\t\t\treturn;\n\t\t}\n\t\tcallHandler(() => onLine(rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine));\n\t}\n\n\t// Amortised O(bytes): each incoming chunk is scanned once with index arithmetic into\n\t// the chunk itself. The persisted `buffer` only ever holds an in-progress partial line,\n\t// and while that partial line is being grown toward the skip-prefix check threshold we\n\t// slice the chunk in small increments so a long skip-prefixed line never buffers more\n\t// than `prefixCheckThreshold` chars before `discarding` kicks in.\n\tfunction processChunk(chunk: string): void {\n\t\tlet idx = 0;\n\t\twhile (idx <= chunk.length) {\n\t\t\tif (discarding) {\n\t\t\t\tconst nl = chunk.indexOf(\"\\n\", idx);\n\t\t\t\tif (nl === -1) return;\n\t\t\t\tdiscarding = false;\n\t\t\t\tidx = nl + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst nl = chunk.indexOf(\"\\n\", idx);\n\t\t\tif (nl === -1) {\n\t\t\t\tif (buffer.length < prefixCheckThreshold) {\n\t\t\t\t\tconst need = prefixCheckThreshold - buffer.length;\n\t\t\t\t\tconst take = Math.min(need, chunk.length - idx);\n\t\t\t\t\tif (take > 0) {\n\t\t\t\t\t\tbuffer += chunk.slice(idx, idx + take);\n\t\t\t\t\t\tidx += take;\n\t\t\t\t\t\trecordBufferSize();\n\t\t\t\t\t}\n\t\t\t\t\tif (buffer.length >= prefixCheckThreshold) {\n\t\t\t\t\t\tconst prefix = matchSkipPrefix(buffer);\n\t\t\t\t\t\tif (prefix !== undefined) {\n\t\t\t\t\t\t\tenterDiscard(prefix);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (idx < chunk.length) {\n\t\t\t\t\tbuffer += chunk.slice(idx);\n\t\t\t\t\tidx = chunk.length;\n\t\t\t\t\trecordBufferSize();\n\t\t\t\t\tif (buffer.length > maxLineChars) {\n\t\t\t\t\t\tenterDiscard(undefined);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst rawLine = buffer + chunk.slice(idx, nl);\n\t\t\tbuffer = \"\";\n\t\t\temit(rawLine);\n\t\t\tidx = nl + 1;\n\t\t}\n\t}\n\n\tconst onData = (chunk: string | Buffer) => {\n\t\tconst decoded = typeof chunk === \"string\" ? chunk : decoder.write(chunk);\n\t\tif (decoded.length > 0) processChunk(decoded);\n\t};\n\n\tconst onEnd = () => {\n\t\tconst tail = decoder.end();\n\t\tif (tail.length > 0) processChunk(tail);\n\t\tif (!discarding && buffer.length > 0) {\n\t\t\tconst rawLine = buffer;\n\t\t\tbuffer = \"\";\n\t\t\temit(rawLine);\n\t\t}\n\t};\n\n\tstream.on(\"data\", onData);\n\tstream.on(\"end\", onEnd);\n\n\treturn {\n\t\tdetach(): void {\n\t\t\tstream.off(\"data\", onData);\n\t\t\tstream.off(\"end\", onEnd);\n\t\t},\n\t\tget maxBufferedChars(): number {\n\t\t\treturn maxBufferedChars;\n\t\t},\n\t\tget skippedLines(): number {\n\t\t\treturn skippedLines;\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Keyword trigger for the `workflow` tool (§16.5): detects the configured keyword in idle or
3
+ * streaming user input, registers and activates the tool for one prompt, and sends a one-time
4
+ * authoring guide as a visible custom message. Never edits the user text or the system prompt.
5
+ */
6
+ import type { BeforeAgentStartEvent, BeforeAgentStartEventResult, ExtensionAPI, ExtensionContext, InputEvent, InputEventResult } from "../extensions/types.ts";
7
+ import type { SessionEntry } from "../session-manager.ts";
8
+ import type { ResolvedPolyphaseSettings } from "./settings.ts";
9
+ /** Whole-word, case-insensitive, Unicode-aware match: the keyword must not be part of a longer word. */
10
+ export declare function detectKeyword(text: string, keyword: string): boolean;
11
+ /** True when a `polyphase-guidance` custom message entry appears after the last compaction entry. */
12
+ export declare function hasGuidanceInContext(entries: readonly SessionEntry[]): boolean;
13
+ export interface KeywordHooks {
14
+ onInput(event: InputEvent, ctx: ExtensionContext): InputEventResult;
15
+ onBeforeAgentStart(event: BeforeAgentStartEvent, ctx: ExtensionContext): BeforeAgentStartEventResult | undefined;
16
+ onAgentSettled(ctx: ExtensionContext): void;
17
+ }
18
+ export interface KeywordHooksDeps {
19
+ pi: ExtensionAPI;
20
+ settings(): ResolvedPolyphaseSettings;
21
+ ensureTool(): boolean;
22
+ activate(): void;
23
+ deactivateIfAuto(): void;
24
+ buildGuide(ctx: ExtensionContext): string;
25
+ }
26
+ export declare function createKeywordHooks(deps: KeywordHooksDeps): KeywordHooks;
27
+ //# sourceMappingURL=keyword.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyword.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/keyword.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EACX,qBAAqB,EACrB,2BAA2B,EAC3B,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAI/D,wGAAwG;AACxG,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAGpE;AAED,qGAAqG;AACrG,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,OAAO,CAU9E;AAED,MAAM,WAAW,YAAY;IAC5B,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,CAAC;IACpE,kBAAkB,CAAC,KAAK,EAAE,qBAAqB,EAAE,GAAG,EAAE,gBAAgB,GAAG,2BAA2B,GAAG,SAAS,CAAC;IACjH,cAAc,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAAC;CAC5C;AAED,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,YAAY,CAAC;IACjB,QAAQ,IAAI,yBAAyB,CAAC;IACtC,UAAU,IAAI,OAAO,CAAC;IACtB,QAAQ,IAAI,IAAI,CAAC;IACjB,gBAAgB,IAAI,IAAI,CAAC;IACzB,UAAU,CAAC,GAAG,EAAE,gBAAgB,GAAG,MAAM,CAAC;CAC1C;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,gBAAgB,GAAG,YAAY,CA2EvE"}
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Keyword trigger for the `workflow` tool (§16.5): detects the configured keyword in idle or
3
+ * streaming user input, registers and activates the tool for one prompt, and sends a one-time
4
+ * authoring guide as a visible custom message. Never edits the user text or the system prompt.
5
+ */
6
+ const GUIDANCE_CUSTOM_TYPE = "polyphase-guidance";
7
+ /** Whole-word, case-insensitive, Unicode-aware match: the keyword must not be part of a longer word. */
8
+ export function detectKeyword(text, keyword) {
9
+ const pattern = new RegExp(`(^|[^\\p{L}\\p{N}_-])${keyword}(?=$|[^\\p{L}\\p{N}_-])`, "iu");
10
+ return pattern.test(text);
11
+ }
12
+ /** True when a `polyphase-guidance` custom message entry appears after the last compaction entry. */
13
+ export function hasGuidanceInContext(entries) {
14
+ let lastCompactionIndex = -1;
15
+ for (let i = 0; i < entries.length; i++) {
16
+ if (entries[i].type === "compaction")
17
+ lastCompactionIndex = i;
18
+ }
19
+ for (let i = lastCompactionIndex + 1; i < entries.length; i++) {
20
+ const entry = entries[i];
21
+ if (entry.type === "custom_message" && entry.customType === GUIDANCE_CUSTOM_TYPE)
22
+ return true;
23
+ }
24
+ return false;
25
+ }
26
+ export function createKeywordHooks(deps) {
27
+ let armed = false;
28
+ // `sendMessage({deliverAs})` on the streaming path queues the guidance into the branch instead
29
+ // of writing it immediately (agent-session.ts sendCustomMessage routes steer/followUp to the
30
+ // agent's queues), so `hasGuidanceInContext` cannot see it there yet. Without this flag, a
31
+ // second keyword steer/follow-up before delivery passes the same `hasGuidanceInContext` check
32
+ // and queues a second copy of the full authoring guide.
33
+ let guidanceQueued = false;
34
+ return {
35
+ onInput(event, ctx) {
36
+ const settings = deps.settings();
37
+ if (settings.workflowTool === "off" ||
38
+ event.source === "extension" ||
39
+ event.text.startsWith("/") ||
40
+ event.text.startsWith("!") ||
41
+ !detectKeyword(event.text, settings.keyword)) {
42
+ // Do nothing else (§16.5): in particular, never clear a pending `armed` arm. An
43
+ // extension-sourced input event can land between an armed user input and the
44
+ // `before_agent_start` that consumes it.
45
+ return { action: "continue" };
46
+ }
47
+ if (event.streamingBehavior === undefined) {
48
+ armed = true;
49
+ return { action: "continue" };
50
+ }
51
+ armed = false;
52
+ if (!deps.ensureTool())
53
+ return { action: "continue" };
54
+ deps.activate();
55
+ if (!guidanceQueued && !hasGuidanceInContext(ctx.sessionManager.getBranch())) {
56
+ guidanceQueued = true;
57
+ const guide = deps.buildGuide(ctx);
58
+ deps.pi.sendMessage({
59
+ customType: GUIDANCE_CUSTOM_TYPE,
60
+ content: [{ type: "text", text: guide }],
61
+ display: true,
62
+ details: { keyword: settings.keyword },
63
+ }, { deliverAs: event.streamingBehavior });
64
+ }
65
+ return { action: "continue" };
66
+ },
67
+ onBeforeAgentStart(event, ctx) {
68
+ if (!armed)
69
+ return undefined;
70
+ armed = false;
71
+ // The armed input and this turn's prompt should be the same text, but a handler earlier
72
+ // in the chain (or a turn that never reached `input`, e.g. a triggered `sendMessage`) can
73
+ // start a turn that never matched the keyword; re-check instead of trusting the stale arm.
74
+ if (!detectKeyword(event.prompt, deps.settings().keyword))
75
+ return undefined;
76
+ if (!deps.ensureTool())
77
+ return undefined;
78
+ deps.activate();
79
+ if (hasGuidanceInContext(ctx.sessionManager.getBranch()))
80
+ return undefined;
81
+ const guide = deps.buildGuide(ctx);
82
+ return {
83
+ message: {
84
+ customType: GUIDANCE_CUSTOM_TYPE,
85
+ content: [{ type: "text", text: guide }],
86
+ display: true,
87
+ details: { keyword: deps.settings().keyword },
88
+ },
89
+ };
90
+ },
91
+ onAgentSettled() {
92
+ guidanceQueued = false;
93
+ deps.deactivateIfAuto();
94
+ },
95
+ };
96
+ }
97
+ //# sourceMappingURL=keyword.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../../src/core/polyphase/keyword.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAaH,MAAM,oBAAoB,GAAG,oBAAoB,CAAC;AAElD,wGAAwG;AACxG,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAAe;IAC1D,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC,wBAAwB,OAAO,yBAAyB,EAAE,IAAI,CAAC,CAAC;IAC3F,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC;AAED,qGAAqG;AACrG,MAAM,UAAU,oBAAoB,CAAC,OAAgC;IACpE,IAAI,mBAAmB,GAAG,CAAC,CAAC,CAAC;IAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KA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GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YACnC,OAAO;gBACN,OAAO,EAAE;oBACR,UAAU,EAAE,oBAAoB;oBAChC,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;oBACxC,OAAO,EAAE,IAAI;oBACb,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE;iBAC7C;aACD,CAAC;QACH,CAAC;QAED,cAAc;YACb,cAAc,GAAG,KAAK,CAAC;YACvB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACzB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Keyword trigger for the `workflow` tool (§16.5): detects the configured keyword in idle or\n * streaming user input, registers and activates the tool for one prompt, and sends a one-time\n * authoring guide as a visible custom message. Never edits the user text or the system prompt.\n */\n\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tExtensionAPI,\n\tExtensionContext,\n\tInputEvent,\n\tInputEventResult,\n} from \"../extensions/types.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\nimport type { ResolvedPolyphaseSettings } from \"./settings.ts\";\n\nconst GUIDANCE_CUSTOM_TYPE = \"polyphase-guidance\";\n\n/** Whole-word, case-insensitive, Unicode-aware match: the keyword must not be part of a longer word. */\nexport function detectKeyword(text: string, keyword: string): boolean {\n\tconst pattern = new RegExp(`(^|[^\\\\p{L}\\\\p{N}_-])${keyword}(?=$|[^\\\\p{L}\\\\p{N}_-])`, \"iu\");\n\treturn pattern.test(text);\n}\n\n/** True when a `polyphase-guidance` custom message entry appears after the last compaction entry. */\nexport function hasGuidanceInContext(entries: readonly SessionEntry[]): boolean {\n\tlet lastCompactionIndex = -1;\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tif (entries[i].type === \"compaction\") lastCompactionIndex = i;\n\t}\n\tfor (let i = lastCompactionIndex + 1; i < entries.length; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"custom_message\" && entry.customType === GUIDANCE_CUSTOM_TYPE) return true;\n\t}\n\treturn false;\n}\n\nexport interface KeywordHooks {\n\tonInput(event: InputEvent, ctx: ExtensionContext): InputEventResult;\n\tonBeforeAgentStart(event: BeforeAgentStartEvent, ctx: ExtensionContext): BeforeAgentStartEventResult | undefined;\n\tonAgentSettled(ctx: ExtensionContext): void;\n}\n\nexport interface KeywordHooksDeps {\n\tpi: ExtensionAPI;\n\tsettings(): ResolvedPolyphaseSettings;\n\tensureTool(): boolean;\n\tactivate(): void;\n\tdeactivateIfAuto(): void;\n\tbuildGuide(ctx: ExtensionContext): string;\n}\n\nexport function createKeywordHooks(deps: KeywordHooksDeps): KeywordHooks {\n\tlet armed = false;\n\t// `sendMessage({deliverAs})` on the streaming path queues the guidance into the branch instead\n\t// of writing it immediately (agent-session.ts sendCustomMessage routes steer/followUp to the\n\t// agent's queues), so `hasGuidanceInContext` cannot see it there yet. Without this flag, a\n\t// second keyword steer/follow-up before delivery passes the same `hasGuidanceInContext` check\n\t// and queues a second copy of the full authoring guide.\n\tlet guidanceQueued = false;\n\n\treturn {\n\t\tonInput(event, ctx) {\n\t\t\tconst settings = deps.settings();\n\t\t\tif (\n\t\t\t\tsettings.workflowTool === \"off\" ||\n\t\t\t\tevent.source === \"extension\" ||\n\t\t\t\tevent.text.startsWith(\"/\") ||\n\t\t\t\tevent.text.startsWith(\"!\") ||\n\t\t\t\t!detectKeyword(event.text, settings.keyword)\n\t\t\t) {\n\t\t\t\t// Do nothing else (§16.5): in particular, never clear a pending `armed` arm. An\n\t\t\t\t// extension-sourced input event can land between an armed user input and the\n\t\t\t\t// `before_agent_start` that consumes it.\n\t\t\t\treturn { action: \"continue\" };\n\t\t\t}\n\n\t\t\tif (event.streamingBehavior === undefined) {\n\t\t\t\tarmed = true;\n\t\t\t\treturn { action: \"continue\" };\n\t\t\t}\n\n\t\t\tarmed = false;\n\t\t\tif (!deps.ensureTool()) return { action: \"continue\" };\n\t\t\tdeps.activate();\n\t\t\tif (!guidanceQueued && !hasGuidanceInContext(ctx.sessionManager.getBranch())) {\n\t\t\t\tguidanceQueued = true;\n\t\t\t\tconst guide = deps.buildGuide(ctx);\n\t\t\t\tdeps.pi.sendMessage(\n\t\t\t\t\t{\n\t\t\t\t\t\tcustomType: GUIDANCE_CUSTOM_TYPE,\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: guide }],\n\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\tdetails: { keyword: settings.keyword },\n\t\t\t\t\t},\n\t\t\t\t\t{ deliverAs: event.streamingBehavior },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { action: \"continue\" };\n\t\t},\n\n\t\tonBeforeAgentStart(event, ctx) {\n\t\t\tif (!armed) return undefined;\n\t\t\tarmed = false;\n\t\t\t// The armed input and this turn's prompt should be the same text, but a handler earlier\n\t\t\t// in the chain (or a turn that never reached `input`, e.g. a triggered `sendMessage`) can\n\t\t\t// start a turn that never matched the keyword; re-check instead of trusting the stale arm.\n\t\t\tif (!detectKeyword(event.prompt, deps.settings().keyword)) return undefined;\n\t\t\tif (!deps.ensureTool()) return undefined;\n\t\t\tdeps.activate();\n\t\t\tif (hasGuidanceInContext(ctx.sessionManager.getBranch())) return undefined;\n\t\t\tconst guide = deps.buildGuide(ctx);\n\t\t\treturn {\n\t\t\t\tmessage: {\n\t\t\t\t\tcustomType: GUIDANCE_CUSTOM_TYPE,\n\t\t\t\t\tcontent: [{ type: \"text\", text: guide }],\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: { keyword: deps.settings().keyword },\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\n\t\tonAgentSettled() {\n\t\t\tguidanceQueued = false;\n\t\t\tdeps.deactivateIfAuto();\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,38 @@
1
+ export interface LimiterLease {
2
+ /** Idempotent: a second call is a no-op. */
3
+ release(): void;
4
+ }
5
+ export interface LimiterStats {
6
+ capacity: number;
7
+ active: number;
8
+ queued: number;
9
+ }
10
+ export declare class LimiterAbortedError extends Error {
11
+ constructor(message?: string);
12
+ }
13
+ /**
14
+ * FIFO semaphore gating how many child agent processes run at once in a session.
15
+ * Leases are held only around a child process, never by orchestrators, so nested
16
+ * acquisition inside a lease cannot deadlock.
17
+ */
18
+ export declare class AgentLimiter {
19
+ private cap;
20
+ private active;
21
+ private readonly waiters;
22
+ private readonly listeners;
23
+ constructor(capacity: number);
24
+ get capacity(): number;
25
+ setCapacity(capacity: number): void;
26
+ acquire(options?: {
27
+ signal?: AbortSignal;
28
+ onQueued?: () => void;
29
+ }): Promise<LimiterLease>;
30
+ stats(): LimiterStats;
31
+ onChange(listener: () => void): () => void;
32
+ rejectAll(reason: Error): void;
33
+ private makeLease;
34
+ /** Grants queued waiters up to capacity. Does not notify; callers notify once themselves. */
35
+ private grantWaiting;
36
+ private notify;
37
+ }
38
+ //# sourceMappingURL=limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limiter.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/limiter.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IAC5B,4CAA4C;IAC5C,OAAO,IAAI,IAAI,CAAC;CAChB;AAED,MAAM,WAAW,YAAY;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CACf;AAED,qBAAa,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAO,SAA4C,EAG9D;CACD;AAcD;;;;GAIG;AACH,qBAAa,YAAY;IACxB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IAEnD,YAAY,QAAQ,EAAE,MAAM,EAE3B;IAED,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAIlC;IAED,OAAO,CAAC,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,CAAC,CAwCxF;IAED,KAAK,IAAI,YAAY,CAEpB;IAED,QAAQ,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAGzC;IAED,SAAS,CAAC,MAAM,EAAE,KAAK,GAAG,IAAI,CAO7B;IAED,OAAO,CAAC,SAAS;IAajB,6FAA6F;IAC7F,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,MAAM;CASd"}
@@ -0,0 +1,129 @@
1
+ export class LimiterAbortedError extends Error {
2
+ constructor(message = "aborted while waiting for an agent slot") {
3
+ super(message);
4
+ this.name = "LimiterAbortedError";
5
+ }
6
+ }
7
+ function normalizeCapacity(capacity) {
8
+ if (capacity === Number.POSITIVE_INFINITY)
9
+ return Number.MAX_SAFE_INTEGER;
10
+ const floored = Math.floor(capacity);
11
+ return Number.isFinite(floored) && floored >= 1 ? floored : 1;
12
+ }
13
+ /**
14
+ * FIFO semaphore gating how many child agent processes run at once in a session.
15
+ * Leases are held only around a child process, never by orchestrators, so nested
16
+ * acquisition inside a lease cannot deadlock.
17
+ */
18
+ export class AgentLimiter {
19
+ cap;
20
+ active = 0;
21
+ waiters = [];
22
+ listeners = new Set();
23
+ constructor(capacity) {
24
+ this.cap = normalizeCapacity(capacity);
25
+ }
26
+ get capacity() {
27
+ return this.cap;
28
+ }
29
+ setCapacity(capacity) {
30
+ this.cap = normalizeCapacity(capacity);
31
+ this.grantWaiting();
32
+ this.notify();
33
+ }
34
+ acquire(options) {
35
+ const signal = options?.signal;
36
+ if (signal?.aborted) {
37
+ return Promise.reject(new LimiterAbortedError());
38
+ }
39
+ if (this.active < this.cap && this.waiters.length === 0) {
40
+ this.active++;
41
+ this.notify();
42
+ return Promise.resolve(this.makeLease());
43
+ }
44
+ return new Promise((resolve, reject) => {
45
+ const waiter = { resolve, reject, cleanup: () => { } };
46
+ if (signal) {
47
+ const onAbort = () => {
48
+ const index = this.waiters.indexOf(waiter);
49
+ if (index === -1)
50
+ return;
51
+ this.waiters.splice(index, 1);
52
+ waiter.reject(new LimiterAbortedError());
53
+ this.notify();
54
+ };
55
+ signal.addEventListener("abort", onAbort, { once: true });
56
+ waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
57
+ }
58
+ this.waiters.push(waiter);
59
+ this.notify();
60
+ // onQueued may abort the signal synchronously; the listener above already ran by now.
61
+ try {
62
+ options?.onQueued?.();
63
+ }
64
+ catch (error) {
65
+ const index = this.waiters.indexOf(waiter);
66
+ if (index !== -1) {
67
+ this.waiters.splice(index, 1);
68
+ waiter.cleanup();
69
+ this.notify();
70
+ }
71
+ reject(error instanceof Error ? error : new Error(String(error)));
72
+ }
73
+ });
74
+ }
75
+ stats() {
76
+ return { capacity: this.cap, active: this.active, queued: this.waiters.length };
77
+ }
78
+ onChange(listener) {
79
+ this.listeners.add(listener);
80
+ return () => this.listeners.delete(listener);
81
+ }
82
+ rejectAll(reason) {
83
+ const waiters = this.waiters.splice(0, this.waiters.length);
84
+ for (const waiter of waiters) {
85
+ waiter.cleanup();
86
+ waiter.reject(reason);
87
+ }
88
+ if (waiters.length > 0)
89
+ this.notify();
90
+ }
91
+ makeLease() {
92
+ let released = false;
93
+ return {
94
+ release: () => {
95
+ if (released)
96
+ return;
97
+ released = true;
98
+ this.active--;
99
+ this.grantWaiting();
100
+ this.notify();
101
+ },
102
+ };
103
+ }
104
+ /** Grants queued waiters up to capacity. Does not notify; callers notify once themselves. */
105
+ grantWaiting() {
106
+ let granted = false;
107
+ while (this.active < this.cap && this.waiters.length > 0) {
108
+ const waiter = this.waiters.shift();
109
+ if (!waiter)
110
+ break;
111
+ waiter.cleanup();
112
+ this.active++;
113
+ waiter.resolve(this.makeLease());
114
+ granted = true;
115
+ }
116
+ return granted;
117
+ }
118
+ notify() {
119
+ for (const listener of this.listeners) {
120
+ try {
121
+ listener();
122
+ }
123
+ catch {
124
+ // A listener (store/dock rendering) must not stall the grant queue.
125
+ }
126
+ }
127
+ }
128
+ }
129
+ //# sourceMappingURL=limiter.js.map