@ashx-j/lunr-dev 0.2.40-dev.54.2 → 0.2.40-dev.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/builtin-extensions/pi-subagents/src/runs/background/attempt-usage.d.ts +5 -0
  2. package/dist/builtin-extensions/pi-subagents/src/runs/background/attempt-usage.js +31 -0
  3. package/dist/builtin-extensions/pi-subagents/src/runs/background/child-stream.d.ts +65 -0
  4. package/dist/builtin-extensions/pi-subagents/src/runs/background/child-stream.js +456 -0
  5. package/dist/builtin-extensions/pi-subagents/src/runs/background/parallel-group-status.d.ts +42 -0
  6. package/dist/builtin-extensions/pi-subagents/src/runs/background/parallel-group-status.js +79 -0
  7. package/dist/builtin-extensions/pi-subagents/src/runs/background/run-log.d.ts +18 -0
  8. package/dist/builtin-extensions/pi-subagents/src/runs/background/run-log.js +43 -0
  9. package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-event-log.d.ts +3 -0
  10. package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-event-log.js +70 -0
  11. package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-single-step.d.ts +92 -0
  12. package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-single-step.js +491 -0
  13. package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-status.d.ts +64 -0
  14. package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-status.js +26 -0
  15. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts +1 -115
  16. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +17 -1160
  17. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.d.ts +19 -0
  18. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.js +331 -0
  19. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.d.ts +37 -0
  20. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.js +321 -0
  21. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/executor-types.d.ts +124 -0
  22. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/executor-types.js +2 -0
  23. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.d.ts +17 -0
  24. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.js +98 -0
  25. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.d.ts +40 -0
  26. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.js +172 -0
  27. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.d.ts +14 -0
  28. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.js +161 -0
  29. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.d.ts +46 -0
  30. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.js +195 -0
  31. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.d.ts +10 -0
  32. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.js +537 -0
  33. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts +5 -81
  34. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +26 -1763
  35. package/dist/builtin-extensions/pi-subagents/src/shared/settings.d.ts +1 -1
  36. package/dist/core/credential-files.d.ts +3 -2
  37. package/dist/core/credential-files.js +10 -4
  38. package/dist/core/permissions.d.ts +6 -0
  39. package/dist/core/permissions.js +6 -0
  40. package/dist/core/tool-call-hooks.js +3 -2
  41. package/dist/node-runtime/{acp-mode-CFYSYACH.js → acp-mode-5KZPFZBO.js} +2 -2
  42. package/dist/node-runtime/{agent-session-services-3ZHQJIKF.js → agent-session-services-KH5CIGC3.js} +5 -5
  43. package/dist/node-runtime/{builtin-extensions-VQHK3YKF.js → builtin-extensions-RZS4SMIS.js} +3 -3
  44. package/dist/node-runtime/{chunk-UZMXBZQT.js → chunk-AKQRASEH.js} +9 -9
  45. package/dist/node-runtime/{chunk-4ZEDT3YW.js → chunk-BJXBM6KD.js} +3 -3
  46. package/dist/node-runtime/{chunk-BNNBTBXY.js → chunk-EJMB4PAV.js} +3 -3
  47. package/dist/node-runtime/{chunk-HVXDYQNN.js → chunk-JI7AUY2T.js} +1 -1
  48. package/dist/node-runtime/{chunk-ITVBE3HR.js → chunk-JJTHGEUS.js} +5 -4
  49. package/dist/node-runtime/{chunk-YDY7A2WB.js → chunk-K24P7GMM.js} +7 -7
  50. package/dist/node-runtime/{chunk-KTCZH72R.js → chunk-LGRRFSE7.js} +3 -2
  51. package/dist/node-runtime/{chunk-7LCR56AK.js → chunk-NWYFKXP5.js} +1 -1
  52. package/dist/node-runtime/{chunk-SV42POA3.js → chunk-PGWSMQ4K.js} +1 -1
  53. package/dist/node-runtime/{chunk-YDMZHLBV.js → chunk-QX5I7QEW.js} +1 -1
  54. package/dist/node-runtime/{chunk-BNZXW77G.js → chunk-RXDLSXEC.js} +1 -1
  55. package/dist/node-runtime/{chunk-N574FRFF.js → chunk-TSZESZ6H.js} +2 -2
  56. package/dist/node-runtime/{chunk-VIYDTWDK.js → chunk-U7MTVVT3.js} +606 -604
  57. package/dist/node-runtime/{chunk-MFDTF25H.js → chunk-UTZCCNFC.js} +5 -5
  58. package/dist/node-runtime/{chunk-U2LTTIWZ.js → chunk-WYJUGRVE.js} +1 -1
  59. package/dist/node-runtime/{chunk-7LNPTBQJ.js → chunk-XPKOWSYN.js} +6 -2
  60. package/dist/node-runtime/{chunk-2ZI6Q6JG.js → chunk-YFXGOLZ6.js} +1 -1
  61. package/dist/node-runtime/{command-SRDEBPUR.js → command-6S6C62CX.js} +1 -1
  62. package/dist/node-runtime/{commands-7EETGZ7V.js → commands-GSZWAQJW.js} +5 -5
  63. package/dist/node-runtime/{commands-CV2JUYHM.js → commands-MM2TPV5I.js} +4 -4
  64. package/dist/node-runtime/{direct-tool-executor-DNZ2MS6Z.js → direct-tool-executor-WJLVHH7U.js} +6 -6
  65. package/dist/node-runtime/{gateway-AMEMDTUT.js → gateway-CWIWPUVC.js} +6 -6
  66. package/dist/node-runtime/index.js +10 -10
  67. package/dist/node-runtime/{init-G23PFPKF.js → init-P3RQ6EFK.js} +5 -5
  68. package/dist/node-runtime/{interactive-mode-7GX3UJFX.js → interactive-mode-2L5JMVKQ.js} +6 -6
  69. package/dist/node-runtime/{lunr-cron-OMQBN3UK.js → lunr-cron-LT3O64NO.js} +4 -4
  70. package/dist/node-runtime/main.js +7 -7
  71. package/dist/node-runtime/{mobile-commands-JQJU35OT.js → mobile-commands-PFXEWP2R.js} +3 -3
  72. package/dist/node-runtime/{pi-mcp-adapter-NKAL5CFR.js → pi-mcp-adapter-2OP5BBC6.js} +8 -8
  73. package/dist/node-runtime/{pi-subagents-36KOL5SV.js → pi-subagents-G2T5XRAX.js} +6 -6
  74. package/dist/node-runtime/{print-mode-Y363FXY4.js → print-mode-S6ZUVPMU.js} +6 -6
  75. package/dist/node-runtime/{proxy-modes-EEYRUGQL.js → proxy-modes-RD2PQ6UH.js} +6 -6
  76. package/dist/node-runtime/rpc-entry.js +7 -7
  77. package/dist/node-runtime/{rpc-mode-ENVT7AXW.js → rpc-mode-C33WERBG.js} +3 -3
  78. package/dist/node-runtime/{src-Y3S2FIS5.js → src-J6FSKIFT.js} +1 -1
  79. package/dist/node-runtime/{subagent-executor-D42G55F5.js → subagent-executor-RTGKJ35C.js} +1924 -1901
  80. package/install-lock/package-lock.json +24 -24
  81. package/install-lock/package.json +2 -2
  82. package/npm-shrinkwrap.json +12 -12
  83. package/package.json +4 -4
@@ -144,7 +144,7 @@ import {
144
144
  writeNestedControlRequest,
145
145
  writeNestedEvent,
146
146
  writePrivateAtomicJson
147
- } from "./chunk-VIYDTWDK.js";
147
+ } from "./chunk-U7MTVVT3.js";
148
148
  import {
149
149
  ASYNC_DIR,
150
150
  CHAIN_RUNS_DIR,
@@ -200,19 +200,19 @@ import {
200
200
  removeOnExit,
201
201
  resolveChildPermissions,
202
202
  snapshotParentPermissionMode
203
- } from "./chunk-BNNBTBXY.js";
203
+ } from "./chunk-EJMB4PAV.js";
204
204
  import {
205
205
  snapshotParentAutoReview
206
- } from "./chunk-SV42POA3.js";
206
+ } from "./chunk-PGWSMQ4K.js";
207
207
  import "./chunk-YSB6URMT.js";
208
208
  import "./chunk-IAZSK7KK.js";
209
209
  import "./chunk-TCT6PCUR.js";
210
210
  import {
211
211
  resolveSubagentRequestParams
212
- } from "./chunk-KTCZH72R.js";
212
+ } from "./chunk-LGRRFSE7.js";
213
213
  import {
214
214
  protectedTargetWriteReason
215
- } from "./chunk-7LNPTBQJ.js";
215
+ } from "./chunk-XPKOWSYN.js";
216
216
  import "./chunk-BDRGN3L2.js";
217
217
  import "./chunk-4SBPXNVV.js";
218
218
  import "./chunk-53YJI7JU.js";
@@ -248,9 +248,9 @@ import {
248
248
  import "./chunk-BRJX2PRC.js";
249
249
 
250
250
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js
251
- import { randomUUID as randomUUID4 } from "node:crypto";
252
- import * as fs16 from "node:fs";
253
- import * as path16 from "node:path";
251
+ import { randomUUID as randomUUID7 } from "node:crypto";
252
+ import * as fs17 from "node:fs";
253
+ import * as path19 from "node:path";
254
254
 
255
255
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.js
256
256
  import { matchesKey, visibleWidth, truncateToWidth } from "@ashx-j/lunr-tui";
@@ -1323,20 +1323,20 @@ function resolvePiPackageRoot() {
1323
1323
  return;
1324
1324
  }
1325
1325
  }
1326
- function isRunnableNodeScript(filePath, existsSync11) {
1327
- return existsSync11(filePath) ? /\.(?:mjs|cjs|js)$/i.test(filePath) : !1;
1326
+ function isRunnableNodeScript(filePath, existsSync12) {
1327
+ return existsSync12(filePath) ? /\.(?:mjs|cjs|js)$/i.test(filePath) : !1;
1328
1328
  }
1329
1329
  function normalizePath(filePath) {
1330
1330
  return path3.isAbsolute(filePath) ? filePath : path3.resolve(filePath);
1331
1331
  }
1332
1332
  function resolvePiCliScript(deps = {}) {
1333
- let existsSync11 = deps.existsSync ?? fs3.existsSync, realpathSync5 = deps.realpathSync ?? fs3.realpathSync, readFileSync9 = deps.readFileSync ?? ((filePath, encoding) => fs3.readFileSync(filePath, encoding)), argv1 = deps.argv1 ?? process.argv[1];
1333
+ let existsSync12 = deps.existsSync ?? fs3.existsSync, realpathSync5 = deps.realpathSync ?? fs3.realpathSync, readFileSync9 = deps.readFileSync ?? ((filePath, encoding) => fs3.readFileSync(filePath, encoding)), argv1 = deps.argv1 ?? process.argv[1];
1334
1334
  if (argv1) {
1335
1335
  let argvPath = normalizePath(argv1);
1336
- if (isRunnableNodeScript(argvPath, existsSync11))
1336
+ if (isRunnableNodeScript(argvPath, existsSync12))
1337
1337
  try {
1338
1338
  let canonicalArgvPath = realpathSync5(argvPath);
1339
- if (isRunnableNodeScript(canonicalArgvPath, existsSync11) && findPiPackageRootFromEntry(canonicalArgvPath))
1339
+ if (isRunnableNodeScript(canonicalArgvPath, existsSync12) && findPiPackageRootFromEntry(canonicalArgvPath))
1340
1340
  return canonicalArgvPath;
1341
1341
  } catch {
1342
1342
  }
@@ -1354,7 +1354,7 @@ function resolvePiCliScript(deps = {}) {
1354
1354
  if (!binPath)
1355
1355
  return;
1356
1356
  let candidate = path3.resolve(path3.dirname(packageJsonPath), binPath);
1357
- if (isRunnableNodeScript(candidate, existsSync11))
1357
+ if (isRunnableNodeScript(candidate, existsSync12))
1358
1358
  return candidate;
1359
1359
  } catch {
1360
1360
  return;
@@ -1414,7 +1414,7 @@ function createJsonlWriter(filePath, source, deps = {}) {
1414
1414
  return;
1415
1415
  closed = !0;
1416
1416
  let current = stream;
1417
- stream = void 0, await new Promise((resolve7) => current.end(() => resolve7()));
1417
+ stream = void 0, await new Promise((resolve8) => current.end(() => resolve8()));
1418
1418
  }
1419
1419
  };
1420
1420
  }
@@ -1872,7 +1872,7 @@ async function runSingleAttempt(runtimeCwd, spec, task, model, options, shared)
1872
1872
  tokens: progress.tokens,
1873
1873
  durationMs: progress.durationMs
1874
1874
  }, result2;
1875
- let spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) }, observedMutationAttempt = !1, exitCode = await new Promise((resolve7) => {
1875
+ let spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) }, observedMutationAttempt = !1, exitCode = await new Promise((resolve8) => {
1876
1876
  let spawnSpec = getPiSpawnCommand(args), proc = spawn(spawnSpec.command, spawnSpec.args, {
1877
1877
  cwd: options.cwd ?? runtimeCwd,
1878
1878
  env: spawnEnv,
@@ -1966,7 +1966,7 @@ async function runSingleAttempt(runtimeCwd, spec, task, model, options, shared)
1966
1966
  return;
1967
1967
  options.intercomEvents?.emit(INTERCOM_DETACH_RESPONSE_EVENT, { requestId, accepted: !0, runId: options.runId, agent: spec.childId, childIndex: options.index ?? 0 }), detachForIntercom();
1968
1968
  }), finish = (code) => {
1969
- settled || (settled = !0, clearCancellationTimers(), clearFinalDrainTimers(), clearWatchdogTailTimer(), clearStdioGuard(), clearTimeoutTimers(), clearTurnBudgetTimers(), protocolHardKillTimer && (clearTimeout(protocolHardKillTimer), protocolHardKillTimer = void 0), activityTimer && (clearInterval(activityTimer), activityTimer = void 0), unsubscribeIntercomDetach?.(), removeAbortListener?.(), removeInterruptListener?.(), resolve7(code));
1969
+ settled || (settled = !0, clearCancellationTimers(), clearFinalDrainTimers(), clearWatchdogTailTimer(), clearStdioGuard(), clearTimeoutTimers(), clearTurnBudgetTimers(), protocolHardKillTimer && (clearTimeout(protocolHardKillTimer), protocolHardKillTimer = void 0), activityTimer && (clearInterval(activityTimer), activityTimer = void 0), unsubscribeIntercomDetach?.(), removeAbortListener?.(), removeInterruptListener?.(), resolve8(code));
1970
1970
  }, drainPendingControlEvents = () => {
1971
1971
  if (pendingControlEvents.length === 0)
1972
1972
  return;
@@ -4199,8 +4199,8 @@ function isAsyncAvailable() {
4199
4199
  return jitiCliPath !== void 0;
4200
4200
  }
4201
4201
  function isNodeExecutableName(execPath) {
4202
- let basename3 = path8.basename(execPath).toLowerCase();
4203
- return basename3 === "node" || basename3 === "node.exe" || basename3 === "nodejs" || basename3 === "nodejs.exe";
4202
+ let basename4 = path8.basename(execPath).toLowerCase();
4203
+ return basename4 === "node" || basename4 === "node.exe" || basename4 === "nodejs" || basename4 === "nodejs.exe";
4204
4204
  }
4205
4205
  function canUseCurrentNodeExecutable(execPath) {
4206
4206
  try {
@@ -5120,79 +5120,10 @@ function handleWatchdogToolAction(action, _params, ctx, runtime) {
5120
5120
  }
5121
5121
  var WATCHDOG_TOOL_ACTIONS = ["watchdog.status", "watchdog.check", "watchdog.recommend-model"];
5122
5122
 
5123
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/chain-append.js
5123
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js
5124
5124
  import { randomUUID } from "node:crypto";
5125
5125
  import * as fs11 from "node:fs";
5126
5126
  import * as path10 from "node:path";
5127
- var APPEND_REQUESTS_DIR = "append-requests";
5128
- function appendDir(asyncDir) {
5129
- return path10.join(asyncDir, APPEND_REQUESTS_DIR);
5130
- }
5131
- function appendRequestPath(asyncDir, request) {
5132
- return path10.join(appendDir(asyncDir), `${request.createdAt}-${request.id}.json`);
5133
- }
5134
- function listAppendRequestFiles(asyncDir) {
5135
- let dir = appendDir(asyncDir);
5136
- try {
5137
- return fs11.readdirSync(dir).filter((entry) => entry.endsWith(".json")).map((entry) => path10.join(dir, entry)).sort();
5138
- } catch (error) {
5139
- if (error.code === "ENOENT")
5140
- return [];
5141
- throw error;
5142
- }
5143
- }
5144
- function countPendingChainAppendRequests(asyncDir) {
5145
- return listAppendRequestFiles(asyncDir).length;
5146
- }
5147
- function runnerStepOutputNames(steps) {
5148
- let names = [];
5149
- for (let step of steps)
5150
- isParallelGroup(step) ? names.push(...step.parallel.map((task) => task.outputName).filter((name) => !!name)) : isDynamicRunnerGroup(step) ? step.collect.as && names.push(step.collect.as) : step.outputName && names.push(step.outputName);
5151
- return names;
5152
- }
5153
- function enqueueChainAppendRequest(input) {
5154
- let status = readStatus(input.asyncDir);
5155
- if (!status)
5156
- throw new Error(`No async run status found for '${input.runId}'.`);
5157
- if (status.runId !== input.runId)
5158
- throw new Error(`Async run id mismatch: expected '${input.runId}', found '${status.runId}'.`);
5159
- if (status.mode !== "chain")
5160
- throw new Error(`Run '${input.runId}' is ${status.mode}; only active chain runs accept appended steps.`);
5161
- if (status.state !== "running")
5162
- throw new Error(`Run '${input.runId}' is ${status.state}; only running chain runs accept appended steps.`);
5163
- if (!((status.steps ?? []).some((step) => step.status === "running" || step.status === "pending") || (status.pendingAppends ?? 0) > 0))
5164
- throw new Error(`Run '${input.runId}' has no running or pending chain steps left; append-step must target an in-progress chain.`);
5165
- if (input.steps.length === 0)
5166
- throw new Error("append-step requires one chain step.");
5167
- let request = {
5168
- id: randomUUID(),
5169
- createdAt: input.now ?? Date.now(),
5170
- steps: input.steps
5171
- };
5172
- fs11.mkdirSync(appendDir(input.asyncDir), { recursive: !0 }), writeAtomicJson(appendRequestPath(input.asyncDir, request), request);
5173
- let pendingCount = countPendingChainAppendRequests(input.asyncDir), statusPath = path10.join(input.asyncDir, "status.json"), updatedStatus = { ...status, pendingAppends: pendingCount, lastUpdate: request.createdAt };
5174
- return writeAtomicJson(statusPath, updatedStatus), appendJsonl(path10.join(input.asyncDir, "events.jsonl"), JSON.stringify({
5175
- type: "subagent.chain.append.requested",
5176
- ts: request.createdAt,
5177
- runId: input.runId,
5178
- requestId: request.id,
5179
- stepCount: input.steps.length,
5180
- pendingAppends: pendingCount
5181
- })), { request, pendingCount };
5182
- }
5183
- function readAppendRequest(filePath) {
5184
- let raw = JSON.parse(fs11.readFileSync(filePath, "utf-8"));
5185
- if (!(!raw.id || typeof raw.id != "string") && !(typeof raw.createdAt != "number" || !Number.isFinite(raw.createdAt)) && !(!Array.isArray(raw.steps) || raw.steps.length === 0))
5186
- return { id: raw.id, createdAt: raw.createdAt, steps: raw.steps };
5187
- }
5188
- function readPendingChainAppendRequests(asyncDir) {
5189
- return listAppendRequestFiles(asyncDir).map((filePath) => readAppendRequest(filePath)).filter((request) => !!request).sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id));
5190
- }
5191
-
5192
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js
5193
- import { randomUUID as randomUUID2 } from "node:crypto";
5194
- import * as fs12 from "node:fs";
5195
- import * as path11 from "node:path";
5196
5127
  function resolveSubagentContext(value) {
5197
5128
  return value === "fork" ? "fork" : "fresh";
5198
5129
  }
@@ -5216,11 +5147,11 @@ function isUnsafeAnthropicThinkingBlock(message, block) {
5216
5147
  function createEntryId(entries) {
5217
5148
  let ids = new Set(entries.map((entry) => entry.id).filter((id) => typeof id == "string"));
5218
5149
  for (let attempt = 0; attempt < 100; attempt++) {
5219
- let id = randomUUID2().slice(0, 8);
5150
+ let id = randomUUID().slice(0, 8);
5220
5151
  if (!ids.has(id))
5221
5152
  return id;
5222
5153
  }
5223
- return randomUUID2();
5154
+ return randomUUID();
5224
5155
  }
5225
5156
  function appendThinkingOffEntry(entries) {
5226
5157
  let last = entries[entries.length - 1];
@@ -5246,7 +5177,7 @@ function sanitizeUnsafeThinkingBlocks(entries) {
5246
5177
  return sanitized;
5247
5178
  }
5248
5179
  function readSessionEntries(sessionFile) {
5249
- return fs12.readFileSync(sessionFile, "utf-8").split(`
5180
+ return fs11.readFileSync(sessionFile, "utf-8").split(`
5250
5181
  `).filter((line) => line.trim().length > 0).map((line, index) => {
5251
5182
  try {
5252
5183
  return JSON.parse(line);
@@ -5275,22 +5206,22 @@ function createForkContextResolver(sessionManager, requestedContext, options = {
5275
5206
  if (cached)
5276
5207
  return cached;
5277
5208
  try {
5278
- if (!fs12.existsSync(parentSessionFile))
5209
+ if (!fs11.existsSync(parentSessionFile))
5279
5210
  throw new Error(`Parent session file does not exist: ${parentSessionFile}. Pi has not persisted enough history to fork yet.`);
5280
5211
  let sourceManager = openSession(parentSessionFile, sessionDir), sessionFile = sourceManager.createBranchedSession(leafId);
5281
5212
  if (!sessionFile)
5282
5213
  throw new Error("Session manager did not return a forked session file.");
5283
5214
  let forceThinkingOff = (sanitized) => sanitized && (options.forceThinkingOffForIndex?.(index) ?? !0), thinkingOverride;
5284
- if (fs12.existsSync(sessionFile)) {
5215
+ if (fs11.existsSync(sessionFile)) {
5285
5216
  let entries = readSessionEntries(sessionFile);
5286
- sanitizeUnsafeThinkingBlocks(entries) && (forceThinkingOff(!0) && (appendThinkingOffEntry(entries), thinkingOverride = "off"), fs12.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join(`
5217
+ sanitizeUnsafeThinkingBlocks(entries) && (forceThinkingOff(!0) && (appendThinkingOffEntry(entries), thinkingOverride = "off"), fs11.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join(`
5287
5218
  `)}
5288
5219
  `, "utf-8"));
5289
5220
  } else {
5290
5221
  let header = sourceManager.getHeader?.(), entries = sourceManager.getEntries?.();
5291
5222
  if (!header || !entries)
5292
5223
  throw new Error(`Session manager returned a forked session file that does not exist and cannot be persisted by fallback: ${sessionFile}`);
5293
- forceThinkingOff(sanitizeUnsafeThinkingBlocks(entries)) && (appendThinkingOffEntry(entries), thinkingOverride = "off"), fs12.mkdirSync(path11.dirname(sessionFile), { recursive: !0 }), fs12.writeFileSync(sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join(`
5224
+ forceThinkingOff(sanitizeUnsafeThinkingBlocks(entries)) && (appendThinkingOffEntry(entries), thinkingOverride = "off"), fs11.mkdirSync(path10.dirname(sessionFile), { recursive: !0 }), fs11.writeFileSync(sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join(`
5294
5225
  `)}
5295
5226
  `, "utf-8");
5296
5227
  }
@@ -5311,18 +5242,9 @@ function createForkContextResolver(sessionManager, requestedContext, options = {
5311
5242
  };
5312
5243
  }
5313
5244
 
5314
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.js
5315
- function lunrContextPolicy(params) {
5316
- return {
5317
- params: { ...params, context: "fresh" },
5318
- contextForAgent: () => "fresh",
5319
- usesFork: !1
5320
- };
5321
- }
5322
-
5323
5245
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/steering.js
5324
- import * as fs13 from "node:fs";
5325
- import * as path12 from "node:path";
5246
+ import * as fs12 from "node:fs";
5247
+ import * as path11 from "node:path";
5326
5248
  function incrementStateCount(status, state) {
5327
5249
  state === "scheduled" ? status.scheduled++ : state === "routed" ? status.pending++ : state === "delivered" || state === "late" ? status.delivered++ : state === "failed" ? status.failed++ : state === "recovered" && status.recovered++;
5328
5250
  }
@@ -5354,29 +5276,29 @@ function steeringActionIsTerminal(result2) {
5354
5276
  return result2?.state === "delivered" || result2?.state === "scheduled" || result2?.state === "partial" || result2?.state === "recovered" || result2?.state === "failed";
5355
5277
  }
5356
5278
  function claimSteeringRecovery(asyncDir, input) {
5357
- let recoveryDir = path12.join(asyncDir, "control", "steer-recovery");
5358
- fs13.mkdirSync(recoveryDir, { recursive: !0, mode: 448 });
5359
- let claimPath = path12.join(recoveryDir, "claim.json"), fd;
5279
+ let recoveryDir = path11.join(asyncDir, "control", "steer-recovery");
5280
+ fs12.mkdirSync(recoveryDir, { recursive: !0, mode: 448 });
5281
+ let claimPath = path11.join(recoveryDir, "claim.json"), fd;
5360
5282
  try {
5361
- fd = fs13.openSync(claimPath, "wx", 384);
5283
+ fd = fs12.openSync(claimPath, "wx", 384);
5362
5284
  } catch (error) {
5363
5285
  throw error.code === "EEXIST" ? new Error("Another steering recovery is already committed for this source run.") : error;
5364
5286
  }
5365
5287
  let writeError;
5366
5288
  try {
5367
- fs13.writeFileSync(fd, JSON.stringify({ version: 1, ...input }, null, 2), "utf-8"), fs13.fsyncSync(fd);
5289
+ fs12.writeFileSync(fd, JSON.stringify({ version: 1, ...input }, null, 2), "utf-8"), fs12.fsyncSync(fd);
5368
5290
  } catch (error) {
5369
5291
  writeError = error;
5370
5292
  } finally {
5371
- fs13.closeSync(fd);
5293
+ fs12.closeSync(fd);
5372
5294
  }
5373
5295
  if (writeError !== void 0)
5374
- throw fs13.rmSync(claimPath, { force: !0 }), writeError;
5375
- let markerPath = path12.join(recoveryDir, `${Buffer.from(input.requestId).toString("base64url")}.json`);
5296
+ throw fs12.rmSync(claimPath, { force: !0 }), writeError;
5297
+ let markerPath = path11.join(recoveryDir, `${Buffer.from(input.requestId).toString("base64url")}.json`);
5376
5298
  try {
5377
5299
  writePrivateAtomicJson(markerPath, { version: 1, ...input });
5378
5300
  } catch (error) {
5379
- throw fs13.rmSync(claimPath, { force: !0 }), error;
5301
+ throw fs12.rmSync(claimPath, { force: !0 }), error;
5380
5302
  }
5381
5303
  return { claimPath, markerPath };
5382
5304
  }
@@ -5419,16 +5341,16 @@ async function waitForSteeringAction(input) {
5419
5341
  let status2 = readSteeringStatus(input.asyncDir), result2 = status2 ? actionResultFromSteeringStatus(status2, input.sourceRunId, input.requestId) : void 0;
5420
5342
  if (steeringActionIsTerminal(result2))
5421
5343
  return result2;
5422
- await new Promise((resolve7) => setTimeout(resolve7, Math.min(50, Math.max(1, deadline - Date.now()))));
5344
+ await new Promise((resolve8) => setTimeout(resolve8, Math.min(50, Math.max(1, deadline - Date.now()))));
5423
5345
  }
5424
5346
  let status = readSteeringStatus(input.asyncDir);
5425
5347
  return status ? actionResultFromSteeringStatus(status, input.sourceRunId, input.requestId) : void 0;
5426
5348
  }
5427
5349
 
5428
5350
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-steering-action.js
5429
- import { randomUUID as randomUUID3 } from "node:crypto";
5430
- import * as fs14 from "node:fs";
5431
- import * as path13 from "node:path";
5351
+ import { randomUUID as randomUUID2 } from "node:crypto";
5352
+ import * as fs13 from "node:fs";
5353
+ import * as path12 from "node:path";
5432
5354
  async function steerAsyncRun(input) {
5433
5355
  if (!input.location.asyncDir)
5434
5356
  return {
@@ -5477,7 +5399,7 @@ async function steerAsyncRun(input) {
5477
5399
  isError: !0,
5478
5400
  details: { mode: "management", results: [] }
5479
5401
  };
5480
- let requestId = randomUUID3();
5402
+ let requestId = randomUUID2();
5481
5403
  try {
5482
5404
  requestAsyncSteer(asyncDir, {
5483
5405
  message: input.message,
@@ -5509,7 +5431,7 @@ async function steerAsyncRun(input) {
5509
5431
  if (status.mode === "single" && status.isNested !== !0 && running.length === 1 && !!finalStatus?.steering && (input.index === void 0 || input.index === 0) && finalResult?.state !== "scheduled" && input.recover) {
5510
5432
  let appendSteeringNotice = (state, message) => {
5511
5433
  try {
5512
- fs14.appendFileSync(path13.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...status.sessionId ? { currentSessionId: status.sessionId } : {} })}
5434
+ fs13.appendFileSync(path12.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...status.sessionId ? { currentSessionId: status.sessionId } : {} })}
5513
5435
  `);
5514
5436
  } catch {
5515
5437
  }
@@ -5522,11 +5444,11 @@ async function steerAsyncRun(input) {
5522
5444
  input.onRecoveryCommitted?.(requestId, committedAt);
5523
5445
  let preCommitStatus = readStatus(asyncDir), preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : void 0;
5524
5446
  if (preCommitResult?.state === "delivered" && preCommitResult.targets.every((target) => target.deliveredAt !== void 0 && target.deliveredAt <= committedAt))
5525
- return fs14.rmSync(markerPath, { force: !0 }), fs14.rmSync(claimPath, { force: !0 }), { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: preCommitResult } };
5447
+ return fs13.rmSync(markerPath, { force: !0 }), fs13.rmSync(claimPath, { force: !0 }), { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: preCommitResult } };
5526
5448
  try {
5527
5449
  deliverInterruptRequest({ asyncDir, pid: latest?.pid ?? status.pid, kill: input.kill, source: "steering-recovery" });
5528
5450
  } catch (error) {
5529
- throw fs14.rmSync(markerPath, { force: !0 }), fs14.rmSync(claimPath, { force: !0 }), new Error(`Failed to commit steering recovery interrupt: ${error instanceof Error ? error.message : String(error)}`);
5451
+ throw fs13.rmSync(markerPath, { force: !0 }), fs13.rmSync(claimPath, { force: !0 }), new Error(`Failed to commit steering recovery interrupt: ${error instanceof Error ? error.message : String(error)}`);
5530
5452
  }
5531
5453
  let pauseDeadline = Date.now() + (input.recoveryTimeoutMs ?? 15e3), paused = null;
5532
5454
  for (; Date.now() <= pauseDeadline && !input.signal?.aborted; ) {
@@ -5535,7 +5457,7 @@ async function steerAsyncRun(input) {
5535
5457
  paused = candidate;
5536
5458
  break;
5537
5459
  }
5538
- await new Promise((resolve7) => setTimeout(resolve7, 50));
5460
+ await new Promise((resolve8) => setTimeout(resolve8, 50));
5539
5461
  }
5540
5462
  if (!paused)
5541
5463
  throw new Error("Source run did not reach confirmed paused state within 15 seconds; no replacement was launched and the recovery claim remains committed to prevent a delayed duplicate.");
@@ -5548,12 +5470,12 @@ async function steerAsyncRun(input) {
5548
5470
  let stepSteering = paused.steps?.[ack.index]?.steering;
5549
5471
  stepSteering && updateSteeringTarget(stepSteering, ack.requestId, ack.index, state, ack.ts, { reason }), lateAckRecorded = !0;
5550
5472
  try {
5551
- fs14.appendFileSync(path13.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: ack.state === "delivered" ? "subagent.steer.delivered" : "subagent.steer.failed", ts: ack.ts, runId: status.runId, requestId: ack.requestId, index: ack.index, late: !0, message: ack.message })}
5473
+ fs13.appendFileSync(path12.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: ack.state === "delivered" ? "subagent.steer.delivered" : "subagent.steer.failed", ts: ack.ts, runId: status.runId, requestId: ack.requestId, index: ack.index, late: !0, message: ack.message })}
5552
5474
  `);
5553
5475
  } catch {
5554
5476
  }
5555
5477
  }
5556
- lateAckRecorded && writeAtomicJson(path13.join(asyncDir, "status.json"), paused);
5478
+ lateAckRecorded && writeAtomicJson(path12.join(asyncDir, "status.json"), paused);
5557
5479
  let recoveryTarget;
5558
5480
  try {
5559
5481
  recoveryTarget = resolveAsyncResumeTarget({ id: status.runId }, { kill: input.kill });
@@ -5571,7 +5493,7 @@ async function steerAsyncRun(input) {
5571
5493
  if (sourceStatus?.state === "paused" && sourceStatus.steering && targetIndex >= 0) {
5572
5494
  updateSteeringTarget(sourceStatus.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
5573
5495
  let stepSteering = sourceStatus.steps?.[targetIndex]?.steering;
5574
- stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId }), writeAtomicJson(path13.join(asyncDir, "status.json"), sourceStatus);
5496
+ stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId }), writeAtomicJson(path12.join(asyncDir, "status.json"), sourceStatus);
5575
5497
  }
5576
5498
  let recovered = sourceStatus?.steering ? actionResultFromSteeringStatus(sourceStatus.steering, status.runId, requestId, revived.details.asyncId) : void 0;
5577
5499
  return appendSteeringNotice("recovered", `Steering recovered for run ${status.runId}; replacement ${revived.details.asyncId} launched.`), { content: [{ type: "text", text: `Steering recovered for async run ${status.runId}; replacement ${revived.details.asyncId} launched after the source paused.` }], details: { mode: "management", results: [], steering: recovered ?? { requestId, state: "recovered", sourceRunId: status.runId, replacementRunId: revived.details.asyncId, targets: [{ index: input.index ?? 0, state: "recovered" }] } } };
@@ -5580,7 +5502,7 @@ async function steerAsyncRun(input) {
5580
5502
  if (failedStatus && failedStatus.state !== "running" && failedStatus.state !== "queued" && failedStatus.steering && targetIndex >= 0) {
5581
5503
  updateSteeringTarget(failedStatus.steering, requestId, targetIndex, "failed", Date.now(), { reason });
5582
5504
  let stepSteering = failedStatus.steps?.[targetIndex]?.steering;
5583
- stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "failed", Date.now(), { reason }), failedStatus.activityState = "needs_attention", writeAtomicJson(path13.join(asyncDir, "status.json"), failedStatus);
5505
+ stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "failed", Date.now(), { reason }), failedStatus.activityState = "needs_attention", writeAtomicJson(path12.join(asyncDir, "status.json"), failedStatus);
5584
5506
  }
5585
5507
  let failed = failedStatus?.steering ? actionResultFromSteeringStatus(failedStatus.steering, status.runId, requestId) : void 0;
5586
5508
  return appendSteeringNotice("failed", `Steering failed for run ${status.runId}: ${reason}`), { content: [{ type: "text", text: `Steering failed for async run ${status.runId} (request ${requestId}): ${reason}` }], isError: !0, details: { mode: "management", results: [], steering: failed ?? { requestId, state: "failed", sourceRunId: status.runId, targets: [{ index: input.index ?? 0, state: "failed", reason }] } } };
@@ -5595,16 +5517,16 @@ async function steerAsyncRun(input) {
5595
5517
  }
5596
5518
 
5597
5519
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.js
5598
- import * as path14 from "node:path";
5520
+ import * as path13 from "node:path";
5599
5521
  function resolveAsyncRootResultPath(resultsDir, runId) {
5600
- return path14.join(resultsDir, `${runId}.json`);
5522
+ return path13.join(resultsDir, `${runId}.json`);
5601
5523
  }
5602
5524
 
5603
5525
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/run-status.js
5604
- import * as fs15 from "node:fs";
5605
- import * as path15 from "node:path";
5526
+ import * as fs14 from "node:fs";
5527
+ import * as path14 from "node:path";
5606
5528
  function hasExistingSessionFile(value) {
5607
- return typeof value == "string" && fs15.existsSync(value);
5529
+ return typeof value == "string" && fs14.existsSync(value);
5608
5530
  }
5609
5531
  function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}) {
5610
5532
  if (options.stopped)
@@ -5640,9 +5562,9 @@ function formatSteeringSummary(input) {
5640
5562
  }
5641
5563
  function rememberedForegroundChildOutput(child) {
5642
5564
  let outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
5643
- if (outputPath && fs15.existsSync(outputPath))
5565
+ if (outputPath && fs14.existsSync(outputPath))
5644
5566
  try {
5645
- let artifactOutput = fs15.readFileSync(outputPath, "utf-8").trim();
5567
+ let artifactOutput = fs14.readFileSync(outputPath, "utf-8").trim();
5646
5568
  if (artifactOutput)
5647
5569
  return artifactOutput;
5648
5570
  } catch {
@@ -5815,7 +5737,7 @@ function inspectSubagentStatus(params, deps = {}) {
5815
5737
  details: { mode: "single", results: [] }
5816
5738
  };
5817
5739
  }
5818
- let status = reconciliation.status, effectiveRunId = status?.runId ?? resolvedId ?? "unknown", logPath = path15.join(asyncDir, `subagent-log-${effectiveRunId}.md`), eventsPath = path15.join(asyncDir, "events.jsonl");
5740
+ let status = reconciliation.status, effectiveRunId = status?.runId ?? resolvedId ?? "unknown", logPath = path14.join(asyncDir, `subagent-log-${effectiveRunId}.md`), eventsPath = path14.join(asyncDir, "events.jsonl");
5819
5741
  if (status) {
5820
5742
  if (params.view === "transcript") {
5821
5743
  if (currentSessionId && status.sessionId !== currentSessionId)
@@ -5859,22 +5781,22 @@ function inspectSubagentStatus(params, deps = {}) {
5859
5781
  `Dir: ${asyncDir}`,
5860
5782
  outputPath ? `Output: ${outputPath}` : void 0,
5861
5783
  reconciliation.message ? `Diagnosis: ${reconciliation.message}` : void 0,
5862
- reconciliation.resultPath && fs15.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : void 0
5784
+ reconciliation.resultPath && fs14.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : void 0
5863
5785
  ].filter((line) => !!line);
5864
5786
  for (let [index, step] of (status.steps ?? []).entries()) {
5865
5787
  let stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : void 0, modelThinking = formatModelSelection(step.modelSelection, step.model, step.thinking), modelText = modelThinking ? ` (${modelThinking})` : "", steeringText2 = formatSteeringSummary(step), steeringSuffix = steeringText2 ? `, steering: ${steeringText2}` : "", errorText2 = step.error ? `, error: ${step.error}` : "", acceptanceText = step.acceptance?.status ? `, acceptance: ${step.acceptance.status}` : "", budgetText = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "", display = step.label ? `${step.label} (${step.agent})` : step.agent, phase = step.phase ? `[${step.phase}] ` : "";
5866
5788
  lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText2}`), lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: !0, maxLines: 20 }));
5867
- let stepOutputPath = path15.join(asyncDir, `output-${index}.log`);
5868
- stepOutputPath !== outputPath && fs15.existsSync(stepOutputPath) && lines.push(` Output: ${stepOutputPath}`), step.status === "running" && (lines.push(` Intercom target: ${resolveSubagentIntercomTarget(status.runId, step.childId ?? step.agent, index)} (if registered)`), lines.push(` Steer: subagent({ action: "steer", id: "${status.runId}", index: ${index}, message: "..." })`));
5789
+ let stepOutputPath = path14.join(asyncDir, `output-${index}.log`);
5790
+ stepOutputPath !== outputPath && fs14.existsSync(stepOutputPath) && lines.push(` Output: ${stepOutputPath}`), step.status === "running" && (lines.push(` Intercom target: ${resolveSubagentIntercomTarget(status.runId, step.childId ?? step.agent, index)} (if registered)`), lines.push(` Steer: subagent({ action: "steer", id: "${status.runId}", index: ${index}, message: "..." })`));
5869
5791
  }
5870
5792
  let attached = new Set((status.steps ?? []).flatMap((step) => step.children?.map((child) => child.id) ?? [])), unattached = nestedChildren.filter((child) => !attached.has(child.id));
5871
- return lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: !0, maxLines: 20 })), nestedWarning && lines.push(`Warning: ${nestedWarning}`), status.sessionFile && lines.push(`Session: ${status.sessionFile}`), status.state === "running" && lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`), status.state !== "running" && lines.push(formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile, { stopped: status.state === "stopped" || status.stopped === !0 })), fs15.existsSync(logPath) && lines.push(`Log: ${logPath}`), fs15.existsSync(eventsPath) && lines.push(`Events: ${eventsPath}`), { content: [{ type: "text", text: lines.join(`
5793
+ return lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: !0, maxLines: 20 })), nestedWarning && lines.push(`Warning: ${nestedWarning}`), status.sessionFile && lines.push(`Session: ${status.sessionFile}`), status.state === "running" && lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`), status.state !== "running" && lines.push(formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile, { stopped: status.state === "stopped" || status.stopped === !0 })), fs14.existsSync(logPath) && lines.push(`Log: ${logPath}`), fs14.existsSync(eventsPath) && lines.push(`Events: ${eventsPath}`), { content: [{ type: "text", text: lines.join(`
5872
5794
  `) }], details: { mode: "single", results: [] } };
5873
5795
  }
5874
5796
  }
5875
5797
  if (resultPath)
5876
5798
  try {
5877
- let raw = fs15.readFileSync(resultPath, "utf-8"), data = JSON.parse(raw);
5799
+ let raw = fs14.readFileSync(resultPath, "utf-8"), data = JSON.parse(raw);
5878
5800
  if (params.view === "transcript")
5879
5801
  try {
5880
5802
  return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
@@ -5898,513 +5820,481 @@ function inspectSubagentStatus(params, deps = {}) {
5898
5820
  };
5899
5821
  }
5900
5822
 
5901
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js
5902
- var MUTATING_MANAGEMENT_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "delete", "eject", "disable", "enable", "reset"]);
5903
- function resolveRequestedCwd(runtimeCwd, requestedCwd) {
5904
- return requestedCwd ? path16.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
5823
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.js
5824
+ import { randomUUID as randomUUID5 } from "node:crypto";
5825
+ import * as path17 from "node:path";
5826
+
5827
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/chain-append.js
5828
+ import { randomUUID as randomUUID3 } from "node:crypto";
5829
+ import * as fs15 from "node:fs";
5830
+ import * as path15 from "node:path";
5831
+ var APPEND_REQUESTS_DIR = "append-requests";
5832
+ function appendDir(asyncDir) {
5833
+ return path15.join(asyncDir, APPEND_REQUESTS_DIR);
5905
5834
  }
5906
- function getForegroundControl(state, runId) {
5907
- if (runId)
5908
- return state.foregroundControls.get(runId);
5909
- if (state.lastForegroundControlId) {
5910
- let latest = state.foregroundControls.get(state.lastForegroundControlId);
5911
- if (latest)
5912
- return latest;
5835
+ function appendRequestPath(asyncDir, request) {
5836
+ return path15.join(appendDir(asyncDir), `${request.createdAt}-${request.id}.json`);
5837
+ }
5838
+ function listAppendRequestFiles(asyncDir) {
5839
+ let dir = appendDir(asyncDir);
5840
+ try {
5841
+ return fs15.readdirSync(dir).filter((entry) => entry.endsWith(".json")).map((entry) => path15.join(dir, entry)).sort();
5842
+ } catch (error) {
5843
+ if (error.code === "ENOENT")
5844
+ return [];
5845
+ throw error;
5913
5846
  }
5914
- let newest;
5915
- for (let control of state.foregroundControls.values())
5916
- (!newest || control.updatedAt > newest.updatedAt) && (newest = control);
5917
- return newest;
5918
5847
  }
5919
- function formatForegroundActivity(control) {
5920
- let facts = [];
5921
- if (control.currentTool && control.currentToolStartedAt ? facts.push(`tool ${control.currentTool} for ${Math.floor(Math.max(0, Date.now() - control.currentToolStartedAt) / 1e3)}s`) : control.currentTool && facts.push(`tool ${control.currentTool}`), control.currentPath && facts.push(`path ${control.currentPath}`), control.turnCount !== void 0 && facts.push(`${control.turnCount} turns`), control.tokens !== void 0 && facts.push(`${control.tokens} tokens`), control.toolCount !== void 0 && facts.push(`${control.toolCount} tools`), !control.lastActivityAt)
5922
- return control.currentActivityState === "needs_attention" ? ["needs attention", ...facts].join(" | ") : control.currentActivityState === "active_long_running" ? ["active but long-running", ...facts].join(" | ") : facts.length ? facts.join(" | ") : void 0;
5923
- let seconds = Math.floor(Math.max(0, Date.now() - control.lastActivityAt) / 1e3);
5924
- return control.currentActivityState === "needs_attention" ? [`no activity for ${seconds}s`, ...facts].join(" | ") : control.currentActivityState === "active_long_running" ? [`active but long-running; last activity ${seconds}s ago`, ...facts].join(" | ") : [`active ${seconds}s ago`, ...facts].join(" | ");
5848
+ function countPendingChainAppendRequests(asyncDir) {
5849
+ return listAppendRequestFiles(asyncDir).length;
5925
5850
  }
5926
- function nestedResolutionScopeForExecutor(deps) {
5927
- if (deps.allowMutatingManagementActions !== !1)
5928
- return;
5929
- let route = resolveInheritedNestedRouteFromEnv(), address = route ? resolveNestedParentAddressFromEnv() : void 0;
5930
- return {
5931
- routes: route ? [route] : [],
5932
- ...address ? { descendantOf: { parentRunId: address.parentRunId, ...address.parentStepIndex !== void 0 ? { parentStepIndex: address.parentStepIndex } : {} } } : {}
5851
+ function runnerStepOutputNames(steps) {
5852
+ let names = [];
5853
+ for (let step of steps)
5854
+ isParallelGroup(step) ? names.push(...step.parallel.map((task) => task.outputName).filter((name) => !!name)) : isDynamicRunnerGroup(step) ? step.collect.as && names.push(step.collect.as) : step.outputName && names.push(step.outputName);
5855
+ return names;
5856
+ }
5857
+ function enqueueChainAppendRequest(input) {
5858
+ let status = readStatus(input.asyncDir);
5859
+ if (!status)
5860
+ throw new Error(`No async run status found for '${input.runId}'.`);
5861
+ if (status.runId !== input.runId)
5862
+ throw new Error(`Async run id mismatch: expected '${input.runId}', found '${status.runId}'.`);
5863
+ if (status.mode !== "chain")
5864
+ throw new Error(`Run '${input.runId}' is ${status.mode}; only active chain runs accept appended steps.`);
5865
+ if (status.state !== "running")
5866
+ throw new Error(`Run '${input.runId}' is ${status.state}; only running chain runs accept appended steps.`);
5867
+ if (!((status.steps ?? []).some((step) => step.status === "running" || step.status === "pending") || (status.pendingAppends ?? 0) > 0))
5868
+ throw new Error(`Run '${input.runId}' has no running or pending chain steps left; append-step must target an in-progress chain.`);
5869
+ if (input.steps.length === 0)
5870
+ throw new Error("append-step requires one chain step.");
5871
+ let request = {
5872
+ id: randomUUID3(),
5873
+ createdAt: input.now ?? Date.now(),
5874
+ steps: input.steps
5933
5875
  };
5876
+ fs15.mkdirSync(appendDir(input.asyncDir), { recursive: !0 }), writeAtomicJson(appendRequestPath(input.asyncDir, request), request);
5877
+ let pendingCount = countPendingChainAppendRequests(input.asyncDir), statusPath = path15.join(input.asyncDir, "status.json"), updatedStatus = { ...status, pendingAppends: pendingCount, lastUpdate: request.createdAt };
5878
+ return writeAtomicJson(statusPath, updatedStatus), appendJsonl(path15.join(input.asyncDir, "events.jsonl"), JSON.stringify({
5879
+ type: "subagent.chain.append.requested",
5880
+ ts: request.createdAt,
5881
+ runId: input.runId,
5882
+ requestId: request.id,
5883
+ stepCount: input.steps.length,
5884
+ pendingAppends: pendingCount
5885
+ })), { request, pendingCount };
5934
5886
  }
5935
- function trustedSessionRootsForStatus(ctx, deps) {
5936
- let roots = deps.config.defaultSessionDir ? [path16.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : [], parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
5937
- return parentSessionFile && roots.push(deps.getSubagentSessionRoot(parentSessionFile)), [...new Set(roots)];
5887
+ function readAppendRequest(filePath) {
5888
+ let raw = JSON.parse(fs15.readFileSync(filePath, "utf-8"));
5889
+ if (!(!raw.id || typeof raw.id != "string") && !(typeof raw.createdAt != "number" || !Number.isFinite(raw.createdAt)) && !(!Array.isArray(raw.steps) || raw.steps.length === 0))
5890
+ return { id: raw.id, createdAt: raw.createdAt, steps: raw.steps };
5938
5891
  }
5939
- function reserveSubagentSpawns(input) {
5940
- if (input.requested <= 0)
5941
- return;
5942
- let maxSpawns = resolveMaxSubagentSpawnsPerSession(input.config.maxSubagentSpawnsPerSession);
5943
- if (maxSpawns === void 0)
5944
- return;
5945
- input.state.subagentSpawns?.sessionId !== input.sessionId && (input.state.subagentSpawns = { sessionId: input.sessionId, count: 0 });
5946
- let used = input.state.subagentSpawns.count;
5947
- if (used + input.requested > maxSpawns)
5948
- return {
5949
- content: [{ type: "text", text: `Subagent spawn limit reached for this session (${used}/${maxSpawns} used, ${input.requested} requested). Complete the work directly or start a new session.` }],
5950
- isError: !0,
5951
- details: { mode: input.mode, results: [] }
5952
- };
5953
- input.state.subagentSpawns.count = used + input.requested;
5892
+ function readPendingChainAppendRequests(asyncDir) {
5893
+ return listAppendRequestFiles(asyncDir).map((filePath) => readAppendRequest(filePath)).filter((request) => !!request).sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id));
5954
5894
  }
5955
- function countRequestedSubagentSpawns(params, config) {
5956
- return params.tasks ? params.tasks.length : params.chain ? params.chain.reduce((total, step) => isDynamicParallelStep(step) ? total + (step.expand.maxItems ?? config.chain?.dynamicFanout?.maxItems ?? 0) : total + getStepAgents(step).length, 0) : params.agent ? 1 : 0;
5895
+
5896
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.js
5897
+ function lunrContextPolicy(params) {
5898
+ return {
5899
+ params: { ...params, context: "fresh" },
5900
+ contextForAgent: () => "fresh",
5901
+ usesFork: !1
5902
+ };
5957
5903
  }
5958
- function foregroundStatusResult(control) {
5959
- let nestedWarning;
5960
- try {
5961
- updateForegroundNestedProjection(control);
5962
- } catch (error) {
5963
- nestedWarning = `Nested status unavailable: ${error instanceof Error ? error.message : String(error)}`;
5964
- }
5965
- let activity = formatForegroundActivity(control), lines = [
5966
- `Run: ${control.runId}`,
5967
- "State: running",
5968
- `Mode: ${control.mode}`,
5969
- control.currentAgent ? `Current: ${control.currentAgent}${control.currentIndex !== void 0 ? ` step ${control.currentIndex + 1}` : ""}` : void 0,
5970
- activity ? `Activity: ${activity}` : void 0
5971
- ].filter((line) => !!line);
5972
- return lines.push(...formatNestedRunStatusLines(control.nestedChildren, { indent: "", commandHints: !0, maxLines: 20 })), nestedWarning && lines.push(`Warning: ${nestedWarning}`), { content: [{ type: "text", text: lines.join(`
5973
- `) }], details: { mode: "management", results: [] } };
5904
+
5905
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.js
5906
+ function resolveAgentDefaultContextPolicy(params) {
5907
+ return lunrContextPolicy(params);
5974
5908
  }
5975
- function trimRememberedForegroundRuns(state) {
5976
- if (state.foregroundRuns)
5977
- for (; state.foregroundRuns.size > 50; ) {
5978
- let oldestTerminal = [...state.foregroundRuns.values()].filter((run) => !run.children.some((child) => child.status === "detached")).sort((left, right) => left.updatedAt - right.updatedAt)[0];
5979
- if (!oldestTerminal)
5980
- break;
5981
- state.foregroundRuns.delete(oldestTerminal.runId);
5909
+ function resolveExplicitContextPolicy(params) {
5910
+ return lunrContextPolicy(params);
5911
+ }
5912
+ function shouldForkAgent(contextPolicy, agentName) {
5913
+ return contextPolicy.contextForAgent(agentName) === "fork";
5914
+ }
5915
+ function withForkContext(result2, context) {
5916
+ return context !== "fork" || !result2.details ? result2 : {
5917
+ ...result2,
5918
+ details: {
5919
+ ...result2.details,
5920
+ context: "fork"
5982
5921
  }
5922
+ };
5983
5923
  }
5984
- function rememberForegroundRun(state, input) {
5985
- state.foregroundRuns ??= /* @__PURE__ */ new Map();
5986
- let previous = state.foregroundRuns.get(input.runId), updatedAt = Date.now();
5987
- state.foregroundRuns.set(input.runId, {
5988
- runId: input.runId,
5989
- mode: input.mode,
5990
- cwd: input.cwd,
5991
- ...input.sessionId ? { sessionId: input.sessionId } : {},
5992
- updatedAt,
5993
- children: input.results.map((result2, index) => {
5994
- let child = {
5995
- agent: result2.agent,
5996
- index,
5997
- status: resolveSubagentResultStatus({ exitCode: result2.exitCode, interrupted: result2.interrupted, detached: result2.detached }),
5998
- updatedAt,
5999
- ...result2.exitCode !== void 0 ? { exitCode: result2.exitCode } : {},
6000
- ...result2.error ? { error: result2.error } : {},
6001
- ...result2.finalOutput ? { finalOutput: result2.finalOutput } : {},
6002
- ...result2.outputMode ? { outputMode: result2.outputMode } : {},
6003
- ...result2.savedOutputPath ? { savedOutputPath: result2.savedOutputPath } : {},
6004
- ...result2.outputSaveError ? { outputSaveError: result2.outputSaveError } : {},
6005
- ...result2.sessionFile ? { sessionFile: result2.sessionFile } : {},
6006
- ...result2.artifactPaths ? { artifactPaths: result2.artifactPaths } : {},
6007
- ...result2.transcriptPath ? { transcriptPath: result2.transcriptPath } : {},
6008
- ...result2.transcriptError ? { transcriptError: result2.transcriptError } : {},
6009
- ...result2.detachedReason ? { detachedReason: result2.detachedReason } : {},
6010
- ...result2.acceptance ? { acceptance: result2.acceptance } : {}
6011
- }, recovered = previous?.children[index];
6012
- return child.status === "detached" && recovered && recovered.status !== "detached" ? recovered : child;
6013
- })
6014
- }), trimRememberedForegroundRuns(state);
5924
+ function withForkThinkingNotes(result2, downgrades) {
5925
+ if (downgrades.size === 0)
5926
+ return result2;
5927
+ let note = `Note: fork context forced thinking off for ${[...downgrades.entries()].sort(([a], [b]) => a - b).map(([index, agent]) => `${agent} (child ${index})`).join(", ")}. The forked transcript contained signed Anthropic thinking blocks that were sanitized, and Anthropic children cannot resume such a transcript with thinking enabled. Use context: "fresh" when an Anthropic child needs thinking.`;
5928
+ return { ...result2, content: [...result2.content, { type: "text", text: note }] };
6015
5929
  }
6016
- function updateRememberedForegroundChild(state, input) {
6017
- state.foregroundRuns ??= /* @__PURE__ */ new Map();
6018
- let updatedAt = Date.now(), run = state.foregroundRuns.get(input.runId);
6019
- run || (run = { runId: input.runId, mode: input.mode, cwd: input.cwd, ...input.sessionId ? { sessionId: input.sessionId } : {}, updatedAt, children: [] }, state.foregroundRuns.set(input.runId, run)), run.updatedAt = updatedAt;
6020
- let child = run.children[input.index] ?? { agent: input.result.agent, index: input.index, status: "detached" };
6021
- run.children[input.index] = {
6022
- ...child,
6023
- agent: input.result.agent,
6024
- index: input.index,
6025
- status: input.result.acceptance?.status === "rejected" ? "failed" : resolveSubagentResultStatus({ exitCode: input.result.exitCode, interrupted: input.result.interrupted, detached: !1 }),
6026
- updatedAt,
6027
- ...input.result.exitCode !== void 0 ? { exitCode: input.result.exitCode } : {},
6028
- ...input.result.error ? { error: input.result.error } : {},
6029
- ...input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {},
6030
- outputMode: input.result.outputMode,
6031
- savedOutputPath: input.result.savedOutputPath,
6032
- outputSaveError: input.result.outputSaveError,
6033
- ...input.result.sessionFile ? { sessionFile: input.result.sessionFile } : {},
6034
- ...input.result.artifactPaths ? { artifactPaths: input.result.artifactPaths } : {},
6035
- ...input.result.transcriptPath ? { transcriptPath: input.result.transcriptPath } : {},
6036
- ...input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {},
6037
- ...input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {},
6038
- ...input.result.acceptance ? { acceptance: input.result.acceptance } : {}
6039
- }, trimRememberedForegroundRuns(state);
6040
- let output = getSingleResultOutput(input.result).trim(), success = input.result.exitCode === 0 && input.result.acceptance?.status !== "rejected", summary = !success && input.result.error ? `${input.result.error}${output ? `
6041
-
6042
- Output:
6043
- ${output}` : ""}` : output || input.result.error || "Detached child exited without final output.";
6044
- input.events.emit(SUBAGENT_FOREGROUND_COMPLETE_EVENT, {
6045
- id: `${input.runId}:${input.index}`,
6046
- runId: input.runId,
6047
- source: "foreground",
6048
- mode: input.mode,
6049
- agent: input.result.agent,
6050
- success,
6051
- summary,
6052
- exitCode: input.result.exitCode,
6053
- state: success ? "complete" : "failed",
6054
- timestamp: updatedAt,
6055
- cwd: input.cwd,
6056
- sessionFile: input.result.sessionFile,
6057
- sessionId: input.sessionId,
6058
- taskIndex: input.index,
6059
- results: [{ childId: input.result.childId, agent: input.result.agent, sessionFile: input.result.sessionFile, usage: input.result.usage, usageRequests: input.result.usageRequests, success, output: summary }]
5930
+ function collectChainSessionFiles(chain, sessionFileForTask, dynamicFanoutMaxItems) {
5931
+ let sessionFiles = [], flatIndex = 0;
5932
+ for (let step of chain) {
5933
+ if (isParallelStep(step)) {
5934
+ for (let task of step.parallel)
5935
+ sessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model)), flatIndex++;
5936
+ continue;
5937
+ }
5938
+ if (isDynamicParallelStep(step)) {
5939
+ let maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
5940
+ for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
5941
+ sessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model)), flatIndex++;
5942
+ continue;
5943
+ }
5944
+ let sequential = step;
5945
+ sessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model)), flatIndex++;
5946
+ }
5947
+ return sessionFiles;
5948
+ }
5949
+ function collectChainThinkingOverrides(chain, thinkingOverrideForTask, dynamicFanoutMaxItems) {
5950
+ let thinkingOverrides = [], flatIndex = 0;
5951
+ for (let step of chain) {
5952
+ if (isParallelStep(step)) {
5953
+ for (let task of step.parallel)
5954
+ thinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model)), flatIndex++;
5955
+ continue;
5956
+ }
5957
+ if (isDynamicParallelStep(step)) {
5958
+ let maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
5959
+ for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
5960
+ thinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model)), flatIndex++;
5961
+ continue;
5962
+ }
5963
+ let sequential = step;
5964
+ thinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model)), flatIndex++;
5965
+ }
5966
+ return thinkingOverrides;
5967
+ }
5968
+ function wrapChainTasksForFork(chain, contextPolicy) {
5969
+ return chain.map((step, stepIndex) => {
5970
+ if (isParallelStep(step))
5971
+ return {
5972
+ ...step,
5973
+ parallel: step.parallel.map((task) => ({
5974
+ ...task,
5975
+ task: shouldForkAgent(contextPolicy, task.agent) ? wrapForkTask(task.task ?? "{previous}") : task.task
5976
+ }))
5977
+ };
5978
+ if (isDynamicParallelStep(step))
5979
+ return {
5980
+ ...step,
5981
+ parallel: {
5982
+ ...step.parallel,
5983
+ task: shouldForkAgent(contextPolicy, step.parallel.agent) ? wrapForkTask(step.parallel.task ?? "{previous}") : step.parallel.task
5984
+ }
5985
+ };
5986
+ let sequential = step;
5987
+ return {
5988
+ ...sequential,
5989
+ task: shouldForkAgent(contextPolicy, sequential.agent) ? wrapForkTask(sequential.task ?? (stepIndex === 0 ? "{task}" : "{previous}")) : sequential.task
5990
+ };
6060
5991
  });
6061
5992
  }
6062
- function resolveForegroundResumeTarget(params, state) {
6063
- let requested = (params.id ?? params.runId)?.trim();
6064
- if (!requested || !state.foregroundRuns?.size || !state.currentSessionId)
5993
+ function preflightForkSessionsForStaticTasks(params, contextPolicy, sessionFileForTask, dynamicFanoutMaxItems) {
5994
+ if (!contextPolicy.usesFork)
6065
5995
  return;
6066
- let sessionRuns = [...state.foregroundRuns.values()].filter((run2) => run2.sessionId === state.currentSessionId), direct = sessionRuns.find((run2) => run2.runId === requested), matches = direct ? [direct] : sessionRuns.filter((run2) => run2.runId.startsWith(requested));
6067
- if (matches.length === 0)
5996
+ if (params.agent) {
5997
+ shouldForkAgent(contextPolicy, params.agent) && sessionFileForTask(params.agent, 0, params.model);
6068
5998
  return;
6069
- if (matches.length > 1)
6070
- throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run2) => run2.runId).join(", ")}. Provide a longer id.`);
6071
- let run = matches[0];
6072
- if (run.children.some((child2) => child2.status === "detached"))
6073
- throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
6074
- if (run.children.length > 1 && params.index === void 0)
6075
- throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
6076
- let index = params.index ?? 0;
6077
- if (!Number.isInteger(index))
6078
- throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
6079
- if (index < 0 || index >= run.children.length)
6080
- throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Index ${index} is out of range.`);
6081
- let child = run.children[index];
6082
- if (!child.sessionFile)
6083
- throw new Error(`Foreground run '${run.runId}' child ${index} does not have a persisted session file to resume from.`);
6084
- if (path16.extname(child.sessionFile) !== ".jsonl")
6085
- throw new Error(`Foreground run '${run.runId}' child ${index} session file must be a .jsonl file: ${child.sessionFile}`);
6086
- let sessionFile = path16.resolve(child.sessionFile);
6087
- if (!fs16.existsSync(sessionFile))
6088
- throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}`);
6089
- return { runId: run.runId, mode: run.mode, state: "complete", agent: child.agent, index, intercomTarget: resolveSubagentIntercomTarget(run.runId, child.agent, index), cwd: run.cwd, sessionFile };
6090
- }
6091
- function isAsyncRunNotFound(error) {
6092
- return error instanceof Error && error.message.startsWith("Async run not found.");
6093
- }
6094
- function isResumeAmbiguity(error) {
6095
- return error instanceof Error && /Ambiguous .*run id prefix/.test(error.message);
6096
- }
6097
- function resumeTargetExact(target, requested) {
6098
- return target?.runId === requested;
6099
- }
6100
- function escapeRegExp(value) {
6101
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6102
- }
6103
- function isExactResumeError(error, source, requested) {
6104
- return !(error instanceof Error) || !requested ? !1 : new RegExp(`\\b${source} run '${escapeRegExp(requested)}'`, "i").test(error.message);
6105
- }
6106
- function resolveResumeTarget(params, state, options = {}) {
6107
- let requested = (params.id ?? params.runId)?.trim() ?? "", foregroundTarget, foregroundError, asyncTarget, asyncError;
6108
- try {
6109
- let target = resolveForegroundResumeTarget(params, state);
6110
- target && (foregroundTarget = { kind: "revive", source: "foreground", ...target });
6111
- } catch (error) {
6112
- foregroundError = error;
6113
- }
6114
- try {
6115
- asyncTarget = { source: "async", ...resolveAsyncResumeTarget(params, {}, { requireSessionFile: options.asyncRequireSessionFile }) };
6116
- } catch (error) {
6117
- asyncError = error;
6118
- }
6119
- if (foregroundTarget && asyncTarget) {
6120
- let foregroundExact = resumeTargetExact(foregroundTarget, requested), asyncExact = resumeTargetExact(asyncTarget, requested);
6121
- if (foregroundExact && !asyncExact)
6122
- return foregroundTarget;
6123
- if (asyncExact && !foregroundExact)
6124
- return asyncTarget;
6125
- throw new Error(`Resume id '${requested}' is ambiguous between foreground run '${foregroundTarget.runId}' and async run '${asyncTarget.runId}'. Provide a full run id.`);
6126
5999
  }
6127
- if (foregroundTarget) {
6128
- if (isExactResumeError(asyncError, "async", requested) || isResumeAmbiguity(asyncError) && !resumeTargetExact(foregroundTarget, requested))
6129
- throw asyncError;
6130
- return foregroundTarget;
6000
+ if (params.tasks) {
6001
+ params.tasks.forEach((task, index) => {
6002
+ shouldForkAgent(contextPolicy, task.agent) && sessionFileForTask(task.agent, index, task.model);
6003
+ });
6004
+ return;
6131
6005
  }
6132
- if (asyncTarget) {
6133
- if (isExactResumeError(foregroundError, "foreground", requested) || isResumeAmbiguity(foregroundError) && !resumeTargetExact(asyncTarget, requested))
6134
- throw foregroundError;
6135
- return asyncTarget;
6006
+ if (!params.chain?.length)
6007
+ return;
6008
+ let flatIndex = 0;
6009
+ for (let step of params.chain) {
6010
+ if (isParallelStep(step)) {
6011
+ for (let task of step.parallel)
6012
+ shouldForkAgent(contextPolicy, task.agent) && sessionFileForTask(task.agent, flatIndex, task.model), flatIndex++;
6013
+ continue;
6014
+ }
6015
+ if (isDynamicParallelStep(step)) {
6016
+ let maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
6017
+ if (shouldForkAgent(contextPolicy, step.parallel.agent))
6018
+ for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
6019
+ sessionFileForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
6020
+ flatIndex += maxItems;
6021
+ continue;
6022
+ }
6023
+ let sequential = step;
6024
+ shouldForkAgent(contextPolicy, sequential.agent) && sessionFileForTask(sequential.agent, flatIndex, sequential.model), flatIndex++;
6136
6025
  }
6137
- throw foregroundError && !isAsyncRunNotFound(asyncError) || foregroundError ? foregroundError : asyncError || new Error("Run not found. Provide id or runId.");
6138
6026
  }
6139
- function getAsyncInterruptTarget(state, runId, location) {
6140
- if (location?.asyncDir)
6027
+
6028
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.js
6029
+ function validateExecutionInput(params, hasChain, hasTasks, hasSingle, allowClarifyTaskPrompt) {
6030
+ if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1)
6141
6031
  return {
6142
- asyncId: location.resolvedId ?? runId ?? path16.basename(location.asyncDir),
6143
- asyncDir: location.asyncDir
6032
+ content: [
6033
+ {
6034
+ type: "text",
6035
+ text: "Provide exactly one mode: { task, description, permissions? }, { tasks: [...] }, or { chain: [...] }."
6036
+ }
6037
+ ],
6038
+ isError: !0,
6039
+ details: { mode: "single", results: [] }
6144
6040
  };
6145
- if (runId) {
6146
- let direct = state.asyncJobs.get(runId);
6147
- return direct ? { asyncId: direct.asyncId, asyncDir: direct.asyncDir } : void 0;
6041
+ let acceptanceErrors = validateExecutionAcceptance(params);
6042
+ if (acceptanceErrors.length > 0)
6043
+ return {
6044
+ content: [{ type: "text", text: acceptanceErrors.join(" ") }],
6045
+ isError: !0,
6046
+ details: { mode: getRequestedModeLabel(params), results: [] }
6047
+ };
6048
+ if (hasSingle && !params.description)
6049
+ return {
6050
+ content: [{ type: "text", text: "description is required and must be a concise single-line label (max 80 characters)." }],
6051
+ isError: !0,
6052
+ details: { mode: "single", results: [] }
6053
+ };
6054
+ if (hasTasks && params.tasks) {
6055
+ for (let i = 0; i < params.tasks.length; i++)
6056
+ if (!params.tasks[i].description)
6057
+ return {
6058
+ content: [{ type: "text", text: `description is required (task ${i + 1})` }],
6059
+ isError: !0,
6060
+ details: { mode: "parallel", results: [] }
6061
+ };
6148
6062
  }
6149
- let newest;
6150
- for (let job of state.asyncJobs.values())
6151
- job.status === "running" && (!newest || (job.updatedAt ?? 0) > newest.updatedAt) && (newest = { asyncId: job.asyncId, asyncDir: job.asyncDir, updatedAt: job.updatedAt ?? 0 });
6152
- return newest ? { asyncId: newest.asyncId, asyncDir: newest.asyncDir } : void 0;
6153
- }
6154
- function emitControlNotification(input) {
6155
- if (!shouldNotifyControlEvent(input.controlConfig, input.event))
6156
- return;
6157
- let childIntercomTarget = input.intercomBridge.active ? resolveSubagentIntercomTarget(input.event.runId, input.event.agent, input.event.index) : void 0, payload = {
6158
- event: input.event,
6159
- source: "foreground",
6160
- childIntercomTarget,
6161
- noticeText: formatControlNoticeMessage(input.event, childIntercomTarget)
6162
- };
6163
- input.controlConfig.notifyChannels.includes("event") && input.pi.events.emit(SUBAGENT_CONTROL_EVENT, payload), input.event.type !== "active_long_running" && input.controlConfig.notifyChannels.includes("intercom") && input.intercomBridge.active && input.intercomBridge.orchestratorTarget && input.pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
6164
- ...payload,
6165
- to: input.intercomBridge.orchestratorTarget,
6166
- message: formatControlIntercomMessage(input.event, childIntercomTarget)
6167
- });
6168
- }
6169
- function interruptAsyncRun(state, runId, kill, location) {
6170
- let target = getAsyncInterruptTarget(state, runId, location);
6171
- if (!target)
6172
- return null;
6173
- let status = reconcileAsyncRun(target.asyncDir, { kill }).status;
6174
- if (state.currentSessionId && status?.sessionId !== state.currentSessionId)
6175
- return {
6176
- content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
6177
- isError: !0,
6178
- details: { mode: "management", results: [] }
6179
- };
6180
- if (!status || status.state !== "running" || typeof status.pid != "number")
6181
- return {
6182
- content: [{ type: "text", text: `No running async run with an interrupt-capable pid was found for '${runId ?? "current"}'.` }],
6183
- isError: !0,
6184
- details: { mode: "management", results: [] }
6185
- };
6186
- try {
6187
- deliverInterruptRequest({ asyncDir: target.asyncDir, pid: status.pid, kill, source: "interrupt-action" });
6188
- let tracked = state.asyncJobs.get(target.asyncId);
6189
- return tracked && (tracked.activityState = void 0, tracked.updatedAt = Date.now()), {
6190
- content: [{ type: "text", text: `Interrupt requested for async run ${target.asyncId}.` }],
6191
- details: { mode: "management", results: [] }
6192
- };
6193
- } catch (error) {
6194
- let message = error instanceof Error ? error.message : String(error);
6195
- return {
6196
- content: [{ type: "text", text: `Failed to interrupt async run ${target.asyncId}: ${message}` }],
6197
- isError: !0,
6198
- details: { mode: "management", results: [] }
6199
- };
6063
+ if (hasChain && params.chain) {
6064
+ if (params.chain.length === 0)
6065
+ return {
6066
+ content: [{ type: "text", text: "Chain must have at least one step" }],
6067
+ isError: !0,
6068
+ details: { mode: "chain", results: [] }
6069
+ };
6070
+ let firstStep = params.chain[0];
6071
+ if (isParallelStep(firstStep)) {
6072
+ let missingTaskIndex = firstStep.parallel.findIndex((t) => !t.task);
6073
+ if (missingTaskIndex !== -1)
6074
+ return {
6075
+ content: [{ type: "text", text: `First parallel step: task ${missingTaskIndex + 1} must have a task (no previous output to reference)` }],
6076
+ isError: !0,
6077
+ details: { mode: "chain", results: [] }
6078
+ };
6079
+ } else {
6080
+ if (isDynamicParallelStep(firstStep))
6081
+ return {
6082
+ content: [{ type: "text", text: "First step in chain cannot be dynamic fanout; expand.from requires a prior structured named output" }],
6083
+ isError: !0,
6084
+ details: { mode: "chain", results: [] }
6085
+ };
6086
+ if (!firstStep.task && !params.task && !allowClarifyTaskPrompt)
6087
+ return {
6088
+ content: [{ type: "text", text: "First step in chain must have a task" }],
6089
+ isError: !0,
6090
+ details: { mode: "chain", results: [] }
6091
+ };
6092
+ }
6093
+ for (let i = 0; i < params.chain.length; i++) {
6094
+ let step = params.chain[i];
6095
+ if (!isParallelStep(step) && !isDynamicParallelStep(step) && !step.description)
6096
+ return {
6097
+ content: [{ type: "text", text: `description is required (step ${i + 1})` }],
6098
+ isError: !0,
6099
+ details: { mode: "chain", results: [] }
6100
+ };
6101
+ if (isParallelStep(step)) {
6102
+ let missing = step.parallel.findIndex((t) => !t.description);
6103
+ if (missing !== -1)
6104
+ return {
6105
+ content: [{ type: "text", text: `description is required (step ${i + 1}, parallel task ${missing + 1})` }],
6106
+ isError: !0,
6107
+ details: { mode: "chain", results: [] }
6108
+ };
6109
+ }
6110
+ if (isParallelStep(step) && step.parallel.length === 0)
6111
+ return {
6112
+ content: [{ type: "text", text: `Parallel step ${i + 1} must have at least one task` }],
6113
+ isError: !0,
6114
+ details: { mode: "chain", results: [] }
6115
+ };
6116
+ }
6200
6117
  }
6118
+ return null;
6201
6119
  }
6202
- function stopAsyncRun(state, runId, kill, location) {
6203
- let target = getAsyncInterruptTarget(state, runId, location);
6204
- if (!target)
6120
+ function validateExecutionChainBindings(params, dynamicFanoutMaxItems) {
6121
+ if ((params.chain?.length ?? 0) === 0)
6205
6122
  return null;
6206
- let status = reconcileAsyncRun(target.asyncDir, { kill }).status;
6207
- if (state.currentSessionId && status?.sessionId !== state.currentSessionId)
6208
- return {
6209
- content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
6210
- isError: !0,
6211
- details: { mode: "management", results: [] }
6212
- };
6213
- if (!status || status.state !== "running" && status.state !== "queued")
6214
- return {
6215
- content: [{ type: "text", text: `No running or queued async run was found for '${runId ?? "current"}'.` }],
6216
- isError: !0,
6217
- details: { mode: "management", results: [] }
6218
- };
6219
6123
  try {
6220
- deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid == "number" ? status.pid : void 0, kill, source: "stop-action" });
6221
- let tracked = state.asyncJobs.get(target.asyncId);
6222
- return tracked && (tracked.activityState = void 0, tracked.updatedAt = Date.now()), {
6223
- content: [{ type: "text", text: `Stop requested for async run ${target.asyncId}.` }],
6224
- details: { mode: "management", results: [] }
6225
- };
6124
+ validateChainOutputBindingsWithContext(params.chain, { maxItems: dynamicFanoutMaxItems });
6226
6125
  } catch (error) {
6227
- let message = error instanceof Error ? error.message : String(error);
6228
- return {
6229
- content: [{ type: "text", text: `Failed to stop async run ${target.asyncId}: ${message}` }],
6230
- isError: !0,
6231
- details: { mode: "management", results: [] }
6232
- };
6126
+ if (error instanceof ChainOutputValidationError)
6127
+ return {
6128
+ content: [{ type: "text", text: error.message }],
6129
+ isError: !0,
6130
+ details: { mode: "chain", results: [] }
6131
+ };
6132
+ throw error;
6233
6133
  }
6134
+ return null;
6234
6135
  }
6235
- function duplicateNames(names) {
6236
- let seen = /* @__PURE__ */ new Set(), duplicates = /* @__PURE__ */ new Set();
6237
- for (let name of names)
6238
- seen.has(name) ? duplicates.add(name) : seen.add(name);
6239
- return [...duplicates];
6136
+ function getRequestedModeLabel(params) {
6137
+ return (params.chain?.length ?? 0) > 0 ? "chain" : (params.tasks?.length ?? 0) > 0 ? "parallel" : (params.task, "single");
6240
6138
  }
6241
- function appendStepToAsyncChain(input) {
6242
- let targetRunId = input.params.id ?? input.params.runId;
6243
- if (!targetRunId)
6244
- return {
6245
- content: [{ type: "text", text: "action='append-step' requires id." }],
6246
- isError: !0,
6247
- details: { mode: "management", results: [] }
6248
- };
6249
- if (!input.params.chain || input.params.chain.length !== 1)
6250
- return {
6251
- content: [{ type: "text", text: "action='append-step' requires chain with exactly one step." }],
6252
- isError: !0,
6253
- details: { mode: "management", results: [] }
6254
- };
6255
- if ((input.params.tasks?.length ?? 0) > 0)
6256
- return {
6257
- content: [{ type: "text", text: "action='append-step' takes chain only, not tasks." }],
6258
- isError: !0,
6259
- details: { mode: "management", results: [] }
6260
- };
6261
- let acceptanceErrors = validateExecutionAcceptance(input.params);
6262
- if (acceptanceErrors.length > 0)
6263
- return {
6264
- content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
6265
- isError: !0,
6266
- details: { mode: "management", results: [] }
6267
- };
6268
- let resolved;
6269
- try {
6270
- resolved = resolveSubagentRunId(targetRunId, { state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) });
6271
- } catch (error) {
6272
- return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
6139
+ function buildRequestedModeError(params, message) {
6140
+ return withForkContext({
6141
+ content: [{ type: "text", text: message }],
6142
+ isError: !0,
6143
+ details: { mode: getRequestedModeLabel(params), results: [] }
6144
+ }, params.context);
6145
+ }
6146
+ function runtimeConfigFromChildSpec(spec) {
6147
+ return {
6148
+ name: spec.childId,
6149
+ description: spec.description,
6150
+ model: spec.model,
6151
+ thinking: void 0,
6152
+ systemPromptMode: "append",
6153
+ inheritProjectContext: !0,
6154
+ inheritSkills: !1,
6155
+ acceptanceRole: spec.effectivePermissions === "read-only" ? "read-only" : "writer",
6156
+ systemPrompt: "",
6157
+ skills: spec.skill === !1 ? [] : normalizeSkillInput(spec.skill) || void 0,
6158
+ output: typeof spec.output == "string" ? spec.output : void 0,
6159
+ toolBudget: spec.toolBudget
6160
+ };
6161
+ }
6162
+ function internalizePromptDrivenChildren(params, options) {
6163
+ let agents = [], flatIndex = 0, normalize2 = (input, defaultTask) => {
6164
+ let spec = normalizeChildSpec(input, {
6165
+ parentMode: options.parentMode,
6166
+ runId: options.runId,
6167
+ index: flatIndex,
6168
+ defaultTask
6169
+ });
6170
+ return agents.push(runtimeConfigFromChildSpec(spec)), { input: { ...input, agent: spec.childId }, spec };
6171
+ };
6172
+ if ((params.tasks?.length ?? 0) > 0) {
6173
+ let tasks = params.tasks.map((task) => {
6174
+ let normalized2 = normalize2(task);
6175
+ return flatIndex++, normalized2.input;
6176
+ });
6177
+ return { params: { ...params, tasks }, agents };
6273
6178
  }
6274
- if (!resolved)
6275
- return {
6276
- content: [{ type: "text", text: `No async chain run found for '${targetRunId}'.` }],
6277
- isError: !0,
6278
- details: { mode: "management", results: [] }
6279
- };
6280
- if (resolved.kind !== "async" || !resolved.location.asyncDir)
6281
- return {
6282
- content: [{ type: "text", text: `Run '${resolved.id}' is not an append-capable async chain run.` }],
6283
- isError: !0,
6284
- details: { mode: "management", results: [] }
6285
- };
6286
- let status = readStatus(resolved.location.asyncDir);
6287
- if (!status)
6288
- return {
6289
- content: [{ type: "text", text: `No async run status found for '${resolved.id}'.` }],
6290
- isError: !0,
6291
- details: { mode: "management", results: [] }
6292
- };
6293
- if (status.mode !== "chain")
6294
- return {
6295
- content: [{ type: "text", text: `Run '${resolved.id}' is ${status.mode}; only active chain runs accept appended steps.` }],
6296
- isError: !0,
6297
- details: { mode: "management", results: [] }
6298
- };
6299
- if (status.state !== "running")
6300
- return {
6301
- content: [{ type: "text", text: `Run '${resolved.id}' is ${status.state}; only running chain runs accept appended steps.` }],
6302
- isError: !0,
6303
- details: { mode: "management", results: [] }
6304
- };
6305
- if (!((status.steps ?? []).some((step) => step.status === "running" || step.status === "pending") || (status.pendingAppends ?? 0) > 0))
6306
- return {
6307
- content: [{ type: "text", text: `Run '${resolved.id}' has no running or pending chain steps left; append-step must target an in-progress chain.` }],
6308
- isError: !0,
6309
- details: { mode: "management", results: [] }
6310
- };
6311
- let pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir), reservedOutputNames = /* @__PURE__ */ new Set([
6312
- ...Object.keys(status.outputs ?? {}),
6313
- ...(status.steps ?? []).map((step) => step.outputName).filter((name) => !!name),
6314
- ...pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps))
6315
- ]);
6316
- try {
6317
- validateChainOutputBindingsWithContext(input.params.chain, { maxItems: input.deps.config.chain?.dynamicFanout?.maxItems }, {
6318
- priorOutputNames: reservedOutputNames,
6319
- startStepIndex: status.chainStepCount ?? status.steps?.length ?? 0
6179
+ if ((params.chain?.length ?? 0) > 0) {
6180
+ let chain = params.chain.map((step) => {
6181
+ if (isParallelStep(step)) {
6182
+ let parallel = step.parallel.map((task) => {
6183
+ let normalized3 = normalize2(task, flatIndex === 0 ? params.task : "{previous}");
6184
+ return flatIndex++, normalized3.input;
6185
+ });
6186
+ return { ...step, parallel };
6187
+ }
6188
+ if (isDynamicParallelStep(step)) {
6189
+ let normalized3 = normalize2(step.parallel, "{previous}"), reserved = step.expand.maxItems ?? options.dynamicFanoutMaxItems ?? 1;
6190
+ return flatIndex += Math.max(1, reserved), { ...step, parallel: normalized3.input };
6191
+ }
6192
+ let normalized2 = normalize2(step, flatIndex === 0 ? params.task : "{previous}");
6193
+ return flatIndex++, normalized2.input;
6320
6194
  });
6321
- } catch (error) {
6322
- if (!(error instanceof ChainOutputValidationError))
6323
- throw error;
6324
- return {
6325
- content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': ${error.message}` }],
6326
- isError: !0,
6327
- details: { mode: "management", results: [] }
6328
- };
6329
- }
6330
- let appendParams, appendChildRunId = `${resolved.id}-append-${randomUUID4().slice(0, 8)}`;
6331
- try {
6332
- appendParams = internalizePromptDrivenChildren(input.params, {
6333
- runId: appendChildRunId,
6334
- parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? void 0),
6335
- dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems
6336
- }).params;
6337
- } catch (error) {
6338
- return {
6339
- content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
6340
- isError: !0,
6341
- details: { mode: "management", results: [] }
6342
- };
6195
+ return { params: { ...params, chain }, agents };
6343
6196
  }
6344
- let contextPolicy = resolveExplicitContextPolicy(appendParams), chainSkillInput = normalizeSkillInput(appendParams.skill), chainSkills = chainSkillInput === !1 ? [] : chainSkillInput ?? [], asyncCtx = {
6345
- pi: input.deps.pi,
6346
- cwd: input.ctx.cwd,
6347
- currentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),
6348
- parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
6349
- currentModelProvider: input.ctx.model?.provider,
6350
- currentModel: input.ctx.model,
6351
- modelScope: void 0
6352
- }, built = buildAsyncRunnerSteps(resolved.id, {
6353
- chain: wrapChainTasksForFork(appendParams.chain, contextPolicy),
6354
- task: appendParams.task,
6355
- resultMode: "chain",
6356
- ctx: asyncCtx,
6357
- availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
6358
- cwd: status.cwd ?? input.requestCwd,
6359
- chainSkills,
6360
- dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
6361
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
6362
- waitToolEnabled: input.deps.waitToolEnabled,
6363
- asyncDir: resolved.location.asyncDir,
6364
- childIdRunId: appendChildRunId,
6365
- validateOutputBindings: !1
6197
+ let normalized = normalize2({
6198
+ agent: params.agent,
6199
+ task: params.task ?? "",
6200
+ description: params.description,
6201
+ permissions: params.permissions,
6202
+ cwd: params.cwd,
6203
+ model: params.model,
6204
+ tier: params.tier,
6205
+ thinking: params.thinking,
6206
+ skill: params.skill,
6207
+ output: params.output,
6208
+ outputMode: params.outputMode,
6209
+ acceptance: params.acceptance,
6210
+ toolBudget: params.toolBudget
6366
6211
  });
6367
- if ("error" in built)
6368
- return {
6369
- content: [{ type: "text", text: built.error }],
6370
- isError: !0,
6371
- details: { mode: "management", results: [] }
6372
- };
6373
- let appendedOutputNames = runnerStepOutputNames(built.steps), duplicateAppendedOutputs = duplicateNames(appendedOutputNames);
6374
- if (duplicateAppendedOutputs.length > 0)
6375
- return {
6376
- content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': duplicate output name in appended step: ${duplicateAppendedOutputs.join(", ")}.` }],
6377
- isError: !0,
6378
- details: { mode: "management", results: [] }
6379
- };
6380
- let pendingOutputNames = new Set(pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps))), pendingDuplicateOutputs = appendedOutputNames.filter((name) => pendingOutputNames.has(name));
6381
- if (pendingDuplicateOutputs.length > 0)
6382
- return {
6383
- content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': output name already belongs to a pending append: ${pendingDuplicateOutputs.join(", ")}.` }],
6384
- isError: !0,
6385
- details: { mode: "management", results: [] }
6386
- };
6387
- try {
6388
- let result2 = enqueueChainAppendRequest({
6389
- asyncDir: resolved.location.asyncDir,
6390
- runId: resolved.id,
6391
- steps: built.steps
6392
- }), stepText = built.steps.length === 1 ? "step" : "steps";
6393
- return {
6394
- content: [{
6395
- type: "text",
6396
- text: `Append queued for chain run ${resolved.id}: ${built.steps.length} ${stepText}. It becomes eligible after the chain's already-queued steps finish. Pending appends: ${result2.pendingCount}.`
6397
- }],
6398
- details: { mode: "management", results: [], asyncId: resolved.id, asyncDir: resolved.location.asyncDir }
6399
- };
6400
- } catch (error) {
6401
- let message = error instanceof Error ? error.message : String(error);
6402
- return {
6403
- content: [{ type: "text", text: `Failed to append step to chain run ${resolved.id}: ${message}` }],
6404
- isError: !0,
6405
- details: { mode: "management", results: [] }
6406
- };
6212
+ return {
6213
+ params: { ...params, agent: normalized.spec.childId },
6214
+ agents
6215
+ };
6216
+ }
6217
+ function resolveForegroundTimeout(params) {
6218
+ let rawTimeout = params.timeoutMs, rawMaxRuntime = params.maxRuntimeMs;
6219
+ if (rawTimeout === void 0 && rawMaxRuntime === void 0)
6220
+ return {};
6221
+ for (let [name, value] of [["timeoutMs", rawTimeout], ["maxRuntimeMs", rawMaxRuntime]])
6222
+ if (value !== void 0 && (typeof value != "number" || !Number.isInteger(value) || value <= 0))
6223
+ return { error: `${name} must be a positive integer.` };
6224
+ return rawTimeout !== void 0 && rawMaxRuntime !== void 0 && rawTimeout !== rawMaxRuntime ? { error: "timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both." } : { timeoutMs: rawTimeout ?? rawMaxRuntime };
6225
+ }
6226
+ function resolveToolBudget(raw, label = "toolBudget") {
6227
+ let resolved = validateToolBudgetConfig(raw, label);
6228
+ return { toolBudget: resolved.budget, error: resolved.error };
6229
+ }
6230
+ function resolveEffectiveToolBudget(input) {
6231
+ return input.stepBudget !== void 0 ? resolveToolBudget(input.stepBudget, "toolBudget") : input.runBudget !== void 0 ? { toolBudget: input.runBudget } : input.agentBudget !== void 0 ? resolveToolBudget(input.agentBudget, "agent.toolBudget") : resolveToolBudget(input.configBudget, "config.toolBudget");
6232
+ }
6233
+ function expandTopLevelTaskCounts(tasks) {
6234
+ let expanded = [];
6235
+ for (let taskIndex = 0; taskIndex < tasks.length; taskIndex++) {
6236
+ let task = tasks[taskIndex], rawCount = task.count;
6237
+ if (rawCount !== void 0 && (typeof rawCount != "number" || !Number.isInteger(rawCount) || rawCount < 1))
6238
+ return { error: `tasks[${taskIndex}].count must be an integer >= 1` };
6239
+ let { count, ...concreteTask } = task;
6240
+ for (let repeat = 0; repeat < (rawCount ?? 1); repeat++)
6241
+ expanded.push({ ...concreteTask });
6242
+ }
6243
+ return { tasks: expanded };
6244
+ }
6245
+ function expandChainParallelCounts(chain) {
6246
+ let expandedChain = [];
6247
+ for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
6248
+ let step = chain[stepIndex];
6249
+ if (!isParallelStep(step)) {
6250
+ expandedChain.push(step);
6251
+ continue;
6252
+ }
6253
+ let expandedParallel = [];
6254
+ for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
6255
+ let task = step.parallel[taskIndex], rawCount = task.count;
6256
+ if (rawCount !== void 0 && (typeof rawCount != "number" || !Number.isInteger(rawCount) || rawCount < 1))
6257
+ return { error: `chain[${stepIndex}].parallel[${taskIndex}].count must be an integer >= 1` };
6258
+ let { count, ...concreteTask } = task;
6259
+ for (let repeat = 0; repeat < (rawCount ?? 1); repeat++)
6260
+ expandedParallel.push({ ...concreteTask });
6261
+ }
6262
+ expandedChain.push({ ...step, parallel: expandedParallel });
6263
+ }
6264
+ return { chain: expandedChain };
6265
+ }
6266
+ function normalizeRepeatedParallelCounts(params) {
6267
+ if (params.tasks) {
6268
+ let expandedTasks = expandTopLevelTaskCounts(params.tasks);
6269
+ return expandedTasks.error ? { error: buildRequestedModeError(params, expandedTasks.error) } : { params: { ...params, tasks: expandedTasks.tasks } };
6407
6270
  }
6271
+ if (params.chain) {
6272
+ let expandedChain = expandChainParallelCounts(params.chain);
6273
+ return expandedChain.error ? { error: buildRequestedModeError(params, expandedChain.error) } : { params: { ...params, chain: expandedChain.chain } };
6274
+ }
6275
+ return { params };
6276
+ }
6277
+ function toExecutionErrorResult(params, error) {
6278
+ let message = error instanceof Error ? error.message : String(error);
6279
+ return withForkContext({
6280
+ content: [{ type: "text", text: message }],
6281
+ isError: !0,
6282
+ details: { mode: getRequestedModeLabel(params), results: [] }
6283
+ }, params.context);
6284
+ }
6285
+
6286
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.js
6287
+ import { randomUUID as randomUUID4 } from "node:crypto";
6288
+ import * as fs16 from "node:fs";
6289
+ import * as path16 from "node:path";
6290
+ function nestedResolutionScopeForExecutor(deps) {
6291
+ if (deps.allowMutatingManagementActions !== !1)
6292
+ return;
6293
+ let route = resolveInheritedNestedRouteFromEnv(), address = route ? resolveNestedParentAddressFromEnv() : void 0;
6294
+ return {
6295
+ routes: route ? [route] : [],
6296
+ ...address ? { descendantOf: { parentRunId: address.parentRunId, ...address.parentStepIndex !== void 0 ? { parentStepIndex: address.parentStepIndex } : {} } } : {}
6297
+ };
6408
6298
  }
6409
6299
  function nestedRunSessionFile(run) {
6410
6300
  return run.sessionFile ?? (run.steps?.length === 1 ? run.steps[0]?.sessionFile : void 0);
@@ -6463,7 +6353,7 @@ async function waitForNestedControlResult(target, requestId, timeoutMs = 1e3) {
6463
6353
  let result2 = readNestedControlResults(target.match.route).find((candidate) => candidate.requestId === requestId && candidate.targetRunId === target.match.run.id);
6464
6354
  if (result2)
6465
6355
  return result2;
6466
- await new Promise((resolve7) => setTimeout(resolve7, 50));
6356
+ await new Promise((resolve8) => setTimeout(resolve8, 50));
6467
6357
  }
6468
6358
  }
6469
6359
  async function sendNestedControlRequest(target, action, message) {
@@ -6551,263 +6441,279 @@ async function steerNestedRun(input) {
6551
6441
  let direct = await directNestedAsyncSteer(input);
6552
6442
  return direct || { content: [{ type: "text", text: `Nested run ${run.id} is not a live async Pi child session with a steering inbox. action='steer' cannot target foreground nested runs.` }], isError: !0, details: { mode: "management", results: [] } };
6553
6443
  }
6554
- async function resumeAsyncRun(input) {
6555
- let followUp = (input.params.message ?? input.params.task ?? "").trim(), attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain : void 0;
6556
- if (!followUp && !attachChain)
6444
+
6445
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.js
6446
+ function getAsyncInterruptTarget(state, runId, location) {
6447
+ if (location?.asyncDir)
6557
6448
  return {
6558
- content: [{ type: "text", text: "action='resume' requires message." }],
6449
+ asyncId: location.resolvedId ?? runId ?? path17.basename(location.asyncDir),
6450
+ asyncDir: location.asyncDir
6451
+ };
6452
+ if (runId) {
6453
+ let direct = state.asyncJobs.get(runId);
6454
+ return direct ? { asyncId: direct.asyncId, asyncDir: direct.asyncDir } : void 0;
6455
+ }
6456
+ let newest;
6457
+ for (let job of state.asyncJobs.values())
6458
+ job.status === "running" && (!newest || (job.updatedAt ?? 0) > newest.updatedAt) && (newest = { asyncId: job.asyncId, asyncDir: job.asyncDir, updatedAt: job.updatedAt ?? 0 });
6459
+ return newest ? { asyncId: newest.asyncId, asyncDir: newest.asyncDir } : void 0;
6460
+ }
6461
+ function interruptAsyncRun(state, runId, kill, location) {
6462
+ let target = getAsyncInterruptTarget(state, runId, location);
6463
+ if (!target)
6464
+ return null;
6465
+ let status = reconcileAsyncRun(target.asyncDir, { kill }).status;
6466
+ if (state.currentSessionId && status?.sessionId !== state.currentSessionId)
6467
+ return {
6468
+ content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
6559
6469
  isError: !0,
6560
6470
  details: { mode: "management", results: [] }
6561
6471
  };
6562
- let acceptanceErrors = validateExecutionAcceptance(input.params);
6563
- if (acceptanceErrors.length > 0)
6472
+ if (!status || status.state !== "running" || typeof status.pid != "number")
6564
6473
  return {
6565
- content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }],
6474
+ content: [{ type: "text", text: `No running async run with an interrupt-capable pid was found for '${runId ?? "current"}'.` }],
6566
6475
  isError: !0,
6567
6476
  details: { mode: "management", results: [] }
6568
6477
  };
6569
- input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
6570
- let target, parentSessionFile = input.ctx.sessionManager.getSessionFile() ?? null;
6571
6478
  try {
6572
- let requestedId = input.params.id ?? input.params.runId, resolved;
6573
- try {
6574
- resolved = requestedId ? resolveSubagentRunId(requestedId, { state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) }) : void 0;
6575
- } catch (error) {
6576
- let message = error instanceof Error ? error.message : "", asyncMatches = message.match(/async:/g)?.length ?? 0;
6577
- if (!isResumeAmbiguity(error) || !message.includes("foreground:") || asyncMatches !== 1)
6578
- throw error;
6579
- }
6580
- if (resolved?.kind === "nested") {
6581
- if (attachChain)
6582
- return {
6583
- content: [{ type: "text", text: "Attaching a running subagent as a chain root is currently available for top-level async runs only." }],
6584
- isError: !0,
6585
- details: { mode: "management", results: [] }
6586
- };
6587
- if (resolved.match.run.state === "running" || resolved.match.run.state === "queued")
6588
- return resumeLiveNestedRun({ target: resolved, message: followUp });
6589
- let trustedSessionRoots = [
6590
- ...input.deps.config.defaultSessionDir ? [path16.resolve(input.deps.expandTilde(input.deps.config.defaultSessionDir))] : [],
6591
- ...parentSessionFile ? [input.deps.getSubagentSessionRoot(parentSessionFile)] : []
6592
- ];
6593
- target = resolveNestedResumeTarget(resolved, trustedSessionRoots);
6594
- } else
6595
- target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: !attachChain });
6479
+ deliverInterruptRequest({ asyncDir: target.asyncDir, pid: status.pid, kill, source: "interrupt-action" });
6480
+ let tracked = state.asyncJobs.get(target.asyncId);
6481
+ return tracked && (tracked.activityState = void 0, tracked.updatedAt = Date.now()), {
6482
+ content: [{ type: "text", text: `Interrupt requested for async run ${target.asyncId}.` }],
6483
+ details: { mode: "management", results: [] }
6484
+ };
6596
6485
  } catch (error) {
6597
- return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
6486
+ let message = error instanceof Error ? error.message : String(error);
6487
+ return {
6488
+ content: [{ type: "text", text: `Failed to interrupt async run ${target.asyncId}: ${message}` }],
6489
+ isError: !0,
6490
+ details: { mode: "management", results: [] }
6491
+ };
6598
6492
  }
6599
- if (target.kind === "live" && !attachChain) {
6600
- let interrupt = interruptLiveAsyncResumeTarget({
6601
- target,
6602
- state: input.deps.state,
6603
- kill: input.deps.kill,
6604
- resultsDir: RESULTS_DIR
6605
- });
6606
- return interrupt.ok ? await deliverSubagentIntercomMessageEvent(input.deps.pi.events, target.intercomTarget, `Follow-up for async run ${target.runId} (${target.agent}):
6607
-
6608
- ${followUp}`, 500, { source: "async-resume", runId: target.runId, agent: target.agent, index: target.index }) ? {
6609
- content: [{ type: "text", text: ["Interrupted live async child, then delivered follow-up.", `Run: ${target.runId}`, `Intercom target: ${target.intercomTarget}`].join(`
6610
- `) }],
6493
+ }
6494
+ function stopAsyncRun(state, runId, kill, location) {
6495
+ let target = getAsyncInterruptTarget(state, runId, location);
6496
+ if (!target)
6497
+ return null;
6498
+ let status = reconcileAsyncRun(target.asyncDir, { kill }).status;
6499
+ if (state.currentSessionId && status?.sessionId !== state.currentSessionId)
6500
+ return {
6501
+ content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
6502
+ isError: !0,
6611
6503
  details: { mode: "management", results: [] }
6612
- } : {
6613
- content: [{ type: "text", text: ["Async child appears live but its intercom target is not registered.", `Run: ${target.runId}`, `Intercom target: ${target.intercomTarget}`, "Wait for completion, then retry action='resume'."].join(`
6614
- `) }],
6504
+ };
6505
+ if (!status || status.state !== "running" && status.state !== "queued")
6506
+ return {
6507
+ content: [{ type: "text", text: `No running or queued async run was found for '${runId ?? "current"}'.` }],
6615
6508
  isError: !0,
6616
6509
  details: { mode: "management", results: [] }
6617
- } : {
6618
- content: [{ type: "text", text: interrupt.message }],
6510
+ };
6511
+ try {
6512
+ deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid == "number" ? status.pid : void 0, kill, source: "stop-action" });
6513
+ let tracked = state.asyncJobs.get(target.asyncId);
6514
+ return tracked && (tracked.activityState = void 0, tracked.updatedAt = Date.now()), {
6515
+ content: [{ type: "text", text: `Stop requested for async run ${target.asyncId}.` }],
6516
+ details: { mode: "management", results: [] }
6517
+ };
6518
+ } catch (error) {
6519
+ let message = error instanceof Error ? error.message : String(error);
6520
+ return {
6521
+ content: [{ type: "text", text: `Failed to stop async run ${target.asyncId}: ${message}` }],
6619
6522
  isError: !0,
6620
6523
  details: { mode: "management", results: [] }
6621
6524
  };
6622
6525
  }
6623
- let { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth);
6624
- if (blocked)
6526
+ }
6527
+ function duplicateNames(names) {
6528
+ let seen = /* @__PURE__ */ new Set(), duplicates = /* @__PURE__ */ new Set();
6529
+ for (let name of names)
6530
+ seen.has(name) ? duplicates.add(name) : seen.add(name);
6531
+ return [...duplicates];
6532
+ }
6533
+ function appendStepToAsyncChain(input) {
6534
+ let targetRunId = input.params.id ?? input.params.runId;
6535
+ if (!targetRunId)
6625
6536
  return {
6626
- content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depth}, max=${maxDepth}). Complete the follow-up directly instead.` }],
6537
+ content: [{ type: "text", text: "action='append-step' requires id." }],
6627
6538
  isError: !0,
6628
6539
  details: { mode: "management", results: [] }
6629
6540
  };
6630
- input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
6631
- let effectiveCwd = target.cwd ?? input.requestCwd, modelScope = void 0, sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId()), intercomBridge = resolveIntercomBridge({
6632
- config: input.deps.config.intercomBridge,
6633
- cwd: input.requestCwd,
6634
- context: input.params.context,
6635
- orchestratorTarget: sessionName
6636
- }), recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : void 0;
6637
- if (attachChain) {
6638
- if (target.source !== "async")
6639
- return {
6640
- content: [{ type: "text", text: "Attaching a running subagent as a chain root is currently available for async runs only." }],
6641
- isError: !0,
6642
- details: { mode: "management", results: [] }
6643
- };
6644
- if (!isAsyncAvailable())
6645
- return {
6646
- content: [{ type: "text", text: "Async mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
6647
- isError: !0,
6648
- details: { mode: "chain", results: [] }
6649
- };
6650
- let runId2 = randomUUID4().slice(0, 8), artifactConfig2 = { ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== !1 }, availableModels2 = input.ctx.modelRegistry.getAvailable().map(toModelInfo), contextPolicy = resolveExplicitContextPolicy(input.params), workflowTask = (input.params.task ?? followUp) || void 0, goal = resolveAsyncEventGoal(workflowTask, attachChain), chain = wrapChainTasksForFork(attachChain, contextPolicy), normalized = normalizeSkillInput(input.params.skill), result3 = executeAsyncChain(runId2, {
6651
- chain,
6652
- task: workflowTask,
6653
- goal,
6654
- attachRoot: {
6655
- runId: target.runId,
6656
- asyncDir: target.asyncDir ?? path16.join(ASYNC_DIR, target.runId),
6657
- resultPath: resolveAsyncRootResultPath(RESULTS_DIR, target.runId),
6658
- index: target.index,
6659
- agent: target.agent,
6660
- label: `Attached ${target.runId}`
6661
- },
6662
- ctx: {
6663
- pi: input.deps.pi,
6664
- cwd: input.requestCwd,
6665
- currentSessionId: input.deps.state.currentSessionId,
6666
- parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
6667
- currentModelProvider: input.ctx.model?.provider,
6668
- currentModel: input.ctx.model,
6669
- modelScope
6670
- },
6671
- availableModels: availableModels2,
6672
- cwd: effectiveCwd,
6673
- maxOutput: input.params.maxOutput,
6674
- artifactsDir: getArtifactsDir(parentSessionFile),
6675
- artifactConfig: artifactConfig2,
6676
- sessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),
6677
- chainSkills: normalized === !1 ? [] : normalized ?? [],
6678
- dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
6679
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
6680
- waitToolEnabled: input.deps.waitToolEnabled,
6681
- worktreeSetupHook: input.deps.config.worktreeSetupHook,
6682
- worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
6683
- worktreeBaseDir: input.deps.config.worktreeBaseDir,
6684
- controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
6685
- communicationEnabled: intercomBridge.communicationEnabled,
6686
- controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : void 0,
6687
- childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId2, agent, index) : void 0,
6688
- globalConcurrencyLimit: input.deps.config.globalConcurrencyLimit
6689
- });
6690
- if (result3.isError)
6691
- return result3;
6692
- let attachedId = result3.details.asyncId ?? runId2, lines2 = [
6693
- `Attached async subagent ${target.runId} as the first step of a new chain.`,
6694
- `Chain run: ${attachedId}`,
6695
- `Root: ${target.agent} (step ${target.index + 1})`,
6696
- result3.details.asyncDir ? `Async dir: ${result3.details.asyncDir}` : void 0,
6697
- `Status if needed: subagent({ action: "status", id: "${attachedId}" })`
6698
- ].filter((line) => !!line);
6699
- return { content: [{ type: "text", text: formatAsyncStartedMessage(lines2.join(`
6700
- `)) }], details: result3.details };
6701
- }
6702
- let runId = randomUUID4().slice(0, 8), artifactConfig = recoveryDescriptor?.artifactConfig ?? { ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== !1 }, artifactsDir = getArtifactsDir(parentSessionFile), availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo), restoredAcceptance;
6703
- if (recoveryDescriptor?.acceptance !== void 0 && input.params.acceptance === void 0)
6704
- try {
6705
- restoredAcceptance = restorePersistedAcceptance(recoveryDescriptor.acceptance, "recoveryDescriptor.acceptance");
6706
- } catch (error) {
6707
- return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
6708
- }
6709
- let resumeTurnBudget = resolveTurnBudgetConfig(input.params.turnBudget);
6710
- if (resumeTurnBudget.error)
6711
- return { content: [{ type: "text", text: resumeTurnBudget.error }], isError: !0, details: { mode: "management", results: [] } };
6712
- let resumeToolBudget = resolveToolBudget(input.params.toolBudget, "toolBudget");
6713
- if (resumeToolBudget.error)
6714
- return { content: [{ type: "text", text: resumeToolBudget.error }], isError: !0, details: { mode: "management", results: [] } };
6715
- let recordedLimits = {};
6716
- if (recoveryDescriptor && (!resumeTurnBudget.turnBudget || !resumeToolBudget.toolBudget))
6717
- try {
6718
- recordedLimits = remainingSteeringRecoveryLimits({ initialTurnBudget: recoveryDescriptor.initialTurnBudget, initialToolBudget: recoveryDescriptor.initialToolBudget }, (target.source === "async" && target.asyncDir ? readStatus(target.asyncDir) : null) ?? {});
6719
- } catch (error) {
6720
- return { content: [{ type: "text", text: `Cannot revive ${target.runId}: ${error instanceof Error ? error.message : String(error)}` }], isError: !0, details: { mode: "management", results: [] } };
6721
- }
6722
- let reviveTurnBudget = resumeTurnBudget.turnBudget ?? recordedLimits.turnBudget, reviveToolBudget = resumeToolBudget.toolBudget ?? recordedLimits.toolBudget, recoverySpec;
6541
+ if (!input.params.chain || input.params.chain.length !== 1)
6542
+ return {
6543
+ content: [{ type: "text", text: "action='append-step' requires chain with exactly one step." }],
6544
+ isError: !0,
6545
+ details: { mode: "management", results: [] }
6546
+ };
6547
+ if ((input.params.tasks?.length ?? 0) > 0)
6548
+ return {
6549
+ content: [{ type: "text", text: "action='append-step' takes chain only, not tasks." }],
6550
+ isError: !0,
6551
+ details: { mode: "management", results: [] }
6552
+ };
6553
+ let acceptanceErrors = validateExecutionAcceptance(input.params);
6554
+ if (acceptanceErrors.length > 0)
6555
+ return {
6556
+ content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
6557
+ isError: !0,
6558
+ details: { mode: "management", results: [] }
6559
+ };
6560
+ let resolved;
6723
6561
  try {
6724
- let recoverySelection = recoveryDescriptor?.modelSelection ?? target.modelSelection, recoveryIsExplicitModel = recoverySelection?.kind === "model";
6725
- recoverySpec = normalizeChildSpec({
6726
- task: buildRevivedAsyncTask(target, followUp),
6727
- description: recoveryDescriptor?.description ?? target.description ?? target.agent,
6728
- permissions: recoveryDescriptor?.permissions ?? target.permissions ?? "read-only",
6729
- model: recoveryIsExplicitModel ? recoverySelection.model ?? recoveryDescriptor?.model ?? target.model : void 0,
6730
- tier: recoveryIsExplicitModel ? void 0 : input.params.tier ?? recoverySelection?.tier ?? recoveryDescriptor?.tier,
6731
- thinking: recoveryIsExplicitModel ? recoveryDescriptor?.thinking ?? target.thinking : void 0,
6732
- modelSelection: recoverySelection,
6733
- skill: recoveryDescriptor?.skills,
6734
- cwd: effectiveCwd,
6735
- output: recoveryDescriptor?.outputPath,
6736
- outputMode: recoveryDescriptor?.outputMode,
6737
- acceptance: input.params.acceptance,
6738
- toolBudget: recoveryDescriptor?.initialToolBudget
6739
- }, {
6740
- parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? void 0),
6741
- runId,
6742
- index: 0,
6743
- childId: recoveryDescriptor?.childId ?? target.childId ?? `${runId}-0`,
6744
- resolvedModelIsRuntime: !recoveryIsExplicitModel && !!(recoveryDescriptor?.model ?? target.model)
6745
- });
6562
+ resolved = resolveSubagentRunId(targetRunId, { state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) });
6746
6563
  } catch (error) {
6747
6564
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
6748
6565
  }
6749
- let result2 = executeAsyncSingle(runId, {
6750
- spec: recoverySpec,
6751
- completionTask: followUp,
6752
- goal: followUp,
6753
- ctx: {
6754
- pi: input.deps.pi,
6755
- cwd: input.requestCwd,
6756
- currentSessionId: input.deps.state.currentSessionId,
6757
- parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
6758
- currentModelProvider: input.ctx.model?.provider,
6759
- currentModel: input.ctx.model,
6760
- modelScope
6761
- },
6762
- cwd: effectiveCwd,
6763
- maxOutput: input.params.maxOutput ?? recoveryDescriptor?.maxOutput,
6764
- artifactsDir,
6765
- artifactConfig,
6766
- sessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),
6767
- ...recoveryDescriptor?.sessionDir ? { sessionDir: recoveryDescriptor.sessionDir } : {},
6768
- sessionFile: target.sessionFile,
6769
- revivalLease: {
6770
- // Non-null: without attachChain, resolveResumeTarget required a session file.
6771
- sessionFile: target.sessionFile,
6772
- runId,
6773
- sourceRunId: target.runId,
6774
- ...input.deps.state.currentSessionId ? { parentSessionId: input.deps.state.currentSessionId } : {}
6775
- },
6776
- modelOverride: recoveryDescriptor?.model ?? target.model,
6777
- thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
6778
- outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
6779
- maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
6780
- waitToolEnabled: input.deps.waitToolEnabled,
6781
- worktreeSetupHook: input.deps.config.worktreeSetupHook,
6782
- worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
6783
- worktreeBaseDir: input.deps.config.worktreeBaseDir,
6784
- controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
6785
- communicationEnabled: intercomBridge.communicationEnabled,
6786
- controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : void 0,
6787
- childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : void 0,
6788
- availableModels,
6789
- output: recoveryDescriptor?.outputPath,
6790
- outputMode: recoveryDescriptor?.outputMode,
6791
- ...recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {},
6792
- ...restoredAcceptance ? { restoredAcceptance } : {},
6793
- ...input.params.timeoutMs !== void 0 ? { timeoutMs: input.params.timeoutMs } : {},
6794
- ...input.absoluteDeadlineAt !== void 0 ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {},
6795
- ...reviveTurnBudget ? { turnBudget: reviveTurnBudget } : {},
6796
- ...reviveToolBudget ? { toolBudget: reviveToolBudget } : {}
6566
+ if (!resolved)
6567
+ return {
6568
+ content: [{ type: "text", text: `No async chain run found for '${targetRunId}'.` }],
6569
+ isError: !0,
6570
+ details: { mode: "management", results: [] }
6571
+ };
6572
+ if (resolved.kind !== "async" || !resolved.location.asyncDir)
6573
+ return {
6574
+ content: [{ type: "text", text: `Run '${resolved.id}' is not an append-capable async chain run.` }],
6575
+ isError: !0,
6576
+ details: { mode: "management", results: [] }
6577
+ };
6578
+ let status = readStatus(resolved.location.asyncDir);
6579
+ if (!status)
6580
+ return {
6581
+ content: [{ type: "text", text: `No async run status found for '${resolved.id}'.` }],
6582
+ isError: !0,
6583
+ details: { mode: "management", results: [] }
6584
+ };
6585
+ if (status.mode !== "chain")
6586
+ return {
6587
+ content: [{ type: "text", text: `Run '${resolved.id}' is ${status.mode}; only active chain runs accept appended steps.` }],
6588
+ isError: !0,
6589
+ details: { mode: "management", results: [] }
6590
+ };
6591
+ if (status.state !== "running")
6592
+ return {
6593
+ content: [{ type: "text", text: `Run '${resolved.id}' is ${status.state}; only running chain runs accept appended steps.` }],
6594
+ isError: !0,
6595
+ details: { mode: "management", results: [] }
6596
+ };
6597
+ if (!((status.steps ?? []).some((step) => step.status === "running" || step.status === "pending") || (status.pendingAppends ?? 0) > 0))
6598
+ return {
6599
+ content: [{ type: "text", text: `Run '${resolved.id}' has no running or pending chain steps left; append-step must target an in-progress chain.` }],
6600
+ isError: !0,
6601
+ details: { mode: "management", results: [] }
6602
+ };
6603
+ let pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir), reservedOutputNames = /* @__PURE__ */ new Set([
6604
+ ...Object.keys(status.outputs ?? {}),
6605
+ ...(status.steps ?? []).map((step) => step.outputName).filter((name) => !!name),
6606
+ ...pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps))
6607
+ ]);
6608
+ try {
6609
+ validateChainOutputBindingsWithContext(input.params.chain, { maxItems: input.deps.config.chain?.dynamicFanout?.maxItems }, {
6610
+ priorOutputNames: reservedOutputNames,
6611
+ startStepIndex: status.chainStepCount ?? status.steps?.length ?? 0
6612
+ });
6613
+ } catch (error) {
6614
+ if (!(error instanceof ChainOutputValidationError))
6615
+ throw error;
6616
+ return {
6617
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': ${error.message}` }],
6618
+ isError: !0,
6619
+ details: { mode: "management", results: [] }
6620
+ };
6621
+ }
6622
+ let appendParams, appendChildRunId = `${resolved.id}-append-${randomUUID5().slice(0, 8)}`;
6623
+ try {
6624
+ appendParams = internalizePromptDrivenChildren(input.params, {
6625
+ runId: appendChildRunId,
6626
+ parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? void 0),
6627
+ dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems
6628
+ }).params;
6629
+ } catch (error) {
6630
+ return {
6631
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
6632
+ isError: !0,
6633
+ details: { mode: "management", results: [] }
6634
+ };
6635
+ }
6636
+ let contextPolicy = resolveExplicitContextPolicy(appendParams), chainSkillInput = normalizeSkillInput(appendParams.skill), chainSkills = chainSkillInput === !1 ? [] : chainSkillInput ?? [], asyncCtx = {
6637
+ pi: input.deps.pi,
6638
+ cwd: input.ctx.cwd,
6639
+ currentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),
6640
+ parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
6641
+ currentModelProvider: input.ctx.model?.provider,
6642
+ currentModel: input.ctx.model,
6643
+ modelScope: void 0
6644
+ }, built = buildAsyncRunnerSteps(resolved.id, {
6645
+ chain: wrapChainTasksForFork(appendParams.chain, contextPolicy),
6646
+ task: appendParams.task,
6647
+ resultMode: "chain",
6648
+ ctx: asyncCtx,
6649
+ availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
6650
+ cwd: status.cwd ?? input.requestCwd,
6651
+ chainSkills,
6652
+ dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
6653
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
6654
+ waitToolEnabled: input.deps.waitToolEnabled,
6655
+ asyncDir: resolved.location.asyncDir,
6656
+ childIdRunId: appendChildRunId,
6657
+ validateOutputBindings: !1
6658
+ });
6659
+ if ("error" in built)
6660
+ return {
6661
+ content: [{ type: "text", text: built.error }],
6662
+ isError: !0,
6663
+ details: { mode: "management", results: [] }
6664
+ };
6665
+ let appendedOutputNames = runnerStepOutputNames(built.steps), duplicateAppendedOutputs = duplicateNames(appendedOutputNames);
6666
+ if (duplicateAppendedOutputs.length > 0)
6667
+ return {
6668
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': duplicate output name in appended step: ${duplicateAppendedOutputs.join(", ")}.` }],
6669
+ isError: !0,
6670
+ details: { mode: "management", results: [] }
6671
+ };
6672
+ let pendingOutputNames = new Set(pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps))), pendingDuplicateOutputs = appendedOutputNames.filter((name) => pendingOutputNames.has(name));
6673
+ if (pendingDuplicateOutputs.length > 0)
6674
+ return {
6675
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': output name already belongs to a pending append: ${pendingDuplicateOutputs.join(", ")}.` }],
6676
+ isError: !0,
6677
+ details: { mode: "management", results: [] }
6678
+ };
6679
+ try {
6680
+ let result2 = enqueueChainAppendRequest({
6681
+ asyncDir: resolved.location.asyncDir,
6682
+ runId: resolved.id,
6683
+ steps: built.steps
6684
+ }), stepText = built.steps.length === 1 ? "step" : "steps";
6685
+ return {
6686
+ content: [{
6687
+ type: "text",
6688
+ text: `Append queued for chain run ${resolved.id}: ${built.steps.length} ${stepText}. It becomes eligible after the chain's already-queued steps finish. Pending appends: ${result2.pendingCount}.`
6689
+ }],
6690
+ details: { mode: "management", results: [], asyncId: resolved.id, asyncDir: resolved.location.asyncDir }
6691
+ };
6692
+ } catch (error) {
6693
+ let message = error instanceof Error ? error.message : String(error);
6694
+ return {
6695
+ content: [{ type: "text", text: `Failed to append step to chain run ${resolved.id}: ${message}` }],
6696
+ isError: !0,
6697
+ details: { mode: "management", results: [] }
6698
+ };
6699
+ }
6700
+ }
6701
+
6702
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.js
6703
+ function emitControlNotification(input) {
6704
+ if (!shouldNotifyControlEvent(input.controlConfig, input.event))
6705
+ return;
6706
+ let childIntercomTarget = input.intercomBridge.active ? resolveSubagentIntercomTarget(input.event.runId, input.event.agent, input.event.index) : void 0, payload = {
6707
+ event: input.event,
6708
+ source: "foreground",
6709
+ childIntercomTarget,
6710
+ noticeText: formatControlNoticeMessage(input.event, childIntercomTarget)
6711
+ };
6712
+ input.controlConfig.notifyChannels.includes("event") && input.pi.events.emit(SUBAGENT_CONTROL_EVENT, payload), input.event.type !== "active_long_running" && input.controlConfig.notifyChannels.includes("intercom") && input.intercomBridge.active && input.intercomBridge.orchestratorTarget && input.pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
6713
+ ...payload,
6714
+ to: input.intercomBridge.orchestratorTarget,
6715
+ message: formatControlIntercomMessage(input.event, childIntercomTarget)
6797
6716
  });
6798
- if (result2.isError)
6799
- return result2;
6800
- let revivedId = result2.details.asyncId ?? runId, revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : void 0, lines = [
6801
- `Revived ${target.source} subagent from ${target.runId}.`,
6802
- `Revived run: ${revivedId}`,
6803
- `Agent: ${target.agent}`,
6804
- `Session: ${target.sessionFile}`,
6805
- result2.details.asyncDir ? `Async dir: ${result2.details.asyncDir}` : void 0,
6806
- revivedTarget ? `Intercom target: ${revivedTarget} (if registered)` : void 0,
6807
- `Status if needed: subagent({ action: "status", id: "${revivedId}" })`
6808
- ].filter((line) => !!line);
6809
- return { content: [{ type: "text", text: formatAsyncStartedMessage(lines.join(`
6810
- `)) }], details: result2.details };
6811
6717
  }
6812
6718
  function resultSummaryForIntercom(result2) {
6813
6719
  let output = getSingleResultOutput(result2);
@@ -6821,11 +6727,6 @@ ${output}` : result2.error;
6821
6727
 
6822
6728
  ${reference}` : summary;
6823
6729
  }
6824
- function formatFailedSingleRunOutput(result2, displayOutput) {
6825
- let error = result2.error || "Failed", output = displayOutput.trim(), lines = [error];
6826
- return output && output !== error.trim() && lines.push("", "Output:", output), result2.artifactPaths?.outputPath && lines.push("", `Output artifact: ${result2.artifactPaths.outputPath}`), lines.join(`
6827
- `);
6828
- }
6829
6730
  function createForegroundControlNotifier(data, deps) {
6830
6731
  return (event) => emitControlNotification({
6831
6732
  pi: deps.pi,
@@ -6881,1124 +6782,1246 @@ async function maybeBuildForegroundIntercomReceipt(input) {
6881
6782
  details: stripDetailsOutputsForIntercomReceipt(input.details)
6882
6783
  };
6883
6784
  }
6884
- function validateExecutionInput(params, hasChain, hasTasks, hasSingle, allowClarifyTaskPrompt) {
6885
- if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1)
6886
- return {
6887
- content: [
6888
- {
6889
- type: "text",
6890
- text: "Provide exactly one mode: { task, description, permissions? }, { tasks: [...] }, or { chain: [...] }."
6891
- }
6892
- ],
6893
- isError: !0,
6894
- details: { mode: "single", results: [] }
6895
- };
6896
- let acceptanceErrors = validateExecutionAcceptance(params);
6897
- if (acceptanceErrors.length > 0)
6898
- return {
6899
- content: [{ type: "text", text: acceptanceErrors.join(" ") }],
6900
- isError: !0,
6901
- details: { mode: getRequestedModeLabel(params), results: [] }
6902
- };
6903
- if (hasSingle && !params.description)
6904
- return {
6905
- content: [{ type: "text", text: "description is required and must be a concise single-line label (max 80 characters)." }],
6906
- isError: !0,
6907
- details: { mode: "single", results: [] }
6908
- };
6909
- if (hasTasks && params.tasks) {
6910
- for (let i = 0; i < params.tasks.length; i++)
6911
- if (!params.tasks[i].description)
6912
- return {
6913
- content: [{ type: "text", text: `description is required (task ${i + 1})` }],
6914
- isError: !0,
6915
- details: { mode: "parallel", results: [] }
6916
- };
6785
+
6786
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.js
6787
+ function getForegroundControl(state, runId) {
6788
+ if (runId)
6789
+ return state.foregroundControls.get(runId);
6790
+ if (state.lastForegroundControlId) {
6791
+ let latest = state.foregroundControls.get(state.lastForegroundControlId);
6792
+ if (latest)
6793
+ return latest;
6917
6794
  }
6918
- if (hasChain && params.chain) {
6919
- if (params.chain.length === 0)
6920
- return {
6921
- content: [{ type: "text", text: "Chain must have at least one step" }],
6922
- isError: !0,
6923
- details: { mode: "chain", results: [] }
6924
- };
6925
- let firstStep = params.chain[0];
6926
- if (isParallelStep(firstStep)) {
6927
- let missingTaskIndex = firstStep.parallel.findIndex((t) => !t.task);
6928
- if (missingTaskIndex !== -1)
6929
- return {
6930
- content: [{ type: "text", text: `First parallel step: task ${missingTaskIndex + 1} must have a task (no previous output to reference)` }],
6931
- isError: !0,
6932
- details: { mode: "chain", results: [] }
6933
- };
6934
- } else {
6935
- if (isDynamicParallelStep(firstStep))
6936
- return {
6937
- content: [{ type: "text", text: "First step in chain cannot be dynamic fanout; expand.from requires a prior structured named output" }],
6938
- isError: !0,
6939
- details: { mode: "chain", results: [] }
6940
- };
6941
- if (!firstStep.task && !params.task && !allowClarifyTaskPrompt)
6942
- return {
6943
- content: [{ type: "text", text: "First step in chain must have a task" }],
6944
- isError: !0,
6945
- details: { mode: "chain", results: [] }
6946
- };
6947
- }
6948
- for (let i = 0; i < params.chain.length; i++) {
6949
- let step = params.chain[i];
6950
- if (!isParallelStep(step) && !isDynamicParallelStep(step) && !step.description)
6951
- return {
6952
- content: [{ type: "text", text: `description is required (step ${i + 1})` }],
6953
- isError: !0,
6954
- details: { mode: "chain", results: [] }
6955
- };
6956
- if (isParallelStep(step)) {
6957
- let missing = step.parallel.findIndex((t) => !t.description);
6958
- if (missing !== -1)
6959
- return {
6960
- content: [{ type: "text", text: `description is required (step ${i + 1}, parallel task ${missing + 1})` }],
6961
- isError: !0,
6962
- details: { mode: "chain", results: [] }
6963
- };
6964
- }
6965
- if (isParallelStep(step) && step.parallel.length === 0)
6966
- return {
6967
- content: [{ type: "text", text: `Parallel step ${i + 1} must have at least one task` }],
6968
- isError: !0,
6969
- details: { mode: "chain", results: [] }
6970
- };
6971
- }
6972
- }
6973
- return null;
6795
+ let newest;
6796
+ for (let control of state.foregroundControls.values())
6797
+ (!newest || control.updatedAt > newest.updatedAt) && (newest = control);
6798
+ return newest;
6974
6799
  }
6975
- function validateExecutionChainBindings(params, dynamicFanoutMaxItems) {
6976
- if ((params.chain?.length ?? 0) === 0)
6977
- return null;
6800
+ function formatForegroundActivity(control) {
6801
+ let facts = [];
6802
+ if (control.currentTool && control.currentToolStartedAt ? facts.push(`tool ${control.currentTool} for ${Math.floor(Math.max(0, Date.now() - control.currentToolStartedAt) / 1e3)}s`) : control.currentTool && facts.push(`tool ${control.currentTool}`), control.currentPath && facts.push(`path ${control.currentPath}`), control.turnCount !== void 0 && facts.push(`${control.turnCount} turns`), control.tokens !== void 0 && facts.push(`${control.tokens} tokens`), control.toolCount !== void 0 && facts.push(`${control.toolCount} tools`), !control.lastActivityAt)
6803
+ return control.currentActivityState === "needs_attention" ? ["needs attention", ...facts].join(" | ") : control.currentActivityState === "active_long_running" ? ["active but long-running", ...facts].join(" | ") : facts.length ? facts.join(" | ") : void 0;
6804
+ let seconds = Math.floor(Math.max(0, Date.now() - control.lastActivityAt) / 1e3);
6805
+ return control.currentActivityState === "needs_attention" ? [`no activity for ${seconds}s`, ...facts].join(" | ") : control.currentActivityState === "active_long_running" ? [`active but long-running; last activity ${seconds}s ago`, ...facts].join(" | ") : [`active ${seconds}s ago`, ...facts].join(" | ");
6806
+ }
6807
+ function foregroundStatusResult(control) {
6808
+ let nestedWarning;
6978
6809
  try {
6979
- validateChainOutputBindingsWithContext(params.chain, { maxItems: dynamicFanoutMaxItems });
6810
+ updateForegroundNestedProjection(control);
6980
6811
  } catch (error) {
6981
- if (error instanceof ChainOutputValidationError)
6982
- return {
6983
- content: [{ type: "text", text: error.message }],
6984
- isError: !0,
6985
- details: { mode: "chain", results: [] }
6986
- };
6987
- throw error;
6812
+ nestedWarning = `Nested status unavailable: ${error instanceof Error ? error.message : String(error)}`;
6988
6813
  }
6989
- return null;
6990
- }
6991
- function getRequestedModeLabel(params) {
6992
- return (params.chain?.length ?? 0) > 0 ? "chain" : (params.tasks?.length ?? 0) > 0 ? "parallel" : (params.task, "single");
6814
+ let activity = formatForegroundActivity(control), lines = [
6815
+ `Run: ${control.runId}`,
6816
+ "State: running",
6817
+ `Mode: ${control.mode}`,
6818
+ control.currentAgent ? `Current: ${control.currentAgent}${control.currentIndex !== void 0 ? ` step ${control.currentIndex + 1}` : ""}` : void 0,
6819
+ activity ? `Activity: ${activity}` : void 0
6820
+ ].filter((line) => !!line);
6821
+ return lines.push(...formatNestedRunStatusLines(control.nestedChildren, { indent: "", commandHints: !0, maxLines: 20 })), nestedWarning && lines.push(`Warning: ${nestedWarning}`), { content: [{ type: "text", text: lines.join(`
6822
+ `) }], details: { mode: "management", results: [] } };
6993
6823
  }
6994
- function resolveAgentDefaultContextPolicy(params) {
6995
- return lunrContextPolicy(params);
6824
+ function trimRememberedForegroundRuns(state) {
6825
+ if (state.foregroundRuns)
6826
+ for (; state.foregroundRuns.size > 50; ) {
6827
+ let oldestTerminal = [...state.foregroundRuns.values()].filter((run) => !run.children.some((child) => child.status === "detached")).sort((left, right) => left.updatedAt - right.updatedAt)[0];
6828
+ if (!oldestTerminal)
6829
+ break;
6830
+ state.foregroundRuns.delete(oldestTerminal.runId);
6831
+ }
6996
6832
  }
6997
- function resolveExplicitContextPolicy(params) {
6998
- return lunrContextPolicy(params);
6833
+ function rememberForegroundRun(state, input) {
6834
+ state.foregroundRuns ??= /* @__PURE__ */ new Map();
6835
+ let previous = state.foregroundRuns.get(input.runId), updatedAt = Date.now();
6836
+ state.foregroundRuns.set(input.runId, {
6837
+ runId: input.runId,
6838
+ mode: input.mode,
6839
+ cwd: input.cwd,
6840
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
6841
+ updatedAt,
6842
+ children: input.results.map((result2, index) => {
6843
+ let child = {
6844
+ agent: result2.agent,
6845
+ index,
6846
+ status: resolveSubagentResultStatus({ exitCode: result2.exitCode, interrupted: result2.interrupted, detached: result2.detached }),
6847
+ updatedAt,
6848
+ ...result2.exitCode !== void 0 ? { exitCode: result2.exitCode } : {},
6849
+ ...result2.error ? { error: result2.error } : {},
6850
+ ...result2.finalOutput ? { finalOutput: result2.finalOutput } : {},
6851
+ ...result2.outputMode ? { outputMode: result2.outputMode } : {},
6852
+ ...result2.savedOutputPath ? { savedOutputPath: result2.savedOutputPath } : {},
6853
+ ...result2.outputSaveError ? { outputSaveError: result2.outputSaveError } : {},
6854
+ ...result2.sessionFile ? { sessionFile: result2.sessionFile } : {},
6855
+ ...result2.artifactPaths ? { artifactPaths: result2.artifactPaths } : {},
6856
+ ...result2.transcriptPath ? { transcriptPath: result2.transcriptPath } : {},
6857
+ ...result2.transcriptError ? { transcriptError: result2.transcriptError } : {},
6858
+ ...result2.detachedReason ? { detachedReason: result2.detachedReason } : {},
6859
+ ...result2.acceptance ? { acceptance: result2.acceptance } : {}
6860
+ }, recovered = previous?.children[index];
6861
+ return child.status === "detached" && recovered && recovered.status !== "detached" ? recovered : child;
6862
+ })
6863
+ }), trimRememberedForegroundRuns(state);
6999
6864
  }
7000
- function shouldForkAgent(contextPolicy, agentName) {
7001
- return contextPolicy.contextForAgent(agentName) === "fork";
6865
+ function updateRememberedForegroundChild(state, input) {
6866
+ state.foregroundRuns ??= /* @__PURE__ */ new Map();
6867
+ let updatedAt = Date.now(), run = state.foregroundRuns.get(input.runId);
6868
+ run || (run = { runId: input.runId, mode: input.mode, cwd: input.cwd, ...input.sessionId ? { sessionId: input.sessionId } : {}, updatedAt, children: [] }, state.foregroundRuns.set(input.runId, run)), run.updatedAt = updatedAt;
6869
+ let child = run.children[input.index] ?? { agent: input.result.agent, index: input.index, status: "detached" };
6870
+ run.children[input.index] = {
6871
+ ...child,
6872
+ agent: input.result.agent,
6873
+ index: input.index,
6874
+ status: input.result.acceptance?.status === "rejected" ? "failed" : resolveSubagentResultStatus({ exitCode: input.result.exitCode, interrupted: input.result.interrupted, detached: !1 }),
6875
+ updatedAt,
6876
+ ...input.result.exitCode !== void 0 ? { exitCode: input.result.exitCode } : {},
6877
+ ...input.result.error ? { error: input.result.error } : {},
6878
+ ...input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {},
6879
+ outputMode: input.result.outputMode,
6880
+ savedOutputPath: input.result.savedOutputPath,
6881
+ outputSaveError: input.result.outputSaveError,
6882
+ ...input.result.sessionFile ? { sessionFile: input.result.sessionFile } : {},
6883
+ ...input.result.artifactPaths ? { artifactPaths: input.result.artifactPaths } : {},
6884
+ ...input.result.transcriptPath ? { transcriptPath: input.result.transcriptPath } : {},
6885
+ ...input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {},
6886
+ ...input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {},
6887
+ ...input.result.acceptance ? { acceptance: input.result.acceptance } : {}
6888
+ }, trimRememberedForegroundRuns(state);
6889
+ let output = getSingleResultOutput(input.result).trim(), success = input.result.exitCode === 0 && input.result.acceptance?.status !== "rejected", summary = !success && input.result.error ? `${input.result.error}${output ? `
6890
+
6891
+ Output:
6892
+ ${output}` : ""}` : output || input.result.error || "Detached child exited without final output.";
6893
+ input.events.emit(SUBAGENT_FOREGROUND_COMPLETE_EVENT, {
6894
+ id: `${input.runId}:${input.index}`,
6895
+ runId: input.runId,
6896
+ source: "foreground",
6897
+ mode: input.mode,
6898
+ agent: input.result.agent,
6899
+ success,
6900
+ summary,
6901
+ exitCode: input.result.exitCode,
6902
+ state: success ? "complete" : "failed",
6903
+ timestamp: updatedAt,
6904
+ cwd: input.cwd,
6905
+ sessionFile: input.result.sessionFile,
6906
+ sessionId: input.sessionId,
6907
+ taskIndex: input.index,
6908
+ results: [{ childId: input.result.childId, agent: input.result.agent, sessionFile: input.result.sessionFile, usage: input.result.usage, usageRequests: input.result.usageRequests, success, output: summary }]
6909
+ });
7002
6910
  }
7003
- function buildRequestedModeError(params, message) {
7004
- return withForkContext({
6911
+
6912
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.js
6913
+ import { randomUUID as randomUUID6 } from "node:crypto";
6914
+ import * as path18 from "node:path";
6915
+ function buildParallelModeError(message) {
6916
+ return {
7005
6917
  content: [{ type: "text", text: message }],
7006
6918
  isError: !0,
7007
- details: { mode: getRequestedModeLabel(params), results: [] }
7008
- }, params.context);
7009
- }
7010
- function runtimeConfigFromChildSpec(spec) {
7011
- return {
7012
- name: spec.childId,
7013
- description: spec.description,
7014
- model: spec.model,
7015
- thinking: void 0,
7016
- systemPromptMode: "append",
7017
- inheritProjectContext: !0,
7018
- inheritSkills: !1,
7019
- acceptanceRole: spec.effectivePermissions === "read-only" ? "read-only" : "writer",
7020
- systemPrompt: "",
7021
- skills: spec.skill === !1 ? [] : normalizeSkillInput(spec.skill) || void 0,
7022
- output: typeof spec.output == "string" ? spec.output : void 0,
7023
- toolBudget: spec.toolBudget
6919
+ details: { mode: "parallel", results: [] }
7024
6920
  };
7025
6921
  }
7026
- function internalizePromptDrivenChildren(params, options) {
7027
- let agents = [], flatIndex = 0, normalize2 = (input, defaultTask) => {
7028
- let spec = normalizeChildSpec(input, {
7029
- parentMode: options.parentMode,
7030
- runId: options.runId,
7031
- index: flatIndex,
7032
- defaultTask
7033
- });
7034
- return agents.push(runtimeConfigFromChildSpec(spec)), { input: { ...input, agent: spec.childId }, spec };
7035
- };
7036
- if ((params.tasks?.length ?? 0) > 0) {
7037
- let tasks = params.tasks.map((task) => {
7038
- let normalized2 = normalize2(task);
7039
- return flatIndex++, normalized2.input;
7040
- });
7041
- return { params: { ...params, tasks }, agents };
7042
- }
7043
- if ((params.chain?.length ?? 0) > 0) {
7044
- let chain = params.chain.map((step) => {
7045
- if (isParallelStep(step)) {
7046
- let parallel = step.parallel.map((task) => {
7047
- let normalized3 = normalize2(task, flatIndex === 0 ? params.task : "{previous}");
7048
- return flatIndex++, normalized3.input;
7049
- });
7050
- return { ...step, parallel };
7051
- }
7052
- if (isDynamicParallelStep(step)) {
7053
- let normalized3 = normalize2(step.parallel, "{previous}"), reserved = step.expand.maxItems ?? options.dynamicFanoutMaxItems ?? 1;
7054
- return flatIndex += Math.max(1, reserved), { ...step, parallel: normalized3.input };
7055
- }
7056
- let normalized2 = normalize2(step, flatIndex === 0 ? params.task : "{previous}");
7057
- return flatIndex++, normalized2.input;
7058
- });
7059
- return { params: { ...params, chain }, agents };
6922
+ function createParallelWorktreeSetup(enabled, cwd, runId, tasks, setupHook, setupHookTimeoutMs, baseDir) {
6923
+ if (!enabled)
6924
+ return {};
6925
+ try {
6926
+ return {
6927
+ setup: createWorktrees(cwd, runId, tasks.length, {
6928
+ agents: tasks.map((task) => task.agent),
6929
+ setupHook: setupHook ? { hookPath: setupHook, timeoutMs: setupHookTimeoutMs } : void 0,
6930
+ baseDir
6931
+ })
6932
+ };
6933
+ } catch (error) {
6934
+ let message = error instanceof Error ? error.message : String(error);
6935
+ return { errorResult: buildParallelModeError(message) };
7060
6936
  }
7061
- let normalized = normalize2({
7062
- agent: params.agent,
7063
- task: params.task ?? "",
7064
- description: params.description,
7065
- permissions: params.permissions,
7066
- cwd: params.cwd,
7067
- model: params.model,
7068
- tier: params.tier,
7069
- thinking: params.thinking,
7070
- skill: params.skill,
7071
- output: params.output,
7072
- outputMode: params.outputMode,
7073
- acceptance: params.acceptance,
7074
- toolBudget: params.toolBudget
7075
- });
7076
- return {
7077
- params: { ...params, agent: normalized.spec.childId },
7078
- agents
7079
- };
7080
6937
  }
7081
- function resolveForegroundTimeout(params) {
7082
- let rawTimeout = params.timeoutMs, rawMaxRuntime = params.maxRuntimeMs;
7083
- if (rawTimeout === void 0 && rawMaxRuntime === void 0)
7084
- return {};
7085
- for (let [name, value] of [["timeoutMs", rawTimeout], ["maxRuntimeMs", rawMaxRuntime]])
7086
- if (value !== void 0 && (typeof value != "number" || !Number.isInteger(value) || value <= 0))
7087
- return { error: `${name} must be a positive integer.` };
7088
- return rawTimeout !== void 0 && rawMaxRuntime !== void 0 && rawTimeout !== rawMaxRuntime ? { error: "timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both." } : { timeoutMs: rawTimeout ?? rawMaxRuntime };
6938
+ function buildParallelWorktreeTaskCwdError(tasks, sharedCwd) {
6939
+ let conflict = findWorktreeTaskCwdConflict(tasks, sharedCwd);
6940
+ if (conflict)
6941
+ return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
7089
6942
  }
7090
- function resolveToolBudget(raw, label = "toolBudget") {
7091
- let resolved = validateToolBudgetConfig(raw, label);
7092
- return { toolBudget: resolved.budget, error: resolved.error };
6943
+ function resolveParallelTaskCwd(task, paramsCwd, worktreeSetup, index) {
6944
+ return worktreeSetup ? worktreeSetup.worktrees[index].agentCwd : resolveChildCwd(paramsCwd, task.cwd);
7093
6945
  }
7094
- function resolveEffectiveToolBudget(input) {
7095
- return input.stepBudget !== void 0 ? resolveToolBudget(input.stepBudget, "toolBudget") : input.runBudget !== void 0 ? { toolBudget: input.runBudget } : input.agentBudget !== void 0 ? resolveToolBudget(input.agentBudget, "agent.toolBudget") : resolveToolBudget(input.configBudget, "config.toolBudget");
6946
+ function buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks) {
6947
+ if (!worktreeSetup)
6948
+ return "";
6949
+ let diffsDir = path18.join(artifactsDir, "worktree-diffs"), diffs = diffWorktrees(worktreeSetup, tasks.map((task) => task.agent), diffsDir);
6950
+ return formatWorktreeDiffSummary(diffs);
7096
6951
  }
7097
- function expandTopLevelTaskCounts(tasks) {
7098
- let expanded = [];
7099
- for (let taskIndex = 0; taskIndex < tasks.length; taskIndex++) {
7100
- let task = tasks[taskIndex], rawCount = task.count;
7101
- if (rawCount !== void 0 && (typeof rawCount != "number" || !Number.isInteger(rawCount) || rawCount < 1))
7102
- return { error: `tasks[${taskIndex}].count must be an integer >= 1` };
7103
- let { count, ...concreteTask } = task;
7104
- for (let repeat = 0; repeat < (rawCount ?? 1); repeat++)
7105
- expanded.push({ ...concreteTask });
7106
- }
7107
- return { tasks: expanded };
7108
- }
7109
- function expandChainParallelCounts(chain) {
7110
- let expandedChain = [];
7111
- for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
7112
- let step = chain[stepIndex];
7113
- if (!isParallelStep(step)) {
7114
- expandedChain.push(step);
7115
- continue;
7116
- }
7117
- let expandedParallel = [];
7118
- for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
7119
- let task = step.parallel[taskIndex], rawCount = task.count;
7120
- if (rawCount !== void 0 && (typeof rawCount != "number" || !Number.isInteger(rawCount) || rawCount < 1))
7121
- return { error: `chain[${stepIndex}].parallel[${taskIndex}].count must be an integer >= 1` };
7122
- let { count, ...concreteTask } = task;
7123
- for (let repeat = 0; repeat < (rawCount ?? 1); repeat++)
7124
- expandedParallel.push({ ...concreteTask });
7125
- }
7126
- expandedChain.push({ ...step, parallel: expandedParallel });
7127
- }
7128
- return { chain: expandedChain };
7129
- }
7130
- function normalizeRepeatedParallelCounts(params) {
7131
- if (params.tasks) {
7132
- let expandedTasks = expandTopLevelTaskCounts(params.tasks);
7133
- return expandedTasks.error ? { error: buildRequestedModeError(params, expandedTasks.error) } : { params: { ...params, tasks: expandedTasks.tasks } };
7134
- }
7135
- if (params.chain) {
7136
- let expandedChain = expandChainParallelCounts(params.chain);
7137
- return expandedChain.error ? { error: buildRequestedModeError(params, expandedChain.error) } : { params: { ...params, chain: expandedChain.chain } };
7138
- }
7139
- return { params };
7140
- }
7141
- function withForkContext(result2, context) {
7142
- return context !== "fork" || !result2.details ? result2 : {
7143
- ...result2,
7144
- details: {
7145
- ...result2.details,
7146
- context: "fork"
7147
- }
7148
- };
7149
- }
7150
- function withForkThinkingNotes(result2, downgrades) {
7151
- if (downgrades.size === 0)
7152
- return result2;
7153
- let note = `Note: fork context forced thinking off for ${[...downgrades.entries()].sort(([a], [b]) => a - b).map(([index, agent]) => `${agent} (child ${index})`).join(", ")}. The forked transcript contained signed Anthropic thinking blocks that were sanitized, and Anthropic children cannot resume such a transcript with thinking enabled. Use context: "fresh" when an Anthropic child needs thinking.`;
7154
- return { ...result2, content: [...result2.content, { type: "text", text: note }] };
7155
- }
7156
- function toExecutionErrorResult(params, error) {
7157
- let message = error instanceof Error ? error.message : String(error);
7158
- return withForkContext({
7159
- content: [{ type: "text", text: message }],
7160
- isError: !0,
7161
- details: { mode: getRequestedModeLabel(params), results: [] }
7162
- }, params.context);
7163
- }
7164
- function collectChainSessionFiles(chain, sessionFileForTask, dynamicFanoutMaxItems) {
7165
- let sessionFiles = [], flatIndex = 0;
7166
- for (let step of chain) {
7167
- if (isParallelStep(step)) {
7168
- for (let task of step.parallel)
7169
- sessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model)), flatIndex++;
7170
- continue;
7171
- }
7172
- if (isDynamicParallelStep(step)) {
7173
- let maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
7174
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
7175
- sessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model)), flatIndex++;
7176
- continue;
7177
- }
7178
- let sequential = step;
7179
- sessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model)), flatIndex++;
7180
- }
7181
- return sessionFiles;
7182
- }
7183
- function collectChainThinkingOverrides(chain, thinkingOverrideForTask, dynamicFanoutMaxItems) {
7184
- let thinkingOverrides = [], flatIndex = 0;
7185
- for (let step of chain) {
7186
- if (isParallelStep(step)) {
7187
- for (let task of step.parallel)
7188
- thinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model)), flatIndex++;
7189
- continue;
7190
- }
7191
- if (isDynamicParallelStep(step)) {
7192
- let maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
7193
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
7194
- thinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model)), flatIndex++;
7195
- continue;
7196
- }
7197
- let sequential = step;
7198
- thinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model)), flatIndex++;
7199
- }
7200
- return thinkingOverrides;
7201
- }
7202
- function firstChainAgent(chain) {
7203
- let first = chain[0];
7204
- if (first)
7205
- return isParallelStep(first) ? first.parallel[0]?.agent : isDynamicParallelStep(first) ? first.parallel.agent : first.agent;
7206
- }
7207
- function firstRawChainTask(chain) {
7208
- let first = chain[0];
7209
- if (first)
7210
- return isParallelStep(first) ? first.parallel[0]?.task : isDynamicParallelStep(first) ? first.parallel.task : first.task;
7211
- }
7212
- function resolveAsyncEventGoal(workflowTask, rawChain, unwrapForkFallback = !1) {
7213
- if (workflowTask?.trim())
7214
- return workflowTask;
7215
- let fallback = firstRawChainTask(rawChain) || "";
7216
- if (!unwrapForkFallback)
7217
- return fallback;
7218
- let forkPrefix = `${DEFAULT_FORK_PREAMBLE}
7219
-
7220
- Task:
7221
- `;
7222
- return fallback.startsWith(forkPrefix) ? fallback.slice(forkPrefix.length) : fallback;
7223
- }
7224
- function wrapChainTasksForFork(chain, contextPolicy) {
7225
- return chain.map((step, stepIndex) => {
7226
- if (isParallelStep(step))
7227
- return {
7228
- ...step,
7229
- parallel: step.parallel.map((task) => ({
7230
- ...task,
7231
- task: shouldForkAgent(contextPolicy, task.agent) ? wrapForkTask(task.task ?? "{previous}") : task.task
7232
- }))
7233
- };
7234
- if (isDynamicParallelStep(step))
7235
- return {
7236
- ...step,
7237
- parallel: {
7238
- ...step.parallel,
7239
- task: shouldForkAgent(contextPolicy, step.parallel.agent) ? wrapForkTask(step.parallel.task ?? "{previous}") : step.parallel.task
7240
- }
7241
- };
7242
- let sequential = step;
7243
- return {
7244
- ...sequential,
7245
- task: shouldForkAgent(contextPolicy, sequential.agent) ? wrapForkTask(sequential.task ?? (stepIndex === 0 ? "{task}" : "{previous}")) : sequential.task
7246
- };
7247
- });
7248
- }
7249
- function preflightForkSessionsForStaticTasks(params, contextPolicy, sessionFileForTask, dynamicFanoutMaxItems) {
7250
- if (!contextPolicy.usesFork)
7251
- return;
7252
- if (params.agent) {
7253
- shouldForkAgent(contextPolicy, params.agent) && sessionFileForTask(params.agent, 0, params.model);
7254
- return;
7255
- }
7256
- if (params.tasks) {
7257
- params.tasks.forEach((task, index) => {
7258
- shouldForkAgent(contextPolicy, task.agent) && sessionFileForTask(task.agent, index, task.model);
7259
- });
7260
- return;
7261
- }
7262
- if (!params.chain?.length)
7263
- return;
7264
- let flatIndex = 0;
7265
- for (let step of params.chain) {
7266
- if (isParallelStep(step)) {
7267
- for (let task of step.parallel)
7268
- shouldForkAgent(contextPolicy, task.agent) && sessionFileForTask(task.agent, flatIndex, task.model), flatIndex++;
6952
+ function findDuplicateParallelOutputPath(input) {
6953
+ let seen = /* @__PURE__ */ new Map();
6954
+ for (let index = 0; index < input.tasks.length; index++) {
6955
+ let behavior = input.behaviors[index];
6956
+ if (!behavior?.output)
7269
6957
  continue;
7270
- }
7271
- if (isDynamicParallelStep(step)) {
7272
- let maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
7273
- if (shouldForkAgent(contextPolicy, step.parallel.agent))
7274
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
7275
- sessionFileForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
7276
- flatIndex += maxItems;
6958
+ let task = input.tasks[index], taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index), outputPath = resolveSingleOutputPath(behavior.output, input.ctxCwd, taskCwd, input.outputBaseDir);
6959
+ if (!outputPath)
7277
6960
  continue;
7278
- }
7279
- let sequential = step;
7280
- shouldForkAgent(contextPolicy, sequential.agent) && sessionFileForTask(sequential.agent, flatIndex, sequential.model), flatIndex++;
6961
+ let previous = seen.get(outputPath);
6962
+ if (previous)
6963
+ return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
6964
+ seen.set(outputPath, { index, agent: task.agent });
7281
6965
  }
7282
6966
  }
7283
- function runAsyncPath(data, deps) {
7284
- let { params, effectiveCwd, agents, ctx, sessionRoot, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, effectiveAsync, controlConfig, intercomBridge, nestedRoute, contextPolicy } = data, hasChain = (params.chain?.length ?? 0) > 0, hasTasks = (params.tasks?.length ?? 0) > 0, hasSingle = !hasChain && !hasTasks && !!params.agent;
7285
- if (!effectiveAsync)
7286
- return null;
7287
- if (hasChain && params.chain) {
7288
- let chainWorktreeTaskCwdError = buildChainWorktreeTaskCwdError(params.chain, effectiveCwd);
7289
- if (chainWorktreeTaskCwdError)
7290
- return {
7291
- content: [{ type: "text", text: chainWorktreeTaskCwdError }],
7292
- isError: !0,
7293
- details: { mode: "chain", results: [] }
7294
- };
7295
- }
7296
- if (hasTasks && params.tasks) {
7297
- let maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);
7298
- if (params.tasks.length > maxParallelTasks)
7299
- return buildParallelModeError(`Max ${maxParallelTasks} tasks`);
7300
- if (params.worktree) {
7301
- let worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(params.tasks, effectiveCwd);
7302
- if (worktreeTaskCwdError)
7303
- return buildParallelModeError(worktreeTaskCwdError);
7304
- }
7305
- }
7306
- if (!isAsyncAvailable())
7307
- return {
7308
- content: [{ type: "text", text: "Async mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7309
- isError: !0,
7310
- details: { mode: "single", results: [] }
7311
- };
7312
- let id = randomUUID4(), asyncCtx = {
7313
- pi: deps.pi,
7314
- cwd: ctx.cwd,
7315
- currentSessionId: deps.state.currentSessionId,
7316
- parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7317
- currentModelProvider: ctx.model?.provider,
7318
- currentModel: ctx.model,
7319
- modelScope: data.modelScope
7320
- }, availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo), currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth), currentProvider = ctx.model?.provider, controlIntercomTarget = intercomBridge.active ? intercomBridge.orchestratorTarget : void 0, childIntercomTarget = intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : void 0;
7321
- if (hasTasks && params.tasks) {
7322
- let skillOverrides = params.tasks.map((task) => normalizeSkillInput(task.skill)), parallelTasks = params.tasks.map((task, index) => ({
7323
- agent: task.agent,
7324
- task: shouldForkAgent(contextPolicy, task.agent) ? wrapForkTask(task.task) : task.task,
6967
+ async function runForegroundParallelTasks(input) {
6968
+ for (let i = 0; i < input.tasks.length; i++)
6969
+ input.sessionFileForTask(input.tasks[i].agent, i, input.modelOverrides[i]);
6970
+ return mapConcurrent(input.tasks, input.concurrencyLimit, async (task, index) => {
6971
+ let behavior = input.behaviors[index], effectiveSkills = behavior?.skills, taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index), readInstructions = behavior ? buildChainInstructions({ ...behavior, output: !1, progress: !1 }, taskCwd, !1) : { prefix: "", suffix: "" }, progressInstructions = behavior ? buildChainInstructions({ ...behavior, output: !1, reads: !1 }, input.progressDir, index === input.firstProgressIndex) : { prefix: "", suffix: "" }, outputPath = resolveSingleOutputPath(behavior?.output, input.ctx.cwd, taskCwd, input.outputBaseDir), agentConfig = input.agents.find((agent) => agent.name === task.agent), taskText = injectSingleOutputInstruction(`${readInstructions.prefix}${input.taskTexts[index]}${progressInstructions.suffix}`, outputPath, agentConfig), interruptController = new AbortController();
6972
+ input.foregroundControl && (input.foregroundControl.currentAgent = task.description || task.agent, input.foregroundControl.currentChildId = task.agent, input.foregroundControl.currentIndex = index, input.foregroundControl.currentActivityState = void 0, input.foregroundControl.updatedAt = Date.now(), input.foregroundControl.interrupt = () => interruptController.signal.aborted ? !1 : (interruptController.abort(), input.foregroundControl.currentActivityState = void 0, input.foregroundControl.updatedAt = Date.now(), !0));
6973
+ let modelSelection = input.modelSelections[index] ?? captureModelSelection({ model: task.model, tier: task.tier });
6974
+ return runSync(input.ctx.cwd, normalizeChildSpec({
6975
+ task: taskText,
7325
6976
  description: task.description,
7326
6977
  permissions: task.permissions,
7327
- cwd: task.cwd,
7328
6978
  model: task.model,
7329
6979
  tier: task.tier,
7330
6980
  thinking: task.thinking,
7331
- ...skillOverrides[index] !== void 0 ? { skill: skillOverrides[index] } : {},
7332
- ...task.output !== void 0 && task.output !== !0 ? { output: task.output } : {},
7333
- ...task.outputMode !== void 0 ? { outputMode: task.outputMode } : {},
7334
- ...task.reads !== void 0 && task.reads !== !0 ? { reads: task.reads } : {},
7335
- ...task.progress !== void 0 ? { progress: task.progress } : {},
7336
- ...task.toolBudget !== void 0 ? { toolBudget: task.toolBudget } : {},
7337
- ...task.acceptance !== void 0 ? { acceptance: task.acceptance } : {}
7338
- }));
7339
- return executeAsyncChain(id, {
7340
- chain: [{
7341
- parallel: parallelTasks,
7342
- concurrency: resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency),
7343
- worktree: params.worktree
7344
- }],
7345
- resultMode: "parallel",
7346
- communicationEnabled: intercomBridge.communicationEnabled,
7347
- goal: params.tasks[0]?.task ?? "",
7348
- ctx: asyncCtx,
7349
- availableModels,
7350
- cwd: effectiveCwd,
7351
- maxOutput: params.maxOutput,
7352
- artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7353
- artifactConfig,
7354
- sessionRoot,
7355
- chainSkills: [],
7356
- sessionFilesByFlatIndex: params.tasks.map((task, index) => sessionFileForTask(task.agent, index, task.model)),
7357
- thinkingOverridesByFlatIndex: params.tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, task.model)),
7358
- maxSubagentDepth: currentMaxSubagentDepth,
7359
- waitToolEnabled: deps.waitToolEnabled,
7360
- worktreeSetupHook: deps.config.worktreeSetupHook,
7361
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7362
- worktreeBaseDir: deps.config.worktreeBaseDir,
7363
- controlConfig,
7364
- controlIntercomTarget,
7365
- childIntercomTarget,
7366
- nestedRoute,
7367
- timeoutMs: data.timeoutMs,
7368
- turnBudget: data.turnBudget,
7369
- toolBudget: data.toolBudget,
7370
- configToolBudget: data.configToolBudget,
7371
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit
6981
+ modelSelection,
6982
+ skill: task.skill,
6983
+ cwd: taskCwd,
6984
+ output: task.output,
6985
+ outputMode: task.outputMode,
6986
+ acceptance: task.acceptance,
6987
+ toolBudget: task.toolBudget
6988
+ }, { parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? void 0), runId: input.runId, index }), {
6989
+ parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
6990
+ cwd: taskCwd,
6991
+ signal: input.signal,
6992
+ interruptSignal: interruptController.signal,
6993
+ allowIntercomDetach: agentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === !0,
6994
+ intercomEvents: input.intercomEvents,
6995
+ runId: input.runId,
6996
+ index,
6997
+ sessionDir: input.sessionDirForIndex(index),
6998
+ sessionFile: input.sessionFileForTask(task.agent, index, input.modelOverrides[index]),
6999
+ artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : void 0,
7000
+ artifactConfig: input.artifactConfig,
7001
+ maxOutput: input.maxOutput,
7002
+ outputPath,
7003
+ outputMode: behavior?.outputMode,
7004
+ maxSubagentDepth: input.maxSubagentDepths[index],
7005
+ waitToolEnabled: input.waitToolEnabled,
7006
+ controlConfig: input.controlConfig,
7007
+ onControlEvent: input.onControlEvent,
7008
+ onDetachedExit: (result2) => updateRememberedForegroundChild(input.state, { runId: input.runId, mode: "parallel", cwd: taskCwd, sessionId: input.parentSessionId, index, result: result2, events: input.intercomEvents }),
7009
+ intercomSessionName: input.childIntercomTarget?.(task.agent, index),
7010
+ orchestratorIntercomTarget: input.orchestratorIntercomTarget,
7011
+ communicationEnabled: input.communicationEnabled,
7012
+ nestedRoute: input.foregroundControl?.nestedRoute,
7013
+ modelOverride: input.modelOverrides[index],
7014
+ thinkingOverride: input.thinkingOverrideForTask(task.agent, index, input.modelOverrides[index]),
7015
+ availableModels: input.availableModels,
7016
+ preferredModelProvider: input.ctx.model?.provider,
7017
+ modelScope: input.modelScope,
7018
+ skills: effectiveSkills === !1 ? [] : effectiveSkills,
7019
+ acceptance: task.acceptance,
7020
+ acceptanceContext: { mode: "parallel" },
7021
+ timeoutMs: input.timeoutMs,
7022
+ deadlineAt: input.deadlineAt,
7023
+ turnBudget: input.turnBudget,
7024
+ toolBudget: input.toolBudgets[index],
7025
+ onUpdate: input.onUpdate ? (progressUpdate) => {
7026
+ let stepResults = progressUpdate.details?.results || [], stepProgress = progressUpdate.details?.progress || [];
7027
+ if (input.foregroundControl && stepProgress.length > 0) {
7028
+ let current = stepProgress[0];
7029
+ input.foregroundControl.currentAgent = task.description || task.agent, input.foregroundControl.currentChildId = task.agent, input.foregroundControl.currentIndex = index, input.foregroundControl.currentActivityState = current?.activityState, input.foregroundControl.lastActivityAt = current?.lastActivityAt, input.foregroundControl.currentTool = current?.currentTool, input.foregroundControl.currentToolStartedAt = current?.currentToolStartedAt, input.foregroundControl.currentPath = current?.currentPath, input.foregroundControl.turnCount = current?.turnCount, input.foregroundControl.tokens = current?.tokens, input.foregroundControl.toolCount = current?.toolCount, input.foregroundControl.updatedAt = Date.now();
7030
+ }
7031
+ stepResults.length > 0 && (input.liveResults[index] = stepResults[0]), stepProgress.length > 0 && (input.liveProgress[index] = stepProgress[0]);
7032
+ let mergedResults = input.liveResults.filter((result2) => result2 !== void 0), mergedProgress = input.liveProgress.filter((progress) => progress !== void 0);
7033
+ input.onUpdate?.({
7034
+ content: progressUpdate.content,
7035
+ details: {
7036
+ mode: "parallel",
7037
+ results: mergedResults,
7038
+ progress: mergedProgress,
7039
+ controlEvents: progressUpdate.details?.controlEvents,
7040
+ totalSteps: input.tasks.length
7041
+ }
7042
+ });
7043
+ } : void 0
7044
+ }).finally(() => {
7045
+ input.foregroundControl?.currentIndex === index && (input.foregroundControl.interrupt = void 0, input.foregroundControl.updatedAt = Date.now());
7372
7046
  });
7047
+ }, input.globalSemaphore, {
7048
+ signal: input.signal,
7049
+ onAbort: (task) => ({
7050
+ agent: task.agent,
7051
+ task: task.task ?? "",
7052
+ exitCode: 1,
7053
+ messages: [],
7054
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
7055
+ error: "Subagent launch cancelled."
7056
+ })
7057
+ });
7058
+ }
7059
+ async function runParallelPath(data, deps) {
7060
+ let { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, backgroundRequestedWhileClarifying, onUpdate, sessionRoot, controlConfig, contextPolicy } = data, onControlEvent = createForegroundControlNotifier(data, deps), childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : void 0, allProgress = [], allArtifactPaths = [], tasks = params.tasks, maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks), parallelConcurrency = resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency);
7061
+ if (tasks.length > maxParallelTasks)
7062
+ return {
7063
+ content: [{ type: "text", text: `Max ${maxParallelTasks} tasks` }],
7064
+ isError: !0,
7065
+ details: { mode: "parallel", results: [] }
7066
+ };
7067
+ let agentConfigs = [];
7068
+ for (let t of tasks) {
7069
+ let config = agents.find((a) => a.name === t.agent);
7070
+ if (!config)
7071
+ return {
7072
+ content: [{ type: "text", text: `Unknown agent: ${t.agent}` }],
7073
+ isError: !0,
7074
+ details: { mode: "parallel", results: [] }
7075
+ };
7076
+ agentConfigs.push(config);
7373
7077
  }
7374
- if (hasChain && params.chain) {
7375
- let normalized = normalizeSkillInput(params.skill), chainSkills = normalized === !1 ? [] : normalized ?? [], rawChain = params.chain, chain = wrapChainTasksForFork(rawChain, contextPolicy);
7376
- return executeAsyncChain(id, {
7377
- chain,
7378
- task: params.task,
7379
- goal: resolveAsyncEventGoal(params.task, rawChain),
7380
- communicationEnabled: intercomBridge.communicationEnabled,
7381
- ctx: asyncCtx,
7382
- availableModels,
7383
- cwd: effectiveCwd,
7384
- maxOutput: params.maxOutput,
7385
- artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7078
+ let currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth), maxSubagentDepths = agentConfigs.map((config) => resolveChildMaxSubagentDepth(currentMaxSubagentDepth, config.maxSubagentDepth)), toolBudgets = [];
7079
+ for (let index = 0; index < tasks.length; index++) {
7080
+ let resolved = resolveEffectiveToolBudget({ stepBudget: tasks[index]?.toolBudget, runBudget: data.toolBudget, agentBudget: agentConfigs[index]?.toolBudget, configBudget: data.configToolBudget });
7081
+ if (resolved.error)
7082
+ return buildParallelModeError(resolved.error);
7083
+ toolBudgets.push(resolved.toolBudget);
7084
+ }
7085
+ if (params.worktree) {
7086
+ let worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(tasks, effectiveCwd);
7087
+ if (worktreeTaskCwdError)
7088
+ return buildParallelModeError(worktreeTaskCwdError);
7089
+ }
7090
+ let currentProvider = ctx.model?.provider, availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo), taskTexts = tasks.map((t) => t.task), skillOverrides = tasks.map((t) => normalizeSkillInput(t.skill)), behaviorOverrides = tasks.map((task, index) => ({
7091
+ ...task.output !== void 0 && task.output !== !0 ? { output: task.output } : {},
7092
+ ...task.outputMode !== void 0 ? { outputMode: task.outputMode } : {},
7093
+ ...task.reads !== void 0 && task.reads !== !0 ? { reads: task.reads } : {},
7094
+ ...task.progress !== void 0 ? { progress: task.progress } : {},
7095
+ ...skillOverrides[index] !== void 0 ? { skills: skillOverrides[index] } : {}
7096
+ })), modelSelections = tasks.map((task) => captureModelSelection({ model: task.model, tier: task.tier })), modelOverrides = tasks.map((task, index) => resolveExecutableChildModel({
7097
+ modelSelection: modelSelections[index],
7098
+ model: task.model,
7099
+ tier: task.tier,
7100
+ thinking: task.thinking,
7101
+ availableModels,
7102
+ preferredProvider: currentProvider
7103
+ }));
7104
+ if (params.clarify === !0 && ctx.hasUI) {
7105
+ let behaviors2 = agentConfigs.map((_c, i) => resolveStepBehavior(behaviorOverrides[i])), availableSkills = discoverAvailableSkills(effectiveCwd), result2 = await ctx.ui.custom((tui, theme, _kb, done) => new ChainClarifyComponent(tui, theme, agentConfigs, taskTexts, "", void 0, behaviors2, availableModels, currentProvider, availableSkills, done, "parallel"), { overlay: !0, overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" } });
7106
+ if (!result2 || !result2.confirmed)
7107
+ return { content: [{ type: "text", text: "Cancelled" }], details: { mode: "parallel", results: [] } };
7108
+ taskTexts = result2.templates;
7109
+ for (let i = 0; i < result2.behaviorOverrides.length; i++) {
7110
+ let override = result2.behaviorOverrides[i];
7111
+ override?.output !== void 0 && (behaviorOverrides[i].output = override.output), override?.reads !== void 0 && (behaviorOverrides[i].reads = override.reads), override?.progress !== void 0 && (behaviorOverrides[i].progress = override.progress), override?.skills !== void 0 && (skillOverrides[i] = override.skills, behaviorOverrides[i].skills = override.skills);
7112
+ }
7113
+ if (result2.runInBackground) {
7114
+ if (!isAsyncAvailable())
7115
+ return {
7116
+ content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7117
+ isError: !0,
7118
+ details: { mode: "parallel", results: [] }
7119
+ };
7120
+ let id = randomUUID6(), asyncCtx = {
7121
+ pi: deps.pi,
7122
+ cwd: ctx.cwd,
7123
+ currentSessionId: deps.state.currentSessionId,
7124
+ parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7125
+ currentModelProvider: ctx.model?.provider,
7126
+ currentModel: ctx.model,
7127
+ modelScope: data.modelScope
7128
+ }, parallelTasks = tasks.map((t, i) => {
7129
+ let taskText = shouldForkAgent(contextPolicy, t.agent) ? wrapForkTask(taskTexts[i]) : taskTexts[i], progress = taskDisallowsFileUpdates(taskText) ? !1 : behaviorOverrides[i]?.progress;
7130
+ return {
7131
+ agent: t.agent,
7132
+ task: taskText,
7133
+ description: t.description,
7134
+ permissions: t.permissions,
7135
+ cwd: t.cwd,
7136
+ model: t.model,
7137
+ tier: t.tier,
7138
+ thinking: t.thinking,
7139
+ ...skillOverrides[i] !== void 0 ? { skill: skillOverrides[i] } : {},
7140
+ ...behaviorOverrides[i]?.output !== void 0 ? { output: behaviorOverrides[i].output } : {},
7141
+ ...behaviorOverrides[i]?.outputMode !== void 0 ? { outputMode: behaviorOverrides[i].outputMode } : {},
7142
+ ...behaviorOverrides[i]?.reads !== void 0 ? { reads: behaviorOverrides[i].reads } : {},
7143
+ ...progress !== void 0 ? { progress } : {},
7144
+ ...t.toolBudget !== void 0 ? { toolBudget: t.toolBudget } : {},
7145
+ ...t.acceptance !== void 0 ? { acceptance: t.acceptance } : {}
7146
+ };
7147
+ });
7148
+ return executeAsyncChain(id, {
7149
+ chain: [{ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree }],
7150
+ resultMode: "parallel",
7151
+ goal: taskTexts[0] ?? "",
7152
+ communicationEnabled: data.intercomBridge.communicationEnabled,
7153
+ ctx: asyncCtx,
7154
+ availableModels,
7155
+ cwd: effectiveCwd,
7156
+ maxOutput: params.maxOutput,
7157
+ artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7158
+ artifactConfig,
7159
+ sessionRoot,
7160
+ chainSkills: [],
7161
+ sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
7162
+ thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
7163
+ maxSubagentDepth: currentMaxSubagentDepth,
7164
+ waitToolEnabled: deps.waitToolEnabled,
7165
+ worktreeSetupHook: deps.config.worktreeSetupHook,
7166
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7167
+ worktreeBaseDir: deps.config.worktreeBaseDir,
7168
+ controlConfig,
7169
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7170
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : void 0,
7171
+ timeoutMs: data.timeoutMs,
7172
+ turnBudget: data.turnBudget,
7173
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7174
+ });
7175
+ }
7176
+ }
7177
+ let behaviors = agentConfigs.map((_config, index) => suppressProgressForReadOnlyTask(resolveStepBehavior(behaviorOverrides[index]), taskTexts[index])), firstProgressIndex = behaviors.findIndex((behavior) => behavior.progress), liveResults = new Array(tasks.length).fill(void 0), liveProgress = new Array(tasks.length).fill(void 0), foregroundControl = deps.state.foregroundControls.get(runId), { setup: worktreeSetup, errorResult } = createParallelWorktreeSetup(params.worktree, effectiveCwd, runId, tasks, deps.config.worktreeSetupHook, deps.config.worktreeSetupHookTimeoutMs, deps.config.worktreeBaseDir);
7178
+ if (errorResult)
7179
+ return errorResult;
7180
+ try {
7181
+ let outputBaseDir = path18.join(artifactsDir, "outputs", runId), duplicateOutputError = findDuplicateParallelOutputPath({
7182
+ tasks,
7183
+ behaviors,
7184
+ paramsCwd: effectiveCwd,
7185
+ ctxCwd: ctx.cwd,
7186
+ outputBaseDir,
7187
+ worktreeSetup
7188
+ });
7189
+ if (duplicateOutputError)
7190
+ return buildParallelModeError(duplicateOutputError);
7191
+ for (let index = 0; index < tasks.length; index++) {
7192
+ let taskCwd = resolveParallelTaskCwd(tasks[index], effectiveCwd, worktreeSetup, index), outputPath = resolveSingleOutputPath(behaviors[index]?.output, ctx.cwd, taskCwd, outputBaseDir), validationError = validateFileOnlyOutputMode(behaviors[index]?.outputMode, outputPath, `Parallel task ${index + 1} (${tasks[index].agent})`) ?? outputTargetError(outputPath, ctx.cwd) ?? readOnlyOutputError(outputPath, outputBaseDir, ctx.sessionManager.getSessionId() ?? void 0);
7193
+ if (validationError)
7194
+ return buildParallelModeError(validationError);
7195
+ }
7196
+ let parallelProgressPrecreated = firstProgressIndex !== -1, parallelProgressDir = path18.join(artifactsDir, "progress", runId);
7197
+ parallelProgressPrecreated && writeInitialProgressFile(parallelProgressDir);
7198
+ for (let i = 0; i < taskTexts.length; i++)
7199
+ shouldForkAgent(contextPolicy, tasks[i].agent) && (taskTexts[i] = wrapForkTask(taskTexts[i]));
7200
+ let deadlineAt = data.deadlineAt ?? (data.timeoutMs !== void 0 ? Date.now() + data.timeoutMs : void 0), results = await runForegroundParallelTasks({
7201
+ tasks,
7202
+ taskTexts,
7203
+ agents,
7204
+ ctx,
7205
+ state: deps.state,
7206
+ intercomEvents: deps.pi.events,
7207
+ parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7208
+ signal,
7209
+ runId,
7210
+ sessionDirForIndex,
7211
+ sessionFileForIndex,
7212
+ sessionFileForTask,
7213
+ thinkingOverrideForTask,
7386
7214
  artifactConfig,
7387
- sessionRoot,
7388
- chainSkills,
7389
- sessionFilesByFlatIndex: collectChainSessionFiles(chain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
7390
- thinkingOverridesByFlatIndex: collectChainThinkingOverrides(chain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
7391
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
7392
- maxSubagentDepth: currentMaxSubagentDepth,
7393
- waitToolEnabled: deps.waitToolEnabled,
7394
- worktreeSetupHook: deps.config.worktreeSetupHook,
7395
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7396
- worktreeBaseDir: deps.config.worktreeBaseDir,
7215
+ artifactsDir,
7216
+ outputBaseDir,
7217
+ maxOutput: params.maxOutput,
7218
+ paramsCwd: effectiveCwd,
7219
+ progressDir: parallelProgressDir,
7220
+ availableModels,
7221
+ modelScope: data.modelScope,
7222
+ modelOverrides,
7223
+ modelSelections,
7224
+ behaviors,
7225
+ firstProgressIndex: parallelProgressPrecreated ? -1 : firstProgressIndex,
7397
7226
  controlConfig,
7398
- controlIntercomTarget,
7399
- childIntercomTarget,
7400
- nestedRoute,
7227
+ onControlEvent,
7228
+ childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : void 0,
7229
+ orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7230
+ communicationEnabled: data.intercomBridge.communicationEnabled,
7231
+ foregroundControl,
7232
+ concurrencyLimit: parallelConcurrency,
7233
+ globalSemaphore: new Semaphore(deps.config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT),
7234
+ maxSubagentDepths,
7235
+ waitToolEnabled: deps.waitToolEnabled,
7236
+ liveResults,
7237
+ liveProgress,
7238
+ onUpdate,
7239
+ worktreeSetup,
7401
7240
  timeoutMs: data.timeoutMs,
7241
+ deadlineAt,
7402
7242
  turnBudget: data.turnBudget,
7403
- toolBudget: data.toolBudget,
7404
- configToolBudget: data.configToolBudget,
7405
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7243
+ toolBudgets
7406
7244
  });
7407
- }
7408
- if (hasSingle) {
7409
- let a = agents.find((x) => x.name === params.agent);
7410
- if (!a)
7245
+ for (let i = 0; i < results.length; i++) {
7246
+ let run = results[i];
7247
+ recordRun(run.agent, taskTexts[i], run.exitCode, run.progressSummary?.durationMs ?? 0);
7248
+ }
7249
+ for (let result2 of results)
7250
+ result2.progress && allProgress.push(result2.progress), result2.artifactPaths && allArtifactPaths.push(result2.artifactPaths);
7251
+ foregroundControl && (updateForegroundNestedProjection(foregroundControl), attachRootChildrenToSteps(runId, results, foregroundControl.nestedChildren));
7252
+ let interrupted = results.find((result2) => result2.interrupted), details = compactForegroundDetails({
7253
+ mode: "parallel",
7254
+ runId,
7255
+ results,
7256
+ progress: params.includeProgress ? allProgress : void 0,
7257
+ artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : void 0,
7258
+ totalChildUsage: sumResultsUsage(results),
7259
+ totalCost: sumResultsCost(results)
7260
+ });
7261
+ if (rememberForegroundRun(deps.state, { runId, mode: "parallel", cwd: effectiveCwd, sessionId: data.parentSessionId, results: details.results }), interrupted)
7411
7262
  return {
7412
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
7413
- isError: !0,
7414
- details: { mode: "single", results: [] }
7263
+ content: [{ type: "text", text: `Parallel run paused after interrupt (${interrupted.agent}). Waiting for explicit next action.` }],
7264
+ details
7415
7265
  };
7416
- let rawOutput = params.output !== void 0 ? params.output : a.output, effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output), effectiveOutputMode = params.outputMode ?? "inline", normalizedSkills = normalizeSkillInput(params.skill), skills = normalizedSkills === !1 ? [] : normalizedSkills, maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, a.maxSubagentDepth), modelSelection = captureModelSelection({ model: params.model, tier: params.tier }), modelOverride = resolveExecutableChildModel({
7417
- modelSelection,
7418
- model: params.model,
7419
- tier: params.tier,
7420
- thinking: params.thinking,
7421
- availableModels,
7422
- preferredProvider: currentProvider
7423
- }), spec = normalizeChildSpec({
7424
- task: shouldForkAgent(contextPolicy, params.agent) ? wrapForkTask(params.task ?? "") : params.task ?? "",
7425
- description: params.description,
7426
- permissions: params.permissions,
7427
- model: params.model,
7428
- tier: params.tier,
7429
- thinking: params.thinking,
7430
- modelSelection,
7431
- skill: params.skill,
7432
- cwd: effectiveCwd,
7433
- output: effectiveOutput,
7434
- outputMode: effectiveOutputMode,
7435
- acceptance: params.acceptance,
7436
- toolBudget: params.toolBudget
7437
- }, {
7438
- parentMode: snapshotParentPermissionMode(ctx.sessionManager.getSessionId() ?? void 0),
7439
- runId: id,
7440
- index: 0,
7441
- childId: params.agent
7266
+ let detachedIndex = results.findIndex((result2) => result2.detached), detached = detachedIndex >= 0 ? results[detachedIndex] : void 0;
7267
+ if (detached)
7268
+ return {
7269
+ content: [{ type: "text", text: `Parallel run detached for intercom coordination (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
7270
+ details
7271
+ };
7272
+ foregroundControl && updateForegroundNestedProjection(foregroundControl);
7273
+ let intercomReceipt = await maybeBuildForegroundIntercomReceipt({
7274
+ pi: deps.pi,
7275
+ intercomBridge: data.intercomBridge,
7276
+ runId,
7277
+ mode: "parallel",
7278
+ details,
7279
+ ...foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}
7442
7280
  });
7443
- return executeAsyncSingle(id, {
7444
- spec,
7445
- goal: params.task ?? "",
7446
- ctx: asyncCtx,
7447
- availableModels,
7448
- cwd: effectiveCwd,
7449
- maxOutput: params.maxOutput,
7450
- artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7451
- artifactConfig,
7452
- sessionRoot,
7453
- sessionFile: sessionFileForTask(params.agent, 0, modelOverride),
7454
- skills,
7455
- output: effectiveOutput,
7456
- outputMode: effectiveOutputMode,
7457
- outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
7458
- modelOverride,
7459
- thinkingOverride: thinkingOverrideForTask(params.agent, 0, modelOverride),
7460
- maxSubagentDepth,
7461
- waitToolEnabled: deps.waitToolEnabled,
7462
- worktreeSetupHook: deps.config.worktreeSetupHook,
7463
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7464
- worktreeBaseDir: deps.config.worktreeBaseDir,
7465
- controlConfig,
7466
- communicationEnabled: intercomBridge.communicationEnabled,
7467
- controlIntercomTarget,
7468
- childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : void 0,
7469
- nestedRoute,
7470
- acceptance: params.acceptance,
7471
- timeoutMs: data.timeoutMs,
7472
- turnBudget: data.turnBudget,
7473
- toolBudget: data.toolBudget,
7474
- configToolBudget: data.configToolBudget
7281
+ if (intercomReceipt)
7282
+ return {
7283
+ content: [{ type: "text", text: intercomReceipt.text }],
7284
+ details: intercomReceipt.details
7285
+ };
7286
+ let worktreeSuffix = buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks), ok = results.filter((result2) => result2.exitCode === 0).length, downgradeNote = backgroundRequestedWhileClarifying ? " (background requested, but clarify kept this run foreground)" : "", aggregatedOutput = aggregateParallelOutputs(results.map((result2) => ({
7287
+ agent: result2.agent,
7288
+ output: result2.truncation?.text || getSingleResultOutput(result2),
7289
+ exitCode: result2.exitCode,
7290
+ error: result2.error,
7291
+ timedOut: result2.timedOut
7292
+ })), (i, agent) => `=== Task ${i + 1}: ${agent} ===`), summary = `${ok}/${results.length} succeeded${downgradeNote}`;
7293
+ return {
7294
+ content: [{ type: "text", text: worktreeSuffix ? `${summary}
7295
+
7296
+ ${aggregatedOutput}
7297
+
7298
+ ${worktreeSuffix}` : `${summary}
7299
+
7300
+ ${aggregatedOutput}` }],
7301
+ details
7302
+ };
7303
+ } finally {
7304
+ worktreeSetup && cleanupWorktrees(worktreeSetup);
7305
+ }
7306
+ }
7307
+
7308
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js
7309
+ var MUTATING_MANAGEMENT_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "delete", "eject", "disable", "enable", "reset"]);
7310
+ function resolveRequestedCwd(runtimeCwd, requestedCwd) {
7311
+ return requestedCwd ? path19.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
7312
+ }
7313
+ function trustedSessionRootsForStatus(ctx, deps) {
7314
+ let roots = deps.config.defaultSessionDir ? [path19.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : [], parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
7315
+ return parentSessionFile && roots.push(deps.getSubagentSessionRoot(parentSessionFile)), [...new Set(roots)];
7316
+ }
7317
+ function reserveSubagentSpawns(input) {
7318
+ if (input.requested <= 0)
7319
+ return;
7320
+ let maxSpawns = resolveMaxSubagentSpawnsPerSession(input.config.maxSubagentSpawnsPerSession);
7321
+ if (maxSpawns === void 0)
7322
+ return;
7323
+ input.state.subagentSpawns?.sessionId !== input.sessionId && (input.state.subagentSpawns = { sessionId: input.sessionId, count: 0 });
7324
+ let used = input.state.subagentSpawns.count;
7325
+ if (used + input.requested > maxSpawns)
7326
+ return {
7327
+ content: [{ type: "text", text: `Subagent spawn limit reached for this session (${used}/${maxSpawns} used, ${input.requested} requested). Complete the work directly or start a new session.` }],
7328
+ isError: !0,
7329
+ details: { mode: input.mode, results: [] }
7330
+ };
7331
+ input.state.subagentSpawns.count = used + input.requested;
7332
+ }
7333
+ function countRequestedSubagentSpawns(params, config) {
7334
+ return params.tasks ? params.tasks.length : params.chain ? params.chain.reduce((total, step) => isDynamicParallelStep(step) ? total + (step.expand.maxItems ?? config.chain?.dynamicFanout?.maxItems ?? 0) : total + getStepAgents(step).length, 0) : params.agent ? 1 : 0;
7335
+ }
7336
+ function resolveForegroundResumeTarget(params, state) {
7337
+ let requested = (params.id ?? params.runId)?.trim();
7338
+ if (!requested || !state.foregroundRuns?.size || !state.currentSessionId)
7339
+ return;
7340
+ let sessionRuns = [...state.foregroundRuns.values()].filter((run2) => run2.sessionId === state.currentSessionId), direct = sessionRuns.find((run2) => run2.runId === requested), matches = direct ? [direct] : sessionRuns.filter((run2) => run2.runId.startsWith(requested));
7341
+ if (matches.length === 0)
7342
+ return;
7343
+ if (matches.length > 1)
7344
+ throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run2) => run2.runId).join(", ")}. Provide a longer id.`);
7345
+ let run = matches[0];
7346
+ if (run.children.some((child2) => child2.status === "detached"))
7347
+ throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
7348
+ if (run.children.length > 1 && params.index === void 0)
7349
+ throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
7350
+ let index = params.index ?? 0;
7351
+ if (!Number.isInteger(index))
7352
+ throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
7353
+ if (index < 0 || index >= run.children.length)
7354
+ throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Index ${index} is out of range.`);
7355
+ let child = run.children[index];
7356
+ if (!child.sessionFile)
7357
+ throw new Error(`Foreground run '${run.runId}' child ${index} does not have a persisted session file to resume from.`);
7358
+ if (path19.extname(child.sessionFile) !== ".jsonl")
7359
+ throw new Error(`Foreground run '${run.runId}' child ${index} session file must be a .jsonl file: ${child.sessionFile}`);
7360
+ let sessionFile = path19.resolve(child.sessionFile);
7361
+ if (!fs17.existsSync(sessionFile))
7362
+ throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}`);
7363
+ return { runId: run.runId, mode: run.mode, state: "complete", agent: child.agent, index, intercomTarget: resolveSubagentIntercomTarget(run.runId, child.agent, index), cwd: run.cwd, sessionFile };
7364
+ }
7365
+ function isAsyncRunNotFound(error) {
7366
+ return error instanceof Error && error.message.startsWith("Async run not found.");
7367
+ }
7368
+ function isResumeAmbiguity(error) {
7369
+ return error instanceof Error && /Ambiguous .*run id prefix/.test(error.message);
7370
+ }
7371
+ function resumeTargetExact(target, requested) {
7372
+ return target?.runId === requested;
7373
+ }
7374
+ function escapeRegExp(value) {
7375
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7376
+ }
7377
+ function isExactResumeError(error, source, requested) {
7378
+ return !(error instanceof Error) || !requested ? !1 : new RegExp(`\\b${source} run '${escapeRegExp(requested)}'`, "i").test(error.message);
7379
+ }
7380
+ function resolveResumeTarget(params, state, options = {}) {
7381
+ let requested = (params.id ?? params.runId)?.trim() ?? "", foregroundTarget, foregroundError, asyncTarget, asyncError;
7382
+ try {
7383
+ let target = resolveForegroundResumeTarget(params, state);
7384
+ target && (foregroundTarget = { kind: "revive", source: "foreground", ...target });
7385
+ } catch (error) {
7386
+ foregroundError = error;
7387
+ }
7388
+ try {
7389
+ asyncTarget = { source: "async", ...resolveAsyncResumeTarget(params, {}, { requireSessionFile: options.asyncRequireSessionFile }) };
7390
+ } catch (error) {
7391
+ asyncError = error;
7392
+ }
7393
+ if (foregroundTarget && asyncTarget) {
7394
+ let foregroundExact = resumeTargetExact(foregroundTarget, requested), asyncExact = resumeTargetExact(asyncTarget, requested);
7395
+ if (foregroundExact && !asyncExact)
7396
+ return foregroundTarget;
7397
+ if (asyncExact && !foregroundExact)
7398
+ return asyncTarget;
7399
+ throw new Error(`Resume id '${requested}' is ambiguous between foreground run '${foregroundTarget.runId}' and async run '${asyncTarget.runId}'. Provide a full run id.`);
7400
+ }
7401
+ if (foregroundTarget) {
7402
+ if (isExactResumeError(asyncError, "async", requested) || isResumeAmbiguity(asyncError) && !resumeTargetExact(foregroundTarget, requested))
7403
+ throw asyncError;
7404
+ return foregroundTarget;
7405
+ }
7406
+ if (asyncTarget) {
7407
+ if (isExactResumeError(foregroundError, "foreground", requested) || isResumeAmbiguity(foregroundError) && !resumeTargetExact(asyncTarget, requested))
7408
+ throw foregroundError;
7409
+ return asyncTarget;
7410
+ }
7411
+ throw foregroundError && !isAsyncRunNotFound(asyncError) || foregroundError ? foregroundError : asyncError || new Error("Run not found. Provide id or runId.");
7412
+ }
7413
+ async function resumeAsyncRun(input) {
7414
+ let followUp = (input.params.message ?? input.params.task ?? "").trim(), attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain : void 0;
7415
+ if (!followUp && !attachChain)
7416
+ return {
7417
+ content: [{ type: "text", text: "action='resume' requires message." }],
7418
+ isError: !0,
7419
+ details: { mode: "management", results: [] }
7420
+ };
7421
+ let acceptanceErrors = validateExecutionAcceptance(input.params);
7422
+ if (acceptanceErrors.length > 0)
7423
+ return {
7424
+ content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }],
7425
+ isError: !0,
7426
+ details: { mode: "management", results: [] }
7427
+ };
7428
+ input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
7429
+ let target, parentSessionFile = input.ctx.sessionManager.getSessionFile() ?? null;
7430
+ try {
7431
+ let requestedId = input.params.id ?? input.params.runId, resolved;
7432
+ try {
7433
+ resolved = requestedId ? resolveSubagentRunId(requestedId, { state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) }) : void 0;
7434
+ } catch (error) {
7435
+ let message = error instanceof Error ? error.message : "", asyncMatches = message.match(/async:/g)?.length ?? 0;
7436
+ if (!isResumeAmbiguity(error) || !message.includes("foreground:") || asyncMatches !== 1)
7437
+ throw error;
7438
+ }
7439
+ if (resolved?.kind === "nested") {
7440
+ if (attachChain)
7441
+ return {
7442
+ content: [{ type: "text", text: "Attaching a running subagent as a chain root is currently available for top-level async runs only." }],
7443
+ isError: !0,
7444
+ details: { mode: "management", results: [] }
7445
+ };
7446
+ if (resolved.match.run.state === "running" || resolved.match.run.state === "queued")
7447
+ return resumeLiveNestedRun({ target: resolved, message: followUp });
7448
+ let trustedSessionRoots = [
7449
+ ...input.deps.config.defaultSessionDir ? [path19.resolve(input.deps.expandTilde(input.deps.config.defaultSessionDir))] : [],
7450
+ ...parentSessionFile ? [input.deps.getSubagentSessionRoot(parentSessionFile)] : []
7451
+ ];
7452
+ target = resolveNestedResumeTarget(resolved, trustedSessionRoots);
7453
+ } else
7454
+ target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: !attachChain });
7455
+ } catch (error) {
7456
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
7457
+ }
7458
+ if (target.kind === "live" && !attachChain) {
7459
+ let interrupt = interruptLiveAsyncResumeTarget({
7460
+ target,
7461
+ state: input.deps.state,
7462
+ kill: input.deps.kill,
7463
+ resultsDir: RESULTS_DIR
7475
7464
  });
7465
+ return interrupt.ok ? await deliverSubagentIntercomMessageEvent(input.deps.pi.events, target.intercomTarget, `Follow-up for async run ${target.runId} (${target.agent}):
7466
+
7467
+ ${followUp}`, 500, { source: "async-resume", runId: target.runId, agent: target.agent, index: target.index }) ? {
7468
+ content: [{ type: "text", text: ["Interrupted live async child, then delivered follow-up.", `Run: ${target.runId}`, `Intercom target: ${target.intercomTarget}`].join(`
7469
+ `) }],
7470
+ details: { mode: "management", results: [] }
7471
+ } : {
7472
+ content: [{ type: "text", text: ["Async child appears live but its intercom target is not registered.", `Run: ${target.runId}`, `Intercom target: ${target.intercomTarget}`, "Wait for completion, then retry action='resume'."].join(`
7473
+ `) }],
7474
+ isError: !0,
7475
+ details: { mode: "management", results: [] }
7476
+ } : {
7477
+ content: [{ type: "text", text: interrupt.message }],
7478
+ isError: !0,
7479
+ details: { mode: "management", results: [] }
7480
+ };
7476
7481
  }
7477
- return null;
7478
- }
7479
- async function runChainPath(data, deps) {
7480
- let { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactsDir, artifactConfig, onUpdate, sessionRoot, controlConfig, contextPolicy } = data, onControlEvent = createForegroundControlNotifier(data, deps), childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : void 0, foregroundControl = deps.state.foregroundControls.get(runId), normalized = normalizeSkillInput(params.skill), chainSkills = normalized === !1 ? [] : normalized ?? [], chain = wrapChainTasksForFork(params.chain, contextPolicy), currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
7481
- if (params.chainDir && snapshotParentPermissionMode(ctx.sessionManager.getSessionId() ?? void 0) === "read-only")
7482
+ let { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth);
7483
+ if (blocked)
7482
7484
  return {
7483
- content: [{ type: "text", text: `Read-only mode cannot put a chain's files in ${params.chainDir}. Leave chainDir unset.` }],
7485
+ content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depth}, max=${maxDepth}). Complete the follow-up directly instead.` }],
7484
7486
  isError: !0,
7485
- details: { mode: "chain", results: [] }
7487
+ details: { mode: "management", results: [] }
7486
7488
  };
7487
- let chainResult = await executeChain({
7488
- chain,
7489
- task: params.task,
7490
- agents,
7491
- ctx,
7492
- modelScope: data.modelScope,
7493
- intercomEvents: deps.pi.events,
7494
- signal,
7495
- runId,
7496
- cwd: effectiveCwd,
7497
- sessionDirForIndex,
7498
- sessionFileForIndex,
7499
- sessionFileForTask,
7500
- thinkingOverrideForTask,
7501
- artifactsDir,
7502
- artifactConfig,
7503
- includeProgress: params.includeProgress,
7504
- clarify: params.clarify,
7505
- onUpdate,
7506
- onControlEvent,
7507
- controlConfig,
7508
- childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : void 0,
7509
- orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7510
- communicationEnabled: data.intercomBridge.communicationEnabled,
7511
- foregroundControl,
7512
- nestedRoute: foregroundControl?.nestedRoute,
7513
- chainSkills,
7514
- chainDir: params.chainDir ?? defaultChainRunsDir(artifactsDir),
7515
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
7516
- maxSubagentDepth: currentMaxSubagentDepth,
7517
- worktreeSetupHook: deps.config.worktreeSetupHook,
7518
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7519
- worktreeBaseDir: deps.config.worktreeBaseDir,
7520
- timeoutMs: data.timeoutMs,
7521
- deadlineAt: data.deadlineAt,
7522
- turnBudget: data.turnBudget,
7523
- onDetachedExit: (index, result2) => updateRememberedForegroundChild(deps.state, { runId, mode: "chain", cwd: effectiveCwd, sessionId: data.parentSessionId, index, result: result2, events: deps.pi.events }),
7524
- toolBudget: data.toolBudget,
7525
- configToolBudget: data.configToolBudget,
7526
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7527
- });
7528
- if (chainResult.requestedAsync) {
7489
+ input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
7490
+ let effectiveCwd = target.cwd ?? input.requestCwd, modelScope = void 0, sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId()), intercomBridge = resolveIntercomBridge({
7491
+ config: input.deps.config.intercomBridge,
7492
+ cwd: input.requestCwd,
7493
+ context: input.params.context,
7494
+ orchestratorTarget: sessionName
7495
+ }), recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : void 0;
7496
+ if (attachChain) {
7497
+ if (target.source !== "async")
7498
+ return {
7499
+ content: [{ type: "text", text: "Attaching a running subagent as a chain root is currently available for async runs only." }],
7500
+ isError: !0,
7501
+ details: { mode: "management", results: [] }
7502
+ };
7529
7503
  if (!isAsyncAvailable())
7530
7504
  return {
7531
- content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7505
+ content: [{ type: "text", text: "Async mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7532
7506
  isError: !0,
7533
7507
  details: { mode: "chain", results: [] }
7534
7508
  };
7535
- let id = randomUUID4(), asyncCtx = {
7536
- pi: deps.pi,
7537
- cwd: ctx.cwd,
7538
- currentSessionId: deps.state.currentSessionId,
7539
- parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7540
- currentModelProvider: ctx.model?.provider,
7541
- currentModel: ctx.model,
7542
- modelScope: data.modelScope
7543
- }, rawAsyncChain = chainResult.requestedAsync.chain, asyncChain = wrapChainTasksForFork(rawAsyncChain, contextPolicy), firstAgent = firstChainAgent(rawAsyncChain);
7544
- return executeAsyncChain(id, {
7545
- chain: asyncChain,
7546
- task: params.task,
7547
- goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : !1),
7548
- ctx: asyncCtx,
7549
- availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
7509
+ let runId2 = randomUUID7().slice(0, 8), artifactConfig2 = { ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== !1 }, availableModels2 = input.ctx.modelRegistry.getAvailable().map(toModelInfo), contextPolicy = resolveExplicitContextPolicy(input.params), workflowTask = (input.params.task ?? followUp) || void 0, goal = resolveAsyncEventGoal(workflowTask, attachChain), chain = wrapChainTasksForFork(attachChain, contextPolicy), normalized = normalizeSkillInput(input.params.skill), result3 = executeAsyncChain(runId2, {
7510
+ chain,
7511
+ task: workflowTask,
7512
+ goal,
7513
+ attachRoot: {
7514
+ runId: target.runId,
7515
+ asyncDir: target.asyncDir ?? path19.join(ASYNC_DIR, target.runId),
7516
+ resultPath: resolveAsyncRootResultPath(RESULTS_DIR, target.runId),
7517
+ index: target.index,
7518
+ agent: target.agent,
7519
+ label: `Attached ${target.runId}`
7520
+ },
7521
+ ctx: {
7522
+ pi: input.deps.pi,
7523
+ cwd: input.requestCwd,
7524
+ currentSessionId: input.deps.state.currentSessionId,
7525
+ parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
7526
+ currentModelProvider: input.ctx.model?.provider,
7527
+ currentModel: input.ctx.model,
7528
+ modelScope
7529
+ },
7530
+ availableModels: availableModels2,
7550
7531
  cwd: effectiveCwd,
7551
- maxOutput: params.maxOutput,
7552
- artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7553
- artifactConfig,
7554
- sessionRoot,
7555
- chainSkills: chainResult.requestedAsync.chainSkills,
7556
- sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
7557
- thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
7558
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
7559
- maxSubagentDepth: currentMaxSubagentDepth,
7560
- waitToolEnabled: deps.waitToolEnabled,
7561
- worktreeSetupHook: deps.config.worktreeSetupHook,
7562
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7563
- worktreeBaseDir: deps.config.worktreeBaseDir,
7564
- controlConfig,
7565
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7566
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : void 0,
7567
- communicationEnabled: data.intercomBridge.communicationEnabled,
7568
- nestedRoute: data.nestedRoute,
7569
- timeoutMs: data.timeoutMs,
7570
- turnBudget: data.turnBudget,
7571
- toolBudget: data.toolBudget,
7572
- configToolBudget: data.configToolBudget,
7573
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7532
+ maxOutput: input.params.maxOutput,
7533
+ artifactsDir: getArtifactsDir(parentSessionFile),
7534
+ artifactConfig: artifactConfig2,
7535
+ sessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),
7536
+ chainSkills: normalized === !1 ? [] : normalized ?? [],
7537
+ dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
7538
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
7539
+ waitToolEnabled: input.deps.waitToolEnabled,
7540
+ worktreeSetupHook: input.deps.config.worktreeSetupHook,
7541
+ worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
7542
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
7543
+ controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
7544
+ communicationEnabled: intercomBridge.communicationEnabled,
7545
+ controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : void 0,
7546
+ childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId2, agent, index) : void 0,
7547
+ globalConcurrencyLimit: input.deps.config.globalConcurrencyLimit
7574
7548
  });
7549
+ if (result3.isError)
7550
+ return result3;
7551
+ let attachedId = result3.details.asyncId ?? runId2, lines2 = [
7552
+ `Attached async subagent ${target.runId} as the first step of a new chain.`,
7553
+ `Chain run: ${attachedId}`,
7554
+ `Root: ${target.agent} (step ${target.index + 1})`,
7555
+ result3.details.asyncDir ? `Async dir: ${result3.details.asyncDir}` : void 0,
7556
+ `Status if needed: subagent({ action: "status", id: "${attachedId}" })`
7557
+ ].filter((line) => !!line);
7558
+ return { content: [{ type: "text", text: formatAsyncStartedMessage(lines2.join(`
7559
+ `)) }], details: result3.details };
7575
7560
  }
7576
- let rawChainDetails = chainResult.details ? { ...chainResult.details, runId } : void 0;
7577
- foregroundControl && rawChainDetails && (updateForegroundNestedProjection(foregroundControl), attachRootChildrenToSteps(runId, rawChainDetails.results, foregroundControl.nestedChildren), rawChainDetails.totalCost = sumResultsCost(rawChainDetails.results));
7578
- let chainDetails = rawChainDetails ? compactForegroundDetails(rawChainDetails) : void 0;
7579
- chainDetails && rememberForegroundRun(deps.state, { runId, mode: "chain", cwd: effectiveCwd, sessionId: data.parentSessionId, results: chainDetails.results });
7580
- let intercomReceipt = !chainResult.isError && chainDetails && !chainDetails.results.some((result2) => result2.interrupted || result2.detached) ? await maybeBuildForegroundIntercomReceipt({
7581
- pi: deps.pi,
7582
- intercomBridge: data.intercomBridge,
7583
- runId,
7584
- mode: "chain",
7585
- details: chainDetails,
7586
- ...foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}
7587
- }) : null;
7588
- return intercomReceipt ? {
7589
- ...chainResult,
7590
- content: [{ type: "text", text: intercomReceipt.text }],
7591
- details: intercomReceipt.details
7592
- } : chainDetails ? { ...chainResult, details: chainDetails } : chainResult;
7593
- }
7594
- function buildParallelModeError(message) {
7595
- return {
7596
- content: [{ type: "text", text: message }],
7597
- isError: !0,
7598
- details: { mode: "parallel", results: [] }
7599
- };
7600
- }
7601
- function createParallelWorktreeSetup(enabled, cwd, runId, tasks, setupHook, setupHookTimeoutMs, baseDir) {
7602
- if (!enabled)
7603
- return {};
7561
+ let runId = randomUUID7().slice(0, 8), artifactConfig = recoveryDescriptor?.artifactConfig ?? { ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== !1 }, artifactsDir = getArtifactsDir(parentSessionFile), availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo), restoredAcceptance;
7562
+ if (recoveryDescriptor?.acceptance !== void 0 && input.params.acceptance === void 0)
7563
+ try {
7564
+ restoredAcceptance = restorePersistedAcceptance(recoveryDescriptor.acceptance, "recoveryDescriptor.acceptance");
7565
+ } catch (error) {
7566
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
7567
+ }
7568
+ let resumeTurnBudget = resolveTurnBudgetConfig(input.params.turnBudget);
7569
+ if (resumeTurnBudget.error)
7570
+ return { content: [{ type: "text", text: resumeTurnBudget.error }], isError: !0, details: { mode: "management", results: [] } };
7571
+ let resumeToolBudget = resolveToolBudget(input.params.toolBudget, "toolBudget");
7572
+ if (resumeToolBudget.error)
7573
+ return { content: [{ type: "text", text: resumeToolBudget.error }], isError: !0, details: { mode: "management", results: [] } };
7574
+ let recordedLimits = {};
7575
+ if (recoveryDescriptor && (!resumeTurnBudget.turnBudget || !resumeToolBudget.toolBudget))
7576
+ try {
7577
+ recordedLimits = remainingSteeringRecoveryLimits({ initialTurnBudget: recoveryDescriptor.initialTurnBudget, initialToolBudget: recoveryDescriptor.initialToolBudget }, (target.source === "async" && target.asyncDir ? readStatus(target.asyncDir) : null) ?? {});
7578
+ } catch (error) {
7579
+ return { content: [{ type: "text", text: `Cannot revive ${target.runId}: ${error instanceof Error ? error.message : String(error)}` }], isError: !0, details: { mode: "management", results: [] } };
7580
+ }
7581
+ let reviveTurnBudget = resumeTurnBudget.turnBudget ?? recordedLimits.turnBudget, reviveToolBudget = resumeToolBudget.toolBudget ?? recordedLimits.toolBudget, recoverySpec;
7604
7582
  try {
7605
- return {
7606
- setup: createWorktrees(cwd, runId, tasks.length, {
7607
- agents: tasks.map((task) => task.agent),
7608
- setupHook: setupHook ? { hookPath: setupHook, timeoutMs: setupHookTimeoutMs } : void 0,
7609
- baseDir
7610
- })
7611
- };
7583
+ let recoverySelection = recoveryDescriptor?.modelSelection ?? target.modelSelection, recoveryIsExplicitModel = recoverySelection?.kind === "model";
7584
+ recoverySpec = normalizeChildSpec({
7585
+ task: buildRevivedAsyncTask(target, followUp),
7586
+ description: recoveryDescriptor?.description ?? target.description ?? target.agent,
7587
+ permissions: recoveryDescriptor?.permissions ?? target.permissions ?? "read-only",
7588
+ model: recoveryIsExplicitModel ? recoverySelection.model ?? recoveryDescriptor?.model ?? target.model : void 0,
7589
+ tier: recoveryIsExplicitModel ? void 0 : input.params.tier ?? recoverySelection?.tier ?? recoveryDescriptor?.tier,
7590
+ thinking: recoveryIsExplicitModel ? recoveryDescriptor?.thinking ?? target.thinking : void 0,
7591
+ modelSelection: recoverySelection,
7592
+ skill: recoveryDescriptor?.skills,
7593
+ cwd: effectiveCwd,
7594
+ output: recoveryDescriptor?.outputPath,
7595
+ outputMode: recoveryDescriptor?.outputMode,
7596
+ acceptance: input.params.acceptance,
7597
+ toolBudget: recoveryDescriptor?.initialToolBudget
7598
+ }, {
7599
+ parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? void 0),
7600
+ runId,
7601
+ index: 0,
7602
+ childId: recoveryDescriptor?.childId ?? target.childId ?? `${runId}-0`,
7603
+ resolvedModelIsRuntime: !recoveryIsExplicitModel && !!(recoveryDescriptor?.model ?? target.model)
7604
+ });
7612
7605
  } catch (error) {
7613
- let message = error instanceof Error ? error.message : String(error);
7614
- return { errorResult: buildParallelModeError(message) };
7615
- }
7616
- }
7617
- function buildParallelWorktreeTaskCwdError(tasks, sharedCwd) {
7618
- let conflict = findWorktreeTaskCwdConflict(tasks, sharedCwd);
7619
- if (conflict)
7620
- return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
7621
- }
7622
- function defaultChainRunsDir(artifactsDir) {
7623
- return ensureArtifactsDir(artifactsDir), path16.join(artifactsDir, "chain-runs");
7624
- }
7625
- function resolveSingleRunOutputBaseDir(deps, artifactsDir, runId) {
7626
- return deps.config.singleRunOutputBaseDir ? path16.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir)) : path16.join(artifactsDir, "outputs", runId);
7627
- }
7628
- function buildChainWorktreeTaskCwdError(chain, sharedCwd) {
7629
- for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
7630
- let step = chain[stepIndex];
7631
- if (!isParallelStep(step) || !step.worktree)
7632
- continue;
7633
- let stepCwd = resolveChildCwd(sharedCwd, step.cwd), conflict = findWorktreeTaskCwdConflict(step.parallel, stepCwd);
7634
- if (!conflict)
7635
- continue;
7636
- let detail = formatWorktreeTaskCwdConflict(conflict, stepCwd);
7637
- return `parallel chain step ${stepIndex + 1}: ${detail}`;
7606
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
7638
7607
  }
7608
+ let result2 = executeAsyncSingle(runId, {
7609
+ spec: recoverySpec,
7610
+ completionTask: followUp,
7611
+ goal: followUp,
7612
+ ctx: {
7613
+ pi: input.deps.pi,
7614
+ cwd: input.requestCwd,
7615
+ currentSessionId: input.deps.state.currentSessionId,
7616
+ parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
7617
+ currentModelProvider: input.ctx.model?.provider,
7618
+ currentModel: input.ctx.model,
7619
+ modelScope
7620
+ },
7621
+ cwd: effectiveCwd,
7622
+ maxOutput: input.params.maxOutput ?? recoveryDescriptor?.maxOutput,
7623
+ artifactsDir,
7624
+ artifactConfig,
7625
+ sessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),
7626
+ ...recoveryDescriptor?.sessionDir ? { sessionDir: recoveryDescriptor.sessionDir } : {},
7627
+ sessionFile: target.sessionFile,
7628
+ revivalLease: {
7629
+ // Non-null: without attachChain, resolveResumeTarget required a session file.
7630
+ sessionFile: target.sessionFile,
7631
+ runId,
7632
+ sourceRunId: target.runId,
7633
+ ...input.deps.state.currentSessionId ? { parentSessionId: input.deps.state.currentSessionId } : {}
7634
+ },
7635
+ modelOverride: recoveryDescriptor?.model ?? target.model,
7636
+ thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
7637
+ outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
7638
+ maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
7639
+ waitToolEnabled: input.deps.waitToolEnabled,
7640
+ worktreeSetupHook: input.deps.config.worktreeSetupHook,
7641
+ worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
7642
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
7643
+ controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
7644
+ communicationEnabled: intercomBridge.communicationEnabled,
7645
+ controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : void 0,
7646
+ childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : void 0,
7647
+ availableModels,
7648
+ output: recoveryDescriptor?.outputPath,
7649
+ outputMode: recoveryDescriptor?.outputMode,
7650
+ ...recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {},
7651
+ ...restoredAcceptance ? { restoredAcceptance } : {},
7652
+ ...input.params.timeoutMs !== void 0 ? { timeoutMs: input.params.timeoutMs } : {},
7653
+ ...input.absoluteDeadlineAt !== void 0 ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {},
7654
+ ...reviveTurnBudget ? { turnBudget: reviveTurnBudget } : {},
7655
+ ...reviveToolBudget ? { toolBudget: reviveToolBudget } : {}
7656
+ });
7657
+ if (result2.isError)
7658
+ return result2;
7659
+ let revivedId = result2.details.asyncId ?? runId, revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : void 0, lines = [
7660
+ `Revived ${target.source} subagent from ${target.runId}.`,
7661
+ `Revived run: ${revivedId}`,
7662
+ `Agent: ${target.agent}`,
7663
+ `Session: ${target.sessionFile}`,
7664
+ result2.details.asyncDir ? `Async dir: ${result2.details.asyncDir}` : void 0,
7665
+ revivedTarget ? `Intercom target: ${revivedTarget} (if registered)` : void 0,
7666
+ `Status if needed: subagent({ action: "status", id: "${revivedId}" })`
7667
+ ].filter((line) => !!line);
7668
+ return { content: [{ type: "text", text: formatAsyncStartedMessage(lines.join(`
7669
+ `)) }], details: result2.details };
7639
7670
  }
7640
- function resolveParallelTaskCwd(task, paramsCwd, worktreeSetup, index) {
7641
- return worktreeSetup ? worktreeSetup.worktrees[index].agentCwd : resolveChildCwd(paramsCwd, task.cwd);
7671
+ function formatFailedSingleRunOutput(result2, displayOutput) {
7672
+ let error = result2.error || "Failed", output = displayOutput.trim(), lines = [error];
7673
+ return output && output !== error.trim() && lines.push("", "Output:", output), result2.artifactPaths?.outputPath && lines.push("", `Output artifact: ${result2.artifactPaths.outputPath}`), lines.join(`
7674
+ `);
7642
7675
  }
7643
- function buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks) {
7644
- if (!worktreeSetup)
7645
- return "";
7646
- let diffsDir = path16.join(artifactsDir, "worktree-diffs"), diffs = diffWorktrees(worktreeSetup, tasks.map((task) => task.agent), diffsDir);
7647
- return formatWorktreeDiffSummary(diffs);
7676
+ function firstChainAgent(chain) {
7677
+ let first = chain[0];
7678
+ if (first)
7679
+ return isParallelStep(first) ? first.parallel[0]?.agent : isDynamicParallelStep(first) ? first.parallel.agent : first.agent;
7648
7680
  }
7649
- function findDuplicateParallelOutputPath(input) {
7650
- let seen = /* @__PURE__ */ new Map();
7651
- for (let index = 0; index < input.tasks.length; index++) {
7652
- let behavior = input.behaviors[index];
7653
- if (!behavior?.output)
7654
- continue;
7655
- let task = input.tasks[index], taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index), outputPath = resolveSingleOutputPath(behavior.output, input.ctxCwd, taskCwd, input.outputBaseDir);
7656
- if (!outputPath)
7657
- continue;
7658
- let previous = seen.get(outputPath);
7659
- if (previous)
7660
- return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
7661
- seen.set(outputPath, { index, agent: task.agent });
7662
- }
7681
+ function firstRawChainTask(chain) {
7682
+ let first = chain[0];
7683
+ if (first)
7684
+ return isParallelStep(first) ? first.parallel[0]?.task : isDynamicParallelStep(first) ? first.parallel.task : first.task;
7663
7685
  }
7664
- async function runForegroundParallelTasks(input) {
7665
- for (let i = 0; i < input.tasks.length; i++)
7666
- input.sessionFileForTask(input.tasks[i].agent, i, input.modelOverrides[i]);
7667
- return mapConcurrent(input.tasks, input.concurrencyLimit, async (task, index) => {
7668
- let behavior = input.behaviors[index], effectiveSkills = behavior?.skills, taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index), readInstructions = behavior ? buildChainInstructions({ ...behavior, output: !1, progress: !1 }, taskCwd, !1) : { prefix: "", suffix: "" }, progressInstructions = behavior ? buildChainInstructions({ ...behavior, output: !1, reads: !1 }, input.progressDir, index === input.firstProgressIndex) : { prefix: "", suffix: "" }, outputPath = resolveSingleOutputPath(behavior?.output, input.ctx.cwd, taskCwd, input.outputBaseDir), agentConfig = input.agents.find((agent) => agent.name === task.agent), taskText = injectSingleOutputInstruction(`${readInstructions.prefix}${input.taskTexts[index]}${progressInstructions.suffix}`, outputPath, agentConfig), interruptController = new AbortController();
7669
- input.foregroundControl && (input.foregroundControl.currentAgent = task.description || task.agent, input.foregroundControl.currentChildId = task.agent, input.foregroundControl.currentIndex = index, input.foregroundControl.currentActivityState = void 0, input.foregroundControl.updatedAt = Date.now(), input.foregroundControl.interrupt = () => interruptController.signal.aborted ? !1 : (interruptController.abort(), input.foregroundControl.currentActivityState = void 0, input.foregroundControl.updatedAt = Date.now(), !0));
7670
- let modelSelection = input.modelSelections[index] ?? captureModelSelection({ model: task.model, tier: task.tier });
7671
- return runSync(input.ctx.cwd, normalizeChildSpec({
7672
- task: taskText,
7673
- description: task.description,
7674
- permissions: task.permissions,
7675
- model: task.model,
7676
- tier: task.tier,
7677
- thinking: task.thinking,
7678
- modelSelection,
7679
- skill: task.skill,
7680
- cwd: taskCwd,
7681
- output: task.output,
7682
- outputMode: task.outputMode,
7683
- acceptance: task.acceptance,
7684
- toolBudget: task.toolBudget
7685
- }, { parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? void 0), runId: input.runId, index }), {
7686
- parentSessionId: input.ctx.sessionManager.getSessionId() ?? void 0,
7687
- cwd: taskCwd,
7688
- signal: input.signal,
7689
- interruptSignal: interruptController.signal,
7690
- allowIntercomDetach: agentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === !0,
7691
- intercomEvents: input.intercomEvents,
7692
- runId: input.runId,
7693
- index,
7694
- sessionDir: input.sessionDirForIndex(index),
7695
- sessionFile: input.sessionFileForTask(task.agent, index, input.modelOverrides[index]),
7696
- artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : void 0,
7697
- artifactConfig: input.artifactConfig,
7698
- maxOutput: input.maxOutput,
7699
- outputPath,
7700
- outputMode: behavior?.outputMode,
7701
- maxSubagentDepth: input.maxSubagentDepths[index],
7702
- waitToolEnabled: input.waitToolEnabled,
7703
- controlConfig: input.controlConfig,
7704
- onControlEvent: input.onControlEvent,
7705
- onDetachedExit: (result2) => updateRememberedForegroundChild(input.state, { runId: input.runId, mode: "parallel", cwd: taskCwd, sessionId: input.parentSessionId, index, result: result2, events: input.intercomEvents }),
7706
- intercomSessionName: input.childIntercomTarget?.(task.agent, index),
7707
- orchestratorIntercomTarget: input.orchestratorIntercomTarget,
7708
- communicationEnabled: input.communicationEnabled,
7709
- nestedRoute: input.foregroundControl?.nestedRoute,
7710
- modelOverride: input.modelOverrides[index],
7711
- thinkingOverride: input.thinkingOverrideForTask(task.agent, index, input.modelOverrides[index]),
7712
- availableModels: input.availableModels,
7713
- preferredModelProvider: input.ctx.model?.provider,
7714
- modelScope: input.modelScope,
7715
- skills: effectiveSkills === !1 ? [] : effectiveSkills,
7716
- acceptance: task.acceptance,
7717
- acceptanceContext: { mode: "parallel" },
7718
- timeoutMs: input.timeoutMs,
7719
- deadlineAt: input.deadlineAt,
7720
- turnBudget: input.turnBudget,
7721
- toolBudget: input.toolBudgets[index],
7722
- onUpdate: input.onUpdate ? (progressUpdate) => {
7723
- let stepResults = progressUpdate.details?.results || [], stepProgress = progressUpdate.details?.progress || [];
7724
- if (input.foregroundControl && stepProgress.length > 0) {
7725
- let current = stepProgress[0];
7726
- input.foregroundControl.currentAgent = task.description || task.agent, input.foregroundControl.currentChildId = task.agent, input.foregroundControl.currentIndex = index, input.foregroundControl.currentActivityState = current?.activityState, input.foregroundControl.lastActivityAt = current?.lastActivityAt, input.foregroundControl.currentTool = current?.currentTool, input.foregroundControl.currentToolStartedAt = current?.currentToolStartedAt, input.foregroundControl.currentPath = current?.currentPath, input.foregroundControl.turnCount = current?.turnCount, input.foregroundControl.tokens = current?.tokens, input.foregroundControl.toolCount = current?.toolCount, input.foregroundControl.updatedAt = Date.now();
7727
- }
7728
- stepResults.length > 0 && (input.liveResults[index] = stepResults[0]), stepProgress.length > 0 && (input.liveProgress[index] = stepProgress[0]);
7729
- let mergedResults = input.liveResults.filter((result2) => result2 !== void 0), mergedProgress = input.liveProgress.filter((progress) => progress !== void 0);
7730
- input.onUpdate?.({
7731
- content: progressUpdate.content,
7732
- details: {
7733
- mode: "parallel",
7734
- results: mergedResults,
7735
- progress: mergedProgress,
7736
- controlEvents: progressUpdate.details?.controlEvents,
7737
- totalSteps: input.tasks.length
7738
- }
7739
- });
7740
- } : void 0
7741
- }).finally(() => {
7742
- input.foregroundControl?.currentIndex === index && (input.foregroundControl.interrupt = void 0, input.foregroundControl.updatedAt = Date.now());
7743
- });
7744
- }, input.globalSemaphore, {
7745
- signal: input.signal,
7746
- onAbort: (task) => ({
7747
- agent: task.agent,
7748
- task: task.task ?? "",
7749
- exitCode: 1,
7750
- messages: [],
7751
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
7752
- error: "Subagent launch cancelled."
7753
- })
7754
- });
7686
+ function resolveAsyncEventGoal(workflowTask, rawChain, unwrapForkFallback = !1) {
7687
+ if (workflowTask?.trim())
7688
+ return workflowTask;
7689
+ let fallback = firstRawChainTask(rawChain) || "";
7690
+ if (!unwrapForkFallback)
7691
+ return fallback;
7692
+ let forkPrefix = `${DEFAULT_FORK_PREAMBLE}
7693
+
7694
+ Task:
7695
+ `;
7696
+ return fallback.startsWith(forkPrefix) ? fallback.slice(forkPrefix.length) : fallback;
7755
7697
  }
7756
- async function runParallelPath(data, deps) {
7757
- let { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, backgroundRequestedWhileClarifying, onUpdate, sessionRoot, controlConfig, contextPolicy } = data, onControlEvent = createForegroundControlNotifier(data, deps), childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : void 0, allProgress = [], allArtifactPaths = [], tasks = params.tasks, maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks), parallelConcurrency = resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency);
7758
- if (tasks.length > maxParallelTasks)
7759
- return {
7760
- content: [{ type: "text", text: `Max ${maxParallelTasks} tasks` }],
7761
- isError: !0,
7762
- details: { mode: "parallel", results: [] }
7763
- };
7764
- let agentConfigs = [];
7765
- for (let t of tasks) {
7766
- let config = agents.find((a) => a.name === t.agent);
7767
- if (!config)
7698
+ function runAsyncPath(data, deps) {
7699
+ let { params, effectiveCwd, agents, ctx, sessionRoot, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, effectiveAsync, controlConfig, intercomBridge, nestedRoute, contextPolicy } = data, hasChain = (params.chain?.length ?? 0) > 0, hasTasks = (params.tasks?.length ?? 0) > 0, hasSingle = !hasChain && !hasTasks && !!params.agent;
7700
+ if (!effectiveAsync)
7701
+ return null;
7702
+ if (hasChain && params.chain) {
7703
+ let chainWorktreeTaskCwdError = buildChainWorktreeTaskCwdError(params.chain, effectiveCwd);
7704
+ if (chainWorktreeTaskCwdError)
7768
7705
  return {
7769
- content: [{ type: "text", text: `Unknown agent: ${t.agent}` }],
7706
+ content: [{ type: "text", text: chainWorktreeTaskCwdError }],
7770
7707
  isError: !0,
7771
- details: { mode: "parallel", results: [] }
7708
+ details: { mode: "chain", results: [] }
7772
7709
  };
7773
- agentConfigs.push(config);
7774
- }
7775
- let currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth), maxSubagentDepths = agentConfigs.map((config) => resolveChildMaxSubagentDepth(currentMaxSubagentDepth, config.maxSubagentDepth)), toolBudgets = [];
7776
- for (let index = 0; index < tasks.length; index++) {
7777
- let resolved = resolveEffectiveToolBudget({ stepBudget: tasks[index]?.toolBudget, runBudget: data.toolBudget, agentBudget: agentConfigs[index]?.toolBudget, configBudget: data.configToolBudget });
7778
- if (resolved.error)
7779
- return buildParallelModeError(resolved.error);
7780
- toolBudgets.push(resolved.toolBudget);
7781
- }
7782
- if (params.worktree) {
7783
- let worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(tasks, effectiveCwd);
7784
- if (worktreeTaskCwdError)
7785
- return buildParallelModeError(worktreeTaskCwdError);
7786
7710
  }
7787
- let currentProvider = ctx.model?.provider, availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo), taskTexts = tasks.map((t) => t.task), skillOverrides = tasks.map((t) => normalizeSkillInput(t.skill)), behaviorOverrides = tasks.map((task, index) => ({
7788
- ...task.output !== void 0 && task.output !== !0 ? { output: task.output } : {},
7789
- ...task.outputMode !== void 0 ? { outputMode: task.outputMode } : {},
7790
- ...task.reads !== void 0 && task.reads !== !0 ? { reads: task.reads } : {},
7791
- ...task.progress !== void 0 ? { progress: task.progress } : {},
7792
- ...skillOverrides[index] !== void 0 ? { skills: skillOverrides[index] } : {}
7793
- })), modelSelections = tasks.map((task) => captureModelSelection({ model: task.model, tier: task.tier })), modelOverrides = tasks.map((task, index) => resolveExecutableChildModel({
7794
- modelSelection: modelSelections[index],
7795
- model: task.model,
7796
- tier: task.tier,
7797
- thinking: task.thinking,
7798
- availableModels,
7799
- preferredProvider: currentProvider
7800
- }));
7801
- if (params.clarify === !0 && ctx.hasUI) {
7802
- let behaviors2 = agentConfigs.map((_c, i) => resolveStepBehavior(behaviorOverrides[i])), availableSkills = discoverAvailableSkills(effectiveCwd), result2 = await ctx.ui.custom((tui, theme, _kb, done) => new ChainClarifyComponent(tui, theme, agentConfigs, taskTexts, "", void 0, behaviors2, availableModels, currentProvider, availableSkills, done, "parallel"), { overlay: !0, overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" } });
7803
- if (!result2 || !result2.confirmed)
7804
- return { content: [{ type: "text", text: "Cancelled" }], details: { mode: "parallel", results: [] } };
7805
- taskTexts = result2.templates;
7806
- for (let i = 0; i < result2.behaviorOverrides.length; i++) {
7807
- let override = result2.behaviorOverrides[i];
7808
- override?.output !== void 0 && (behaviorOverrides[i].output = override.output), override?.reads !== void 0 && (behaviorOverrides[i].reads = override.reads), override?.progress !== void 0 && (behaviorOverrides[i].progress = override.progress), override?.skills !== void 0 && (skillOverrides[i] = override.skills, behaviorOverrides[i].skills = override.skills);
7809
- }
7810
- if (result2.runInBackground) {
7811
- if (!isAsyncAvailable())
7812
- return {
7813
- content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7814
- isError: !0,
7815
- details: { mode: "parallel", results: [] }
7816
- };
7817
- let id = randomUUID4(), asyncCtx = {
7818
- pi: deps.pi,
7819
- cwd: ctx.cwd,
7820
- currentSessionId: deps.state.currentSessionId,
7821
- parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7822
- currentModelProvider: ctx.model?.provider,
7823
- currentModel: ctx.model,
7824
- modelScope: data.modelScope
7825
- }, parallelTasks = tasks.map((t, i) => {
7826
- let taskText = shouldForkAgent(contextPolicy, t.agent) ? wrapForkTask(taskTexts[i]) : taskTexts[i], progress = taskDisallowsFileUpdates(taskText) ? !1 : behaviorOverrides[i]?.progress;
7827
- return {
7828
- agent: t.agent,
7829
- task: taskText,
7830
- description: t.description,
7831
- permissions: t.permissions,
7832
- cwd: t.cwd,
7833
- model: t.model,
7834
- tier: t.tier,
7835
- thinking: t.thinking,
7836
- ...skillOverrides[i] !== void 0 ? { skill: skillOverrides[i] } : {},
7837
- ...behaviorOverrides[i]?.output !== void 0 ? { output: behaviorOverrides[i].output } : {},
7838
- ...behaviorOverrides[i]?.outputMode !== void 0 ? { outputMode: behaviorOverrides[i].outputMode } : {},
7839
- ...behaviorOverrides[i]?.reads !== void 0 ? { reads: behaviorOverrides[i].reads } : {},
7840
- ...progress !== void 0 ? { progress } : {},
7841
- ...t.toolBudget !== void 0 ? { toolBudget: t.toolBudget } : {},
7842
- ...t.acceptance !== void 0 ? { acceptance: t.acceptance } : {}
7843
- };
7844
- });
7845
- return executeAsyncChain(id, {
7846
- chain: [{ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree }],
7847
- resultMode: "parallel",
7848
- goal: taskTexts[0] ?? "",
7849
- communicationEnabled: data.intercomBridge.communicationEnabled,
7850
- ctx: asyncCtx,
7851
- availableModels,
7852
- cwd: effectiveCwd,
7853
- maxOutput: params.maxOutput,
7854
- artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7855
- artifactConfig,
7856
- sessionRoot,
7857
- chainSkills: [],
7858
- sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
7859
- thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
7860
- maxSubagentDepth: currentMaxSubagentDepth,
7861
- waitToolEnabled: deps.waitToolEnabled,
7862
- worktreeSetupHook: deps.config.worktreeSetupHook,
7863
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7864
- worktreeBaseDir: deps.config.worktreeBaseDir,
7865
- controlConfig,
7866
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7867
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : void 0,
7868
- timeoutMs: data.timeoutMs,
7869
- turnBudget: data.turnBudget,
7870
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7871
- });
7711
+ if (hasTasks && params.tasks) {
7712
+ let maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);
7713
+ if (params.tasks.length > maxParallelTasks)
7714
+ return buildParallelModeError(`Max ${maxParallelTasks} tasks`);
7715
+ if (params.worktree) {
7716
+ let worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(params.tasks, effectiveCwd);
7717
+ if (worktreeTaskCwdError)
7718
+ return buildParallelModeError(worktreeTaskCwdError);
7872
7719
  }
7873
7720
  }
7874
- let behaviors = agentConfigs.map((_config, index) => suppressProgressForReadOnlyTask(resolveStepBehavior(behaviorOverrides[index]), taskTexts[index])), firstProgressIndex = behaviors.findIndex((behavior) => behavior.progress), liveResults = new Array(tasks.length).fill(void 0), liveProgress = new Array(tasks.length).fill(void 0), foregroundControl = deps.state.foregroundControls.get(runId), { setup: worktreeSetup, errorResult } = createParallelWorktreeSetup(params.worktree, effectiveCwd, runId, tasks, deps.config.worktreeSetupHook, deps.config.worktreeSetupHookTimeoutMs, deps.config.worktreeBaseDir);
7875
- if (errorResult)
7876
- return errorResult;
7877
- try {
7878
- let outputBaseDir = path16.join(artifactsDir, "outputs", runId), duplicateOutputError = findDuplicateParallelOutputPath({
7879
- tasks,
7880
- behaviors,
7881
- paramsCwd: effectiveCwd,
7882
- ctxCwd: ctx.cwd,
7883
- outputBaseDir,
7884
- worktreeSetup
7885
- });
7886
- if (duplicateOutputError)
7887
- return buildParallelModeError(duplicateOutputError);
7888
- for (let index = 0; index < tasks.length; index++) {
7889
- let taskCwd = resolveParallelTaskCwd(tasks[index], effectiveCwd, worktreeSetup, index), outputPath = resolveSingleOutputPath(behaviors[index]?.output, ctx.cwd, taskCwd, outputBaseDir), validationError = validateFileOnlyOutputMode(behaviors[index]?.outputMode, outputPath, `Parallel task ${index + 1} (${tasks[index].agent})`) ?? outputTargetError(outputPath, ctx.cwd) ?? readOnlyOutputError(outputPath, outputBaseDir, ctx.sessionManager.getSessionId() ?? void 0);
7890
- if (validationError)
7891
- return buildParallelModeError(validationError);
7892
- }
7893
- let parallelProgressPrecreated = firstProgressIndex !== -1, parallelProgressDir = path16.join(artifactsDir, "progress", runId);
7894
- parallelProgressPrecreated && writeInitialProgressFile(parallelProgressDir);
7895
- for (let i = 0; i < taskTexts.length; i++)
7896
- shouldForkAgent(contextPolicy, tasks[i].agent) && (taskTexts[i] = wrapForkTask(taskTexts[i]));
7897
- let deadlineAt = data.deadlineAt ?? (data.timeoutMs !== void 0 ? Date.now() + data.timeoutMs : void 0), results = await runForegroundParallelTasks({
7898
- tasks,
7899
- taskTexts,
7900
- agents,
7901
- ctx,
7902
- state: deps.state,
7903
- intercomEvents: deps.pi.events,
7904
- parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7905
- signal,
7906
- runId,
7907
- sessionDirForIndex,
7908
- sessionFileForIndex,
7909
- sessionFileForTask,
7910
- thinkingOverrideForTask,
7911
- artifactConfig,
7912
- artifactsDir,
7913
- outputBaseDir,
7914
- maxOutput: params.maxOutput,
7915
- paramsCwd: effectiveCwd,
7916
- progressDir: parallelProgressDir,
7721
+ if (!isAsyncAvailable())
7722
+ return {
7723
+ content: [{ type: "text", text: "Async mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7724
+ isError: !0,
7725
+ details: { mode: "single", results: [] }
7726
+ };
7727
+ let id = randomUUID7(), asyncCtx = {
7728
+ pi: deps.pi,
7729
+ cwd: ctx.cwd,
7730
+ currentSessionId: deps.state.currentSessionId,
7731
+ parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7732
+ currentModelProvider: ctx.model?.provider,
7733
+ currentModel: ctx.model,
7734
+ modelScope: data.modelScope
7735
+ }, availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo), currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth), currentProvider = ctx.model?.provider, controlIntercomTarget = intercomBridge.active ? intercomBridge.orchestratorTarget : void 0, childIntercomTarget = intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : void 0;
7736
+ if (hasTasks && params.tasks) {
7737
+ let skillOverrides = params.tasks.map((task) => normalizeSkillInput(task.skill)), parallelTasks = params.tasks.map((task, index) => ({
7738
+ agent: task.agent,
7739
+ task: shouldForkAgent(contextPolicy, task.agent) ? wrapForkTask(task.task) : task.task,
7740
+ description: task.description,
7741
+ permissions: task.permissions,
7742
+ cwd: task.cwd,
7743
+ model: task.model,
7744
+ tier: task.tier,
7745
+ thinking: task.thinking,
7746
+ ...skillOverrides[index] !== void 0 ? { skill: skillOverrides[index] } : {},
7747
+ ...task.output !== void 0 && task.output !== !0 ? { output: task.output } : {},
7748
+ ...task.outputMode !== void 0 ? { outputMode: task.outputMode } : {},
7749
+ ...task.reads !== void 0 && task.reads !== !0 ? { reads: task.reads } : {},
7750
+ ...task.progress !== void 0 ? { progress: task.progress } : {},
7751
+ ...task.toolBudget !== void 0 ? { toolBudget: task.toolBudget } : {},
7752
+ ...task.acceptance !== void 0 ? { acceptance: task.acceptance } : {}
7753
+ }));
7754
+ return executeAsyncChain(id, {
7755
+ chain: [{
7756
+ parallel: parallelTasks,
7757
+ concurrency: resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency),
7758
+ worktree: params.worktree
7759
+ }],
7760
+ resultMode: "parallel",
7761
+ communicationEnabled: intercomBridge.communicationEnabled,
7762
+ goal: params.tasks[0]?.task ?? "",
7763
+ ctx: asyncCtx,
7917
7764
  availableModels,
7918
- modelScope: data.modelScope,
7919
- modelOverrides,
7920
- modelSelections,
7921
- behaviors,
7922
- firstProgressIndex: parallelProgressPrecreated ? -1 : firstProgressIndex,
7765
+ cwd: effectiveCwd,
7766
+ maxOutput: params.maxOutput,
7767
+ artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7768
+ artifactConfig,
7769
+ sessionRoot,
7770
+ chainSkills: [],
7771
+ sessionFilesByFlatIndex: params.tasks.map((task, index) => sessionFileForTask(task.agent, index, task.model)),
7772
+ thinkingOverridesByFlatIndex: params.tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, task.model)),
7773
+ maxSubagentDepth: currentMaxSubagentDepth,
7774
+ waitToolEnabled: deps.waitToolEnabled,
7775
+ worktreeSetupHook: deps.config.worktreeSetupHook,
7776
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7777
+ worktreeBaseDir: deps.config.worktreeBaseDir,
7923
7778
  controlConfig,
7924
- onControlEvent,
7925
- childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : void 0,
7926
- orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7927
- communicationEnabled: data.intercomBridge.communicationEnabled,
7928
- foregroundControl,
7929
- concurrencyLimit: parallelConcurrency,
7930
- globalSemaphore: new Semaphore(deps.config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT),
7931
- maxSubagentDepths,
7779
+ controlIntercomTarget,
7780
+ childIntercomTarget,
7781
+ nestedRoute,
7782
+ timeoutMs: data.timeoutMs,
7783
+ turnBudget: data.turnBudget,
7784
+ toolBudget: data.toolBudget,
7785
+ configToolBudget: data.configToolBudget,
7786
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7787
+ });
7788
+ }
7789
+ if (hasChain && params.chain) {
7790
+ let normalized = normalizeSkillInput(params.skill), chainSkills = normalized === !1 ? [] : normalized ?? [], rawChain = params.chain, chain = wrapChainTasksForFork(rawChain, contextPolicy);
7791
+ return executeAsyncChain(id, {
7792
+ chain,
7793
+ task: params.task,
7794
+ goal: resolveAsyncEventGoal(params.task, rawChain),
7795
+ communicationEnabled: intercomBridge.communicationEnabled,
7796
+ ctx: asyncCtx,
7797
+ availableModels,
7798
+ cwd: effectiveCwd,
7799
+ maxOutput: params.maxOutput,
7800
+ artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7801
+ artifactConfig,
7802
+ sessionRoot,
7803
+ chainSkills,
7804
+ sessionFilesByFlatIndex: collectChainSessionFiles(chain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
7805
+ thinkingOverridesByFlatIndex: collectChainThinkingOverrides(chain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
7806
+ dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
7807
+ maxSubagentDepth: currentMaxSubagentDepth,
7932
7808
  waitToolEnabled: deps.waitToolEnabled,
7933
- liveResults,
7934
- liveProgress,
7935
- onUpdate,
7936
- worktreeSetup,
7809
+ worktreeSetupHook: deps.config.worktreeSetupHook,
7810
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7811
+ worktreeBaseDir: deps.config.worktreeBaseDir,
7812
+ controlConfig,
7813
+ controlIntercomTarget,
7814
+ childIntercomTarget,
7815
+ nestedRoute,
7937
7816
  timeoutMs: data.timeoutMs,
7938
- deadlineAt,
7939
7817
  turnBudget: data.turnBudget,
7940
- toolBudgets
7941
- });
7942
- for (let i = 0; i < results.length; i++) {
7943
- let run = results[i];
7944
- recordRun(run.agent, taskTexts[i], run.exitCode, run.progressSummary?.durationMs ?? 0);
7945
- }
7946
- for (let result2 of results)
7947
- result2.progress && allProgress.push(result2.progress), result2.artifactPaths && allArtifactPaths.push(result2.artifactPaths);
7948
- foregroundControl && (updateForegroundNestedProjection(foregroundControl), attachRootChildrenToSteps(runId, results, foregroundControl.nestedChildren));
7949
- let interrupted = results.find((result2) => result2.interrupted), details = compactForegroundDetails({
7950
- mode: "parallel",
7951
- runId,
7952
- results,
7953
- progress: params.includeProgress ? allProgress : void 0,
7954
- artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : void 0,
7955
- totalChildUsage: sumResultsUsage(results),
7956
- totalCost: sumResultsCost(results)
7818
+ toolBudget: data.toolBudget,
7819
+ configToolBudget: data.configToolBudget,
7820
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7957
7821
  });
7958
- if (rememberForegroundRun(deps.state, { runId, mode: "parallel", cwd: effectiveCwd, sessionId: data.parentSessionId, results: details.results }), interrupted)
7822
+ }
7823
+ if (hasSingle) {
7824
+ let a = agents.find((x) => x.name === params.agent);
7825
+ if (!a)
7959
7826
  return {
7960
- content: [{ type: "text", text: `Parallel run paused after interrupt (${interrupted.agent}). Waiting for explicit next action.` }],
7961
- details
7827
+ content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
7828
+ isError: !0,
7829
+ details: { mode: "single", results: [] }
7962
7830
  };
7963
- let detachedIndex = results.findIndex((result2) => result2.detached), detached = detachedIndex >= 0 ? results[detachedIndex] : void 0;
7964
- if (detached)
7831
+ let rawOutput = params.output !== void 0 ? params.output : a.output, effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output), effectiveOutputMode = params.outputMode ?? "inline", normalizedSkills = normalizeSkillInput(params.skill), skills = normalizedSkills === !1 ? [] : normalizedSkills, maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, a.maxSubagentDepth), modelSelection = captureModelSelection({ model: params.model, tier: params.tier }), modelOverride = resolveExecutableChildModel({
7832
+ modelSelection,
7833
+ model: params.model,
7834
+ tier: params.tier,
7835
+ thinking: params.thinking,
7836
+ availableModels,
7837
+ preferredProvider: currentProvider
7838
+ }), spec = normalizeChildSpec({
7839
+ task: shouldForkAgent(contextPolicy, params.agent) ? wrapForkTask(params.task ?? "") : params.task ?? "",
7840
+ description: params.description,
7841
+ permissions: params.permissions,
7842
+ model: params.model,
7843
+ tier: params.tier,
7844
+ thinking: params.thinking,
7845
+ modelSelection,
7846
+ skill: params.skill,
7847
+ cwd: effectiveCwd,
7848
+ output: effectiveOutput,
7849
+ outputMode: effectiveOutputMode,
7850
+ acceptance: params.acceptance,
7851
+ toolBudget: params.toolBudget
7852
+ }, {
7853
+ parentMode: snapshotParentPermissionMode(ctx.sessionManager.getSessionId() ?? void 0),
7854
+ runId: id,
7855
+ index: 0,
7856
+ childId: params.agent
7857
+ });
7858
+ return executeAsyncSingle(id, {
7859
+ spec,
7860
+ goal: params.task ?? "",
7861
+ ctx: asyncCtx,
7862
+ availableModels,
7863
+ cwd: effectiveCwd,
7864
+ maxOutput: params.maxOutput,
7865
+ artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7866
+ artifactConfig,
7867
+ sessionRoot,
7868
+ sessionFile: sessionFileForTask(params.agent, 0, modelOverride),
7869
+ skills,
7870
+ output: effectiveOutput,
7871
+ outputMode: effectiveOutputMode,
7872
+ outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
7873
+ modelOverride,
7874
+ thinkingOverride: thinkingOverrideForTask(params.agent, 0, modelOverride),
7875
+ maxSubagentDepth,
7876
+ waitToolEnabled: deps.waitToolEnabled,
7877
+ worktreeSetupHook: deps.config.worktreeSetupHook,
7878
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7879
+ worktreeBaseDir: deps.config.worktreeBaseDir,
7880
+ controlConfig,
7881
+ communicationEnabled: intercomBridge.communicationEnabled,
7882
+ controlIntercomTarget,
7883
+ childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : void 0,
7884
+ nestedRoute,
7885
+ acceptance: params.acceptance,
7886
+ timeoutMs: data.timeoutMs,
7887
+ turnBudget: data.turnBudget,
7888
+ toolBudget: data.toolBudget,
7889
+ configToolBudget: data.configToolBudget
7890
+ });
7891
+ }
7892
+ return null;
7893
+ }
7894
+ async function runChainPath(data, deps) {
7895
+ let { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactsDir, artifactConfig, onUpdate, sessionRoot, controlConfig, contextPolicy } = data, onControlEvent = createForegroundControlNotifier(data, deps), childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : void 0, foregroundControl = deps.state.foregroundControls.get(runId), normalized = normalizeSkillInput(params.skill), chainSkills = normalized === !1 ? [] : normalized ?? [], chain = wrapChainTasksForFork(params.chain, contextPolicy), currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
7896
+ if (params.chainDir && snapshotParentPermissionMode(ctx.sessionManager.getSessionId() ?? void 0) === "read-only")
7897
+ return {
7898
+ content: [{ type: "text", text: `Read-only mode cannot put a chain's files in ${params.chainDir}. Leave chainDir unset.` }],
7899
+ isError: !0,
7900
+ details: { mode: "chain", results: [] }
7901
+ };
7902
+ let chainResult = await executeChain({
7903
+ chain,
7904
+ task: params.task,
7905
+ agents,
7906
+ ctx,
7907
+ modelScope: data.modelScope,
7908
+ intercomEvents: deps.pi.events,
7909
+ signal,
7910
+ runId,
7911
+ cwd: effectiveCwd,
7912
+ sessionDirForIndex,
7913
+ sessionFileForIndex,
7914
+ sessionFileForTask,
7915
+ thinkingOverrideForTask,
7916
+ artifactsDir,
7917
+ artifactConfig,
7918
+ includeProgress: params.includeProgress,
7919
+ clarify: params.clarify,
7920
+ onUpdate,
7921
+ onControlEvent,
7922
+ controlConfig,
7923
+ childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : void 0,
7924
+ orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7925
+ communicationEnabled: data.intercomBridge.communicationEnabled,
7926
+ foregroundControl,
7927
+ nestedRoute: foregroundControl?.nestedRoute,
7928
+ chainSkills,
7929
+ chainDir: params.chainDir ?? defaultChainRunsDir(artifactsDir),
7930
+ dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
7931
+ maxSubagentDepth: currentMaxSubagentDepth,
7932
+ worktreeSetupHook: deps.config.worktreeSetupHook,
7933
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7934
+ worktreeBaseDir: deps.config.worktreeBaseDir,
7935
+ timeoutMs: data.timeoutMs,
7936
+ deadlineAt: data.deadlineAt,
7937
+ turnBudget: data.turnBudget,
7938
+ onDetachedExit: (index, result2) => updateRememberedForegroundChild(deps.state, { runId, mode: "chain", cwd: effectiveCwd, sessionId: data.parentSessionId, index, result: result2, events: deps.pi.events }),
7939
+ toolBudget: data.toolBudget,
7940
+ configToolBudget: data.configToolBudget,
7941
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7942
+ });
7943
+ if (chainResult.requestedAsync) {
7944
+ if (!isAsyncAvailable())
7965
7945
  return {
7966
- content: [{ type: "text", text: `Parallel run detached for intercom coordination (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
7967
- details
7946
+ content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
7947
+ isError: !0,
7948
+ details: { mode: "chain", results: [] }
7968
7949
  };
7969
- foregroundControl && updateForegroundNestedProjection(foregroundControl);
7970
- let intercomReceipt = await maybeBuildForegroundIntercomReceipt({
7950
+ let id = randomUUID7(), asyncCtx = {
7971
7951
  pi: deps.pi,
7972
- intercomBridge: data.intercomBridge,
7973
- runId,
7974
- mode: "parallel",
7975
- details,
7976
- ...foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}
7952
+ cwd: ctx.cwd,
7953
+ currentSessionId: deps.state.currentSessionId,
7954
+ parentSessionId: ctx.sessionManager.getSessionId() ?? void 0,
7955
+ currentModelProvider: ctx.model?.provider,
7956
+ currentModel: ctx.model,
7957
+ modelScope: data.modelScope
7958
+ }, rawAsyncChain = chainResult.requestedAsync.chain, asyncChain = wrapChainTasksForFork(rawAsyncChain, contextPolicy), firstAgent = firstChainAgent(rawAsyncChain);
7959
+ return executeAsyncChain(id, {
7960
+ chain: asyncChain,
7961
+ task: params.task,
7962
+ goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : !1),
7963
+ ctx: asyncCtx,
7964
+ availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
7965
+ cwd: effectiveCwd,
7966
+ maxOutput: params.maxOutput,
7967
+ artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
7968
+ artifactConfig,
7969
+ sessionRoot,
7970
+ chainSkills: chainResult.requestedAsync.chainSkills,
7971
+ sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
7972
+ thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
7973
+ dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
7974
+ maxSubagentDepth: currentMaxSubagentDepth,
7975
+ waitToolEnabled: deps.waitToolEnabled,
7976
+ worktreeSetupHook: deps.config.worktreeSetupHook,
7977
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
7978
+ worktreeBaseDir: deps.config.worktreeBaseDir,
7979
+ controlConfig,
7980
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : void 0,
7981
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : void 0,
7982
+ communicationEnabled: data.intercomBridge.communicationEnabled,
7983
+ nestedRoute: data.nestedRoute,
7984
+ timeoutMs: data.timeoutMs,
7985
+ turnBudget: data.turnBudget,
7986
+ toolBudget: data.toolBudget,
7987
+ configToolBudget: data.configToolBudget,
7988
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit
7977
7989
  });
7978
- if (intercomReceipt)
7979
- return {
7980
- content: [{ type: "text", text: intercomReceipt.text }],
7981
- details: intercomReceipt.details
7982
- };
7983
- let worktreeSuffix = buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks), ok = results.filter((result2) => result2.exitCode === 0).length, downgradeNote = backgroundRequestedWhileClarifying ? " (background requested, but clarify kept this run foreground)" : "", aggregatedOutput = aggregateParallelOutputs(results.map((result2) => ({
7984
- agent: result2.agent,
7985
- output: result2.truncation?.text || getSingleResultOutput(result2),
7986
- exitCode: result2.exitCode,
7987
- error: result2.error,
7988
- timedOut: result2.timedOut
7989
- })), (i, agent) => `=== Task ${i + 1}: ${agent} ===`), summary = `${ok}/${results.length} succeeded${downgradeNote}`;
7990
- return {
7991
- content: [{ type: "text", text: worktreeSuffix ? `${summary}
7992
-
7993
- ${aggregatedOutput}
7994
-
7995
- ${worktreeSuffix}` : `${summary}
7996
-
7997
- ${aggregatedOutput}` }],
7998
- details
7999
- };
8000
- } finally {
8001
- worktreeSetup && cleanupWorktrees(worktreeSetup);
7990
+ }
7991
+ let rawChainDetails = chainResult.details ? { ...chainResult.details, runId } : void 0;
7992
+ foregroundControl && rawChainDetails && (updateForegroundNestedProjection(foregroundControl), attachRootChildrenToSteps(runId, rawChainDetails.results, foregroundControl.nestedChildren), rawChainDetails.totalCost = sumResultsCost(rawChainDetails.results));
7993
+ let chainDetails = rawChainDetails ? compactForegroundDetails(rawChainDetails) : void 0;
7994
+ chainDetails && rememberForegroundRun(deps.state, { runId, mode: "chain", cwd: effectiveCwd, sessionId: data.parentSessionId, results: chainDetails.results });
7995
+ let intercomReceipt = !chainResult.isError && chainDetails && !chainDetails.results.some((result2) => result2.interrupted || result2.detached) ? await maybeBuildForegroundIntercomReceipt({
7996
+ pi: deps.pi,
7997
+ intercomBridge: data.intercomBridge,
7998
+ runId,
7999
+ mode: "chain",
8000
+ details: chainDetails,
8001
+ ...foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}
8002
+ }) : null;
8003
+ return intercomReceipt ? {
8004
+ ...chainResult,
8005
+ content: [{ type: "text", text: intercomReceipt.text }],
8006
+ details: intercomReceipt.details
8007
+ } : chainDetails ? { ...chainResult, details: chainDetails } : chainResult;
8008
+ }
8009
+ function defaultChainRunsDir(artifactsDir) {
8010
+ return ensureArtifactsDir(artifactsDir), path19.join(artifactsDir, "chain-runs");
8011
+ }
8012
+ function resolveSingleRunOutputBaseDir(deps, artifactsDir, runId) {
8013
+ return deps.config.singleRunOutputBaseDir ? path19.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir)) : path19.join(artifactsDir, "outputs", runId);
8014
+ }
8015
+ function buildChainWorktreeTaskCwdError(chain, sharedCwd) {
8016
+ for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
8017
+ let step = chain[stepIndex];
8018
+ if (!isParallelStep(step) || !step.worktree)
8019
+ continue;
8020
+ let stepCwd = resolveChildCwd(sharedCwd, step.cwd), conflict = findWorktreeTaskCwdConflict(step.parallel, stepCwd);
8021
+ if (!conflict)
8022
+ continue;
8023
+ let detail = formatWorktreeTaskCwdConflict(conflict, stepCwd);
8024
+ return `parallel chain step ${stepIndex + 1}: ${detail}`;
8002
8025
  }
8003
8026
  }
8004
8027
  async function runSinglePath(data, deps) {
@@ -8060,7 +8083,7 @@ async function runSinglePath(data, deps) {
8060
8083
  isError: !0,
8061
8084
  details: { mode: "single", results: [] }
8062
8085
  };
8063
- let id = randomUUID4(), asyncCtx = {
8086
+ let id = randomUUID7(), asyncCtx = {
8064
8087
  pi: deps.pi,
8065
8088
  cwd: ctx.cwd,
8066
8089
  currentSessionId: deps.state.currentSessionId,
@@ -8102,7 +8125,7 @@ async function runSinglePath(data, deps) {
8102
8125
  }
8103
8126
  }
8104
8127
  shouldForkAgent(contextPolicy, params.agent) && (task = wrapForkTask(task));
8105
- let cleanTask = task, outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, effectiveCwd, resolveSingleRunOutputBaseDir(deps, artifactsDir, runId)), validationError = validateFileOnlyOutputMode(effectiveOutputMode, outputPath, `Single run (${params.agent})`) ?? outputTargetError(outputPath, ctx.cwd) ?? readOnlyOutputError(outputPath, path16.join(artifactsDir, "outputs", runId), ctx.sessionManager.getSessionId() ?? void 0);
8128
+ let cleanTask = task, outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, effectiveCwd, resolveSingleRunOutputBaseDir(deps, artifactsDir, runId)), validationError = validateFileOnlyOutputMode(effectiveOutputMode, outputPath, `Single run (${params.agent})`) ?? outputTargetError(outputPath, ctx.cwd) ?? readOnlyOutputError(outputPath, path19.join(artifactsDir, "outputs", runId), ctx.sessionManager.getSessionId() ?? void 0);
8106
8129
  if (validationError)
8107
8130
  return { content: [{ type: "text", text: validationError }], isError: !0, details: { mode: "single", results: [] } };
8108
8131
  task = injectSingleOutputInstruction(task, outputPath, agentConfig);
@@ -8310,7 +8333,7 @@ function createSubagentExecutor(deps) {
8310
8333
  let targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
8311
8334
  if (paramsWithResolvedCwd.dir)
8312
8335
  try {
8313
- let location = resolveAsyncRunLocation(paramsWithResolvedCwd, ASYNC_DIR, RESULTS_DIR), runId2 = location.resolvedId ?? targetRunId ?? path16.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
8336
+ let location = resolveAsyncRunLocation(paramsWithResolvedCwd, ASYNC_DIR, RESULTS_DIR), runId2 = location.resolvedId ?? targetRunId ?? path19.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
8314
8337
  return steerAsyncRun({ state: deps.state, runId: runId2, message, index: paramsWithResolvedCwd.index, kill: deps.kill, location, signal, recover: ({ absoluteDeadlineAt, ...limits }) => resumeAsyncRun({ params: { ...limits, action: "resume", id: runId2, message }, requestCwd, ctx, deps, absoluteDeadlineAt }) });
8315
8338
  } catch (error) {
8316
8339
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
@@ -8338,7 +8361,7 @@ function createSubagentExecutor(deps) {
8338
8361
  if (paramsWithResolvedCwd.dir)
8339
8362
  try {
8340
8363
  let location = resolveAsyncRunLocation(paramsWithResolvedCwd, ASYNC_DIR, RESULTS_DIR);
8341
- return stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path16.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
8364
+ return stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path19.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
8342
8365
  } catch (error) {
8343
8366
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
8344
8367
  }
@@ -8423,7 +8446,7 @@ function createSubagentExecutor(deps) {
8423
8446
  return buildRequestedModeError(effectiveParams, configToolBudget.error);
8424
8447
  let effectiveCwd = effectiveParams.cwd ?? ctx.cwd, parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
8425
8448
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
8426
- let runId = randomUUID4().slice(0, 8), parentPermissionMode = snapshotParentPermissionMode(ctx.sessionManager.getSessionId() ?? void 0), internalized;
8449
+ let runId = randomUUID7().slice(0, 8), parentPermissionMode = snapshotParentPermissionMode(ctx.sessionManager.getSessionId() ?? void 0), internalized;
8427
8450
  try {
8428
8451
  internalized = internalizePromptDrivenChildren(effectiveParams, {
8429
8452
  runId,
@@ -8474,18 +8497,18 @@ function createSubagentExecutor(deps) {
8474
8497
  if (effectiveParams.sessionDir) {
8475
8498
  if (parentPermissionMode === "read-only")
8476
8499
  return buildRequestedModeError(effectiveParams, `Read-only mode cannot put subagent session files in ${effectiveParams.sessionDir}. Leave sessionDir unset.`);
8477
- sessionRoot = path16.resolve(deps.expandTilde(effectiveParams.sessionDir));
8500
+ sessionRoot = path19.resolve(deps.expandTilde(effectiveParams.sessionDir));
8478
8501
  } else {
8479
- let baseSessionRoot = deps.config.defaultSessionDir ? path16.resolve(deps.expandTilde(deps.config.defaultSessionDir)) : deps.getSubagentSessionRoot(parentSessionFile);
8480
- !deps.config.defaultSessionDir && !parentSessionFile && !effectiveAsync && removeOnExit(baseSessionRoot), sessionRoot = path16.join(baseSessionRoot, runId);
8502
+ let baseSessionRoot = deps.config.defaultSessionDir ? path19.resolve(deps.expandTilde(deps.config.defaultSessionDir)) : deps.getSubagentSessionRoot(parentSessionFile);
8503
+ !deps.config.defaultSessionDir && !parentSessionFile && !effectiveAsync && removeOnExit(baseSessionRoot), sessionRoot = path19.join(baseSessionRoot, runId);
8481
8504
  }
8482
8505
  try {
8483
- fs16.mkdirSync(sessionRoot, { recursive: !0 });
8506
+ fs17.mkdirSync(sessionRoot, { recursive: !0 });
8484
8507
  } catch (error) {
8485
8508
  let message = error instanceof Error ? error.message : String(error);
8486
8509
  return toExecutionErrorResult(effectiveParams, new Error(`Failed to create session directory '${sessionRoot}': ${message}`));
8487
8510
  }
8488
- let sessionDirForIndex = (idx) => path16.join(sessionRoot, `run-${idx ?? 0}`), forkSessionFileForTask = (agentName, idx = 0, modelOverride) => {
8511
+ let sessionDirForIndex = (idx) => path19.join(sessionRoot, `run-${idx ?? 0}`), forkSessionFileForTask = (agentName, idx = 0, modelOverride) => {
8489
8512
  if (shouldForkAgent(contextPolicy, agentName))
8490
8513
  return prepareForkThinking(agentName, idx, modelOverride), forkSessionFileForIndex(idx);
8491
8514
  }, forkThinkingOverrideForTask = (agentName, idx = 0, modelOverride) => {
@@ -8494,7 +8517,7 @@ function createSubagentExecutor(deps) {
8494
8517
  prepareForkThinking(agentName, idx, modelOverride);
8495
8518
  let override = forkThinkingOverrideForIndex(idx);
8496
8519
  return override === "off" && forkThinkingDowngrades.set(idx, agentName), override;
8497
- }, childSessionFileForTask = (agentName, idx, modelOverride) => forkSessionFileForTask(agentName, idx, modelOverride) ?? path16.join(sessionDirForIndex(idx), "session.jsonl"), childSessionFileForIndex = (idx) => path16.join(sessionDirForIndex(idx), "session.jsonl");
8520
+ }, childSessionFileForTask = (agentName, idx, modelOverride) => forkSessionFileForTask(agentName, idx, modelOverride) ?? path19.join(sessionDirForIndex(idx), "session.jsonl"), childSessionFileForIndex = (idx) => path19.join(sessionDirForIndex(idx), "session.jsonl");
8498
8521
  try {
8499
8522
  effectiveParams.clarify === !0 && ctx.hasUI || preflightForkSessionsForStaticTasks(contextPolicy.params, contextPolicy, forkSessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems);
8500
8523
  } catch (error) {