@draht/coding-agent 2026.10.16-1 → 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 (133) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/{chunk-BOGY4QVF.js → chunk-3DQNSI5W.js} +4 -4
  4. package/dist/bundle/chunks/{chunk-VQOV5VFH.js → chunk-4COXSQRQ.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-6QIFWMDF.js → chunk-CQF6U56X.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-GD2WVXWT.js → chunk-I2SOJ4JN.js} +3 -3
  7. package/dist/bundle/chunks/{chunk-KJJJSTND.js → chunk-QPCP4VHF.js} +103 -91
  8. package/dist/bundle/chunks/{chunk-AHGUOQPH.js → chunk-X3YFUSCK.js} +1 -1
  9. package/dist/bundle/chunks/{cli-O6OWCY7N.js → cli-VCHSHNKT.js} +1 -1
  10. package/dist/bundle/chunks/{execute-4JU5WQXP.js → execute-AGEWJLIO.js} +1 -1
  11. package/dist/bundle/chunks/{runtime-FIGQHW75.js → runtime-2B56SZM6.js} +1 -1
  12. package/dist/bundle/chunks/{virtual-modules-UIGTRGHQ.js → virtual-modules-XT4MP2GI.js} +1 -1
  13. package/dist/bundle/cli-runtime.js +1 -1
  14. package/dist/bundle/index.js +1 -1
  15. package/dist/bundle/rpc-entry.js +1 -1
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +4 -0
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/builtins/duet.d.ts +7 -1
  20. package/dist/core/builtins/duet.d.ts.map +1 -1
  21. package/dist/core/builtins/duet.js +83 -14
  22. package/dist/core/builtins/duet.js.map +1 -1
  23. package/dist/core/builtins/polyphase.d.ts.map +1 -1
  24. package/dist/core/builtins/polyphase.js +21 -2
  25. package/dist/core/builtins/polyphase.js.map +1 -1
  26. package/dist/core/builtins/subagent.d.ts +59 -2
  27. package/dist/core/builtins/subagent.d.ts.map +1 -1
  28. package/dist/core/builtins/subagent.js +258 -62
  29. package/dist/core/builtins/subagent.js.map +1 -1
  30. package/dist/core/extensions/loader.d.ts.map +1 -1
  31. package/dist/core/extensions/loader.js +23 -0
  32. package/dist/core/extensions/loader.js.map +1 -1
  33. package/dist/core/extensions/runner.d.ts.map +1 -1
  34. package/dist/core/extensions/runner.js +2 -0
  35. package/dist/core/extensions/runner.js.map +1 -1
  36. package/dist/core/extensions/types.d.ts +12 -0
  37. package/dist/core/extensions/types.d.ts.map +1 -1
  38. package/dist/core/extensions/types.js.map +1 -1
  39. package/dist/core/keybindings.d.ts +5 -0
  40. package/dist/core/keybindings.d.ts.map +1 -1
  41. package/dist/core/keybindings.js +4 -0
  42. package/dist/core/keybindings.js.map +1 -1
  43. package/dist/core/multi-agent/permission-gate.d.ts +18 -6
  44. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  45. package/dist/core/multi-agent/permission-gate.js +867 -59
  46. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  47. package/dist/core/polyphase/approval.d.ts +6 -2
  48. package/dist/core/polyphase/approval.d.ts.map +1 -1
  49. package/dist/core/polyphase/approval.js +23 -35
  50. package/dist/core/polyphase/approval.js.map +1 -1
  51. package/dist/core/polyphase/child-events.js +1 -1
  52. package/dist/core/polyphase/child-events.js.map +1 -1
  53. package/dist/core/polyphase/child-process.d.ts.map +1 -1
  54. package/dist/core/polyphase/child-process.js +65 -7
  55. package/dist/core/polyphase/child-process.js.map +1 -1
  56. package/dist/core/polyphase/commands.d.ts.map +1 -1
  57. package/dist/core/polyphase/commands.js +46 -5
  58. package/dist/core/polyphase/commands.js.map +1 -1
  59. package/dist/core/polyphase/details.d.ts.map +1 -1
  60. package/dist/core/polyphase/details.js +5 -0
  61. package/dist/core/polyphase/details.js.map +1 -1
  62. package/dist/core/polyphase/permission-bridge.d.ts +128 -0
  63. package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
  64. package/dist/core/polyphase/permission-bridge.js +357 -0
  65. package/dist/core/polyphase/permission-bridge.js.map +1 -0
  66. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  67. package/dist/core/polyphase/render/run-block.js +13 -4
  68. package/dist/core/polyphase/render/run-block.js.map +1 -1
  69. package/dist/core/polyphase/render/snapshot.d.ts +4 -0
  70. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  71. package/dist/core/polyphase/render/snapshot.js +4 -0
  72. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  73. package/dist/core/polyphase/result-text.d.ts.map +1 -1
  74. package/dist/core/polyphase/result-text.js +23 -3
  75. package/dist/core/polyphase/result-text.js.map +1 -1
  76. package/dist/core/polyphase/session.d.ts +15 -1
  77. package/dist/core/polyphase/session.d.ts.map +1 -1
  78. package/dist/core/polyphase/session.js +36 -1
  79. package/dist/core/polyphase/session.js.map +1 -1
  80. package/dist/core/polyphase/settings.d.ts +1 -0
  81. package/dist/core/polyphase/settings.d.ts.map +1 -1
  82. package/dist/core/polyphase/settings.js +1 -1
  83. package/dist/core/polyphase/settings.js.map +1 -1
  84. package/dist/core/polyphase/store.d.ts +18 -0
  85. package/dist/core/polyphase/store.d.ts.map +1 -1
  86. package/dist/core/polyphase/store.js +38 -0
  87. package/dist/core/polyphase/store.js.map +1 -1
  88. package/dist/core/polyphase/types.d.ts +60 -3
  89. package/dist/core/polyphase/types.d.ts.map +1 -1
  90. package/dist/core/polyphase/types.js.map +1 -1
  91. package/dist/core/polyphase/ui/inspector.js +1 -1
  92. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  93. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
  94. package/dist/core/polyphase/workflow/agent-host.js +17 -3
  95. package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
  96. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
  97. package/dist/core/polyphase/workflow/guidance.js +16 -5
  98. package/dist/core/polyphase/workflow/guidance.js.map +1 -1
  99. package/dist/core/polyphase/workflow/launch.d.ts +2 -1
  100. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
  101. package/dist/core/polyphase/workflow/launch.js +22 -3
  102. package/dist/core/polyphase/workflow/launch.js.map +1 -1
  103. package/dist/core/polyphase/workflow/limits.d.ts +80 -0
  104. package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
  105. package/dist/core/polyphase/workflow/limits.js +234 -0
  106. package/dist/core/polyphase/workflow/limits.js.map +1 -0
  107. package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
  108. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
  109. package/dist/core/polyphase/workflow/runtime.js.map +1 -1
  110. package/dist/core/polyphase/workflow/tool.d.ts +1 -0
  111. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
  112. package/dist/core/polyphase/workflow/tool.js +23 -2
  113. package/dist/core/polyphase/workflow/tool.js.map +1 -1
  114. package/dist/core/usage-totals.d.ts +5 -0
  115. package/dist/core/usage-totals.d.ts.map +1 -1
  116. package/dist/core/usage-totals.js +16 -0
  117. package/dist/core/usage-totals.js.map +1 -1
  118. package/dist/main.d.ts.map +1 -1
  119. package/dist/main.js +4 -0
  120. package/dist/main.js.map +1 -1
  121. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  122. package/dist/modes/interactive/interactive-mode.js +2 -0
  123. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  124. package/dist/utils/shell.d.ts.map +1 -1
  125. package/dist/utils/shell.js +3 -0
  126. package/dist/utils/shell.js.map +1 -1
  127. package/docs/duet.md +1 -1
  128. package/docs/environment-variables.md +3 -1
  129. package/docs/extensions.md +2 -1
  130. package/docs/keybindings.md +1 -0
  131. package/docs/polyphase.md +97 -33
  132. package/docs/settings.md +2 -2
  133. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"child-process.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/child-process.ts"],"names":[],"mappings":"AAAA;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AU,CAAC;IACxB,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,gFAAgF;IAChF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CAC5B;AAED,uGAAuG;AACvG,wBAAgB,oBAAoB,CACnC,IAAI,EAAE,cAAc,EACpB,KAAK,EAAE;IAAE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,EACzD,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAA;CAAE,CAuC5C;AAgND;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAStE;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,iBAAiB,EAC1B,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,EACnC,IAAI,EAAE,MAAM,GACV,QAAQ,CAKV;AA0BD,4GAA4G;AAC5G,wBAAgB,wBAAwB,CACvC,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,UAAU,EAClB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,KAAK,IAAI,GAC5C,IAAI,CAkBN;AAsED,iFAAiF;AACjF,wBAAsB,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,CAiC5E;AAED,wBAAgB,wBAAwB,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,WAAW,CAG5E"}
@@ -13,12 +13,14 @@ import { isBunBinary } from "../../config.js";
13
13
  import { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from "../../utils/shell.js";
14
14
  import { ChildEventReducer, parseChildLine, summarizeToolArgs, toRunResult, } from "./child-events.js";
15
15
  import { attachChildLineReader } from "./jsonl-reader.js";
16
+ import { POLYPHASE_PERMISSION_BRIDGE_ENV, serveChildPermissionAsks, } from "./permission-bridge.js";
16
17
  import { currentPolyphaseDepth, DUET_DELEGATE_TOOL_NAME, POLYPHASE_DEPTH_ENV, POLYPHASE_RESULT_TOOL_NAME, POLYPHASE_SCHEMA_FILE_ENV, WORKFLOW_TOOL_NAME, } from "./types.js";
17
18
  const DEFAULT_KILL_GRACE_MS = 5000;
18
19
  const LEGACY_TOOL_SUMMARY_MAX_CHARS = 60;
19
20
  const LEGACY_TEXT_PROGRESS_MAX_CHARS = 80;
20
21
  const INSPECT_OR_DEBUG_FLAG = /^--(?:inspect|debug)/;
21
22
  const STRUCTURED_OUTPUT_NOTICE_MAX_CHARS = 200;
23
+ const PERMISSION_NOTICE_MAX_CHARS = 200;
22
24
  /**
23
25
  * Bun binary: `{execPath, []}`. Otherwise `{execPath, [...execArgv without --inspect*
24
26
  * and --debug*, argv[1]]}`, which keeps tsx (and other loader-based dev runs) working in children.
@@ -50,7 +52,8 @@ export function buildChildInvocation(spec, files, options) {
50
52
  if (files.systemPromptFile)
51
53
  args.push("--append-system-prompt", files.systemPromptFile);
52
54
  const baseEnv = spec.baseEnv ?? process.env;
53
- const env = { ...baseEnv, ...(run?.env ?? {}) };
55
+ const resolvedRunEnv = typeof run?.env === "function" ? run.env() : run?.env;
56
+ const env = { ...baseEnv, ...(resolvedRunEnv ?? {}) };
54
57
  env[POLYPHASE_DEPTH_ENV] = String(currentPolyphaseDepth(baseEnv) + 1);
55
58
  if (files.schemaFile) {
56
59
  env[POLYPHASE_SCHEMA_FILE_ENV] = files.schemaFile;
@@ -58,8 +61,51 @@ export function buildChildInvocation(spec, files, options) {
58
61
  else {
59
62
  delete env[POLYPHASE_SCHEMA_FILE_ENV];
60
63
  }
64
+ // Set only for a child whose asks this process will answer. A copy inherited from our own bridged
65
+ // parent must not reach a child we do not serve: it would write asks to a channel nobody reads.
66
+ if (run?.onPermissionAsk) {
67
+ env[POLYPHASE_PERMISSION_BRIDGE_ENV] = "1";
68
+ }
69
+ else {
70
+ delete env[POLYPHASE_PERMISSION_BRIDGE_ENV];
71
+ }
61
72
  return { args, env };
62
73
  }
74
+ function hasPipedStdio(proc) {
75
+ return proc.stdin !== null && proc.stdout !== null && proc.stderr !== null;
76
+ }
77
+ /** Spawns with piped stdio, plus the IPC channel the permission bridge runs over when `ipc` is set. */
78
+ function spawnChild(command, args, options) {
79
+ const proc = spawn(command.bin, [...command.argsPrefix, ...args], {
80
+ cwd: options.cwd,
81
+ env: options.env,
82
+ shell: false,
83
+ stdio: options.ipc ? ["pipe", "pipe", "pipe", "ipc"] : ["pipe", "pipe", "pipe"],
84
+ });
85
+ if (!hasPipedStdio(proc)) {
86
+ proc.kill("SIGKILL");
87
+ throw new Error("child process started without piped stdio");
88
+ }
89
+ return proc;
90
+ }
91
+ /** The transcript line an agent's run shows for one of its permission asks, or none. */
92
+ function permissionNotice(request, verdict) {
93
+ const summary = summarizeToolArgs(request.toolName, request.input);
94
+ const call = summary ? `${request.toolName} ${summary}` : request.toolName;
95
+ const line = (text) => truncateProgress(text, PERMISSION_NOTICE_MAX_CHARS);
96
+ if (verdict === undefined)
97
+ return { level: "info", text: line(`approval requested: ${call}`) };
98
+ switch (verdict.kind) {
99
+ case "approved":
100
+ return { level: "info", text: line(`approved: ${call}`) };
101
+ case "denied":
102
+ return { level: "warning", text: line(`denied: ${call} (${verdict.reason})`) };
103
+ case "unavailable":
104
+ case "cancelled":
105
+ // The child itself reports what became of the call: a blocked tool, or an aborted turn.
106
+ return undefined;
107
+ }
108
+ }
63
109
  function truncateProgress(text, max) {
64
110
  return text.length > max ? `${text.slice(0, max)}...` : text;
65
111
  }
@@ -89,17 +135,21 @@ function legacyProgressText(record, pendingFirstDelta) {
89
135
  function spawnAttempt(spec, command, reducer, files, options) {
90
136
  const killGraceMs = spec.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
91
137
  const { args, env } = buildChildInvocation(spec, files, options);
138
+ const asker = spec.run?.onPermissionAsk;
92
139
  return new Promise((resolve) => {
93
140
  let settled = false;
94
141
  let closed = false;
95
142
  let killTimer;
96
143
  let proc;
144
+ let permissionServer;
97
145
  const finishOnce = (exit) => {
98
146
  if (settled)
99
147
  return;
100
148
  settled = true;
101
149
  if (killTimer)
102
150
  clearTimeout(killTimer);
151
+ // Takes down any dialog still open for this child: nobody is left to receive the answer.
152
+ permissionServer?.dispose();
103
153
  if (spec.signal)
104
154
  spec.signal.removeEventListener("abort", onAbort);
105
155
  resolve({ exit, finish: reducer.finish(exit) });
@@ -118,12 +168,7 @@ function spawnAttempt(spec, command, reducer, files, options) {
118
168
  killTimer.unref();
119
169
  }
120
170
  try {
121
- proc = spawn(command.bin, [...command.argsPrefix, ...args], {
122
- cwd: spec.cwd,
123
- env,
124
- shell: false,
125
- stdio: ["pipe", "pipe", "pipe"],
126
- });
171
+ proc = spawnChild(command, args, { cwd: spec.cwd, env, ipc: asker !== undefined });
127
172
  }
128
173
  catch (error) {
129
174
  finishOnce({
@@ -151,6 +196,19 @@ function spawnAttempt(spec, command, reducer, files, options) {
151
196
  if (change !== "none")
152
197
  spec.run?.onChange?.(change);
153
198
  };
199
+ const notePermission = (request, verdict) => {
200
+ const notice = permissionNotice(request, verdict);
201
+ if (notice && !settled)
202
+ forward(recordReducerNotice(reducer, notice.level, notice.text));
203
+ };
204
+ if (asker) {
205
+ permissionServer = serveChildPermissionAsks(proc, asker, {
206
+ cwd: spec.cwd,
207
+ signal: spec.signal,
208
+ onAsk: (request) => notePermission(request),
209
+ onVerdict: (request, verdict) => notePermission(request, verdict),
210
+ });
211
+ }
154
212
  const pendingFirstDelta = new Set();
155
213
  attachChildLineReader(proc.stdout, (line) => {
156
214
  const record = parseChildLine(line);
@@ -1 +1 @@
1
- {"version":3,"file":"child-process.js","sourceRoot":"","sources":["../../../src/core/polyphase/child-process.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAuC,K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,IAAI,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,EAAE,CAAC,CAAC;IACvG,CAAC;YAAS,CAAC;QACV,IAAI,OAAO,EAAE,CAAC;YACb,IAAI,CAAC;gBACJ,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACtD,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACX,CAAC;IACF,CAAC;AACF,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,OAAsB;IAC9D,OAAO,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,EAAE,CAC1D,aAAa,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * Spawns and supervises one child draht process for a subagent/workflow run (§7.1-7.4).\n *\n * `buildChildInvocation` and `resolveDrahtCommand` are pure; `runChildAgent` owns every\n * side effect (temp files, spawn, line reading, abort escalation) and never rejects.\n */\n\nimport { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { JsonObject, JsonValue } from \"@draht/ai\";\nimport { validateToolArguments } from \"@draht/ai\";\nimport type { TSchema } from \"typebox\";\nimport { isBunBinary } from \"../../config.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\nimport {\n\tChildEventReducer,\n\ttype ChildExit,\n\ttype ChildFinish,\n\ttype ChildWireRecord,\n\tparseChildLine,\n\tsummarizeToolArgs,\n\ttoRunResult,\n} from \"./child-events.ts\";\nimport { attachChildLineReader } from \"./jsonl-reader.ts\";\nimport {\n\ttype AgentConfig,\n\ttype AgentRunContext,\n\ttype AgentRunner,\n\tcurrentPolyphaseDepth,\n\tDUET_DELEGATE_TOOL_NAME,\n\tPOLYPHASE_DEPTH_ENV,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\tPOLYPHASE_SCHEMA_FILE_ENV,\n\ttype ProgressFn,\n\ttype RunResult,\n\ttype TranscriptItem,\n\tWORKFLOW_TOOL_NAME,\n} from \"./types.ts\";\n\nconst DEFAULT_KILL_GRACE_MS = 5000;\nconst LEGACY_TOOL_SUMMARY_MAX_CHARS = 60;\nconst LEGACY_TEXT_PROGRESS_MAX_CHARS = 80;\nconst INSPECT_OR_DEBUG_FLAG = /^--(?:inspect|debug)/;\nconst STRUCTURED_OUTPUT_NOTICE_MAX_CHARS = 200;\n\nexport interface ChildCommand {\n\tbin: string;\n\targsPrefix: readonly string[];\n}\n\n/**\n * Bun binary: `{execPath, []}`. Otherwise `{execPath, [...execArgv without --inspect*\n * and --debug*, argv[1]]}`, which keeps tsx (and other loader-based dev runs) working in children.\n */\nexport function resolveDrahtCommand(): ChildCommand {\n\tif (isBunBinary) return { bin: process.execPath, argsPrefix: [] };\n\tconst execArgv = process.execArgv.filter((arg) => !INSPECT_OR_DEBUG_FLAG.test(arg));\n\treturn { bin: process.execPath, argsPrefix: [...execArgv, process.argv[1]] };\n}\n\nexport interface ChildSpawnSpec {\n\tcwd: string;\n\tagent: AgentConfig;\n\ttask: string;\n\tstep?: number;\n\trun?: AgentRunContext;\n\tsignal?: AbortSignal;\n\tonProgress?: ProgressFn;\n\tcommand?: ChildCommand;\n\t/** Grace period between SIGTERM and SIGKILL-via-tree on abort. Default 5000. */\n\tkillGraceMs?: number;\n\tbaseEnv?: NodeJS.ProcessEnv;\n}\n\n/** Pure: computes argv and env for one spawn. `files` are temp paths already written by the caller. */\nexport function buildChildInvocation(\n\tspec: ChildSpawnSpec,\n\tfiles: { systemPromptFile?: string; schemaFile?: string },\n\toptions?: { omitModel?: boolean },\n): { args: string[]; env: NodeJS.ProcessEnv } {\n\tconst { agent, run } = spec;\n\tconst omitModel = options?.omitModel ?? false;\n\tconst args: string[] = [\"--mode\", \"json\", \"-p\", \"--no-session\"];\n\n\tconst model = run?.model ?? agent.model;\n\tif (!omitModel && model) args.push(\"--model\", model);\n\tif (!omitModel && run?.thinking) args.push(\"--thinking\", run.thinking);\n\n\tif (agent.tools?.length) {\n\t\tconst tools = [...agent.tools, ...(run?.extraTools ?? [])];\n\t\targs.push(\"--tools\", tools.join(\",\"));\n\t}\n\n\tif (agent.disableExtensions) args.push(\"--no-extensions\");\n\n\tconst excludeTools = [WORKFLOW_TOOL_NAME, DUET_DELEGATE_TOOL_NAME, ...(run?.excludeTools ?? [])];\n\targs.push(\"--exclude-tools\", [...new Set(excludeTools)].join(\",\"));\n\n\tif (files.systemPromptFile) args.push(\"--append-system-prompt\", files.systemPromptFile);\n\n\tconst baseEnv = spec.baseEnv ?? process.env;\n\tconst env: NodeJS.ProcessEnv = { ...baseEnv, ...(run?.env ?? {}) };\n\tenv[POLYPHASE_DEPTH_ENV] = String(currentPolyphaseDepth(baseEnv) + 1);\n\tif (files.schemaFile) {\n\t\tenv[POLYPHASE_SCHEMA_FILE_ENV] = files.schemaFile;\n\t} else {\n\t\tdelete env[POLYPHASE_SCHEMA_FILE_ENV];\n\t}\n\n\treturn { args, env };\n}\n\nfunction truncateProgress(text: string, max: number): string {\n\treturn text.length > max ? `${text.slice(0, max)}...` : text;\n}\n\n/**\n * Legacy `onProgress` strings duet relies on: a short line on every tool start, and one line for\n * the first delta of each new text item (a cheap \"what is it writing\" signal, not a transcript).\n */\nfunction legacyProgressText(record: ChildWireRecord, pendingFirstDelta: Set<number>): string | undefined {\n\tif (record.type === \"tool_execution_start\") {\n\t\tconst summary = truncateProgress(\n\t\t\tsummarizeToolArgs(record.toolName, record.args as JsonValue | undefined),\n\t\t\tLEGACY_TOOL_SUMMARY_MAX_CHARS,\n\t\t);\n\t\treturn summary ? `${record.toolName} ${summary}` : record.toolName;\n\t}\n\tif (record.type === \"message_update\") {\n\t\tconst event = record.assistantMessageEvent;\n\t\tif (event.type === \"text_start\") {\n\t\t\tpendingFirstDelta.add(event.contentIndex);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (event.type === \"text_delta\" && pendingFirstDelta.delete(event.contentIndex)) {\n\t\t\tconst firstLine = event.delta.split(\"\\n\")[0] ?? \"\";\n\t\t\treturn truncateProgress(firstLine, LEGACY_TEXT_PROGRESS_MAX_CHARS);\n\t\t}\n\t}\n\treturn undefined;\n}\n\ninterface SpawnAttemptResult {\n\texit: ChildExit;\n\tfinish: ChildFinish;\n}\n\n/** One spawn: wires the line reader, stderr tail, abort escalation, and resolves via `reducer.finish`. */\nfunction spawnAttempt(\n\tspec: ChildSpawnSpec,\n\tcommand: ChildCommand,\n\treducer: ChildEventReducer,\n\tfiles: { systemPromptFile?: string; schemaFile?: string },\n\toptions: { omitModel?: boolean },\n): Promise<SpawnAttemptResult> {\n\tconst killGraceMs = spec.killGraceMs ?? DEFAULT_KILL_GRACE_MS;\n\tconst { args, env } = buildChildInvocation(spec, files, options);\n\n\treturn new Promise<SpawnAttemptResult>((resolve) => {\n\t\tlet settled = false;\n\t\tlet closed = false;\n\t\tlet killTimer: NodeJS.Timeout | undefined;\n\t\tlet proc: ChildProcessWithoutNullStreams;\n\n\t\tconst finishOnce = (exit: ChildExit) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tif (spec.signal) spec.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve({ exit, finish: reducer.finish(exit) });\n\t\t};\n\n\t\tfunction onAbort(): void {\n\t\t\tif (settled) return;\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {}\n\t\t\tkillTimer = setTimeout(() => {\n\t\t\t\tif (!closed && proc.pid !== undefined) killProcessTree(proc.pid);\n\t\t\t}, killGraceMs);\n\t\t\tkillTimer.unref();\n\t\t}\n\n\t\ttry {\n\t\t\tproc = spawn(command.bin, [...command.argsPrefix, ...args], {\n\t\t\t\tcwd: spec.cwd,\n\t\t\t\tenv,\n\t\t\t\tshell: false,\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tfinishOnce({\n\t\t\t\tcode: null,\n\t\t\t\tsignal: null,\n\t\t\t\tcancelled: spec.signal?.aborted === true,\n\t\t\t\tspawnError: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst pid = proc.pid;\n\t\tif (pid !== undefined) trackDetachedChildPid(pid);\n\t\ttry {\n\t\t\tspec.run?.onStart?.({ pid, argv: args });\n\t\t} catch {\n\t\t\t// A throwing onStart must not cut this executor short: the stdin/stdout/stderr wiring and\n\t\t\t// close/error handlers below still need to run, or this child would keep running with\n\t\t\t// nothing left to supervise it (never settling, never killed on abort).\n\t\t}\n\n\t\tproc.stdin.on(\"error\", () => {});\n\t\tproc.stdin.end(`Task: ${spec.task}`);\n\n\t\tconst forward = (change: ReturnType<ChildEventReducer[\"apply\"]>) => {\n\t\t\tif (change !== \"none\") spec.run?.onChange?.(change);\n\t\t};\n\t\tconst pendingFirstDelta = new Set<number>();\n\t\tattachChildLineReader(\n\t\t\tproc.stdout,\n\t\t\t(line) => {\n\t\t\t\tconst record = parseChildLine(line);\n\t\t\t\tif (!record) return;\n\t\t\t\tforward(reducer.apply(record));\n\t\t\t\tconst progress = legacyProgressText(record, pendingFirstDelta);\n\t\t\t\tif (progress) spec.onProgress?.(progress);\n\t\t\t},\n\t\t\t{\n\t\t\t\tonSkipped: (prefix) => {\n\t\t\t\t\tif (prefix.includes(\"tool_execution_update\")) forward(reducer.noteHeartbeat());\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tproc.stderr.setEncoding(\"utf8\");\n\t\tproc.stderr.on(\"data\", (chunk: string) => reducer.noteStderr(chunk));\n\n\t\tif (spec.signal) {\n\t\t\tif (spec.signal.aborted) onAbort();\n\t\t\telse spec.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\n\t\tproc.on(\"error\", (error) => {\n\t\t\tclosed = true;\n\t\t\tfinishOnce({\n\t\t\t\tcode: null,\n\t\t\t\tsignal: null,\n\t\t\t\tcancelled: spec.signal?.aborted === true,\n\t\t\t\tspawnError: error.message,\n\t\t\t});\n\t\t});\n\n\t\tproc.on(\"close\", (code, signal) => {\n\t\t\tclosed = true;\n\t\t\tif (pid !== undefined) untrackDetachedChildPid(pid);\n\t\t\tfinishOnce({ code, signal, cancelled: spec.signal?.aborted === true });\n\t\t});\n\t});\n}\n\nfunction isJsonObjectValue(value: JsonValue): value is JsonObject {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * §7.4: extracts the per-field errors from `validateToolArguments`'s formatted message (one\n * ` - path: message` line per failing field, then a blank line and \"Received arguments:\"),\n * joins them onto one line, and caps the result. Any other error (e.g. \"structured output must\n * be a JSON object\") has no such lines and is passed through as its own (single-line) message.\n */\nexport function formatStructuredOutputError(rawMessage: string): string {\n\tconst [body] = rawMessage.split(\"\\n\\nReceived arguments:\");\n\tconst lines = (body ?? rawMessage).split(\"\\n\");\n\tconst fieldErrors = lines\n\t\t.slice(1)\n\t\t.map((line) => line.replace(/^\\s*-\\s*/, \"\").trim())\n\t\t.filter((line) => line.length > 0);\n\tconst detail = fieldErrors.length > 0 ? fieldErrors.join(\"; \") : (lines[0] ?? rawMessage);\n\treturn truncateProgress(detail.replace(/\\s+/g, \" \").trim(), STRUCTURED_OUTPUT_NOTICE_MAX_CHARS);\n}\n\n/**\n * ChildEventReducer exposes no public \"add a notice\" API (pushNotice and bump are private, with\n * no exported hook for callers outside the class). This pushes the item directly, then reuses\n * the public `trimForRetention` pass with an unreachable budget, which recomputes\n * `transcriptChars` from scratch and bumps `version`/`coarseVersion` without evicting anything,\n * so version-keyed consumers (render caches, store) observe the change. Passing the run's\n * post-finish budget here would trim the whole live transcript down to that size as a side\n * effect, which is the store's job at `finish()` (§8.3 retention), not this mid-run notice's.\n * Always \"coarse\", since `trimForRetention` always bumps coarse.\n */\nexport function recordReducerNotice(\n\treducer: ChildEventReducer,\n\tlevel: \"info\" | \"warning\" | \"error\",\n\ttext: string,\n): \"coarse\" {\n\tconst item: TranscriptItem = { kind: \"notice\", seq: reducer.state.nextSeq++, rev: 1, level, text, at: Date.now() };\n\treducer.state.transcript.push(item);\n\treducer.trimForRetention(Number.POSITIVE_INFINITY);\n\treturn \"coarse\";\n}\n\nconst REDOS_SCHEMA_KEYWORDS = new Set([\"pattern\", \"patternProperties\"]);\n\n/**\n * Deep-clones `schema`, dropping every `pattern`/`patternProperties` keyword at any depth. A\n * workflow script controls `schema` end to end (§guardAgentRequest only caps its JSON size), so a\n * crafted `pattern` such as `\"^(a+)+$\"` paired with a near-matching structured-output value makes\n * `validateToolArguments` backtrack exponentially. The child already validated the same value\n * against the *full* schema (including any `pattern`) before this parent-side re-validation runs,\n * so dropping regex keywords here only removes a redundant, attacker-triggerable check — it does\n * not let a value through the child missed.\n */\nfunction stripRegexSchemaKeywords(value: JsonValue): JsonValue {\n\tif (Array.isArray(value)) return value.map(stripRegexSchemaKeywords);\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst result: JsonObject = {};\n\t\tfor (const [key, child] of Object.entries(value)) {\n\t\t\tif (REDOS_SCHEMA_KEYWORDS.has(key)) continue;\n\t\t\tresult[key] = stripRegexSchemaKeywords(child);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\n/** §7.4: validate `state.structured` against `run.schema`, mutating the reducer's public state in place. */\nexport function validateStructuredOutput(\n\treducer: ChildEventReducer,\n\tschema: JsonObject,\n\tonChange?: (change: \"fine\" | \"coarse\") => void,\n): void {\n\tconst pending = reducer.state.structured;\n\tif (!pending) return;\n\ttry {\n\t\tif (!isJsonObjectValue(pending.value)) throw new Error(\"structured output must be a JSON object\");\n\t\tconst safeSchema = stripRegexSchemaKeywords(schema) as JsonObject;\n\t\tconst validated = validateToolArguments(\n\t\t\t{ name: POLYPHASE_RESULT_TOOL_NAME, description: \"\", parameters: safeSchema as unknown as TSchema },\n\t\t\t{ type: \"toolCall\", id: \"result\", name: POLYPHASE_RESULT_TOOL_NAME, arguments: pending.value },\n\t\t);\n\t\treducer.state.structured = { value: validated as JsonValue };\n\t} catch (error) {\n\t\treducer.state.structured = undefined;\n\t\tconst rawMessage = error instanceof Error ? error.message : String(error);\n\t\tconst message = formatStructuredOutputError(rawMessage);\n\t\tconst change = recordReducerNotice(reducer, \"warning\", `structured output invalid: ${message}`);\n\t\tonChange?.(change);\n\t}\n}\n\n/** §7.3: re-spawn once without `--model`/`--thinking` when the inherited model could not be resolved. */\nfunction shouldFallbackToChildDefault(\n\tspec: ChildSpawnSpec,\n\treducer: ChildEventReducer,\n\tresult: SpawnAttemptResult,\n): boolean {\n\treturn (\n\t\tspec.run?.fallbackToChildDefaultModel === true &&\n\t\t!result.exit.cancelled &&\n\t\tresult.finish.exitCode !== 0 &&\n\t\treducer.state.recordsSeen === 0 &&\n\t\t/model/i.test(reducer.state.stderrTail)\n\t);\n}\n\n/** Writes the appended-system-prompt and polyphase_result schema temp files, then runs §7.2-7.4. */\nasync function runInTempDir(spec: ChildSpawnSpec, tempDir: string, reducer: ChildEventReducer): Promise<RunResult> {\n\tconst combinedPrompt = `${spec.agent.systemPrompt}\\n\\n${spec.run?.extraSystemPrompt ?? \"\"}`;\n\tlet systemPromptFile: string | undefined;\n\tif (combinedPrompt.trim().length > 0) {\n\t\tsystemPromptFile = path.join(tempDir, \"prompt.md\");\n\t\tfs.writeFileSync(systemPromptFile, combinedPrompt, { encoding: \"utf-8\", mode: 0o600 });\n\t}\n\n\tlet schemaFile: string | undefined;\n\tif (spec.run?.schema) {\n\t\tschemaFile = path.join(tempDir, \"schema.json\");\n\t\tfs.writeFileSync(schemaFile, JSON.stringify(spec.run.schema), { encoding: \"utf-8\", mode: 0o600 });\n\t}\n\n\tconst files = { systemPromptFile, schemaFile };\n\tconst command = spec.command ?? resolveDrahtCommand();\n\n\treducer.markSpawning();\n\tconst start = Date.now();\n\tlet result = await spawnAttempt(spec, command, reducer, files, {});\n\n\tif (shouldFallbackToChildDefault(spec, reducer, result)) {\n\t\tconst requested = spec.run?.model ?? spec.agent.model ?? \"\";\n\t\treducer.resetForRetry(\n\t\t\t{ source: \"child-default\", confirmed: false },\n\t\t\t`inherited model ${requested} is unavailable in the child; using the child's default model`,\n\t\t);\n\t\tresult = await spawnAttempt(spec, command, reducer, files, { omitModel: true });\n\t}\n\n\tif (spec.run?.schema) validateStructuredOutput(reducer, spec.run.schema, spec.run?.onChange);\n\n\treturn toRunResult(reducer.state, { agent: spec.agent.name, task: spec.task, step: spec.step }, result.finish, {\n\t\tcancelled: result.exit.cancelled,\n\t\tstructured: reducer.state.structured,\n\t\tdurationMs: Date.now() - start,\n\t});\n}\n\nfunction createReducerForSpec(spec: ChildSpawnSpec): ChildEventReducer {\n\treturn (\n\t\tspec.run?.reducer ??\n\t\tnew ChildEventReducer({\n\t\t\tmodel: spec.run?.modelInfo ?? {\n\t\t\t\tsource: spec.agent.model ? \"frontmatter\" : \"child-default\",\n\t\t\t\trequested: spec.agent.model,\n\t\t\t\tconfirmed: false,\n\t\t\t},\n\t\t})\n\t);\n}\n\n/** Never rejects: spawn and runtime failures resolve as a failed `RunResult`. */\nexport async function runChildAgent(spec: ChildSpawnSpec): Promise<RunResult> {\n\tconst reducer = createReducerForSpec(spec);\n\tconst base = { agent: spec.agent.name, task: spec.task, step: spec.step };\n\tconst attemptStart = Date.now();\n\n\tif (spec.signal?.aborted) {\n\t\tconst finish = reducer.finish({ code: null, signal: null, cancelled: true });\n\t\treturn toRunResult(reducer.state, base, finish, {\n\t\t\tcancelled: true,\n\t\t\tdurationMs: Date.now() - attemptStart,\n\t\t});\n\t}\n\n\tlet tempDir: string | undefined;\n\ttry {\n\t\ttempDir = fs.mkdtempSync(path.join(os.tmpdir(), \"draht-polyphase-\"));\n\t\treturn await runInTempDir(spec, tempDir, reducer);\n\t} catch (error) {\n\t\tconst cancelled = spec.signal?.aborted === true;\n\t\tconst finish = reducer.finish({\n\t\t\tcode: null,\n\t\t\tsignal: null,\n\t\t\tcancelled,\n\t\t\tspawnError: error instanceof Error ? error.message : String(error),\n\t\t});\n\t\treturn toRunResult(reducer.state, base, finish, { cancelled, durationMs: Date.now() - attemptStart });\n\t} finally {\n\t\tif (tempDir) {\n\t\t\ttry {\n\t\t\t\tfs.rmSync(tempDir, { recursive: true, force: true });\n\t\t\t} catch {}\n\t\t}\n\t}\n}\n\nexport function createProcessAgentRunner(command?: ChildCommand): AgentRunner {\n\treturn (cwd, agent, task, signal, step, onProgress, run) =>\n\t\trunChildAgent({ cwd, agent, task, step, run, signal, onProgress, command });\n}\n"]}
1
+ {"version":3,"file":"child-process.js","sourceRoot":"","sources":["../../../src/core/polyphase/child-process.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAA0D,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACnG,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACvG,OAAO,EACN,iBAAiB,EAIjB,cAAc,EACd,iBAAiB,EACjB,WAAW,GACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAEN,+BAA+B,EAC/B,wBAAwB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAMN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AC;QACV,IAAI,OAAO,EAAE,CAAC;YACb,IAAI,CAAC;gBACJ,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACtD,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACX,CAAC;IACF,CAAC;AACF,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,OAAsB;IAC9D,OAAO,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,EAAE,CAC1D,aAAa,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * Spawns and supervises one child draht process for a subagent/workflow run (§7.1-7.4).\n *\n * `buildChildInvocation` and `resolveDrahtCommand` are pure; `runChildAgent` owns every\n * side effect (temp files, spawn, line reading, abort escalation) and never rejects.\n */\n\nimport { type ChildProcess, type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { JsonObject, JsonValue } from \"@draht/ai\";\nimport { validateToolArguments } from \"@draht/ai\";\nimport type { TSchema } from \"typebox\";\nimport { isBunBinary } from \"../../config.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\nimport {\n\tChildEventReducer,\n\ttype ChildExit,\n\ttype ChildFinish,\n\ttype ChildWireRecord,\n\tparseChildLine,\n\tsummarizeToolArgs,\n\ttoRunResult,\n} from \"./child-events.ts\";\nimport { attachChildLineReader } from \"./jsonl-reader.ts\";\nimport {\n\ttype ChildPermissionServer,\n\tPOLYPHASE_PERMISSION_BRIDGE_ENV,\n\tserveChildPermissionAsks,\n} from \"./permission-bridge.ts\";\nimport {\n\ttype AgentConfig,\n\ttype AgentRunContext,\n\ttype AgentRunner,\n\ttype ChildPermissionRequest,\n\ttype ChildPermissionVerdict,\n\tcurrentPolyphaseDepth,\n\tDUET_DELEGATE_TOOL_NAME,\n\tPOLYPHASE_DEPTH_ENV,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\tPOLYPHASE_SCHEMA_FILE_ENV,\n\ttype ProgressFn,\n\ttype RunResult,\n\ttype TranscriptItem,\n\tWORKFLOW_TOOL_NAME,\n} from \"./types.ts\";\n\nconst DEFAULT_KILL_GRACE_MS = 5000;\nconst LEGACY_TOOL_SUMMARY_MAX_CHARS = 60;\nconst LEGACY_TEXT_PROGRESS_MAX_CHARS = 80;\nconst INSPECT_OR_DEBUG_FLAG = /^--(?:inspect|debug)/;\nconst STRUCTURED_OUTPUT_NOTICE_MAX_CHARS = 200;\nconst PERMISSION_NOTICE_MAX_CHARS = 200;\n\nexport interface ChildCommand {\n\tbin: string;\n\targsPrefix: readonly string[];\n}\n\n/**\n * Bun binary: `{execPath, []}`. Otherwise `{execPath, [...execArgv without --inspect*\n * and --debug*, argv[1]]}`, which keeps tsx (and other loader-based dev runs) working in children.\n */\nexport function resolveDrahtCommand(): ChildCommand {\n\tif (isBunBinary) return { bin: process.execPath, argsPrefix: [] };\n\tconst execArgv = process.execArgv.filter((arg) => !INSPECT_OR_DEBUG_FLAG.test(arg));\n\treturn { bin: process.execPath, argsPrefix: [...execArgv, process.argv[1]] };\n}\n\nexport interface ChildSpawnSpec {\n\tcwd: string;\n\tagent: AgentConfig;\n\ttask: string;\n\tstep?: number;\n\trun?: AgentRunContext;\n\tsignal?: AbortSignal;\n\tonProgress?: ProgressFn;\n\tcommand?: ChildCommand;\n\t/** Grace period between SIGTERM and SIGKILL-via-tree on abort. Default 5000. */\n\tkillGraceMs?: number;\n\tbaseEnv?: NodeJS.ProcessEnv;\n}\n\n/** Pure: computes argv and env for one spawn. `files` are temp paths already written by the caller. */\nexport function buildChildInvocation(\n\tspec: ChildSpawnSpec,\n\tfiles: { systemPromptFile?: string; schemaFile?: string },\n\toptions?: { omitModel?: boolean },\n): { args: string[]; env: NodeJS.ProcessEnv } {\n\tconst { agent, run } = spec;\n\tconst omitModel = options?.omitModel ?? false;\n\tconst args: string[] = [\"--mode\", \"json\", \"-p\", \"--no-session\"];\n\n\tconst model = run?.model ?? agent.model;\n\tif (!omitModel && model) args.push(\"--model\", model);\n\tif (!omitModel && run?.thinking) args.push(\"--thinking\", run.thinking);\n\n\tif (agent.tools?.length) {\n\t\tconst tools = [...agent.tools, ...(run?.extraTools ?? [])];\n\t\targs.push(\"--tools\", tools.join(\",\"));\n\t}\n\n\tif (agent.disableExtensions) args.push(\"--no-extensions\");\n\n\tconst excludeTools = [WORKFLOW_TOOL_NAME, DUET_DELEGATE_TOOL_NAME, ...(run?.excludeTools ?? [])];\n\targs.push(\"--exclude-tools\", [...new Set(excludeTools)].join(\",\"));\n\n\tif (files.systemPromptFile) args.push(\"--append-system-prompt\", files.systemPromptFile);\n\n\tconst baseEnv = spec.baseEnv ?? process.env;\n\tconst resolvedRunEnv = typeof run?.env === \"function\" ? run.env() : run?.env;\n\tconst env: NodeJS.ProcessEnv = { ...baseEnv, ...(resolvedRunEnv ?? {}) };\n\tenv[POLYPHASE_DEPTH_ENV] = String(currentPolyphaseDepth(baseEnv) + 1);\n\tif (files.schemaFile) {\n\t\tenv[POLYPHASE_SCHEMA_FILE_ENV] = files.schemaFile;\n\t} else {\n\t\tdelete env[POLYPHASE_SCHEMA_FILE_ENV];\n\t}\n\t// Set only for a child whose asks this process will answer. A copy inherited from our own bridged\n\t// parent must not reach a child we do not serve: it would write asks to a channel nobody reads.\n\tif (run?.onPermissionAsk) {\n\t\tenv[POLYPHASE_PERMISSION_BRIDGE_ENV] = \"1\";\n\t} else {\n\t\tdelete env[POLYPHASE_PERMISSION_BRIDGE_ENV];\n\t}\n\n\treturn { args, env };\n}\n\nfunction hasPipedStdio(proc: ChildProcess): proc is ChildProcessWithoutNullStreams {\n\treturn proc.stdin !== null && proc.stdout !== null && proc.stderr !== null;\n}\n\n/** Spawns with piped stdio, plus the IPC channel the permission bridge runs over when `ipc` is set. */\nfunction spawnChild(\n\tcommand: ChildCommand,\n\targs: readonly string[],\n\toptions: { cwd: string; env: NodeJS.ProcessEnv; ipc: boolean },\n): ChildProcessWithoutNullStreams {\n\tconst proc = spawn(command.bin, [...command.argsPrefix, ...args], {\n\t\tcwd: options.cwd,\n\t\tenv: options.env,\n\t\tshell: false,\n\t\tstdio: options.ipc ? [\"pipe\", \"pipe\", \"pipe\", \"ipc\"] : [\"pipe\", \"pipe\", \"pipe\"],\n\t});\n\tif (!hasPipedStdio(proc)) {\n\t\tproc.kill(\"SIGKILL\");\n\t\tthrow new Error(\"child process started without piped stdio\");\n\t}\n\treturn proc;\n}\n\n/** The transcript line an agent's run shows for one of its permission asks, or none. */\nfunction permissionNotice(\n\trequest: ChildPermissionRequest,\n\tverdict?: ChildPermissionVerdict,\n): { level: \"info\" | \"warning\"; text: string } | undefined {\n\tconst summary = summarizeToolArgs(request.toolName, request.input);\n\tconst call = summary ? `${request.toolName} ${summary}` : request.toolName;\n\tconst line = (text: string) => truncateProgress(text, PERMISSION_NOTICE_MAX_CHARS);\n\tif (verdict === undefined) return { level: \"info\", text: line(`approval requested: ${call}`) };\n\tswitch (verdict.kind) {\n\t\tcase \"approved\":\n\t\t\treturn { level: \"info\", text: line(`approved: ${call}`) };\n\t\tcase \"denied\":\n\t\t\treturn { level: \"warning\", text: line(`denied: ${call} (${verdict.reason})`) };\n\t\tcase \"unavailable\":\n\t\tcase \"cancelled\":\n\t\t\t// The child itself reports what became of the call: a blocked tool, or an aborted turn.\n\t\t\treturn undefined;\n\t}\n}\n\nfunction truncateProgress(text: string, max: number): string {\n\treturn text.length > max ? `${text.slice(0, max)}...` : text;\n}\n\n/**\n * Legacy `onProgress` strings duet relies on: a short line on every tool start, and one line for\n * the first delta of each new text item (a cheap \"what is it writing\" signal, not a transcript).\n */\nfunction legacyProgressText(record: ChildWireRecord, pendingFirstDelta: Set<number>): string | undefined {\n\tif (record.type === \"tool_execution_start\") {\n\t\tconst summary = truncateProgress(\n\t\t\tsummarizeToolArgs(record.toolName, record.args as JsonValue | undefined),\n\t\t\tLEGACY_TOOL_SUMMARY_MAX_CHARS,\n\t\t);\n\t\treturn summary ? `${record.toolName} ${summary}` : record.toolName;\n\t}\n\tif (record.type === \"message_update\") {\n\t\tconst event = record.assistantMessageEvent;\n\t\tif (event.type === \"text_start\") {\n\t\t\tpendingFirstDelta.add(event.contentIndex);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (event.type === \"text_delta\" && pendingFirstDelta.delete(event.contentIndex)) {\n\t\t\tconst firstLine = event.delta.split(\"\\n\")[0] ?? \"\";\n\t\t\treturn truncateProgress(firstLine, LEGACY_TEXT_PROGRESS_MAX_CHARS);\n\t\t}\n\t}\n\treturn undefined;\n}\n\ninterface SpawnAttemptResult {\n\texit: ChildExit;\n\tfinish: ChildFinish;\n}\n\n/** One spawn: wires the line reader, stderr tail, abort escalation, and resolves via `reducer.finish`. */\nfunction spawnAttempt(\n\tspec: ChildSpawnSpec,\n\tcommand: ChildCommand,\n\treducer: ChildEventReducer,\n\tfiles: { systemPromptFile?: string; schemaFile?: string },\n\toptions: { omitModel?: boolean },\n): Promise<SpawnAttemptResult> {\n\tconst killGraceMs = spec.killGraceMs ?? DEFAULT_KILL_GRACE_MS;\n\tconst { args, env } = buildChildInvocation(spec, files, options);\n\tconst asker = spec.run?.onPermissionAsk;\n\n\treturn new Promise<SpawnAttemptResult>((resolve) => {\n\t\tlet settled = false;\n\t\tlet closed = false;\n\t\tlet killTimer: NodeJS.Timeout | undefined;\n\t\tlet proc: ChildProcessWithoutNullStreams;\n\t\tlet permissionServer: ChildPermissionServer | undefined;\n\n\t\tconst finishOnce = (exit: ChildExit) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\t// Takes down any dialog still open for this child: nobody is left to receive the answer.\n\t\t\tpermissionServer?.dispose();\n\t\t\tif (spec.signal) spec.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve({ exit, finish: reducer.finish(exit) });\n\t\t};\n\n\t\tfunction onAbort(): void {\n\t\t\tif (settled) return;\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {}\n\t\t\tkillTimer = setTimeout(() => {\n\t\t\t\tif (!closed && proc.pid !== undefined) killProcessTree(proc.pid);\n\t\t\t}, killGraceMs);\n\t\t\tkillTimer.unref();\n\t\t}\n\n\t\ttry {\n\t\t\tproc = spawnChild(command, args, { cwd: spec.cwd, env, ipc: asker !== undefined });\n\t\t} catch (error) {\n\t\t\tfinishOnce({\n\t\t\t\tcode: null,\n\t\t\t\tsignal: null,\n\t\t\t\tcancelled: spec.signal?.aborted === true,\n\t\t\t\tspawnError: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst pid = proc.pid;\n\t\tif (pid !== undefined) trackDetachedChildPid(pid);\n\t\ttry {\n\t\t\tspec.run?.onStart?.({ pid, argv: args });\n\t\t} catch {\n\t\t\t// A throwing onStart must not cut this executor short: the stdin/stdout/stderr wiring and\n\t\t\t// close/error handlers below still need to run, or this child would keep running with\n\t\t\t// nothing left to supervise it (never settling, never killed on abort).\n\t\t}\n\n\t\tproc.stdin.on(\"error\", () => {});\n\t\tproc.stdin.end(`Task: ${spec.task}`);\n\n\t\tconst forward = (change: ReturnType<ChildEventReducer[\"apply\"]>) => {\n\t\t\tif (change !== \"none\") spec.run?.onChange?.(change);\n\t\t};\n\t\tconst notePermission = (request: ChildPermissionRequest, verdict?: ChildPermissionVerdict) => {\n\t\t\tconst notice = permissionNotice(request, verdict);\n\t\t\tif (notice && !settled) forward(recordReducerNotice(reducer, notice.level, notice.text));\n\t\t};\n\t\tif (asker) {\n\t\t\tpermissionServer = serveChildPermissionAsks(proc, asker, {\n\t\t\t\tcwd: spec.cwd,\n\t\t\t\tsignal: spec.signal,\n\t\t\t\tonAsk: (request) => notePermission(request),\n\t\t\t\tonVerdict: (request, verdict) => notePermission(request, verdict),\n\t\t\t});\n\t\t}\n\t\tconst pendingFirstDelta = new Set<number>();\n\t\tattachChildLineReader(\n\t\t\tproc.stdout,\n\t\t\t(line) => {\n\t\t\t\tconst record = parseChildLine(line);\n\t\t\t\tif (!record) return;\n\t\t\t\tforward(reducer.apply(record));\n\t\t\t\tconst progress = legacyProgressText(record, pendingFirstDelta);\n\t\t\t\tif (progress) spec.onProgress?.(progress);\n\t\t\t},\n\t\t\t{\n\t\t\t\tonSkipped: (prefix) => {\n\t\t\t\t\tif (prefix.includes(\"tool_execution_update\")) forward(reducer.noteHeartbeat());\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tproc.stderr.setEncoding(\"utf8\");\n\t\tproc.stderr.on(\"data\", (chunk: string) => reducer.noteStderr(chunk));\n\n\t\tif (spec.signal) {\n\t\t\tif (spec.signal.aborted) onAbort();\n\t\t\telse spec.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\n\t\tproc.on(\"error\", (error) => {\n\t\t\tclosed = true;\n\t\t\tfinishOnce({\n\t\t\t\tcode: null,\n\t\t\t\tsignal: null,\n\t\t\t\tcancelled: spec.signal?.aborted === true,\n\t\t\t\tspawnError: error.message,\n\t\t\t});\n\t\t});\n\n\t\tproc.on(\"close\", (code, signal) => {\n\t\t\tclosed = true;\n\t\t\tif (pid !== undefined) untrackDetachedChildPid(pid);\n\t\t\tfinishOnce({ code, signal, cancelled: spec.signal?.aborted === true });\n\t\t});\n\t});\n}\n\nfunction isJsonObjectValue(value: JsonValue): value is JsonObject {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * §7.4: extracts the per-field errors from `validateToolArguments`'s formatted message (one\n * ` - path: message` line per failing field, then a blank line and \"Received arguments:\"),\n * joins them onto one line, and caps the result. Any other error (e.g. \"structured output must\n * be a JSON object\") has no such lines and is passed through as its own (single-line) message.\n */\nexport function formatStructuredOutputError(rawMessage: string): string {\n\tconst [body] = rawMessage.split(\"\\n\\nReceived arguments:\");\n\tconst lines = (body ?? rawMessage).split(\"\\n\");\n\tconst fieldErrors = lines\n\t\t.slice(1)\n\t\t.map((line) => line.replace(/^\\s*-\\s*/, \"\").trim())\n\t\t.filter((line) => line.length > 0);\n\tconst detail = fieldErrors.length > 0 ? fieldErrors.join(\"; \") : (lines[0] ?? rawMessage);\n\treturn truncateProgress(detail.replace(/\\s+/g, \" \").trim(), STRUCTURED_OUTPUT_NOTICE_MAX_CHARS);\n}\n\n/**\n * ChildEventReducer exposes no public \"add a notice\" API (pushNotice and bump are private, with\n * no exported hook for callers outside the class). This pushes the item directly, then reuses\n * the public `trimForRetention` pass with an unreachable budget, which recomputes\n * `transcriptChars` from scratch and bumps `version`/`coarseVersion` without evicting anything,\n * so version-keyed consumers (render caches, store) observe the change. Passing the run's\n * post-finish budget here would trim the whole live transcript down to that size as a side\n * effect, which is the store's job at `finish()` (§8.3 retention), not this mid-run notice's.\n * Always \"coarse\", since `trimForRetention` always bumps coarse.\n */\nexport function recordReducerNotice(\n\treducer: ChildEventReducer,\n\tlevel: \"info\" | \"warning\" | \"error\",\n\ttext: string,\n): \"coarse\" {\n\tconst item: TranscriptItem = { kind: \"notice\", seq: reducer.state.nextSeq++, rev: 1, level, text, at: Date.now() };\n\treducer.state.transcript.push(item);\n\treducer.trimForRetention(Number.POSITIVE_INFINITY);\n\treturn \"coarse\";\n}\n\nconst REDOS_SCHEMA_KEYWORDS = new Set([\"pattern\", \"patternProperties\"]);\n\n/**\n * Deep-clones `schema`, dropping every `pattern`/`patternProperties` keyword at any depth. A\n * workflow script controls `schema` end to end (§guardAgentRequest only caps its JSON size), so a\n * crafted `pattern` such as `\"^(a+)+$\"` paired with a near-matching structured-output value makes\n * `validateToolArguments` backtrack exponentially. The child already validated the same value\n * against the *full* schema (including any `pattern`) before this parent-side re-validation runs,\n * so dropping regex keywords here only removes a redundant, attacker-triggerable check — it does\n * not let a value through the child missed.\n */\nfunction stripRegexSchemaKeywords(value: JsonValue): JsonValue {\n\tif (Array.isArray(value)) return value.map(stripRegexSchemaKeywords);\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst result: JsonObject = {};\n\t\tfor (const [key, child] of Object.entries(value)) {\n\t\t\tif (REDOS_SCHEMA_KEYWORDS.has(key)) continue;\n\t\t\tresult[key] = stripRegexSchemaKeywords(child);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\n/** §7.4: validate `state.structured` against `run.schema`, mutating the reducer's public state in place. */\nexport function validateStructuredOutput(\n\treducer: ChildEventReducer,\n\tschema: JsonObject,\n\tonChange?: (change: \"fine\" | \"coarse\") => void,\n): void {\n\tconst pending = reducer.state.structured;\n\tif (!pending) return;\n\ttry {\n\t\tif (!isJsonObjectValue(pending.value)) throw new Error(\"structured output must be a JSON object\");\n\t\tconst safeSchema = stripRegexSchemaKeywords(schema) as JsonObject;\n\t\tconst validated = validateToolArguments(\n\t\t\t{ name: POLYPHASE_RESULT_TOOL_NAME, description: \"\", parameters: safeSchema as unknown as TSchema },\n\t\t\t{ type: \"toolCall\", id: \"result\", name: POLYPHASE_RESULT_TOOL_NAME, arguments: pending.value },\n\t\t);\n\t\treducer.state.structured = { value: validated as JsonValue };\n\t} catch (error) {\n\t\treducer.state.structured = undefined;\n\t\tconst rawMessage = error instanceof Error ? error.message : String(error);\n\t\tconst message = formatStructuredOutputError(rawMessage);\n\t\tconst change = recordReducerNotice(reducer, \"warning\", `structured output invalid: ${message}`);\n\t\tonChange?.(change);\n\t}\n}\n\n/** §7.3: re-spawn once without `--model`/`--thinking` when the inherited model could not be resolved. */\nfunction shouldFallbackToChildDefault(\n\tspec: ChildSpawnSpec,\n\treducer: ChildEventReducer,\n\tresult: SpawnAttemptResult,\n): boolean {\n\treturn (\n\t\tspec.run?.fallbackToChildDefaultModel === true &&\n\t\t!result.exit.cancelled &&\n\t\tresult.finish.exitCode !== 0 &&\n\t\treducer.state.recordsSeen === 0 &&\n\t\t/model/i.test(reducer.state.stderrTail)\n\t);\n}\n\n/** Writes the appended-system-prompt and polyphase_result schema temp files, then runs §7.2-7.4. */\nasync function runInTempDir(spec: ChildSpawnSpec, tempDir: string, reducer: ChildEventReducer): Promise<RunResult> {\n\tconst combinedPrompt = `${spec.agent.systemPrompt}\\n\\n${spec.run?.extraSystemPrompt ?? \"\"}`;\n\tlet systemPromptFile: string | undefined;\n\tif (combinedPrompt.trim().length > 0) {\n\t\tsystemPromptFile = path.join(tempDir, \"prompt.md\");\n\t\tfs.writeFileSync(systemPromptFile, combinedPrompt, { encoding: \"utf-8\", mode: 0o600 });\n\t}\n\n\tlet schemaFile: string | undefined;\n\tif (spec.run?.schema) {\n\t\tschemaFile = path.join(tempDir, \"schema.json\");\n\t\tfs.writeFileSync(schemaFile, JSON.stringify(spec.run.schema), { encoding: \"utf-8\", mode: 0o600 });\n\t}\n\n\tconst files = { systemPromptFile, schemaFile };\n\tconst command = spec.command ?? resolveDrahtCommand();\n\n\treducer.markSpawning();\n\tconst start = Date.now();\n\tlet result = await spawnAttempt(spec, command, reducer, files, {});\n\n\tif (shouldFallbackToChildDefault(spec, reducer, result)) {\n\t\tconst requested = spec.run?.model ?? spec.agent.model ?? \"\";\n\t\treducer.resetForRetry(\n\t\t\t{ source: \"child-default\", confirmed: false },\n\t\t\t`inherited model ${requested} is unavailable in the child; using the child's default model`,\n\t\t);\n\t\tresult = await spawnAttempt(spec, command, reducer, files, { omitModel: true });\n\t}\n\n\tif (spec.run?.schema) validateStructuredOutput(reducer, spec.run.schema, spec.run?.onChange);\n\n\treturn toRunResult(reducer.state, { agent: spec.agent.name, task: spec.task, step: spec.step }, result.finish, {\n\t\tcancelled: result.exit.cancelled,\n\t\tstructured: reducer.state.structured,\n\t\tdurationMs: Date.now() - start,\n\t});\n}\n\nfunction createReducerForSpec(spec: ChildSpawnSpec): ChildEventReducer {\n\treturn (\n\t\tspec.run?.reducer ??\n\t\tnew ChildEventReducer({\n\t\t\tmodel: spec.run?.modelInfo ?? {\n\t\t\t\tsource: spec.agent.model ? \"frontmatter\" : \"child-default\",\n\t\t\t\trequested: spec.agent.model,\n\t\t\t\tconfirmed: false,\n\t\t\t},\n\t\t})\n\t);\n}\n\n/** Never rejects: spawn and runtime failures resolve as a failed `RunResult`. */\nexport async function runChildAgent(spec: ChildSpawnSpec): Promise<RunResult> {\n\tconst reducer = createReducerForSpec(spec);\n\tconst base = { agent: spec.agent.name, task: spec.task, step: spec.step };\n\tconst attemptStart = Date.now();\n\n\tif (spec.signal?.aborted) {\n\t\tconst finish = reducer.finish({ code: null, signal: null, cancelled: true });\n\t\treturn toRunResult(reducer.state, base, finish, {\n\t\t\tcancelled: true,\n\t\t\tdurationMs: Date.now() - attemptStart,\n\t\t});\n\t}\n\n\tlet tempDir: string | undefined;\n\ttry {\n\t\ttempDir = fs.mkdtempSync(path.join(os.tmpdir(), \"draht-polyphase-\"));\n\t\treturn await runInTempDir(spec, tempDir, reducer);\n\t} catch (error) {\n\t\tconst cancelled = spec.signal?.aborted === true;\n\t\tconst finish = reducer.finish({\n\t\t\tcode: null,\n\t\t\tsignal: null,\n\t\t\tcancelled,\n\t\t\tspawnError: error instanceof Error ? error.message : String(error),\n\t\t});\n\t\treturn toRunResult(reducer.state, base, finish, { cancelled, durationMs: Date.now() - attemptStart });\n\t} finally {\n\t\tif (tempDir) {\n\t\t\ttry {\n\t\t\t\tfs.rmSync(tempDir, { recursive: true, force: true });\n\t\t\t} catch {}\n\t\t}\n\t}\n}\n\nexport function createProcessAgentRunner(command?: ChildCommand): AgentRunner {\n\treturn (cwd, agent, task, signal, step, onProgress, run) =>\n\t\trunChildAgent({ cwd, agent, task, step, run, signal, onProgress, command });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/commands.ts"],"names":[],"mappings":"AAAA;;;;GAI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xC,SAAS,EAAE,SAAS,aAAa,EAAE,EACnC,QAAQ,EAAE;IAAE,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAC1G,gBAAgB,CAiClB;AAED,uFAAuF;AACvF,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,oBAAoB,EAAE,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAStG;AAED,iGAAiG;AACjG,wBAAsB,2BAA2B,CAChD,IAAI,EAAE,oBAAoB,EAC1B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,uBAAuB,GAC1B,OAAO,CAAC,IAAI,CAAC,CA8If;AAyBD,2FAA2F;AAC3F,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,oBAAoB,GAAG,IAAI,CAoEzE"}
@@ -8,9 +8,11 @@ import { getAgentDir } from "../../config.js";
8
8
  import { keyDisplayText } from "../../modes/interactive/components/keybinding-hints.js";
9
9
  import { loadPermissionRules } from "../builtins/subagent.js";
10
10
  import { PermissionGate } from "../multi-agent/index.js";
11
+ import { isValidUsage } from "../usage-totals.js";
11
12
  import { describeToolCallForApproval } from "./approval.js";
12
13
  import { collectArchivedRuns } from "./details.js";
13
14
  import { startWorkflowRun } from "./workflow/launch.js";
15
+ import { parsePromptDirectives, resolveWorkflowLimits, stripPromptDirectives } from "./workflow/limits.js";
14
16
  import { extractWorkflowMeta } from "./workflow/meta.js";
15
17
  import { discoverSavedWorkflows, readSavedWorkflowSource, } from "./workflow/saved.js";
16
18
  function discoveryOptions(ctx) {
@@ -96,18 +98,30 @@ export async function runSavedWorkflowFromCommand(deps, name, args, ctx) {
96
98
  }
97
99
  const session = deps.getSession(ctx);
98
100
  const settings = session.settings();
101
+ // D-B: a `+500k`/`+30min`-style directive is parsed straight from this command's own args (the
102
+ // user's literal input), not the session's pending-prompt state, and stripped before the rest
103
+ // of this handler (gate, approval, the script) ever sees it.
104
+ const promptDirectives = parsePromptDirectives(args);
105
+ const strippedArgs = stripPromptDirectives(args);
106
+ const limits = resolveWorkflowLimits({
107
+ prompt: promptDirectives,
108
+ config: {
109
+ budgetTokens: settings.defaultBudgetTokens,
110
+ timeLimitMs: settings.workflowTimeoutMs > 0 ? settings.workflowTimeoutMs : null,
111
+ },
112
+ });
99
113
  const gate = new PermissionGate(loadPermissionRules(ctx.cwd, ctx.isProjectTrusted()), {
100
114
  cwd: ctx.cwd,
101
115
  mode: session.permissionMode(),
102
116
  });
103
- const decision = gate.evaluate("workflow", { name, args });
117
+ const decision = gate.evaluate("workflow", { name, args: strippedArgs });
104
118
  if (decision.action === "deny") {
105
119
  ctx.ui.notify(decision.reason, "error");
106
120
  return;
107
121
  }
108
122
  if (decision.action === "approve") {
109
123
  if (!ctx.hasUI) {
110
- ctx.ui.notify(`Workflow ${name} needs approval but no UI is available; use /yolo or an allow rule`, "error");
124
+ ctx.ui.notify(`Workflow ${name} needs approval but no UI is available (${decision.reason}); add an allow rule to permissions.yml, or start with DRAHT_PERMISSION_MODE=auto (yolo if a rule asks for approval)`, "error");
111
125
  return;
112
126
  }
113
127
  session.notifyParentPrompt();
@@ -119,9 +133,11 @@ export async function runSavedWorkflowFromCommand(deps, name, args, ctx) {
119
133
  concurrency: settings.maxConcurrency,
120
134
  maxAgents: settings.maxAgentsPerRun,
121
135
  budgetTokens: settings.defaultBudgetTokens,
136
+ timeLimitMs: settings.workflowTimeoutMs > 0 ? settings.workflowTimeoutMs : null,
122
137
  },
138
+ promptDirectives,
123
139
  };
124
- const description = describeToolCallForApproval("workflow", { name, args }, approvalContext);
140
+ const description = describeToolCallForApproval("workflow", { name, args: strippedArgs }, approvalContext);
125
141
  const title = description?.title ?? `Run workflow "${name}"?`;
126
142
  const message = description?.message ?? extraction.meta.description;
127
143
  const approved = await ctx.ui.confirm(title, message);
@@ -143,14 +159,15 @@ export async function runSavedWorkflowFromCommand(deps, name, args, ctx) {
143
159
  parentSignal: undefined,
144
160
  meta: extraction.meta,
145
161
  body: extraction.body,
146
- args,
162
+ args: strippedArgs,
147
163
  source: { kind: workflow.source, path: workflow.path },
148
- budgetTokens: settings.defaultBudgetTokens,
164
+ limits,
149
165
  runner: deps.runner,
150
166
  });
151
167
  const reportCompletion = (completion) => {
152
168
  if (session.disposed)
153
169
  return;
170
+ recordCommandRunUsage(deps.pi, name, handle.run);
154
171
  try {
155
172
  deps.pi.sendMessage({
156
173
  customType: "polyphase-workflow",
@@ -177,6 +194,30 @@ export async function runSavedWorkflowFromCommand(deps, name, args, ctx) {
177
194
  }
178
195
  void handle.done.then(reportCompletion);
179
196
  }
197
+ /**
198
+ * Attributes a finished command-run's cost to its agents' models. One usage
199
+ * entry per agent that reported any usage, kind `"polyphase"`, note `/<name> <label>`. An agent
200
+ * whose model was never confirmed by the child is recorded as provider `"unknown"` with the
201
+ * requested model string, rather than the parent's unconfirmed guess. Tool-origin runs report
202
+ * their own usage through the tool result and must not reach this function (no double counting).
203
+ */
204
+ function recordCommandRunUsage(pi, workflowName, run) {
205
+ for (const agent of run.agents) {
206
+ const usage = agent.state.usage;
207
+ if (!usage || !isValidUsage(usage))
208
+ continue;
209
+ const model = agent.state.model;
210
+ const provider = model.confirmed && model.provider ? model.provider : "unknown";
211
+ const modelId = model.confirmed && model.id ? model.id : (model.requested ?? "unknown");
212
+ try {
213
+ pi.appendUsage("polyphase", provider, modelId, usage, `/${workflowName} ${agent.label}`);
214
+ }
215
+ catch {
216
+ // The extension ctx can go stale concurrently (e.g. a session shutdown that raced this
217
+ // report); the run already finished, so dropping the usage entry here is safe.
218
+ }
219
+ }
220
+ }
180
221
  /** `/workflow` and `/workflows` (factory body, registered once per extension instance). */
181
222
  export function registerWorkflowCommands(deps) {
182
223
  deps.pi.registerCommand("workflow", {
@@ -1 +1 @@
1
- {"version":3,"file":"commands.js","sourceRoot":"","sources":["../../../src/core/polyphase/commands.ts"],"names":[],"mappings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,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC;gBACnD,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;gBAC7E,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,qBAAqB,CAAC;aACjD,CAAC;YACF,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;QAClF,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `/workflow`, `/workflows` and the per-saved-workflow `/<name>` commands (§16.2), plus the\n * command-path approval flow (§15.3). Saved workflow runs started this way are host-side: they\n * are independent of agent turns and report back with a non-triggering custom message.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { keyDisplayText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { loadPermissionRules } from \"../builtins/subagent.ts\";\nimport type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from \"../extensions/types.ts\";\nimport { PermissionGate } from \"../multi-agent/index.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport { type ApprovalContext, describeToolCallForApproval } from \"./approval.ts\";\nimport { collectArchivedRuns } from \"./details.ts\";\nimport type { PolyphaseSession } from \"./session.ts\";\nimport type { AgentRunner } from \"./types.ts\";\nimport type { PolyphaseUiController } from \"./ui/controller.ts\";\nimport { startWorkflowRun, type WorkflowRunCompletion } from \"./workflow/launch.ts\";\nimport { extractWorkflowMeta } from \"./workflow/meta.ts\";\nimport {\n\tdiscoverSavedWorkflows,\n\treadSavedWorkflowSource,\n\ttype SavedDiscoveryOptions,\n\ttype SavedWorkflow,\n} from \"./workflow/saved.ts\";\n\nexport interface PolyphaseCommandDeps {\n\tpi: ExtensionAPI;\n\tgetSession(ctx: ExtensionContext): PolyphaseSession;\n\tgetUi(): PolyphaseUiController | undefined;\n\trunner?: AgentRunner;\n\tkeyword(): string;\n\t/** The most recent discovery result, refreshed at every `session_start`. */\n\tgetSavedWorkflows(): readonly SavedWorkflow[];\n}\n\nexport interface SavedCommandPlan {\n\tregister: SavedWorkflow[];\n\tskipped: Array<{ workflow: SavedWorkflow; reason: string }>;\n}\n\nfunction discoveryOptions(ctx: ExtensionContext): SavedDiscoveryOptions {\n\treturn { cwd: ctx.cwd, agentDir: getAgentDir(), projectTrusted: ctx.isProjectTrusted() };\n}\n\nfunction describeSavedWorkflow(workflow: SavedWorkflow): string {\n\treturn `${workflow.name} — ${workflow.description}`;\n}\n\n/**\n * Collision check for every valid saved workflow name against `BUILTIN_SLASH_COMMANDS`,\n * `pi.getCommands()` (including the bare name after `skill:`), and the reserved polyphase names.\n * Invalid workflows are silently excluded: they are already diagnosed by `discoverSavedWorkflows`.\n */\nexport function planSavedWorkflowCommands(\n\tworkflows: readonly SavedWorkflow[],\n\texisting: { builtin: readonly string[]; commands: readonly SlashCommandInfo[]; reserved: readonly string[] },\n): SavedCommandPlan {\n\tconst builtinNames = new Set(existing.builtin);\n\tconst reservedNames = new Set(existing.reserved);\n\tconst commandNames = new Set<string>();\n\tfor (const command of existing.commands) {\n\t\tcommandNames.add(command.name);\n\t\tif (command.name.startsWith(\"skill:\")) commandNames.add(command.name.slice(\"skill:\".length));\n\t}\n\n\tconst register: SavedWorkflow[] = [];\n\tconst skipped: SavedCommandPlan[\"skipped\"] = [];\n\tconst claimed = new Set<string>();\n\n\tfor (const workflow of workflows) {\n\t\tif (!workflow.valid) continue;\n\t\tconst name = workflow.name;\n\t\tif (builtinNames.has(name)) {\n\t\t\tskipped.push({ workflow, reason: \"conflicts with a built-in command\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (reservedNames.has(name)) {\n\t\t\tskipped.push({ workflow, reason: \"is a reserved polyphase command name\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (commandNames.has(name) || claimed.has(name)) {\n\t\t\tskipped.push({ workflow, reason: \"conflicts with an existing command\" });\n\t\t\tcontinue;\n\t\t}\n\t\tclaimed.add(name);\n\t\tregister.push(workflow);\n\t}\n\n\treturn { register, skipped };\n}\n\n/** Called at `session_start`: registers `/<name>` for every planned saved workflow. */\nexport function registerSavedWorkflowCommands(deps: PolyphaseCommandDeps, plan: SavedCommandPlan): void {\n\tfor (const workflow of plan.register) {\n\t\tdeps.pi.registerCommand(workflow.name, {\n\t\t\tdescription: workflow.description,\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tawait runSavedWorkflowFromCommand(deps, workflow.name, args.trim(), ctx);\n\t\t\t},\n\t\t});\n\t}\n}\n\n/** `/<name> [args]` and `/workflow <name> [args]` (§15.3): gate, approve, start, report back. */\nexport async function runSavedWorkflowFromCommand(\n\tdeps: PolyphaseCommandDeps,\n\tname: string,\n\targs: string,\n\tctx: ExtensionCommandContext,\n): Promise<void> {\n\tconst discovery = discoverSavedWorkflows(discoveryOptions(ctx));\n\tconst workflow = discovery.workflows.find((candidate) => candidate.name === name);\n\tif (!workflow) {\n\t\tconst available = discovery.workflows.map((candidate) => candidate.name).join(\", \");\n\t\tctx.ui.notify(`Unknown saved workflow \"${name}\". Available: ${available || \"(none)\"}`, \"error\");\n\t\treturn;\n\t}\n\tif (!workflow.valid) {\n\t\tctx.ui.notify(\n\t\t\t`Saved workflow \"${name}\" has an invalid meta block: ${workflow.error ?? \"unknown error\"}`,\n\t\t\t\"error\",\n\t\t);\n\t\treturn;\n\t}\n\n\tlet source: string;\n\ttry {\n\t\tsource = readSavedWorkflowSource(workflow);\n\t} catch (error) {\n\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\treturn;\n\t}\n\n\tconst extraction = extractWorkflowMeta(source);\n\tif (!extraction.ok) {\n\t\tctx.ui.notify(\n\t\t\t`Saved workflow \"${name}\" has an invalid meta block at line ${extraction.error.line}: ${extraction.error.message}`,\n\t\t\t\"error\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst session = deps.getSession(ctx);\n\tconst settings = session.settings();\n\n\tconst gate = new PermissionGate(loadPermissionRules(ctx.cwd, ctx.isProjectTrusted()), {\n\t\tcwd: ctx.cwd,\n\t\tmode: session.permissionMode(),\n\t});\n\tconst decision = gate.evaluate(\"workflow\", { name, args });\n\n\tif (decision.action === \"deny\") {\n\t\tctx.ui.notify(decision.reason, \"error\");\n\t\treturn;\n\t}\n\n\tif (decision.action === \"approve\") {\n\t\tif (!ctx.hasUI) {\n\t\t\tctx.ui.notify(`Workflow ${name} needs approval but no UI is available; use /yolo or an allow rule`, \"error\");\n\t\t\treturn;\n\t\t}\n\t\tsession.notifyParentPrompt();\n\t\tconst approvalContext: ApprovalContext = {\n\t\t\tcwd: ctx.cwd,\n\t\t\tprojectTrusted: ctx.isProjectTrusted(),\n\t\t\tagentDir: getAgentDir(),\n\t\t\tlimits: {\n\t\t\t\tconcurrency: settings.maxConcurrency,\n\t\t\t\tmaxAgents: settings.maxAgentsPerRun,\n\t\t\t\tbudgetTokens: settings.defaultBudgetTokens,\n\t\t\t},\n\t\t};\n\t\tconst description = describeToolCallForApproval(\"workflow\", { name, args }, approvalContext);\n\t\tconst title = description?.title ?? `Run workflow \"${name}\"?`;\n\t\tconst message = description?.message ?? extraction.meta.description;\n\t\tconst approved = await ctx.ui.confirm(title, message);\n\t\tif (!approved) {\n\t\t\tctx.ui.notify(`Workflow ${name} not started`, \"info\");\n\t\t\treturn;\n\t\t}\n\t\t// A session_shutdown can run while the confirm dialog is open (e.g. an RPC new_session or\n\t\t// switch_session); the disposed session's store/limiter have already cancelled and rejected\n\t\t// everything, and nothing is left to cancel a run started on it afterwards.\n\t\tif (session.disposed) return;\n\t}\n\n\tconst handle = startWorkflowRun({\n\t\tctx,\n\t\tsession,\n\t\tid: `cmd-${randomUUID()}`,\n\t\torigin: \"command\",\n\t\tparentSignal: undefined,\n\t\tmeta: extraction.meta,\n\t\tbody: extraction.body,\n\t\targs,\n\t\tsource: { kind: workflow.source, path: workflow.path },\n\t\tbudgetTokens: settings.defaultBudgetTokens,\n\t\trunner: deps.runner,\n\t});\n\n\tconst reportCompletion = (completion: WorkflowRunCompletion): void => {\n\t\tif (session.disposed) return;\n\t\ttry {\n\t\t\tdeps.pi.sendMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: \"polyphase-workflow\",\n\t\t\t\t\tcontent: [{ type: \"text\", text: completion.text }],\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: completion.details,\n\t\t\t\t},\n\t\t\t\t{ triggerTurn: false },\n\t\t\t);\n\t\t} catch {\n\t\t\t// The extension runtime can go stale concurrently (e.g. a session shutdown that raced\n\t\t\t// this report); the run already finished and was recorded, so dropping the message here\n\t\t\t// is safe and must never surface as an unhandled rejection.\n\t\t}\n\t};\n\n\tconst inspectorHint = keyDisplayText(\"app.polyphase.inspector\");\n\tctx.ui.notify(`Started workflow ${name}${inspectorHint ? ` · ${inspectorHint} to inspect` : \"\"}`, \"info\");\n\n\t// print/json have no inspector and no later agent turn to pick up a background report, and\n\t// disposing the runtime right after this handler returns (print mode) would cancel the run\n\t// before it ever reports (§19): await it instead of firing and forgetting.\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\tconst completion = await handle.done;\n\t\treportCompletion(completion);\n\t\treturn;\n\t}\n\n\tvoid handle.done.then(reportCompletion);\n}\n\n/** `/workflow` and `/workflows` (factory body, registered once per extension instance). */\nexport function registerWorkflowCommands(deps: PolyphaseCommandDeps): void {\n\tdeps.pi.registerCommand(\"workflow\", {\n\t\tdescription: \"Run a saved workflow, or describe a new one. Usage: /workflow [name] [args]\",\n\t\tgetArgumentCompletions: (partial) => {\n\t\t\treturn deps\n\t\t\t\t.getSavedWorkflows()\n\t\t\t\t.filter((workflow) => workflow.name.startsWith(partial))\n\t\t\t\t.map((workflow) => ({ value: workflow.name, label: describeSavedWorkflow(workflow) }));\n\t\t},\n\t\thandler: async (args, ctx) => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tif (trimmed) {\n\t\t\t\tconst match = /\\s/.exec(trimmed);\n\t\t\t\tconst name = match ? trimmed.slice(0, match.index) : trimmed;\n\t\t\t\tconst workflowArgs = match ? trimmed.slice(match.index + 1).trim() : \"\";\n\t\t\t\tawait runSavedWorkflowFromCommand(deps, name, workflowArgs, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst discovery = discoverSavedWorkflows(discoveryOptions(ctx));\n\t\t\tif (ctx.mode === \"tui\" && ctx.hasUI) {\n\t\t\t\tconst describeNew = \"Describe a new workflow…\";\n\t\t\t\tconst options = [...discovery.workflows.map(describeSavedWorkflow), describeNew];\n\t\t\t\tconst choice = await ctx.ui.select(\"Run a workflow\", options);\n\t\t\t\tif (choice === undefined) return;\n\t\t\t\tif (choice === describeNew) {\n\t\t\t\t\tctx.ui.setEditorText(`${deps.keyword()} `);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst index = options.indexOf(choice);\n\t\t\t\tconst workflow = discovery.workflows[index];\n\t\t\t\tif (workflow) await runSavedWorkflowFromCommand(deps, workflow.name, \"\", ctx);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst lines = [\n\t\t\t\t...discovery.workflows.map(\n\t\t\t\t\t(workflow) =>\n\t\t\t\t\t\t`${workflow.name} (${workflow.source}${workflow.valid ? \"\" : \", invalid\"}) — ${workflow.description}`,\n\t\t\t\t),\n\t\t\t\t...discovery.diagnostics.map((diagnostic) => diagnostic.message),\n\t\t\t];\n\t\t\tctx.ui.notify(lines.length > 0 ? lines.join(\"\\n\") : \"No saved workflows found.\", \"info\");\n\t\t},\n\t});\n\n\tdeps.pi.registerCommand(\"workflows\", {\n\t\tdescription: \"List workflow runs and saved workflows, or open the inspector. Usage: /workflows [list]\",\n\t\thandler: async (args, ctx) => {\n\t\t\tif (args.trim() !== \"list\" && ctx.mode === \"tui\" && ctx.hasUI) {\n\t\t\t\tdeps.getUi()?.openInspector({ view: \"runs\" });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst session = deps.getSession(ctx);\n\t\t\tconst runs = session.store.runs();\n\t\t\tconst liveRunIds = new Set(runs.map((run) => run.id));\n\t\t\tconst archived = collectArchivedRuns(ctx.sessionManager.getBranch(), liveRunIds);\n\t\t\tconst discovery = discoverSavedWorkflows(discoveryOptions(ctx));\n\n\t\t\tconst lines = [\n\t\t\t\t...runs.map((run) => `${run.status}: ${run.title}`),\n\t\t\t\t...archived.map((entry) => `${entry.details.status}: ${entry.details.title}`),\n\t\t\t\t...discovery.workflows.map(describeSavedWorkflow),\n\t\t\t];\n\t\t\tctx.ui.notify(lines.length > 0 ? lines.join(\"\\n\") : \"No workflow runs.\", \"info\");\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"commands.js","sourceRoot":"","sources":["../../../src/core/polyphase/commands.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,wDAAwD,CAAC;AACxF,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAwB,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAClF,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAKnD,OAAO,EAAE,gBAAgB,EAA8B,MAAM,sBAAsB,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC3G,OAAO,EAAE,mBAAmB,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AAM,KAAK,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;gBAC7E,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,qBAAqB,CAAC;aACjD,CAAC;YACF,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;QAClF,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `/workflow`, `/workflows` and the per-saved-workflow `/<name>` commands (§16.2), plus the\n * command-path approval flow (§15.3). Saved workflow runs started this way are host-side: they\n * are independent of agent turns and report back with a non-triggering custom message.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { keyDisplayText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { loadPermissionRules } from \"../builtins/subagent.ts\";\nimport type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from \"../extensions/types.ts\";\nimport { PermissionGate } from \"../multi-agent/index.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport { isValidUsage } from \"../usage-totals.ts\";\nimport { type ApprovalContext, describeToolCallForApproval } from \"./approval.ts\";\nimport { collectArchivedRuns } from \"./details.ts\";\nimport type { PolyphaseSession } from \"./session.ts\";\nimport type { PolyphaseRun } from \"./store.ts\";\nimport type { AgentRunner } from \"./types.ts\";\nimport type { PolyphaseUiController } from \"./ui/controller.ts\";\nimport { startWorkflowRun, type WorkflowRunCompletion } from \"./workflow/launch.ts\";\nimport { parsePromptDirectives, resolveWorkflowLimits, stripPromptDirectives } from \"./workflow/limits.ts\";\nimport { extractWorkflowMeta } from \"./workflow/meta.ts\";\nimport {\n\tdiscoverSavedWorkflows,\n\treadSavedWorkflowSource,\n\ttype SavedDiscoveryOptions,\n\ttype SavedWorkflow,\n} from \"./workflow/saved.ts\";\n\nexport interface PolyphaseCommandDeps {\n\tpi: ExtensionAPI;\n\tgetSession(ctx: ExtensionContext): PolyphaseSession;\n\tgetUi(): PolyphaseUiController | undefined;\n\trunner?: AgentRunner;\n\tkeyword(): string;\n\t/** The most recent discovery result, refreshed at every `session_start`. */\n\tgetSavedWorkflows(): readonly SavedWorkflow[];\n}\n\nexport interface SavedCommandPlan {\n\tregister: SavedWorkflow[];\n\tskipped: Array<{ workflow: SavedWorkflow; reason: string }>;\n}\n\nfunction discoveryOptions(ctx: ExtensionContext): SavedDiscoveryOptions {\n\treturn { cwd: ctx.cwd, agentDir: getAgentDir(), projectTrusted: ctx.isProjectTrusted() };\n}\n\nfunction describeSavedWorkflow(workflow: SavedWorkflow): string {\n\treturn `${workflow.name} — ${workflow.description}`;\n}\n\n/**\n * Collision check for every valid saved workflow name against `BUILTIN_SLASH_COMMANDS`,\n * `pi.getCommands()` (including the bare name after `skill:`), and the reserved polyphase names.\n * Invalid workflows are silently excluded: they are already diagnosed by `discoverSavedWorkflows`.\n */\nexport function planSavedWorkflowCommands(\n\tworkflows: readonly SavedWorkflow[],\n\texisting: { builtin: readonly string[]; commands: readonly SlashCommandInfo[]; reserved: readonly string[] },\n): SavedCommandPlan {\n\tconst builtinNames = new Set(existing.builtin);\n\tconst reservedNames = new Set(existing.reserved);\n\tconst commandNames = new Set<string>();\n\tfor (const command of existing.commands) {\n\t\tcommandNames.add(command.name);\n\t\tif (command.name.startsWith(\"skill:\")) commandNames.add(command.name.slice(\"skill:\".length));\n\t}\n\n\tconst register: SavedWorkflow[] = [];\n\tconst skipped: SavedCommandPlan[\"skipped\"] = [];\n\tconst claimed = new Set<string>();\n\n\tfor (const workflow of workflows) {\n\t\tif (!workflow.valid) continue;\n\t\tconst name = workflow.name;\n\t\tif (builtinNames.has(name)) {\n\t\t\tskipped.push({ workflow, reason: \"conflicts with a built-in command\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (reservedNames.has(name)) {\n\t\t\tskipped.push({ workflow, reason: \"is a reserved polyphase command name\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (commandNames.has(name) || claimed.has(name)) {\n\t\t\tskipped.push({ workflow, reason: \"conflicts with an existing command\" });\n\t\t\tcontinue;\n\t\t}\n\t\tclaimed.add(name);\n\t\tregister.push(workflow);\n\t}\n\n\treturn { register, skipped };\n}\n\n/** Called at `session_start`: registers `/<name>` for every planned saved workflow. */\nexport function registerSavedWorkflowCommands(deps: PolyphaseCommandDeps, plan: SavedCommandPlan): void {\n\tfor (const workflow of plan.register) {\n\t\tdeps.pi.registerCommand(workflow.name, {\n\t\t\tdescription: workflow.description,\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tawait runSavedWorkflowFromCommand(deps, workflow.name, args.trim(), ctx);\n\t\t\t},\n\t\t});\n\t}\n}\n\n/** `/<name> [args]` and `/workflow <name> [args]` (§15.3): gate, approve, start, report back. */\nexport async function runSavedWorkflowFromCommand(\n\tdeps: PolyphaseCommandDeps,\n\tname: string,\n\targs: string,\n\tctx: ExtensionCommandContext,\n): Promise<void> {\n\tconst discovery = discoverSavedWorkflows(discoveryOptions(ctx));\n\tconst workflow = discovery.workflows.find((candidate) => candidate.name === name);\n\tif (!workflow) {\n\t\tconst available = discovery.workflows.map((candidate) => candidate.name).join(\", \");\n\t\tctx.ui.notify(`Unknown saved workflow \"${name}\". Available: ${available || \"(none)\"}`, \"error\");\n\t\treturn;\n\t}\n\tif (!workflow.valid) {\n\t\tctx.ui.notify(\n\t\t\t`Saved workflow \"${name}\" has an invalid meta block: ${workflow.error ?? \"unknown error\"}`,\n\t\t\t\"error\",\n\t\t);\n\t\treturn;\n\t}\n\n\tlet source: string;\n\ttry {\n\t\tsource = readSavedWorkflowSource(workflow);\n\t} catch (error) {\n\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\treturn;\n\t}\n\n\tconst extraction = extractWorkflowMeta(source);\n\tif (!extraction.ok) {\n\t\tctx.ui.notify(\n\t\t\t`Saved workflow \"${name}\" has an invalid meta block at line ${extraction.error.line}: ${extraction.error.message}`,\n\t\t\t\"error\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst session = deps.getSession(ctx);\n\tconst settings = session.settings();\n\n\t// D-B: a `+500k`/`+30min`-style directive is parsed straight from this command's own args (the\n\t// user's literal input), not the session's pending-prompt state, and stripped before the rest\n\t// of this handler (gate, approval, the script) ever sees it.\n\tconst promptDirectives = parsePromptDirectives(args);\n\tconst strippedArgs = stripPromptDirectives(args);\n\tconst limits = resolveWorkflowLimits({\n\t\tprompt: promptDirectives,\n\t\tconfig: {\n\t\t\tbudgetTokens: settings.defaultBudgetTokens,\n\t\t\ttimeLimitMs: settings.workflowTimeoutMs > 0 ? settings.workflowTimeoutMs : null,\n\t\t},\n\t});\n\n\tconst gate = new PermissionGate(loadPermissionRules(ctx.cwd, ctx.isProjectTrusted()), {\n\t\tcwd: ctx.cwd,\n\t\tmode: session.permissionMode(),\n\t});\n\tconst decision = gate.evaluate(\"workflow\", { name, args: strippedArgs });\n\n\tif (decision.action === \"deny\") {\n\t\tctx.ui.notify(decision.reason, \"error\");\n\t\treturn;\n\t}\n\n\tif (decision.action === \"approve\") {\n\t\tif (!ctx.hasUI) {\n\t\t\tctx.ui.notify(\n\t\t\t\t`Workflow ${name} needs approval but no UI is available (${decision.reason}); add an allow rule to permissions.yml, or start with DRAHT_PERMISSION_MODE=auto (yolo if a rule asks for approval)`,\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tsession.notifyParentPrompt();\n\t\tconst approvalContext: ApprovalContext = {\n\t\t\tcwd: ctx.cwd,\n\t\t\tprojectTrusted: ctx.isProjectTrusted(),\n\t\t\tagentDir: getAgentDir(),\n\t\t\tlimits: {\n\t\t\t\tconcurrency: settings.maxConcurrency,\n\t\t\t\tmaxAgents: settings.maxAgentsPerRun,\n\t\t\t\tbudgetTokens: settings.defaultBudgetTokens,\n\t\t\t\ttimeLimitMs: settings.workflowTimeoutMs > 0 ? settings.workflowTimeoutMs : null,\n\t\t\t},\n\t\t\tpromptDirectives,\n\t\t};\n\t\tconst description = describeToolCallForApproval(\"workflow\", { name, args: strippedArgs }, approvalContext);\n\t\tconst title = description?.title ?? `Run workflow \"${name}\"?`;\n\t\tconst message = description?.message ?? extraction.meta.description;\n\t\tconst approved = await ctx.ui.confirm(title, message);\n\t\tif (!approved) {\n\t\t\tctx.ui.notify(`Workflow ${name} not started`, \"info\");\n\t\t\treturn;\n\t\t}\n\t\t// A session_shutdown can run while the confirm dialog is open (e.g. an RPC new_session or\n\t\t// switch_session); the disposed session's store/limiter have already cancelled and rejected\n\t\t// everything, and nothing is left to cancel a run started on it afterwards.\n\t\tif (session.disposed) return;\n\t}\n\n\tconst handle = startWorkflowRun({\n\t\tctx,\n\t\tsession,\n\t\tid: `cmd-${randomUUID()}`,\n\t\torigin: \"command\",\n\t\tparentSignal: undefined,\n\t\tmeta: extraction.meta,\n\t\tbody: extraction.body,\n\t\targs: strippedArgs,\n\t\tsource: { kind: workflow.source, path: workflow.path },\n\t\tlimits,\n\t\trunner: deps.runner,\n\t});\n\n\tconst reportCompletion = (completion: WorkflowRunCompletion): void => {\n\t\tif (session.disposed) return;\n\t\trecordCommandRunUsage(deps.pi, name, handle.run);\n\t\ttry {\n\t\t\tdeps.pi.sendMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: \"polyphase-workflow\",\n\t\t\t\t\tcontent: [{ type: \"text\", text: completion.text }],\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: completion.details,\n\t\t\t\t},\n\t\t\t\t{ triggerTurn: false },\n\t\t\t);\n\t\t} catch {\n\t\t\t// The extension runtime can go stale concurrently (e.g. a session shutdown that raced\n\t\t\t// this report); the run already finished and was recorded, so dropping the message here\n\t\t\t// is safe and must never surface as an unhandled rejection.\n\t\t}\n\t};\n\n\tconst inspectorHint = keyDisplayText(\"app.polyphase.inspector\");\n\tctx.ui.notify(`Started workflow ${name}${inspectorHint ? ` · ${inspectorHint} to inspect` : \"\"}`, \"info\");\n\n\t// print/json have no inspector and no later agent turn to pick up a background report, and\n\t// disposing the runtime right after this handler returns (print mode) would cancel the run\n\t// before it ever reports (§19): await it instead of firing and forgetting.\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\tconst completion = await handle.done;\n\t\treportCompletion(completion);\n\t\treturn;\n\t}\n\n\tvoid handle.done.then(reportCompletion);\n}\n\n/**\n * Attributes a finished command-run's cost to its agents' models. One usage\n * entry per agent that reported any usage, kind `\"polyphase\"`, note `/<name> <label>`. An agent\n * whose model was never confirmed by the child is recorded as provider `\"unknown\"` with the\n * requested model string, rather than the parent's unconfirmed guess. Tool-origin runs report\n * their own usage through the tool result and must not reach this function (no double counting).\n */\nfunction recordCommandRunUsage(pi: ExtensionAPI, workflowName: string, run: PolyphaseRun): void {\n\tfor (const agent of run.agents) {\n\t\tconst usage = agent.state.usage;\n\t\tif (!usage || !isValidUsage(usage)) continue;\n\t\tconst model = agent.state.model;\n\t\tconst provider = model.confirmed && model.provider ? model.provider : \"unknown\";\n\t\tconst modelId = model.confirmed && model.id ? model.id : (model.requested ?? \"unknown\");\n\t\ttry {\n\t\t\tpi.appendUsage(\"polyphase\", provider, modelId, usage, `/${workflowName} ${agent.label}`);\n\t\t} catch {\n\t\t\t// The extension ctx can go stale concurrently (e.g. a session shutdown that raced this\n\t\t\t// report); the run already finished, so dropping the usage entry here is safe.\n\t\t}\n\t}\n}\n\n/** `/workflow` and `/workflows` (factory body, registered once per extension instance). */\nexport function registerWorkflowCommands(deps: PolyphaseCommandDeps): void {\n\tdeps.pi.registerCommand(\"workflow\", {\n\t\tdescription: \"Run a saved workflow, or describe a new one. Usage: /workflow [name] [args]\",\n\t\tgetArgumentCompletions: (partial) => {\n\t\t\treturn deps\n\t\t\t\t.getSavedWorkflows()\n\t\t\t\t.filter((workflow) => workflow.name.startsWith(partial))\n\t\t\t\t.map((workflow) => ({ value: workflow.name, label: describeSavedWorkflow(workflow) }));\n\t\t},\n\t\thandler: async (args, ctx) => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tif (trimmed) {\n\t\t\t\tconst match = /\\s/.exec(trimmed);\n\t\t\t\tconst name = match ? trimmed.slice(0, match.index) : trimmed;\n\t\t\t\tconst workflowArgs = match ? trimmed.slice(match.index + 1).trim() : \"\";\n\t\t\t\tawait runSavedWorkflowFromCommand(deps, name, workflowArgs, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst discovery = discoverSavedWorkflows(discoveryOptions(ctx));\n\t\t\tif (ctx.mode === \"tui\" && ctx.hasUI) {\n\t\t\t\tconst describeNew = \"Describe a new workflow…\";\n\t\t\t\tconst options = [...discovery.workflows.map(describeSavedWorkflow), describeNew];\n\t\t\t\tconst choice = await ctx.ui.select(\"Run a workflow\", options);\n\t\t\t\tif (choice === undefined) return;\n\t\t\t\tif (choice === describeNew) {\n\t\t\t\t\tctx.ui.setEditorText(`${deps.keyword()} `);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst index = options.indexOf(choice);\n\t\t\t\tconst workflow = discovery.workflows[index];\n\t\t\t\tif (workflow) await runSavedWorkflowFromCommand(deps, workflow.name, \"\", ctx);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst lines = [\n\t\t\t\t...discovery.workflows.map(\n\t\t\t\t\t(workflow) =>\n\t\t\t\t\t\t`${workflow.name} (${workflow.source}${workflow.valid ? \"\" : \", invalid\"}) — ${workflow.description}`,\n\t\t\t\t),\n\t\t\t\t...discovery.diagnostics.map((diagnostic) => diagnostic.message),\n\t\t\t];\n\t\t\tctx.ui.notify(lines.length > 0 ? lines.join(\"\\n\") : \"No saved workflows found.\", \"info\");\n\t\t},\n\t});\n\n\tdeps.pi.registerCommand(\"workflows\", {\n\t\tdescription: \"List workflow runs and saved workflows, or open the inspector. Usage: /workflows [list]\",\n\t\thandler: async (args, ctx) => {\n\t\t\tif (args.trim() !== \"list\" && ctx.mode === \"tui\" && ctx.hasUI) {\n\t\t\t\tdeps.getUi()?.openInspector({ view: \"runs\" });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst session = deps.getSession(ctx);\n\t\t\tconst runs = session.store.runs();\n\t\t\tconst liveRunIds = new Set(runs.map((run) => run.id));\n\t\t\tconst archived = collectArchivedRuns(ctx.sessionManager.getBranch(), liveRunIds);\n\t\t\tconst discovery = discoverSavedWorkflows(discoveryOptions(ctx));\n\n\t\t\tconst lines = [\n\t\t\t\t...runs.map((run) => `${run.status}: ${run.title}`),\n\t\t\t\t...archived.map((entry) => `${entry.details.status}: ${entry.details.title}`),\n\t\t\t\t...discovery.workflows.map(describeSavedWorkflow),\n\t\t\t];\n\t\t\tctx.ui.notify(lines.length > 0 ? lines.join(\"\\n\") : \"No workflow runs.\", \"info\");\n\t\t},\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"details.d.ts","sourceRoot":"","sources":["../../../src/core/polyphase/details.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAI1D,OAAO,KAAK,EAMX,gBAAgB,EAChB,OAAO,EACP,MAAM,YAAY,CAAC;AAqcpB;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAC1D,gBAAgB,CAWlB;AAoBD;;;qGAGqG;AACrG,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,gBAAgB,CAe5E;AAED,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,MAA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EAAE,EAChC,UAAU,EAAE,WAAW,CAAC,MAAM,CAAC,EAC/B,KAAK,SAAK,GACR,WAAW,EAAE,CASf;AAED,uDAAuD;AACvD,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,GAAG,KAAK,GAAG,SAAS,CAQ3D"}
@@ -331,6 +331,8 @@ function buildAtLevel(run, plan, ctx, statusLines) {
331
331
  source: run.workflow.source,
332
332
  ...(run.workflow.path !== undefined ? { path: truncateChars(run.workflow.path, plan.workflowPathMax) } : {}),
333
333
  args: truncateChars(run.workflow.args, plan.workflowArgsMax),
334
+ budgetSource: run.workflow.budgetSource,
335
+ timeLimitSource: run.workflow.timeLimitSource,
334
336
  };
335
337
  }
336
338
  if (run.phases.length > 0) {
@@ -351,6 +353,9 @@ function buildAtLevel(run, plan, ctx, statusLines) {
351
353
  exhausted: run.budget.exhausted,
352
354
  };
353
355
  }
356
+ if (run.timeLimit?.totalMs !== null && run.timeLimit?.totalMs !== undefined) {
357
+ details.timeLimit = { totalMs: run.timeLimit.totalMs, reached: run.timeLimit.reached };
358
+ }
354
359
  if (run.resultPreview !== undefined) {
355
360
  details.resultPreview = truncateChars(capHeadTail(run.resultPreview, plan.resultPreviewMax).text, plan.resultPreviewMax);
356
361
  }