@ashx-j/lunr-dev 0.2.40-dev.54.2 → 0.2.40-dev.55.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 (36) hide show
  1. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.d.ts +19 -0
  2. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.js +331 -0
  3. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.d.ts +37 -0
  4. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.js +321 -0
  5. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/executor-types.d.ts +124 -0
  6. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/executor-types.js +2 -0
  7. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.d.ts +17 -0
  8. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.js +98 -0
  9. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.d.ts +40 -0
  10. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.js +172 -0
  11. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.d.ts +14 -0
  12. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.js +161 -0
  13. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.d.ts +46 -0
  14. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.js +195 -0
  15. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.d.ts +10 -0
  16. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.js +537 -0
  17. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts +5 -81
  18. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +26 -1763
  19. package/dist/builtin-extensions/pi-subagents/src/shared/settings.d.ts +1 -1
  20. package/dist/node-runtime/{builtin-extensions-VQHK3YKF.js → builtin-extensions-YJ7F6GND.js} +1 -1
  21. package/dist/node-runtime/{chunk-YDY7A2WB.js → chunk-3UQ7ZNLI.js} +2 -2
  22. package/dist/node-runtime/{chunk-UZMXBZQT.js → chunk-5HVA5ECB.js} +3 -3
  23. package/dist/node-runtime/{chunk-VIYDTWDK.js → chunk-CDILDA4F.js} +604 -602
  24. package/dist/node-runtime/{chunk-MFDTF25H.js → chunk-G3PARFR4.js} +2 -2
  25. package/dist/node-runtime/{command-SRDEBPUR.js → command-H52R5R2G.js} +1 -1
  26. package/dist/node-runtime/{gateway-AMEMDTUT.js → gateway-OHPDCOOB.js} +1 -1
  27. package/dist/node-runtime/index.js +2 -2
  28. package/dist/node-runtime/{lunr-cron-OMQBN3UK.js → lunr-cron-SV2EXYKV.js} +1 -1
  29. package/dist/node-runtime/main.js +2 -2
  30. package/dist/node-runtime/{pi-subagents-36KOL5SV.js → pi-subagents-WS6OU5MG.js} +2 -2
  31. package/dist/node-runtime/rpc-entry.js +2 -2
  32. package/dist/node-runtime/{subagent-executor-D42G55F5.js → subagent-executor-LPVOWPMG.js} +1920 -1897
  33. package/install-lock/package-lock.json +24 -24
  34. package/install-lock/package.json +2 -2
  35. package/npm-shrinkwrap.json +12 -12
  36. package/package.json +4 -4
@@ -1340,51 +1340,6 @@ function resolveCurrentSessionId(sessionManager) {
1340
1340
  return sessionId;
1341
1341
  }
1342
1342
 
1343
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/tool-budget.js
1344
- var DEFAULT_TOOL_BUDGET_BLOCK = ["read", "grep", "find", "ls"], TOOL_BUDGET_ENV = "PI_SUBAGENT_TOOL_BUDGET";
1345
- function normalizeToolBudgetBlock(block) {
1346
- return block === "*" ? "*" : block === void 0 ? [...DEFAULT_TOOL_BUDGET_BLOCK] : [...new Set(block.map((tool) => tool.trim()).filter(Boolean))];
1347
- }
1348
- function validateToolBudgetConfig(raw, label = "toolBudget") {
1349
- if (raw === void 0)
1350
- return {};
1351
- if (!raw || typeof raw != "object" || Array.isArray(raw))
1352
- return { error: `${label} must be an object with hard and optional soft/block.` };
1353
- let value = raw;
1354
- if (typeof value.hard != "number" || !Number.isInteger(value.hard) || value.hard < 1)
1355
- return { error: `${label}.hard must be an integer >= 1.` };
1356
- if (value.soft !== void 0 && (typeof value.soft != "number" || !Number.isInteger(value.soft) || value.soft < 1))
1357
- return { error: `${label}.soft must be an integer >= 1 when provided.` };
1358
- if (value.soft !== void 0 && value.soft > value.hard)
1359
- return { error: `${label}.soft must be <= ${label}.hard.` };
1360
- if (value.block !== void 0 && value.block !== "*") {
1361
- if (!Array.isArray(value.block))
1362
- return { error: `${label}.block must be "*" or an array of tool names.` };
1363
- if (value.block.length === 0)
1364
- return { error: `${label}.block must contain at least one tool name.` };
1365
- for (let item of value.block)
1366
- if (typeof item != "string" || !item.trim())
1367
- return { error: `${label}.block must contain non-empty tool names.` };
1368
- }
1369
- return { budget: { hard: value.hard, ...value.soft !== void 0 ? { soft: value.soft } : {}, block: normalizeToolBudgetBlock(value.block) } };
1370
- }
1371
- function initialToolBudgetState(budget) {
1372
- return { ...budget, toolCount: 0, outcome: "within-budget" };
1373
- }
1374
- function toolBudgetState(budget, toolCount, blockedTool) {
1375
- let overHard = toolCount > budget.hard, overSoft = budget.soft !== void 0 && toolCount >= budget.soft;
1376
- return {
1377
- ...budget,
1378
- toolCount,
1379
- outcome: overHard ? "hard-blocked" : overSoft ? "soft-reached" : "within-budget",
1380
- ...overSoft ? { softReachedAt: budget.soft } : {},
1381
- ...overHard ? { hardReachedAt: budget.hard, blockedTool } : {}
1382
- };
1383
- }
1384
- function encodeToolBudgetEnv(budget) {
1385
- return budget ? JSON.stringify(budget) : void 0;
1386
- }
1387
-
1388
1343
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/model-scope.js
1389
1344
  function stripThinkingSuffix(model) {
1390
1345
  return splitKnownThinkingSuffix(model).baseModel;
@@ -1728,6 +1683,51 @@ function readStructuredOutput(runtime) {
1728
1683
  return validation.status === "invalid" ? { error: `Structured output validation failed: ${validation.message}` } : { value };
1729
1684
  }
1730
1685
 
1686
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/tool-budget.js
1687
+ var DEFAULT_TOOL_BUDGET_BLOCK = ["read", "grep", "find", "ls"], TOOL_BUDGET_ENV = "PI_SUBAGENT_TOOL_BUDGET";
1688
+ function normalizeToolBudgetBlock(block) {
1689
+ return block === "*" ? "*" : block === void 0 ? [...DEFAULT_TOOL_BUDGET_BLOCK] : [...new Set(block.map((tool) => tool.trim()).filter(Boolean))];
1690
+ }
1691
+ function validateToolBudgetConfig(raw, label = "toolBudget") {
1692
+ if (raw === void 0)
1693
+ return {};
1694
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
1695
+ return { error: `${label} must be an object with hard and optional soft/block.` };
1696
+ let value = raw;
1697
+ if (typeof value.hard != "number" || !Number.isInteger(value.hard) || value.hard < 1)
1698
+ return { error: `${label}.hard must be an integer >= 1.` };
1699
+ if (value.soft !== void 0 && (typeof value.soft != "number" || !Number.isInteger(value.soft) || value.soft < 1))
1700
+ return { error: `${label}.soft must be an integer >= 1 when provided.` };
1701
+ if (value.soft !== void 0 && value.soft > value.hard)
1702
+ return { error: `${label}.soft must be <= ${label}.hard.` };
1703
+ if (value.block !== void 0 && value.block !== "*") {
1704
+ if (!Array.isArray(value.block))
1705
+ return { error: `${label}.block must be "*" or an array of tool names.` };
1706
+ if (value.block.length === 0)
1707
+ return { error: `${label}.block must contain at least one tool name.` };
1708
+ for (let item of value.block)
1709
+ if (typeof item != "string" || !item.trim())
1710
+ return { error: `${label}.block must contain non-empty tool names.` };
1711
+ }
1712
+ return { budget: { hard: value.hard, ...value.soft !== void 0 ? { soft: value.soft } : {}, block: normalizeToolBudgetBlock(value.block) } };
1713
+ }
1714
+ function initialToolBudgetState(budget) {
1715
+ return { ...budget, toolCount: 0, outcome: "within-budget" };
1716
+ }
1717
+ function toolBudgetState(budget, toolCount, blockedTool) {
1718
+ let overHard = toolCount > budget.hard, overSoft = budget.soft !== void 0 && toolCount >= budget.soft;
1719
+ return {
1720
+ ...budget,
1721
+ toolCount,
1722
+ outcome: overHard ? "hard-blocked" : overSoft ? "soft-reached" : "within-budget",
1723
+ ...overSoft ? { softReachedAt: budget.soft } : {},
1724
+ ...overHard ? { hardReachedAt: budget.hard, blockedTool } : {}
1725
+ };
1726
+ }
1727
+ function encodeToolBudgetEnv(budget) {
1728
+ return budget ? JSON.stringify(budget) : void 0;
1729
+ }
1730
+
1731
1731
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/tool-availability.js
1732
1732
  import * as fs8 from "node:fs";
1733
1733
  var REQUIRED_CHILD_TOOLS_ENV = "PI_SUBAGENT_REQUIRED_TOOLS", CHILD_TOOL_DIAGNOSTIC_PATH_ENV = "PI_SUBAGENT_TOOL_DIAGNOSTIC_PATH";
@@ -2356,102 +2356,6 @@ function normalizeChildSpec(input, options) {
2356
2356
  };
2357
2357
  }
2358
2358
 
2359
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/status-format.js
2360
- function formatActivityAge(ms) {
2361
- return ms < 1e3 ? "now" : ms < 6e4 ? `${Math.floor(ms / 1e3)}s` : `${Math.floor(ms / 6e4)}m`;
2362
- }
2363
- function formatActivityLabel(lastActivityAt, activityState, now = Date.now()) {
2364
- if (lastActivityAt === void 0)
2365
- return activityState === "needs_attention" ? "needs attention" : activityState === "active_long_running" ? "active but long-running" : void 0;
2366
- let age = formatActivityAge(Math.max(0, now - lastActivityAt));
2367
- return activityState === "needs_attention" ? `no activity for ${age}` : activityState === "active_long_running" ? `active but long-running \xB7 last activity ${age === "now" ? "now" : `${age} ago`}` : age === "now" ? "active now" : `active ${age} ago`;
2368
- }
2369
- function isCompletedStepStatus(status) {
2370
- return status === "complete" || status === "completed";
2371
- }
2372
- function formatAgentRunningLabel(count) {
2373
- return count === 1 ? "1 agent running" : `${count} agents running`;
2374
- }
2375
- function formatParallelOutcome(steps, total, options = {}) {
2376
- let running = steps.filter((step) => step.status === "running").length, done = steps.filter((step) => isCompletedStepStatus(step.status)).length, failed = steps.filter((step) => step.status === "failed").length, stopped = steps.filter((step) => step.status === "stopped").length, paused = steps.filter((step) => step.status === "paused").length, parts = [`${done}/${total} done`];
2377
- return options.showRunning !== !1 && running > 0 && parts.unshift(formatAgentRunningLabel(running)), failed > 0 && parts.push(`${failed} failed`), stopped > 0 && parts.push(`${stopped} stopped`), paused > 0 && parts.push(`${paused} paused`), parts.join(" \xB7 ");
2378
- }
2379
-
2380
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/nested-render.js
2381
- function countNestedRuns(children) {
2382
- let counts = { total: 0, running: 0, paused: 0, complete: 0, failed: 0, stopped: 0, queued: 0 };
2383
- for (let child of children ?? []) {
2384
- counts.total++, counts[child.state]++;
2385
- let nested = countNestedRuns([...child.children ?? [], ...child.steps?.flatMap((step) => step.children ?? []) ?? []]);
2386
- counts.total += nested.total, counts.running += nested.running, counts.paused += nested.paused, counts.complete += nested.complete, counts.failed += nested.failed, counts.stopped += nested.stopped, counts.queued += nested.queued;
2387
- }
2388
- return counts;
2389
- }
2390
- function formatNestedAggregate(children) {
2391
- let counts = countNestedRuns(children);
2392
- if (counts.total === 0)
2393
- return;
2394
- let parts = [
2395
- counts.running > 0 ? `${counts.running} running` : "",
2396
- counts.paused > 0 ? `${counts.paused} paused` : "",
2397
- counts.failed > 0 ? `${counts.failed} failed` : "",
2398
- counts.stopped > 0 ? `${counts.stopped} stopped` : "",
2399
- counts.complete > 0 ? `${counts.complete} complete` : "",
2400
- counts.queued > 0 ? `${counts.queued} queued` : ""
2401
- ].filter(Boolean);
2402
- return `+${counts.total} nested run${counts.total === 1 ? "" : "s"}${parts.length ? ` (${parts.join(", ")})` : ""}`;
2403
- }
2404
- function nestedRunLabel(run) {
2405
- return run.agent ? run.agent : run.agents?.length ? run.agents.length === 1 ? run.agents[0] : `${run.agents.slice(0, 2).join(", ")}${run.agents.length > 2 ? ` +${run.agents.length - 2}` : ""}` : run.id;
2406
- }
2407
- function formatNestedActivity(input) {
2408
- let facts = [];
2409
- input.currentTool && input.currentToolStartedAt !== void 0 ? facts.push(`tool ${input.currentTool} ${formatDuration(Math.max(0, Date.now() - input.currentToolStartedAt))}`) : input.currentTool && facts.push(`tool ${input.currentTool}`), input.currentPath && facts.push(shortenPath(input.currentPath)), input.turnCount !== void 0 && facts.push(`${input.turnCount} turns`), input.toolCount !== void 0 && facts.push(`${input.toolCount} tools`), input.totalTokens && facts.push(`${formatTokens(input.totalTokens.total)} tok`);
2410
- let activity = formatActivityLabel(input.lastActivityAt, input.activityState);
2411
- return activity || facts.length ? [activity, ...facts].filter(Boolean).join(" | ") : void 0;
2412
- }
2413
- function formatNestedRunLines(children, options) {
2414
- let lines = [], append = (items, depth, indent) => {
2415
- if (!(!items?.length || lines.length >= options.maxLines)) {
2416
- if (depth > options.maxDepth) {
2417
- let aggregate = formatNestedAggregate(items);
2418
- aggregate && lines.length < options.maxLines && lines.push(`${indent}\u21B3 ${aggregate}`);
2419
- return;
2420
- }
2421
- for (let index = 0; index < items.length; index++) {
2422
- let child = items[index];
2423
- if (lines.length >= options.maxLines) {
2424
- let aggregate = formatNestedAggregate(items.slice(index));
2425
- aggregate && (lines[lines.length - 1] = `${indent}\u21B3 ${aggregate}`);
2426
- return;
2427
- }
2428
- let activity = child.state === "running" ? formatNestedActivity(child) : void 0, error = child.error ? ` | error: ${child.error}` : "";
2429
- if (lines.push(`${indent}\u21B3 ${nestedRunLabel(child)} [${child.id}] ${child.state}${activity ? ` | ${activity}` : ""}${error}`), options.commandHints && lines.length < options.maxLines && lines.push(`${indent} Status: subagent({ action: "status", id: "${child.id}" })`), depth === options.maxDepth) {
2430
- let aggregate = formatNestedAggregate([...child.steps?.flatMap((step) => step.children ?? []) ?? [], ...child.children ?? []]);
2431
- aggregate && lines.length < options.maxLines && lines.push(`${indent} \u21B3 ${aggregate}`);
2432
- continue;
2433
- }
2434
- for (let [stepIndex, step] of (child.steps ?? []).entries()) {
2435
- if (lines.length >= options.maxLines)
2436
- return;
2437
- let stepActivity = step.status === "running" ? formatNestedActivity(step) : void 0;
2438
- lines.push(`${indent} ${stepIndex + 1}. ${step.agent} ${step.status}${stepActivity ? ` | ${stepActivity}` : ""}${step.error ? ` | error: ${step.error}` : ""}`), append(step.children, depth + 1, `${indent} `);
2439
- }
2440
- append(child.children, depth + 1, `${indent} `);
2441
- }
2442
- }
2443
- };
2444
- return append(children, 0, options.indent), lines;
2445
- }
2446
- function formatNestedRunStatusLines(children, options = {}) {
2447
- return formatNestedRunLines(children, {
2448
- indent: options.indent ?? " ",
2449
- maxDepth: options.maxDepth ?? 2,
2450
- maxLines: options.maxLines ?? 40,
2451
- commandHints: options.commandHints ?? !1
2452
- });
2453
- }
2454
-
2455
2359
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/nested-events.js
2456
2360
  import { randomUUID } from "node:crypto";
2457
2361
  import * as fs11 from "node:fs";
@@ -3146,371 +3050,62 @@ function nestedResultsPath(rootRunId, id) {
3146
3050
  return assertSafeId("rootRunId", rootRunId), assertSafeId("id", id), path11.join(RESULTS_DIR, "nested", rootRunId, `${id}.json`);
3147
3051
  }
3148
3052
 
3149
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/stale-run-reconciler.js
3150
- import * as fs12 from "node:fs";
3053
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js
3054
+ import { spawn } from "node:child_process";
3055
+ import { spawnSync } from "node:child_process";
3151
3056
  import * as path12 from "node:path";
3152
3057
 
3153
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/parallel-groups.js
3154
- function isValidParallelGroup(group, stepCount, chainStepCount) {
3155
- if (typeof group != "object" || group === null)
3156
- return !1;
3157
- let { start, count, stepIndex } = group;
3158
- return typeof start == "number" && typeof count == "number" && typeof stepIndex == "number" && Number.isInteger(start) && Number.isInteger(count) && Number.isInteger(stepIndex) && start >= 0 && count > 0 && stepIndex >= 0 && stepIndex < chainStepCount && start + count <= stepCount;
3159
- }
3160
- function normalizeParallelGroups(groups, stepCount, chainStepCount) {
3161
- return Array.isArray(groups) ? groups.filter((group) => isValidParallelGroup(group, stepCount, chainStepCount)).sort((left, right) => left.stepIndex - right.stepIndex || left.start - right.start) : [];
3162
- }
3163
- function flatToLogicalStepIndex(flatIndex, chainStepCount, groups) {
3164
- let logicalIndex = 0, cursor = 0;
3165
- for (let group of groups) {
3166
- for (; cursor < group.start && logicalIndex < chainStepCount; ) {
3167
- if (cursor === flatIndex)
3168
- return logicalIndex;
3169
- cursor++, logicalIndex++;
3170
- }
3171
- if (flatIndex >= group.start && flatIndex < group.start + group.count)
3172
- return group.stepIndex;
3173
- cursor = group.start + group.count, logicalIndex = group.stepIndex + 1;
3174
- }
3175
- for (; cursor <= flatIndex && logicalIndex < chainStepCount; ) {
3176
- if (cursor === flatIndex)
3177
- return logicalIndex;
3178
- cursor++, logicalIndex++;
3179
- }
3180
- return Math.max(0, chainStepCount - 1);
3181
- }
3182
-
3183
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/stale-run-reconciler.js
3184
- function getErrorMessage2(error) {
3185
- return error instanceof Error ? error.message : String(error);
3186
- }
3187
- function readRunnerStartupDiagnostics(asyncDir) {
3188
- let stderrPath = path12.join(asyncDir, "runner.stderr.log"), maxBytes = 64 * 1024, content;
3189
- try {
3190
- let stat = fs12.statSync(stderrPath);
3191
- if (stat.size <= 0)
3192
- return;
3193
- let fd = fs12.openSync(stderrPath, "r");
3194
- try {
3195
- let bytesToRead = Math.min(stat.size, maxBytes), start = Math.max(0, stat.size - bytesToRead), buffer = Buffer.alloc(bytesToRead);
3196
- fs12.readSync(fd, buffer, 0, bytesToRead, start), content = buffer.toString("utf-8").trim();
3197
- } finally {
3198
- fs12.closeSync(fd);
3199
- }
3200
- } catch {
3201
- return;
3202
- }
3203
- if (!content)
3204
- return;
3205
- let lines = content.split(/\r?\n/).slice(-30).join(`
3206
- `);
3207
- return lines.length > 4e3 ? `${lines.slice(-4e3)}
3208
- [stderr tail truncated]` : lines;
3209
- }
3210
- function isNotFoundError2(error) {
3211
- return typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT";
3212
- }
3213
- function appendJsonlBestEffort(filePath, payload) {
3214
- try {
3215
- fs12.mkdirSync(path12.dirname(filePath), { recursive: !0 }), fs12.appendFileSync(filePath, `${JSON.stringify(payload)}
3216
- `, "utf-8");
3217
- } catch {
3218
- }
3219
- }
3220
- function readStatusFile(asyncDir) {
3221
- let statusPath = path12.join(asyncDir, "status.json"), content;
3222
- try {
3223
- content = fs12.readFileSync(statusPath, "utf-8");
3224
- } catch (error) {
3225
- if (isNotFoundError2(error))
3226
- return null;
3227
- throw new Error(`Failed to read async status file '${statusPath}': ${getErrorMessage2(error)}`, {
3228
- cause: error instanceof Error ? error : void 0
3229
- });
3230
- }
3231
- try {
3232
- return JSON.parse(content);
3233
- } catch (error) {
3234
- throw new Error(`Failed to parse async status file '${statusPath}': ${getErrorMessage2(error)}`, {
3235
- cause: error instanceof Error ? error : void 0
3236
- });
3237
- }
3238
- }
3239
- function readResultRepairData(resultPath) {
3240
- try {
3241
- let data = JSON.parse(fs12.readFileSync(resultPath, "utf-8")), state = data.success ? "complete" : data.state === "stopped" ? "stopped" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed", results = Array.isArray(data.results) ? data.results.map((entry, index) => {
3242
- if (!entry || typeof entry != "object" || Array.isArray(entry))
3243
- return {};
3244
- let child = entry;
3245
- if (child.model !== void 0 && typeof child.model != "string")
3246
- throw new Error(`Invalid async result file '${resultPath}': results[${index}].model must be a string.`);
3247
- if (child.thinking !== void 0 && typeof child.thinking != "string")
3248
- throw new Error(`Invalid async result file '${resultPath}': results[${index}].thinking must be a string.`);
3249
- return child;
3250
- }) : void 0;
3251
- return { state, ...results ? { results } : {} };
3252
- } catch (error) {
3253
- if (isNotFoundError2(error))
3254
- return;
3255
- throw new Error(`Failed to read async result file '${resultPath}': ${getErrorMessage2(error)}`, {
3256
- cause: error instanceof Error ? error : void 0
3257
- });
3258
- }
3259
- }
3260
- function childState(overallState, child) {
3261
- return child?.success === !0 ? "complete" : child?.success === !1 ? "failed" : overallState;
3262
- }
3263
- function terminalStatusFromResult(status, resultPath, now) {
3264
- let repair = readResultRepairData(resultPath);
3265
- if (!repair)
3266
- return;
3267
- let steps = (status.steps ?? []).map((step, index) => {
3268
- if (step.status !== "running" && step.status !== "pending")
3269
- return step;
3270
- let child = repair.results?.[index], state = childState(repair.state, child), model = child?.model ?? step.model, thinking = resolveEffectiveThinking(model, child?.thinking ?? step.thinking);
3271
- return {
3272
- ...step,
3273
- status: state === "complete" ? "complete" : state,
3274
- endedAt: step.endedAt ?? now,
3275
- durationMs: step.startedAt !== void 0 && step.durationMs === void 0 ? Math.max(0, now - step.startedAt) : step.durationMs,
3276
- exitCode: step.exitCode ?? (state === "complete" || state === "paused" ? 0 : 1),
3277
- error: state === "failed" || state === "stopped" ? step.error ?? child?.error : step.error,
3278
- stopped: state === "stopped" ? !0 : step.stopped,
3279
- sessionFile: step.sessionFile ?? child?.sessionFile,
3280
- model,
3281
- thinking,
3282
- attemptedModels: child?.attemptedModels ?? step.attemptedModels,
3283
- modelAttempts: child?.modelAttempts ?? step.modelAttempts
3284
- };
3285
- });
3286
- return {
3287
- ...status,
3288
- state: repair.state,
3289
- ...repair.state === "stopped" ? { stopped: !0 } : {},
3290
- activityState: void 0,
3291
- lastUpdate: now,
3292
- endedAt: status.endedAt ?? now,
3293
- steps
3294
- };
3295
- }
3296
- function buildStartedStatus(asyncDir, startedRun, now) {
3297
- let startedAt = startedRun.startedAt ?? now, agents = startedRun.agents?.length ? startedRun.agents : ["subagent"], chainStepCount = startedRun.chainStepCount, parallelGroups = chainStepCount !== void 0 ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount) : [];
3298
- return {
3299
- runId: startedRun.runId || path12.basename(asyncDir),
3300
- ...startedRun.sessionId ? { sessionId: startedRun.sessionId } : {},
3301
- mode: startedRun.mode ?? "single",
3302
- state: "running",
3303
- pid: startedRun.pid,
3304
- startedAt,
3305
- lastUpdate: now,
3306
- currentStep: 0,
3307
- ...chainStepCount !== void 0 ? { chainStepCount } : {},
3308
- ...parallelGroups.length ? { parallelGroups } : {},
3309
- steps: agents.map((agent) => ({
3310
- agent,
3311
- status: "running",
3312
- startedAt
3313
- })),
3314
- ...startedRun.sessionFile ? { sessionFile: startedRun.sessionFile } : {}
3315
- };
3316
- }
3317
- function buildFailedRepair(status, asyncDir, now, reason) {
3318
- let runId = status.runId || path12.basename(asyncDir), pid = typeof status.pid == "number" ? status.pid : "unknown", baseMessage = reason ?? `Async runner process ${pid} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`, diagnostics = readRunnerStartupDiagnostics(asyncDir), message = diagnostics ? `${baseMessage}
3319
-
3320
- Runner stderr tail:
3321
- ${diagnostics}` : baseMessage, repairedSteps = (status.steps?.length ? status.steps : [{ agent: "subagent", status: "running" }]).map((step) => step.status === "running" || step.status === "pending" ? {
3322
- ...step,
3323
- status: "failed",
3324
- activityState: void 0,
3325
- endedAt: step.endedAt ?? now,
3326
- durationMs: step.startedAt !== void 0 && step.durationMs === void 0 ? Math.max(0, now - step.startedAt) : step.durationMs,
3327
- exitCode: step.exitCode ?? 1,
3328
- error: step.error ?? message
3329
- } : step), repairedStatus = {
3330
- ...status,
3331
- state: "failed",
3332
- activityState: void 0,
3333
- lastUpdate: now,
3334
- endedAt: now,
3335
- steps: repairedSteps
3336
- }, resultAgent = repairedSteps[status.currentStep ?? 0]?.agent ?? repairedSteps[0]?.agent ?? "subagent";
3337
- return {
3338
- status: repairedStatus,
3339
- message,
3340
- result: {
3341
- id: runId,
3342
- agent: resultAgent,
3343
- mode: status.mode,
3344
- success: !1,
3345
- state: "failed",
3346
- summary: message,
3347
- results: repairedSteps.map((step) => ({
3348
- agent: step.agent,
3349
- output: step.status === "complete" || step.status === "completed" ? "" : message,
3350
- error: step.status === "complete" || step.status === "completed" ? void 0 : step.error ?? message,
3351
- success: step.status === "complete" || step.status === "completed",
3352
- model: step.model,
3353
- attemptedModels: step.attemptedModels,
3354
- modelAttempts: step.modelAttempts,
3355
- sessionFile: step.sessionFile
3356
- })),
3357
- exitCode: 1,
3358
- timestamp: now,
3359
- durationMs: Math.max(0, now - status.startedAt),
3360
- asyncDir,
3361
- sessionId: status.sessionId,
3362
- sessionFile: status.sessionFile
3363
- }
3364
- };
3365
- }
3366
- function writeFailedRepair(asyncDir, status, resultPath, now, reason) {
3367
- let repair = buildFailedRepair(status, asyncDir, now, reason);
3368
- return writeAtomicJson(resultPath, repair.result), writeAtomicJson(path12.join(asyncDir, "status.json"), repair.status), appendJsonlBestEffort(path12.join(asyncDir, "events.jsonl"), {
3369
- type: "subagent.run.repaired_stale",
3370
- ts: now,
3371
- runId: repair.status.runId,
3372
- pid: status.pid,
3373
- resultPath,
3374
- message: repair.message
3375
- }), { status: repair.status, repaired: !0, resultPath, message: repair.message };
3376
- }
3377
- function terminal2(state) {
3378
- return state === "complete" || state === "failed" || state === "paused" || state === "stopped";
3379
- }
3380
- function* nestedRuns(children) {
3381
- for (let child of children ?? [])
3382
- yield child, yield* nestedRuns(child.children), yield* nestedRuns(child.steps?.flatMap((step) => step.children ?? []));
3383
- }
3384
- function reconcileNestedAsyncDescendants(route, options = {}) {
3385
- let registry = projectNestedEvents(route);
3386
- for (let run of nestedRuns(registry.children)) {
3387
- if (run.state !== "running" && run.state !== "queued")
3388
- continue;
3389
- let asyncDir = resolveNestedAsyncDir(route.rootRunId, run);
3390
- if (!asyncDir)
3391
- continue;
3392
- let result = reconcileAsyncRun(asyncDir, {
3393
- ...options,
3394
- resultsDir: path12.join(options.resultsDir ?? RESULTS_DIR, "nested", route.rootRunId)
3395
- }), status = result.status;
3396
- if (!status || !result.repaired && !terminal2(status.state))
3397
- continue;
3398
- let ts = options.now?.() ?? Date.now();
3399
- writeNestedEvent(route, {
3400
- type: terminal2(status.state) ? "subagent.nested.completed" : "subagent.nested.updated",
3401
- ts,
3402
- parentRunId: run.parentRunId,
3403
- parentStepIndex: run.parentStepIndex,
3404
- child: nestedSummaryFromAsyncStatus(status, asyncDir, {
3405
- id: run.id,
3406
- parentRunId: run.parentRunId,
3407
- parentStepIndex: run.parentStepIndex,
3408
- depth: run.depth,
3409
- path: run.path,
3410
- mode: run.mode,
3411
- ts
3412
- })
3413
- });
3414
- }
3415
- }
3416
- function checkPidLiveness(pid, kill = process.kill) {
3417
- try {
3418
- return kill(pid, 0), "alive";
3419
- } catch (error) {
3420
- let code = typeof error == "object" && error !== null && "code" in error ? error.code : void 0;
3421
- return code === "ESRCH" ? "dead" : "unknown";
3422
- }
3423
- }
3424
- function reconcileAsyncRun(asyncDir, options = {}) {
3425
- let now = options.now?.() ?? Date.now(), status = readStatusFile(asyncDir), startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : void 0, effectiveStatus = status ?? startedStatus;
3426
- if (!effectiveStatus)
3427
- return { status: null, repaired: !1 };
3428
- let statusPath = path12.join(asyncDir, "status.json");
3429
- for (let [index, step] of (effectiveStatus.steps ?? []).entries()) {
3430
- let stepRecord = step;
3431
- if (stepRecord.model !== void 0 && typeof stepRecord.model != "string")
3432
- throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
3433
- if (stepRecord.thinking !== void 0 && typeof stepRecord.thinking != "string")
3434
- throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
3435
- }
3436
- let runId = effectiveStatus.runId || path12.basename(asyncDir), resultPath = path12.join(options.resultsDir ?? RESULTS_DIR, `${runId}.json`);
3437
- if (fs12.existsSync(resultPath)) {
3438
- let terminalStatus = effectiveStatus.state === "running" || effectiveStatus.state === "queued" ? terminalStatusFromResult(effectiveStatus, resultPath, now) : void 0;
3439
- return terminalStatus ? (writeAtomicJson(path12.join(asyncDir, "status.json"), terminalStatus), { status: terminalStatus, repaired: !0, resultPath, message: "Existing async result file was used to repair stale running status." }) : { status: effectiveStatus, repaired: !1, resultPath };
3440
- }
3441
- if (effectiveStatus.state !== "running" || typeof effectiveStatus.pid != "number")
3442
- return { status: status ?? null, repaired: !1, resultPath };
3443
- if (!status) {
3444
- let startedAt = options.startedRun?.startedAt ?? effectiveStatus.startedAt;
3445
- if (now - startedAt < (options.missingStatusGraceMs ?? 1e3))
3446
- return { status: null, repaired: !1, resultPath };
3447
- }
3448
- if (checkPidLiveness(effectiveStatus.pid, options.kill) !== "dead") {
3449
- let staleAfterMs = options.staleAlivePidMs ?? 864e5, lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
3450
- if (now - lastUpdate <= staleAfterMs)
3451
- return { status: status ?? null, repaired: !1, resultPath };
3452
- let message = `Async runner process ${effectiveStatus.pid} still has a live PID, but status has not updated for ${now - lastUpdate}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;
3453
- return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now, message);
3454
- }
3455
- return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now);
3456
- }
3457
-
3458
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js
3459
- import { spawn } from "node:child_process";
3460
- import { spawnSync } from "node:child_process";
3461
- import * as path13 from "node:path";
3462
-
3463
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.js
3464
- var REVIEW_ONLY_PATTERNS = [
3465
- /\breview only\b/i,
3466
- /\bsuggest fixes only\b/i,
3467
- /\bonly return findings\b/i,
3468
- /\breturn findings only\b/i
3469
- ], REVIEWER_REQUIRED_EDIT_PATTERNS = [
3470
- /\bmust\s+(?:edit|modify|change|fix|patch|apply)\b/i,
3471
- /\brequired\s+to\s+(?:edit|modify|change|fix|patch|apply)\b/i,
3472
- /\bregardless\s+of\s+findings\b/i,
3473
- /\balways\s+(?:edit|modify|change|fix|patch|apply)\b/i,
3474
- /\bapply\s+(?:the\s+)?fix(?:es)?\s+directly\b/i,
3475
- /\bmake\s+(?:the\s+)?code\s+changes\b/i
3476
- ], NO_EDIT_PROHIBITION_PATTERN = /\b(?:do not|don't|must not)\s+(?:implement|edit|modify|write(?:\s+to)?|touch|change)\b((?:(?!\b(?:but|and|then)\b)[^.;,:!?\n–—-])*)/gi, GENERIC_PROHIBITION_OBJECT = /^\s*(?:(?:any|all|the|these|those|your|our|existing|project|source|sources|repo|repository)[\s/,-]*)*(?:files?|code|codebase|sources?|anything|repo(?:sitory)?)?\s*$/i, SCOPED_NO_EDIT_CONSTRAINT_PATTERNS = [
3477
- /\bdo not edit files?\s+outside\b/i,
3478
- /\bdo not edit\s+outside\b/i,
3479
- /\bdo not edit\s+unrelated files?\b/i,
3480
- /\bdo not change\s+unrelated files?\b/i,
3481
- /\bdo not modify\s+unrelated files?\b/i
3482
- ], NO_TOOL_INTENT_PATTERNS = [
3483
- /\bno tools? needed\b/i,
3484
- /\bno tools? required\b/i,
3485
- /\bwithout using tools\b/i,
3486
- /\bdo not use tools\b/i,
3487
- /\bdon't use tools\b/i
3488
- ], READ_ONLY_DELIVERABLE_PATTERNS = [
3489
- /\b(?:draft|write|compose|prepare|produce)\s+(?:(?:a|an|the)\s+)?(?:github\s+)?(?:issue|bug report|issue draft|issue body|proposal|plan|report|summary|findings?|analysis|recommendations?)\b/i,
3490
- /\b(?:issue|bug report)\s+(?:draft|body|template)\b/i,
3491
- /\b(?:return|provide|produce)\s+(?:text|markdown|answer|findings?|recommendations?)\s+only\b/i
3492
- ], RESEARCH_TASK_PATTERNS = [
3493
- /\binvestigate\b/i,
3494
- /\bresearch\b/i
3495
- ], FIX_OR_PATCH_IMPLEMENTATION_PATTERN = /\b(?:fix|patch)\s+(?:(?:it|this|that|them|each|any|all|these|those)\b|(?:(?:a|an|the|any|all)\s+)?(?:(?:failing|failed|broken|flaky|red|cold|start|current|existing|reported|approved|known|regression|unit|integration|e2e|source|typescript|type-?script|ts|type-?check|compiler)\s+)*(?:bug|defect|issues?|problems?|failures?|regressions?|tests?|errors?|items?|typos?|code|source|implementation|component|function|module|class|method|logic|file|files|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command|lint(?:ing)?|build|ci|type-?check|type\s+checking)\b)/i, WORKER_IMPLEMENTATION_PATTERNS = [
3496
- /\b(?:implement|edit|modify|refactor|delete)\b/i,
3497
- FIX_OR_PATCH_IMPLEMENTATION_PATTERN,
3498
- /\b(?:update|add|remove|replace|create)\b(?!\s+(?:(?:a|an|the)\s+)?(?:report|summary|findings?)(?:\b|$))/i,
3499
- /\bapply\s+(?:the\s+)?(?:(?:suggested|proposed|recommended)\s+)?(?:changes?|fix(?:es)?|patch)\b/i,
3500
- /\bmake\s+(?:the\s+)?changes\b/i,
3501
- /\bdo those fixes\b/i
3502
- ], GENERAL_IMPLEMENTATION_PATTERNS = [
3503
- /\b(?:implement|edit|modify|refactor)\b/i,
3504
- FIX_OR_PATCH_IMPLEMENTATION_PATTERN,
3505
- /\bapply\s+(?:the\s+)?(?:(?:suggested|proposed|recommended)\s+)?(?:changes?|fix(?:es)?|patch)\b/i,
3506
- /\bmake\s+(?:the\s+)?changes\b/i,
3507
- /\bdo those fixes\b/i,
3508
- /\b(?:update|add|remove|replace|delete|create)\s+(?:the\s+)?(?:file|files|code|source|implementation|test|tests|component|function|module|class|method|logic|import|imports|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command)\b/i
3509
- ];
3510
- function stripFrameworkInstructions(task) {
3511
- return task.split(`
3512
- `).filter((line) => !/^\s*\[(?:Write to|Read from):/i.test(line)).filter((line) => !/^\s*(?:Create and maintain progress at:|Update progress at:|\*\*Output:\*\*|Write your findings to(?: exactly this path)?:|Return the complete artifact in your final response\.|The runtime will persist it to exactly this path:|Do not call contact_supervisor merely because no write-capable tool is available\.|This path is authoritative for this run\.|Ignore any other output filename or output path mentioned elsewhere)/i.test(line)).join(`
3513
- `);
3058
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.js
3059
+ var REVIEW_ONLY_PATTERNS = [
3060
+ /\breview only\b/i,
3061
+ /\bsuggest fixes only\b/i,
3062
+ /\bonly return findings\b/i,
3063
+ /\breturn findings only\b/i
3064
+ ], REVIEWER_REQUIRED_EDIT_PATTERNS = [
3065
+ /\bmust\s+(?:edit|modify|change|fix|patch|apply)\b/i,
3066
+ /\brequired\s+to\s+(?:edit|modify|change|fix|patch|apply)\b/i,
3067
+ /\bregardless\s+of\s+findings\b/i,
3068
+ /\balways\s+(?:edit|modify|change|fix|patch|apply)\b/i,
3069
+ /\bapply\s+(?:the\s+)?fix(?:es)?\s+directly\b/i,
3070
+ /\bmake\s+(?:the\s+)?code\s+changes\b/i
3071
+ ], NO_EDIT_PROHIBITION_PATTERN = /\b(?:do not|don't|must not)\s+(?:implement|edit|modify|write(?:\s+to)?|touch|change)\b((?:(?!\b(?:but|and|then)\b)[^.;,:!?\n–—-])*)/gi, GENERIC_PROHIBITION_OBJECT = /^\s*(?:(?:any|all|the|these|those|your|our|existing|project|source|sources|repo|repository)[\s/,-]*)*(?:files?|code|codebase|sources?|anything|repo(?:sitory)?)?\s*$/i, SCOPED_NO_EDIT_CONSTRAINT_PATTERNS = [
3072
+ /\bdo not edit files?\s+outside\b/i,
3073
+ /\bdo not edit\s+outside\b/i,
3074
+ /\bdo not edit\s+unrelated files?\b/i,
3075
+ /\bdo not change\s+unrelated files?\b/i,
3076
+ /\bdo not modify\s+unrelated files?\b/i
3077
+ ], NO_TOOL_INTENT_PATTERNS = [
3078
+ /\bno tools? needed\b/i,
3079
+ /\bno tools? required\b/i,
3080
+ /\bwithout using tools\b/i,
3081
+ /\bdo not use tools\b/i,
3082
+ /\bdon't use tools\b/i
3083
+ ], READ_ONLY_DELIVERABLE_PATTERNS = [
3084
+ /\b(?:draft|write|compose|prepare|produce)\s+(?:(?:a|an|the)\s+)?(?:github\s+)?(?:issue|bug report|issue draft|issue body|proposal|plan|report|summary|findings?|analysis|recommendations?)\b/i,
3085
+ /\b(?:issue|bug report)\s+(?:draft|body|template)\b/i,
3086
+ /\b(?:return|provide|produce)\s+(?:text|markdown|answer|findings?|recommendations?)\s+only\b/i
3087
+ ], RESEARCH_TASK_PATTERNS = [
3088
+ /\binvestigate\b/i,
3089
+ /\bresearch\b/i
3090
+ ], FIX_OR_PATCH_IMPLEMENTATION_PATTERN = /\b(?:fix|patch)\s+(?:(?:it|this|that|them|each|any|all|these|those)\b|(?:(?:a|an|the|any|all)\s+)?(?:(?:failing|failed|broken|flaky|red|cold|start|current|existing|reported|approved|known|regression|unit|integration|e2e|source|typescript|type-?script|ts|type-?check|compiler)\s+)*(?:bug|defect|issues?|problems?|failures?|regressions?|tests?|errors?|items?|typos?|code|source|implementation|component|function|module|class|method|logic|file|files|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command|lint(?:ing)?|build|ci|type-?check|type\s+checking)\b)/i, WORKER_IMPLEMENTATION_PATTERNS = [
3091
+ /\b(?:implement|edit|modify|refactor|delete)\b/i,
3092
+ FIX_OR_PATCH_IMPLEMENTATION_PATTERN,
3093
+ /\b(?:update|add|remove|replace|create)\b(?!\s+(?:(?:a|an|the)\s+)?(?:report|summary|findings?)(?:\b|$))/i,
3094
+ /\bapply\s+(?:the\s+)?(?:(?:suggested|proposed|recommended)\s+)?(?:changes?|fix(?:es)?|patch)\b/i,
3095
+ /\bmake\s+(?:the\s+)?changes\b/i,
3096
+ /\bdo those fixes\b/i
3097
+ ], GENERAL_IMPLEMENTATION_PATTERNS = [
3098
+ /\b(?:implement|edit|modify|refactor)\b/i,
3099
+ FIX_OR_PATCH_IMPLEMENTATION_PATTERN,
3100
+ /\bapply\s+(?:the\s+)?(?:(?:suggested|proposed|recommended)\s+)?(?:changes?|fix(?:es)?|patch)\b/i,
3101
+ /\bmake\s+(?:the\s+)?changes\b/i,
3102
+ /\bdo those fixes\b/i,
3103
+ /\b(?:update|add|remove|replace|delete|create)\s+(?:the\s+)?(?:file|files|code|source|implementation|test|tests|component|function|module|class|method|logic|import|imports|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command)\b/i
3104
+ ];
3105
+ function stripFrameworkInstructions(task) {
3106
+ return task.split(`
3107
+ `).filter((line) => !/^\s*\[(?:Write to|Read from):/i.test(line)).filter((line) => !/^\s*(?:Create and maintain progress at:|Update progress at:|\*\*Output:\*\*|Write your findings to(?: exactly this path)?:|Return the complete artifact in your final response\.|The runtime will persist it to exactly this path:|Do not call contact_supervisor merely because no write-capable tool is available\.|This path is authoritative for this run\.|Ignore any other output filename or output path mentioned elsewhere)/i.test(line)).join(`
3108
+ `);
3514
3109
  }
3515
3110
  function stripPatterns(task, patterns) {
3516
3111
  let stripped = task;
@@ -4181,7 +3776,7 @@ function aggregateAcceptanceReport(input) {
4181
3776
  }
4182
3777
  function runVerifyCommand(command, defaultCwd, options = {}) {
4183
3778
  return new Promise((resolve12) => {
4184
- let startedAt = Date.now(), cwd = command.cwd ? path13.resolve(defaultCwd, command.cwd) : defaultCwd, stdout = "", stderr = "", timedOut = !1, settled = !1, hardKill, child = spawn(command.command, {
3779
+ let startedAt = Date.now(), cwd = command.cwd ? path12.resolve(defaultCwd, command.cwd) : defaultCwd, stdout = "", stderr = "", timedOut = !1, settled = !1, hardKill, child = spawn(command.command, {
4185
3780
  cwd,
4186
3781
  env: { ...process.env, ...command.env ?? {} },
4187
3782
  shell: !0,
@@ -4355,23 +3950,127 @@ function formatTurnBudgetOutput(message, output) {
4355
3950
  Partial output before turn-budget abort:
4356
3951
  ${output}` : message;
4357
3952
  }
4358
- function initialTurnBudgetState(budget) {
4359
- return { ...budget, outcome: "within-budget", turnCount: 0 };
3953
+ function initialTurnBudgetState(budget) {
3954
+ return { ...budget, outcome: "within-budget", turnCount: 0 };
3955
+ }
3956
+ function turnBudgetState(budget, turnCount, exceeded) {
3957
+ return {
3958
+ ...budget,
3959
+ turnCount,
3960
+ outcome: exceeded ? "exceeded" : "wrap-up-requested",
3961
+ wrapUpRequestedAtTurn: budget.maxTurns,
3962
+ ...exceeded ? { exceededAtTurn: turnCount } : {}
3963
+ };
3964
+ }
3965
+ function shouldAbortForTurnBudget(budget, turnCount, terminalAssistantStop) {
3966
+ let hardLimit = budget.maxTurns + budget.graceTurns;
3967
+ return turnCount < hardLimit ? !1 : turnCount > hardLimit ? !0 : !terminalAssistantStop;
3968
+ }
3969
+
3970
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js
3971
+ import * as fs12 from "node:fs";
3972
+ import * as os6 from "node:os";
3973
+ import * as path13 from "node:path";
3974
+ var NATIVE_INTERCOM_EXTENSION_DIR = "native:pi-subagents-supervisor-channel";
3975
+ function defaultAgentDir() {
3976
+ return getAgentDir();
3977
+ }
3978
+ function defaultSubagentConfigDir(agentDir = defaultAgentDir()) {
3979
+ return path13.join(agentDir, "extensions", "subagent");
3980
+ }
3981
+ var DEFAULT_INTERCOM_TARGET_PREFIX = "subagent-chat", INTERCOM_BRIDGE_MARKER = "Intercom orchestration channel:", DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `You own reversible implementation decisions within your assigned scope. Use contact_supervisor for coordination with "{orchestratorTarget}"; its tool description defines delivery and reply behavior.
3982
+ Consolidate dependency findings into one handoff when another task needs them before completion. Escalate permission, safety, scope changes, or a blocked decision with evidence and your recommended choice. Continue independent work before opening a blocking request.
3983
+ Native intercom reaches only the supervisor, not siblings. Use the supplied contracts and artifacts instead of discovering sibling sessions.
3984
+ Return one self-contained final result; the runtime delivers it. If you cannot write a configured output artifact with your available tools, return its complete contents for the runtime to persist.`;
3985
+ function resolveIntercomSessionTarget(sessionName, sessionId) {
3986
+ let trimmedName = sessionName?.trim();
3987
+ if (trimmedName)
3988
+ return trimmedName;
3989
+ let normalizedSessionId = sessionId.startsWith("session-") ? sessionId.slice(8) : sessionId;
3990
+ return `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;
3991
+ }
3992
+ function sanitizeIntercomTargetPart(value) {
3993
+ return value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "agent";
3994
+ }
3995
+ function resolveSubagentIntercomTarget(runId, agent, index) {
3996
+ let stepSuffix = index !== void 0 ? `-${index + 1}` : "";
3997
+ return `subagent-${sanitizeIntercomTargetPart(agent)}-${sanitizeIntercomTargetPart(runId)}${stepSuffix}`;
3998
+ }
3999
+ function resolveIntercomBridgeMode(value) {
4000
+ return value === "off" || value === "always" || value === "fork-only" ? value : "always";
4001
+ }
4002
+ function resolveIntercomBridgeConfig(value) {
4003
+ return !value || typeof value != "object" || Array.isArray(value) ? { mode: "always", instructionFile: "" } : {
4004
+ mode: resolveIntercomBridgeMode(value.mode),
4005
+ instructionFile: typeof value.instructionFile == "string" ? value.instructionFile : ""
4006
+ };
4007
+ }
4008
+ function expandTilde(filePath) {
4009
+ return filePath.startsWith("~/") ? path13.join(os6.homedir(), filePath.slice(2)) : filePath;
4010
+ }
4011
+ function resolveInstructionTemplate(instructionFile, settingsDir) {
4012
+ if (!instructionFile)
4013
+ return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;
4014
+ let expandedPath = expandTilde(instructionFile), resolvedPath = path13.isAbsolute(expandedPath) ? expandedPath : path13.resolve(settingsDir, expandedPath);
4015
+ try {
4016
+ return fs12.readFileSync(resolvedPath, "utf-8");
4017
+ } catch (error) {
4018
+ return console.warn(`Failed to read intercom bridge instructionFile at '${resolvedPath}'. Using default instructions.`, error), DEFAULT_INTERCOM_BRIDGE_TEMPLATE;
4019
+ }
4020
+ }
4021
+ function buildIntercomBridgeInstruction(orchestratorTarget, template) {
4022
+ let instruction = template.replaceAll("{orchestratorTarget}", orchestratorTarget).trim();
4023
+ return instruction.startsWith(INTERCOM_BRIDGE_MARKER) ? instruction : `${INTERCOM_BRIDGE_MARKER}
4024
+ ${instruction}`;
4360
4025
  }
4361
- function turnBudgetState(budget, turnCount, exceeded) {
4026
+ function inactiveReason(mode, context, orchestratorTarget) {
4027
+ if (mode === "off")
4028
+ return "bridge mode is off";
4029
+ if (mode === "fork-only" && context !== "fork")
4030
+ return "bridge mode is fork-only and context is not fork";
4031
+ if (!orchestratorTarget)
4032
+ return "orchestrator target is not available";
4033
+ }
4034
+ function diagnoseIntercomBridge(input) {
4035
+ let config = resolveIntercomBridgeConfig(input.config), mode = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()) ? config.mode : "off", orchestratorTarget = input.orchestratorTarget?.trim(), wantsIntercom = mode !== "off" && !(mode === "fork-only" && input.context !== "fork"), reason = inactiveReason(mode, input.context, orchestratorTarget);
4362
4036
  return {
4363
- ...budget,
4364
- turnCount,
4365
- outcome: exceeded ? "exceeded" : "wrap-up-requested",
4366
- wrapUpRequestedAtTurn: budget.maxTurns,
4367
- ...exceeded ? { exceededAtTurn: turnCount } : {}
4037
+ active: reason === void 0,
4038
+ mode,
4039
+ wantsIntercom,
4040
+ supervisorChannelAvailable: !0,
4041
+ extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
4042
+ ...orchestratorTarget ? { orchestratorTarget } : {},
4043
+ ...reason ? { reason } : {}
4368
4044
  };
4369
4045
  }
4370
- function shouldAbortForTurnBudget(budget, turnCount, terminalAssistantStop) {
4371
- let hardLimit = budget.maxTurns + budget.graceTurns;
4372
- return turnCount < hardLimit ? !1 : turnCount > hardLimit ? !0 : !terminalAssistantStop;
4046
+ function resolveIntercomBridge(input) {
4047
+ let config = resolveIntercomBridgeConfig(input.config), communicationEnabled = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()), mode = communicationEnabled ? config.mode : "off", orchestratorTarget = input.orchestratorTarget?.trim(), agentDir = path13.resolve(input.agentDir ?? defaultAgentDir()), settingsDir = path13.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir)), defaultInstruction = buildIntercomBridgeInstruction(orchestratorTarget || "{orchestratorTarget}", DEFAULT_INTERCOM_BRIDGE_TEMPLATE);
4048
+ return inactiveReason(mode, input.context, orchestratorTarget) || !orchestratorTarget ? { active: !1, communicationEnabled, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction } : {
4049
+ active: !0,
4050
+ communicationEnabled,
4051
+ mode,
4052
+ orchestratorTarget,
4053
+ extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
4054
+ instruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir))
4055
+ };
4056
+ }
4057
+ function applyIntercomBridgeToAgent(agent, bridge) {
4058
+ if (!bridge.active || !bridge.orchestratorTarget)
4059
+ return agent;
4060
+ let bridgeTools = ["intercom", "contact_supervisor"], tools = agent.tools ? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))] : agent.tools, instruction = bridge.instruction, trimmedPrompt = agent.systemPrompt?.trim() || "", systemPrompt = trimmedPrompt.includes(INTERCOM_BRIDGE_MARKER) ? trimmedPrompt : trimmedPrompt ? `${trimmedPrompt}
4061
+
4062
+ ${instruction}` : instruction;
4063
+ return tools === agent.tools && systemPrompt === agent.systemPrompt ? agent : {
4064
+ ...agent,
4065
+ tools,
4066
+ systemPrompt
4067
+ };
4373
4068
  }
4374
4069
 
4070
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js
4071
+ import * as fs15 from "node:fs";
4072
+ import * as path16 from "node:path";
4073
+
4375
4074
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/control-channel.js
4376
4075
  import { randomUUID as randomUUID2 } from "node:crypto";
4377
4076
  import * as fs13 from "node:fs";
@@ -4523,109 +4222,316 @@ function deliverStopRequest(input) {
4523
4222
  requestAsyncStop(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
4524
4223
  }
4525
4224
 
4526
- // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js
4225
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/stale-run-reconciler.js
4527
4226
  import * as fs14 from "node:fs";
4528
- import * as os6 from "node:os";
4529
4227
  import * as path15 from "node:path";
4530
- var NATIVE_INTERCOM_EXTENSION_DIR = "native:pi-subagents-supervisor-channel";
4531
- function defaultAgentDir() {
4532
- return getAgentDir();
4228
+
4229
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/parallel-groups.js
4230
+ function isValidParallelGroup(group, stepCount, chainStepCount) {
4231
+ if (typeof group != "object" || group === null)
4232
+ return !1;
4233
+ let { start, count, stepIndex } = group;
4234
+ return typeof start == "number" && typeof count == "number" && typeof stepIndex == "number" && Number.isInteger(start) && Number.isInteger(count) && Number.isInteger(stepIndex) && start >= 0 && count > 0 && stepIndex >= 0 && stepIndex < chainStepCount && start + count <= stepCount;
4533
4235
  }
4534
- function defaultSubagentConfigDir(agentDir = defaultAgentDir()) {
4535
- return path15.join(agentDir, "extensions", "subagent");
4236
+ function normalizeParallelGroups(groups, stepCount, chainStepCount) {
4237
+ return Array.isArray(groups) ? groups.filter((group) => isValidParallelGroup(group, stepCount, chainStepCount)).sort((left, right) => left.stepIndex - right.stepIndex || left.start - right.start) : [];
4536
4238
  }
4537
- var DEFAULT_INTERCOM_TARGET_PREFIX = "subagent-chat", INTERCOM_BRIDGE_MARKER = "Intercom orchestration channel:", DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `You own reversible implementation decisions within your assigned scope. Use contact_supervisor for coordination with "{orchestratorTarget}"; its tool description defines delivery and reply behavior.
4538
- Consolidate dependency findings into one handoff when another task needs them before completion. Escalate permission, safety, scope changes, or a blocked decision with evidence and your recommended choice. Continue independent work before opening a blocking request.
4539
- Native intercom reaches only the supervisor, not siblings. Use the supplied contracts and artifacts instead of discovering sibling sessions.
4540
- Return one self-contained final result; the runtime delivers it. If you cannot write a configured output artifact with your available tools, return its complete contents for the runtime to persist.`;
4541
- function resolveIntercomSessionTarget(sessionName, sessionId) {
4542
- let trimmedName = sessionName?.trim();
4543
- if (trimmedName)
4544
- return trimmedName;
4545
- let normalizedSessionId = sessionId.startsWith("session-") ? sessionId.slice(8) : sessionId;
4546
- return `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;
4239
+ function flatToLogicalStepIndex(flatIndex, chainStepCount, groups) {
4240
+ let logicalIndex = 0, cursor = 0;
4241
+ for (let group of groups) {
4242
+ for (; cursor < group.start && logicalIndex < chainStepCount; ) {
4243
+ if (cursor === flatIndex)
4244
+ return logicalIndex;
4245
+ cursor++, logicalIndex++;
4246
+ }
4247
+ if (flatIndex >= group.start && flatIndex < group.start + group.count)
4248
+ return group.stepIndex;
4249
+ cursor = group.start + group.count, logicalIndex = group.stepIndex + 1;
4250
+ }
4251
+ for (; cursor <= flatIndex && logicalIndex < chainStepCount; ) {
4252
+ if (cursor === flatIndex)
4253
+ return logicalIndex;
4254
+ cursor++, logicalIndex++;
4255
+ }
4256
+ return Math.max(0, chainStepCount - 1);
4547
4257
  }
4548
- function sanitizeIntercomTargetPart(value) {
4549
- return value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "agent";
4258
+
4259
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/stale-run-reconciler.js
4260
+ function getErrorMessage2(error) {
4261
+ return error instanceof Error ? error.message : String(error);
4262
+ }
4263
+ function readRunnerStartupDiagnostics(asyncDir) {
4264
+ let stderrPath = path15.join(asyncDir, "runner.stderr.log"), maxBytes = 64 * 1024, content;
4265
+ try {
4266
+ let stat = fs14.statSync(stderrPath);
4267
+ if (stat.size <= 0)
4268
+ return;
4269
+ let fd = fs14.openSync(stderrPath, "r");
4270
+ try {
4271
+ let bytesToRead = Math.min(stat.size, maxBytes), start = Math.max(0, stat.size - bytesToRead), buffer = Buffer.alloc(bytesToRead);
4272
+ fs14.readSync(fd, buffer, 0, bytesToRead, start), content = buffer.toString("utf-8").trim();
4273
+ } finally {
4274
+ fs14.closeSync(fd);
4275
+ }
4276
+ } catch {
4277
+ return;
4278
+ }
4279
+ if (!content)
4280
+ return;
4281
+ let lines = content.split(/\r?\n/).slice(-30).join(`
4282
+ `);
4283
+ return lines.length > 4e3 ? `${lines.slice(-4e3)}
4284
+ [stderr tail truncated]` : lines;
4285
+ }
4286
+ function isNotFoundError2(error) {
4287
+ return typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT";
4288
+ }
4289
+ function appendJsonlBestEffort(filePath, payload) {
4290
+ try {
4291
+ fs14.mkdirSync(path15.dirname(filePath), { recursive: !0 }), fs14.appendFileSync(filePath, `${JSON.stringify(payload)}
4292
+ `, "utf-8");
4293
+ } catch {
4294
+ }
4295
+ }
4296
+ function readStatusFile(asyncDir) {
4297
+ let statusPath = path15.join(asyncDir, "status.json"), content;
4298
+ try {
4299
+ content = fs14.readFileSync(statusPath, "utf-8");
4300
+ } catch (error) {
4301
+ if (isNotFoundError2(error))
4302
+ return null;
4303
+ throw new Error(`Failed to read async status file '${statusPath}': ${getErrorMessage2(error)}`, {
4304
+ cause: error instanceof Error ? error : void 0
4305
+ });
4306
+ }
4307
+ try {
4308
+ return JSON.parse(content);
4309
+ } catch (error) {
4310
+ throw new Error(`Failed to parse async status file '${statusPath}': ${getErrorMessage2(error)}`, {
4311
+ cause: error instanceof Error ? error : void 0
4312
+ });
4313
+ }
4314
+ }
4315
+ function readResultRepairData(resultPath) {
4316
+ try {
4317
+ let data = JSON.parse(fs14.readFileSync(resultPath, "utf-8")), state = data.success ? "complete" : data.state === "stopped" ? "stopped" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed", results = Array.isArray(data.results) ? data.results.map((entry, index) => {
4318
+ if (!entry || typeof entry != "object" || Array.isArray(entry))
4319
+ return {};
4320
+ let child = entry;
4321
+ if (child.model !== void 0 && typeof child.model != "string")
4322
+ throw new Error(`Invalid async result file '${resultPath}': results[${index}].model must be a string.`);
4323
+ if (child.thinking !== void 0 && typeof child.thinking != "string")
4324
+ throw new Error(`Invalid async result file '${resultPath}': results[${index}].thinking must be a string.`);
4325
+ return child;
4326
+ }) : void 0;
4327
+ return { state, ...results ? { results } : {} };
4328
+ } catch (error) {
4329
+ if (isNotFoundError2(error))
4330
+ return;
4331
+ throw new Error(`Failed to read async result file '${resultPath}': ${getErrorMessage2(error)}`, {
4332
+ cause: error instanceof Error ? error : void 0
4333
+ });
4334
+ }
4335
+ }
4336
+ function childState(overallState, child) {
4337
+ return child?.success === !0 ? "complete" : child?.success === !1 ? "failed" : overallState;
4338
+ }
4339
+ function terminalStatusFromResult(status, resultPath, now) {
4340
+ let repair = readResultRepairData(resultPath);
4341
+ if (!repair)
4342
+ return;
4343
+ let steps = (status.steps ?? []).map((step, index) => {
4344
+ if (step.status !== "running" && step.status !== "pending")
4345
+ return step;
4346
+ let child = repair.results?.[index], state = childState(repair.state, child), model = child?.model ?? step.model, thinking = resolveEffectiveThinking(model, child?.thinking ?? step.thinking);
4347
+ return {
4348
+ ...step,
4349
+ status: state === "complete" ? "complete" : state,
4350
+ endedAt: step.endedAt ?? now,
4351
+ durationMs: step.startedAt !== void 0 && step.durationMs === void 0 ? Math.max(0, now - step.startedAt) : step.durationMs,
4352
+ exitCode: step.exitCode ?? (state === "complete" || state === "paused" ? 0 : 1),
4353
+ error: state === "failed" || state === "stopped" ? step.error ?? child?.error : step.error,
4354
+ stopped: state === "stopped" ? !0 : step.stopped,
4355
+ sessionFile: step.sessionFile ?? child?.sessionFile,
4356
+ model,
4357
+ thinking,
4358
+ attemptedModels: child?.attemptedModels ?? step.attemptedModels,
4359
+ modelAttempts: child?.modelAttempts ?? step.modelAttempts
4360
+ };
4361
+ });
4362
+ return {
4363
+ ...status,
4364
+ state: repair.state,
4365
+ ...repair.state === "stopped" ? { stopped: !0 } : {},
4366
+ activityState: void 0,
4367
+ lastUpdate: now,
4368
+ endedAt: status.endedAt ?? now,
4369
+ steps
4370
+ };
4371
+ }
4372
+ function buildStartedStatus(asyncDir, startedRun, now) {
4373
+ let startedAt = startedRun.startedAt ?? now, agents = startedRun.agents?.length ? startedRun.agents : ["subagent"], chainStepCount = startedRun.chainStepCount, parallelGroups = chainStepCount !== void 0 ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount) : [];
4374
+ return {
4375
+ runId: startedRun.runId || path15.basename(asyncDir),
4376
+ ...startedRun.sessionId ? { sessionId: startedRun.sessionId } : {},
4377
+ mode: startedRun.mode ?? "single",
4378
+ state: "running",
4379
+ pid: startedRun.pid,
4380
+ startedAt,
4381
+ lastUpdate: now,
4382
+ currentStep: 0,
4383
+ ...chainStepCount !== void 0 ? { chainStepCount } : {},
4384
+ ...parallelGroups.length ? { parallelGroups } : {},
4385
+ steps: agents.map((agent) => ({
4386
+ agent,
4387
+ status: "running",
4388
+ startedAt
4389
+ })),
4390
+ ...startedRun.sessionFile ? { sessionFile: startedRun.sessionFile } : {}
4391
+ };
4392
+ }
4393
+ function buildFailedRepair(status, asyncDir, now, reason) {
4394
+ let runId = status.runId || path15.basename(asyncDir), pid = typeof status.pid == "number" ? status.pid : "unknown", baseMessage = reason ?? `Async runner process ${pid} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`, diagnostics = readRunnerStartupDiagnostics(asyncDir), message = diagnostics ? `${baseMessage}
4395
+
4396
+ Runner stderr tail:
4397
+ ${diagnostics}` : baseMessage, repairedSteps = (status.steps?.length ? status.steps : [{ agent: "subagent", status: "running" }]).map((step) => step.status === "running" || step.status === "pending" ? {
4398
+ ...step,
4399
+ status: "failed",
4400
+ activityState: void 0,
4401
+ endedAt: step.endedAt ?? now,
4402
+ durationMs: step.startedAt !== void 0 && step.durationMs === void 0 ? Math.max(0, now - step.startedAt) : step.durationMs,
4403
+ exitCode: step.exitCode ?? 1,
4404
+ error: step.error ?? message
4405
+ } : step), repairedStatus = {
4406
+ ...status,
4407
+ state: "failed",
4408
+ activityState: void 0,
4409
+ lastUpdate: now,
4410
+ endedAt: now,
4411
+ steps: repairedSteps
4412
+ }, resultAgent = repairedSteps[status.currentStep ?? 0]?.agent ?? repairedSteps[0]?.agent ?? "subagent";
4413
+ return {
4414
+ status: repairedStatus,
4415
+ message,
4416
+ result: {
4417
+ id: runId,
4418
+ agent: resultAgent,
4419
+ mode: status.mode,
4420
+ success: !1,
4421
+ state: "failed",
4422
+ summary: message,
4423
+ results: repairedSteps.map((step) => ({
4424
+ agent: step.agent,
4425
+ output: step.status === "complete" || step.status === "completed" ? "" : message,
4426
+ error: step.status === "complete" || step.status === "completed" ? void 0 : step.error ?? message,
4427
+ success: step.status === "complete" || step.status === "completed",
4428
+ model: step.model,
4429
+ attemptedModels: step.attemptedModels,
4430
+ modelAttempts: step.modelAttempts,
4431
+ sessionFile: step.sessionFile
4432
+ })),
4433
+ exitCode: 1,
4434
+ timestamp: now,
4435
+ durationMs: Math.max(0, now - status.startedAt),
4436
+ asyncDir,
4437
+ sessionId: status.sessionId,
4438
+ sessionFile: status.sessionFile
4439
+ }
4440
+ };
4550
4441
  }
4551
- function resolveSubagentIntercomTarget(runId, agent, index) {
4552
- let stepSuffix = index !== void 0 ? `-${index + 1}` : "";
4553
- return `subagent-${sanitizeIntercomTargetPart(agent)}-${sanitizeIntercomTargetPart(runId)}${stepSuffix}`;
4442
+ function writeFailedRepair(asyncDir, status, resultPath, now, reason) {
4443
+ let repair = buildFailedRepair(status, asyncDir, now, reason);
4444
+ return writeAtomicJson(resultPath, repair.result), writeAtomicJson(path15.join(asyncDir, "status.json"), repair.status), appendJsonlBestEffort(path15.join(asyncDir, "events.jsonl"), {
4445
+ type: "subagent.run.repaired_stale",
4446
+ ts: now,
4447
+ runId: repair.status.runId,
4448
+ pid: status.pid,
4449
+ resultPath,
4450
+ message: repair.message
4451
+ }), { status: repair.status, repaired: !0, resultPath, message: repair.message };
4554
4452
  }
4555
- function resolveIntercomBridgeMode(value) {
4556
- return value === "off" || value === "always" || value === "fork-only" ? value : "always";
4453
+ function terminal2(state) {
4454
+ return state === "complete" || state === "failed" || state === "paused" || state === "stopped";
4557
4455
  }
4558
- function resolveIntercomBridgeConfig(value) {
4559
- return !value || typeof value != "object" || Array.isArray(value) ? { mode: "always", instructionFile: "" } : {
4560
- mode: resolveIntercomBridgeMode(value.mode),
4561
- instructionFile: typeof value.instructionFile == "string" ? value.instructionFile : ""
4562
- };
4456
+ function* nestedRuns(children) {
4457
+ for (let child of children ?? [])
4458
+ yield child, yield* nestedRuns(child.children), yield* nestedRuns(child.steps?.flatMap((step) => step.children ?? []));
4563
4459
  }
4564
- function expandTilde(filePath) {
4565
- return filePath.startsWith("~/") ? path15.join(os6.homedir(), filePath.slice(2)) : filePath;
4460
+ function reconcileNestedAsyncDescendants(route, options = {}) {
4461
+ let registry = projectNestedEvents(route);
4462
+ for (let run of nestedRuns(registry.children)) {
4463
+ if (run.state !== "running" && run.state !== "queued")
4464
+ continue;
4465
+ let asyncDir = resolveNestedAsyncDir(route.rootRunId, run);
4466
+ if (!asyncDir)
4467
+ continue;
4468
+ let result = reconcileAsyncRun(asyncDir, {
4469
+ ...options,
4470
+ resultsDir: path15.join(options.resultsDir ?? RESULTS_DIR, "nested", route.rootRunId)
4471
+ }), status = result.status;
4472
+ if (!status || !result.repaired && !terminal2(status.state))
4473
+ continue;
4474
+ let ts = options.now?.() ?? Date.now();
4475
+ writeNestedEvent(route, {
4476
+ type: terminal2(status.state) ? "subagent.nested.completed" : "subagent.nested.updated",
4477
+ ts,
4478
+ parentRunId: run.parentRunId,
4479
+ parentStepIndex: run.parentStepIndex,
4480
+ child: nestedSummaryFromAsyncStatus(status, asyncDir, {
4481
+ id: run.id,
4482
+ parentRunId: run.parentRunId,
4483
+ parentStepIndex: run.parentStepIndex,
4484
+ depth: run.depth,
4485
+ path: run.path,
4486
+ mode: run.mode,
4487
+ ts
4488
+ })
4489
+ });
4490
+ }
4566
4491
  }
4567
- function resolveInstructionTemplate(instructionFile, settingsDir) {
4568
- if (!instructionFile)
4569
- return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;
4570
- let expandedPath = expandTilde(instructionFile), resolvedPath = path15.isAbsolute(expandedPath) ? expandedPath : path15.resolve(settingsDir, expandedPath);
4492
+ function checkPidLiveness(pid, kill = process.kill) {
4571
4493
  try {
4572
- return fs14.readFileSync(resolvedPath, "utf-8");
4494
+ return kill(pid, 0), "alive";
4573
4495
  } catch (error) {
4574
- return console.warn(`Failed to read intercom bridge instructionFile at '${resolvedPath}'. Using default instructions.`, error), DEFAULT_INTERCOM_BRIDGE_TEMPLATE;
4496
+ let code = typeof error == "object" && error !== null && "code" in error ? error.code : void 0;
4497
+ return code === "ESRCH" ? "dead" : "unknown";
4575
4498
  }
4576
4499
  }
4577
- function buildIntercomBridgeInstruction(orchestratorTarget, template) {
4578
- let instruction = template.replaceAll("{orchestratorTarget}", orchestratorTarget).trim();
4579
- return instruction.startsWith(INTERCOM_BRIDGE_MARKER) ? instruction : `${INTERCOM_BRIDGE_MARKER}
4580
- ${instruction}`;
4581
- }
4582
- function inactiveReason(mode, context, orchestratorTarget) {
4583
- if (mode === "off")
4584
- return "bridge mode is off";
4585
- if (mode === "fork-only" && context !== "fork")
4586
- return "bridge mode is fork-only and context is not fork";
4587
- if (!orchestratorTarget)
4588
- return "orchestrator target is not available";
4589
- }
4590
- function diagnoseIntercomBridge(input) {
4591
- let config = resolveIntercomBridgeConfig(input.config), mode = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()) ? config.mode : "off", orchestratorTarget = input.orchestratorTarget?.trim(), wantsIntercom = mode !== "off" && !(mode === "fork-only" && input.context !== "fork"), reason = inactiveReason(mode, input.context, orchestratorTarget);
4592
- return {
4593
- active: reason === void 0,
4594
- mode,
4595
- wantsIntercom,
4596
- supervisorChannelAvailable: !0,
4597
- extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
4598
- ...orchestratorTarget ? { orchestratorTarget } : {},
4599
- ...reason ? { reason } : {}
4600
- };
4601
- }
4602
- function resolveIntercomBridge(input) {
4603
- let config = resolveIntercomBridgeConfig(input.config), communicationEnabled = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()), mode = communicationEnabled ? config.mode : "off", orchestratorTarget = input.orchestratorTarget?.trim(), agentDir = path15.resolve(input.agentDir ?? defaultAgentDir()), settingsDir = path15.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir)), defaultInstruction = buildIntercomBridgeInstruction(orchestratorTarget || "{orchestratorTarget}", DEFAULT_INTERCOM_BRIDGE_TEMPLATE);
4604
- return inactiveReason(mode, input.context, orchestratorTarget) || !orchestratorTarget ? { active: !1, communicationEnabled, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction } : {
4605
- active: !0,
4606
- communicationEnabled,
4607
- mode,
4608
- orchestratorTarget,
4609
- extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
4610
- instruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir))
4611
- };
4612
- }
4613
- function applyIntercomBridgeToAgent(agent, bridge) {
4614
- if (!bridge.active || !bridge.orchestratorTarget)
4615
- return agent;
4616
- let bridgeTools = ["intercom", "contact_supervisor"], tools = agent.tools ? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))] : agent.tools, instruction = bridge.instruction, trimmedPrompt = agent.systemPrompt?.trim() || "", systemPrompt = trimmedPrompt.includes(INTERCOM_BRIDGE_MARKER) ? trimmedPrompt : trimmedPrompt ? `${trimmedPrompt}
4617
-
4618
- ${instruction}` : instruction;
4619
- return tools === agent.tools && systemPrompt === agent.systemPrompt ? agent : {
4620
- ...agent,
4621
- tools,
4622
- systemPrompt
4623
- };
4500
+ function reconcileAsyncRun(asyncDir, options = {}) {
4501
+ let now = options.now?.() ?? Date.now(), status = readStatusFile(asyncDir), startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : void 0, effectiveStatus = status ?? startedStatus;
4502
+ if (!effectiveStatus)
4503
+ return { status: null, repaired: !1 };
4504
+ let statusPath = path15.join(asyncDir, "status.json");
4505
+ for (let [index, step] of (effectiveStatus.steps ?? []).entries()) {
4506
+ let stepRecord = step;
4507
+ if (stepRecord.model !== void 0 && typeof stepRecord.model != "string")
4508
+ throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
4509
+ if (stepRecord.thinking !== void 0 && typeof stepRecord.thinking != "string")
4510
+ throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
4511
+ }
4512
+ let runId = effectiveStatus.runId || path15.basename(asyncDir), resultPath = path15.join(options.resultsDir ?? RESULTS_DIR, `${runId}.json`);
4513
+ if (fs14.existsSync(resultPath)) {
4514
+ let terminalStatus = effectiveStatus.state === "running" || effectiveStatus.state === "queued" ? terminalStatusFromResult(effectiveStatus, resultPath, now) : void 0;
4515
+ return terminalStatus ? (writeAtomicJson(path15.join(asyncDir, "status.json"), terminalStatus), { status: terminalStatus, repaired: !0, resultPath, message: "Existing async result file was used to repair stale running status." }) : { status: effectiveStatus, repaired: !1, resultPath };
4516
+ }
4517
+ if (effectiveStatus.state !== "running" || typeof effectiveStatus.pid != "number")
4518
+ return { status: status ?? null, repaired: !1, resultPath };
4519
+ if (!status) {
4520
+ let startedAt = options.startedRun?.startedAt ?? effectiveStatus.startedAt;
4521
+ if (now - startedAt < (options.missingStatusGraceMs ?? 1e3))
4522
+ return { status: null, repaired: !1, resultPath };
4523
+ }
4524
+ if (checkPidLiveness(effectiveStatus.pid, options.kill) !== "dead") {
4525
+ let staleAfterMs = options.staleAlivePidMs ?? 864e5, lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
4526
+ if (now - lastUpdate <= staleAfterMs)
4527
+ return { status: status ?? null, repaired: !1, resultPath };
4528
+ let message = `Async runner process ${effectiveStatus.pid} still has a live PID, but status has not updated for ${now - lastUpdate}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;
4529
+ return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now, message);
4530
+ }
4531
+ return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now);
4624
4532
  }
4625
4533
 
4626
4534
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js
4627
- import * as fs15 from "node:fs";
4628
- import * as path16 from "node:path";
4629
4535
  var ASYNC_RESUME_INTERRUPT_SIGNAL = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
4630
4536
  function interruptLiveAsyncResumeTarget(input) {
4631
4537
  let asyncId = input.target.runId;
@@ -5223,6 +5129,102 @@ function handleSubagentControlNotice(input) {
5223
5129
  timer.unref?.(), pending.set(timerKey, timer);
5224
5130
  }
5225
5131
 
5132
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/status-format.js
5133
+ function formatActivityAge(ms) {
5134
+ return ms < 1e3 ? "now" : ms < 6e4 ? `${Math.floor(ms / 1e3)}s` : `${Math.floor(ms / 6e4)}m`;
5135
+ }
5136
+ function formatActivityLabel(lastActivityAt, activityState, now = Date.now()) {
5137
+ if (lastActivityAt === void 0)
5138
+ return activityState === "needs_attention" ? "needs attention" : activityState === "active_long_running" ? "active but long-running" : void 0;
5139
+ let age = formatActivityAge(Math.max(0, now - lastActivityAt));
5140
+ return activityState === "needs_attention" ? `no activity for ${age}` : activityState === "active_long_running" ? `active but long-running \xB7 last activity ${age === "now" ? "now" : `${age} ago`}` : age === "now" ? "active now" : `active ${age} ago`;
5141
+ }
5142
+ function isCompletedStepStatus(status) {
5143
+ return status === "complete" || status === "completed";
5144
+ }
5145
+ function formatAgentRunningLabel(count) {
5146
+ return count === 1 ? "1 agent running" : `${count} agents running`;
5147
+ }
5148
+ function formatParallelOutcome(steps, total, options = {}) {
5149
+ let running = steps.filter((step) => step.status === "running").length, done = steps.filter((step) => isCompletedStepStatus(step.status)).length, failed = steps.filter((step) => step.status === "failed").length, stopped = steps.filter((step) => step.status === "stopped").length, paused = steps.filter((step) => step.status === "paused").length, parts = [`${done}/${total} done`];
5150
+ return options.showRunning !== !1 && running > 0 && parts.unshift(formatAgentRunningLabel(running)), failed > 0 && parts.push(`${failed} failed`), stopped > 0 && parts.push(`${stopped} stopped`), paused > 0 && parts.push(`${paused} paused`), parts.join(" \xB7 ");
5151
+ }
5152
+
5153
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/nested-render.js
5154
+ function countNestedRuns(children) {
5155
+ let counts = { total: 0, running: 0, paused: 0, complete: 0, failed: 0, stopped: 0, queued: 0 };
5156
+ for (let child of children ?? []) {
5157
+ counts.total++, counts[child.state]++;
5158
+ let nested = countNestedRuns([...child.children ?? [], ...child.steps?.flatMap((step) => step.children ?? []) ?? []]);
5159
+ counts.total += nested.total, counts.running += nested.running, counts.paused += nested.paused, counts.complete += nested.complete, counts.failed += nested.failed, counts.stopped += nested.stopped, counts.queued += nested.queued;
5160
+ }
5161
+ return counts;
5162
+ }
5163
+ function formatNestedAggregate(children) {
5164
+ let counts = countNestedRuns(children);
5165
+ if (counts.total === 0)
5166
+ return;
5167
+ let parts = [
5168
+ counts.running > 0 ? `${counts.running} running` : "",
5169
+ counts.paused > 0 ? `${counts.paused} paused` : "",
5170
+ counts.failed > 0 ? `${counts.failed} failed` : "",
5171
+ counts.stopped > 0 ? `${counts.stopped} stopped` : "",
5172
+ counts.complete > 0 ? `${counts.complete} complete` : "",
5173
+ counts.queued > 0 ? `${counts.queued} queued` : ""
5174
+ ].filter(Boolean);
5175
+ return `+${counts.total} nested run${counts.total === 1 ? "" : "s"}${parts.length ? ` (${parts.join(", ")})` : ""}`;
5176
+ }
5177
+ function nestedRunLabel(run) {
5178
+ return run.agent ? run.agent : run.agents?.length ? run.agents.length === 1 ? run.agents[0] : `${run.agents.slice(0, 2).join(", ")}${run.agents.length > 2 ? ` +${run.agents.length - 2}` : ""}` : run.id;
5179
+ }
5180
+ function formatNestedActivity(input) {
5181
+ let facts = [];
5182
+ input.currentTool && input.currentToolStartedAt !== void 0 ? facts.push(`tool ${input.currentTool} ${formatDuration(Math.max(0, Date.now() - input.currentToolStartedAt))}`) : input.currentTool && facts.push(`tool ${input.currentTool}`), input.currentPath && facts.push(shortenPath(input.currentPath)), input.turnCount !== void 0 && facts.push(`${input.turnCount} turns`), input.toolCount !== void 0 && facts.push(`${input.toolCount} tools`), input.totalTokens && facts.push(`${formatTokens(input.totalTokens.total)} tok`);
5183
+ let activity = formatActivityLabel(input.lastActivityAt, input.activityState);
5184
+ return activity || facts.length ? [activity, ...facts].filter(Boolean).join(" | ") : void 0;
5185
+ }
5186
+ function formatNestedRunLines(children, options) {
5187
+ let lines = [], append = (items, depth, indent) => {
5188
+ if (!(!items?.length || lines.length >= options.maxLines)) {
5189
+ if (depth > options.maxDepth) {
5190
+ let aggregate = formatNestedAggregate(items);
5191
+ aggregate && lines.length < options.maxLines && lines.push(`${indent}\u21B3 ${aggregate}`);
5192
+ return;
5193
+ }
5194
+ for (let index = 0; index < items.length; index++) {
5195
+ let child = items[index];
5196
+ if (lines.length >= options.maxLines) {
5197
+ let aggregate = formatNestedAggregate(items.slice(index));
5198
+ aggregate && (lines[lines.length - 1] = `${indent}\u21B3 ${aggregate}`);
5199
+ return;
5200
+ }
5201
+ let activity = child.state === "running" ? formatNestedActivity(child) : void 0, error = child.error ? ` | error: ${child.error}` : "";
5202
+ if (lines.push(`${indent}\u21B3 ${nestedRunLabel(child)} [${child.id}] ${child.state}${activity ? ` | ${activity}` : ""}${error}`), options.commandHints && lines.length < options.maxLines && lines.push(`${indent} Status: subagent({ action: "status", id: "${child.id}" })`), depth === options.maxDepth) {
5203
+ let aggregate = formatNestedAggregate([...child.steps?.flatMap((step) => step.children ?? []) ?? [], ...child.children ?? []]);
5204
+ aggregate && lines.length < options.maxLines && lines.push(`${indent} \u21B3 ${aggregate}`);
5205
+ continue;
5206
+ }
5207
+ for (let [stepIndex, step] of (child.steps ?? []).entries()) {
5208
+ if (lines.length >= options.maxLines)
5209
+ return;
5210
+ let stepActivity = step.status === "running" ? formatNestedActivity(step) : void 0;
5211
+ lines.push(`${indent} ${stepIndex + 1}. ${step.agent} ${step.status}${stepActivity ? ` | ${stepActivity}` : ""}${step.error ? ` | error: ${step.error}` : ""}`), append(step.children, depth + 1, `${indent} `);
5212
+ }
5213
+ append(child.children, depth + 1, `${indent} `);
5214
+ }
5215
+ }
5216
+ };
5217
+ return append(children, 0, options.indent), lines;
5218
+ }
5219
+ function formatNestedRunStatusLines(children, options = {}) {
5220
+ return formatNestedRunLines(children, {
5221
+ indent: options.indent ?? " ",
5222
+ maxDepth: options.maxDepth ?? 2,
5223
+ maxLines: options.maxLines ?? 40,
5224
+ commandHints: options.commandHints ?? !1
5225
+ });
5226
+ }
5227
+
5226
5228
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.js
5227
5229
  import * as fs17 from "node:fs";
5228
5230
  import * as path18 from "node:path";