@draht/coding-agent 2026.10.16 → 2026.10.19-1

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 (173) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
  6. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  7. package/dist/bundle/chunks/{chunk-OWGSPJPZ.js → chunk-3DQNSI5W.js} +5 -5
  8. package/dist/bundle/chunks/{chunk-JFDPOIUH.js → chunk-4COXSQRQ.js} +1 -1
  9. package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
  10. package/dist/bundle/chunks/{chunk-TJ3AW62W.js → chunk-CQF6U56X.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
  12. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
  13. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  14. package/dist/bundle/chunks/{chunk-6APPDDHH.js → chunk-I2SOJ4JN.js} +3 -3
  15. package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
  16. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  17. package/dist/bundle/chunks/{chunk-MIUVNYYW.js → chunk-QPCP4VHF.js} +123 -111
  18. package/dist/bundle/chunks/{chunk-KU5HAKZL.js → chunk-QVTLBSTH.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-2VAF4XJI.js → chunk-U6LDZZGM.js} +10 -10
  20. package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
  21. package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
  22. package/dist/bundle/chunks/{chunk-NHTOADU6.js → chunk-X3YFUSCK.js} +1 -1
  23. package/dist/bundle/chunks/{cli-U7Y4VNNI.js → cli-VCHSHNKT.js} +1 -1
  24. package/dist/bundle/chunks/{execute-ZWB4PIQQ.js → execute-AGEWJLIO.js} +1 -1
  25. package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
  26. package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
  27. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  28. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  29. package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
  30. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  31. package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
  32. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
  33. package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
  34. package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
  35. package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
  36. package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
  37. package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
  38. package/dist/bundle/chunks/{runtime-PXJK4L7Y.js → runtime-2B56SZM6.js} +1 -1
  39. package/dist/bundle/chunks/{runtime-363BOYEO.js → runtime-TJ3EAMJK.js} +1 -1
  40. package/dist/bundle/chunks/{settings-manager-GEOZJXFQ.js → settings-manager-HC5RR36T.js} +1 -1
  41. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  42. package/dist/bundle/chunks/{virtual-modules-BEJ4ZJ3D.js → virtual-modules-XT4MP2GI.js} +1 -1
  43. package/dist/bundle/cli-runtime.js +1 -1
  44. package/dist/bundle/index.js +1 -1
  45. package/dist/bundle/rpc-entry.js +1 -1
  46. package/dist/core/agent-session.d.ts.map +1 -1
  47. package/dist/core/agent-session.js +4 -0
  48. package/dist/core/agent-session.js.map +1 -1
  49. package/dist/core/builtins/duet.d.ts +7 -1
  50. package/dist/core/builtins/duet.d.ts.map +1 -1
  51. package/dist/core/builtins/duet.js +83 -14
  52. package/dist/core/builtins/duet.js.map +1 -1
  53. package/dist/core/builtins/polyphase.d.ts.map +1 -1
  54. package/dist/core/builtins/polyphase.js +21 -2
  55. package/dist/core/builtins/polyphase.js.map +1 -1
  56. package/dist/core/builtins/subagent.d.ts +59 -2
  57. package/dist/core/builtins/subagent.d.ts.map +1 -1
  58. package/dist/core/builtins/subagent.js +258 -62
  59. package/dist/core/builtins/subagent.js.map +1 -1
  60. package/dist/core/extensions/loader.d.ts.map +1 -1
  61. package/dist/core/extensions/loader.js +23 -0
  62. package/dist/core/extensions/loader.js.map +1 -1
  63. package/dist/core/extensions/runner.d.ts.map +1 -1
  64. package/dist/core/extensions/runner.js +2 -0
  65. package/dist/core/extensions/runner.js.map +1 -1
  66. package/dist/core/extensions/types.d.ts +12 -0
  67. package/dist/core/extensions/types.d.ts.map +1 -1
  68. package/dist/core/extensions/types.js.map +1 -1
  69. package/dist/core/keybindings.d.ts +5 -0
  70. package/dist/core/keybindings.d.ts.map +1 -1
  71. package/dist/core/keybindings.js +4 -0
  72. package/dist/core/keybindings.js.map +1 -1
  73. package/dist/core/multi-agent/permission-gate.d.ts +18 -6
  74. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  75. package/dist/core/multi-agent/permission-gate.js +867 -59
  76. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  77. package/dist/core/polyphase/approval.d.ts +6 -2
  78. package/dist/core/polyphase/approval.d.ts.map +1 -1
  79. package/dist/core/polyphase/approval.js +23 -35
  80. package/dist/core/polyphase/approval.js.map +1 -1
  81. package/dist/core/polyphase/child-events.js +1 -1
  82. package/dist/core/polyphase/child-events.js.map +1 -1
  83. package/dist/core/polyphase/child-process.d.ts.map +1 -1
  84. package/dist/core/polyphase/child-process.js +65 -7
  85. package/dist/core/polyphase/child-process.js.map +1 -1
  86. package/dist/core/polyphase/commands.d.ts.map +1 -1
  87. package/dist/core/polyphase/commands.js +46 -5
  88. package/dist/core/polyphase/commands.js.map +1 -1
  89. package/dist/core/polyphase/details.d.ts.map +1 -1
  90. package/dist/core/polyphase/details.js +5 -0
  91. package/dist/core/polyphase/details.js.map +1 -1
  92. package/dist/core/polyphase/permission-bridge.d.ts +128 -0
  93. package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
  94. package/dist/core/polyphase/permission-bridge.js +357 -0
  95. package/dist/core/polyphase/permission-bridge.js.map +1 -0
  96. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  97. package/dist/core/polyphase/render/run-block.js +13 -4
  98. package/dist/core/polyphase/render/run-block.js.map +1 -1
  99. package/dist/core/polyphase/render/snapshot.d.ts +4 -0
  100. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  101. package/dist/core/polyphase/render/snapshot.js +4 -0
  102. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  103. package/dist/core/polyphase/result-text.d.ts.map +1 -1
  104. package/dist/core/polyphase/result-text.js +23 -3
  105. package/dist/core/polyphase/result-text.js.map +1 -1
  106. package/dist/core/polyphase/session.d.ts +15 -1
  107. package/dist/core/polyphase/session.d.ts.map +1 -1
  108. package/dist/core/polyphase/session.js +36 -1
  109. package/dist/core/polyphase/session.js.map +1 -1
  110. package/dist/core/polyphase/settings.d.ts +1 -0
  111. package/dist/core/polyphase/settings.d.ts.map +1 -1
  112. package/dist/core/polyphase/settings.js +1 -1
  113. package/dist/core/polyphase/settings.js.map +1 -1
  114. package/dist/core/polyphase/store.d.ts +18 -0
  115. package/dist/core/polyphase/store.d.ts.map +1 -1
  116. package/dist/core/polyphase/store.js +38 -0
  117. package/dist/core/polyphase/store.js.map +1 -1
  118. package/dist/core/polyphase/types.d.ts +60 -3
  119. package/dist/core/polyphase/types.d.ts.map +1 -1
  120. package/dist/core/polyphase/types.js.map +1 -1
  121. package/dist/core/polyphase/ui/inspector.js +1 -1
  122. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  123. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
  124. package/dist/core/polyphase/workflow/agent-host.js +17 -3
  125. package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
  126. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
  127. package/dist/core/polyphase/workflow/guidance.js +16 -5
  128. package/dist/core/polyphase/workflow/guidance.js.map +1 -1
  129. package/dist/core/polyphase/workflow/launch.d.ts +2 -1
  130. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
  131. package/dist/core/polyphase/workflow/launch.js +22 -3
  132. package/dist/core/polyphase/workflow/launch.js.map +1 -1
  133. package/dist/core/polyphase/workflow/limits.d.ts +80 -0
  134. package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
  135. package/dist/core/polyphase/workflow/limits.js +234 -0
  136. package/dist/core/polyphase/workflow/limits.js.map +1 -0
  137. package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
  138. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
  139. package/dist/core/polyphase/workflow/runtime.js.map +1 -1
  140. package/dist/core/polyphase/workflow/tool.d.ts +1 -0
  141. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
  142. package/dist/core/polyphase/workflow/tool.js +23 -2
  143. package/dist/core/polyphase/workflow/tool.js.map +1 -1
  144. package/dist/core/usage-totals.d.ts +5 -0
  145. package/dist/core/usage-totals.d.ts.map +1 -1
  146. package/dist/core/usage-totals.js +16 -0
  147. package/dist/core/usage-totals.js.map +1 -1
  148. package/dist/main.d.ts.map +1 -1
  149. package/dist/main.js +4 -0
  150. package/dist/main.js.map +1 -1
  151. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  152. package/dist/modes/interactive/interactive-mode.js +2 -0
  153. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  154. package/dist/utils/shell.d.ts.map +1 -1
  155. package/dist/utils/shell.js +3 -0
  156. package/dist/utils/shell.js.map +1 -1
  157. package/docs/duet.md +1 -1
  158. package/docs/environment-variables.md +3 -1
  159. package/docs/extensions.md +2 -1
  160. package/docs/keybindings.md +1 -0
  161. package/docs/polyphase.md +97 -33
  162. package/docs/settings.md +2 -2
  163. package/package.json +10 -10
  164. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  165. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
  166. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  167. package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
  168. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  169. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  170. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  171. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  172. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
  173. /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
@@ -0,0 +1,357 @@
1
+ /**
2
+ * The permission bridge: a polyphase child asks its parent session to decide a permission ask it
3
+ * cannot answer itself.
4
+ *
5
+ * A child runs `--mode json -p` and has no UI of its own, so before this every `approve` decision
6
+ * inside it ended as a block nobody had been asked about. The bridge carries the ask to the parent
7
+ * over the Node IPC channel `child-process.ts` opens next to the child's stdio (Bun implements the
8
+ * same channel, including for a compiled binary spawning itself). Only a child spawned with
9
+ * {@link POLYPHASE_PERMISSION_BRIDGE_ENV} set uses it, so a draht process some unrelated IPC parent
10
+ * forked never writes to that parent's channel.
11
+ *
12
+ * Child to parent: `ask` (one per gated tool call) and `withdraw` (the child's turn was aborted
13
+ * while it waited). Parent to child: `answer`. Neither side trusts the other's strings: every
14
+ * message is validated and bounded on arrival, the parent rebuilds the dialog from the raw
15
+ * arguments with its own neutralization, and the cwd a request is evaluated against comes from the
16
+ * parent's own spawn spec, never from the child.
17
+ */
18
+ import { randomUUID } from "node:crypto";
19
+ /** Set to `"1"` in a child's environment when its parent serves permission asks over IPC. */
20
+ export const POLYPHASE_PERMISSION_BRIDGE_ENV = "DRAHT_POLYPHASE_PERMISSION_BRIDGE";
21
+ const ASK_TYPE = "draht.permission.ask";
22
+ const WITHDRAW_TYPE = "draht.permission.withdraw";
23
+ const ANSWER_TYPE = "draht.permission.answer";
24
+ /**
25
+ * Argument keys the permission gate decides on. They cross verbatim and are never shortened: a
26
+ * cut `command` would let the parent approve a different call than the one the child runs.
27
+ */
28
+ const GATE_ARG_KEYS = new Set(["command", "path", "file_path"]);
29
+ const MAX_ID_CHARS = 128;
30
+ const MAX_NAME_CHARS = 256;
31
+ const MAX_INPUT_KEYS = 64;
32
+ const MAX_DISPLAY_VALUE_CHARS = 2048;
33
+ const MAX_INPUT_CHARS = 256 * 1024;
34
+ const MAX_VIA_LABELS = 8;
35
+ const MAX_REASON_CHARS = 4096;
36
+ /** Display-only key standing in for the arguments the key cap left out of a dialog. */
37
+ const OMITTED_ARGS_KEY = "(more arguments)";
38
+ function isRecord(value) {
39
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40
+ }
41
+ function isBoundedString(value, max) {
42
+ return typeof value === "string" && value.length > 0 && value.length <= max;
43
+ }
44
+ function isScalar(value) {
45
+ return (typeof value === "string" ||
46
+ typeof value === "boolean" ||
47
+ value === null ||
48
+ (typeof value === "number" && Number.isFinite(value)));
49
+ }
50
+ function boundDisplayValue(text) {
51
+ return text.length > MAX_DISPLAY_VALUE_CHARS ? `${text.slice(0, MAX_DISPLAY_VALUE_CHARS)}…` : text;
52
+ }
53
+ function serializeForDisplay(value) {
54
+ try {
55
+ return JSON.stringify(value) ?? String(value);
56
+ }
57
+ catch {
58
+ return String(value);
59
+ }
60
+ }
61
+ /**
62
+ * A tool call's arguments as they cross the bridge: the gate's own keys verbatim, every other value
63
+ * reduced to a bounded scalar that only feeds the dialog.
64
+ *
65
+ * The gate keys are taken FIRST and never give way to the key cap. Capping them in argument order
66
+ * let a call bury its `path` behind 64 junk keys (integer-like keys always enumerate first): the
67
+ * parent then judged a pathless `grep` (the project cwd) and approved, unasked, a read anywhere.
68
+ *
69
+ * A non-string gate value is ignored by the gate, so the parent's gate must not see it either; it
70
+ * crosses under a key the gate never reads, where the dialog still shows it. Serializing it into the
71
+ * gate key instead would hand the parent's gate a command or path the child's gate never judged.
72
+ */
73
+ export function toChildPermissionInput(input) {
74
+ const gate = [];
75
+ const display = [];
76
+ for (const [key, value] of Object.entries(input)) {
77
+ if (value === undefined)
78
+ continue;
79
+ if (GATE_ARG_KEYS.has(key)) {
80
+ if (typeof value === "string")
81
+ gate.push([key, value]);
82
+ else
83
+ display.push([`${key} (not a string)`, boundDisplayValue(serializeForDisplay(value))]);
84
+ continue;
85
+ }
86
+ if (key.length === 0 || key.length > MAX_NAME_CHARS)
87
+ continue;
88
+ if (typeof value === "string")
89
+ display.push([key, boundDisplayValue(value)]);
90
+ else if (isScalar(value))
91
+ display.push([key, value]);
92
+ else
93
+ display.push([key, boundDisplayValue(serializeForDisplay(value))]);
94
+ }
95
+ const room = MAX_INPUT_KEYS - gate.length;
96
+ const shown = display.length <= room
97
+ ? display
98
+ : [...display.slice(0, room - 1), [OMITTED_ARGS_KEY, `${display.length - room + 1} more not shown`]];
99
+ // `Object.fromEntries` defines own properties, so a `__proto__` key stays a plain key.
100
+ return Object.fromEntries([...gate, ...shown]);
101
+ }
102
+ function parseInput(value) {
103
+ if (!isRecord(value))
104
+ return undefined;
105
+ const entries = Object.entries(value);
106
+ if (entries.length > MAX_INPUT_KEYS)
107
+ return undefined;
108
+ const parsed = [];
109
+ let chars = 0;
110
+ for (const [key, entry] of entries) {
111
+ if (key.length === 0 || key.length > MAX_NAME_CHARS || !isScalar(entry))
112
+ return undefined;
113
+ chars += key.length + (typeof entry === "string" ? entry.length : 0);
114
+ if (chars > MAX_INPUT_CHARS)
115
+ return undefined;
116
+ parsed.push([key, entry]);
117
+ }
118
+ return Object.fromEntries(parsed);
119
+ }
120
+ function parseVia(value) {
121
+ if (!Array.isArray(value) || value.length > MAX_VIA_LABELS)
122
+ return undefined;
123
+ const labels = [];
124
+ for (const label of value) {
125
+ if (!isBoundedString(label, MAX_NAME_CHARS))
126
+ return undefined;
127
+ labels.push(label);
128
+ }
129
+ return labels;
130
+ }
131
+ export function parseAskMessage(value) {
132
+ if (!isRecord(value) || value.type !== ASK_TYPE || !isBoundedString(value.id, MAX_ID_CHARS))
133
+ return undefined;
134
+ const id = value.id;
135
+ const input = parseInput(value.input);
136
+ const via = parseVia(value.via);
137
+ if (!isBoundedString(value.toolName, MAX_NAME_CHARS) ||
138
+ !isBoundedString(value.toolCallId, MAX_NAME_CHARS) ||
139
+ input === undefined ||
140
+ via === undefined) {
141
+ return { ok: false, id };
142
+ }
143
+ return {
144
+ ok: true,
145
+ message: { type: ASK_TYPE, id, toolName: value.toolName, toolCallId: value.toolCallId, input, via },
146
+ };
147
+ }
148
+ export function parseWithdrawMessage(value) {
149
+ if (!isRecord(value) || value.type !== WITHDRAW_TYPE || !isBoundedString(value.id, MAX_ID_CHARS))
150
+ return undefined;
151
+ return { type: WITHDRAW_TYPE, id: value.id };
152
+ }
153
+ const VERDICT_KINDS = ["approved", "denied", "unavailable", "cancelled"];
154
+ function isVerdictKind(value) {
155
+ return typeof value === "string" && VERDICT_KINDS.includes(value);
156
+ }
157
+ /** The answer's verdict, or `undefined` when `value` is not a well-formed answer. */
158
+ export function parseAnswerMessage(value) {
159
+ if (!isRecord(value) || value.type !== ANSWER_TYPE || !isBoundedString(value.id, MAX_ID_CHARS))
160
+ return undefined;
161
+ if (!isVerdictKind(value.verdict))
162
+ return undefined;
163
+ if (value.verdict === "denied") {
164
+ const reason = isBoundedString(value.reason, MAX_REASON_CHARS) ? value.reason : "Denied in the parent session";
165
+ return { id: value.id, verdict: { kind: "denied", reason } };
166
+ }
167
+ return { id: value.id, verdict: { kind: value.verdict } };
168
+ }
169
+ function toAnswerMessage(id, verdict) {
170
+ const message = { type: ANSWER_TYPE, id, verdict: verdict.kind };
171
+ if (verdict.kind === "denied")
172
+ message.reason = verdict.reason.slice(0, MAX_REASON_CHARS);
173
+ return message;
174
+ }
175
+ export function createParentPermissionBridge(channel) {
176
+ const pending = new Map();
177
+ let unsubscribe;
178
+ const onMessage = (message) => {
179
+ const answer = parseAnswerMessage(message);
180
+ if (answer)
181
+ pending.get(answer.id)?.(answer.verdict);
182
+ };
183
+ const onDisconnect = () => {
184
+ for (const settle of [...pending.values()])
185
+ settle({ kind: "unavailable" });
186
+ };
187
+ return {
188
+ ask(request, signal) {
189
+ if (signal?.aborted)
190
+ return Promise.resolve({ kind: "cancelled" });
191
+ if (!channel.isConnected())
192
+ return Promise.resolve({ kind: "unavailable" });
193
+ const id = randomUUID();
194
+ return new Promise((resolve) => {
195
+ const settle = (verdict) => {
196
+ if (!pending.delete(id))
197
+ return;
198
+ signal?.removeEventListener("abort", onAbort);
199
+ // Subscribed, the channel keeps this process alive after its work is done, so it is
200
+ // held only while an ask is actually waiting.
201
+ if (pending.size === 0) {
202
+ unsubscribe?.();
203
+ unsubscribe = undefined;
204
+ }
205
+ resolve(verdict);
206
+ };
207
+ const onAbort = () => {
208
+ // Takes the parent's dialog down; the parent's late answer, if any, finds nothing to settle.
209
+ if (channel.isConnected()) {
210
+ try {
211
+ channel.send({ type: WITHDRAW_TYPE, id }, () => { });
212
+ }
213
+ catch { }
214
+ }
215
+ settle({ kind: "cancelled" });
216
+ };
217
+ pending.set(id, settle);
218
+ unsubscribe ??= channel.subscribe(onMessage, onDisconnect);
219
+ signal?.addEventListener("abort", onAbort, { once: true });
220
+ const message = {
221
+ type: ASK_TYPE,
222
+ id,
223
+ toolName: request.toolName,
224
+ toolCallId: request.toolCallId,
225
+ input: request.input,
226
+ via: [...request.via],
227
+ };
228
+ try {
229
+ channel.send(message, (error) => {
230
+ if (error)
231
+ settle({ kind: "unavailable" });
232
+ });
233
+ }
234
+ catch {
235
+ settle({ kind: "unavailable" });
236
+ }
237
+ });
238
+ },
239
+ };
240
+ }
241
+ function processParentChannel() {
242
+ if (typeof process.send !== "function")
243
+ return undefined;
244
+ return {
245
+ isConnected: () => process.connected === true,
246
+ send: (message, callback) => {
247
+ process.send?.(message, callback);
248
+ },
249
+ subscribe: (onMessage, onDisconnect) => {
250
+ process.on("message", onMessage);
251
+ process.on("disconnect", onDisconnect);
252
+ return () => {
253
+ process.off("message", onMessage);
254
+ process.off("disconnect", onDisconnect);
255
+ };
256
+ },
257
+ };
258
+ }
259
+ let processBridgeClaimed = false;
260
+ let processBridge;
261
+ /**
262
+ * Takes this process's bridge marker out of its environment and, when the marker was set and an
263
+ * IPC channel to the parent exists, connects the bridge. Idempotent. `main()` calls it before
264
+ * anything is spawned: like Node's own `NODE_CHANNEL_FD`, the marker is consumed, so no tool
265
+ * subprocess or extension child inherits a claim on an IPC channel it does not own (a vitest worker
266
+ * started from a bridged child would otherwise send its asks to vitest and wait forever).
267
+ */
268
+ export function claimParentPermissionBridge() {
269
+ if (processBridgeClaimed)
270
+ return;
271
+ processBridgeClaimed = true;
272
+ const requested = process.env[POLYPHASE_PERMISSION_BRIDGE_ENV] === "1";
273
+ delete process.env[POLYPHASE_PERMISSION_BRIDGE_ENV];
274
+ const channel = requested ? processParentChannel() : undefined;
275
+ processBridge = channel ? createParentPermissionBridge(channel) : undefined;
276
+ }
277
+ /**
278
+ * This process's bridge to the polyphase parent that spawned it, or `undefined` when there is
279
+ * none: not a bridged child, or no IPC channel to its parent.
280
+ */
281
+ export function getParentPermissionBridge() {
282
+ claimParentPermissionBridge();
283
+ return processBridge;
284
+ }
285
+ /** Answers one child's permission asks with `asker`, until the child exits and `dispose` is called. */
286
+ export function serveChildPermissionAsks(child, asker, options) {
287
+ const pending = new Map();
288
+ let disposed = false;
289
+ const reply = (id, verdict) => {
290
+ if (disposed || !child.connected)
291
+ return;
292
+ try {
293
+ child.send(toAnswerMessage(id, verdict), () => { });
294
+ }
295
+ catch {
296
+ // The child went away between the check and the send; it has nothing left to settle.
297
+ }
298
+ };
299
+ const onMessage = (message) => {
300
+ if (disposed)
301
+ return;
302
+ const withdraw = parseWithdrawMessage(message);
303
+ if (withdraw) {
304
+ pending.get(withdraw.id)?.abort();
305
+ return;
306
+ }
307
+ const parsed = parseAskMessage(message);
308
+ if (parsed === undefined)
309
+ return;
310
+ if (!parsed.ok) {
311
+ reply(parsed.id, { kind: "unavailable" });
312
+ return;
313
+ }
314
+ const ask = parsed.message;
315
+ if (pending.has(ask.id))
316
+ return;
317
+ const controller = new AbortController();
318
+ pending.set(ask.id, controller);
319
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
320
+ const request = {
321
+ toolName: ask.toolName,
322
+ toolCallId: ask.toolCallId,
323
+ input: ask.input,
324
+ via: ask.via,
325
+ cwd: options.cwd,
326
+ };
327
+ void (async () => {
328
+ let verdict;
329
+ try {
330
+ options.onAsk?.(request);
331
+ verdict = signal.aborted ? { kind: "cancelled" } : await asker(request, signal);
332
+ }
333
+ catch {
334
+ verdict = { kind: "unavailable" };
335
+ }
336
+ pending.delete(ask.id);
337
+ try {
338
+ options.onVerdict?.(request, verdict);
339
+ }
340
+ catch { }
341
+ reply(ask.id, verdict);
342
+ })();
343
+ };
344
+ child.on("message", onMessage);
345
+ return {
346
+ dispose() {
347
+ if (disposed)
348
+ return;
349
+ disposed = true;
350
+ child.off("message", onMessage);
351
+ for (const controller of pending.values())
352
+ controller.abort();
353
+ pending.clear();
354
+ },
355
+ };
356
+ }
357
+ //# sourceMappingURL=permission-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permission-bridge.js","sourceRoot":"","sources":["../../../src/core/polyphase/permission-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AASzC,6FAA6F;AAC7F,MAAM,CAAC,MAAM,+BAA+B,GAAG,mCAAmC,CAAC;AAEnF,MAAM,QAAQ,GAAG,sBAAsB,CAAC;AACxC,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C;;;GAGG;AACH,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAErF,MAAM,YAAY,GAAG,GAAG,CAAC;AACzB,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,cAAc,GAAG,EAAE,CAAC;AAC1B,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,eAAe,GAAG,GAAG,GAAG,IAAI,CAAC;AACnC,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAC9B,uFAAuF;AACvF,MAAM,gBAAgB,GAAG,kBAAkB,CAAC;AAuB5C,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,GAAW;IACnD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,CAAC;AAC7E,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,CACN,OAAO,KAAK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C;YAC9D,OAAO,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * The permission bridge: a polyphase child asks its parent session to decide a permission ask it\n * cannot answer itself.\n *\n * A child runs `--mode json -p` and has no UI of its own, so before this every `approve` decision\n * inside it ended as a block nobody had been asked about. The bridge carries the ask to the parent\n * over the Node IPC channel `child-process.ts` opens next to the child's stdio (Bun implements the\n * same channel, including for a compiled binary spawning itself). Only a child spawned with\n * {@link POLYPHASE_PERMISSION_BRIDGE_ENV} set uses it, so a draht process some unrelated IPC parent\n * forked never writes to that parent's channel.\n *\n * Child to parent: `ask` (one per gated tool call) and `withdraw` (the child's turn was aborted\n * while it waited). Parent to child: `answer`. Neither side trusts the other's strings: every\n * message is validated and bounded on arrival, the parent rebuilds the dialog from the raw\n * arguments with its own neutralization, and the cwd a request is evaluated against comes from the\n * parent's own spawn spec, never from the child.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type {\n\tChildPermissionAsker,\n\tChildPermissionInput,\n\tChildPermissionRequest,\n\tChildPermissionValue,\n\tChildPermissionVerdict,\n} from \"./types.ts\";\n\n/** Set to `\"1\"` in a child's environment when its parent serves permission asks over IPC. */\nexport const POLYPHASE_PERMISSION_BRIDGE_ENV = \"DRAHT_POLYPHASE_PERMISSION_BRIDGE\";\n\nconst ASK_TYPE = \"draht.permission.ask\";\nconst WITHDRAW_TYPE = \"draht.permission.withdraw\";\nconst ANSWER_TYPE = \"draht.permission.answer\";\n\n/**\n * Argument keys the permission gate decides on. They cross verbatim and are never shortened: a\n * cut `command` would let the parent approve a different call than the one the child runs.\n */\nconst GATE_ARG_KEYS: ReadonlySet<string> = new Set([\"command\", \"path\", \"file_path\"]);\n\nconst MAX_ID_CHARS = 128;\nconst MAX_NAME_CHARS = 256;\nconst MAX_INPUT_KEYS = 64;\nconst MAX_DISPLAY_VALUE_CHARS = 2048;\nconst MAX_INPUT_CHARS = 256 * 1024;\nconst MAX_VIA_LABELS = 8;\nconst MAX_REASON_CHARS = 4096;\n/** Display-only key standing in for the arguments the key cap left out of a dialog. */\nconst OMITTED_ARGS_KEY = \"(more arguments)\";\n\nexport interface PermissionAskMessage {\n\ttype: typeof ASK_TYPE;\n\tid: string;\n\ttoolName: string;\n\ttoolCallId: string;\n\tinput: ChildPermissionInput;\n\tvia: string[];\n}\n\nexport interface PermissionWithdrawMessage {\n\ttype: typeof WITHDRAW_TYPE;\n\tid: string;\n}\n\nexport interface PermissionAnswerMessage {\n\ttype: typeof ANSWER_TYPE;\n\tid: string;\n\tverdict: ChildPermissionVerdict[\"kind\"];\n\treason?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBoundedString(value: unknown, max: number): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= max;\n}\n\nfunction isScalar(value: unknown): value is ChildPermissionValue {\n\treturn (\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\" ||\n\t\tvalue === null ||\n\t\t(typeof value === \"number\" && Number.isFinite(value))\n\t);\n}\n\nfunction boundDisplayValue(text: string): string {\n\treturn text.length > MAX_DISPLAY_VALUE_CHARS ? `${text.slice(0, MAX_DISPLAY_VALUE_CHARS)}…` : text;\n}\n\nfunction serializeForDisplay(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? String(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\n/**\n * A tool call's arguments as they cross the bridge: the gate's own keys verbatim, every other value\n * reduced to a bounded scalar that only feeds the dialog.\n *\n * The gate keys are taken FIRST and never give way to the key cap. Capping them in argument order\n * let a call bury its `path` behind 64 junk keys (integer-like keys always enumerate first): the\n * parent then judged a pathless `grep` (the project cwd) and approved, unasked, a read anywhere.\n *\n * A non-string gate value is ignored by the gate, so the parent's gate must not see it either; it\n * crosses under a key the gate never reads, where the dialog still shows it. Serializing it into the\n * gate key instead would hand the parent's gate a command or path the child's gate never judged.\n */\nexport function toChildPermissionInput(input: Record<string, unknown>): ChildPermissionInput {\n\tconst gate: [string, ChildPermissionValue][] = [];\n\tconst display: [string, ChildPermissionValue][] = [];\n\tfor (const [key, value] of Object.entries(input)) {\n\t\tif (value === undefined) continue;\n\t\tif (GATE_ARG_KEYS.has(key)) {\n\t\t\tif (typeof value === \"string\") gate.push([key, value]);\n\t\t\telse display.push([`${key} (not a string)`, boundDisplayValue(serializeForDisplay(value))]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (key.length === 0 || key.length > MAX_NAME_CHARS) continue;\n\t\tif (typeof value === \"string\") display.push([key, boundDisplayValue(value)]);\n\t\telse if (isScalar(value)) display.push([key, value]);\n\t\telse display.push([key, boundDisplayValue(serializeForDisplay(value))]);\n\t}\n\tconst room = MAX_INPUT_KEYS - gate.length;\n\tconst shown =\n\t\tdisplay.length <= room\n\t\t\t? display\n\t\t\t: [...display.slice(0, room - 1), [OMITTED_ARGS_KEY, `${display.length - room + 1} more not shown`] as const];\n\t// `Object.fromEntries` defines own properties, so a `__proto__` key stays a plain key.\n\treturn Object.fromEntries([...gate, ...shown]);\n}\n\nfunction parseInput(value: unknown): ChildPermissionInput | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst entries = Object.entries(value);\n\tif (entries.length > MAX_INPUT_KEYS) return undefined;\n\tconst parsed: [string, ChildPermissionValue][] = [];\n\tlet chars = 0;\n\tfor (const [key, entry] of entries) {\n\t\tif (key.length === 0 || key.length > MAX_NAME_CHARS || !isScalar(entry)) return undefined;\n\t\tchars += key.length + (typeof entry === \"string\" ? entry.length : 0);\n\t\tif (chars > MAX_INPUT_CHARS) return undefined;\n\t\tparsed.push([key, entry]);\n\t}\n\treturn Object.fromEntries(parsed);\n}\n\nfunction parseVia(value: unknown): string[] | undefined {\n\tif (!Array.isArray(value) || value.length > MAX_VIA_LABELS) return undefined;\n\tconst labels: string[] = [];\n\tfor (const label of value) {\n\t\tif (!isBoundedString(label, MAX_NAME_CHARS)) return undefined;\n\t\tlabels.push(label);\n\t}\n\treturn labels;\n}\n\n/**\n * What arrived on a child's channel, when it claims to be an ask. An ask with a usable `id` but an\n * unusable body is still answered (`unavailable`), or the child's gate would wait for an answer\n * that never comes; one without a usable `id` cannot be answered at all and is dropped.\n */\nexport type ParsedAsk = { ok: true; message: PermissionAskMessage } | { ok: false; id: string };\n\nexport function parseAskMessage(value: unknown): ParsedAsk | undefined {\n\tif (!isRecord(value) || value.type !== ASK_TYPE || !isBoundedString(value.id, MAX_ID_CHARS)) return undefined;\n\tconst id = value.id;\n\tconst input = parseInput(value.input);\n\tconst via = parseVia(value.via);\n\tif (\n\t\t!isBoundedString(value.toolName, MAX_NAME_CHARS) ||\n\t\t!isBoundedString(value.toolCallId, MAX_NAME_CHARS) ||\n\t\tinput === undefined ||\n\t\tvia === undefined\n\t) {\n\t\treturn { ok: false, id };\n\t}\n\treturn {\n\t\tok: true,\n\t\tmessage: { type: ASK_TYPE, id, toolName: value.toolName, toolCallId: value.toolCallId, input, via },\n\t};\n}\n\nexport function parseWithdrawMessage(value: unknown): PermissionWithdrawMessage | undefined {\n\tif (!isRecord(value) || value.type !== WITHDRAW_TYPE || !isBoundedString(value.id, MAX_ID_CHARS)) return undefined;\n\treturn { type: WITHDRAW_TYPE, id: value.id };\n}\n\nconst VERDICT_KINDS: readonly ChildPermissionVerdict[\"kind\"][] = [\"approved\", \"denied\", \"unavailable\", \"cancelled\"];\n\nfunction isVerdictKind(value: unknown): value is ChildPermissionVerdict[\"kind\"] {\n\treturn typeof value === \"string\" && (VERDICT_KINDS as readonly string[]).includes(value);\n}\n\n/** The answer's verdict, or `undefined` when `value` is not a well-formed answer. */\nexport function parseAnswerMessage(value: unknown): { id: string; verdict: ChildPermissionVerdict } | undefined {\n\tif (!isRecord(value) || value.type !== ANSWER_TYPE || !isBoundedString(value.id, MAX_ID_CHARS)) return undefined;\n\tif (!isVerdictKind(value.verdict)) return undefined;\n\tif (value.verdict === \"denied\") {\n\t\tconst reason = isBoundedString(value.reason, MAX_REASON_CHARS) ? value.reason : \"Denied in the parent session\";\n\t\treturn { id: value.id, verdict: { kind: \"denied\", reason } };\n\t}\n\treturn { id: value.id, verdict: { kind: value.verdict } };\n}\n\nfunction toAnswerMessage(id: string, verdict: ChildPermissionVerdict): PermissionAnswerMessage {\n\tconst message: PermissionAnswerMessage = { type: ANSWER_TYPE, id, verdict: verdict.kind };\n\tif (verdict.kind === \"denied\") message.reason = verdict.reason.slice(0, MAX_REASON_CHARS);\n\treturn message;\n}\n\n// ── Child side ───────────────────────────────────────────────────────────────\n\n/** The child's end of the IPC channel: `process` in production, a fake in tests. */\nexport interface ParentChannel {\n\tisConnected(): boolean;\n\tsend(message: PermissionAskMessage | PermissionWithdrawMessage, callback: (error: Error | null) => void): void;\n\t/** Returns the unsubscribe. While subscribed, Node and Bun keep the process alive. */\n\tsubscribe(onMessage: (message: unknown) => void, onDisconnect: () => void): () => void;\n}\n\nexport interface ParentPermissionAsk {\n\ttoolName: string;\n\ttoolCallId: string;\n\tinput: ChildPermissionInput;\n\t/** Labels of the agents below this process the ask already passed through, outermost first. */\n\tvia: readonly string[];\n}\n\nexport interface ParentPermissionBridge {\n\t/** Have the parent decide one gated call. Never rejects. */\n\task(request: ParentPermissionAsk, signal?: AbortSignal): Promise<ChildPermissionVerdict>;\n}\n\nexport function createParentPermissionBridge(channel: ParentChannel): ParentPermissionBridge {\n\tconst pending = new Map<string, (verdict: ChildPermissionVerdict) => void>();\n\tlet unsubscribe: (() => void) | undefined;\n\n\tconst onMessage = (message: unknown) => {\n\t\tconst answer = parseAnswerMessage(message);\n\t\tif (answer) pending.get(answer.id)?.(answer.verdict);\n\t};\n\tconst onDisconnect = () => {\n\t\tfor (const settle of [...pending.values()]) settle({ kind: \"unavailable\" });\n\t};\n\n\treturn {\n\t\task(request, signal) {\n\t\t\tif (signal?.aborted) return Promise.resolve({ kind: \"cancelled\" });\n\t\t\tif (!channel.isConnected()) return Promise.resolve({ kind: \"unavailable\" });\n\t\t\tconst id = randomUUID();\n\t\t\treturn new Promise<ChildPermissionVerdict>((resolve) => {\n\t\t\t\tconst settle = (verdict: ChildPermissionVerdict) => {\n\t\t\t\t\tif (!pending.delete(id)) return;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t// Subscribed, the channel keeps this process alive after its work is done, so it is\n\t\t\t\t\t// held only while an ask is actually waiting.\n\t\t\t\t\tif (pending.size === 0) {\n\t\t\t\t\t\tunsubscribe?.();\n\t\t\t\t\t\tunsubscribe = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve(verdict);\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t// Takes the parent's dialog down; the parent's late answer, if any, finds nothing to settle.\n\t\t\t\t\tif (channel.isConnected()) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tchannel.send({ type: WITHDRAW_TYPE, id }, () => {});\n\t\t\t\t\t\t} catch {}\n\t\t\t\t\t}\n\t\t\t\t\tsettle({ kind: \"cancelled\" });\n\t\t\t\t};\n\t\t\t\tpending.set(id, settle);\n\t\t\t\tunsubscribe ??= channel.subscribe(onMessage, onDisconnect);\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tconst message: PermissionAskMessage = {\n\t\t\t\t\ttype: ASK_TYPE,\n\t\t\t\t\tid,\n\t\t\t\t\ttoolName: request.toolName,\n\t\t\t\t\ttoolCallId: request.toolCallId,\n\t\t\t\t\tinput: request.input,\n\t\t\t\t\tvia: [...request.via],\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tchannel.send(message, (error) => {\n\t\t\t\t\t\tif (error) settle({ kind: \"unavailable\" });\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\tsettle({ kind: \"unavailable\" });\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n\nfunction processParentChannel(): ParentChannel | undefined {\n\tif (typeof process.send !== \"function\") return undefined;\n\treturn {\n\t\tisConnected: () => process.connected === true,\n\t\tsend: (message, callback) => {\n\t\t\tprocess.send?.(message, callback);\n\t\t},\n\t\tsubscribe: (onMessage, onDisconnect) => {\n\t\t\tprocess.on(\"message\", onMessage);\n\t\t\tprocess.on(\"disconnect\", onDisconnect);\n\t\t\treturn () => {\n\t\t\t\tprocess.off(\"message\", onMessage);\n\t\t\t\tprocess.off(\"disconnect\", onDisconnect);\n\t\t\t};\n\t\t},\n\t};\n}\n\nlet processBridgeClaimed = false;\nlet processBridge: ParentPermissionBridge | undefined;\n\n/**\n * Takes this process's bridge marker out of its environment and, when the marker was set and an\n * IPC channel to the parent exists, connects the bridge. Idempotent. `main()` calls it before\n * anything is spawned: like Node's own `NODE_CHANNEL_FD`, the marker is consumed, so no tool\n * subprocess or extension child inherits a claim on an IPC channel it does not own (a vitest worker\n * started from a bridged child would otherwise send its asks to vitest and wait forever).\n */\nexport function claimParentPermissionBridge(): void {\n\tif (processBridgeClaimed) return;\n\tprocessBridgeClaimed = true;\n\tconst requested = process.env[POLYPHASE_PERMISSION_BRIDGE_ENV] === \"1\";\n\tdelete process.env[POLYPHASE_PERMISSION_BRIDGE_ENV];\n\tconst channel = requested ? processParentChannel() : undefined;\n\tprocessBridge = channel ? createParentPermissionBridge(channel) : undefined;\n}\n\n/**\n * This process's bridge to the polyphase parent that spawned it, or `undefined` when there is\n * none: not a bridged child, or no IPC channel to its parent.\n */\nexport function getParentPermissionBridge(): ParentPermissionBridge | undefined {\n\tclaimParentPermissionBridge();\n\treturn processBridge;\n}\n\n// ── Parent side ──────────────────────────────────────────────────────────────\n\n/** The parent's end of one child's IPC channel. `ChildProcess` satisfies it. */\nexport interface ChildChannel {\n\treadonly connected: boolean;\n\tsend(message: PermissionAnswerMessage, callback: (error: Error | null) => void): boolean;\n\ton(event: \"message\", listener: (message: unknown) => void): unknown;\n\toff(event: \"message\", listener: (message: unknown) => void): unknown;\n}\n\nexport interface ServeChildPermissionAsksOptions {\n\t/** Where the child was spawned: what every request from it is evaluated against. */\n\tcwd: string;\n\t/** Aborts every pending ask, e.g. the agent's own cancellation. */\n\tsignal?: AbortSignal;\n\tonAsk?: (request: ChildPermissionRequest) => void;\n\tonVerdict?: (request: ChildPermissionRequest, verdict: ChildPermissionVerdict) => void;\n}\n\nexport interface ChildPermissionServer {\n\t/** Stop listening and abort every pending ask. Idempotent. */\n\tdispose(): void;\n}\n\n/** Answers one child's permission asks with `asker`, until the child exits and `dispose` is called. */\nexport function serveChildPermissionAsks(\n\tchild: ChildChannel,\n\tasker: ChildPermissionAsker,\n\toptions: ServeChildPermissionAsksOptions,\n): ChildPermissionServer {\n\tconst pending = new Map<string, AbortController>();\n\tlet disposed = false;\n\n\tconst reply = (id: string, verdict: ChildPermissionVerdict) => {\n\t\tif (disposed || !child.connected) return;\n\t\ttry {\n\t\t\tchild.send(toAnswerMessage(id, verdict), () => {});\n\t\t} catch {\n\t\t\t// The child went away between the check and the send; it has nothing left to settle.\n\t\t}\n\t};\n\n\tconst onMessage = (message: unknown) => {\n\t\tif (disposed) return;\n\t\tconst withdraw = parseWithdrawMessage(message);\n\t\tif (withdraw) {\n\t\t\tpending.get(withdraw.id)?.abort();\n\t\t\treturn;\n\t\t}\n\t\tconst parsed = parseAskMessage(message);\n\t\tif (parsed === undefined) return;\n\t\tif (!parsed.ok) {\n\t\t\treply(parsed.id, { kind: \"unavailable\" });\n\t\t\treturn;\n\t\t}\n\t\tconst ask = parsed.message;\n\t\tif (pending.has(ask.id)) return;\n\t\tconst controller = new AbortController();\n\t\tpending.set(ask.id, controller);\n\t\tconst signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n\t\tconst request: ChildPermissionRequest = {\n\t\t\ttoolName: ask.toolName,\n\t\t\ttoolCallId: ask.toolCallId,\n\t\t\tinput: ask.input,\n\t\t\tvia: ask.via,\n\t\t\tcwd: options.cwd,\n\t\t};\n\t\tvoid (async () => {\n\t\t\tlet verdict: ChildPermissionVerdict;\n\t\t\ttry {\n\t\t\t\toptions.onAsk?.(request);\n\t\t\t\tverdict = signal.aborted ? { kind: \"cancelled\" } : await asker(request, signal);\n\t\t\t} catch {\n\t\t\t\tverdict = { kind: \"unavailable\" };\n\t\t\t}\n\t\t\tpending.delete(ask.id);\n\t\t\ttry {\n\t\t\t\toptions.onVerdict?.(request, verdict);\n\t\t\t} catch {}\n\t\t\treply(ask.id, verdict);\n\t\t})();\n\t};\n\n\tchild.on(\"message\", onMessage);\n\treturn {\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tchild.off(\"message\", onMessage);\n\t\t\tfor (const controller of pending.values()) controller.abort();\n\t\t\tpending.clear();\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"run-block.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/render/run-block.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,SAAS,EAAgB,MAAM,YAAY,CAAC;AAE1D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAiBvE,OAAO,KAAK,EAAmC,WAAW,EAAE,MAAM,eAAe,CAAC;AAElF,MAAM,WAAW,gBAAgB;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,iFAAiF;IACjF,KAAK,EAAE,OAAO,CAAC;IACf,0FAA0F;IAC1F,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACZ;AAiHD;;;;+FAI+F;AAC/F,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD;AA2CD;;8DAE8D;AAC9D,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,WAAW,GAAG,WAAW,CAWnE;AAurBD;4DAC4D;AAC5D,wBAAgB,SAAS,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,MAA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,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,gBAAgB,GAAG,MAAM,EAAE,CAYjH;AAMD;0FAC0F;AAC1F,qBAAa,iBAAkB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAA0B;IAC1C,OAAO,CAAC,KAAK,CAAoB;IACjC,OAAO,CAAC,OAAO,CAA+B;IAC9C,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,WAAW,CAAgB;IAEnC,MAAM,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAI3E;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAY9B;IAED,UAAU,IAAI,IAAI,CAEjB;CACD"}
@@ -9,6 +9,7 @@ import { keyHint, keyText } from "../../../modes/interactive/components/keybindi
9
9
  import { stripAnsi } from "../../../utils/ansi.js";
10
10
  import { sanitizeBinaryOutput } from "../../../utils/shell.js";
11
11
  import { normalizeDisplayText, replaceTabs } from "../../tools/render-utils.js";
12
+ import { formatLimitDuration } from "../workflow/limits.js";
12
13
  import { columns, fitLine, formatCost, formatDuration, formatModelLabel, formatTokens, oneLine, spinnerFrame, statusGlyph, } from "./format.js";
13
14
  const COUNT_ORDER = ["running", "done", "failed", "cancelled", "queued", "pending", "skipped"];
14
15
  const STATUS_WORDS = {
@@ -106,12 +107,17 @@ function cancelledByText(agents) {
106
107
  const byUser = cancelled.length > 0 && cancelled.every((a) => a.cancelReason === "user" || a.cancelReason === undefined);
107
108
  return byUser ? "cancelled by you" : "cancelled";
108
109
  }
109
- /** A single agent's cancel wording: `cancelled by you` for the user, else `cancelled by <reason>`
110
- * (budget/run/parent/shutdown), matching §11.4's mockup wording for the user case. */
110
+ /** A single agent's cancel wording: `cancelled by you` for the user, `cancelled (time limit)` for
111
+ * the workflow time limit (D-B), else `cancelled by <reason>` (budget/run/parent/shutdown),
112
+ * matching §11.4's mockup wording for the user case. */
111
113
  function cancelReasonText(reason) {
112
114
  if (!reason)
113
115
  return "cancelled";
114
- return reason === "user" ? "cancelled by you" : `cancelled by ${reason}`;
116
+ if (reason === "user")
117
+ return "cancelled by you";
118
+ if (reason === "time")
119
+ return "cancelled (time limit)";
120
+ return `cancelled by ${reason}`;
115
121
  }
116
122
  /** Child-sourced text (output, error, status/now lines, task, tool summaries, labels, log lines,
117
123
  * result previews) may carry ANSI/OSC sequences, raw tabs or a trailing CR. Stripped and normalized
@@ -178,7 +184,7 @@ export function sanitizeSnapshot(snapshot) {
178
184
  /** The fixed §11.4 mockup wording: a blocked tool's real gate reason (child-events.ts keeps it in
179
185
  * full, `NO_UI_APPROVAL_SUFFIX` included) is never shown on the tool row, only in the inspector's
180
186
  * expanded detail, so a long or sensitive rule description can never widen or leak onto this line. */
181
- const BLOCKED_TOOL_TEXT = "blocked: needs approval (subagents cannot ask)";
187
+ const BLOCKED_TOOL_TEXT = "blocked: needs approval, nobody could be asked";
182
188
  /** The run's true agent count, including any dropped before this snapshot was built (a degraded
183
189
  * archived/final `details` with `agentsOmitted` set). `snapshot.counts` already covers every agent
184
190
  * (it is copied from `details.totals.byStatus`), so only `agents.length` on its own undercounts. */
@@ -571,6 +577,9 @@ function workflowFinalSummaryLeft(snapshot, theme) {
571
577
  if (snapshot.budget?.exhausted) {
572
578
  return `${theme.fg("warning", "⚠")} budget of ${formatTokens(snapshot.budget.totalTokens)} tokens reached · ${cancelled} agent${cancelled === 1 ? "" : "s"} cancelled${note}`;
573
579
  }
580
+ if (snapshot.timeLimit?.reached) {
581
+ return `${theme.fg("warning", "⚠")} time limit of ${formatLimitDuration(snapshot.timeLimit.totalMs)} reached · ${cancelled} agent${cancelled === 1 ? "" : "s"} cancelled${note}`;
582
+ }
574
583
  if (snapshot.status === "cancelled") {
575
584
  return `${statusGlyph("cancelled", theme, { now: 0, animate: false })} ${cancelledByText(snapshot.agents)} after ${total} agent${total === 1 ? "" : "s"}${note}`;
576
585
  }