@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
@@ -12,23 +12,26 @@
12
12
  import { randomUUID } from "node:crypto";
13
13
  import * as fs from "node:fs";
14
14
  import * as path from "node:path";
15
+ import { getKeybindings, isKeyRelease, isKeyRepeat } from "@draht/tui";
15
16
  import { Type } from "@sinclair/typebox";
16
17
  import { CONFIG_DIR_NAME, getAgentDir, getPackageDir } from "../../config.js";
17
18
  import { comparablePath, realPathStrict } from "../../utils/canonical-path.js";
18
19
  import { parseFrontmatter } from "../../utils/frontmatter.js";
19
- import { AgentFSM, isPermissionMode, loadRules, MailboxSystem, PERMISSION_MODES, PermissionGate, parseRules, TaskBoard, WorktreeIsolator, } from "../multi-agent/index.js";
20
+ import { AgentFSM, DEFAULT_SESSION_PERMISSION_MODE, isPermissionMode, loadRules, MailboxSystem, PERMISSION_MODES, PermissionGate, parseRules, stricterPermissionMode, TaskBoard, WorktreeIsolator, } from "../multi-agent/index.js";
20
21
  import { describeToolCallForApproval } from "../polyphase/approval.js";
21
22
  import { createProcessAgentRunner } from "../polyphase/child-process.js";
22
23
  import { buildDetails, sumRunUsage } from "../polyphase/details.js";
23
24
  import { createPartialUpdateEmitter } from "../polyphase/emitter.js";
24
25
  import { LimiterAbortedError } from "../polyphase/limiter.js";
25
26
  import { resolveChildModel } from "../polyphase/model-selection.js";
27
+ import { getParentPermissionBridge, toChildPermissionInput, } from "../polyphase/permission-bridge.js";
26
28
  import { createSubagentRenderers } from "../polyphase/render/renderers.js";
27
29
  import { capHeadTail, formatSubagentResultText } from "../polyphase/result-text.js";
28
- import { disposePolyphaseSession, getPolyphaseSession, peekPolyphaseSession } from "../polyphase/session.js";
30
+ import { disposePolyphaseSession, getPolyphaseSession, peekPolyphaseSession, } from "../polyphase/session.js";
29
31
  import { resolvePolyphaseSettings } from "../polyphase/settings.js";
30
32
  import { currentPolyphaseDepth, NO_UI_APPROVAL_SUFFIX, THINKING_LEVELS, WORKFLOW_TOOL_NAME, } from "../polyphase/types.js";
31
33
  import { boundedSafeText } from "../socket-server/safe-text.js";
34
+ import { resolveToCwd } from "../tools/path-utils.js";
32
35
  const MAX_PARALLEL = 8;
33
36
  const MAX_CONCURRENCY = 4;
34
37
  // ─── Multi-agent coordination primitives ───────────────────────────────────
@@ -39,6 +42,47 @@ const MAX_CONCURRENCY = 4;
39
42
  // parallel-mode assignments, and worktree isolation is opt-in per call.
40
43
  /** Mailbox address subagent runs deliver their `TaskResult`/`Abort` message to by default. */
41
44
  export const SUBAGENT_RESULT_MAILBOX = "subagent-results";
45
+ /** Env var a child reads its permission mode from at startup (loaded once, before any gate). */
46
+ export const PERMISSION_MODE_ENV = "DRAHT_PERMISSION_MODE";
47
+ /**
48
+ * Env for a spawned child: the session's permission mode AT SPAWN TIME, always set (so a stale
49
+ * `DRAHT_PERMISSION_MODE` in the parent's own process env can never silently escalate a child
50
+ * beyond what the parent session currently uses). Every subagent/workflow/duet child goes through
51
+ * this so `/permissions`/`/yolo` changes in the parent reach children spawned afterwards —
52
+ * changing the mode later does not affect a child already running.
53
+ *
54
+ * Returns a thunk rather than reading the mode immediately: callers build `AgentRunContext.env`
55
+ * before a limiter slot is free (`perItem`, runs ahead of `limiter.acquire`), so reading eagerly
56
+ * here would freeze a queued agent's mode at queue time instead of its actual spawn time.
57
+ * `child-process.ts`'s `buildChildInvocation` calls it only once the child is about to spawn.
58
+ */
59
+ export function permissionEnv(session) {
60
+ return () => ({ [PERMISSION_MODE_ENV]: session.permissionMode() });
61
+ }
62
+ /**
63
+ * Where `app.permissions.cycle` switches to. It alternates `auto` and `ask` and never enters
64
+ * `yolo`, so no single key press drops every approval; that takes `/yolo`. From `yolo` it goes back
65
+ * to `auto`.
66
+ */
67
+ const NEXT_PERMISSION_MODE = {
68
+ auto: "ask",
69
+ ask: "auto",
70
+ yolo: "auto",
71
+ };
72
+ /**
73
+ * The mode `DRAHT_PERMISSION_MODE` starts a session in. Unset or blank means
74
+ * `DEFAULT_SESSION_PERMISSION_MODE`; a mode name counts whatever its case or surrounding
75
+ * whitespace; anything else means `ask`, the strictest. Someone who set the variable at all
76
+ * most likely meant to opt out of auto, so a typo must not quietly opt them back in.
77
+ */
78
+ export function seedPermissionMode(value) {
79
+ const normalized = value?.trim().toLowerCase() ?? "";
80
+ if (normalized === "")
81
+ return { mode: DEFAULT_SESSION_PERMISSION_MODE };
82
+ if (isPermissionMode(normalized))
83
+ return { mode: normalized };
84
+ return { mode: "ask", unrecognized: value };
85
+ }
42
86
  const mailboxSystem = new MailboxSystem();
43
87
  const taskBoard = new TaskBoard();
44
88
  const worktreeIsolator = new WorktreeIsolator();
@@ -468,25 +512,24 @@ function safeField(raw, verdict) {
468
512
  * `buildRequestFrame` hand-builds that wire frame and has no field for it (see
469
513
  * `PermissionAskDetail.summary`'s doc).
470
514
  */
471
- function buildPermissionAskDetail(event, ctx, reason, description) {
472
- const input = (event.input ?? {});
515
+ function buildPermissionAskDetail(call, cwd, reason, extras = {}) {
516
+ const { description } = extras;
517
+ const input = (call.input ?? {});
473
518
  const verdict = { truncated: false };
474
519
  const detail = {
475
520
  kind: "tool_permission",
476
- toolCallId: safeField(event.toolCallId, verdict),
477
- toolName: safeField(event.toolName, verdict),
521
+ toolCallId: safeField(call.toolCallId, verdict),
522
+ toolName: safeField(call.toolName, verdict),
478
523
  // `ctx.cwd` is the raw, un-normalised `config.cwd`; a symlinked worktree would otherwise
479
524
  // read as a different project on the answering surface.
480
- cwd: safeField(comparablePath(ctx.cwd), verdict),
525
+ cwd: safeField(comparablePath(cwd), verdict),
481
526
  reason: safeField(reason, verdict),
482
527
  options: TOOL_PERMISSION_OPTIONS,
483
528
  truncated: false,
484
529
  };
485
- if (description !== undefined) {
486
- detail.summary = description.message
487
- .split("\n")
488
- .slice(0, MAX_SUMMARY_LINES)
489
- .map((line) => safeField(line, verdict));
530
+ const summary = description?.message.split("\n") ?? extras.summary;
531
+ if (summary !== undefined) {
532
+ detail.summary = summary.slice(0, MAX_SUMMARY_LINES).map((line) => safeField(line, verdict));
490
533
  }
491
534
  if (description?.operation !== undefined) {
492
535
  detail.operation = safeField(description.operation, verdict);
@@ -542,53 +585,158 @@ export function loadPermissionRules(projectDir, projectTrusted, globalDir) {
542
585
  */
543
586
  export function createPermissionGateToolCallHandler(gate, options) {
544
587
  return async (event, ctx) => {
545
- const decision = gate.evaluate(event.toolName, event.input);
588
+ const input = event.input;
589
+ const decision = gate.evaluate(event.toolName, input);
546
590
  if (decision.action === "deny") {
547
591
  return { block: true, reason: decision.reason };
548
592
  }
549
593
  if (decision.action === "approve") {
550
- // No answering surface at all: keep today's loud, operator-facing block verbatim rather
551
- // than letting a no-op UI resolve `false` and be recorded as a user's denial.
552
594
  if (!ctx.hasUI) {
553
- return { block: true, reason: `${decision.reason} ${NO_UI_APPROVAL_SUFFIX}` };
554
- }
555
- const description = options?.describe?.(event, ctx);
556
- // Called right before the prompt, so an open inspector closes and the parent dialog
557
- // stays reachable.
558
- options?.beforePrompt?.(ctx);
559
- const detail = buildPermissionAskDetail(event, ctx, decision.reason, description);
560
- const title = description?.title ?? "Approve tool call?";
561
- const message = description
562
- ? `${description.message}\n\n${decision.reason}`
563
- : `${event.toolName}: ${decision.reason}`;
564
- // Both positional strings are unchanged so every existing renderer keeps working; the
565
- // canonical facts ride alongside them for surfaces that can render structure.
566
- //
567
- // `signal` is the turn's OWN abort signal, read live off the context (it is the active
568
- // run's controller, minted fresh per run, so it is never a stale aborted one). A
569
- // permission ask that inherits "wait forever" with no way to be dismissed is its own
570
- // hazard: this ask parks the agent loop inside `beforeToolCall`, and before this the
571
- // only things that could end it were a human answering and the relay's own backstop
572
- // clock. Aborting the turn now takes the dialog down on every surface, and — because
573
- // nobody answered — it is recorded as `cancelled` by the system rather than as this
574
- // human's refusal.
575
- const approved = await ctx.ui.confirm(title, message, { detail, signal: ctx.signal });
576
- if (!approved) {
577
- // The turn being aborted is NOT a refusal, and saying so in the transcript would put the
578
- // same fabrication in front of the model that the durable record was just cleared of:
579
- // the JSONL reads `cancelled` by `system`, so the reason the model sees must not read
580
- // `User denied approval`. This branch became reachable the moment `signal` started being
581
- // passed above — before that, an abort could not end an ask at all.
582
- if (ctx.signal?.aborted) {
583
- return { block: true, reason: "the turn was aborted before this call was approved" };
595
+ // No surface of its own. A polyphase child hands the ask to the session that spawned it;
596
+ // only when nobody can be asked does the call get today's loud, operator-facing block,
597
+ // rather than a no-op UI resolving `false` and being recorded as a user's denial.
598
+ const verdict = await options?.parentBridge?.ask({
599
+ toolName: event.toolName,
600
+ toolCallId: event.toolCallId,
601
+ input: toChildPermissionInput(input),
602
+ via: [],
603
+ }, ctx.signal);
604
+ switch (verdict?.kind) {
605
+ case "approved":
606
+ return undefined;
607
+ case "denied":
608
+ return { block: true, reason: verdict.reason };
609
+ case "cancelled":
610
+ return { block: true, reason: "the turn was aborted before this call was approved" };
611
+ default:
612
+ return { block: true, reason: `${decision.reason} ${NO_UI_APPROVAL_SUFFIX}` };
584
613
  }
585
- return { block: true, reason: "User denied approval" };
586
614
  }
587
- return undefined;
615
+ const prompt = () => promptForApproval(event, ctx, decision.reason, options);
616
+ return options?.runPrompt ? options.runPrompt(prompt) : prompt();
588
617
  }
589
618
  return undefined;
590
619
  };
591
620
  }
621
+ /** The `approve` dialog of `createPermissionGateToolCallHandler`, for a process with a UI. */
622
+ async function promptForApproval(event, ctx, reason, options) {
623
+ // Queued behind another dialog, the turn may have ended before this one's turn came.
624
+ if (ctx.signal?.aborted) {
625
+ return { block: true, reason: "the turn was aborted before this call was approved" };
626
+ }
627
+ const description = options?.describe?.(event, ctx);
628
+ // Called right before the prompt, so an open inspector closes and the parent dialog
629
+ // stays reachable.
630
+ options?.beforePrompt?.(ctx);
631
+ const detail = buildPermissionAskDetail(event, ctx.cwd, reason, { description });
632
+ const title = description?.title ?? "Approve tool call?";
633
+ const message = description ? `${description.message}\n\n${reason}` : `${event.toolName}: ${reason}`;
634
+ // Both positional strings are unchanged so every existing renderer keeps working; the
635
+ // canonical facts ride alongside them for surfaces that can render structure.
636
+ //
637
+ // `signal` is the turn's OWN abort signal, read live off the context (it is the active
638
+ // run's controller, minted fresh per run, so it is never a stale aborted one). A
639
+ // permission ask that inherits "wait forever" with no way to be dismissed is its own
640
+ // hazard: this ask parks the agent loop inside `beforeToolCall`, and before this the
641
+ // only things that could end it were a human answering and the relay's own backstop
642
+ // clock. Aborting the turn now takes the dialog down on every surface, and — because
643
+ // nobody answered — it is recorded as `cancelled` by the system rather than as this
644
+ // human's refusal.
645
+ const approved = await ctx.ui.confirm(title, message, { detail, signal: ctx.signal });
646
+ if (!approved) {
647
+ // The turn being aborted is NOT a refusal, and saying so in the transcript would put the
648
+ // same fabrication in front of the model that the durable record was just cleared of:
649
+ // the JSONL reads `cancelled` by `system`, so the reason the model sees must not read
650
+ // `User denied approval`. This branch became reachable the moment `signal` started being
651
+ // passed above — before that, an abort could not end an ask at all.
652
+ if (ctx.signal?.aborted) {
653
+ return { block: true, reason: "the turn was aborted before this call was approved" };
654
+ }
655
+ return { block: true, reason: "User denied approval" };
656
+ }
657
+ return undefined;
658
+ }
659
+ // ─── Permission asks from children ──────────────────────────────────────────
660
+ /** Tools whose missing `path` means the cwd (READ_ONLY_PATH_TOOLS in permission-gate.ts). */
661
+ const CWD_DEFAULT_PATH_TOOLS = new Set(["grep", "find", "ls"]);
662
+ /**
663
+ * A child's request as it goes one level further up: paths resolved, the way the tools resolve them
664
+ * (`~`, a leading `@`, `file://`), against the cwd this process spawned the child in, because the
665
+ * parent above evaluates them against its own direct child's cwd, where a relative path names a
666
+ * different file. A read-only tool's missing path means "the child's cwd", so it is spelled out for
667
+ * the same reason.
668
+ */
669
+ function forwardableInput(request) {
670
+ const entries = Object.entries(request.input).map(([key, value]) => (key === "path" || key === "file_path") && typeof value === "string"
671
+ ? [key, resolveToCwd(value, request.cwd)]
672
+ : [key, value]);
673
+ const hasPath = entries.some(([key, value]) => (key === "path" || key === "file_path") && typeof value === "string");
674
+ if (!hasPath && CWD_DEFAULT_PATH_TOOLS.has(request.toolName.toLowerCase()))
675
+ entries.push(["path", request.cwd]);
676
+ return Object.fromEntries(entries);
677
+ }
678
+ /**
679
+ * Decides a permission ask a child could not decide itself, in THIS session. First under the
680
+ * session's current rules and mode, so a `/permissions auto` or `/yolo` typed after the child
681
+ * started still covers what it asks. Then, if a human is still needed, with this session's own
682
+ * dialog: one at a time, so asks from parallel agents queue instead of displacing each other into
683
+ * silent denials. Without a UI the ask goes one level further up; when nobody can be asked the
684
+ * verdict is `unavailable` and the child blocks the call exactly as it did before.
685
+ */
686
+ export function createChildPermissionAsker(ctx, session, options) {
687
+ return async (request, signal) => {
688
+ try {
689
+ const gate = new PermissionGate(loadPermissionRules(ctx.cwd, ctx.isProjectTrusted()), {
690
+ cwd: request.cwd,
691
+ mode: session.permissionMode(),
692
+ });
693
+ const decision = gate.evaluate(request.toolName, request.input);
694
+ if (decision.action === "deny")
695
+ return { kind: "denied", reason: decision.reason };
696
+ if (decision.action === "allow")
697
+ return { kind: "approved" };
698
+ const via = [options.agentLabel, ...request.via];
699
+ if (!ctx.hasUI) {
700
+ if (!options.upstream)
701
+ return { kind: "unavailable" };
702
+ return await options.upstream.ask({ toolName: request.toolName, toolCallId: request.toolCallId, input: forwardableInput(request), via }, signal);
703
+ }
704
+ return await session.runPermissionPrompt(async () => {
705
+ if (signal.aborted)
706
+ return { kind: "cancelled" };
707
+ session.notifyParentPrompt();
708
+ const requester = via.join(" › ");
709
+ // The id names the agent too: the call is not in this session's transcript, and a bare
710
+ // child id (`call-1`) would collide with this session's own in a durable permission record.
711
+ const call = { ...request, toolCallId: `${via.join("/")}/${request.toolCallId}` };
712
+ const detail = buildPermissionAskDetail(call, request.cwd, decision.reason, {
713
+ summary: [`Requested by subagent ${requester}`],
714
+ });
715
+ const approved = await ctx.ui.confirm(`Approve ${request.toolName} for subagent ${requester}?`, `${requester} wants to run ${request.toolName}: ${decision.reason}`, { detail, signal });
716
+ if (signal.aborted)
717
+ return { kind: "cancelled" };
718
+ return approved
719
+ ? { kind: "approved" }
720
+ : { kind: "denied", reason: "Denied by the user in the parent session" };
721
+ }, signal);
722
+ }
723
+ catch {
724
+ // A context gone stale (session replaced or reloaded) or an unreadable permissions.yml:
725
+ // nobody can answer, so the child blocks the call as it always did.
726
+ return { kind: "unavailable" };
727
+ }
728
+ };
729
+ }
730
+ /**
731
+ * What a spawned child takes from this session's permissions: the mode it starts in, and who
732
+ * answers the asks its own gate cannot.
733
+ */
734
+ export function childPermissionContext(ctx, session, agentLabel) {
735
+ return {
736
+ env: permissionEnv(session),
737
+ onPermissionAsk: createChildPermissionAsker(ctx, session, { agentLabel, upstream: getParentPermissionBridge() }),
738
+ };
739
+ }
592
740
  // ─── Extension ──────────────────────────────────────────────────────────────
593
741
  const ThinkingParam = Type.Union(THINKING_LEVELS.map((level) => Type.Literal(level)), {
594
742
  description: "Thinking level for this agent",
@@ -677,6 +825,11 @@ export function describeMergeFailure(result) {
677
825
  /** `createSubagentExtension(options?)`; the default export is `createSubagentExtension()` (§10.5). */
678
826
  export function createSubagentExtension(options = {}) {
679
827
  const runnerOverride = options.runner;
828
+ // The mode last chosen with /permissions, /yolo or `app.permissions.cycle`. A runtime rebuild
829
+ // (/new, /resume, /fork, /reload) runs the factory below again, and seeding from the environment
830
+ // alone would turn a chosen `ask` back into auto. Only applied where it asks more than the seed,
831
+ // so it never relaxes a session.
832
+ let chosenPermissionMode;
680
833
  return (pi) => {
681
834
  // Autocomplete gets no ctx, so the last trust answer a ctx gave for this cwd stands in; unseen cwds count as untrusted.
682
835
  let lastProjectTrust;
@@ -685,6 +838,7 @@ export function createSubagentExtension(options = {}) {
685
838
  };
686
839
  const rememberedProjectTrust = (cwd) => lastProjectTrust?.cwd === cwd ? lastProjectTrust.trusted : false;
687
840
  let currentSession;
841
+ let unsubscribeModeKey;
688
842
  const renderDeps = {
689
843
  getStore: () => currentSession?.store,
690
844
  viewportRows: () => process.stdout.rows || 24,
@@ -808,6 +962,7 @@ export function createSubagentExtension(options = {}) {
808
962
  modelInfo: choices[i].info,
809
963
  fallbackToChildDefaultModel: choices[i].info.source === "inherited",
810
964
  excludeTools: exclude,
965
+ ...childPermissionContext(ctx, session, live[i].label),
811
966
  }),
812
967
  });
813
968
  const results = await runChainTasks(ctx.cwd, steps.map((s) => ({ agent: s.agent, task: s.task })), { signal, worktree, runner: runnerOverride, limiter: session.limiter, perItem });
@@ -919,6 +1074,7 @@ export function createSubagentExtension(options = {}) {
919
1074
  modelInfo: choices[i].info,
920
1075
  fallbackToChildDefaultModel: choices[i].info.source === "inherited",
921
1076
  excludeTools: exclude,
1077
+ ...childPermissionContext(ctx, session, live[i].label),
922
1078
  }),
923
1079
  });
924
1080
  const results = await runParallelTasks(ctx.cwd, items.map((item) => ({ agent: item.agent, task: item.task })), {
@@ -1017,6 +1173,7 @@ export function createSubagentExtension(options = {}) {
1017
1173
  modelInfo: choice.info,
1018
1174
  fallbackToChildDefaultModel: choice.info.source === "inherited",
1019
1175
  excludeTools: exclude,
1176
+ ...childPermissionContext(ctx, session, live.label),
1020
1177
  });
1021
1178
  const result = await runSingleTask(ctx.cwd, agent, params.task, {
1022
1179
  signal: live.signal,
@@ -1079,18 +1236,30 @@ export function createSubagentExtension(options = {}) {
1079
1236
  // only for a trusted project — and per-session cwd changes take effect
1080
1237
  // without an extension reload.
1081
1238
  //
1082
- // The session permission mode (default/auto/yolo) is session-scoped state,
1083
- // settable via /permissions and /yolo below and seeded from
1084
- // DRAHT_PERMISSION_MODE. It relaxes prompting, never `deny` rules.
1085
- let permissionMode = isPermissionMode(process.env.DRAHT_PERMISSION_MODE)
1086
- ? process.env.DRAHT_PERMISSION_MODE
1087
- : "default";
1239
+ // The session permission mode (ask/auto/yolo) is session-scoped state,
1240
+ // settable via /permissions, /yolo and `app.permissions.cycle` below and
1241
+ // seeded from DRAHT_PERMISSION_MODE (see `seedPermissionMode`). It relaxes
1242
+ // prompting, never `deny` rules.
1243
+ const seededPermissionMode = seedPermissionMode(process.env[PERMISSION_MODE_ENV]);
1244
+ let permissionMode = chosenPermissionMode === undefined
1245
+ ? seededPermissionMode.mode
1246
+ : stricterPermissionMode(seededPermissionMode.mode, chosenPermissionMode);
1247
+ // Where `/yolo` switches back to: the last mode other than yolo.
1248
+ let modeBeforeYolo = permissionMode === "yolo" ? DEFAULT_SESSION_PERMISSION_MODE : permissionMode;
1249
+ // Only a mode other than the one sessions start in gets a footer entry.
1088
1250
  function updatePermissionStatus(ctx) {
1089
- ctx.ui.setStatus("permissions", permissionMode === "default" ? undefined : `perms: ${permissionMode}`);
1251
+ ctx.ui.setStatus("permissions", permissionMode === DEFAULT_SESSION_PERMISSION_MODE ? undefined : `perms: ${permissionMode}`);
1252
+ }
1253
+ function setPermissionMode(mode, ctx) {
1254
+ permissionMode = mode;
1255
+ chosenPermissionMode = mode;
1256
+ if (mode !== "yolo")
1257
+ modeBeforeYolo = mode;
1258
+ updatePermissionStatus(ctx);
1090
1259
  }
1091
1260
  const MODE_DESCRIPTIONS = {
1092
- default: "rules as authored; unmatched bash commands require approval",
1093
- auto: "auto-approve bash unless the command looks dangerous (deny rules still block)",
1261
+ ask: "rules as authored; unmatched bash commands require approval",
1262
+ auto: "auto-approve bash unless the command looks dangerous, and start workflows and duet batches without asking (deny rules still block)",
1094
1263
  yolo: "no approval prompts this session (deny rules still block)",
1095
1264
  };
1096
1265
  pi.on("tool_call", (event, ctx) => {
@@ -1112,7 +1281,9 @@ export function createSubagentExtension(options = {}) {
1112
1281
  concurrency: limits.maxConcurrency,
1113
1282
  maxAgents: limits.maxAgentsPerRun,
1114
1283
  budgetTokens: limits.defaultBudgetTokens,
1284
+ timeLimitMs: limits.workflowTimeoutMs > 0 ? limits.workflowTimeoutMs : null,
1115
1285
  },
1286
+ promptDirectives: peekPolyphaseSession(c.sessionManager)?.pendingDirectives(),
1116
1287
  });
1117
1288
  }
1118
1289
  catch {
@@ -1120,6 +1291,11 @@ export function createSubagentExtension(options = {}) {
1120
1291
  }
1121
1292
  },
1122
1293
  beforePrompt: (c) => peekPolyphaseSession(c.sessionManager)?.notifyParentPrompt(),
1294
+ parentBridge: getParentPermissionBridge(),
1295
+ runPrompt: (prompt) => {
1296
+ const session = peekPolyphaseSession(ctx.sessionManager);
1297
+ return session ? session.runPermissionPrompt(prompt, ctx.signal) : prompt();
1298
+ },
1123
1299
  })(event, ctx);
1124
1300
  });
1125
1301
  // /permissions command — show or set the session permission mode
@@ -1135,8 +1311,7 @@ export function createSubagentExtension(options = {}) {
1135
1311
  ctx.ui.notify(`Unknown mode "${requested}". Available: ${PERMISSION_MODES.join(", ")}`, "warning");
1136
1312
  return;
1137
1313
  }
1138
- permissionMode = requested;
1139
- updatePermissionStatus(ctx);
1314
+ setPermissionMode(requested, ctx);
1140
1315
  ctx.ui.notify(`Permission mode: ${permissionMode} — ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
1141
1316
  },
1142
1317
  });
@@ -1144,11 +1319,10 @@ export function createSubagentExtension(options = {}) {
1144
1319
  pi.registerCommand("yolo", {
1145
1320
  description: "Toggle yolo permission mode for this session (skip approval prompts; deny rules still block)",
1146
1321
  handler: async (_args, ctx) => {
1147
- permissionMode = permissionMode === "yolo" ? "default" : "yolo";
1148
- updatePermissionStatus(ctx);
1322
+ setPermissionMode(permissionMode === "yolo" ? modeBeforeYolo : "yolo", ctx);
1149
1323
  ctx.ui.notify(permissionMode === "yolo"
1150
1324
  ? "yolo mode ON — no approval prompts this session (deny rules still block)"
1151
- : "yolo mode OFF — back to default permissions", "info");
1325
+ : `yolo mode OFF — back to ${permissionMode} mode: ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
1152
1326
  },
1153
1327
  });
1154
1328
  // ── Agent selection for user prompts ─────────────────────────────────────
@@ -1222,12 +1396,34 @@ export function createSubagentExtension(options = {}) {
1222
1396
  return { action: "transform", text: wrapped, images: event.images };
1223
1397
  });
1224
1398
  pi.on("session_start", (_event, ctx) => {
1399
+ // A mode seeded from DRAHT_PERMISSION_MODE is shown before any command changes it.
1400
+ updatePermissionStatus(ctx);
1401
+ if (seededPermissionMode.unrecognized !== undefined) {
1402
+ ctx.ui.notify(`${PERMISSION_MODE_ENV}=${JSON.stringify(seededPermissionMode.unrecognized)} names no permission mode (${PERMISSION_MODES.join(", ")}); starting in ask`, "warning");
1403
+ }
1404
+ unsubscribeModeKey?.();
1405
+ unsubscribeModeKey = undefined;
1406
+ if (ctx.mode === "tui" && ctx.hasUI) {
1407
+ unsubscribeModeKey = ctx.ui.onTerminalInput((data) => {
1408
+ if (!getKeybindings().matches(data, "app.permissions.cycle"))
1409
+ return undefined;
1410
+ // A terminal reporting key releases (kitty protocol) or repeats sends the key again; one
1411
+ // press switches once.
1412
+ if (isKeyRelease(data) || isKeyRepeat(data))
1413
+ return { consume: true };
1414
+ setPermissionMode(NEXT_PERMISSION_MODE[permissionMode], ctx);
1415
+ ctx.ui.notify(`Permission mode: ${permissionMode} — ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
1416
+ return { consume: true };
1417
+ });
1418
+ }
1225
1419
  if (!ctx.sessionManager)
1226
1420
  return;
1227
1421
  currentSession = getPolyphaseSession(ctx.sessionManager, pi.getSettings().polyphase);
1228
1422
  currentSession.setPermissionModeProvider(() => permissionMode);
1229
1423
  });
1230
1424
  pi.on("session_shutdown", (_event, ctx) => {
1425
+ unsubscribeModeKey?.();
1426
+ unsubscribeModeKey = undefined;
1231
1427
  disposePolyphaseSession(ctx.sessionManager, "shutdown");
1232
1428
  currentSession = undefined;
1233
1429
  });