pi-subagents 0.84.0 → 0.86.0

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 (210) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-JG4QKI5M.js → chunk-2IYBCYFU.js} +214 -97
  5. package/bundle/{chunk-V2BZYLEP.js → chunk-374MZFF4.js} +7 -2
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-3RKFH2UZ.js} +11 -156
  7. package/bundle/{chunk-F4ASL6OV.js → chunk-5H4BICQZ.js} +1 -1
  8. package/bundle/{chunk-PALJGGYC.js → chunk-6VD7BGIC.js} +6 -3
  9. package/bundle/{chunk-C5P5CHYK.js → chunk-77ASNIEM.js} +1 -1
  10. package/bundle/{chunk-XDQORLZ5.js → chunk-7ADDXUGF.js} +15 -6
  11. package/bundle/{chunk-PV63UFUR.js → chunk-7QA7ZA46.js} +183 -28
  12. package/bundle/{chunk-NKQ6JNAS.js → chunk-7ZUFN6ME.js} +2 -1
  13. package/bundle/{chunk-SSG7IEP5.js → chunk-A637IMAO.js} +2 -2
  14. package/bundle/{chunk-L3WFKBEI.js → chunk-BGXEAYUM.js} +247 -153
  15. package/bundle/{chunk-J5YL7LYR.js → chunk-BU6PFPVX.js} +59 -27
  16. package/bundle/{chunk-DZDETGRJ.js → chunk-BWC2LVII.js} +259 -216
  17. package/bundle/{chunk-CGN2TVE7.js → chunk-GJGTMLPE.js} +322 -18
  18. package/bundle/{chunk-D3JAFGMO.js → chunk-GRJHIXYF.js} +1 -1
  19. package/bundle/chunk-HXRB42AF.js +108 -0
  20. package/bundle/{chunk-LFDBD4PW.js → chunk-LGINOOY5.js} +2 -2
  21. package/bundle/{chunk-G2Z6ZH26.js → chunk-NAFLUJ26.js} +1 -1
  22. package/bundle/{chunk-235AWJUQ.js → chunk-O3YH7XIY.js} +324 -111
  23. package/bundle/{chunk-2DHZTCOL.js → chunk-PYOAIN3V.js} +2 -2
  24. package/bundle/{chunk-LNRJCP2Y.js → chunk-QGO6HXHG.js} +417 -242
  25. package/bundle/{chunk-VQVVHSY6.js → chunk-QM3JGE4W.js} +22 -11
  26. package/bundle/{chunk-2S4K53MV.js → chunk-S2Q75LP3.js} +1 -1
  27. package/bundle/{chunk-NENDSQUY.js → chunk-UR7OW5S7.js} +9 -6
  28. package/bundle/{chunk-AKOIVLA5.js → chunk-WN2E5XHN.js} +135 -77
  29. package/bundle/{chunk-2D52JFLF.js → chunk-YK3QYNLE.js} +41 -117
  30. package/bundle/{chunk-7BWGNDNK.js → chunk-ZJJCPV3L.js} +190 -1177
  31. package/bundle/chunk-ZPY5QZCS.js +1067 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +23 -2
  38. package/docs/configuration.md +4 -4
  39. package/docs/extension-api.md +16 -1
  40. package/docs/tool-reference.md +2 -0
  41. package/docs/workflows.md +30 -2
  42. package/package.json +1 -1
  43. package/src/agents/agent-management.js +27 -11
  44. package/src/agents/agent-memory.d.ts +1 -4
  45. package/src/agents/agent-memory.js +1 -4
  46. package/src/agents/agents.d.ts +1 -3
  47. package/src/agents/agents.js +7 -6
  48. package/src/agents/frontmatter.js +1 -8
  49. package/src/agents/global-npm-root.d.ts +1 -0
  50. package/src/agents/global-npm-root.js +11 -3
  51. package/src/agents/skills.d.ts +0 -3
  52. package/src/agents/skills.js +0 -3
  53. package/src/extension/config.js +7 -1
  54. package/src/extension/herdr-pi-bridge.js +10 -2
  55. package/src/extension/index.d.ts +0 -13
  56. package/src/extension/index.js +43 -32
  57. package/src/extension/public-execution.d.ts +1 -0
  58. package/src/extension/public-execution.js +4 -0
  59. package/src/extension/reply-workflow-script.js +24 -4
  60. package/src/extension/schemas.d.ts +8 -3
  61. package/src/extension/schemas.js +5 -3
  62. package/src/extension/session-switch.d.ts +25 -0
  63. package/src/extension/session-switch.js +138 -0
  64. package/src/extension/subagent-guide.d.ts +1 -1
  65. package/src/extension/subagent-guide.js +1 -1
  66. package/src/extension/subagent-launch-tool.d.ts +25 -0
  67. package/src/extension/subagent-launch-tool.js +48 -0
  68. package/src/extension/tool-activation.js +35 -12
  69. package/src/extension/tool-description.d.ts +1 -1
  70. package/src/extension/tool-description.js +14 -8
  71. package/src/inspectors/herdr/actions.d.ts +0 -1
  72. package/src/inspectors/herdr/actions.js +0 -1
  73. package/src/inspectors/session-roots-codec.d.ts +0 -1
  74. package/src/inspectors/session-roots-codec.js +0 -1
  75. package/src/inspectors/tmux/actions.d.ts +0 -1
  76. package/src/inspectors/tmux/actions.js +0 -1
  77. package/src/integrations/herdr-status.js +3 -8
  78. package/src/intercom/native-supervisor-channel.js +65 -9
  79. package/src/runs/background/async-execution.d.ts +5 -9
  80. package/src/runs/background/async-execution.js +62 -27
  81. package/src/runs/background/async-job-tracker.js +12 -0
  82. package/src/runs/background/async-resume.d.ts +2 -1
  83. package/src/runs/background/async-resume.js +112 -39
  84. package/src/runs/background/async-retention.js +6 -1
  85. package/src/runs/background/auto-drain.js +2 -1
  86. package/src/runs/background/boot-id.d.ts +1 -3
  87. package/src/runs/background/boot-id.js +1 -3
  88. package/src/runs/background/completion-batcher.d.ts +3 -4
  89. package/src/runs/background/completion-batcher.js +2 -3
  90. package/src/runs/background/control-channel.d.ts +0 -6
  91. package/src/runs/background/control-channel.js +0 -6
  92. package/src/runs/background/fleet-view.js +2 -3
  93. package/src/runs/background/notify.d.ts +0 -2
  94. package/src/runs/background/notify.js +0 -2
  95. package/src/runs/background/result-watcher.d.ts +1 -0
  96. package/src/runs/background/result-watcher.js +59 -29
  97. package/src/runs/background/resume-guidance.js +4 -2
  98. package/src/runs/background/retained-children.js +2 -1
  99. package/src/runs/background/run-child-session.d.ts +0 -1
  100. package/src/runs/background/run-child-session.js +1 -1
  101. package/src/runs/background/run-status.js +9 -7
  102. package/src/runs/background/scheduled-runs.d.ts +3 -1
  103. package/src/runs/background/scheduled-runs.js +13 -16
  104. package/src/runs/background/subagent-runner.d.ts +2 -4
  105. package/src/runs/background/subagent-runner.js +15 -12
  106. package/src/runs/background/subagent-wait.js +12 -15
  107. package/src/runs/background/wait-config.d.ts +2 -0
  108. package/src/runs/background/wait-config.js +17 -3
  109. package/src/runs/background/wait-tool.js +4 -2
  110. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  111. package/src/runs/background/workflow-terminal-proof.js +0 -1
  112. package/src/runs/foreground/execution.d.ts +0 -3
  113. package/src/runs/foreground/execution.js +17 -9
  114. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  115. package/src/runs/foreground/subagent-executor.js +107 -26
  116. package/src/runs/shared/acceptance.js +69 -26
  117. package/src/runs/shared/child-commands.js +15 -2
  118. package/src/runs/shared/child-hooks.d.ts +1 -7
  119. package/src/runs/shared/child-hooks.js +13 -5
  120. package/src/runs/shared/child-launch.js +6 -2
  121. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  122. package/src/runs/shared/child-session.d.ts +1 -1
  123. package/src/runs/shared/child-session.js +21 -2
  124. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  125. package/src/runs/shared/child-tool-plan.js +0 -1
  126. package/src/runs/shared/claude-code-adapter.js +11 -0
  127. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  128. package/src/runs/shared/external-cli-contract.js +18 -13
  129. package/src/runs/shared/external-cli-runner.js +26 -6
  130. package/src/runs/shared/herdr-connection.js +2 -1
  131. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  132. package/src/runs/shared/herdr-pane-host.js +17 -1
  133. package/src/runs/shared/herdr-placed-run.js +48 -22
  134. package/src/runs/shared/lane-metadata.d.ts +0 -1
  135. package/src/runs/shared/lane-metadata.js +0 -1
  136. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  137. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  138. package/src/runs/shared/model-resolution.d.ts +2 -2
  139. package/src/runs/shared/model-resolution.js +7 -1
  140. package/src/runs/shared/model-scope.d.ts +1 -5
  141. package/src/runs/shared/model-scope.js +1 -5
  142. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  143. package/src/runs/shared/mutation-evidence.js +52 -7
  144. package/src/runs/shared/nested-events.d.ts +1 -0
  145. package/src/runs/shared/nested-events.js +1 -1
  146. package/src/runs/shared/parallel-utils.d.ts +0 -1
  147. package/src/runs/shared/permissions.js +5 -3
  148. package/src/runs/shared/placement-host.d.ts +5 -1
  149. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  150. package/src/runs/shared/rex-pane-host.js +0 -2
  151. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  152. package/src/runs/shared/run-launch-folder.js +21 -0
  153. package/src/runs/shared/runner-launcher.d.ts +12 -1
  154. package/src/runs/shared/runner-launcher.js +16 -0
  155. package/src/runs/shared/single-output.d.ts +3 -3
  156. package/src/runs/shared/single-output.js +5 -3
  157. package/src/runs/shared/structured-output.d.ts +8 -0
  158. package/src/runs/shared/structured-output.js +40 -5
  159. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  160. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  161. package/src/runs/shared/tool-timeout.js +2 -1
  162. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  163. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  164. package/src/runs/shared/worktree.d.ts +3 -0
  165. package/src/runs/shared/worktree.js +20 -0
  166. package/src/shared/capacity-resilient-json.d.ts +1 -1
  167. package/src/shared/child-cache-retention.d.ts +1 -2
  168. package/src/shared/child-cache-retention.js +1 -2
  169. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  170. package/src/shared/fleet-transcript-reader.js +333 -0
  171. package/src/shared/formatters.d.ts +0 -18
  172. package/src/shared/formatters.js +0 -18
  173. package/src/shared/session-succession.d.ts +16 -1
  174. package/src/shared/session-succession.js +41 -2
  175. package/src/shared/session-warnings.d.ts +7 -0
  176. package/src/shared/session-warnings.js +26 -0
  177. package/src/shared/settings.d.ts +0 -23
  178. package/src/shared/settings.js +3 -35
  179. package/src/shared/types.d.ts +85 -59
  180. package/src/shared/types.js +0 -12
  181. package/src/shared/utils.d.ts +0 -14
  182. package/src/shared/utils.js +0 -22
  183. package/src/shared/wait-tool-name.d.ts +8 -0
  184. package/src/shared/wait-tool-name.js +13 -0
  185. package/src/slash/slash-commands.js +2 -1
  186. package/src/slash/subagent-cost.d.ts +3 -2
  187. package/src/slash/subagent-cost.js +22 -3
  188. package/src/slash/subagents-admin.js +0 -1
  189. package/src/tui/fleet-status.d.ts +0 -5
  190. package/src/tui/fleet-status.js +4 -24
  191. package/src/tui/fleet-transcript.d.ts +1 -44
  192. package/src/tui/fleet-transcript.js +1 -327
  193. package/src/tui/fleet.js +6 -4
  194. package/src/tui/render.d.ts +0 -9
  195. package/src/tui/render.js +161 -66
  196. package/src/tui/subagent-messages.js +3 -2
  197. package/src/watchdog/register-child.d.ts +2 -3
  198. package/src/watchdog/register-child.js +2 -3
  199. package/src/watchdog/turn-delta.js +2 -1
  200. package/src/workflows/scripted-workflow.js +241 -20
  201. package/src/workflows/workflow-launch-record.d.ts +15 -6
  202. package/src/workflows/workflow-launch-record.js +30 -12
  203. package/src/workflows/workflow-receipt.js +36 -53
  204. package/src/workflows/workflow-resume-claim.js +2 -2
  205. package/src/workflows/workflow-resume.d.ts +1 -1
  206. package/src/workflows/workflow-resume.js +11 -8
  207. package/src/workflows/workflow-script-worker.d.ts +13 -0
  208. package/src/workflows/workflow-script-worker.js +79 -0
  209. package/workflow-script-process.cjs +36 -0
  210. package/workflow-script-worker.cjs +4 -1
@@ -12,6 +12,11 @@ import {
12
12
  normalizeCapabilityCeilingAllowedAgents
13
13
  } from "./chunk-QXASAHIA.js";
14
14
 
15
+ // src/shared/atomic-json.ts
16
+ import { createHash } from "node:crypto";
17
+ import * as fs from "node:fs";
18
+ import * as path from "node:path";
19
+
15
20
  // src/shared/file-system-retry.ts
16
21
  var WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : void 0;
17
22
  var WAIT_VIEW = WAIT_BUFFER ? new Int32Array(WAIT_BUFFER) : void 0;
@@ -70,9 +75,6 @@ function runFileSystemOperationWithRetry(operation, options = {}) {
70
75
  }
71
76
 
72
77
  // src/shared/atomic-json.ts
73
- import { createHash } from "node:crypto";
74
- import * as fs from "node:fs";
75
- import * as path from "node:path";
76
78
  var MAX_PATH_COMPONENT_BYTES = 255;
77
79
  function renameWithRetry(fsImpl, sourcePath, targetPath, retryDelaysMs, wait) {
78
80
  runFileSystemOperationWithRetry(() => {
@@ -169,6 +171,14 @@ function validateCodeOwnedProfileRunner(agent) {
169
171
  }
170
172
  return void 0;
171
173
  }
174
+ var EXTERNAL_CLI_ADAPTER_SAFETY = {
175
+ "codex-exec": { sandbox: "read-only", approvalPolicy: "never", ephemeral: true },
176
+ "codex-exec-writer": { access: "workspace-write", sandbox: "workspace-write", approvalPolicy: "never", ephemeral: true },
177
+ "claude-code": { access: "read-only", authentication: "existing-cli-required", permissionMode: "plan", tools: "none", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false },
178
+ "claude-code-writer": { access: "workspace-write", authentication: "existing-cli-required", permissionMode: "acceptEdits", tools: "Read,Write,Edit,Glob,Grep", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false },
179
+ "cursor-agent": { access: "read-only", authentication: "cursor-api-key-or-existing-login", mode: "ask", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false },
180
+ "cursor-agent-writer": { access: "workspace-write", authentication: "cursor-api-key-or-existing-login", mode: "print", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false }
181
+ };
172
182
  function parseExternalCliCapabilityNarrowing(value, label) {
173
183
  if (value === void 0) return void 0;
174
184
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
@@ -181,13 +191,8 @@ function parseExternalCliCapabilityNarrowing(value, label) {
181
191
  return input;
182
192
  }
183
193
  function resolveExternalCliRunnerStatus(input) {
184
- const codexExec = input.adapter === "codex-exec";
185
- const codexExecWriter = input.adapter === "codex-exec-writer";
186
- const claudeCode = input.adapter === "claude-code";
187
- const claudeCodeWriter = input.adapter === "claude-code-writer";
188
- const cursorAgent = input.adapter === "cursor-agent";
189
- const cursorAgentWriter = input.adapter === "cursor-agent-writer";
190
- const cursor = cursorAgent || cursorAgentWriter;
194
+ const cursor = input.adapter === "cursor-agent" || input.adapter === "cursor-agent-writer";
195
+ const profileSafety = input.adapter ? EXTERNAL_CLI_ADAPTER_SAFETY[input.adapter] : void 0;
191
196
  const unsupported = cursor ? PROMPT_FILE_UNSUPPORTED : UNSUPPORTED;
192
197
  return {
193
198
  type: "external-cli",
@@ -195,12 +200,11 @@ function resolveExternalCliRunnerStatus(input) {
195
200
  args: input.args ?? [],
196
201
  promptDelivery: cursor ? "prompt-file" : input.promptDelivery ?? "stdin",
197
202
  adapter: { id: input.adapter ?? "external-cli", version: 1, executionMode: cursor ? "one-shot-prompt-file" : "one-shot-stdin" },
198
- ...codexExec ? { safety: { sandbox: "read-only", approvalPolicy: "never", ephemeral: true } } : {},
199
- ...codexExecWriter ? { safety: { access: "workspace-write", sandbox: "workspace-write", approvalPolicy: "never", ephemeral: true } } : {},
200
- ...claudeCode ? { safety: { access: "read-only", authentication: "existing-cli-required", permissionMode: "plan", tools: "none", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false } } : {},
201
- ...claudeCodeWriter ? { safety: { access: "workspace-write", authentication: "existing-cli-required", permissionMode: "acceptEdits", tools: "Read,Write,Edit,Glob,Grep", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false } } : {},
202
- ...cursorAgent ? { safety: { access: "read-only", authentication: "cursor-api-key-or-existing-login", mode: "ask", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false } } : {},
203
- ...cursorAgentWriter ? { safety: { access: "workspace-write", authentication: "cursor-api-key-or-existing-login", mode: "print", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false } } : {},
203
+ ...profileSafety ? {
204
+ safety: { ...profileSafety },
205
+ // A Herdr saved machine launches the remote adapter binary, never runner.command.
206
+ safetySource: { measured: false, ...input.machine ? {} : { command: input.command } }
207
+ } : {},
204
208
  ...input.machine ? { machine: input.machine } : {},
205
209
  capabilities: {
206
210
  stop: true,
@@ -248,6 +252,7 @@ function externalCliReceiptMetadata(input) {
248
252
  capabilities: { ...runner.capabilities },
249
253
  ...machine ? { machine: { ...machine, ...machine.remoteGit ? { remoteGit: { ...machine.remoteGit } } : {} } } : {},
250
254
  ...runner.safety ? { safety: { ...runner.safety } } : {},
255
+ ...runner.safetySource ? { safetySource: { ...runner.safetySource } } : {},
251
256
  ...input.externalProcess ? {
252
257
  outputArtifacts: {
253
258
  stdoutPath: input.externalProcess.stdoutPath,
@@ -263,9 +268,9 @@ function externalCliReceiptMetadata(input) {
263
268
 
264
269
  // src/agents/skills.ts
265
270
  import { execSync as execSync2 } from "node:child_process";
266
- import * as fs15 from "node:fs";
267
- import * as os6 from "node:os";
268
- import * as path16 from "node:path";
271
+ import * as fs16 from "node:fs";
272
+ import * as os7 from "node:os";
273
+ import * as path17 from "node:path";
269
274
  import { parse as parseYaml2 } from "yaml";
270
275
 
271
276
  // src/agents/frontmatter.ts
@@ -278,12 +283,12 @@ function foldBlock(block) {
278
283
  let previousIsMoreIndented = false;
279
284
  let blankLines = 0;
280
285
  for (const line of block.split("\n")) {
281
- const current = line.trimEnd();
282
- if (current.trim() === "") {
286
+ const current2 = line.trimEnd();
287
+ if (current2.trim() === "") {
283
288
  if (hasContent) blankLines++;
284
289
  continue;
285
290
  }
286
- const currentIsMoreIndented = current.length > current.trimStart().length;
291
+ const currentIsMoreIndented = current2.length > current2.trimStart().length;
287
292
  if (hasContent) {
288
293
  if (blankLines > 0) {
289
294
  folded += "\n".repeat(blankLines + (previousIsMoreIndented || currentIsMoreIndented ? 1 : 0));
@@ -291,7 +296,7 @@ function foldBlock(block) {
291
296
  folded += previousIsMoreIndented || currentIsMoreIndented ? "\n" : " ";
292
297
  }
293
298
  }
294
- folded += current;
299
+ folded += current2;
295
300
  hasContent = true;
296
301
  previousIsMoreIndented = currentIsMoreIndented;
297
302
  blankLines = 0;
@@ -392,15 +397,15 @@ function flushBlockLines(blockLines, folded, literal) {
392
397
  }
393
398
 
394
399
  // src/shared/utils.ts
400
+ import * as fs15 from "node:fs";
401
+ import * as os6 from "node:os";
402
+ import * as path16 from "node:path";
403
+
404
+ // src/shared/settings.ts
395
405
  import * as fs14 from "node:fs";
396
406
  import * as os5 from "node:os";
397
407
  import * as path15 from "node:path";
398
408
 
399
- // src/shared/settings.ts
400
- import * as fs13 from "node:fs";
401
- import * as os4 from "node:os";
402
- import * as path14 from "node:path";
403
-
404
409
  // src/agents/agents.ts
405
410
  import { execSync } from "node:child_process";
406
411
  import * as fs11 from "node:fs";
@@ -444,8 +449,8 @@ function deadOwner(owner) {
444
449
  } catch (error) {
445
450
  return error.code === "ESRCH";
446
451
  }
447
- const current = startIdentity(owner.pid);
448
- return owner.processStart !== void 0 && current !== void 0 && owner.processStart !== current;
452
+ const current2 = startIdentity(owner.pid);
453
+ return owner.processStart !== void 0 && current2 !== void 0 && owner.processStart !== current2;
449
454
  }
450
455
  function tryLease(lockPath) {
451
456
  const owner = { token: randomUUID(), pid: process.pid, hostname: os.hostname(), processStart: startIdentity(process.pid) };
@@ -579,7 +584,7 @@ async function waitUntilGroupTerminal(processGroupId, timeoutMs) {
579
584
  if (!Array.isArray(members)) return { state: "enumeration-failed", diagnostic: members.diagnostic };
580
585
  return { state: "still-active", diagnostic: `Process group ${processGroupId} still has active members: ${members.join(", ")}.` };
581
586
  }
582
- await new Promise((resolve11) => setTimeout(resolve11, Math.min(VERIFY_INTERVAL_MS, remaining)));
587
+ await new Promise((resolve12) => setTimeout(resolve12, Math.min(VERIFY_INTERVAL_MS, remaining)));
583
588
  }
584
589
  }
585
590
  function observed(processGroupId) {
@@ -636,36 +641,36 @@ var MAX_EXTENSION_BINDINGS_BYTES = 16 * 1024;
636
641
  var MAX_EXTENSION_BINDINGS_DEPTH = 16;
637
642
  var MAX_EXTENSION_BINDINGS_PROPERTIES = 256;
638
643
  var EXTENSION_BINDING_NAMESPACE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62})\/[1-9][0-9]{0,8}$/;
639
- function canonicalizeJson(value, path17, depth, seen, propertyCount) {
644
+ function canonicalizeJson(value, path18, depth, seen, propertyCount) {
640
645
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
641
646
  if (typeof value === "number") {
642
- if (!Number.isFinite(value)) throw new Error(`${path17} must contain only finite JSON numbers.`);
647
+ if (!Number.isFinite(value)) throw new Error(`${path18} must contain only finite JSON numbers.`);
643
648
  return value;
644
649
  }
645
- if (typeof value !== "object") throw new Error(`${path17} must contain only plain JSON values.`);
646
- if (depth > MAX_EXTENSION_BINDINGS_DEPTH) throw new Error(`${path17} exceeds the maximum nesting depth of ${MAX_EXTENSION_BINDINGS_DEPTH}.`);
647
- if (seen.has(value)) throw new Error(`${path17} must not contain cycles.`);
650
+ if (typeof value !== "object") throw new Error(`${path18} must contain only plain JSON values.`);
651
+ if (depth > MAX_EXTENSION_BINDINGS_DEPTH) throw new Error(`${path18} exceeds the maximum nesting depth of ${MAX_EXTENSION_BINDINGS_DEPTH}.`);
652
+ if (seen.has(value)) throw new Error(`${path18} must not contain cycles.`);
648
653
  seen.add(value);
649
654
  try {
650
655
  if (Array.isArray(value)) {
651
656
  const output2 = [];
652
657
  for (let index = 0; index < value.length; index++) {
653
- if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(`${path17} must not contain sparse arrays.`);
654
- output2.push(canonicalizeJson(value[index], `${path17}[${index}]`, depth + 1, seen, propertyCount));
658
+ if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(`${path18} must not contain sparse arrays.`);
659
+ output2.push(canonicalizeJson(value[index], `${path18}[${index}]`, depth + 1, seen, propertyCount));
655
660
  }
656
661
  return Object.freeze(output2);
657
662
  }
658
663
  const prototype = Object.getPrototypeOf(value);
659
- if (prototype !== Object.prototype && prototype !== null) throw new Error(`${path17} must contain only plain JSON objects.`);
660
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path17} must not contain symbol keys.`);
664
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${path18} must contain only plain JSON objects.`);
665
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path18} must not contain symbol keys.`);
661
666
  const descriptors = Object.getOwnPropertyDescriptors(value);
662
667
  const output = {};
663
668
  for (const key of Object.keys(descriptors).sort()) {
664
669
  const descriptor = descriptors[key];
665
- if (!descriptor.enumerable || !("value" in descriptor)) throw new Error(`${path17}.${key} must be an enumerable data property.`);
670
+ if (!descriptor.enumerable || !("value" in descriptor)) throw new Error(`${path18}.${key} must be an enumerable data property.`);
666
671
  propertyCount.value += 1;
667
672
  if (propertyCount.value > MAX_EXTENSION_BINDINGS_PROPERTIES) throw new Error(`extensionBindings exceeds ${MAX_EXTENSION_BINDINGS_PROPERTIES} total properties.`);
668
- Object.defineProperty(output, key, { value: canonicalizeJson(descriptor.value, `${path17}.${key}`, depth + 1, seen, propertyCount), enumerable: true, writable: false, configurable: false });
673
+ Object.defineProperty(output, key, { value: canonicalizeJson(descriptor.value, `${path18}.${key}`, depth + 1, seen, propertyCount), enumerable: true, writable: false, configurable: false });
669
674
  }
670
675
  return Object.freeze(output);
671
676
  } finally {
@@ -792,7 +797,7 @@ var MAX_RAW_LOG_BYTES = 8 * 1024 * 1024;
792
797
  var MAX_PARSER_LINE_BYTES = 256 * 1024;
793
798
  var MAX_PARSER_STREAM_BYTES = 32 * 1024 * 1024;
794
799
  var MAX_PARSER_OUTPUT_BYTES = 1024 * 1024;
795
- var MAX_SKIPPABLE_LINE_BYTES = 1024 * 1024;
800
+ var MAX_SKIPPABLE_LINE_BYTES = 8 * 1024 * 1024;
796
801
 
797
802
  // src/shared/model-info.ts
798
803
  var THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
@@ -1400,14 +1405,14 @@ function readPiPackageJson(packageJsonPath, readFileSync11 = (filePath, encoding
1400
1405
  }
1401
1406
  function selectPiPackage(deps) {
1402
1407
  const existsSync10 = deps.existsSync ?? fs6.existsSync;
1403
- const realpathSync11 = deps.realpathSync ?? fs6.realpathSync;
1408
+ const realpathSync12 = deps.realpathSync ?? fs6.realpathSync;
1404
1409
  const argv1 = deps.argv1 ?? process.argv[1];
1405
1410
  const env = deps.env ?? process.env;
1406
1411
  if (argv1) {
1407
1412
  const argvPath = normalizePath(argv1);
1408
1413
  if (isRunnableNodeScript(argvPath, existsSync10)) {
1409
1414
  try {
1410
- const canonicalArgvPath = realpathSync11(argvPath);
1415
+ const canonicalArgvPath = realpathSync12(argvPath);
1411
1416
  const root2 = isRunnableNodeScript(canonicalArgvPath, existsSync10) ? findPiPackageRootFromEntry(canonicalArgvPath) : void 0;
1412
1417
  if (root2) return { root: root2, cliScript: canonicalArgvPath };
1413
1418
  } catch {
@@ -1589,6 +1594,8 @@ function createStructuredOutputToolParameters(schema, options = {}) {
1589
1594
  };
1590
1595
  }
1591
1596
  var cachedCompile;
1597
+ var loadedCompile;
1598
+ var compileLoadError;
1592
1599
  async function resolveCompileFromPackageRoot(packageRoot) {
1593
1600
  const requireFromRoot = createRequire(path7.join(packageRoot, "package.json"));
1594
1601
  const resolved = requireFromRoot.resolve("typebox/compile");
@@ -1624,23 +1631,30 @@ async function importCompile() {
1624
1631
  }
1625
1632
  function loadCompile() {
1626
1633
  if (!cachedCompile) {
1627
- cachedCompile = importCompile().catch((error) => {
1634
+ cachedCompile = importCompile().then((compile) => {
1635
+ loadedCompile = compile;
1636
+ return compile;
1637
+ }, (error) => {
1628
1638
  cachedCompile = void 0;
1639
+ compileLoadError = error;
1629
1640
  throw error;
1630
1641
  });
1631
1642
  }
1632
1643
  return cachedCompile;
1633
1644
  }
1645
+ function structuredOutputValidatorReady() {
1646
+ return loadCompile().then(() => void 0, () => void 0);
1647
+ }
1634
1648
  function jsonPointerTarget(root, pointer) {
1635
1649
  if (pointer === "#") return root;
1636
1650
  if (!pointer.startsWith("#/")) return void 0;
1637
- let current = root;
1651
+ let current2 = root;
1638
1652
  for (const encoded of pointer.slice(2).split("/")) {
1639
- if (!current || typeof current !== "object") return void 0;
1653
+ if (!current2 || typeof current2 !== "object") return void 0;
1640
1654
  const key = encoded.replace(/~1/g, "/").replace(/~0/g, "~");
1641
- current = current[key];
1655
+ current2 = current2[key];
1642
1656
  }
1643
- return current;
1657
+ return current2;
1644
1658
  }
1645
1659
  function resolveLocalRefs(root, node) {
1646
1660
  const seen = /* @__PURE__ */ new Set();
@@ -1785,15 +1799,29 @@ function createStructuredOutputRuntime(schema, baseDir, options = {}) {
1785
1799
  };
1786
1800
  }
1787
1801
  async function validateStructuredOutputValue(schema, value) {
1788
- const compile = await loadCompile();
1802
+ return validateWithCompile(await loadCompile(), schema, value);
1803
+ }
1804
+ function prepareStructuredOutputArguments(schema, args) {
1805
+ if (!args || typeof args !== "object" || !("value" in args)) return args;
1806
+ if (!loadedCompile) throw compileLoadError ?? new Error("Structured output validator is still loading; call structured_output again.");
1807
+ const validation = validateWithCompile(loadedCompile, schema, args.value);
1808
+ if (validation.status === "invalid") throw new Error(`Structured output validation failed: ${validation.message}`);
1809
+ return args;
1810
+ }
1811
+ function validateWithCompile(compile, schema, value) {
1789
1812
  let validator;
1790
1813
  try {
1791
1814
  validator = compile(schema);
1792
1815
  } catch (error) {
1793
1816
  return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
1794
1817
  }
1795
- if (validator.Check(value)) return { status: "valid" };
1796
- const originalErrors = [...validator.Errors(value)];
1818
+ let originalErrors;
1819
+ try {
1820
+ if (validator.Check(value)) return { status: "valid" };
1821
+ originalErrors = [...validator.Errors(value)];
1822
+ } catch (error) {
1823
+ return { status: "invalid", message: `outputSchema cannot be validated (cyclic or too deep): ${error instanceof Error ? error.message : String(error)}` };
1824
+ }
1797
1825
  const errors = [];
1798
1826
  const uniqueErrors = /* @__PURE__ */ new Set();
1799
1827
  const seen = /* @__PURE__ */ new Set();
@@ -2173,9 +2201,9 @@ function acceptChildWatchdogEvent(input) {
2173
2201
  ...warnings?.length ? { warnings } : {}
2174
2202
  };
2175
2203
  }
2176
- function applyChildWatchdogMessage(current, message) {
2177
- if (message?.role !== "assistant" || !current?.warnings?.some((entry) => !entry.addressed)) return void 0;
2178
- return { ...current, warnings: current.warnings.map((entry) => entry.addressed ? entry : { ...entry, addressed: true }) };
2204
+ function applyChildWatchdogMessage(current2, message) {
2205
+ if (message?.role !== "assistant" || !current2?.warnings?.some((entry) => !entry.addressed)) return void 0;
2206
+ return { ...current2, warnings: current2.warnings.map((entry) => entry.addressed ? entry : { ...entry, addressed: true }) };
2179
2207
  }
2180
2208
  function unresolvedChildWatchdogBlockers(progress) {
2181
2209
  return (progress?.warnings ?? []).filter((warning) => warning.severity === "blocker" && (!warning.addressed || warning.stalemate));
@@ -3183,12 +3211,30 @@ function verifyRedactionEnv(env) {
3183
3211
  return value.length >= 4 && SENSITIVE_ENV_KEY_PATTERN.test(key);
3184
3212
  }));
3185
3213
  }
3186
- function redactVerifyEnv(value, env) {
3214
+ function verifySecrets(env) {
3215
+ return [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
3216
+ }
3217
+ function redactSecrets(value, secrets) {
3187
3218
  let redacted = value;
3188
- const secrets = [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
3189
3219
  for (const secret of secrets) redacted = redacted.replaceAll(secret, "[REDACTED]");
3190
3220
  return redacted;
3191
3221
  }
3222
+ function redactVerifyEnv(value, env) {
3223
+ return redactSecrets(value, verifySecrets(env));
3224
+ }
3225
+ function parseRedactedVerifyValue(text, secrets) {
3226
+ return JSON.parse(text, (_key, value, context) => {
3227
+ if (typeof value === "string") return redactSecrets(value, secrets);
3228
+ if (typeof value === "number" && secrets.length > 0) {
3229
+ const source = context?.source;
3230
+ return source !== void 0 && redactSecrets(source, secrets) === source ? value : "[REDACTED]";
3231
+ }
3232
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3233
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactSecrets(key, secrets), item]));
3234
+ }
3235
+ return value;
3236
+ });
3237
+ }
3192
3238
  var DEFAULT_VERIFY_TIMEOUT_MS = 12e4;
3193
3239
  function hash(value) {
3194
3240
  return createHash2("sha256").update(value).digest("hex");
@@ -3214,32 +3260,48 @@ function isCachedVerifyResult(value) {
3214
3260
  return typeof result.id === "string" && typeof result.command === "string" && (typeof result.exitCode === "number" || result.exitCode === null) && (result.status === "passed" || result.status === "failed" || result.status === "timed-out" || result.status === "allowed-failure") && typeof result.durationMs === "number";
3215
3261
  }
3216
3262
  var TYPED_VERIFY_OUTPUT_MAX_BYTES = 12e3;
3217
- async function applyTypedVerifyOutput(command, run) {
3263
+ async function applyTypedVerifyOutput(command, run, rawStdout) {
3218
3264
  if (run.status !== "passed") return;
3219
- const stdout = run.stdout ?? "";
3265
+ const secrets = verifySecrets(command.env);
3266
+ const stdout = rawStdout.trim();
3220
3267
  const fail = (message) => {
3221
3268
  run.status = "failed";
3222
- run.structuredOutputError = message;
3269
+ run.structuredOutputError = redactSecrets(message, secrets);
3223
3270
  };
3224
- if (!stdout.trim()) return fail('output: "json" command printed nothing on stdout.');
3225
- if (stdout.endsWith("...[truncated]")) return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
3271
+ if (!stdout) return fail('output: "json" command printed nothing on stdout.');
3272
+ if (stdout.length > TYPED_VERIFY_OUTPUT_MAX_BYTES) return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
3226
3273
  let value;
3227
3274
  try {
3228
3275
  value = JSON.parse(stdout);
3229
- } catch (error) {
3230
- return fail(`output: "json" stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
3276
+ } catch {
3277
+ let reason = "parse failed";
3278
+ try {
3279
+ JSON.parse(redactSecrets(stdout, secrets));
3280
+ } catch (error) {
3281
+ reason = error instanceof Error ? error.message : String(error);
3282
+ }
3283
+ return fail(`output: "json" stdout is not valid JSON: ${reason}`);
3231
3284
  }
3285
+ const redactedValue = parseRedactedVerifyValue(stdout, secrets);
3232
3286
  if (command.schema) {
3233
3287
  const validation = await validateStructuredOutputValue(command.schema, value);
3234
- if (validation.status === "invalid") return fail(`output: "json" stdout does not match gate.schema: ${validation.message}`);
3288
+ if (validation.status === "invalid") {
3289
+ const redactedValidation = await validateStructuredOutputValue(command.schema, redactedValue);
3290
+ return fail(`output: "json" stdout does not match gate.schema${redactedValidation.status === "invalid" ? `: ${redactedValidation.message}` : "."}`);
3291
+ }
3235
3292
  }
3236
- run.structuredOutput = value;
3293
+ run.structuredOutput = redactedValue;
3237
3294
  }
3238
3295
  function typedVerifyOutput(ledger) {
3239
3296
  const run = ledger?.verifyRuns?.find((entry) => entry.structuredOutput !== void 0);
3240
3297
  return run ? { value: run.structuredOutput } : void 0;
3241
3298
  }
3242
3299
  async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
3300
+ if (command.output === "json") {
3301
+ const { run, rawStdout } = await runVerifyCommand(command, defaultCwd, options);
3302
+ await applyTypedVerifyOutput(command, run, rawStdout);
3303
+ return run;
3304
+ }
3243
3305
  const cwd = command.cwd ? path8.resolve(defaultCwd, command.cwd) : defaultCwd;
3244
3306
  let workspaceState;
3245
3307
  try {
@@ -3247,8 +3309,8 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
3247
3309
  } catch {
3248
3310
  workspaceState = void 0;
3249
3311
  }
3250
- if (!workspaceState || !options.artifactsDir || !options.runId || command.output === "json") {
3251
- return runVerifyCommand(command, defaultCwd, options);
3312
+ if (!workspaceState || !options.artifactsDir || !options.runId) {
3313
+ return (await runVerifyCommand(command, defaultCwd, options)).run;
3252
3314
  }
3253
3315
  const envKeys = Object.keys(command.env ?? {}).sort();
3254
3316
  const envHash = hash(JSON.stringify(Object.fromEntries(Object.entries(effectiveVerifyEnv(command.env)).sort(([left], [right]) => left.localeCompare(right)))));
@@ -3272,7 +3334,7 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
3272
3334
  }
3273
3335
  } catch {
3274
3336
  }
3275
- const result = await runVerifyCommand(command, defaultCwd, options);
3337
+ const { run: result } = await runVerifyCommand(command, defaultCwd, options);
3276
3338
  const evidenced = { ...result, artifactPath, cacheKey, memoized: false, envKeys, envHash, workspaceState };
3277
3339
  try {
3278
3340
  fs8.mkdirSync(path8.dirname(artifactPath), { recursive: true });
@@ -3301,11 +3363,11 @@ function quoteExecutableForShell(command, platform = process.platform) {
3301
3363
  const firstToken = trimmed.match(/^\S+/)?.[0];
3302
3364
  if (/\.(?:exe|bat|cmd|com|ps1)$/i.test(firstToken ?? "")) return command;
3303
3365
  const match = trimmed.match(/^([A-Za-z]:\\[^"<>|&*?\r\n]*?\s[^"<>|&*?\r\n]*?\\[^"<>|&*?\r\n]*?\.(?:exe|bat|cmd|com|ps1))(?=\s|$)/i);
3304
- const executable = match?.[1];
3305
- if (executable && /\s/.test(executable) && !/[A-Za-z]:\\/.test(executable.slice(3))) {
3306
- const rest = trimmed.slice(executable.length);
3366
+ const executable2 = match?.[1];
3367
+ if (executable2 && /\s/.test(executable2) && !/[A-Za-z]:\\/.test(executable2.slice(3))) {
3368
+ const rest = trimmed.slice(executable2.length);
3307
3369
  const leading = command.slice(0, command.length - trimmed.length);
3308
- return `${leading}"${executable}"${rest}`;
3370
+ return `${leading}"${executable2}"${rest}`;
3309
3371
  }
3310
3372
  const extensionlessSpacedFilenameMatch = trimmed.match(/^([A-Za-z]:\\[^"<>|&*?\r\n]*?\s[^"<>|&*?\r\n]*?)(?=\s+--|$)/i);
3311
3373
  const extensionlessSpacedFilename = extensionlessSpacedFilenameMatch?.[1];
@@ -3324,7 +3386,7 @@ function quoteExecutableForShell(command, platform = process.platform) {
3324
3386
  return command;
3325
3387
  }
3326
3388
  function runVerifyCommand(command, defaultCwd, options = {}) {
3327
- return new Promise((resolve11) => {
3389
+ return new Promise((resolve12) => {
3328
3390
  const startedAt = Date.now();
3329
3391
  const cwd = command.cwd ? path8.resolve(defaultCwd, command.cwd) : defaultCwd;
3330
3392
  let stdout = "";
@@ -3345,12 +3407,15 @@ function runVerifyCommand(command, defaultCwd, options = {}) {
3345
3407
  clearTimeout(timeout);
3346
3408
  if (hardKill) clearTimeout(hardKill);
3347
3409
  options.signal?.removeEventListener("abort", abortVerification);
3348
- resolve11({
3349
- id: command.id,
3350
- command: command.command,
3351
- cwd,
3352
- durationMs: Date.now() - startedAt,
3353
- ...result
3410
+ resolve12({
3411
+ run: {
3412
+ id: command.id,
3413
+ command: command.command,
3414
+ cwd,
3415
+ durationMs: Date.now() - startedAt,
3416
+ ...result
3417
+ },
3418
+ rawStdout: stdout
3354
3419
  });
3355
3420
  };
3356
3421
  const abortVerification = () => {
@@ -3472,7 +3537,6 @@ async function evaluateAcceptance(input) {
3472
3537
  artifactsDir: input.artifactsDir,
3473
3538
  runId: input.runId
3474
3539
  });
3475
- if (command.output === "json") await applyTypedVerifyOutput(command, run);
3476
3540
  ledger.verifyRuns.push(run);
3477
3541
  if (input.signal?.aborted) break;
3478
3542
  }
@@ -4030,11 +4094,11 @@ function resolveMemoryDir(rootDir, scopedPath) {
4030
4094
  return { error: "memory root must not be a symlink" };
4031
4095
  }
4032
4096
  const rootReal = fs9.existsSync(rootDir) ? fs9.realpathSync(rootDir) : path9.resolve(rootDir);
4033
- let current = rootDir;
4097
+ let current2 = rootDir;
4034
4098
  for (const segment of segments) {
4035
- current = path9.join(current, segment);
4036
- if (!fs9.existsSync(current)) break;
4037
- const currentReal = fs9.realpathSync(current);
4099
+ current2 = path9.join(current2, segment);
4100
+ if (!fs9.existsSync(current2)) break;
4101
+ const currentReal = fs9.realpathSync(current2);
4038
4102
  if (!isWithin(currentReal, rootReal)) {
4039
4103
  return { error: "memory path resolves outside the memory root" };
4040
4104
  }
@@ -4152,7 +4216,20 @@ function buildAgentMemoryInjection(agent, cwd) {
4152
4216
  // src/runs/shared/permissions.ts
4153
4217
  import * as fs10 from "node:fs";
4154
4218
  import * as path10 from "node:path";
4155
- var INTERNAL_TOOLS = /* @__PURE__ */ new Set(["contact_supervisor", "intercom", "bg_wait", "structured_output"]);
4219
+
4220
+ // src/shared/wait-tool-name.ts
4221
+ var DEFAULT_WAIT_TOOL_NAME = "bg_wait";
4222
+ var current = DEFAULT_WAIT_TOOL_NAME;
4223
+ function waitToolName() {
4224
+ return current;
4225
+ }
4226
+ function setWaitToolName(name) {
4227
+ current = name;
4228
+ }
4229
+
4230
+ // src/runs/shared/permissions.ts
4231
+ var COORDINATION_TOOLS = /* @__PURE__ */ new Set(["contact_supervisor", "intercom", "structured_output"]);
4232
+ var isInternalTool = (tool) => COORDINATION_TOOLS.has(tool) || tool === waitToolName();
4156
4233
  var DECISIONS = /* @__PURE__ */ new Set(["allow", "ask", "deny"]);
4157
4234
  var MAX_POLICY_BYTES = 16 * 1024;
4158
4235
  var MAX_PREVIEW_BYTES = 2048;
@@ -4168,7 +4245,7 @@ function validatePermissionRules(value, label) {
4168
4245
  for (const [tool, decision] of Object.entries(value)) {
4169
4246
  if (!tool.trim()) throw new Error(`${label} contains an empty tool name.`);
4170
4247
  if (tool === "bash") throw new Error(`${label}.bash is unsupported; pi-subagents leaves bash policy to pi-guard.`);
4171
- if (INTERNAL_TOOLS.has(tool)) throw new Error(`${label}.${tool} is reserved for child coordination and cannot be gated.`);
4248
+ if (isInternalTool(tool) || tool === DEFAULT_WAIT_TOOL_NAME) throw new Error(`${label}.${tool} is reserved for child coordination and cannot be gated.`);
4172
4249
  if (!DECISIONS.has(decision)) throw new Error(`${label}.${tool} must be allow, ask, or deny.`);
4173
4250
  result[tool] = decision;
4174
4251
  }
@@ -4188,7 +4265,7 @@ function resolvePermissionRules(globalConfig, agentRules) {
4188
4265
  return Object.keys(merged).length ? merged : void 0;
4189
4266
  }
4190
4267
  function permissionDecision(rules, toolName) {
4191
- if (toolName === "bash" || INTERNAL_TOOLS.has(toolName)) return "allow";
4268
+ if (toolName === "bash" || isInternalTool(toolName)) return "allow";
4192
4269
  return rules?.[toolName] ?? "allow";
4193
4270
  }
4194
4271
  function redact(value, key = "", depth = 0) {
@@ -5232,7 +5309,8 @@ function applyBuiltinOverride(agent, override, meta) {
5232
5309
  ...meta,
5233
5310
  base: agent.override?.base ?? cloneOverrideBase(agent),
5234
5311
  fields: [.../* @__PURE__ */ new Set([...agent.override?.fields ?? [], ...Object.keys(override)])].sort(),
5235
- fieldScopes: Object.fromEntries(Object.entries({ ...agent.override?.fieldScopes ?? {} }).map(([field, scopes]) => [field, [...scopes]]))
5312
+ fieldScopes: Object.fromEntries(Object.entries({ ...agent.override?.fieldScopes ?? {} }).map(([field, scopes]) => [field, [...scopes]])),
5313
+ paths: { ...agent.override?.paths, [meta.scope]: meta.path }
5236
5314
  };
5237
5315
  for (const field of Object.keys(override)) {
5238
5316
  const scopes = overrideInfo.fieldScopes[field] ?? [];
@@ -5334,10 +5412,12 @@ function applyBuiltinOverrides(builtinAgents, userSettings, projectSettings, use
5334
5412
  };
5335
5413
  return builtinAgents.map((agent) => {
5336
5414
  const projectOverride = projectSettings.overrides[agent.name];
5415
+ const userOverride = userSettings.overrides[agent.name];
5337
5416
  if (projectOverride && projectSettingsPath) {
5417
+ const withUserOverride = userOverride ? applyBuiltinOverride(agent, userOverride, { scope: "user", path: userSettingsPath }) : agent;
5338
5418
  return applyGlobalThinking(
5339
- applyBuiltinOverride(agent, projectOverride, { scope: "project", path: projectSettingsPath }),
5340
- projectOverride.thinking !== void 0
5419
+ applyBuiltinOverride(withUserOverride, projectOverride, { scope: "project", path: projectSettingsPath }),
5420
+ projectOverride.thinking !== void 0 || !projectThinkingConfigured && userOverride?.thinking !== void 0
5341
5421
  );
5342
5422
  }
5343
5423
  if (projectBulkDisabled && projectSettingsPath) {
@@ -5346,7 +5426,6 @@ function applyBuiltinOverrides(builtinAgents, userSettings, projectSettings, use
5346
5426
  false
5347
5427
  );
5348
5428
  }
5349
- const userOverride = userSettings.overrides[agent.name];
5350
5429
  if (userOverride) {
5351
5430
  return applyGlobalThinking(
5352
5431
  applyBuiltinOverride(agent, userOverride, { scope: "user", path: userSettingsPath }),
@@ -5413,9 +5492,9 @@ function removeBuiltinAgentOverride(cwd, name, scope, options) {
5413
5492
  const agentOverrides = nextSubagents.agentOverrides;
5414
5493
  if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false, machinePreserved: false };
5415
5494
  const nextOverrides = { ...agentOverrides };
5416
- const current = nextOverrides[name];
5495
+ const current2 = nextOverrides[name];
5417
5496
  if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false, machinePreserved: false };
5418
- const configuredMachine = current && typeof current === "object" && !Array.isArray(current) ? current.machine : void 0;
5497
+ const configuredMachine = current2 && typeof current2 === "object" && !Array.isArray(current2) ? current2.machine : void 0;
5419
5498
  const machine = configuredMachine === false || typeof configuredMachine === "string" && configuredMachine.trim() ? configuredMachine : void 0;
5420
5499
  if (options?.preserveMachine && machine !== void 0) nextOverrides[name] = { machine };
5421
5500
  else delete nextOverrides[name];
@@ -5555,11 +5634,11 @@ function inspectAgentDefinitionDirectory(dir, operations = DEFAULT_AGENT_DEFINIT
5555
5634
  let unreadable = false;
5556
5635
  const visitedDirectories = /* @__PURE__ */ new Set();
5557
5636
  const inspectedDirectories = /* @__PURE__ */ new Set();
5558
- const visit = (current) => {
5559
- inspectedDirectories.add(path11.resolve(current));
5637
+ const visit = (current2) => {
5638
+ inspectedDirectories.add(path11.resolve(current2));
5560
5639
  let realDir;
5561
5640
  try {
5562
- realDir = operations.realpathSync?.(current) ?? path11.resolve(current);
5641
+ realDir = operations.realpathSync?.(current2) ?? path11.resolve(current2);
5563
5642
  } catch {
5564
5643
  unreadable = true;
5565
5644
  return;
@@ -5568,13 +5647,13 @@ function inspectAgentDefinitionDirectory(dir, operations = DEFAULT_AGENT_DEFINIT
5568
5647
  visitedDirectories.add(realDir);
5569
5648
  let entries;
5570
5649
  try {
5571
- entries = operations.readdirSync(current).sort((a, b) => a.name.localeCompare(b.name));
5650
+ entries = operations.readdirSync(current2).sort((a, b) => a.name.localeCompare(b.name));
5572
5651
  } catch {
5573
5652
  unreadable = true;
5574
5653
  return;
5575
5654
  }
5576
5655
  for (const entry of entries) {
5577
- const filePath = path11.join(current, entry.name);
5656
+ const filePath = path11.join(current2, entry.name);
5578
5657
  if (isExcluded(filePath)) continue;
5579
5658
  let isDirectory2 = entry.isDirectory();
5580
5659
  if (entry.isSymbolicLink()) {
@@ -6058,11 +6137,11 @@ function addDirectoryWatchPaths(paths, root, files, directories = []) {
6058
6137
  }
6059
6138
  for (const file of files) {
6060
6139
  paths.add(path11.resolve(file));
6061
- let current = path11.resolve(path11.dirname(file));
6062
- while (isPathWithin(resolvedRoot, current)) {
6063
- paths.add(current);
6064
- if (current === resolvedRoot) break;
6065
- current = path11.dirname(current);
6140
+ let current2 = path11.resolve(path11.dirname(file));
6141
+ while (isPathWithin(resolvedRoot, current2)) {
6142
+ paths.add(current2);
6143
+ if (current2 === resolvedRoot) break;
6144
+ current2 = path11.dirname(current2);
6066
6145
  }
6067
6146
  }
6068
6147
  }
@@ -6103,12 +6182,12 @@ function discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot, projectTr
6103
6182
  }
6104
6183
  function projectDiscoveryWatchPaths(cwd) {
6105
6184
  const paths = [];
6106
- let current = path11.resolve(cwd);
6185
+ let current2 = path11.resolve(cwd);
6107
6186
  while (true) {
6108
- paths.push(getProjectConfigDir(current), path11.join(current, ".agents"), path11.join(current, ".git"));
6109
- const parent = path11.dirname(current);
6110
- if (parent === current) break;
6111
- current = parent;
6187
+ paths.push(getProjectConfigDir(current2), path11.join(current2, ".agents"), path11.join(current2, ".git"));
6188
+ const parent = path11.dirname(current2);
6189
+ if (parent === current2) break;
6190
+ current2 = parent;
6112
6191
  }
6113
6192
  return paths;
6114
6193
  }
@@ -6212,7 +6291,7 @@ function getAgentDiscoverySources(cwd, preferredModelProvider, includeChains = f
6212
6291
  const key = discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot, projectTrusted);
6213
6292
  const cached = agentDiscoveryCache.get(key);
6214
6293
  if (cached && cached.fingerprint === discoveryFingerprint(cached.sources)) {
6215
- if (includeChains) {
6294
+ if (includeChains && !cached.sources.userChains) {
6216
6295
  ensureDiscoveryChains(cached.sources);
6217
6296
  cached.fingerprint = discoveryFingerprint(cached.sources);
6218
6297
  }
@@ -6446,11 +6525,82 @@ function discoverAgentsAll(cwd, preferredModelProvider, options = {}) {
6446
6525
  }
6447
6526
 
6448
6527
  // src/runs/shared/child-launch-plan.ts
6449
- import * as path13 from "node:path";
6528
+ import * as path14 from "node:path";
6450
6529
 
6451
6530
  // src/runs/shared/single-output.ts
6531
+ import * as fs13 from "node:fs";
6532
+ import * as path13 from "node:path";
6533
+
6534
+ // src/runs/shared/rex-machine.ts
6535
+ import { spawnSync as spawnSync4 } from "node:child_process";
6452
6536
  import * as fs12 from "node:fs";
6537
+ import * as os4 from "node:os";
6453
6538
  import * as path12 from "node:path";
6539
+ var REX_LOCAL_MACHINE = "local";
6540
+ var REX_EXIT_GONE = 3;
6541
+ var REX_EXIT_UNREACHABLE = 4;
6542
+ function isRexLocalMachine(machine) {
6543
+ return machine?.provider === "rex" && !("target" in machine);
6544
+ }
6545
+ var REX_BUNDLE_BIN = "Library/Application Support/com.superlogical.rex/RexServer/Versions/Current/Rex Server.app/Contents/MacOS/rex";
6546
+ var REX_CALL_TIMEOUT_MS = 15e3;
6547
+ var REX_MAX_OUTPUT = 1024 * 1024;
6548
+ function rexGlobalArgs(server) {
6549
+ return server ? ["--autostart=false", "-S", server] : ["--autostart=false"];
6550
+ }
6551
+ function executable(file) {
6552
+ try {
6553
+ fs12.accessSync(file, fs12.constants.X_OK);
6554
+ return fs12.statSync(file).isFile();
6555
+ } catch {
6556
+ return false;
6557
+ }
6558
+ }
6559
+ function resolveRexBinary(env = process.env) {
6560
+ const fromDir = env.REX_BIN_DIR ? [path12.join(env.REX_BIN_DIR, "rex")] : [];
6561
+ const fromPath = (env.PATH ?? "").split(path12.delimiter).filter((dir) => path12.isAbsolute(dir)).map((dir) => path12.join(dir, "rex"));
6562
+ const found = [...fromDir, ...fromPath, path12.join(os4.homedir(), REX_BUNDLE_BIN)].find(executable);
6563
+ if (!found) throw new Error("The Rex CLI was not found: set REX_BIN_DIR, put rex on PATH, or install Rex.");
6564
+ return found;
6565
+ }
6566
+ function rexCommandEnv(source = process.env) {
6567
+ const { REX_SESSION: _session, REX_BLOCK: _block, REX_SERVER: _server, ...env } = source;
6568
+ return env;
6569
+ }
6570
+ function sessionConfirmed(stdout, session) {
6571
+ try {
6572
+ const parsed = JSON.parse(stdout);
6573
+ return parsed?.session_id === session;
6574
+ } catch {
6575
+ return false;
6576
+ }
6577
+ }
6578
+ function resolveRexLocalPlacement(input) {
6579
+ if (process.platform === "win32") throw new Error("Machine 'local' runs the child in a Rex pane, which is not supported on Windows.");
6580
+ const env = input.env ?? process.env, session = env.REX_SESSION?.trim(), server = env.REX_SERVER?.trim();
6581
+ if (!session) throw new Error("Machine 'local' opens the child in a new tab of this Rex session, but this Pi is not running inside Rex (REX_SESSION is not set).");
6582
+ const result = spawnSync4(resolveRexBinary(env), [...rexGlobalArgs(server), "session", "inspect", session, "--json"], { encoding: "utf8", env: rexCommandEnv(env), timeout: REX_CALL_TIMEOUT_MS, maxBuffer: REX_MAX_OUTPUT, windowsHide: true });
6583
+ if (result.error) throw new Error(`Could not ask Rex about this session: ${result.error.message}`, { cause: result.error });
6584
+ if (result.status === REX_EXIT_GONE) throw new Error(`Machine 'local' needs this Pi's Rex session, but the Rex server does not know session ${session}.`);
6585
+ if (result.status === REX_EXIT_UNREACHABLE) throw new Error("Machine 'local' needs the Rex server, but it is unreachable.");
6586
+ if (result.status !== 0) throw new Error(`rex session inspect exited with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
6587
+ if (!sessionConfirmed(result.stdout, session)) throw new Error(`The Rex server did not confirm session ${session}.`);
6588
+ const stepCwd = input.stepCwd?.trim();
6589
+ const home = stepCwd === "~" || stepCwd?.startsWith("~/") ? path12.join(os4.homedir(), stepCwd.slice(1)) : void 0;
6590
+ const requested = home ?? (stepCwd ? path12.resolve(input.cwd, stepCwd) : input.cwd);
6591
+ let cwd;
6592
+ try {
6593
+ cwd = fs12.realpathSync(requested);
6594
+ } catch (error) {
6595
+ throw new Error(`Machine 'local' cwd does not exist: ${requested}.`, { cause: error });
6596
+ }
6597
+ if (!fs12.statSync(cwd).isDirectory()) throw new Error(`Machine 'local' cwd is not a directory: ${requested}.`);
6598
+ const machine = { provider: "rex", id: REX_LOCAL_MACHINE, session, cwd };
6599
+ if (server) machine.server = server;
6600
+ return machine;
6601
+ }
6602
+
6603
+ // src/runs/shared/single-output.ts
6454
6604
  var READ_ONLY_OUTPUT_TOOLS = /* @__PURE__ */ new Set([
6455
6605
  "read",
6456
6606
  "grep",
@@ -6479,7 +6629,7 @@ function snapshotFromStatError(error) {
6479
6629
  }
6480
6630
  function extractChildWrittenOutput(messages, outputPath, cwd) {
6481
6631
  if (!messages?.length || !outputPath) return void 0;
6482
- const resolvedTarget = path12.resolve(cwd ?? ".", outputPath);
6632
+ const resolvedTarget = path13.resolve(cwd ?? ".", outputPath);
6483
6633
  const comparableTarget = process.platform === "win32" ? resolvedTarget.toLowerCase() : resolvedTarget;
6484
6634
  const successfulCallIds = /* @__PURE__ */ new Set();
6485
6635
  for (const message of messages) {
@@ -6494,7 +6644,7 @@ function extractChildWrittenOutput(messages, outputPath, cwd) {
6494
6644
  if (part.type !== "toolCall" || part.name !== "write" || !successfulCallIds.has(part.id)) continue;
6495
6645
  const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments) ? part.arguments : {};
6496
6646
  if (typeof args.path !== "string" || typeof args.content !== "string") continue;
6497
- const resolvedWritePath = path12.resolve(cwd ?? ".", args.path);
6647
+ const resolvedWritePath = path13.resolve(cwd ?? ".", args.path);
6498
6648
  const comparableWritePath = process.platform === "win32" ? resolvedWritePath.toLowerCase() : resolvedWritePath;
6499
6649
  if (comparableWritePath !== comparableTarget) continue;
6500
6650
  content = args.content;
@@ -6510,10 +6660,10 @@ function normalizeSingleOutputOverride(output, defaultOutput) {
6510
6660
  }
6511
6661
  function resolveSingleOutputPath(output, runtimeCwd, requestedCwd, relativeBaseDir) {
6512
6662
  if (typeof output !== "string" || !output || output === "false" || output === "true") return void 0;
6513
- if (path12.isAbsolute(output)) return output;
6514
- if (relativeBaseDir) return path12.resolve(relativeBaseDir, output);
6515
- const baseCwd = requestedCwd ? path12.isAbsolute(requestedCwd) ? requestedCwd : path12.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
6516
- return path12.resolve(baseCwd, output);
6663
+ if (path13.isAbsolute(output)) return output;
6664
+ if (relativeBaseDir) return path13.resolve(relativeBaseDir, output);
6665
+ const baseCwd = requestedCwd ? path13.isAbsolute(requestedCwd) ? requestedCwd : path13.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
6666
+ return path13.resolve(baseCwd, output);
6517
6667
  }
6518
6668
  function requestedOutputPathFromTask(task) {
6519
6669
  for (const line of task.split(/\r?\n/).reverse()) {
@@ -6527,12 +6677,13 @@ function requestedOutputPathFromTask(task) {
6527
6677
  function outputPathMappingFromTask(task, savedPath) {
6528
6678
  const requestedPath = requestedOutputPathFromTask(task);
6529
6679
  if (!requestedPath || !savedPath) return void 0;
6530
- if (path12.isAbsolute(requestedPath) && path12.normalize(requestedPath) === path12.normalize(savedPath)) return void 0;
6680
+ if (path13.isAbsolute(requestedPath) && path13.normalize(requestedPath) === path13.normalize(savedPath)) return void 0;
6531
6681
  return { requestedPath, savedPath };
6532
6682
  }
6533
- function injectSingleOutputInstruction(task, outputPath, capabilities) {
6683
+ function injectSingleOutputInstruction(task, outputPath, capabilities, machine) {
6534
6684
  if (!outputPath) return task;
6535
- const delivery = !capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools) ? `Write your findings to exactly this path: ${outputPath}` : [
6685
+ const remote = machine !== void 0 && !isRexLocalMachine(machine);
6686
+ const delivery = !remote && (!capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools)) ? `Write your findings to exactly this path: ${outputPath}` : [
6536
6687
  "Return the complete artifact in your final response.",
6537
6688
  `The runtime will persist it to exactly this path: ${outputPath}`,
6538
6689
  "Do not call contact_supervisor merely because no write-capable tool is available."
@@ -6564,7 +6715,7 @@ function formatByteSize(bytes) {
6564
6715
  return `${value.toFixed(1)} ${units[unitIndex]}`;
6565
6716
  }
6566
6717
  function formatSavedOutputReference(savedPath, fullOutput) {
6567
- const absolutePath = path12.resolve(savedPath);
6718
+ const absolutePath = path13.resolve(savedPath);
6568
6719
  const bytes = Buffer.byteLength(fullOutput, "utf-8");
6569
6720
  const lines = countLines(fullOutput);
6570
6721
  return {
@@ -6580,9 +6731,9 @@ var SAVED_OUTPUT_LINE = /\n\nOutput saved to: (.+) \([^()\n]*\)\. Read this file
6580
6731
  var MAX_UNFILED_TRAILING_BLOCKS = 8;
6581
6732
  function readFullOutputFile(filePath) {
6582
6733
  try {
6583
- const stat = fs12.statSync(filePath);
6734
+ const stat = fs13.statSync(filePath);
6584
6735
  if (!stat.isFile() || stat.size > MAX_FULL_OUTPUT_FILE_BYTES) return void 0;
6585
- return fs12.readFileSync(filePath, "utf-8");
6736
+ return fs13.readFileSync(filePath, "utf-8");
6586
6737
  } catch {
6587
6738
  return void 0;
6588
6739
  }
@@ -6600,7 +6751,7 @@ function fileBackedHead(output, fullOutput, maxTrailingBlocks) {
6600
6751
  }
6601
6752
  function capInlineOutput(output, files) {
6602
6753
  const match = files.savedPath ? output.match(SAVED_OUTPUT_LINE) : null;
6603
- const savedLine = match && files.savedPath && match[1] === path12.resolve(files.savedPath) ? match : void 0;
6754
+ const savedLine = match && files.savedPath && match[1] === path13.resolve(files.savedPath) ? match : void 0;
6604
6755
  const body = savedLine ? output.slice(0, savedLine.index) : output;
6605
6756
  const filePath = savedLine ? files.savedPath : files.artifactPath;
6606
6757
  if (body.length <= INLINE_OUTPUT_HEAD_CHARS || !filePath) return output;
@@ -6640,15 +6791,15 @@ function validateFileOnlyOutputMode(outputMode, outputPath, context) {
6640
6791
  return void 0;
6641
6792
  }
6642
6793
  function resolveSingleOutputClaimPath(outputPath) {
6643
- let existing = path12.resolve(outputPath);
6794
+ let existing = path13.resolve(outputPath);
6644
6795
  const missingSegments = [];
6645
- while (!fs12.existsSync(existing)) {
6646
- missingSegments.unshift(path12.basename(existing));
6647
- const parent = path12.dirname(existing);
6796
+ while (!fs13.existsSync(existing)) {
6797
+ missingSegments.unshift(path13.basename(existing));
6798
+ const parent = path13.dirname(existing);
6648
6799
  if (parent === existing) break;
6649
6800
  existing = parent;
6650
6801
  }
6651
- return path12.join(fs12.realpathSync(existing), ...missingSegments);
6802
+ return path13.join(fs13.realpathSync(existing), ...missingSegments);
6652
6803
  }
6653
6804
  function outputClaimError(outputPath, expectedClaimPath) {
6654
6805
  if (expectedClaimPath && resolveSingleOutputClaimPath(outputPath) !== expectedClaimPath) return "Output path changed after it was claimed.";
@@ -6657,7 +6808,7 @@ function outputClaimError(outputPath, expectedClaimPath) {
6657
6808
  function captureSingleOutputSnapshot(outputPath) {
6658
6809
  if (!outputPath) return void 0;
6659
6810
  try {
6660
- const stat = fs12.statSync(outputPath);
6811
+ const stat = fs13.statSync(outputPath);
6661
6812
  return { exists: true, mtimeMs: stat.mtimeMs, size: stat.size };
6662
6813
  } catch (error) {
6663
6814
  return snapshotFromStatError(error);
@@ -6666,7 +6817,7 @@ function captureSingleOutputSnapshot(outputPath) {
6666
6817
  function inspectSingleOutputChange(outputPath, beforeRun) {
6667
6818
  if (beforeRun?.error) return { changed: false, error: beforeRun.error };
6668
6819
  try {
6669
- const stat = fs12.statSync(outputPath);
6820
+ const stat = fs13.statSync(outputPath);
6670
6821
  return {
6671
6822
  changed: !beforeRun?.exists || stat.mtimeMs !== beforeRun.mtimeMs || stat.size !== beforeRun.size
6672
6823
  };
@@ -6685,8 +6836,8 @@ function persistSingleOutput(outputPath, fullOutput, expectedClaimPath) {
6685
6836
  try {
6686
6837
  const claimError = outputClaimError(outputPath, expectedClaimPath);
6687
6838
  if (claimError) return { error: claimError, fatalError: true };
6688
- fs12.mkdirSync(path12.dirname(outputPath), { recursive: true });
6689
- fs12.writeFileSync(outputPath, fullOutput, "utf-8");
6839
+ fs13.mkdirSync(path13.dirname(outputPath), { recursive: true });
6840
+ fs13.writeFileSync(outputPath, fullOutput, "utf-8");
6690
6841
  return { savedPath: outputPath };
6691
6842
  } catch (err) {
6692
6843
  return { error: err instanceof Error ? err.message : String(err) };
@@ -6705,7 +6856,7 @@ function resolveSingleOutput(outputPath, fallbackOutput, beforeRun, expectedClai
6705
6856
  }
6706
6857
  if (changedSinceStart.changed) {
6707
6858
  try {
6708
- return { fullOutput: fs12.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
6859
+ return { fullOutput: fs13.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
6709
6860
  } catch (error) {
6710
6861
  return {
6711
6862
  fullOutput: fallbackOutput,
@@ -6809,12 +6960,12 @@ function planChildLaunch(input) {
6809
6960
  input.originalTask
6810
6961
  );
6811
6962
  const inheritedRelativeParallelOutput = Boolean(
6812
- input.parallelOutputNamespace && input.stepOverrides.output === void 0 && typeof behavior.output === "string" && !path13.isAbsolute(behavior.output)
6963
+ input.parallelOutputNamespace && input.stepOverrides.output === void 0 && typeof behavior.output === "string" && !path14.isAbsolute(behavior.output)
6813
6964
  );
6814
6965
  if (inheritedRelativeParallelOutput && input.parallelOutputNamespace?.taskIndex !== void 0) {
6815
6966
  behavior = {
6816
6967
  ...behavior,
6817
- output: path13.join(
6968
+ output: path14.join(
6818
6969
  `parallel-${input.parallelOutputNamespace.stepIndex}`,
6819
6970
  `${input.parallelOutputNamespace.taskIndex}-${input.agentConfig.name}`,
6820
6971
  behavior.output
@@ -6846,8 +6997,8 @@ var Semaphore = class {
6846
6997
  this.available--;
6847
6998
  return Promise.resolve();
6848
6999
  }
6849
- return new Promise((resolve11) => {
6850
- this.queue.push(resolve11);
7000
+ return new Promise((resolve12) => {
7001
+ this.queue.push(resolve12);
6851
7002
  });
6852
7003
  }
6853
7004
  release() {
@@ -6879,47 +7030,47 @@ function getStepAgents(step) {
6879
7030
  return [step.agent];
6880
7031
  }
6881
7032
  function cleanupOldChainDirs() {
6882
- if (!fs13.existsSync(CHAIN_RUNS_DIR)) return;
7033
+ if (!fs14.existsSync(CHAIN_RUNS_DIR)) return;
6883
7034
  const now = Date.now();
6884
7035
  let dirs;
6885
7036
  try {
6886
- dirs = fs13.readdirSync(CHAIN_RUNS_DIR);
7037
+ dirs = fs14.readdirSync(CHAIN_RUNS_DIR);
6887
7038
  } catch {
6888
7039
  return;
6889
7040
  }
6890
7041
  for (const dir of dirs) {
6891
7042
  try {
6892
- const dirPath = path14.join(CHAIN_RUNS_DIR, dir);
6893
- const stat = fs13.statSync(dirPath);
7043
+ const dirPath = path15.join(CHAIN_RUNS_DIR, dir);
7044
+ const stat = fs14.statSync(dirPath);
6894
7045
  if (stat.isDirectory() && now - stat.mtimeMs > CHAIN_DIR_MAX_AGE_MS) {
6895
- fs13.rmSync(dirPath, { recursive: true });
7046
+ fs14.rmSync(dirPath, { recursive: true });
6896
7047
  }
6897
7048
  } catch {
6898
7049
  }
6899
7050
  }
6900
7051
  }
6901
7052
  function expandHomePath(filePath) {
6902
- if (filePath === "~") return os4.homedir();
6903
- if (filePath.startsWith("~/")) return path14.join(os4.homedir(), filePath.slice(2));
7053
+ if (filePath === "~") return os5.homedir();
7054
+ if (filePath.startsWith("~/")) return path15.join(os5.homedir(), filePath.slice(2));
6904
7055
  return filePath;
6905
7056
  }
6906
7057
  function resolveChainPath(filePath, chainDir) {
6907
7058
  const expanded = expandHomePath(filePath);
6908
- return path14.isAbsolute(expanded) ? expanded : path14.join(chainDir, expanded);
7059
+ return path15.isAbsolute(expanded) ? expanded : path15.join(chainDir, expanded);
6909
7060
  }
6910
7061
  function resolveExistingReadInstructionPaths(reads, instructionCwd, existenceCwd = instructionCwd) {
6911
7062
  return reads.flatMap((filePath) => {
6912
7063
  const instructionPath = resolveChainPath(filePath, instructionCwd);
6913
7064
  const existencePath = resolveChainPath(filePath, existenceCwd);
6914
- return fs13.existsSync(existencePath) ? [instructionPath] : [];
7065
+ return fs14.existsSync(existencePath) ? [instructionPath] : [];
6915
7066
  });
6916
7067
  }
6917
7068
  function resolveExistingReadPaths(reads, cwd) {
6918
7069
  return resolveExistingReadInstructionPaths(reads, cwd);
6919
7070
  }
6920
7071
  function writeInitialProgressFile(progressDir) {
6921
- fs13.mkdirSync(progressDir, { recursive: true });
6922
- fs13.writeFileSync(path14.join(progressDir, "progress.md"), INITIAL_PROGRESS_CONTENT);
7072
+ fs14.mkdirSync(progressDir, { recursive: true });
7073
+ fs14.writeFileSync(path15.join(progressDir, "progress.md"), INITIAL_PROGRESS_CONTENT);
6923
7074
  }
6924
7075
  function buildChainInstructions(behavior, chainDir, isFirstProgressAgent, previousSummary, readExistenceDir = chainDir) {
6925
7076
  const prefixParts = [];
@@ -6933,7 +7084,7 @@ function buildChainInstructions(behavior, chainDir, isFirstProgressAgent, previo
6933
7084
  prefixParts.push(`[Write to: ${outputPath}]`);
6934
7085
  }
6935
7086
  if (behavior.progress) {
6936
- const progressPath = path14.join(chainDir, "progress.md");
7087
+ const progressPath = path15.join(chainDir, "progress.md");
6937
7088
  if (isFirstProgressAgent) {
6938
7089
  suffixParts.push(`Create and maintain progress at: ${progressPath}`);
6939
7090
  } else {
@@ -7286,6 +7437,11 @@ function closestModelCandidates(model, availableModels) {
7286
7437
  };
7287
7438
  }).filter((entry) => entry.sameId || entry.close).sort((left, right) => Number(right.sameId) - Number(left.sameId) || left.distance - right.distance || Number(right.sameProvider) - Number(left.sameProvider) || left.fullId.localeCompare(right.fullId)).slice(0, MAX_MODEL_CANDIDATES).map((entry) => `${entry.fullId}${thinkingSuffix}`);
7288
7439
  }
7440
+ function isUnavailableSubagentModel(model, availableModels, preferredProvider) {
7441
+ const trimmed = model?.trim();
7442
+ if (!trimmed || trimmed === INHERIT_MODEL || !availableModels?.length) return false;
7443
+ return resolveSubagentModelCandidate(trimmed, availableModels, preferredProvider) === void 0;
7444
+ }
7289
7445
  function resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider) {
7290
7446
  const resolved = resolveSubagentModelCandidate(model, availableModels, preferredProvider);
7291
7447
  if (resolved) return resolved;
@@ -7417,7 +7573,7 @@ var PI_CODING_AGENT_PACKAGE_ROOT_ENV = "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROO
7417
7573
  var PROMPT_REDACTED = "[prompt redacted]";
7418
7574
  var SUBAGENT_STOPPED_MESSAGE = "Subagent stopped.";
7419
7575
  var SUBAGENT_TIMED_OUT_MESSAGE = "Subagent timed out.";
7420
- function resolveWatchPath(watchPath, nativeRealpath = fs14.realpathSync.native) {
7576
+ function resolveWatchPath(watchPath, nativeRealpath = fs15.realpathSync.native) {
7421
7577
  try {
7422
7578
  return nativeRealpath(watchPath);
7423
7579
  } catch {
@@ -7430,7 +7586,7 @@ function validConfigDirName(value) {
7430
7586
  function readConfigDirNameFromPackageRoot(packageRoot) {
7431
7587
  if (!packageRoot) return void 0;
7432
7588
  try {
7433
- const pkg = JSON.parse(fs14.readFileSync(path15.join(packageRoot, "package.json"), "utf-8"));
7589
+ const pkg = JSON.parse(fs15.readFileSync(path16.join(packageRoot, "package.json"), "utf-8"));
7434
7590
  if (pkg.name !== PI_CODING_AGENT_PACKAGE_NAME) return void 0;
7435
7591
  return validConfigDirName(pkg.piConfig?.configDir);
7436
7592
  } catch {
@@ -7442,11 +7598,11 @@ function resolveConfigDirNameFromPackageJson(entryPoint = process.argv[1], packa
7442
7598
  if (packageRootValue) return packageRootValue;
7443
7599
  if (!entryPoint) return void 0;
7444
7600
  try {
7445
- let dir = path15.dirname(fs14.realpathSync(entryPoint));
7446
- while (dir !== path15.dirname(dir)) {
7601
+ let dir = path16.dirname(fs15.realpathSync(entryPoint));
7602
+ while (dir !== path16.dirname(dir)) {
7447
7603
  const value = readConfigDirNameFromPackageRoot(dir);
7448
7604
  if (value) return value;
7449
- dir = path15.dirname(dir);
7605
+ dir = path16.dirname(dir);
7450
7606
  }
7451
7607
  } catch {
7452
7608
  }
@@ -7468,14 +7624,14 @@ function getConfigDirName() {
7468
7624
  return value;
7469
7625
  }
7470
7626
  function getProjectConfigDir(projectRoot) {
7471
- return path15.join(projectRoot, getConfigDirName());
7627
+ return path16.join(projectRoot, getConfigDirName());
7472
7628
  }
7473
7629
  function getAgentDir() {
7474
7630
  const configured = process.env.PI_CODING_AGENT_DIR;
7475
- const home = process.env.HOME || process.env.USERPROFILE || os5.homedir();
7631
+ const home = process.env.HOME || process.env.USERPROFILE || os6.homedir();
7476
7632
  if (configured === "~") return home;
7477
- if (configured?.startsWith("~/") || configured?.startsWith("~\\")) return path15.join(home, configured.slice(2));
7478
- return configured || path15.join(home, getConfigDirName(), "agent");
7633
+ if (configured?.startsWith("~/") || configured?.startsWith("~\\")) return path16.join(home, configured.slice(2));
7634
+ return configured || path16.join(home, getConfigDirName(), "agent");
7479
7635
  }
7480
7636
  var statusCache = /* @__PURE__ */ new Map();
7481
7637
  var MAX_STATUS_CACHE_ENTRIES = 512;
@@ -7484,19 +7640,19 @@ function getErrorMessage(error) {
7484
7640
  }
7485
7641
  function resolveChildCwd(baseCwd, childCwd) {
7486
7642
  if (!childCwd) return baseCwd;
7487
- return path15.isAbsolute(childCwd) ? childCwd : path15.resolve(baseCwd, childCwd);
7643
+ return path16.isAbsolute(childCwd) ? childCwd : path16.resolve(baseCwd, childCwd);
7488
7644
  }
7489
7645
  function isNotFoundError(error) {
7490
7646
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
7491
7647
  }
7492
7648
  function readStatus(asyncDir) {
7493
- if (Buffer.byteLength(path15.basename(asyncDir), "utf-8") > 255) {
7649
+ if (Buffer.byteLength(path16.basename(asyncDir), "utf-8") > 255) {
7494
7650
  return null;
7495
7651
  }
7496
- const statusPath = path15.join(asyncDir, "status.json");
7652
+ const statusPath = path16.join(asyncDir, "status.json");
7497
7653
  let stat;
7498
7654
  try {
7499
- stat = fs14.statSync(statusPath);
7655
+ stat = fs15.statSync(statusPath);
7500
7656
  } catch (error) {
7501
7657
  if (isNotFoundError(error)) {
7502
7658
  statusCache.delete(statusPath);
@@ -7514,7 +7670,7 @@ function readStatus(asyncDir) {
7514
7670
  }
7515
7671
  let content;
7516
7672
  try {
7517
- content = fs14.readFileSync(statusPath, "utf-8");
7673
+ content = fs15.readFileSync(statusPath, "utf-8");
7518
7674
  } catch (error) {
7519
7675
  if (isNotFoundError(error)) {
7520
7676
  statusCache.delete(statusPath);
@@ -7554,12 +7710,12 @@ function readStatus(asyncDir) {
7554
7710
  return status;
7555
7711
  }
7556
7712
  function findLatestSessionFile(sessionDir) {
7557
- if (!fs14.existsSync(sessionDir)) return null;
7558
- const files = fs14.readdirSync(sessionDir).filter((f) => f.endsWith(".jsonl")).map((f) => {
7559
- const filePath = path15.join(sessionDir, f);
7713
+ if (!fs15.existsSync(sessionDir)) return null;
7714
+ const files = fs15.readdirSync(sessionDir).filter((f) => f.endsWith(".jsonl")).map((f) => {
7715
+ const filePath = path16.join(sessionDir, f);
7560
7716
  return {
7561
7717
  path: filePath,
7562
- mtime: fs14.statSync(filePath).mtimeMs
7718
+ mtime: fs15.statSync(filePath).mtimeMs
7563
7719
  };
7564
7720
  }).sort((a, b) => b.mtime - a.mtime);
7565
7721
  const latest = files[0];
@@ -7865,12 +8021,12 @@ function stripSkillFrontmatter(content) {
7865
8021
  return normalized.slice(endIndex + 4).trim();
7866
8022
  }
7867
8023
  function isWithinPath(filePath, dir) {
7868
- const relative6 = path16.relative(dir, filePath);
7869
- return relative6 === "" || !relative6.startsWith("..") && !path16.isAbsolute(relative6);
8024
+ const relative6 = path17.relative(dir, filePath);
8025
+ return relative6 === "" || !relative6.startsWith("..") && !path17.isAbsolute(relative6);
7870
8026
  }
7871
8027
  function readOptionalJsonFile(filePath, label) {
7872
8028
  try {
7873
- return JSON.parse(fs15.readFileSync(filePath, "utf-8"));
8029
+ return JSON.parse(fs16.readFileSync(filePath, "utf-8"));
7874
8030
  } catch (error) {
7875
8031
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
7876
8032
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -7882,38 +8038,38 @@ function readOptionalJsonFile(filePath, label) {
7882
8038
  }
7883
8039
  function readJsonFileBestEffort2(filePath) {
7884
8040
  try {
7885
- return JSON.parse(fs15.readFileSync(filePath, "utf-8"));
8041
+ return JSON.parse(fs16.readFileSync(filePath, "utf-8"));
7886
8042
  } catch {
7887
8043
  return null;
7888
8044
  }
7889
8045
  }
7890
8046
  function extractSkillPathsFromPackageRoot(packageRoot, source, bestEffort = false) {
7891
- const packageJsonPath = path16.join(packageRoot, "package.json");
8047
+ const packageJsonPath = path17.join(packageRoot, "package.json");
7892
8048
  const pkg = bestEffort ? readJsonFileBestEffort2(packageJsonPath) : readOptionalJsonFile(packageJsonPath, "package manifest");
7893
8049
  if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return [];
7894
8050
  const pi = pkg.pi;
7895
8051
  if (!pi || typeof pi !== "object" || Array.isArray(pi)) return [];
7896
8052
  const skills = pi.skills;
7897
8053
  if (!Array.isArray(skills)) return [];
7898
- return skills.filter((entry) => typeof entry === "string").map((entry) => ({ path: path16.resolve(packageRoot, entry), source }));
8054
+ return skills.filter((entry) => typeof entry === "string").map((entry) => ({ path: path17.resolve(packageRoot, entry), source }));
7899
8055
  }
7900
8056
  var cachedGlobalNpmRoot2 = null;
7901
8057
  function getGlobalNpmRoot2() {
7902
8058
  const offline = process.env.PI_OFFLINE?.toLowerCase();
7903
8059
  if (offline === "1" || offline === "true" || offline === "yes") return null;
7904
8060
  if (cachedGlobalNpmRoot2 !== null) return cachedGlobalNpmRoot2;
7905
- const windowsGlobalRoot = process.platform === "win32" && process.env.APPDATA ? path16.join(process.env.APPDATA, "npm", "node_modules") : void 0;
8061
+ const windowsGlobalRoot = process.platform === "win32" && process.env.APPDATA ? path17.join(process.env.APPDATA, "npm", "node_modules") : void 0;
7906
8062
  if (windowsGlobalRoot) {
7907
8063
  try {
7908
- if (fs15.statSync(windowsGlobalRoot).isDirectory()) {
7909
- cachedGlobalNpmRoot2 = fs15.realpathSync(windowsGlobalRoot);
8064
+ if (fs16.statSync(windowsGlobalRoot).isDirectory()) {
8065
+ cachedGlobalNpmRoot2 = fs16.realpathSync(windowsGlobalRoot);
7910
8066
  return cachedGlobalNpmRoot2;
7911
8067
  }
7912
8068
  } catch {
7913
8069
  }
7914
8070
  }
7915
8071
  try {
7916
- cachedGlobalNpmRoot2 = fs15.realpathSync(execSync2("npm root -g", { encoding: "utf-8", timeout: 5e3, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }).trim());
8072
+ cachedGlobalNpmRoot2 = fs16.realpathSync(execSync2("npm root -g", { encoding: "utf-8", timeout: 5e3, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }).trim());
7917
8073
  return cachedGlobalNpmRoot2;
7918
8074
  } catch {
7919
8075
  cachedGlobalNpmRoot2 = "";
@@ -7923,8 +8079,8 @@ function getGlobalNpmRoot2() {
7923
8079
  function collectInstalledPackageSkillPaths(cwd, agentDir) {
7924
8080
  const projectConfigDir = getProjectConfigDir(cwd);
7925
8081
  const dirs = [
7926
- { path: path16.join(projectConfigDir, "npm", "node_modules"), source: "project-package" },
7927
- { path: path16.join(agentDir, "npm", "node_modules"), source: "user-package" }
8082
+ { path: path17.join(projectConfigDir, "npm", "node_modules"), source: "project-package" },
8083
+ { path: path17.join(agentDir, "npm", "node_modules"), source: "user-package" }
7928
8084
  ];
7929
8085
  const globalRoot = getGlobalNpmRoot2();
7930
8086
  if (globalRoot) {
@@ -7932,10 +8088,10 @@ function collectInstalledPackageSkillPaths(cwd, agentDir) {
7932
8088
  }
7933
8089
  const results = [];
7934
8090
  for (const dir of dirs) {
7935
- if (!fs15.existsSync(dir.path)) continue;
8091
+ if (!fs16.existsSync(dir.path)) continue;
7936
8092
  let entries;
7937
8093
  try {
7938
- entries = fs15.readdirSync(dir.path, { withFileTypes: true });
8094
+ entries = fs16.readdirSync(dir.path, { withFileTypes: true });
7939
8095
  } catch {
7940
8096
  continue;
7941
8097
  }
@@ -7943,22 +8099,22 @@ function collectInstalledPackageSkillPaths(cwd, agentDir) {
7943
8099
  if (entry.name.startsWith(".")) continue;
7944
8100
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
7945
8101
  if (entry.name.startsWith("@")) {
7946
- const scopeDir = path16.join(dir.path, entry.name);
8102
+ const scopeDir = path17.join(dir.path, entry.name);
7947
8103
  let scopeEntries;
7948
8104
  try {
7949
- scopeEntries = fs15.readdirSync(scopeDir, { withFileTypes: true });
8105
+ scopeEntries = fs16.readdirSync(scopeDir, { withFileTypes: true });
7950
8106
  } catch {
7951
8107
  continue;
7952
8108
  }
7953
8109
  for (const scopeEntry of scopeEntries) {
7954
8110
  if (scopeEntry.name.startsWith(".")) continue;
7955
8111
  if (!scopeEntry.isDirectory() && !scopeEntry.isSymbolicLink()) continue;
7956
- const pkgRoot2 = path16.join(scopeDir, scopeEntry.name);
8112
+ const pkgRoot2 = path17.join(scopeDir, scopeEntry.name);
7957
8113
  results.push(...extractSkillPathsFromPackageRoot(pkgRoot2, dir.source, true));
7958
8114
  }
7959
8115
  continue;
7960
8116
  }
7961
- const pkgRoot = path16.join(dir.path, entry.name);
8117
+ const pkgRoot = path17.join(dir.path, entry.name);
7962
8118
  results.push(...extractSkillPathsFromPackageRoot(pkgRoot, dir.source, true));
7963
8119
  }
7964
8120
  }
@@ -7968,8 +8124,8 @@ function collectSettingsSkillPaths(cwd, agentDir) {
7968
8124
  const results = [];
7969
8125
  const projectConfigDir = getProjectConfigDir(cwd);
7970
8126
  const settingsFiles = [
7971
- { file: path16.join(projectConfigDir, "settings.json"), base: projectConfigDir, source: "project-settings" },
7972
- { file: path16.join(agentDir, "settings.json"), base: agentDir, source: "user-settings" }
8127
+ { file: path17.join(projectConfigDir, "settings.json"), base: projectConfigDir, source: "project-settings" },
8128
+ { file: path17.join(agentDir, "settings.json"), base: agentDir, source: "user-settings" }
7973
8129
  ];
7974
8130
  for (const { file, base, source } of settingsFiles) {
7975
8131
  const settings = readOptionalJsonFile(file, "skills settings file");
@@ -7980,9 +8136,9 @@ function collectSettingsSkillPaths(cwd, agentDir) {
7980
8136
  if (typeof entry !== "string") continue;
7981
8137
  let resolved = entry;
7982
8138
  if (resolved.startsWith("~/")) {
7983
- resolved = path16.join(os6.homedir(), resolved.slice(2));
7984
- } else if (!path16.isAbsolute(resolved)) {
7985
- resolved = path16.resolve(base, resolved);
8139
+ resolved = path17.join(os7.homedir(), resolved.slice(2));
8140
+ } else if (!path17.isAbsolute(resolved)) {
8141
+ resolved = path17.resolve(base, resolved);
7986
8142
  }
7987
8143
  results.push({ path: resolved, source });
7988
8144
  }
@@ -7990,7 +8146,7 @@ function collectSettingsSkillPaths(cwd, agentDir) {
7990
8146
  return results;
7991
8147
  }
7992
8148
  function isSafePackagePath2(value) {
7993
- return value.length > 0 && !path16.isAbsolute(value) && value.split(/[\\/]/).every((part) => part.length > 0 && part !== "." && part !== "..");
8149
+ return value.length > 0 && !path17.isAbsolute(value) && value.split(/[\\/]/).every((part) => part.length > 0 && part !== "." && part !== "..");
7994
8150
  }
7995
8151
  function parseNpmPackageName2(source) {
7996
8152
  const spec = source.slice(4).trim();
@@ -8039,26 +8195,26 @@ function resolveSettingsPackageRoot2(source, baseDir) {
8039
8195
  if (!trimmed) return void 0;
8040
8196
  if (trimmed.startsWith("git:")) {
8041
8197
  const parsed = parseGitPackagePath2(trimmed);
8042
- return parsed ? path16.join(baseDir, "git", parsed.host, parsed.repoPath) : void 0;
8198
+ return parsed ? path17.join(baseDir, "git", parsed.host, parsed.repoPath) : void 0;
8043
8199
  }
8044
8200
  if (trimmed.startsWith("npm:")) {
8045
8201
  const packageName = parseNpmPackageName2(trimmed);
8046
- return packageName ? path16.join(baseDir, "npm", "node_modules", packageName) : void 0;
8202
+ return packageName ? path17.join(baseDir, "npm", "node_modules", packageName) : void 0;
8047
8203
  }
8048
8204
  const normalized = trimmed.startsWith("file:") ? trimmed.slice(5) : trimmed;
8049
- if (normalized === "~") return os6.homedir();
8050
- if (normalized.startsWith("~/")) return path16.join(os6.homedir(), normalized.slice(2));
8051
- if (path16.isAbsolute(normalized)) return normalized;
8205
+ if (normalized === "~") return os7.homedir();
8206
+ if (normalized.startsWith("~/")) return path17.join(os7.homedir(), normalized.slice(2));
8207
+ if (path17.isAbsolute(normalized)) return normalized;
8052
8208
  if (normalized === "." || normalized === ".." || normalized.startsWith("./") || normalized.startsWith("../")) {
8053
- return path16.resolve(baseDir, normalized);
8209
+ return path17.resolve(baseDir, normalized);
8054
8210
  }
8055
8211
  return void 0;
8056
8212
  }
8057
8213
  function collectSettingsPackageSkillPaths(cwd, agentDir) {
8058
8214
  const projectConfigDir = getProjectConfigDir(cwd);
8059
8215
  const settingsFiles = [
8060
- { file: path16.join(projectConfigDir, "settings.json"), base: projectConfigDir, source: "project-package" },
8061
- { file: path16.join(agentDir, "settings.json"), base: agentDir, source: "user-package" }
8216
+ { file: path17.join(projectConfigDir, "settings.json"), base: projectConfigDir, source: "project-package" },
8217
+ { file: path17.join(agentDir, "settings.json"), base: agentDir, source: "user-package" }
8062
8218
  ];
8063
8219
  const results = [];
8064
8220
  for (const { file, base, source } of settingsFiles) {
@@ -8079,10 +8235,10 @@ function collectSettingsPackageSkillPaths(cwd, agentDir) {
8079
8235
  function buildSkillPaths(cwd, agentDir) {
8080
8236
  const projectConfigDir = getProjectConfigDir(cwd);
8081
8237
  const skillPaths = [
8082
- { path: path16.join(projectConfigDir, "skills"), source: "project" },
8083
- { path: path16.join(cwd, ".agents", "skills"), source: "project" },
8084
- { path: path16.join(agentDir, "skills"), source: "user" },
8085
- { path: path16.join(os6.homedir(), ".agents", "skills"), source: "user" },
8238
+ { path: path17.join(projectConfigDir, "skills"), source: "project" },
8239
+ { path: path17.join(cwd, ".agents", "skills"), source: "project" },
8240
+ { path: path17.join(agentDir, "skills"), source: "user" },
8241
+ { path: path17.join(os7.homedir(), ".agents", "skills"), source: "user" },
8086
8242
  ...collectInstalledPackageSkillPaths(cwd, agentDir),
8087
8243
  ...collectSettingsPackageSkillPaths(cwd, agentDir),
8088
8244
  ...extractSkillPathsFromPackageRoot(cwd, "project-package"),
@@ -8090,7 +8246,7 @@ function buildSkillPaths(cwd, agentDir) {
8090
8246
  ];
8091
8247
  const deduped = /* @__PURE__ */ new Map();
8092
8248
  for (const entry of skillPaths) {
8093
- const resolvedPath = path16.resolve(entry.path);
8249
+ const resolvedPath = path17.resolve(entry.path);
8094
8250
  const existing = deduped.get(resolvedPath);
8095
8251
  if (!existing || (SOURCE_PRIORITY[entry.source] ?? 0) > (SOURCE_PRIORITY[existing.source] ?? 0)) {
8096
8252
  deduped.set(resolvedPath, { path: resolvedPath, source: entry.source });
@@ -8100,14 +8256,14 @@ function buildSkillPaths(cwd, agentDir) {
8100
8256
  }
8101
8257
  function inferSkillSource(filePath, cwd, agentDir, sourceHint) {
8102
8258
  if (sourceHint) return sourceHint;
8103
- const projectConfigRoot = path16.resolve(getProjectConfigDir(cwd));
8104
- const projectSkillsRoot = path16.resolve(projectConfigRoot, "skills");
8105
- const projectPackagesRoot = path16.resolve(projectConfigRoot, "npm", "node_modules");
8106
- const projectAgentsRoot = path16.resolve(cwd, ".agents");
8107
- const userSkillsRoot = path16.resolve(agentDir, "skills");
8108
- const userPackagesRoot = path16.resolve(agentDir, "npm", "node_modules");
8109
- const userAgentRoot = path16.resolve(agentDir);
8110
- const userAgentsRoot = path16.resolve(os6.homedir(), ".agents");
8259
+ const projectConfigRoot = path17.resolve(getProjectConfigDir(cwd));
8260
+ const projectSkillsRoot = path17.resolve(projectConfigRoot, "skills");
8261
+ const projectPackagesRoot = path17.resolve(projectConfigRoot, "npm", "node_modules");
8262
+ const projectAgentsRoot = path17.resolve(cwd, ".agents");
8263
+ const userSkillsRoot = path17.resolve(agentDir, "skills");
8264
+ const userPackagesRoot = path17.resolve(agentDir, "npm", "node_modules");
8265
+ const userAgentRoot = path17.resolve(agentDir);
8266
+ const userAgentsRoot = path17.resolve(os7.homedir(), ".agents");
8111
8267
  if (isWithinPath(filePath, projectPackagesRoot)) return "project-package";
8112
8268
  if (isWithinPath(filePath, projectSkillsRoot) || isWithinPath(filePath, projectAgentsRoot)) return "project";
8113
8269
  if (isWithinPath(filePath, projectConfigRoot)) return "project-settings";
@@ -8131,7 +8287,7 @@ function parseSkillDescription(content) {
8131
8287
  }
8132
8288
  function maybeReadSkillMetadata(filePath) {
8133
8289
  try {
8134
- const content = fs15.readFileSync(filePath, "utf-8");
8290
+ const content = fs16.readFileSync(filePath, "utf-8");
8135
8291
  return { description: parseSkillDescription(content), disableModelInvocation: maybeReadSkillDisableModelInvocation(content) };
8136
8292
  } catch {
8137
8293
  return {};
@@ -8156,8 +8312,8 @@ function collectFilesystemSkills(cwd, agentDir, skillPaths) {
8156
8312
  const visitedDirectories = /* @__PURE__ */ new Map();
8157
8313
  let order = 0;
8158
8314
  const pushEntry = (name, filePath, sourceHint) => {
8159
- const resolvedFile = path16.resolve(filePath);
8160
- if (!fs15.existsSync(resolvedFile)) return;
8315
+ const resolvedFile = path17.resolve(filePath);
8316
+ if (!fs16.existsSync(resolvedFile)) return;
8161
8317
  const source = inferSkillSource(resolvedFile, cwd, agentDir, sourceHint);
8162
8318
  const { description, disableModelInvocation } = maybeReadSkillMetadata(resolvedFile);
8163
8319
  const existingIndex = seen.get(resolvedFile);
@@ -8189,9 +8345,9 @@ function collectFilesystemSkills(cwd, agentDir, skillPaths) {
8189
8345
  const markDirectoryVisited = (dirPath, sourceHint) => {
8190
8346
  let resolvedDir;
8191
8347
  try {
8192
- resolvedDir = fs15.realpathSync(dirPath);
8348
+ resolvedDir = fs16.realpathSync(dirPath);
8193
8349
  } catch {
8194
- resolvedDir = path16.resolve(dirPath);
8350
+ resolvedDir = path17.resolve(dirPath);
8195
8351
  }
8196
8352
  const priority = sourceHint ? SOURCE_PRIORITY[sourceHint] ?? 0 : SOURCE_PRIORITY.unknown;
8197
8353
  const previousPriority = visitedDirectories.get(resolvedDir);
@@ -8201,24 +8357,24 @@ function collectFilesystemSkills(cwd, agentDir, skillPaths) {
8201
8357
  };
8202
8358
  const walkSkillDirectories = (dirPath, sourceHint) => {
8203
8359
  if (!markDirectoryVisited(dirPath, sourceHint)) return;
8204
- const skillFile = path16.join(dirPath, "SKILL.md");
8205
- if (fs15.existsSync(skillFile)) {
8206
- pushEntry(path16.basename(dirPath), skillFile, sourceHint);
8360
+ const skillFile = path17.join(dirPath, "SKILL.md");
8361
+ if (fs16.existsSync(skillFile)) {
8362
+ pushEntry(path17.basename(dirPath), skillFile, sourceHint);
8207
8363
  return;
8208
8364
  }
8209
8365
  let entriesInDir;
8210
8366
  try {
8211
- entriesInDir = fs15.readdirSync(dirPath, { withFileTypes: true });
8367
+ entriesInDir = fs16.readdirSync(dirPath, { withFileTypes: true });
8212
8368
  } catch {
8213
8369
  return;
8214
8370
  }
8215
8371
  for (const entry of entriesInDir) {
8216
8372
  if (shouldSkipDirectory(entry.name)) continue;
8217
8373
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
8218
- const entryPath = path16.join(dirPath, entry.name);
8374
+ const entryPath = path17.join(dirPath, entry.name);
8219
8375
  let stat;
8220
8376
  try {
8221
- stat = fs15.statSync(entryPath);
8377
+ stat = fs16.statSync(entryPath);
8222
8378
  } catch {
8223
8379
  continue;
8224
8380
  }
@@ -8228,41 +8384,41 @@ function collectFilesystemSkills(cwd, agentDir, skillPaths) {
8228
8384
  }
8229
8385
  };
8230
8386
  for (const skillPath of skillPaths) {
8231
- if (!fs15.existsSync(skillPath.path)) continue;
8387
+ if (!fs16.existsSync(skillPath.path)) continue;
8232
8388
  let stat;
8233
8389
  try {
8234
- stat = fs15.statSync(skillPath.path);
8390
+ stat = fs16.statSync(skillPath.path);
8235
8391
  } catch {
8236
8392
  continue;
8237
8393
  }
8238
8394
  if (stat.isFile()) {
8239
- const fileName = path16.basename(skillPath.path);
8395
+ const fileName = path17.basename(skillPath.path);
8240
8396
  if (!fileName.toLowerCase().endsWith(".md")) continue;
8241
- const skillName = fileName.toLowerCase() === "skill.md" ? path16.basename(path16.dirname(skillPath.path)) : path16.basename(fileName, path16.extname(fileName));
8397
+ const skillName = fileName.toLowerCase() === "skill.md" ? path17.basename(path17.dirname(skillPath.path)) : path17.basename(fileName, path17.extname(fileName));
8242
8398
  pushEntry(skillName, skillPath.path, skillPath.source);
8243
8399
  continue;
8244
8400
  }
8245
8401
  if (!stat.isDirectory()) continue;
8246
- const rootSkillFile = path16.join(skillPath.path, "SKILL.md");
8247
- if (fs15.existsSync(rootSkillFile)) {
8248
- pushEntry(path16.basename(skillPath.path), rootSkillFile, skillPath.source);
8402
+ const rootSkillFile = path17.join(skillPath.path, "SKILL.md");
8403
+ if (fs16.existsSync(rootSkillFile)) {
8404
+ pushEntry(path17.basename(skillPath.path), rootSkillFile, skillPath.source);
8249
8405
  continue;
8250
8406
  }
8251
8407
  markDirectoryVisited(skillPath.path, skillPath.source);
8252
8408
  let childEntries;
8253
8409
  try {
8254
- childEntries = fs15.readdirSync(skillPath.path, { withFileTypes: true });
8410
+ childEntries = fs16.readdirSync(skillPath.path, { withFileTypes: true });
8255
8411
  } catch {
8256
8412
  continue;
8257
8413
  }
8258
8414
  for (const child of childEntries) {
8259
8415
  if (child.name.startsWith(".")) continue;
8260
- const childPath = path16.join(skillPath.path, child.name);
8416
+ const childPath = path17.join(skillPath.path, child.name);
8261
8417
  if (child.isDirectory() || child.isSymbolicLink()) {
8262
8418
  if (shouldSkipDirectory(child.name)) continue;
8263
8419
  let childStat;
8264
8420
  try {
8265
- childStat = fs15.statSync(childPath);
8421
+ childStat = fs16.statSync(childPath);
8266
8422
  } catch {
8267
8423
  continue;
8268
8424
  }
@@ -8270,7 +8426,7 @@ function collectFilesystemSkills(cwd, agentDir, skillPaths) {
8270
8426
  continue;
8271
8427
  }
8272
8428
  if (child.isFile() && child.name.toLowerCase().endsWith(".md")) {
8273
- pushEntry(path16.basename(child.name, path16.extname(child.name)), childPath, skillPath.source);
8429
+ pushEntry(path17.basename(child.name, path17.extname(child.name)), childPath, skillPath.source);
8274
8430
  }
8275
8431
  }
8276
8432
  }
@@ -8286,8 +8442,8 @@ function getCachedSkills(cwd) {
8286
8442
  const loaded = collectFilesystemSkills(cwd, agentDir, skillPaths);
8287
8443
  const dedupedByName = /* @__PURE__ */ new Map();
8288
8444
  for (const entry of loaded) {
8289
- const current = dedupedByName.get(entry.name);
8290
- dedupedByName.set(entry.name, chooseHigherPrioritySkill(current, entry));
8445
+ const current2 = dedupedByName.get(entry.name);
8446
+ dedupedByName.set(entry.name, chooseHigherPrioritySkill(current2, entry));
8291
8447
  }
8292
8448
  const skills = [...dedupedByName.values()].sort((a, b) => a.order - b.order);
8293
8449
  loadSkillsCache = { cwd, agentDir, skills, timestamp: now };
@@ -8301,12 +8457,12 @@ function resolveSkillPath(skillName, cwd) {
8301
8457
  }
8302
8458
  function readSkill(skillName, skillPath, source) {
8303
8459
  try {
8304
- const stat = fs15.statSync(skillPath);
8460
+ const stat = fs16.statSync(skillPath);
8305
8461
  const cached = skillCache.get(skillPath);
8306
8462
  if (cached && cached.mtime === stat.mtimeMs) {
8307
8463
  return cached.skill;
8308
8464
  }
8309
- const raw = fs15.readFileSync(skillPath, "utf-8");
8465
+ const raw = fs16.readFileSync(skillPath, "utf-8");
8310
8466
  const content = stripSkillFrontmatter(raw);
8311
8467
  const description = parseSkillDescription(raw);
8312
8468
  const disableModelInvocation = maybeReadSkillDisableModelInvocation(raw);
@@ -8335,7 +8491,7 @@ function resolveSkills(skillNames, cwd, localSkillPaths, localBaseDir) {
8335
8491
  if (localSkillPaths?.length) {
8336
8492
  const agentDir = getAgentDir();
8337
8493
  const localEntries = collectFilesystemSkills(cwd, agentDir, localSkillPaths.map((entry) => ({
8338
- path: path16.resolve(localBaseDir ?? cwd, entry),
8494
+ path: path17.resolve(localBaseDir ?? cwd, entry),
8339
8495
  source: "unknown"
8340
8496
  })));
8341
8497
  for (const entry of localEntries) {
@@ -8363,7 +8519,7 @@ function resolveSkills(skillNames, cwd, localSkillPaths, localBaseDir) {
8363
8519
  function resolveSkillsWithFallback(skillNames, primaryCwd, fallbackCwd, localSkillPaths, localBaseDir) {
8364
8520
  const primary = resolveSkills(skillNames, primaryCwd, localSkillPaths, localBaseDir);
8365
8521
  if (!fallbackCwd || primary.missing.length === 0) return primary;
8366
- if (path16.resolve(primaryCwd) === path16.resolve(fallbackCwd)) return primary;
8522
+ if (path17.resolve(primaryCwd) === path17.resolve(fallbackCwd)) return primary;
8367
8523
  const fallback = resolveSkills(primary.missing, fallbackCwd);
8368
8524
  return {
8369
8525
  resolved: [...primary.resolved, ...fallback.resolved],
@@ -8438,6 +8594,7 @@ export {
8438
8594
  CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL,
8439
8595
  isCodeOwnedExternalCliAdapterId,
8440
8596
  validateCodeOwnedProfileRunner,
8597
+ EXTERNAL_CLI_ADAPTER_SAFETY,
8441
8598
  parseExternalCliCapabilityNarrowing,
8442
8599
  resolveExternalCliRunnerStatus,
8443
8600
  normalizeExternalCliRunnerStatus,
@@ -8449,6 +8606,17 @@ export {
8449
8606
  buildSkillInjection,
8450
8607
  normalizeSkillInput,
8451
8608
  discoverAvailableSkills,
8609
+ REX_LOCAL_MACHINE,
8610
+ REX_EXIT_GONE,
8611
+ REX_EXIT_UNREACHABLE,
8612
+ isRexLocalMachine,
8613
+ REX_BUNDLE_BIN,
8614
+ REX_CALL_TIMEOUT_MS,
8615
+ REX_MAX_OUTPUT,
8616
+ rexGlobalArgs,
8617
+ resolveRexBinary,
8618
+ rexCommandEnv,
8619
+ resolveRexLocalPlacement,
8452
8620
  extractChildWrittenOutput,
8453
8621
  normalizeSingleOutputOverride,
8454
8622
  resolveSingleOutputPath,
@@ -8509,6 +8677,7 @@ export {
8509
8677
  scopedModelIdsFromContext,
8510
8678
  normalizeModelSegment,
8511
8679
  resolveModelCandidate,
8680
+ isUnavailableSubagentModel,
8512
8681
  resolveSubagentModelOverride,
8513
8682
  resolveEffectiveSubagentModel,
8514
8683
  resolveModelOrigin,
@@ -8571,9 +8740,11 @@ export {
8571
8740
  MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR,
8572
8741
  formatStructuredOutputRejectionError,
8573
8742
  createStructuredOutputToolParameters,
8743
+ structuredOutputValidatorReady,
8574
8744
  assertJsonSchemaObject,
8575
8745
  createStructuredOutputRuntime,
8576
8746
  validateStructuredOutputValue,
8747
+ prepareStructuredOutputArguments,
8577
8748
  cleanupStructuredOutputRuntime,
8578
8749
  ChainOutputValidationError,
8579
8750
  validateChainOutputBindings,
@@ -8593,6 +8764,7 @@ export {
8593
8764
  childWatchdogProgressForModel,
8594
8765
  isAgentContract,
8595
8766
  attachContractProjections,
8767
+ normalizeAcceptanceInput,
8596
8768
  resolveAcceptanceReportMode,
8597
8769
  parseGateInput,
8598
8770
  acceptanceHasTypedVerify,
@@ -8625,6 +8797,9 @@ export {
8625
8797
  projectScopeRequiresTrustMessage,
8626
8798
  BUILTIN_AGENT_NAMES,
8627
8799
  buildAgentMemoryInjection,
8800
+ DEFAULT_WAIT_TOOL_NAME,
8801
+ waitToolName,
8802
+ setWaitToolName,
8628
8803
  redactSecretValues,
8629
8804
  validatePermissionRules,
8630
8805
  validatePermissionConfig,