pi-subagents 0.85.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-O7CPL6H4.js → chunk-2D2DQGC2.js} +9 -9
  5. package/bundle/{chunk-KZ34KQQH.js → chunk-2NY5PCKQ.js} +11 -5
  6. package/bundle/{chunk-PVIVCDG2.js → chunk-3CVOAS77.js} +2 -2
  7. package/bundle/{chunk-N7B2KD74.js → chunk-6O7YH2QV.js} +1 -1
  8. package/bundle/{chunk-IQIWF2VX.js → chunk-AIL46SZU.js} +8 -6
  9. package/bundle/{chunk-H2NLFTC5.js → chunk-BFF6YDK6.js} +1 -1
  10. package/bundle/{chunk-UX4SCV5N.js → chunk-C3KWLXDH.js} +159 -98
  11. package/bundle/{chunk-GCSLVFCX.js → chunk-C5QWQSSM.js} +1 -1
  12. package/bundle/{chunk-3UZ5FVVJ.js → chunk-DGTZKYIE.js} +39 -34
  13. package/bundle/{chunk-KDMFBYFM.js → chunk-ESWW6XSX.js} +1 -1
  14. package/bundle/{chunk-WOVMHDES.js → chunk-EYGBK6CE.js} +194 -94
  15. package/bundle/{chunk-CS4O36CZ.js → chunk-HDICKROY.js} +5 -5
  16. package/bundle/{chunk-DV2NCNPR.js → chunk-JLDQ6YUR.js} +12 -12
  17. package/bundle/{chunk-RQAUNAWG.js → chunk-LFKMM3UH.js} +2 -2
  18. package/bundle/{chunk-L2ENOFVZ.js → chunk-LZKVUWIY.js} +66 -26
  19. package/bundle/{chunk-RV5OGHLO.js → chunk-M2VBGET6.js} +2 -2
  20. package/bundle/{chunk-HFTBF7SG.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-JNXT3MPI.js → chunk-OTLDAYEQ.js} +5 -5
  22. package/bundle/{chunk-JWYG26RE.js → chunk-OZCPYJEY.js} +80 -37
  23. package/bundle/{chunk-LGMILZNE.js → chunk-PGU4TZV3.js} +79 -32
  24. package/bundle/{chunk-KEY3UQMQ.js → chunk-SIAQXPJ4.js} +6 -8
  25. package/bundle/{chunk-QO75KJBT.js → chunk-USRX7QXD.js} +2 -2
  26. package/bundle/{chunk-7MAE3DJV.js → chunk-VFUFOZBU.js} +1 -1
  27. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  28. package/bundle/{chunk-T5V5BRCL.js → chunk-W52LJANO.js} +1 -1
  29. package/bundle/{chunk-PHZP3KHB.js → chunk-XSDYTXHF.js} +18 -11
  30. package/bundle/{chunk-LTPH2DXH.js → chunk-XV7RTWTS.js} +3 -3
  31. package/bundle/{chunk-JO67XSKD.js → chunk-YEXKJJVS.js} +12 -7
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +12 -10
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/workflow-resources.js +1 -1
  38. package/docs/agents.md +9 -3
  39. package/docs/configuration.md +14 -6
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/tool-reference.md +3 -0
  43. package/package.json +1 -1
  44. package/skills/pi-subagents/SKILL.md +7 -4
  45. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  46. package/src/agents/agent-management.js +10 -6
  47. package/src/agents/agent-serializer.d.ts +2 -0
  48. package/src/agents/agent-serializer.js +1 -1
  49. package/src/agents/agents.js +37 -12
  50. package/src/api/preflight.d.ts +3 -1
  51. package/src/api/preflight.js +2 -0
  52. package/src/extension/index.js +4 -2
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/tool-activation.js +10 -1
  56. package/src/extension/tool-description.d.ts +1 -1
  57. package/src/extension/tool-description.js +8 -8
  58. package/src/runs/background/async-execution.d.ts +2 -1
  59. package/src/runs/background/async-execution.js +4 -2
  60. package/src/runs/background/run-status.js +5 -4
  61. package/src/runs/background/runner-aliases.js +15 -0
  62. package/src/runs/background/subagent-runner.js +6 -6
  63. package/src/runs/background/wait-subscriptions.js +124 -12
  64. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  65. package/src/runs/foreground/async-stop-action.js +9 -1
  66. package/src/runs/foreground/execution.js +1 -0
  67. package/src/runs/foreground/subagent-executor.d.ts +1 -0
  68. package/src/runs/foreground/subagent-executor.js +51 -8
  69. package/src/runs/shared/acceptance.js +69 -26
  70. package/src/runs/shared/child-session.d.ts +5 -4
  71. package/src/runs/shared/child-session.js +43 -33
  72. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  73. package/src/runs/shared/external-cli-contract.js +18 -13
  74. package/src/runs/shared/herdr-placed-run.js +3 -2
  75. package/src/runs/shared/mcp-config-sources.d.ts +2 -1
  76. package/src/runs/shared/mcp-config-sources.js +1 -1
  77. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -1
  78. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -6
  79. package/src/runs/shared/model-resolution.d.ts +19 -4
  80. package/src/runs/shared/model-resolution.js +50 -51
  81. package/src/runs/shared/structured-output.js +10 -3
  82. package/src/shared/artifacts.js +25 -13
  83. package/src/shared/pruned-fork.js +2 -2
  84. package/src/shared/types.d.ts +71 -48
  85. package/src/tui/render.js +83 -22
  86. package/src/watchdog/model-selection.js +2 -2
  87. package/src/watchdog/review.js +2 -2
  88. package/src/workflows/scripted-workflow.d.ts +2 -0
  89. package/src/workflows/scripted-workflow.js +103 -39
  90. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  91. package/src/workflows/structured-workflow-scripts.js +32 -11
  92. package/src/workflows/workflow-receipt.js +36 -53
  93. package/src/workflows/workflow-resources.js +4 -4
  94. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  95. package/src/workflows/workflow-resume-claim.js +1 -1
  96. package/src/workflows/workflow-resume.d.ts +1 -1
  97. package/src/workflows/workflow-resume.js +3 -1
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-7F6RKT6W.js";
4
4
  import {
5
5
  PROJECT_SUBAGENTS_RELATIVE_DIR
6
- } from "./chunk-PHZP3KHB.js";
6
+ } from "./chunk-XSDYTXHF.js";
7
7
  import {
8
8
  DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
9
9
  DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
@@ -25,7 +25,7 @@ import {
25
25
  withFileLease,
26
26
  writeAtomicJson,
27
27
  writePrivateAtomicJson
28
- } from "./chunk-UX4SCV5N.js";
28
+ } from "./chunk-C3KWLXDH.js";
29
29
  import {
30
30
  DIRS,
31
31
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -2084,6 +2084,7 @@ function validGitRef(ref) {
2084
2084
  }
2085
2085
  var requireFromPackage = createRequire(new URL("../src/workflows/scripted-workflow.js", import.meta.url).href);
2086
2086
  var WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5e3;
2087
+ var WORKFLOW_DRAIN_CHILD_MESSAGE = "Workflow draining; child not started.";
2087
2088
  function isWorkflowScriptFailureKind(value) {
2088
2089
  return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
2089
2090
  }
@@ -2582,23 +2583,46 @@ function directObjectPropertyValue(node, name) {
2582
2583
  }
2583
2584
  return value;
2584
2585
  }
2585
- function validateStaticBaseRef(params, owner) {
2586
- if (params.type !== "ObjectExpression" || !Array.isArray(params.properties)) return [];
2587
- for (let index = params.properties.length - 1; index >= 0; index--) {
2588
- const property = params.properties[index];
2589
- if (!astNode(property) || property.type !== "Property") return [];
2586
+ function arrayElements(node) {
2587
+ return astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
2588
+ }
2589
+ function finalStaticProperty(node, name) {
2590
+ if (node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return void 0;
2591
+ for (let index = node.properties.length - 1; index >= 0; index--) {
2592
+ const property = node.properties[index];
2593
+ if (!astNode(property) || property.type !== "Property") return void 0;
2590
2594
  const key = staticPropertyKey(property);
2591
- if (key === void 0) return [];
2592
- if (key !== "baseRef") continue;
2593
- if (property.kind !== "init" || !astNode(property.value)) return [];
2594
- const valueNode = property.value;
2595
- const value = literalString(valueNode);
2596
- if ((value !== void 0 || valueNode.type === "Literal") && !validGitRef(value)) {
2597
- return [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }];
2598
- }
2599
- return [];
2595
+ if (key === void 0) return void 0;
2596
+ if (key === name) return property;
2597
+ }
2598
+ return void 0;
2599
+ }
2600
+ function validateStaticBaseRef(params, owner) {
2601
+ const property = finalStaticProperty(params, "baseRef");
2602
+ if (property?.kind !== "init" || !astNode(property.value)) return [];
2603
+ const valueNode = property.value;
2604
+ const value = literalString(valueNode);
2605
+ return (value !== void 0 || valueNode.type === "Literal") && !validGitRef(value) ? [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }] : [];
2606
+ }
2607
+ var LANE_RETAINED_RESUME_ERROR = 'cannot resume a retained run id in runs.lanes; use runs.run(key, { resume: id }) outside lanes, or start the lane with an agent stage and use resume: "previous" later.';
2608
+ function staticLane(lane) {
2609
+ return astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties) && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== void 0);
2610
+ }
2611
+ function validateStaticLaneResumes(call) {
2612
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
2613
+ const lanes = arrayElements(args[0]);
2614
+ const errors = [];
2615
+ for (let laneIndex = 0; laneIndex < lanes.length; laneIndex++) {
2616
+ const lane = lanes[laneIndex];
2617
+ if (astNode(lane) && lane.type === "SpreadElement") break;
2618
+ if (!staticLane(lane)) continue;
2619
+ const first = arrayElements(directObjectPropertyValue(lane, "stages"))[0];
2620
+ if (!astNode(first)) continue;
2621
+ const property = finalStaticProperty(first, "resume");
2622
+ const resume = property?.kind === "init" ? literalString(property.value) : void 0;
2623
+ if (resume !== void 0 && resume !== "previous") errors.push({ message: `runs.lanes lane ${laneIndex} stage 0 ${LANE_RETAINED_RESUME_ERROR}`, ...nodeLocation(first) });
2600
2624
  }
2601
- return [];
2625
+ return errors;
2602
2626
  }
2603
2627
  function staticChildAgentNode(params) {
2604
2628
  if (!astNode(params) || params.type !== "ObjectExpression" || !Array.isArray(params.properties)) return void 0;
@@ -2613,9 +2637,7 @@ function staticChildAgentNode(params) {
2613
2637
  }
2614
2638
  function validateStaticChildAgents(call, agentNameError) {
2615
2639
  const args = Array.isArray(call.arguments) ? call.arguments : [];
2616
- const elements = (node) => astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
2617
- const staticLane = (lane) => astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties) && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== void 0);
2618
- const children = directRunsCall(call, "run") ? [{ owner: "runs.run", params: args[1] }] : directRunsCall(call, "all") ? elements(args[0]).map((params) => ({ owner: "runs.all item", params })) : directRunsCall(call, "lanes") ? elements(args[0]).flatMap((lane) => staticLane(lane) ? elements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : []) : [];
2640
+ const children = directRunsCall(call, "run") ? [{ owner: "runs.run", params: args[1] }] : directRunsCall(call, "all") ? arrayElements(args[0]).map((params) => ({ owner: "runs.all item", params })) : directRunsCall(call, "lanes") ? arrayElements(args[0]).flatMap((lane) => staticLane(lane) ? arrayElements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : []) : [];
2619
2641
  const errors = [];
2620
2642
  for (const child of children) {
2621
2643
  const agentNode = staticChildAgentNode(child.params);
@@ -2627,8 +2649,7 @@ function validateStaticChildAgents(call, agentNameError) {
2627
2649
  }
2628
2650
  function directRunsAllKeys(call) {
2629
2651
  const args = Array.isArray(call.arguments) ? call.arguments : [];
2630
- const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
2631
- return items.flatMap((item) => {
2652
+ return arrayElements(args[0]).flatMap((item) => {
2632
2653
  if (!astNode(item)) return [];
2633
2654
  const keyNode = directObjectPropertyValue(item, "key");
2634
2655
  const key = literalString(keyNode);
@@ -2807,15 +2828,14 @@ ${script}
2807
2828
  errors.push({ message: `${subject}; every runs.all item needs a stable key, for example runs.all([{ key: "review", agent, task }]).`, ...nodeLocation(item.node) });
2808
2829
  }
2809
2830
  const args = Array.isArray(node.arguments) ? node.arguments : [];
2810
- if (astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements)) {
2811
- for (const item of args[0].elements) if (astNode(item)) {
2812
- errors.push(...validateStaticBaseRef(item, "runs.all item"));
2813
- const message = definitelyNonJson(item);
2814
- if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
2815
- }
2831
+ for (const item of arrayElements(args[0])) if (astNode(item)) {
2832
+ errors.push(...validateStaticBaseRef(item, "runs.all item"));
2833
+ const message = definitelyNonJson(item);
2834
+ if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
2816
2835
  }
2817
2836
  }
2818
2837
  if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
2838
+ if (directRunsCall(node, "lanes") && !runsRebound) errors.push(...validateStaticLaneResumes(node));
2819
2839
  if (agentNameError) errors.push(...validateStaticChildAgents(node, agentNameError));
2820
2840
  const boundaryValue = node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "emit" && Array.isArray(node.arguments) && astNode(node.arguments[0]) ? node.arguments[0] : node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "MemberExpression" && astNode(node.callee.object) && node.callee.object.type === "Identifier" && node.callee.object.name === "state" && astNode(node.callee.property) && node.callee.property.type === "Identifier" && node.callee.property.name === "set" && Array.isArray(node.arguments) && astNode(node.arguments[1]) ? node.arguments[1] : void 0;
2821
2841
  if (boundaryValue) {
@@ -2839,7 +2859,7 @@ ${script}
2839
2859
  const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
2840
2860
  if (keys.size === 0) continue;
2841
2861
  const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
2842
- const itemCount = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements.length : 0;
2862
+ const itemCount = arrayElements(args[0]).length;
2843
2863
  const arrayResultShape = Array.from({ length: itemCount });
2844
2864
  for (const later of laterStatements) {
2845
2865
  walkAstWithoutShadowedIdentifier(later, name, (node) => {
@@ -2985,6 +3005,9 @@ async function runWorkflowScript(options) {
2985
3005
  let acceptanceRecoveryBarrier;
2986
3006
  let settled = false;
2987
3007
  let finishing = false;
3008
+ let draining = false;
3009
+ let onDrained;
3010
+ const acquiredLaunches = /* @__PURE__ */ new Set();
2988
3011
  let assemblyAbortRequested = false;
2989
3012
  let assemblyFlushTimer;
2990
3013
  let abortError;
@@ -3025,6 +3048,12 @@ async function runWorkflowScript(options) {
3025
3048
  const recordAcceptanceRecoveryBarrier = (key, result) => {
3026
3049
  if (isAcceptanceMetadataRecovery(result)) acceptanceRecoveryBarrier = { key };
3027
3050
  };
3051
+ const drainIfIdle = () => {
3052
+ if (!onDrained || [...launches.keys()].some((key) => !children.has(key))) return;
3053
+ const done = onDrained;
3054
+ onDrained = void 0;
3055
+ done();
3056
+ };
3028
3057
  const stopChild = (key, message = `Workflow child '${key}' stopped.`) => {
3029
3058
  if (!launches.has(key) || children.has(key)) return false;
3030
3059
  stoppedLaunches.add(key);
@@ -3042,8 +3071,19 @@ async function runWorkflowScript(options) {
3042
3071
  error: message
3043
3072
  });
3044
3073
  traceChanged();
3074
+ drainIfIdle();
3045
3075
  return true;
3046
3076
  };
3077
+ const drain = (done) => {
3078
+ if (!draining) {
3079
+ draining = true;
3080
+ onDrained = done;
3081
+ }
3082
+ for (const key of launches.keys()) if (!acquiredLaunches.has(key)) stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
3083
+ const started = [...launches.keys()].filter((key) => !children.has(key)).length;
3084
+ drainIfIdle();
3085
+ return started;
3086
+ };
3047
3087
  const notifyChildSettled = (key, result) => {
3048
3088
  if (result.state === "running" || !options.onChildSettled || !options.workflowRunId) return;
3049
3089
  const outcome = result.ok ? "completed" : result.stopped ? "stopped" : result.detached ? "paused" : "failed";
@@ -3064,6 +3104,7 @@ async function runWorkflowScript(options) {
3064
3104
  }
3065
3105
  };
3066
3106
  options.registerStopChild?.(stopChild);
3107
+ options.registerDrain?.(drain);
3067
3108
  return await new Promise((resolve6, reject) => {
3068
3109
  const finish = (outcome) => {
3069
3110
  if (settled || finishing) return;
@@ -3077,6 +3118,7 @@ async function runWorkflowScript(options) {
3077
3118
  if (settled) return;
3078
3119
  settled = true;
3079
3120
  options.registerStopChild?.(void 0);
3121
+ options.registerDrain?.(void 0);
3080
3122
  if (timer) clearTimeout(timer);
3081
3123
  options.signal?.removeEventListener("abort", onAbort);
3082
3124
  void worker.terminate();
@@ -3200,7 +3242,7 @@ async function runWorkflowScript(options) {
3200
3242
  const respond = (promise2, responsePath, onBoundaryError) => {
3201
3243
  void promise2.then(
3202
3244
  (value) => {
3203
- if (settled) return;
3245
+ if (settled || draining) return;
3204
3246
  const normalized = responsePath ? omitNonJsonWorkflowResultMetadata(value) : omitUndefinedWorkflowValues(value);
3205
3247
  if (!responsePath) {
3206
3248
  worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
@@ -3215,7 +3257,7 @@ async function runWorkflowScript(options) {
3215
3257
  }
3216
3258
  },
3217
3259
  (error) => {
3218
- if (!settled) {
3260
+ if (!settled && !draining) {
3219
3261
  const errorKind = error instanceof Error ? error.workflowErrorKind : void 0;
3220
3262
  worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...isWorkflowScriptFailureKind(errorKind) ? { errorKind } : {} });
3221
3263
  }
@@ -3299,6 +3341,7 @@ async function runWorkflowScript(options) {
3299
3341
  return respond(Promise.reject(error));
3300
3342
  }
3301
3343
  if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.host('${key2}')`))));
3344
+ if (draining) return respond(Promise.reject(new Error(`runs.host('${key2}') refused: the workflow is draining.`)));
3302
3345
  if (!options.host) return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
3303
3346
  if (hostCalls.size >= HOST_STEP_MAX_COUNT) return respond(Promise.reject(new Error(`workflowScript supports at most ${HOST_STEP_MAX_COUNT} runs.host calls.`)));
3304
3347
  const startedAt2 = Date.now();
@@ -3417,7 +3460,7 @@ async function runWorkflowScript(options) {
3417
3460
  return true;
3418
3461
  });
3419
3462
  admission = Promise.resolve().then(() => {
3420
- if (settled || finishing) return;
3463
+ if (settled || finishing || draining) return;
3421
3464
  for (const call of calls) assertRecoveryBarrierAllowsRun(call.key, call.params);
3422
3465
  return options.admit?.(calls, childController.signal);
3423
3466
  });
@@ -3425,6 +3468,7 @@ async function runWorkflowScript(options) {
3425
3468
  }
3426
3469
  let resolvedResumeLineage;
3427
3470
  const promise = admission.then(async () => {
3471
+ if (draining) stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
3428
3472
  if (settled || finishing || stoppedLaunches.has(key)) {
3429
3473
  const reason = childController.signal.reason;
3430
3474
  const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
@@ -3458,6 +3502,7 @@ async function runWorkflowScript(options) {
3458
3502
  const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
3459
3503
  return stoppedChildResult(key, text);
3460
3504
  }
3505
+ acquiredLaunches.add(key);
3461
3506
  const result = await options.launch(key, launchParams, childSignal, { admitted: true, batch: batch !== void 0 });
3462
3507
  const autoResumeParams = setupAbortResumeParams(params, result, childSignal);
3463
3508
  if (!autoResumeParams) return result;
@@ -3487,6 +3532,7 @@ async function runWorkflowScript(options) {
3487
3532
  trace.push(settledEntry);
3488
3533
  traceChanged();
3489
3534
  notifyChildSettled(key, normalized);
3535
+ drainIfIdle();
3490
3536
  return normalized;
3491
3537
  }, (error) => {
3492
3538
  const text = error instanceof Error ? error.message : String(error);
@@ -3497,6 +3543,7 @@ async function runWorkflowScript(options) {
3497
3543
  trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...generatedLaneKey ? { generatedLaneKey } : {}, error: text });
3498
3544
  traceChanged();
3499
3545
  notifyChildSettled(key, failure);
3546
+ drainIfIdle();
3500
3547
  return failure;
3501
3548
  });
3502
3549
  launches.set(key, { fingerprint, promise, observed: callObserved, ...generatedLaneKey ? { generatedLaneKey } : {} });
@@ -7,7 +7,7 @@ import {
7
7
  getAgentDir,
8
8
  getConfigDirName,
9
9
  getProjectConfigDir
10
- } from "./chunk-UX4SCV5N.js";
10
+ } from "./chunk-C3KWLXDH.js";
11
11
  import {
12
12
  TEMP_ROOT_DIR
13
13
  } from "./chunk-JEZOSEWG.js";
@@ -56,7 +56,7 @@ function isMcpServerDefinition(value) {
56
56
  }
57
57
  if (value.requestHeadersCommand !== void 0 && !isRequestHeadersCommand(value.requestHeadersCommand)) return false;
58
58
  if (value.auth !== void 0 && value.auth !== "oauth" && value.auth !== "bearer" && value.auth !== false) return false;
59
- return value.directTools === void 0 || typeof value.directTools === "boolean" || isStringArray(value.directTools);
59
+ return value.directTools === void 0 || typeof value.directTools === "boolean" || value.directTools === "search" || isStringArray(value.directTools);
60
60
  }
61
61
  function isRecord(value) {
62
62
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -705,10 +705,8 @@ function parseServerEntries(value) {
705
705
  function parseSettings(value) {
706
706
  if (!isRecord2(value)) return void 0;
707
707
  const toolPrefix = value.toolPrefix === "server" || value.toolPrefix === "short" || value.toolPrefix === "none" || value.toolPrefix === "mcp" ? value.toolPrefix : void 0;
708
- const directTools = typeof value.directTools === "boolean" ? value.directTools : void 0;
709
708
  const settings = {
710
709
  ...toolPrefix ? { toolPrefix } : {},
711
- ...directTools !== void 0 ? { directTools } : {},
712
710
  ...value.agentPluginPaths !== void 0 ? { agentPluginPaths: value.agentPluginPaths } : {}
713
711
  };
714
712
  return Object.keys(settings).length ? settings : void 0;
@@ -807,7 +805,7 @@ function interpolateEnvRecord(values) {
807
805
  return Object.fromEntries(Object.entries(values).map(([key, value]) => [key, interpolateSecretExpression(value)]));
808
806
  }
809
807
  function interpolateEnvVars(value) {
810
- return value.replace(/\$\{(\w+)\}/g, (_, name) => process.env[name] ?? "").replace(/\$env:(\w+)/g, (_, name) => process.env[name] ?? "").replace(/\{env:(\w+)\}/g, (_, name) => process.env[name] ?? "");
808
+ return value.replace(/\$\{(\w+)(?::-([^}]*))?\}/g, (_, name, fallback) => process.env[name] ?? fallback ?? "").replace(/\$env:(\w+)/g, (_, name) => process.env[name] ?? "").replace(/\{env:(\w+)\}/g, (_, name) => process.env[name] ?? "");
811
809
  }
812
810
  function interpolateSecretExpression(value) {
813
811
  if (value.startsWith("!!")) return interpolateEnvVars(value.slice(1));
@@ -815,9 +813,9 @@ function interpolateSecretExpression(value) {
815
813
  }
816
814
  function getMissingEnvVars(value) {
817
815
  const missing = /* @__PURE__ */ new Set();
818
- for (const match of value.matchAll(/\$\{(\w+)\}|\$env:(\w+)|\{env:(\w+)\}/g)) {
819
- const name = match[1] ?? match[2] ?? match[3];
820
- if (name && process.env[name] === void 0) missing.add(name);
816
+ for (const match of value.matchAll(/\$\{(\w+)(:-[^}]*)?\}|\$env:(\w+)|\{env:(\w+)\}/g)) {
817
+ const name = match[1] ?? match[3] ?? match[4];
818
+ if (name && match[2] === void 0 && process.env[name] === void 0) missing.add(name);
821
819
  }
822
820
  return [...missing];
823
821
  }
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  getProjectSubagentsDir
3
- } from "./chunk-PHZP3KHB.js";
3
+ } from "./chunk-XSDYTXHF.js";
4
4
  import {
5
5
  discoverAgents,
6
6
  formatUnknownAgentError,
7
7
  resolveAgentName,
8
8
  unknownAgentDiagnosticContext
9
- } from "./chunk-UX4SCV5N.js";
9
+ } from "./chunk-C3KWLXDH.js";
10
10
 
11
11
  // src/agents/agent-refinements.ts
12
12
  import { createHash, randomUUID } from "node:crypto";
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  resolveWatchPath,
6
6
  writeAtomicJson
7
- } from "./chunk-UX4SCV5N.js";
7
+ } from "./chunk-C3KWLXDH.js";
8
8
  import {
9
9
  POLL_INTERVAL_MS
10
10
  } from "./chunk-JEZOSEWG.js";
@@ -112,7 +112,21 @@ import { randomUUID } from "node:crypto";
112
112
  var OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
113
113
  var PLACEHOLDER_PATTERN = /\{(?:task|previous|outputs\.([A-Za-z_][A-Za-z0-9_]*))\}/g;
114
114
  var CHILD_FIELDS = ["cwd", "model"];
115
- var TOP_LEVEL_CONTROLS_HINT = " Put worktree and other child controls on the subagent call itself; they apply to every child.";
115
+ var SHARED_CHILD_CONTROLS = /* @__PURE__ */ new Set(["worktree", "baseRef", "context", "skill", "fast", "agentScope", "outputMode", "outputSchema", "agentContract", "acceptance", "gate", "toolBudget", "toolTimeoutMs", "control"]);
116
+ var SCRIPT_CHILD_FIELDS = /* @__PURE__ */ new Set(["key", "label", "phase", "resume", "async", "timeoutMs"]);
117
+ function unsupportedChildFieldAdvice(fields, scripts) {
118
+ const perChild = scripts ? "use workflow: true with runs.all items" : "you need workflow scripts, which disabledFeatures has turned off";
119
+ const advice = [];
120
+ const itemFields = fields.filter((field) => CHILD_FIELDS.includes(field));
121
+ if (itemFields.length > 0) advice.push(`Set ${itemFields.join(", ")} on each item, or on the subagent call itself to give every child the same value.`);
122
+ if (fields.includes("output")) advice.push(`For one shared output, set output on the subagent call itself: the workflow result is written there and each child gets its own file beside it. For exact or different per-child paths, ${perChild}. Do not drop output if you need durable child files.`);
123
+ const shared = fields.filter((field) => SHARED_CHILD_CONTROLS.has(field));
124
+ if (shared.length > 0) advice.push(`Set ${shared.join(", ")} on the subagent call itself to give every child the same value; for different values per child, ${perChild}.`);
125
+ const scriptOnly = fields.filter((field) => SCRIPT_CHILD_FIELDS.has(field));
126
+ if (scriptOnly.length > 0) advice.push(`For per-child ${scriptOnly.join(", ")}, ${perChild}.`);
127
+ advice.push("No child was launched.");
128
+ return advice.join(" ");
129
+ }
116
130
  function isPlainRecord(value) {
117
131
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
118
132
  const prototype = Object.getPrototypeOf(value);
@@ -122,10 +136,10 @@ function nonEmptyString(value, path) {
122
136
  if (typeof value !== "string" || !value.trim()) throw new Error(`${path} must be a non-empty string.`);
123
137
  return value;
124
138
  }
125
- function exactFields(value, path, allowed, hint) {
139
+ function exactFields(value, path, allowed, hint, scripts) {
126
140
  if (!isPlainRecord(value)) throw new Error(`${path} must be an object.`);
127
141
  const unsupported = Object.keys(value).filter((key) => !allowed.includes(key));
128
- if (unsupported.length > 0) throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint}`);
142
+ if (unsupported.length > 0) throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint} ${unsupportedChildFieldAdvice(unsupported, scripts)}`);
129
143
  return value;
130
144
  }
131
145
  function compileTemplate(template, scope) {
@@ -184,11 +198,11 @@ var SETTLE_HELPER = [
184
198
  ' return new Error(label + ": " + children.filter(function (child) { return !child.ok; }).map(function (child) { return child.key + " (" + child.agent + ") failed" + (child.error ? ": " + child.error : ""); }).join("; "));',
185
199
  "}"
186
200
  ].join("\n");
187
- function buildTasksScript(steps, originalTask) {
201
+ function buildTasksScript(steps, originalTask, scripts) {
188
202
  if (!Array.isArray(steps) || steps.length === 0) throw new Error("tasks must be a non-empty array of { agent, task } items.");
189
203
  const children = steps.map((item, index) => {
190
204
  const path = `tasks[${index}]`;
191
- const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], `Each tasks item accepts agent and task, plus optional cwd and model.${TOP_LEVEL_CONTROLS_HINT}`);
205
+ const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], "Each tasks item accepts agent and task, plus optional cwd and model.", scripts);
192
206
  const agent = nonEmptyString(record.agent, `${path}.agent`);
193
207
  const task = nonEmptyString(record.task, `${path}.task`);
194
208
  const taskExpression = compileTemplate(task, {
@@ -219,18 +233,18 @@ function buildChainScript(steps, originalTask) {
219
233
  let stepChildren;
220
234
  let outputName;
221
235
  if (isPlainRecord(step) && Object.hasOwn(step, "parallel")) {
222
- const record = exactFields(step, path, ["parallel"], `A parallel step accepts only parallel; as is supported on sequential steps only.${TOP_LEVEL_CONTROLS_HINT}`);
236
+ const record = exactFields(step, path, ["parallel"], "A parallel step accepts only parallel; as is supported on sequential steps only.", false);
223
237
  const items = record.parallel;
224
238
  if (!Array.isArray(items) || items.length === 0) throw new Error(`${path}.parallel must be a non-empty array of { agent, task } items.`);
225
239
  stepChildren = items.map((item, itemIndex) => {
226
240
  const itemPath = `${path}.parallel[${itemIndex}]`;
227
- const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], `Each parallel item accepts agent and task, plus optional cwd and model.${TOP_LEVEL_CONTROLS_HINT}`);
241
+ const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], "Each parallel item accepts agent and task, plus optional cwd and model.", false);
228
242
  const agent = nonEmptyString(itemRecord.agent, `${itemPath}.agent`);
229
243
  const task = nonEmptyString(itemRecord.task, `${itemPath}.task`);
230
244
  return { key: `step-${number}-${itemIndex + 1}`, agent, fields: childFields(itemRecord, itemPath), taskExpression: compileTemplate(task, { path: `${itemPath}.task`, hasOriginalTask, previous, outputs }) };
231
245
  });
232
246
  } else {
233
- const record = exactFields(step, path, ["agent", "task", "as", ...CHILD_FIELDS], `A sequential step accepts agent, task, as, cwd and model; a parallel step accepts only parallel.${TOP_LEVEL_CONTROLS_HINT}`);
247
+ const record = exactFields(step, path, ["agent", "task", "as", ...CHILD_FIELDS], "A sequential step accepts agent, task, as, cwd and model; a parallel step accepts only parallel.", false);
234
248
  const agent = nonEmptyString(record.agent, `${path}.agent`);
235
249
  let task;
236
250
  if (record.task === void 0) {
@@ -256,8 +270,8 @@ function buildChainScript(steps, originalTask) {
256
270
  lines.push("return { ok: true, children };");
257
271
  return lines.join("\n");
258
272
  }
259
- function buildStructuredWorkflowScript(kind, steps, originalTask) {
260
- return kind === "tasks" ? buildTasksScript(steps, originalTask) : buildChainScript(steps, originalTask);
273
+ function buildStructuredWorkflowScript(kind, steps, originalTask, scripts) {
274
+ return kind === "tasks" ? buildTasksScript(steps, originalTask, scripts) : buildChainScript(steps, originalTask);
261
275
  }
262
276
 
263
277
  // src/workflows/workflow-resources.ts
@@ -375,9 +389,9 @@ function resolveRunCi(args) {
375
389
  }
376
390
  function resolveParallel(args) {
377
391
  const unsupported = Object.keys(args).filter((key) => key !== "tasks");
378
- if (unsupported.length > 0) return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...].${TOP_LEVEL_CONTROLS_HINT}` };
392
+ if (unsupported.length > 0) return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...]. ${unsupportedChildFieldAdvice(unsupported, true)}` };
379
393
  try {
380
- return { script: buildStructuredWorkflowScript("tasks", args.tasks, void 0) };
394
+ return { script: buildStructuredWorkflowScript("tasks", args.tasks, void 0, true) };
381
395
  } catch (error) {
382
396
  return { error: `workflow 'parallel' args.${error instanceof Error ? error.message : String(error)}` };
383
397
  }
@@ -415,7 +429,7 @@ function resolveStructuredWorkflowResource(input) {
415
429
  validatePlainJson(task, "task");
416
430
  }
417
431
  if (jsonByteLength({ [kind]: steps, task }) > MAX_ARGS_BYTES) return { ok: false, error: `${kind} input exceeds ${MAX_ARGS_BYTES} bytes.` };
418
- const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task);
432
+ const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task, false);
419
433
  return { ok: true, resource: issueWorkflowResource(kind, STRUCTURED_WORKFLOW_RESOURCE_VERSION, script) };
420
434
  } catch (error) {
421
435
  return { ok: false, error: error instanceof Error ? error.message.slice(0, 4096) : "Structured workflow resolution failed." };
@@ -11,7 +11,7 @@ import {
11
11
  readStatus,
12
12
  writeAtomicJson,
13
13
  writePrivateAtomicJson
14
- } from "./chunk-UX4SCV5N.js";
14
+ } from "./chunk-C3KWLXDH.js";
15
15
  import {
16
16
  ASYNC_DIR,
17
17
  INTERCOM_DETACH_REQUEST_EVENT,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getAgentDir
3
- } from "./chunk-UX4SCV5N.js";
3
+ } from "./chunk-C3KWLXDH.js";
4
4
  import {
5
5
  TEMP_ARTIFACTS_DIR
6
6
  } from "./chunk-JEZOSEWG.js";
@@ -9,6 +9,7 @@ import {
9
9
  import * as fs from "node:fs";
10
10
  import * as path from "node:path";
11
11
  var CLEANUP_MARKER_FILE = ".last-cleanup";
12
+ var RETAINED_ARTIFACT_DIRS = /* @__PURE__ */ new Set(["handoffs", "worktree-diffs"]);
12
13
  var PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
13
14
  var PROJECT_ARTIFACT_PATHS = [
14
15
  `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/output.md`,
@@ -187,19 +188,25 @@ function cleanupOldArtifacts(dir, maxAgeDays) {
187
188
  }
188
189
  const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
189
190
  const cutoff = now - maxAgeMs;
190
- for (const file of fs.readdirSync(dir)) {
191
- if (file === CLEANUP_MARKER_FILE) continue;
192
- const filePath = path.join(dir, file);
193
- try {
194
- const stat = fs.statSync(filePath);
195
- if (stat.mtimeMs < cutoff) {
196
- fs.unlinkSync(filePath);
197
- }
198
- } catch {
199
- }
191
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
192
+ if (entry.name === CLEANUP_MARKER_FILE || entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)) continue;
193
+ removeOldEntry(path.join(dir, entry.name), cutoff);
200
194
  }
201
195
  fs.writeFileSync(markerPath, String(now));
202
196
  }
197
+ function removeOldEntry(entryPath, cutoff) {
198
+ try {
199
+ const stat = fs.lstatSync(entryPath);
200
+ const old = stat.mtimeMs < cutoff;
201
+ if (!stat.isDirectory()) {
202
+ if (old) fs.unlinkSync(entryPath);
203
+ return;
204
+ }
205
+ for (const name of fs.readdirSync(entryPath)) removeOldEntry(path.join(entryPath, name), cutoff);
206
+ if (old && fs.readdirSync(entryPath).length === 0) fs.rmdirSync(entryPath);
207
+ } catch {
208
+ }
209
+ }
203
210
  function cleanupAllArtifactDirs(maxAgeDays) {
204
211
  cleanupOldArtifacts(TEMP_ARTIFACTS_DIR, maxAgeDays);
205
212
  const sessionsBase = path.join(getAgentDir(), "sessions");
@@ -46,10 +46,10 @@ import {
46
46
  validateModelResponseAliases,
47
47
  withWorkflowChildRunModel,
48
48
  withWorktreeTransaction
49
- } from "./chunk-LGMILZNE.js";
49
+ } from "./chunk-PGU4TZV3.js";
50
50
  import {
51
51
  validateIntercomBridgeConfig
52
- } from "./chunk-KDMFBYFM.js";
52
+ } from "./chunk-ESWW6XSX.js";
53
53
  import {
54
54
  stableJsonDigest
55
55
  } from "./chunk-7F6RKT6W.js";
@@ -80,7 +80,7 @@ import {
80
80
  validateToolBudgetConfig,
81
81
  waitForFileSystemRetry,
82
82
  writeAtomicJson
83
- } from "./chunk-UX4SCV5N.js";
83
+ } from "./chunk-C3KWLXDH.js";
84
84
  import {
85
85
  DIRS,
86
86
  RUNNER_LAUNCHER_NAME_PATTERN,
@@ -4,13 +4,13 @@ import {
4
4
  remoteShellCommand,
5
5
  runBoundedCommand,
6
6
  sshMachineAccess
7
- } from "./chunk-N7B2KD74.js";
7
+ } from "./chunk-6O7YH2QV.js";
8
8
  import {
9
9
  package_default
10
- } from "./chunk-HFTBF7SG.js";
10
+ } from "./chunk-OOE3R7IQ.js";
11
11
  import {
12
12
  ensureSupervisorChannelDir
13
- } from "./chunk-T5V5BRCL.js";
13
+ } from "./chunk-W52LJANO.js";
14
14
  import "./chunk-HXRB42AF.js";
15
15
  import "./chunk-NIXWDZZV.js";
16
16
  import {
@@ -34,7 +34,7 @@ import {
34
34
  resolveRexBinary,
35
35
  rexCommandEnv,
36
36
  rexGlobalArgs
37
- } from "./chunk-UX4SCV5N.js";
37
+ } from "./chunk-C3KWLXDH.js";
38
38
  import "./chunk-JEZOSEWG.js";
39
39
  import "./chunk-YFCK7H2S.js";
40
40
  import "./chunk-QXASAHIA.js";
@@ -1305,17 +1305,22 @@ function createPlacedPiSession(launch) {
1305
1305
  return launch.machine?.provider === "rex" ? createRexPiSession(launch) : createHerdrPiSession(launch);
1306
1306
  }
1307
1307
  function createPlacementAwareChildSessionFactory(local, createRemote = createPlacedPiSession) {
1308
- const remote = /* @__PURE__ */ new Set();
1308
+ const remote = /* @__PURE__ */ new Map();
1309
1309
  return { async create(launch) {
1310
1310
  if (!launch.machine) return local.create(launch);
1311
1311
  serializeHerdrPiLaunch(launch);
1312
1312
  const child = await createRemote(launch);
1313
- remote.add(child);
1313
+ remote.set(child, launch.parentSessionFile);
1314
1314
  return child;
1315
1315
  }, async dispose() {
1316
- await Promise.allSettled([...remote].map((child) => child.dispose()));
1316
+ await Promise.allSettled([...remote.keys()].map((child) => child.dispose()));
1317
1317
  remote.clear();
1318
1318
  await local.dispose();
1319
+ }, async disposeForParent(parentSessionFile) {
1320
+ const matching = [...remote].filter(([, parent]) => parent === parentSessionFile).map(([child]) => child);
1321
+ await Promise.allSettled(matching.map((child) => child.dispose()));
1322
+ for (const child of matching) remote.delete(child);
1323
+ await local.disposeForParent(parentSessionFile);
1319
1324
  } };
1320
1325
  }
1321
1326
  export {
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  requestAsyncStop
3
- } from "./chunk-7MAE3DJV.js";
3
+ } from "./chunk-VFUFOZBU.js";
4
4
  import "./chunk-NIXWDZZV.js";
5
- import "./chunk-UX4SCV5N.js";
5
+ import "./chunk-C3KWLXDH.js";
6
6
  import "./chunk-JEZOSEWG.js";
7
7
  import "./chunk-YFCK7H2S.js";
8
8
  import "./chunk-QXASAHIA.js";
package/bundle/index.js CHANGED
@@ -17,7 +17,7 @@ function readInstalledPackageVersion() {
17
17
  var loadedPackageVersion = readInstalledPackageVersion();
18
18
 
19
19
  // index.ts
20
- var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-DV2NCNPR.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-3UZ5FVVJ.js")).default;
20
+ var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-JLDQ6YUR.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-DGTZKYIE.js")).default;
21
21
  function registerSubagentExtension(pi) {
22
22
  const installedVersion = readInstalledPackageVersion();
23
23
  if (installedVersion !== loadedPackageVersion) {
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  resolveIntercomSessionTarget
3
- } from "./chunk-KDMFBYFM.js";
3
+ } from "./chunk-ESWW6XSX.js";
4
4
  import "./chunk-7F6RKT6W.js";
5
- import "./chunk-UX4SCV5N.js";
5
+ import "./chunk-C3KWLXDH.js";
6
6
  import "./chunk-JEZOSEWG.js";
7
7
  import "./chunk-YFCK7H2S.js";
8
8
  import "./chunk-QXASAHIA.js";