@xzzpig/pi-subagents 0.18.0 → 0.20.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 (108) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +32 -16
  4. package/docs/configuration.md +76 -9
  5. package/docs/extension-api.md +6 -5
  6. package/docs/missions.md +28 -14
  7. package/docs/models.md +8 -4
  8. package/docs/observability.md +10 -5
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +90 -88
  11. package/docs/workflows.md +171 -173
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +66 -3
  25. package/src/api/preflight.ts +109 -63
  26. package/src/extension/config.ts +15 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +90 -174
  32. package/src/extension/public-execution.ts +72 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +40 -135
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/missions/goal-driver.ts +44 -31
  42. package/src/missions/store.ts +10 -1
  43. package/src/profiles/profiles.ts +5 -2
  44. package/src/runs/background/async-execution.ts +146 -59
  45. package/src/runs/background/async-job-tracker.ts +66 -24
  46. package/src/runs/background/async-retention.ts +46 -16
  47. package/src/runs/background/await-async-run.ts +78 -0
  48. package/src/runs/background/chain-root-attachment.ts +4 -4
  49. package/src/runs/background/control-channel.ts +61 -2
  50. package/src/runs/background/notify.ts +5 -0
  51. package/src/runs/background/run-child-session.ts +17 -7
  52. package/src/runs/background/run-status.ts +6 -0
  53. package/src/runs/background/runner-aliases.ts +37 -6
  54. package/src/runs/background/runner-child-launch.ts +3 -0
  55. package/src/runs/background/scheduled-runs.ts +33 -18
  56. package/src/runs/background/stale-run-reconciler.ts +13 -2
  57. package/src/runs/background/subagent-runner.ts +58 -5
  58. package/src/runs/foreground/async-stop-action.ts +17 -3
  59. package/src/runs/foreground/command-action.ts +41 -0
  60. package/src/runs/foreground/execution.ts +145 -131
  61. package/src/runs/foreground/subagent-executor.ts +546 -296
  62. package/src/runs/shared/async-status-projection.ts +5 -0
  63. package/src/runs/shared/child-commands.ts +228 -0
  64. package/src/runs/shared/child-launch.ts +15 -2
  65. package/src/runs/shared/child-session.ts +184 -24
  66. package/src/runs/shared/child-tool-plan.ts +16 -4
  67. package/src/runs/shared/claude-code-adapter.ts +157 -2
  68. package/src/runs/shared/dynamic-fanout.ts +2 -2
  69. package/src/runs/shared/external-cli-preflight.ts +54 -6
  70. package/src/runs/shared/external-cli-runner.ts +5 -1
  71. package/src/runs/shared/mcp-config-sources.ts +2 -1
  72. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
  73. package/src/runs/shared/model-resolution.ts +38 -10
  74. package/src/runs/shared/model-scope.ts +28 -9
  75. package/src/runs/shared/nested-events.ts +55 -55
  76. package/src/runs/shared/parallel-utils.ts +4 -0
  77. package/src/runs/shared/pi-spawn.ts +7 -95
  78. package/src/runs/shared/run-history.ts +87 -0
  79. package/src/runs/shared/subagent-control.ts +32 -17
  80. package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
  81. package/src/runs/shared/worktree.ts +1 -1
  82. package/src/shared/disabled-features.ts +123 -0
  83. package/src/shared/extension-context.ts +13 -0
  84. package/src/shared/model-info.ts +9 -0
  85. package/src/shared/required-child-extensions.ts +39 -5
  86. package/src/shared/settings.ts +1 -1
  87. package/src/shared/types.ts +27 -1
  88. package/src/slash/prompt-template-bridge.ts +2 -2
  89. package/src/slash/slash-commands.ts +10 -5
  90. package/src/slash/subagent-cost.ts +9 -5
  91. package/src/slash/subagents-admin.ts +24 -24
  92. package/src/tui/fleet-status.ts +14 -6
  93. package/src/tui/fleet.ts +14 -2
  94. package/src/tui/render.ts +117 -56
  95. package/src/tui/running-tone.ts +28 -0
  96. package/src/watchdog/diff-tool.ts +23 -9
  97. package/src/watchdog/register-child.ts +3 -3
  98. package/src/watchdog/register-main.ts +3 -3
  99. package/src/watchdog/review.ts +2 -2
  100. package/src/watchdog/turn-delta.ts +1 -1
  101. package/src/workflows/chat-progress.ts +2 -2
  102. package/src/workflows/scripted-workflow.ts +117 -37
  103. package/src/workflows/structured-workflow-scripts.ts +177 -0
  104. package/src/workflows/workflow-checklist.ts +6 -0
  105. package/src/workflows/workflow-receipt.ts +10 -4
  106. package/src/workflows/workflow-resources.ts +44 -16
  107. package/src/workflows/workflow-reuse.ts +120 -0
  108. package/src/workflows/workflow-revival.ts +123 -0
@@ -178,7 +178,7 @@ export function formatWatchdogOrchestrationActivity(event: unknown): string {
178
178
  const eligible = call.name === "bg_wait"
179
179
  || (call.name === "subagent_supervisor" && ["pending", "list", "reply"].includes(args.action))
180
180
  || (call.name === "subagent" && (["status", "resume", "interrupt", "steer", "stop"].includes(args.action)
181
- || (args.action === undefined && (typeof args.agent === "string" || typeof args.workflowScript === "string" || typeof args.workflowScriptPath === "string"))));
181
+ || (args.action === undefined && (typeof args.agent === "string" || args.workflow !== undefined))));
182
182
  if (!eligible) continue;
183
183
  const result = turn.toolResults.find((value) => {
184
184
  const result = value as { role?: string; toolCallId?: string; toolName?: string };
@@ -90,8 +90,8 @@ export function resolveWorkflowChatProgress(input: ResolveWorkflowChatProgressIn
90
90
  if (requestedMode === "auto") mode = sameRepo && !input.background ? "live-card" : "off";
91
91
  else mode = requestedMode;
92
92
 
93
- if (mode === "live-card" && !sameRepo) return { error: "chatProgress: 'live-card' is only available for workflowScript runs in the same Git repository." };
94
- if (mode === "live-card" && input.background) return { error: "chatProgress: 'live-card' is unavailable for async workflowScript. Async workflows have no inline live card; omit chatProgress or use auto/off. Use async:false only when the parent must block." };
93
+ if (mode === "live-card" && !sameRepo) return { error: "chatProgress: 'live-card' is only available for workflow script runs in the same Git repository." };
94
+ if (mode === "live-card" && input.background) return { error: "chatProgress: 'live-card' is unavailable for async workflow scripts. Async workflows have no inline live card; omit chatProgress or use auto/off. Use async:false only when the parent must block." };
95
95
  return { projection: { mode, repoRelation, ...(repoLabel ? { repoLabel } : {}) } };
96
96
  }
97
97
 
@@ -5,7 +5,7 @@ import { Worker } from "node:worker_threads";
5
5
  import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../runs/shared/parallel-utils.ts";
6
6
  import { HOST_STEP_MAX_COUNT } from "../runs/shared/host-step-status.ts";
7
7
  import { describeGateAcceptanceConflict, parseGateInput } from "../runs/shared/acceptance.ts";
8
- import type { AcceptanceRecoveryMetadata, HostStepNode, SingleResult } from "../shared/types.ts";
8
+ import type { AcceptanceRecoveryMetadata, HostStepNode, SingleResult, WorkflowScriptFailureKind } from "../shared/types.ts";
9
9
  import { normalizeWorkflowHostCommandParams, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "./host-command.ts";
10
10
 
11
11
  const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
@@ -23,7 +23,7 @@ export interface WorkflowScriptValidationError {
23
23
  message: string;
24
24
  line?: number;
25
25
  column?: number;
26
- kind?: "spawn-budget";
26
+ kind?: "spawn-budget" | "agent";
27
27
  }
28
28
 
29
29
  export interface WorkflowScriptValidationWarning {
@@ -39,6 +39,8 @@ export interface WorkflowScriptValidationResult {
39
39
 
40
40
  export interface WorkflowScriptValidationOptions {
41
41
  maxSubagentSpawnsPerRun?: number;
42
+ /** Returns why launch-time resolution would reject this literal child agent name. */
43
+ agentNameError?: (name: string) => string | undefined;
42
44
  }
43
45
 
44
46
  const WORKER_SOURCE = String.raw`
@@ -67,6 +69,7 @@ let topLevelWorkflowPromise;
67
69
  let suppressNativePromiseConsumption = 0;
68
70
  const activeNativePromises = [];
69
71
  const pending = new Map();
72
+ const workflowErrorKinds = new WeakMap();
70
73
  const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
71
74
  function validGitRef(ref) {
72
75
  if (typeof ref !== "string" || !ref || ref === "@" || new TextEncoder().encode(ref).length > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
@@ -870,6 +873,15 @@ function isSyntaxError(error) {
870
873
  return error instanceof SyntaxError || error?.name === "SyntaxError";
871
874
  }
872
875
 
876
+ function postWorkflowError(error) {
877
+ // Pre-run syntax and portability errors are tagged "validation" where the script is compiled;
878
+ // anything reaching here was thrown while the script ran, including a runtime SyntaxError.
879
+ const taggedKind = error && (typeof error === "object" || typeof error === "function") ? workflowErrorKinds.get(error) : undefined;
880
+ parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), errorKind: taggedKind ?? "script" });
881
+ }
882
+
883
+ process.on("unhandledRejection", postWorkflowError);
884
+
873
885
  const NESTED_ASYNC_WORKFLOW_ERROR = "workflowScript validation failed before child launch; no children launched. workflowScript does not support nested async functions. Use top-level await, plain helper functions that return runs.run(...), or explicit Promise chains so workflows stay portable across Node and Bun. Parallel plus sequential rewrite: const a = runs.run(\"a\", { agent: \"worker\", task: \"A\" }); const writer = await runs.run(\"writer\", { agent: \"worker\", task: \"Write\" }); const review = await runs.run(\"review\", { agent: \"reviewer\", task: writer.output }); const [aResult] = await Promise.all([a]); return { a: aResult.output, issue: { writerRunId: writer.runId, reviewRunId: review.runId } };";
874
886
  const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
875
887
 
@@ -986,7 +998,7 @@ parentPort.on("message", async (message) => {
986
998
  if (message.ok) entry.resolve(message.value);
987
999
  else {
988
1000
  const error = new Error(message.error);
989
- if (message.errorKind === "detached-child") error.workflowErrorKind = "detached-child";
1001
+ if (message.errorKind === "child" || message.errorKind === "detached-child") workflowErrorKinds.set(error, message.errorKind);
990
1002
  entry.reject(error);
991
1003
  }
992
1004
  return;
@@ -1005,7 +1017,7 @@ parentPort.on("message", async (message) => {
1005
1017
  assertPortableWorkflowScript(message.script);
1006
1018
  compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js" });
1007
1019
  } catch (error) {
1008
- parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
1020
+ parentPort.postMessage({ type: "error", errorKind: "validation", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
1009
1021
  return;
1010
1022
  }
1011
1023
  const nativePromisePrototype = vm.runInContext("(async () => {})().constructor.prototype", context);
@@ -1069,12 +1081,12 @@ parentPort.on("message", async (message) => {
1069
1081
  try {
1070
1082
  assertJsonValue(persistedValue, "return");
1071
1083
  } catch (error) {
1072
- parentPort.postMessage({ type: "error", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
1084
+ parentPort.postMessage({ type: "error", errorKind: "return-serialization", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
1073
1085
  return;
1074
1086
  }
1075
1087
  parentPort.postMessage({ type: "complete", value: persistedValue });
1076
1088
  } catch (error) {
1077
- parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), ...(error && error.workflowErrorKind === "detached-child" ? { errorKind: "detached-child" } : {}) });
1089
+ postWorkflowError(error);
1078
1090
  }
1079
1091
  });
1080
1092
  `;
@@ -1109,6 +1121,8 @@ export interface WorkflowScriptChildResult {
1109
1121
  continuation?: { runIds: string[] };
1110
1122
  artifactPaths: string[];
1111
1123
  results?: SingleResult[];
1124
+ /** Came from a runtime-replaced run of the same script and args (its saved result, or its still-running child re-attached); this run launched nothing. */
1125
+ reused?: boolean;
1112
1126
  }
1113
1127
 
1114
1128
  export interface WorkflowScriptTraceEntry {
@@ -1126,6 +1140,8 @@ export interface WorkflowScriptTraceEntry {
1126
1140
  generatedLaneKey?: string;
1127
1141
  lane?: import("../shared/types.ts").WorkflowLaneMetadata;
1128
1142
  warning?: string;
1143
+ /** The settled result came from a previous run of the same script and args; no child was launched. */
1144
+ reused?: boolean;
1129
1145
  }
1130
1146
 
1131
1147
  /** Bounded plan metadata emitted when a workflow materializes a runs.lanes graph. */
@@ -1178,12 +1194,20 @@ export interface WorkflowScriptResult {
1178
1194
  children: WorkflowScriptChildResult[];
1179
1195
  }
1180
1196
 
1197
+ function isWorkflowScriptFailureKind(value: unknown): value is WorkflowScriptFailureKind {
1198
+ return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
1199
+ }
1200
+
1201
+ function taggedWorkflowError(message: string, kind: WorkflowScriptFailureKind): Error & { workflowErrorKind: WorkflowScriptFailureKind } {
1202
+ return Object.assign(new Error(message), { workflowErrorKind: kind });
1203
+ }
1204
+
1181
1205
  export class WorkflowScriptError extends Error {
1182
1206
  readonly partial: Omit<WorkflowScriptResult, "value">;
1183
- readonly errorKind?: "detached-child" | "timeout";
1207
+ readonly errorKind?: WorkflowScriptFailureKind;
1184
1208
 
1185
- constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: "detached-child" | "timeout") {
1186
- super(message);
1209
+ constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: WorkflowScriptFailureKind, options?: ErrorOptions) {
1210
+ super(message, options);
1187
1211
  this.name = "WorkflowScriptError";
1188
1212
  this.partial = partial;
1189
1213
  this.errorKind = errorKind;
@@ -1200,6 +1224,8 @@ export interface WorkflowChildSettledNotification {
1200
1224
  outputReference?: string;
1201
1225
  error?: string;
1202
1226
  workflowRunning: boolean;
1227
+ /** The script-visible result, exactly as returned to the script. */
1228
+ result: WorkflowScriptChildResult;
1203
1229
  }
1204
1230
 
1205
1231
  export interface RunWorkflowScriptOptions {
@@ -1455,7 +1481,9 @@ export function formatWorkflowJsonPreview(value: unknown, maxLength: number): st
1455
1481
  try {
1456
1482
  assertWorkflowJsonValue(value);
1457
1483
  const serialized = JSON.stringify(value);
1458
- return typeof serialized === "string" ? serialized.slice(0, maxLength) : undefined;
1484
+ if (typeof serialized !== "string") return undefined;
1485
+ // Serialized JSON never ends in "…", so the suffix always means the preview was cut.
1486
+ return serialized.length > maxLength ? `${serialized.slice(0, maxLength)}…` : serialized;
1459
1487
  } catch {
1460
1488
  return undefined;
1461
1489
  }
@@ -1506,6 +1534,11 @@ function canonicalRunParams(params: Record<string, unknown>): Record<string, unk
1506
1534
  return withoutAcceptance;
1507
1535
  }
1508
1536
 
1537
+ /** Canonical launch-params identity; matches the worker's stableRunJson(canonicalRunParams(params)). */
1538
+ export function workflowRunParamsFingerprint(params: Record<string, unknown>): string {
1539
+ return stableJson(canonicalRunParams(params));
1540
+ }
1541
+
1509
1542
  function validateKey(value: unknown, owner = "runs.run"): string {
1510
1543
  if (typeof value !== "string" || !KEY_PATTERN.test(value)) {
1511
1544
  throw new Error(`${owner} key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.`);
@@ -1717,6 +1750,43 @@ function validateStaticBaseRef(params: AstNode, owner: string): WorkflowScriptVa
1717
1750
  return [];
1718
1751
  }
1719
1752
 
1753
+ // Children with their own cwd, agentScope, or resume resolve agents elsewhere, and a
1754
+ // spread or computed key can replace `agent`; leave those to launch-time resolution.
1755
+ function staticChildAgentNode(params: unknown): AstNode | undefined {
1756
+ if (!astNode(params) || params.type !== "ObjectExpression" || !Array.isArray(params.properties)) return undefined;
1757
+ let agent: AstNode | undefined;
1758
+ for (const property of params.properties) {
1759
+ if (!astNode(property) || property.type !== "Property") return undefined;
1760
+ const key = staticPropertyKey(property);
1761
+ if (key === undefined || key === "cwd" || key === "agentScope" || key === "resume") return undefined;
1762
+ if (key === "agent") agent = property.kind === "init" && astNode(property.value) ? property.value : undefined;
1763
+ }
1764
+ return literalString(agent) === undefined ? undefined : agent;
1765
+ }
1766
+
1767
+ function validateStaticChildAgents(call: AstNode, agentNameError: (name: string) => string | undefined): WorkflowScriptValidationError[] {
1768
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
1769
+ const elements = (node: unknown): unknown[] => astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
1770
+ // A spread or unknown computed key on the lane can replace `stages`.
1771
+ const staticLane = (lane: unknown): lane is AstNode => astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties)
1772
+ && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== undefined);
1773
+ const children: Array<{ owner: string; params: unknown }> = directRunsCall(call, "run")
1774
+ ? [{ owner: "runs.run", params: args[1] }]
1775
+ : directRunsCall(call, "all")
1776
+ ? elements(args[0]).map((params) => ({ owner: "runs.all item", params }))
1777
+ : directRunsCall(call, "lanes")
1778
+ ? elements(args[0]).flatMap((lane) => staticLane(lane) ? elements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : [])
1779
+ : [];
1780
+ const errors: WorkflowScriptValidationError[] = [];
1781
+ for (const child of children) {
1782
+ const agentNode = staticChildAgentNode(child.params);
1783
+ const agentName = literalString(agentNode);
1784
+ const error = agentName === undefined ? undefined : agentNameError(agentName);
1785
+ if (agentNode && error) errors.push({ kind: "agent", message: `${child.owner}: ${error}`, ...nodeLocation(agentNode) });
1786
+ }
1787
+ return errors;
1788
+ }
1789
+
1720
1790
  function directRunsAllKeys(call: AstNode): Array<{ key: string; node: AstNode }> {
1721
1791
  const args = Array.isArray(call.arguments) ? call.arguments : [];
1722
1792
  const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
@@ -1861,6 +1931,8 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
1861
1931
  ? root.body[0].expression.callee
1862
1932
  : undefined;
1863
1933
  const workflowBody = wrapper && astNode(wrapper.body) ? wrapper.body : root;
1934
+ // A rebound `runs` may not be the workflow API, so its calls prove nothing about child launches.
1935
+ const agentNameError = options.agentNameError && !invalidatesRunsBinding(workflowBody) ? options.agentNameError : undefined;
1864
1936
  walkAst(workflowBody, (node) => {
1865
1937
  if (node !== wrapper && node.async === true && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) {
1866
1938
  errors.push({ message: "workflowScript does not support nested async functions. Use top-level await, plain helper functions that return runs.run(...), or explicit Promise chains.", ...nodeLocation(node) });
@@ -1888,6 +1960,7 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
1888
1960
  }
1889
1961
  }
1890
1962
  if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
1963
+ if (agentNameError) errors.push(...validateStaticChildAgents(node, agentNameError));
1891
1964
  const boundaryValue = node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "emit" && Array.isArray(node.arguments) && astNode(node.arguments[0])
1892
1965
  ? node.arguments[0]
1893
1966
  : 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])
@@ -2013,10 +2086,11 @@ function setupAbortResumeParams(params: Record<string, unknown>, result: Workflo
2013
2086
  }
2014
2087
 
2015
2088
  export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
2016
- if (!options.script.trim()) throw new Error("workflowScript must not be empty.");
2017
- if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) throw new Error("workflow script timeout must be a positive integer.");
2089
+ const emptyPartial = (): Omit<WorkflowScriptResult, "value"> => ({ emits: [], console: [], trace: [], children: [] });
2090
+ if (!options.script.trim()) throw new WorkflowScriptError("workflowScript must not be empty.", emptyPartial(), "validation");
2091
+ if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) throw new WorkflowScriptError("workflow script timeout must be a positive integer.", emptyPartial(), "runtime");
2018
2092
  if (options.globalConcurrencyLimit !== undefined && (!Number.isSafeInteger(options.globalConcurrencyLimit) || options.globalConcurrencyLimit < 1)) {
2019
- throw new Error("workflow script global concurrency limit must be a positive integer.");
2093
+ throw new WorkflowScriptError("workflow script global concurrency limit must be a positive integer.", emptyPartial(), "runtime");
2020
2094
  }
2021
2095
  const launchSemaphore = new Semaphore(options.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
2022
2096
 
@@ -2026,7 +2100,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2026
2100
  realpathSync(process.cwd());
2027
2101
  } catch (error) {
2028
2102
  const code = typeof error === "object" && error !== null && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
2029
- if (code !== "ENOENT") throw new Error("Workflow current cwd could not be validated.", { cause: error });
2103
+ if (code !== "ENOENT") throw new WorkflowScriptError("Workflow current cwd could not be validated.", emptyPartial(), "runtime", { cause: error });
2030
2104
  staleCwd = true;
2031
2105
  }
2032
2106
  try {
@@ -2042,7 +2116,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2042
2116
  }
2043
2117
  } catch (error) {
2044
2118
  const detail = error instanceof Error ? error.message : String(error);
2045
- throw new Error(`Workflow process cwd is unavailable: ${options.processCwd}: ${detail}`, { cause: error });
2119
+ throw new WorkflowScriptError(`Workflow process cwd is unavailable: ${options.processCwd}: ${detail}`, emptyPartial(), "runtime", { cause: error });
2046
2120
  }
2047
2121
  }
2048
2122
 
@@ -2050,9 +2124,14 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2050
2124
  try {
2051
2125
  acornPath = resolveWorkflowParserEntry();
2052
2126
  } catch (error) {
2053
- throw new Error("Workflow parser dependency 'acorn' is unavailable from pi-subagents. Reinstall pi-subagents dependencies before launching workflowScript.", { cause: error });
2127
+ throw new WorkflowScriptError("Workflow parser dependency 'acorn' is unavailable from pi-subagents. Reinstall pi-subagents dependencies before launching workflowScript.", emptyPartial(), "runtime", { cause: error });
2128
+ }
2129
+ let worker: Worker;
2130
+ try {
2131
+ worker = new Worker(WORKER_SOURCE, { eval: true, workerData: { acornPath } });
2132
+ } catch (error) {
2133
+ throw new WorkflowScriptError(`Workflow worker could not start: ${error instanceof Error ? error.message : String(error)}`, emptyPartial(), "runtime", { cause: error });
2054
2134
  }
2055
- const worker = new Worker(WORKER_SOURCE, { eval: true, workerData: { acornPath } });
2056
2135
  const emits: unknown[] = [];
2057
2136
  const consoleEntries: WorkflowScriptResult["console"] = [];
2058
2137
  const trace: WorkflowScriptTraceEntry[] = [];
@@ -2155,6 +2234,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2155
2234
  ...(outputReference ? { outputReference } : {}),
2156
2235
  ...(!result.ok && result.error ? { error: result.error } : {}),
2157
2236
  workflowRunning: !settled && !finishing,
2237
+ result,
2158
2238
  });
2159
2239
  } catch (error) {
2160
2240
  console.error("Workflow onChildSettled callback failed:", error);
@@ -2189,8 +2269,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2189
2269
  return unobservedHosts.length > 0 ? new Error(`workflowScript completed with unawaited runs.host call(s): ${unobservedHosts.map((key) => `'${key}'`).join(", ")}. Await or return each call.`) : undefined;
2190
2270
  })()
2191
2271
  : undefined;
2192
- if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), outcome.error.workflowErrorKind === "detached-child" || outcome.error.workflowErrorKind === "timeout" ? outcome.error.workflowErrorKind : undefined));
2193
- else if (completionError) reject(new WorkflowScriptError(completionError.message, partial()));
2272
+ // Stops and reloads end through the abort paths untagged: they are not failures.
2273
+ if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), isWorkflowScriptFailureKind(outcome.error.workflowErrorKind) ? outcome.error.workflowErrorKind : undefined));
2274
+ else if (completionError) reject(new WorkflowScriptError(completionError.message, partial(), "validation"));
2194
2275
  else resolve({ value: outcome.value, ...partial() });
2195
2276
  });
2196
2277
  };
@@ -2210,7 +2291,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2210
2291
  mayFlushAssembly = options.continueAfterAbortWhenChildrenSettled?.(error) === true;
2211
2292
  } catch (callbackError) {
2212
2293
  const callbackMessage = callbackError instanceof Error ? callbackError.message : String(callbackError);
2213
- return finish({ error: new Error(`Workflow assembly flush eligibility failed: ${callbackMessage}`) });
2294
+ return finish({ error: taggedWorkflowError(`Workflow assembly flush eligibility failed: ${callbackMessage}`, "runtime") });
2214
2295
  }
2215
2296
  if (mayFlushAssembly && allChildrenSettled) {
2216
2297
  // A reloaded async workflow may already be past its last child launch.
@@ -2242,16 +2323,14 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2242
2323
  const timer = options.timeoutMs === undefined
2243
2324
  ? undefined
2244
2325
  : setTimeout(() => {
2245
- const error = new Error(`Workflow script timed out after ${options.timeoutMs}ms.`) as Error & { workflowErrorKind: "timeout" };
2246
- error.workflowErrorKind = "timeout";
2247
- finish({ error });
2326
+ finish({ error: taggedWorkflowError(`Workflow script timed out after ${options.timeoutMs}ms.`, "timeout") });
2248
2327
  }, options.timeoutMs);
2249
2328
  options.signal?.addEventListener("abort", onAbort, { once: true });
2250
2329
  if (options.signal?.aborted) return onAbort();
2251
2330
 
2252
- worker.on("error", (error) => finish({ error: new Error(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`) }));
2331
+ worker.on("error", (error) => finish({ error: taggedWorkflowError(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`, "runtime") }));
2253
2332
  worker.on("exit", (code) => {
2254
- if (!settled && code !== 0) finish({ error: new Error(`Workflow worker exited with code ${code}.`) });
2333
+ if (!settled && code !== 0) finish({ error: taggedWorkflowError(`Workflow worker exited with code ${code}.`, "runtime") });
2255
2334
  });
2256
2335
  worker.on("message", (message: Record<string, unknown>) => {
2257
2336
  if (settled) return;
@@ -2263,7 +2342,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2263
2342
  try {
2264
2343
  assertWorkflowJsonValue(message.value, "emit");
2265
2344
  } catch (error) {
2266
- finish({ error: new Error(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
2345
+ finish({ error: taggedWorkflowError(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`, "runtime") });
2267
2346
  return;
2268
2347
  }
2269
2348
  emits.push(message.value);
@@ -2271,7 +2350,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2271
2350
  options.onEmit?.([...emits]);
2272
2351
  } catch (error) {
2273
2352
  emits.pop();
2274
- finish({ error: new Error(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
2353
+ finish({ error: taggedWorkflowError(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`, "runtime") });
2275
2354
  }
2276
2355
  return;
2277
2356
  }
@@ -2284,16 +2363,14 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2284
2363
  try {
2285
2364
  assertWorkflowJsonValue(message.value, "return");
2286
2365
  } catch (error) {
2287
- return finish({ error: new Error(`Workflow return could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
2366
+ return finish({ error: taggedWorkflowError(`Workflow return could not be persisted: ${error instanceof Error ? error.message : String(error)}`, "return-serialization") });
2288
2367
  }
2289
2368
  return finish({ value: message.value });
2290
2369
  }
2291
2370
  if (message.type === "error") {
2292
2371
  const rawError = typeof message.error === "string" ? message.error : "Workflow script failed.";
2293
2372
  const text = message.errorPhase === "return-serialization" ? `${rawError}${workflowReturnRecoveryHint(partial().children)}` : rawError;
2294
- const workflowError = new Error(text) as Error & { workflowErrorKind?: "detached-child" };
2295
- if (message.errorKind === "detached-child") workflowError.workflowErrorKind = "detached-child";
2296
- return finish({ error: workflowError });
2373
+ return finish({ error: isWorkflowScriptFailureKind(message.errorKind) ? taggedWorkflowError(text, message.errorKind) : new Error(text) });
2297
2374
  }
2298
2375
  if (message.type === "callObserved" && typeof message.callId === "number") {
2299
2376
  const key = typeof message.key === "string" ? message.key : undefined;
@@ -2333,7 +2410,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2333
2410
  }
2334
2411
  },
2335
2412
  (error: unknown) => {
2336
- if (!settled) worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...(error instanceof Error && (error as { workflowErrorKind?: unknown }).workflowErrorKind === "detached-child" ? { errorKind: "detached-child" } : {}) });
2413
+ if (!settled) {
2414
+ const errorKind = error instanceof Error ? (error as { workflowErrorKind?: unknown }).workflowErrorKind : undefined;
2415
+ worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...(isWorkflowScriptFailureKind(errorKind) ? { errorKind } : {}) });
2416
+ }
2337
2417
  },
2338
2418
  );
2339
2419
  };
@@ -2473,13 +2553,11 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2473
2553
  const recoverableAcceptanceMetadata = result.recovery?.status === "available-for-review"
2474
2554
  && result.recovery.reason === "acceptance-metadata-rejected";
2475
2555
  if (!result.ok && result.state !== "running" && !result.stopped && !recoverableAcceptanceMetadata) {
2476
- const childError = new Error(result.detached ? `Run '${key}' detached: ${result.error ?? result.output}` : `Run '${key}' failed: ${result.error ?? result.output}`) as Error & { workflowErrorKind?: "detached-child" };
2477
- if (result.detached) childError.workflowErrorKind = "detached-child";
2478
- throw childError;
2556
+ throw taggedWorkflowError(`Run '${key}' ${result.detached ? "detached" : "failed"}: ${result.error ?? result.output}`, result.detached ? "detached-child" : "child");
2479
2557
  }
2480
2558
  return result;
2481
2559
  });
2482
- const fingerprint = stableJson(canonicalRunParams(params));
2560
+ const fingerprint = workflowRunParamsFingerprint(params);
2483
2561
  const existing = launches.get(key);
2484
2562
  if (existing) {
2485
2563
  if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
@@ -2612,7 +2690,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2612
2690
  children.set(key, normalized);
2613
2691
  recordAcceptanceRecoveryBarrier(key, normalized);
2614
2692
  const state = normalized.state === "running" ? "started" : normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
2615
- trace.push({ operation: "run", key, state, durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), ...(normalized.agent ? { agent: normalized.agent } : {}), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok && normalized.state !== "running" ? { error: normalized.error ?? normalized.output } : {}) });
2693
+ const settledEntry: WorkflowScriptTraceEntry = { operation: "run", key, state, durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), ...(normalized.agent ? { agent: normalized.agent } : {}), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok && normalized.state !== "running" ? { error: normalized.error ?? normalized.output } : {}) };
2694
+ if (normalized.reused) settledEntry.reused = true;
2695
+ trace.push(settledEntry);
2616
2696
  traceChanged();
2617
2697
  notifyChildSettled(key, normalized);
2618
2698
  return normalized;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Package-owned workflow scripts for the data-only `tasks` and `chain` inputs.
3
+ * Callers supply only data; every caller string is embedded with JSON.stringify
4
+ * and never becomes code. Scripts run on the ordinary workflow runtime.
5
+ */
6
+
7
+ export type StructuredWorkflowKind = "tasks" | "chain";
8
+
9
+ const OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
+ const PLACEHOLDER_PATTERN = /\{(?:task|previous|outputs\.([A-Za-z_][A-Za-z0-9_]*))\}/g;
11
+
12
+ interface TemplateScope {
13
+ path: string;
14
+ /** Whether the script declares `originalTask` for {task}. */
15
+ hasOriginalTask: boolean;
16
+ /** Script variable holding the previous step's output, or the reason {previous} is unavailable. */
17
+ previous: { variable: string } | { unavailable: string };
18
+ /** Script variables for outputs named by earlier sequential steps; undefined when named outputs are unavailable. */
19
+ outputs?: ReadonlyMap<string, string>;
20
+ outputsUnavailable?: string;
21
+ }
22
+
23
+ interface StepChild {
24
+ key: string;
25
+ agent: string;
26
+ taskExpression: string;
27
+ }
28
+
29
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
30
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
31
+ const prototype = Object.getPrototypeOf(value);
32
+ return prototype === Object.prototype || prototype === null;
33
+ }
34
+
35
+ function nonEmptyString(value: unknown, path: string): string {
36
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${path} must be a non-empty string.`);
37
+ return value;
38
+ }
39
+
40
+ function exactFields(value: unknown, path: string, allowed: readonly string[], hint: string): Record<string, unknown> {
41
+ if (!isPlainRecord(value)) throw new Error(`${path} must be an object.`);
42
+ const unsupported = Object.keys(value).filter((key) => !allowed.includes(key));
43
+ if (unsupported.length > 0) throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint}`);
44
+ return value;
45
+ }
46
+
47
+ /** Single pass: text inserted for a placeholder is never scanned again. Unrecognized brace text stays literal. */
48
+ function compileTemplate(template: string, scope: TemplateScope): string {
49
+ const parts: string[] = [];
50
+ let cursor = 0;
51
+ for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {
52
+ const literal = template.slice(cursor, match.index);
53
+ cursor = match.index + match[0].length;
54
+ let variable: string;
55
+ if (match[0] === "{task}") {
56
+ if (!scope.hasOriginalTask) throw new Error(`${scope.path} references {task}, but no top-level task was provided.`);
57
+ variable = "originalTask";
58
+ } else if (match[0] === "{previous}") {
59
+ if ("unavailable" in scope.previous) throw new Error(`${scope.path} cannot use {previous}; ${scope.previous.unavailable}`);
60
+ variable = scope.previous.variable;
61
+ } else {
62
+ const name = match[1]!;
63
+ if (!scope.outputs) throw new Error(`${scope.path} cannot use {outputs.${name}}; ${scope.outputsUnavailable}`);
64
+ const named = scope.outputs.get(name);
65
+ if (!named) throw new Error(`${scope.path} references {outputs.${name}}, but no earlier sequential step sets as: "${name}".`);
66
+ variable = named;
67
+ }
68
+ if (literal) parts.push(JSON.stringify(literal));
69
+ parts.push(variable);
70
+ }
71
+ const literal = template.slice(cursor);
72
+ if (literal || parts.length === 0) parts.push(JSON.stringify(literal));
73
+ return parts.join(" + ");
74
+ }
75
+
76
+ function prelude(originalTask: string | undefined): string[] {
77
+ return originalTask === undefined ? [SETTLE_HELPER] : [SETTLE_HELPER, `const originalTask = ${JSON.stringify(originalTask)};`];
78
+ }
79
+
80
+ function runsAllCall(children: readonly StepChild[]): string {
81
+ return `await runs.all([${children.map((child) => `{ key: ${JSON.stringify(child.key)}, agent: ${JSON.stringify(child.agent)}, task: ${child.taskExpression} }`).join(", ")}])`;
82
+ }
83
+
84
+ const SETTLE_HELPER = [
85
+ "function settle(results, agents) {",
86
+ " return results.map(function (result, index) {",
87
+ " const child = { key: result.key, agent: agents[index], ok: result.ok === true, output: typeof result.output === \"string\" ? result.output : \"\" };",
88
+ " if (!child.ok && typeof result.error === \"string\") child.error = result.error;",
89
+ " return child;",
90
+ " });",
91
+ "}",
92
+ // A failed child fails the workflow; the runtime keeps every settled child in the partial results.
93
+ "function failure(label, children) {",
94
+ " 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(\"; \"));",
95
+ "}",
96
+ ].join("\n");
97
+
98
+ function buildTasksScript(steps: unknown, originalTask: string | undefined): string {
99
+ if (!Array.isArray(steps) || steps.length === 0) throw new Error("tasks must be a non-empty array of { agent, task } items.");
100
+ const children = steps.map((item, index): StepChild => {
101
+ const path = `tasks[${index}]`;
102
+ const record = exactFields(item, path, ["agent", "task"], "Each tasks item accepts only agent and task.");
103
+ const agent = nonEmptyString(record.agent, `${path}.agent`);
104
+ const task = nonEmptyString(record.task, `${path}.task`);
105
+ const taskExpression = compileTemplate(task, {
106
+ path: `${path}.task`,
107
+ hasOriginalTask: originalTask !== undefined,
108
+ previous: { unavailable: "tasks items may only use {task}." },
109
+ outputsUnavailable: "tasks items may only use {task}.",
110
+ });
111
+ return { key: `task-${index + 1}`, agent, taskExpression };
112
+ });
113
+ return [
114
+ ...prelude(originalTask),
115
+ `const run1 = ${runsAllCall(children)};`,
116
+ `const children = settle(run1, ${JSON.stringify(children.map((child) => child.agent))});`,
117
+ "if (!children.every(function (child) { return child.ok; })) throw failure(\"tasks failed\", children);",
118
+ "return { ok: true, children };",
119
+ ].join("\n");
120
+ }
121
+
122
+ function buildChainScript(steps: unknown, originalTask: string | undefined): string {
123
+ if (!Array.isArray(steps) || steps.length === 0) throw new Error("chain must be a non-empty array of steps.");
124
+ const lines = [...prelude(originalTask), "const children = [];"];
125
+ const hasOriginalTask = originalTask !== undefined;
126
+ const outputs = new Map<string, string>();
127
+ for (const [index, step] of steps.entries()) {
128
+ const number = index + 1;
129
+ const path = `chain[${index}]`;
130
+ const previous: TemplateScope["previous"] = index === 0
131
+ ? { unavailable: "the first chain step has no previous output." }
132
+ : { variable: `output${index}` };
133
+ let stepChildren: StepChild[];
134
+ let outputName: string | undefined;
135
+ if (isPlainRecord(step) && Object.hasOwn(step, "parallel")) {
136
+ const record = exactFields(step, path, ["parallel"], "A parallel step accepts only parallel; as is supported on sequential steps only.");
137
+ const items = record.parallel;
138
+ if (!Array.isArray(items) || items.length === 0) throw new Error(`${path}.parallel must be a non-empty array of { agent, task } items.`);
139
+ stepChildren = items.map((item, itemIndex): StepChild => {
140
+ const itemPath = `${path}.parallel[${itemIndex}]`;
141
+ const itemRecord = exactFields(item, itemPath, ["agent", "task"], "Each parallel item accepts only agent and task.");
142
+ const agent = nonEmptyString(itemRecord.agent, `${itemPath}.agent`);
143
+ const task = nonEmptyString(itemRecord.task, `${itemPath}.task`);
144
+ return { key: `step-${number}-${itemIndex + 1}`, agent, taskExpression: compileTemplate(task, { path: `${itemPath}.task`, hasOriginalTask, previous, outputs }) };
145
+ });
146
+ } else {
147
+ const record = exactFields(step, path, ["agent", "task", "as"], "A sequential step accepts only agent, task and as; a parallel step accepts only parallel.");
148
+ const agent = nonEmptyString(record.agent, `${path}.agent`);
149
+ let task: string;
150
+ if (record.task === undefined) {
151
+ if (index === 0) throw new Error(`${path}.task is required; the first chain step has no previous output.`);
152
+ task = "{previous}";
153
+ } else task = nonEmptyString(record.task, `${path}.task`);
154
+ if (record.as !== undefined) {
155
+ if (typeof record.as !== "string" || !OUTPUT_NAME_PATTERN.test(record.as)) throw new Error(`${path}.as must be an identifier matching ${OUTPUT_NAME_PATTERN}.`);
156
+ if (outputs.has(record.as)) throw new Error(`${path}.as '${record.as}' is already used by an earlier step.`);
157
+ outputName = record.as;
158
+ }
159
+ stepChildren = [{ key: `step-${number}`, agent, taskExpression: compileTemplate(task, { path: `${path}.task`, hasOriginalTask, previous, outputs }) }];
160
+ }
161
+ lines.push(
162
+ `const run${number} = ${runsAllCall(stepChildren)};`,
163
+ `const step${number} = settle(run${number}, ${JSON.stringify(stepChildren.map((child) => child.agent))});`,
164
+ `children.push(...step${number});`,
165
+ `if (!step${number}.every(function (child) { return child.ok; })) throw failure(${JSON.stringify(`chain stopped at step ${number}`)}, step${number});`,
166
+ );
167
+ if (index < steps.length - 1) lines.push(`const output${number} = step${number}.map(function (child) { return child.output; }).join("\\n\\n");`);
168
+ if (outputName !== undefined) outputs.set(outputName, `output${number}`);
169
+ }
170
+ lines.push("return { ok: true, children };");
171
+ return lines.join("\n");
172
+ }
173
+
174
+ /** Validate exact data shapes and expand them into a package-owned workflow script. */
175
+ export function buildStructuredWorkflowScript(kind: StructuredWorkflowKind, steps: unknown, originalTask: string | undefined): string {
176
+ return kind === "tasks" ? buildTasksScript(steps, originalTask) : buildChainScript(steps, originalTask);
177
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AsyncJobStep, HostStepNode, WorkflowGraphNode, WorkflowGraphSnapshot, WorkflowPreflightLane, WorkflowPreflight } from "../shared/types.ts";
2
+ import { childThinkingLevel, type ThinkingLevel } from "../shared/model-info.ts";
2
3
  import { sanitizeDisplayText } from "../shared/display-text.ts";
3
4
  import { workflowPreflightLaneForRuntimeKey as laneFor } from "./workflow-preflight.ts";
4
5
 
@@ -6,6 +7,7 @@ export type WorkflowChecklistState = "complete" | "running" | "queued" | "blocke
6
7
 
7
8
  export interface WorkflowChecklistStep {
8
9
  key?: string;
10
+ thinking?: string;
9
11
  workflowKey?: string;
10
12
  runId?: string;
11
13
  label?: string;
@@ -53,6 +55,8 @@ export interface WorkflowChecklistItem {
53
55
  phase: string;
54
56
  state: WorkflowChecklistState;
55
57
  agent?: string;
58
+ /** Thinking level of the child this item stands for. */
59
+ thinking?: ThinkingLevel;
56
60
  context?: "fresh" | "fork";
57
61
  startedAt?: number;
58
62
  durationMs?: number;
@@ -196,12 +200,14 @@ function stepKey(step: WorkflowChecklistStep): string | undefined {
196
200
 
197
201
  function stepItem(step: WorkflowChecklistStep, index: number, phase: string, key = stepKey(step) ?? `step-${index + 1}`, label = step.label ?? step.description ?? stepKey(step) ?? step.agent ?? key, preflight?: WorkflowPreflightLane): WorkflowChecklistItem {
198
202
  const state = checklistState(step);
203
+ const thinking = childThinkingLevel(step);
199
204
  return {
200
205
  key: keyText(key, `step-${index + 1}`),
201
206
  label: keyText(label, key),
202
207
  phase,
203
208
  state,
204
209
  ...(text(step.agent) ? { agent: text(step.agent) } : {}),
210
+ ...(thinking ? { thinking } : {}),
205
211
  ...(step.context ? { context: step.context } : {}),
206
212
  ...(finite(step.startedAt) !== undefined ? { startedAt: finite(step.startedAt) } : {}),
207
213
  ...(duration(step, undefined, state) !== undefined ? { durationMs: duration(step, undefined, state) } : {}),