@vicary/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-DD22RXYJ.js → chunk-75LVXBSA.js} +166 -60
  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-77ASNIEM.js → chunk-ESWW6XSX.js} +1 -1
  13. package/bundle/{chunk-3RKFH2UZ.js → chunk-HDICKROY.js} +5 -5
  14. package/bundle/{chunk-XOFYXQKZ.js → chunk-HTI7DD5D.js} +2 -2
  15. package/bundle/{chunk-WN2E5XHN.js → chunk-LZKVUWIY.js} +4 -4
  16. package/bundle/{chunk-6VD7BGIC.js → chunk-M2VBGET6.js} +2 -2
  17. package/bundle/{chunk-2DITXA3H.js → chunk-NJTSXIMG.js} +12 -12
  18. package/bundle/{chunk-QFLPV64W.js → chunk-NMYBVCGP.js} +25 -24
  19. package/bundle/{chunk-CJHFDQFJ.js → chunk-O7A26O6B.js} +8 -6
  20. package/bundle/{chunk-7ZUFN6ME.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-GJGTMLPE.js → chunk-PGU4TZV3.js} +79 -32
  22. package/bundle/{chunk-WHC2XHGF.js → chunk-PUSTU4Q7.js} +75 -33
  23. package/bundle/{chunk-374MZFF4.js → chunk-SIAQXPJ4.js} +6 -8
  24. package/bundle/{chunk-LGINOOY5.js → chunk-USRX7QXD.js} +2 -2
  25. package/bundle/{chunk-5H4BICQZ.js → chunk-VFUFOZBU.js} +1 -1
  26. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  27. package/bundle/{chunk-ZPY5QZCS.js → chunk-W52LJANO.js} +1 -1
  28. package/bundle/{chunk-GRJHIXYF.js → chunk-XSDYTXHF.js} +18 -11
  29. package/bundle/{chunk-BGXEAYUM.js → chunk-XV7RTWTS.js} +3 -3
  30. package/bundle/{chunk-BU6PFPVX.js → chunk-YEXKJJVS.js} +12 -7
  31. package/bundle/{chunk-GLVJMI6R.js → chunk-Z4TR7MK6.js} +5 -5
  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 +2 -2
  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
@@ -10,10 +10,10 @@ import {
10
10
  setInlineWorkflowCoverage,
11
11
  setMainThinkingLevelSource,
12
12
  widgetRenderKey
13
- } from "./chunk-WN2E5XHN.js";
13
+ } from "./chunk-LZKVUWIY.js";
14
14
  import {
15
15
  package_default
16
- } from "./chunk-7ZUFN6ME.js";
16
+ } from "./chunk-OOE3R7IQ.js";
17
17
  import {
18
18
  EXTERNAL_JOB_BRIDGE_REQUEST_DIR,
19
19
  REVIVAL_ORIGIN_FILE,
@@ -29,7 +29,7 @@ import {
29
29
  createWaitSubscriptionManager,
30
30
  deliverSubagentResultIntercomEvent,
31
31
  deriveChildSessionName,
32
- disposeChildSessions,
32
+ disposeChildSessionsForParent,
33
33
  editableAgentConfig,
34
34
  externalJobBridgeEligibility,
35
35
  flattenSubagentToolOptions,
@@ -62,7 +62,7 @@ import {
62
62
  snapshotProviderDiagnostics,
63
63
  workflowResumeClaimState,
64
64
  workflowResumeRefusal
65
- } from "./chunk-DD22RXYJ.js";
65
+ } from "./chunk-75LVXBSA.js";
66
66
  import {
67
67
  SUBAGENT_CHILD_ENV,
68
68
  SUBAGENT_PARENT_SESSION_ENV,
@@ -82,14 +82,14 @@ import {
82
82
  resolvePiSessionId,
83
83
  resolveWaitToolConfig,
84
84
  setDeclarationPinning
85
- } from "./chunk-CJHFDQFJ.js";
85
+ } from "./chunk-O7A26O6B.js";
86
86
  import {
87
87
  deliverAsyncRunStop,
88
88
  ownerConfirmedDead,
89
89
  readSessionMessagesTail,
90
90
  resolveSubagentRunId,
91
91
  restoreForegroundRunHistory
92
- } from "./chunk-UR7OW5S7.js";
92
+ } from "./chunk-2NY5PCKQ.js";
93
93
  import {
94
94
  ASYNC_STATUS_SNAPSHOT_KIND,
95
95
  ASYNC_STATUS_SNAPSHOT_VERSION,
@@ -105,7 +105,7 @@ import {
105
105
  resolveAsyncStatusChild,
106
106
  runLaunchDir,
107
107
  stopStoppableAsyncStatusChildren
108
- } from "./chunk-BGXEAYUM.js";
108
+ } from "./chunk-XV7RTWTS.js";
109
109
  import {
110
110
  CONTACT_SUPERVISOR_TOOL_NAME,
111
111
  NATIVE_SUPERVISOR_TOOL_NAME,
@@ -115,7 +115,7 @@ import {
115
115
  parseSupervisorReplyData,
116
116
  parseSupervisorRequestDetails,
117
117
  topLevelSupervisorTool
118
- } from "./chunk-ZPY5QZCS.js";
118
+ } from "./chunk-W52LJANO.js";
119
119
  import {
120
120
  MODEL_ONLY_TOOL,
121
121
  canRenderComponents,
@@ -130,7 +130,7 @@ import {
130
130
  reportSessionWarning,
131
131
  withCachedUiContext
132
132
  } from "./chunk-HXRB42AF.js";
133
- import "./chunk-NF7IEKBH.js";
133
+ import "./chunk-W2BZS6UC.js";
134
134
  import {
135
135
  disabledFeatureUseError,
136
136
  getActiveAsyncCapacitySnapshot,
@@ -140,7 +140,7 @@ import {
140
140
  resolveDisabledFeatureSurface,
141
141
  resolveMaxActiveAsyncRunsPerSession,
142
142
  resolveScheduledStoreRoot
143
- } from "./chunk-6VD7BGIC.js";
143
+ } from "./chunk-M2VBGET6.js";
144
144
  import {
145
145
  ACTIVE_RUN_INDEX_DIR,
146
146
  MissionNotFoundError,
@@ -191,28 +191,28 @@ import {
191
191
  withWorkflowChildRunModel,
192
192
  writeAsyncResultFile,
193
193
  writeResultIndexForData
194
- } from "./chunk-GJGTMLPE.js";
195
- import "./chunk-5H4BICQZ.js";
194
+ } from "./chunk-PGU4TZV3.js";
195
+ import "./chunk-VFUFOZBU.js";
196
196
  import {
197
197
  shouldUseNativeFsWatch
198
198
  } from "./chunk-NIXWDZZV.js";
199
199
  import {
200
200
  validateIntercomBridgeConfig
201
- } from "./chunk-77ASNIEM.js";
201
+ } from "./chunk-ESWW6XSX.js";
202
202
  import "./chunk-7F6RKT6W.js";
203
- import "./chunk-374MZFF4.js";
203
+ import "./chunk-SIAQXPJ4.js";
204
204
  import "./chunk-CTPAE36Y.js";
205
205
  import {
206
206
  listHerdrProjectPaneRoots,
207
207
  restoreHerdrProjectPaneSnapshots
208
- } from "./chunk-PYOAIN3V.js";
208
+ } from "./chunk-3CVOAS77.js";
209
209
  import "./chunk-7J4ZXMY7.js";
210
210
  import {
211
211
  cleanupAllArtifactDirs,
212
212
  cleanupOldArtifacts,
213
213
  getArtifactPaths,
214
214
  getArtifactsDir
215
- } from "./chunk-GRJHIXYF.js";
215
+ } from "./chunk-XSDYTXHF.js";
216
216
  import {
217
217
  listBackgroundWorkProviders
218
218
  } from "./chunk-XA3DY6UG.js";
@@ -220,12 +220,12 @@ import "./chunk-YYREO77V.js";
220
220
  import "./chunk-UKG4V45O.js";
221
221
  import {
222
222
  registerRuntimeAgentEventListener
223
- } from "./chunk-S2Q75LP3.js";
223
+ } from "./chunk-BFF6YDK6.js";
224
224
  import {
225
225
  clearRuntimeAgentsForPi,
226
226
  listRuntimeAgentConfigs,
227
227
  mergeRuntimeAgents
228
- } from "./chunk-NAFLUJ26.js";
228
+ } from "./chunk-C5QWQSSM.js";
229
229
  import {
230
230
  DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
231
231
  DEFAULT_WAIT_TOOL_NAME,
@@ -268,7 +268,7 @@ import {
268
268
  waitToolName,
269
269
  withSettingsFileLease,
270
270
  writeAtomicJson
271
- } from "./chunk-QGO6HXHG.js";
271
+ } from "./chunk-C3KWLXDH.js";
272
272
  import {
273
273
  DEFAULT_ARTIFACT_CONFIG,
274
274
  DIRS,
@@ -5360,7 +5360,7 @@ function registerSlashCommands(pi, state, options = {}) {
5360
5360
  }
5361
5361
  fleetOpen = true;
5362
5362
  try {
5363
- const { openSubagentFleet } = await import("./chunk-7QA7ZA46.js");
5363
+ const { openSubagentFleet } = await import("./chunk-2D2DQGC2.js");
5364
5364
  await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, inspectorPlugins: () => getInspectorPlugins(pi), resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings });
5365
5365
  } finally {
5366
5366
  fleetOpen = false;
@@ -8765,7 +8765,7 @@ function registerSubagentExtension(pi) {
8765
8765
  const ctx = withLastUiContext((current) => current);
8766
8766
  if (!ctx) return;
8767
8767
  try {
8768
- const { openSubagentFleet } = await import("./chunk-7QA7ZA46.js");
8768
+ const { openSubagentFleet } = await import("./chunk-2D2DQGC2.js");
8769
8769
  await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings, inspectorPlugins: () => getInspectorPlugins(pi) });
8770
8770
  } catch (error) {
8771
8771
  if (isStaleExtensionContextError(error)) {
@@ -8974,7 +8974,7 @@ function registerSubagentExtension(pi) {
8974
8974
  let executor;
8975
8975
  let executorPromise;
8976
8976
  let executorModulePromise;
8977
- const loadExecutorModule = () => executorModulePromise ??= import("./chunk-WHC2XHGF.js");
8977
+ const loadExecutorModule = () => executorModulePromise ??= import("./chunk-PUSTU4Q7.js");
8978
8978
  const getExecutor = () => {
8979
8979
  executorPromise ??= loadExecutorModule().then(({ createSubagentExecutor }) => {
8980
8980
  executor = createSubagentExecutor(executorDeps);
@@ -8988,7 +8988,7 @@ function registerSubagentExtension(pi) {
8988
8988
  modulePreloadTimer = setTimeout(() => {
8989
8989
  loadExecutorModule().catch(() => {
8990
8990
  });
8991
- if (fleetViewEnabled) import("./chunk-7QA7ZA46.js").catch(() => {
8991
+ if (fleetViewEnabled) import("./chunk-2D2DQGC2.js").catch(() => {
8992
8992
  });
8993
8993
  }, MODULE_PRELOAD_DELAY_MS);
8994
8994
  modulePreloadTimer.unref?.();
@@ -9557,13 +9557,14 @@ ${close}` }]
9557
9557
  supervisorChannel.activateTransport();
9558
9558
  });
9559
9559
  pi.on("session_shutdown", async (event) => {
9560
+ const parentSessionFile = state.parentSessionFile ?? void 0;
9560
9561
  sessionSwitchGuard.sessionShutdown(event);
9561
9562
  cancelCompactionResume();
9562
9563
  completionNotifier.sessionShutdown(event?.reason);
9563
9564
  parentWake.sessionShutdown(event?.reason);
9564
9565
  runtimeEntry.cleanup(event?.reason);
9565
9566
  try {
9566
- await disposeChildSessions();
9567
+ await disposeChildSessionsForParent(parentSessionFile);
9567
9568
  } catch (error) {
9568
9569
  console.error("Failed to dispose in-process child sessions:", error);
9569
9570
  }
@@ -8,23 +8,23 @@ import {
8
8
  projectTimeoutRecovery,
9
9
  readAsyncRecoveryDescriptor,
10
10
  utf8Tail
11
- } from "./chunk-BGXEAYUM.js";
11
+ } from "./chunk-XV7RTWTS.js";
12
12
  import {
13
13
  MAX_ARGS_BYTES,
14
14
  MAX_ARGS_DEPTH,
15
15
  MAX_ARGS_FIELDS,
16
16
  MAX_ARGS_ITEMS
17
- } from "./chunk-NF7IEKBH.js";
17
+ } from "./chunk-W2BZS6UC.js";
18
18
  import {
19
19
  fallbackResultPayloadPathForSessionRun,
20
20
  nestedRunScope,
21
21
  resultFilePath,
22
22
  resultPayloadMatchesSessionRun,
23
23
  resultPayloadPathForSessionRun
24
- } from "./chunk-GJGTMLPE.js";
24
+ } from "./chunk-PGU4TZV3.js";
25
25
  import {
26
26
  PROJECT_SUBAGENTS_RELATIVE_DIR
27
- } from "./chunk-GRJHIXYF.js";
27
+ } from "./chunk-XSDYTXHF.js";
28
28
  import {
29
29
  listBackgroundWorkWakeChannels,
30
30
  snapshotBackgroundWork
@@ -40,6 +40,7 @@ import {
40
40
  formatDuration,
41
41
  getAgentDir,
42
42
  getProjectConfigDir,
43
+ knownModelProviders,
43
44
  resolveEffectiveThinking,
44
45
  resolveModelCandidate,
45
46
  shortenPath,
@@ -49,7 +50,7 @@ import {
49
50
  waitToolName,
50
51
  withSettingsFileLease,
51
52
  writePrivateAtomicJson
52
- } from "./chunk-QGO6HXHG.js";
53
+ } from "./chunk-C3KWLXDH.js";
53
54
  import {
54
55
  DIRS,
55
56
  INTERCOM_DETACH_REQUEST_EVENT,
@@ -837,6 +838,7 @@ var SubagentParamProperties = {
837
838
  supersession: Type2.Optional(Type2.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
838
839
  index: Type2.Optional(Type2.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
839
840
  childId: Type2.Optional(Type2.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
841
+ drain: Type2.Optional(Type2.Boolean({ description: "stop: a live async workflow starts no new children; started ones finish." })),
840
842
  toolCallId: Type2.Optional(Type2.String({ description: "Command tool-call id." })),
841
843
  view: Type2.Optional(Type2.String({
842
844
  enum: ["fleet", "transcript"],
@@ -4189,7 +4191,7 @@ function resolveReviewThinking(input) {
4189
4191
  function resolveConfiguredModel(ctx, rawModel) {
4190
4192
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
4191
4193
  const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : void 0;
4192
- const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider);
4194
+ const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry));
4193
4195
  if (!resolved) {
4194
4196
  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.`);
4195
4197
  }
@@ -1,7 +1,7 @@
1
1
  // package.json
2
2
  var package_default = {
3
3
  name: "pi-subagents",
4
- version: "0.86.0",
4
+ version: "0.87.0",
5
5
  private: true,
6
6
  description: "Pi extension for single-agent delegation and scripted multi-agent workflows",
7
7
  author: "Nico Bailon",
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-7F6RKT6W.js";
4
4
  import {
5
5
  PROJECT_SUBAGENTS_RELATIVE_DIR
6
- } from "./chunk-GRJHIXYF.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-QGO6HXHG.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 } : {} });