pi-subagents 0.86.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 (86) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-7QA7ZA46.js → chunk-2D2DQGC2.js} +9 -9
  5. package/bundle/{chunk-UR7OW5S7.js → chunk-2NY5PCKQ.js} +11 -5
  6. package/bundle/{chunk-PYOAIN3V.js → chunk-3CVOAS77.js} +2 -2
  7. package/bundle/{chunk-YK3QYNLE.js → chunk-6O7YH2QV.js} +1 -1
  8. package/bundle/{chunk-ZJJCPV3L.js → chunk-AIL46SZU.js} +8 -6
  9. package/bundle/{chunk-S2Q75LP3.js → chunk-BFF6YDK6.js} +1 -1
  10. package/bundle/{chunk-QGO6HXHG.js → chunk-C3KWLXDH.js} +79 -63
  11. package/bundle/{chunk-NAFLUJ26.js → chunk-C5QWQSSM.js} +1 -1
  12. package/bundle/{chunk-O3YH7XIY.js → chunk-DGTZKYIE.js} +25 -24
  13. package/bundle/{chunk-77ASNIEM.js → chunk-ESWW6XSX.js} +1 -1
  14. package/bundle/{chunk-BWC2LVII.js → chunk-EYGBK6CE.js} +166 -60
  15. package/bundle/{chunk-3RKFH2UZ.js → chunk-HDICKROY.js} +5 -5
  16. package/bundle/{chunk-QM3JGE4W.js → chunk-JLDQ6YUR.js} +12 -12
  17. package/bundle/{chunk-A637IMAO.js → chunk-LFKMM3UH.js} +2 -2
  18. package/bundle/{chunk-WN2E5XHN.js → chunk-LZKVUWIY.js} +4 -4
  19. package/bundle/{chunk-6VD7BGIC.js → chunk-M2VBGET6.js} +2 -2
  20. package/bundle/{chunk-7ZUFN6ME.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-7ADDXUGF.js → chunk-OTLDAYEQ.js} +5 -5
  22. package/bundle/{chunk-2IYBCYFU.js → chunk-OZCPYJEY.js} +75 -33
  23. package/bundle/{chunk-GJGTMLPE.js → chunk-PGU4TZV3.js} +79 -32
  24. package/bundle/{chunk-374MZFF4.js → chunk-SIAQXPJ4.js} +6 -8
  25. package/bundle/{chunk-LGINOOY5.js → chunk-USRX7QXD.js} +2 -2
  26. package/bundle/{chunk-5H4BICQZ.js → chunk-VFUFOZBU.js} +1 -1
  27. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  28. package/bundle/{chunk-ZPY5QZCS.js → chunk-W52LJANO.js} +1 -1
  29. package/bundle/{chunk-GRJHIXYF.js → chunk-XSDYTXHF.js} +18 -11
  30. package/bundle/{chunk-BGXEAYUM.js → chunk-XV7RTWTS.js} +3 -3
  31. package/bundle/{chunk-BU6PFPVX.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 +3 -3
  39. package/docs/configuration.md +12 -4
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/tool-reference.md +1 -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/runs/background/async-execution.d.ts +2 -1
  56. package/src/runs/background/async-execution.js +4 -2
  57. package/src/runs/background/runner-aliases.js +15 -0
  58. package/src/runs/background/wait-subscriptions.js +124 -12
  59. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  60. package/src/runs/foreground/async-stop-action.js +9 -1
  61. package/src/runs/foreground/execution.js +1 -0
  62. package/src/runs/foreground/subagent-executor.d.ts +1 -0
  63. package/src/runs/foreground/subagent-executor.js +51 -8
  64. package/src/runs/shared/child-session.d.ts +5 -4
  65. package/src/runs/shared/child-session.js +43 -33
  66. package/src/runs/shared/herdr-placed-run.js +3 -2
  67. package/src/runs/shared/mcp-config-sources.d.ts +2 -1
  68. package/src/runs/shared/mcp-config-sources.js +1 -1
  69. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -1
  70. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -6
  71. package/src/runs/shared/model-resolution.d.ts +19 -4
  72. package/src/runs/shared/model-resolution.js +50 -51
  73. package/src/shared/artifacts.js +25 -13
  74. package/src/shared/pruned-fork.js +2 -2
  75. package/src/shared/types.d.ts +14 -0
  76. package/src/watchdog/model-selection.js +2 -2
  77. package/src/watchdog/review.js +2 -2
  78. package/src/workflows/scripted-workflow.d.ts +2 -0
  79. package/src/workflows/scripted-workflow.js +103 -39
  80. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  81. package/src/workflows/structured-workflow-scripts.js +32 -11
  82. package/src/workflows/workflow-resources.js +4 -4
  83. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  84. package/src/workflows/workflow-resume-claim.js +1 -1
  85. package/src/workflows/workflow-resume.d.ts +1 -1
  86. package/src/workflows/workflow-resume.js +3 -1
@@ -1,7 +1,7 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { createReadOnlyTools, convertToLlm } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
- import { resolveModelCandidate } from "../runs/shared/model-resolution.js";
4
+ import { knownModelProviders, resolveModelCandidate } from "../runs/shared/model-resolution.js";
5
5
  import { agentStreamOptions } from "../shared/agent-stream-options.js";
6
6
  import { opencodeSessionHeaders } from "../shared/opencode-session-headers.js";
7
7
  import { resolveEffectiveThinking, splitKnownThinkingSuffix, THINKING_LEVELS, toModelInfo } from "../shared/model-info.js";
@@ -54,7 +54,7 @@ function resolveReviewThinking(input) {
54
54
  function resolveConfiguredModel(ctx, rawModel) {
55
55
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
56
56
  const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : undefined;
57
- const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider);
57
+ const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry));
58
58
  if (!resolved) {
59
59
  throw new Error(`Configured watchdog model '${rawModel}' did not match exactly one authenticated available model. Use provider/model or configure credentials for the intended provider.`);
60
60
  }
@@ -184,6 +184,8 @@ export interface RunWorkflowScriptOptions {
184
184
  set: (key: string, value: unknown) => void | Promise<void>;
185
185
  };
186
186
  registerStopChild?: (stop: ((key: string, message?: string) => boolean) | undefined) => void;
187
+ /** Drain: stop children that have not started, refuse new launches, and call `onDrained` once every started child has a result. Returns the started-child count. */
188
+ registerDrain?: (drain: ((onDrained: () => void) => number) | undefined) => void;
187
189
  onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
188
190
  onLanePlan?: (lanes: WorkflowLanePlan[]) => void;
189
191
  onEmit?: (emits: unknown[]) => void;
@@ -20,6 +20,7 @@ function validGitRef(ref) {
20
20
  }
21
21
  const requireFromPackage = createRequire(import.meta.url);
22
22
  const WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5_000;
23
+ const WORKFLOW_DRAIN_CHILD_MESSAGE = "Workflow draining; child not started.";
23
24
  function isWorkflowScriptFailureKind(value) {
24
25
  return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
25
26
  }
@@ -718,29 +719,63 @@ function directObjectPropertyValue(node, name) {
718
719
  }
719
720
  return value;
720
721
  }
721
- function validateStaticBaseRef(params, owner) {
722
- if (params.type !== "ObjectExpression" || !Array.isArray(params.properties))
723
- return [];
724
- // Inspect the final definition only. A later spread or unknown key may overwrite it.
725
- for (let index = params.properties.length - 1; index >= 0; index--) {
726
- const property = params.properties[index];
722
+ function arrayElements(node) {
723
+ return astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
724
+ }
725
+ /** The final definition of `name` in an object literal; undefined when a later spread or unknown key may overwrite it. */
726
+ function finalStaticProperty(node, name) {
727
+ if (node.type !== "ObjectExpression" || !Array.isArray(node.properties))
728
+ return undefined;
729
+ for (let index = node.properties.length - 1; index >= 0; index--) {
730
+ const property = node.properties[index];
727
731
  if (!astNode(property) || property.type !== "Property")
728
- return [];
732
+ return undefined;
729
733
  const key = staticPropertyKey(property);
730
734
  if (key === undefined)
731
- return [];
732
- if (key !== "baseRef")
733
- continue;
734
- if (property.kind !== "init" || !astNode(property.value))
735
- return [];
736
- const valueNode = property.value;
737
- const value = literalString(valueNode);
738
- if ((value !== undefined || valueNode.type === "Literal") && !validGitRef(value)) {
739
- return [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }];
740
- }
735
+ return undefined;
736
+ if (key === name)
737
+ return property;
738
+ }
739
+ return undefined;
740
+ }
741
+ function validateStaticBaseRef(params, owner) {
742
+ const property = finalStaticProperty(params, "baseRef");
743
+ if (property?.kind !== "init" || !astNode(property.value))
741
744
  return [];
745
+ const valueNode = property.value;
746
+ const value = literalString(valueNode);
747
+ return (value !== undefined || valueNode.type === "Literal") && !validGitRef(value)
748
+ ? [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }]
749
+ : [];
750
+ }
751
+ // Same text as validateLaneSpecs in workflow-script-worker.cjs; a test compares the two.
752
+ const 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.";
753
+ // A spread or unknown computed key on the lane can replace `stages`.
754
+ function staticLane(lane) {
755
+ return astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties)
756
+ && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== undefined);
757
+ }
758
+ /** The launch-time first-stage resume rule, for lanes written out as literals. */
759
+ function validateStaticLaneResumes(call) {
760
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
761
+ const lanes = arrayElements(args[0]);
762
+ const errors = [];
763
+ for (let laneIndex = 0; laneIndex < lanes.length; laneIndex++) {
764
+ const lane = lanes[laneIndex];
765
+ // A spread shifts every later lane index the runtime reports.
766
+ if (astNode(lane) && lane.type === "SpreadElement")
767
+ break;
768
+ if (!staticLane(lane))
769
+ continue;
770
+ const first = arrayElements(directObjectPropertyValue(lane, "stages"))[0];
771
+ if (!astNode(first))
772
+ continue;
773
+ const property = finalStaticProperty(first, "resume");
774
+ const resume = property?.kind === "init" ? literalString(property.value) : undefined;
775
+ if (resume !== undefined && resume !== "previous")
776
+ errors.push({ message: `runs.lanes lane ${laneIndex} stage 0 ${LANE_RETAINED_RESUME_ERROR}`, ...nodeLocation(first) });
742
777
  }
743
- return [];
778
+ return errors;
744
779
  }
745
780
  // Children with their own cwd, agentScope, or resume resolve agents elsewhere, and a
746
781
  // spread or computed key can replace `agent`; leave those to launch-time resolution.
@@ -761,16 +796,12 @@ function staticChildAgentNode(params) {
761
796
  }
762
797
  function validateStaticChildAgents(call, agentNameError) {
763
798
  const args = Array.isArray(call.arguments) ? call.arguments : [];
764
- const elements = (node) => astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
765
- // A spread or unknown computed key on the lane can replace `stages`.
766
- const staticLane = (lane) => astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties)
767
- && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== undefined);
768
799
  const children = directRunsCall(call, "run")
769
800
  ? [{ owner: "runs.run", params: args[1] }]
770
801
  : directRunsCall(call, "all")
771
- ? elements(args[0]).map((params) => ({ owner: "runs.all item", params }))
802
+ ? arrayElements(args[0]).map((params) => ({ owner: "runs.all item", params }))
772
803
  : directRunsCall(call, "lanes")
773
- ? elements(args[0]).flatMap((lane) => staticLane(lane) ? elements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : [])
804
+ ? arrayElements(args[0]).flatMap((lane) => staticLane(lane) ? arrayElements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : [])
774
805
  : [];
775
806
  const errors = [];
776
807
  for (const child of children) {
@@ -784,8 +815,7 @@ function validateStaticChildAgents(call, agentNameError) {
784
815
  }
785
816
  function directRunsAllKeys(call) {
786
817
  const args = Array.isArray(call.arguments) ? call.arguments : [];
787
- const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
788
- return items.flatMap((item) => {
818
+ return arrayElements(args[0]).flatMap((item) => {
789
819
  if (!astNode(item))
790
820
  return [];
791
821
  const keyNode = directObjectPropertyValue(item, "key");
@@ -1021,18 +1051,18 @@ export function validateWorkflowScript(script, options = {}) {
1021
1051
  errors.push({ message: `${subject}; every runs.all item needs a stable key, for example runs.all([{ key: "review", agent, task }]).`, ...nodeLocation(item.node) });
1022
1052
  }
1023
1053
  const args = Array.isArray(node.arguments) ? node.arguments : [];
1024
- if (astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements)) {
1025
- for (const item of args[0].elements)
1026
- if (astNode(item)) {
1027
- errors.push(...validateStaticBaseRef(item, "runs.all item"));
1028
- const message = definitelyNonJson(item);
1029
- if (message)
1030
- errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
1031
- }
1032
- }
1054
+ for (const item of arrayElements(args[0]))
1055
+ if (astNode(item)) {
1056
+ errors.push(...validateStaticBaseRef(item, "runs.all item"));
1057
+ const message = definitelyNonJson(item);
1058
+ if (message)
1059
+ errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
1060
+ }
1033
1061
  }
1034
1062
  if (directRunsCall(node, "host"))
1035
1063
  errors.push(...validateStaticHostCall(node));
1064
+ if (directRunsCall(node, "lanes") && !runsRebound)
1065
+ errors.push(...validateStaticLaneResumes(node));
1036
1066
  if (agentNameError)
1037
1067
  errors.push(...validateStaticChildAgents(node, agentNameError));
1038
1068
  const boundaryValue = node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "emit" && Array.isArray(node.arguments) && astNode(node.arguments[0])
@@ -1068,7 +1098,7 @@ export function validateWorkflowScript(script, options = {}) {
1068
1098
  if (keys.size === 0)
1069
1099
  continue;
1070
1100
  const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
1071
- const itemCount = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements.length : 0;
1101
+ const itemCount = arrayElements(args[0]).length;
1072
1102
  const arrayResultShape = Array.from({ length: itemCount });
1073
1103
  for (const later of laterStatements) {
1074
1104
  walkAstWithoutShadowedIdentifier(later, name, (node) => {
@@ -1243,6 +1273,10 @@ export async function runWorkflowScript(options) {
1243
1273
  let acceptanceRecoveryBarrier;
1244
1274
  let settled = false;
1245
1275
  let finishing = false;
1276
+ let draining = false;
1277
+ let onDrained;
1278
+ // Keys past the concurrency semaphore: a drain lets these finish and stops the rest.
1279
+ const acquiredLaunches = new Set();
1246
1280
  let assemblyAbortRequested = false;
1247
1281
  let assemblyFlushTimer;
1248
1282
  let abortError;
@@ -1293,6 +1327,13 @@ export async function runWorkflowScript(options) {
1293
1327
  if (isAcceptanceMetadataRecovery(result))
1294
1328
  acceptanceRecoveryBarrier = { key };
1295
1329
  };
1330
+ const drainIfIdle = () => {
1331
+ if (!onDrained || [...launches.keys()].some((key) => !children.has(key)))
1332
+ return;
1333
+ const done = onDrained;
1334
+ onDrained = undefined;
1335
+ done();
1336
+ };
1296
1337
  const stopChild = (key, message = `Workflow child '${key}' stopped.`) => {
1297
1338
  if (!launches.has(key) || children.has(key))
1298
1339
  return false;
@@ -1311,8 +1352,21 @@ export async function runWorkflowScript(options) {
1311
1352
  error: message,
1312
1353
  });
1313
1354
  traceChanged();
1355
+ drainIfIdle();
1314
1356
  return true;
1315
1357
  };
1358
+ const drain = (done) => {
1359
+ if (!draining) {
1360
+ draining = true;
1361
+ onDrained = done;
1362
+ }
1363
+ for (const key of launches.keys())
1364
+ if (!acquiredLaunches.has(key))
1365
+ stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
1366
+ const started = [...launches.keys()].filter((key) => !children.has(key)).length;
1367
+ drainIfIdle();
1368
+ return started;
1369
+ };
1316
1370
  const notifyChildSettled = (key, result) => {
1317
1371
  if (result.state === "running" || !options.onChildSettled || !options.workflowRunId)
1318
1372
  return;
@@ -1341,6 +1395,7 @@ export async function runWorkflowScript(options) {
1341
1395
  }
1342
1396
  };
1343
1397
  options.registerStopChild?.(stopChild);
1398
+ options.registerDrain?.(drain);
1344
1399
  return await new Promise((resolve, reject) => {
1345
1400
  const finish = (outcome) => {
1346
1401
  if (settled || finishing)
@@ -1356,6 +1411,7 @@ export async function runWorkflowScript(options) {
1356
1411
  return;
1357
1412
  settled = true;
1358
1413
  options.registerStopChild?.(undefined);
1414
+ options.registerDrain?.(undefined);
1359
1415
  if (timer)
1360
1416
  clearTimeout(timer);
1361
1417
  options.signal?.removeEventListener("abort", onAbort);
@@ -1518,7 +1574,8 @@ export async function runWorkflowScript(options) {
1518
1574
  return finish({ error: abortError ?? new Error("Workflow context was replaced or reloaded.") });
1519
1575
  const respond = (promise, responsePath, onBoundaryError) => {
1520
1576
  void promise.then((value) => {
1521
- if (settled)
1577
+ // While draining, the script gets no answers: a refusal it throws on would abort the started children.
1578
+ if (settled || draining)
1522
1579
  return;
1523
1580
  const normalized = responsePath ? omitNonJsonWorkflowResultMetadata(value) : omitUndefinedWorkflowValues(value);
1524
1581
  if (!responsePath) {
@@ -1534,7 +1591,7 @@ export async function runWorkflowScript(options) {
1534
1591
  worker.postMessage({ type: "response", callId: message.callId, ok: false, error: `${responsePath} must contain only JSON data before it can be returned from workflowScript. Return a plain projection such as { runId, ok, output }. ${error instanceof Error ? error.message : String(error)}` });
1535
1592
  }
1536
1593
  }, (error) => {
1537
- if (!settled) {
1594
+ if (!settled && !draining) {
1538
1595
  const errorKind = error instanceof Error ? error.workflowErrorKind : undefined;
1539
1596
  worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...(isWorkflowScriptFailureKind(errorKind) ? { errorKind } : {}) });
1540
1597
  }
@@ -1633,6 +1690,8 @@ export async function runWorkflowScript(options) {
1633
1690
  }
1634
1691
  if (acceptanceRecoveryBarrier)
1635
1692
  return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.host('${key}')`))));
1693
+ if (draining)
1694
+ return respond(Promise.reject(new Error(`runs.host('${key}') refused: the workflow is draining.`)));
1636
1695
  if (!options.host)
1637
1696
  return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
1638
1697
  if (hostCalls.size >= HOST_STEP_MAX_COUNT)
@@ -1780,7 +1839,7 @@ export async function runWorkflowScript(options) {
1780
1839
  return true;
1781
1840
  });
1782
1841
  admission = Promise.resolve().then(() => {
1783
- if (settled || finishing)
1842
+ if (settled || finishing || draining)
1784
1843
  return;
1785
1844
  for (const call of calls)
1786
1845
  assertRecoveryBarrierAllowsRun(call.key, call.params);
@@ -1791,6 +1850,8 @@ export async function runWorkflowScript(options) {
1791
1850
  }
1792
1851
  let resolvedResumeLineage;
1793
1852
  const promise = admission.then(async () => {
1853
+ if (draining)
1854
+ stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
1794
1855
  if (settled || finishing || stoppedLaunches.has(key)) {
1795
1856
  const reason = childController.signal.reason;
1796
1857
  const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
@@ -1836,6 +1897,7 @@ export async function runWorkflowScript(options) {
1836
1897
  const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
1837
1898
  return stoppedChildResult(key, text);
1838
1899
  }
1900
+ acquiredLaunches.add(key);
1839
1901
  const result = await options.launch(key, launchParams, childSignal, { admitted: true, batch: batch !== undefined });
1840
1902
  const autoResumeParams = setupAbortResumeParams(params, result, childSignal);
1841
1903
  if (!autoResumeParams)
@@ -1870,6 +1932,7 @@ export async function runWorkflowScript(options) {
1870
1932
  trace.push(settledEntry);
1871
1933
  traceChanged();
1872
1934
  notifyChildSettled(key, normalized);
1935
+ drainIfIdle();
1873
1936
  return normalized;
1874
1937
  }, (error) => {
1875
1938
  const text = error instanceof Error ? error.message : String(error);
@@ -1881,6 +1944,7 @@ export async function runWorkflowScript(options) {
1881
1944
  trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), error: text });
1882
1945
  traceChanged();
1883
1946
  notifyChildSettled(key, failure);
1947
+ drainIfIdle();
1884
1948
  return failure;
1885
1949
  });
1886
1950
  launches.set(key, { fingerprint, promise, observed: callObserved, ...(generatedLaneKey ? { generatedLaneKey } : {}) });
@@ -4,7 +4,8 @@
4
4
  * and never becomes code. Scripts run on the ordinary workflow runtime.
5
5
  */
6
6
  export type StructuredWorkflowKind = "tasks" | "chain";
7
- export declare const TOP_LEVEL_CONTROLS_HINT = " Put worktree and other child controls on the subagent call itself; they apply to every child.";
7
+ /** Recovery advice per rejected field, so a retry keeps the caller's intent instead of dropping the field. */
8
+ export declare function unsupportedChildFieldAdvice(fields: readonly string[], scripts: boolean): string;
8
9
  export declare function isPlainRecord(value: unknown): value is Record<string, unknown>;
9
- /** Validate exact data shapes and expand them into a package-owned workflow script. */
10
- export declare function buildStructuredWorkflowScript(kind: StructuredWorkflowKind, steps: unknown, originalTask: string | undefined): string;
10
+ /** Validate exact data shapes and expand them into a package-owned workflow script. `scripts` is true only for the named `parallel` workflow; top-level tasks and chain exist only when workflow scripts are disabled. */
11
+ export declare function buildStructuredWorkflowScript(kind: StructuredWorkflowKind, steps: unknown, originalTask: string | undefined, scripts: boolean): string;
@@ -7,7 +7,28 @@ const OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
7
7
  const PLACEHOLDER_PATTERN = /\{(?:task|previous|outputs\.([A-Za-z_][A-Za-z0-9_]*))\}/g;
8
8
  /** Optional per-child launch fields copied verbatim onto the generated runs.all item. */
9
9
  const CHILD_FIELDS = ["cwd", "model"];
10
- export const TOP_LEVEL_CONTROLS_HINT = " Put worktree and other child controls on the subagent call itself; they apply to every child.";
10
+ // Outer subagent-call controls that default onto every workflow child (docs/workflows.md); output gets its own advice.
11
+ const SHARED_CHILD_CONTROLS = new Set(["worktree", "baseRef", "context", "skill", "fast", "agentScope", "outputMode", "outputSchema", "agentContract", "acceptance", "gate", "toolBudget", "toolTimeoutMs", "control"]);
12
+ // runs.run/runs.all child fields whose outer-call form is missing or means something else (async and timeoutMs apply to the workflow).
13
+ const SCRIPT_CHILD_FIELDS = new Set(["key", "label", "phase", "resume", "async", "timeoutMs"]);
14
+ /** Recovery advice per rejected field, so a retry keeps the caller's intent instead of dropping the field. */
15
+ export function unsupportedChildFieldAdvice(fields, scripts) {
16
+ const perChild = scripts ? "use workflow: true with runs.all items" : "you need workflow scripts, which disabledFeatures has turned off";
17
+ const advice = [];
18
+ const itemFields = fields.filter((field) => CHILD_FIELDS.includes(field));
19
+ if (itemFields.length > 0)
20
+ advice.push(`Set ${itemFields.join(", ")} on each item, or on the subagent call itself to give every child the same value.`);
21
+ if (fields.includes("output"))
22
+ 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.`);
23
+ const shared = fields.filter((field) => SHARED_CHILD_CONTROLS.has(field));
24
+ if (shared.length > 0)
25
+ advice.push(`Set ${shared.join(", ")} on the subagent call itself to give every child the same value; for different values per child, ${perChild}.`);
26
+ const scriptOnly = fields.filter((field) => SCRIPT_CHILD_FIELDS.has(field));
27
+ if (scriptOnly.length > 0)
28
+ advice.push(`For per-child ${scriptOnly.join(", ")}, ${perChild}.`);
29
+ advice.push("No child was launched.");
30
+ return advice.join(" ");
31
+ }
11
32
  export function isPlainRecord(value) {
12
33
  if (!value || typeof value !== "object" || Array.isArray(value))
13
34
  return false;
@@ -19,12 +40,12 @@ function nonEmptyString(value, path) {
19
40
  throw new Error(`${path} must be a non-empty string.`);
20
41
  return value;
21
42
  }
22
- function exactFields(value, path, allowed, hint) {
43
+ function exactFields(value, path, allowed, hint, scripts) {
23
44
  if (!isPlainRecord(value))
24
45
  throw new Error(`${path} must be an object.`);
25
46
  const unsupported = Object.keys(value).filter((key) => !allowed.includes(key));
26
47
  if (unsupported.length > 0)
27
- throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint}`);
48
+ throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint} ${unsupportedChildFieldAdvice(unsupported, scripts)}`);
28
49
  return value;
29
50
  }
30
51
  /** Single pass: text inserted for a placeholder is never scanned again. Unrecognized brace text stays literal. */
@@ -93,12 +114,12 @@ const SETTLE_HELPER = [
93
114
  " 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(\"; \"));",
94
115
  "}",
95
116
  ].join("\n");
96
- function buildTasksScript(steps, originalTask) {
117
+ function buildTasksScript(steps, originalTask, scripts) {
97
118
  if (!Array.isArray(steps) || steps.length === 0)
98
119
  throw new Error("tasks must be a non-empty array of { agent, task } items.");
99
120
  const children = steps.map((item, index) => {
100
121
  const path = `tasks[${index}]`;
101
- 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}`);
122
+ const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], "Each tasks item accepts agent and task, plus optional cwd and model.", scripts);
102
123
  const agent = nonEmptyString(record.agent, `${path}.agent`);
103
124
  const task = nonEmptyString(record.task, `${path}.task`);
104
125
  const taskExpression = compileTemplate(task, {
@@ -132,20 +153,20 @@ function buildChainScript(steps, originalTask) {
132
153
  let stepChildren;
133
154
  let outputName;
134
155
  if (isPlainRecord(step) && Object.hasOwn(step, "parallel")) {
135
- const record = exactFields(step, path, ["parallel"], `A parallel step accepts only parallel; as is supported on sequential steps only.${TOP_LEVEL_CONTROLS_HINT}`);
156
+ const record = exactFields(step, path, ["parallel"], "A parallel step accepts only parallel; as is supported on sequential steps only.", false);
136
157
  const items = record.parallel;
137
158
  if (!Array.isArray(items) || items.length === 0)
138
159
  throw new Error(`${path}.parallel must be a non-empty array of { agent, task } items.`);
139
160
  stepChildren = items.map((item, itemIndex) => {
140
161
  const itemPath = `${path}.parallel[${itemIndex}]`;
141
- 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}`);
162
+ const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], "Each parallel item accepts agent and task, plus optional cwd and model.", false);
142
163
  const agent = nonEmptyString(itemRecord.agent, `${itemPath}.agent`);
143
164
  const task = nonEmptyString(itemRecord.task, `${itemPath}.task`);
144
165
  return { key: `step-${number}-${itemIndex + 1}`, agent, fields: childFields(itemRecord, itemPath), taskExpression: compileTemplate(task, { path: `${itemPath}.task`, hasOriginalTask, previous, outputs }) };
145
166
  });
146
167
  }
147
168
  else {
148
- 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}`);
169
+ 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);
149
170
  const agent = nonEmptyString(record.agent, `${path}.agent`);
150
171
  let task;
151
172
  if (record.task === undefined) {
@@ -173,7 +194,7 @@ function buildChainScript(steps, originalTask) {
173
194
  lines.push("return { ok: true, children };");
174
195
  return lines.join("\n");
175
196
  }
176
- /** Validate exact data shapes and expand them into a package-owned workflow script. */
177
- export function buildStructuredWorkflowScript(kind, steps, originalTask) {
178
- return kind === "tasks" ? buildTasksScript(steps, originalTask) : buildChainScript(steps, originalTask);
197
+ /** Validate exact data shapes and expand them into a package-owned workflow script. `scripts` is true only for the named `parallel` workflow; top-level tasks and chain exist only when workflow scripts are disabled. */
198
+ export function buildStructuredWorkflowScript(kind, steps, originalTask, scripts) {
199
+ return kind === "tasks" ? buildTasksScript(steps, originalTask, scripts) : buildChainScript(steps, originalTask);
179
200
  }
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { stableJsonDigest } from "../shared/launch-contract.js";
3
3
  import { createWorkflowResourcePermit, } from "../shared/workflow-child-permit.js";
4
- import { buildStructuredWorkflowScript, isPlainRecord, TOP_LEVEL_CONTROLS_HINT } from "./structured-workflow-scripts.js";
4
+ import { buildStructuredWorkflowScript, isPlainRecord, unsupportedChildFieldAdvice } from "./structured-workflow-scripts.js";
5
5
  const RESOURCE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
6
6
  export const MAX_ARGS_BYTES = 16 * 1024;
7
7
  export const MAX_ARGS_FIELDS = 16;
@@ -152,9 +152,9 @@ function resolveRunCi(args) {
152
152
  function resolveParallel(args) {
153
153
  const unsupported = Object.keys(args).filter((key) => key !== "tasks");
154
154
  if (unsupported.length > 0)
155
- return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...].${TOP_LEVEL_CONTROLS_HINT}` };
155
+ return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...]. ${unsupportedChildFieldAdvice(unsupported, true)}` };
156
156
  try {
157
- return { script: buildStructuredWorkflowScript("tasks", args.tasks, undefined) };
157
+ return { script: buildStructuredWorkflowScript("tasks", args.tasks, undefined, true) };
158
158
  }
159
159
  catch (error) {
160
160
  return { error: `workflow 'parallel' args.${error instanceof Error ? error.message : String(error)}` };
@@ -204,7 +204,7 @@ export function resolveStructuredWorkflowResource(input) {
204
204
  }
205
205
  if (jsonByteLength({ [kind]: steps, task }) > MAX_ARGS_BYTES)
206
206
  return { ok: false, error: `${kind} input exceeds ${MAX_ARGS_BYTES} bytes.` };
207
- const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task);
207
+ const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task, false);
208
208
  return { ok: true, resource: issueWorkflowResource(kind, STRUCTURED_WORKFLOW_RESOURCE_VERSION, script) };
209
209
  }
210
210
  catch (error) {
@@ -54,6 +54,8 @@ export declare function resumedRunStarted(sourceAsyncDir: string, newRunId: stri
54
54
  export declare function workflowResumeClaimState(asyncDir: string, options?: {
55
55
  liveness?: ClaimLiveness;
56
56
  }): WorkflowResumeClaimState;
57
+ /** Creates the claim file only if none exists, with its whole body in place at once. */
58
+ export declare function createClaimFile(filePath: string, claim: object): boolean;
57
59
  /**
58
60
  * Claims the right to continue the stopped run in `asyncDir` as `newRunId`. A dead claimant is
59
61
  * superseded by the next generation file; of several takers, the one whose exclusive create
@@ -93,7 +93,7 @@ export function workflowResumeClaimState(asyncDir, options = {}) {
93
93
  return claimantLiveness(top.filePath, top.claim, options.liveness) === "dead" ? { kind: "none" } : { kind: "busy", pid: top.claim.pid, newRunId: top.claim.newRunId };
94
94
  }
95
95
  /** Creates the claim file only if none exists, with its whole body in place at once. */
96
- function createClaimFile(filePath, claim) {
96
+ export function createClaimFile(filePath, claim) {
97
97
  const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
98
98
  try {
99
99
  fs.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
@@ -1,5 +1,5 @@
1
1
  type WorkflowResumeTrigger = "auto" | "manual";
2
- export type WorkflowResumeRefusalCode = "not-owned" | "not-interrupted" | "claim-busy" | "claim-resumed" | "launch-missing" | "launch-invalid" | "structured" | "internal" | "digest" | "authority" | "capacity" | "attempts" | "launch-failed";
2
+ export type WorkflowResumeRefusalCode = "not-owned" | "not-interrupted" | "claim-busy" | "claim-resumed" | "launch-missing" | "launch-invalid" | "structured" | "internal" | "digest" | "authority" | "capacity" | "attempts" | "launch-failed" | "drained";
3
3
  export interface WorkflowResumeRefusalReason {
4
4
  code: WorkflowResumeRefusalCode;
5
5
  reason: string;
@@ -12,7 +12,7 @@ import { isReusableWorkflowStopCause, WORKFLOW_STOP_CAUSE_OWNER_EXITED } from ".
12
12
  /** A run may be resumed again after at most this many resumes that followed Pi exits (auto-resume only). */
13
13
  const MAX_WORKFLOW_RESUME_ATTEMPTS = 3;
14
14
  export function workflowResumeRefusal(code, reason, runId) {
15
- const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority"
15
+ const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority" || code === "drained"
16
16
  ? relaunchByHandText(runId)
17
17
  : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
18
18
  return { code, reason, byHand };
@@ -67,6 +67,8 @@ export function prepareWorkflowResume(input) {
67
67
  const status = readStatus(sourceAsyncDir);
68
68
  if (!status || status.mode !== "workflow" || !isReusableWorkflowStopCause(status.workflow?.stopCause))
69
69
  return refuse("not-interrupted", "not interrupted; pass message to revive one of its children");
70
+ if (status.workflow?.drainRequestedAt !== undefined)
71
+ return refuse("drained", "it was being drained when it was interrupted");
70
72
  // The attempt the resumed run records: only resumes that follow a Pi exit count.
71
73
  const attempt = (status.workflow?.resumeOrigin?.attempt ?? 0) + (status.workflow?.stopCause === WORKFLOW_STOP_CAUSE_OWNER_EXITED ? 1 : 0);
72
74
  if (trigger === "auto" && attempt > MAX_WORKFLOW_RESUME_ATTEMPTS)