@xzzpig/pi-subagents 0.16.0 → 0.19.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.
- package/CHANGELOG.md +233 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +34 -21
- package/docs/configuration.md +82 -7
- package/docs/extension-api.md +75 -8
- package/docs/missions.md +13 -13
- package/docs/models.md +7 -5
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +5 -5
- package/docs/tool-reference.md +98 -100
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +214 -162
- package/inspector-runner.mjs +1 -1
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +15 -9
- package/prompts/council.md +6 -3
- package/prompts/review-loop.md +1 -1
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +13 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
- package/skills/pi-subagents/references/execution-controls.md +72 -69
- package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
- package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +63 -54
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +132 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +7 -2
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +10 -4
- package/src/extension/fanout-child.ts +20 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +168 -206
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +39 -11
- package/src/extension/schemas.ts +47 -138
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +146 -0
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +26 -16
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +60 -95
- package/src/runs/background/async-job-tracker.ts +91 -56
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +98 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +20 -6
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +16 -4
- package/src/runs/background/runner-aliases.ts +54 -16
- package/src/runs/background/runner-child-launch.ts +4 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +111 -288
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +111 -139
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +715 -258
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +37 -16
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +144 -8
- package/src/runs/shared/child-tool-plan.ts +38 -116
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +5 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +35 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +12 -0
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +4 -1
- package/src/runs/shared/pi-spawn.ts +1 -3
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +36 -9
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/model-info.ts +9 -0
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +73 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +18 -3
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +17 -246
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +4 -5
- package/src/tui/fleet-status.ts +38 -8
- package/src/tui/fleet.ts +21 -6
- package/src/tui/render.ts +166 -71
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +47 -12
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +13 -5
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +16 -16
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +12 -6
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +225 -59
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -4,9 +4,8 @@ import { dirname, resolve as resolvePath } from "node:path";
|
|
|
4
4
|
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
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import type { AcceptanceRecoveryMetadata, HostStepNode, SingleResult } from "../shared/types.ts";
|
|
7
|
+
import { describeGateAcceptanceConflict, parseGateInput } from "../runs/shared/acceptance.ts";
|
|
8
|
+
import type { AcceptanceRecoveryMetadata, HostStepNode, SingleResult, WorkflowScriptFailureKind } from "../shared/types.ts";
|
|
10
9
|
import { normalizeWorkflowHostCommandParams, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "./host-command.ts";
|
|
11
10
|
|
|
12
11
|
const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
@@ -24,7 +23,7 @@ export interface WorkflowScriptValidationError {
|
|
|
24
23
|
message: string;
|
|
25
24
|
line?: number;
|
|
26
25
|
column?: number;
|
|
27
|
-
kind?: "spawn-budget";
|
|
26
|
+
kind?: "spawn-budget" | "agent";
|
|
28
27
|
}
|
|
29
28
|
|
|
30
29
|
export interface WorkflowScriptValidationWarning {
|
|
@@ -40,6 +39,8 @@ export interface WorkflowScriptValidationResult {
|
|
|
40
39
|
|
|
41
40
|
export interface WorkflowScriptValidationOptions {
|
|
42
41
|
maxSubagentSpawnsPerRun?: number;
|
|
42
|
+
/** Returns why launch-time resolution would reject this literal child agent name. */
|
|
43
|
+
agentNameError?: (name: string) => string | undefined;
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
const WORKER_SOURCE = String.raw`
|
|
@@ -68,6 +69,7 @@ let topLevelWorkflowPromise;
|
|
|
68
69
|
let suppressNativePromiseConsumption = 0;
|
|
69
70
|
const activeNativePromises = [];
|
|
70
71
|
const pending = new Map();
|
|
72
|
+
const workflowErrorKinds = new WeakMap();
|
|
71
73
|
const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
72
74
|
function validGitRef(ref) {
|
|
73
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;
|
|
@@ -384,8 +386,8 @@ function laneStageRecord(stageKey, child, forcedState) {
|
|
|
384
386
|
const ok = result?.ok === true;
|
|
385
387
|
const verdict = laneStageVerdict(result);
|
|
386
388
|
const blocked = laneStageIsBlocked(result);
|
|
387
|
-
const state = forcedState ?? (result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
|
|
388
|
-
const error = state !== "completed"
|
|
389
|
+
const state = forcedState ?? (result?.state === "running" ? "running" : result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
|
|
390
|
+
const error = state !== "completed" && state !== "running"
|
|
389
391
|
? state === "blocked" && blocked
|
|
390
392
|
? "Stage returned a blocked verdict."
|
|
391
393
|
: typeof result?.error === "string"
|
|
@@ -633,6 +635,24 @@ function validateLaneMetadata(value, label, workflowKey) {
|
|
|
633
635
|
}
|
|
634
636
|
}
|
|
635
637
|
|
|
638
|
+
// Mirrors parseGateInput in src/runs/shared/acceptance.ts; the sandbox cannot import it.
|
|
639
|
+
function describeGateShapeError(gate) {
|
|
640
|
+
const shape = "gate must be a non-empty command string or { command, output?: \"json\", schema?, timeoutMs? }.";
|
|
641
|
+
if (typeof gate === "string") return gate.trim() ? undefined : shape;
|
|
642
|
+
if (!gate || typeof gate !== "object" || Array.isArray(gate)) return shape;
|
|
643
|
+
for (const key of Object.keys(gate)) {
|
|
644
|
+
if (!["command", "output", "schema", "timeoutMs"].includes(key)) return "gate." + key + " is not supported.";
|
|
645
|
+
}
|
|
646
|
+
if (typeof gate.command !== "string" || !gate.command.trim()) return shape;
|
|
647
|
+
if (gate.output !== undefined && gate.output !== "json") return "gate.output must be \"json\" when present.";
|
|
648
|
+
if (gate.schema !== undefined) {
|
|
649
|
+
if (gate.output !== "json") return "gate.schema requires gate.output: \"json\".";
|
|
650
|
+
if (!gate.schema || typeof gate.schema !== "object" || Array.isArray(gate.schema)) return "gate.schema must be a JSON Schema object.";
|
|
651
|
+
}
|
|
652
|
+
if (gate.timeoutMs !== undefined && (!Number.isInteger(gate.timeoutMs) || gate.timeoutMs < 1)) return "gate.timeoutMs must be an integer >= 1.";
|
|
653
|
+
return undefined;
|
|
654
|
+
}
|
|
655
|
+
|
|
636
656
|
function describeGateAcceptanceConflict(gate, acceptance) {
|
|
637
657
|
const render = (value) => {
|
|
638
658
|
let encoded;
|
|
@@ -658,7 +678,10 @@ function validateRunCall(key, params, label, fingerprints) {
|
|
|
658
678
|
if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
|
|
659
679
|
if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) throw new Error(label + " baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.");
|
|
660
680
|
validateLaneMetadata(params.lane, label + " lane", key);
|
|
661
|
-
if (params.gate !== undefined
|
|
681
|
+
if (params.gate !== undefined) {
|
|
682
|
+
const gateError = describeGateShapeError(params.gate);
|
|
683
|
+
if (gateError) throw new Error(label + " " + gateError);
|
|
684
|
+
}
|
|
662
685
|
if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify." + describeGateAcceptanceConflict(params.gate, params.acceptance));
|
|
663
686
|
if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
|
|
664
687
|
if (params.extensionBindings !== undefined && params.resume !== undefined) throw new Error(label + " extensionBindings is not supported with retained resume; resume uses the original retained child binding.");
|
|
@@ -850,6 +873,15 @@ function isSyntaxError(error) {
|
|
|
850
873
|
return error instanceof SyntaxError || error?.name === "SyntaxError";
|
|
851
874
|
}
|
|
852
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
|
+
|
|
853
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 } };";
|
|
854
886
|
const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
|
|
855
887
|
|
|
@@ -966,7 +998,7 @@ parentPort.on("message", async (message) => {
|
|
|
966
998
|
if (message.ok) entry.resolve(message.value);
|
|
967
999
|
else {
|
|
968
1000
|
const error = new Error(message.error);
|
|
969
|
-
if (message.errorKind === "
|
|
1001
|
+
if (message.errorKind === "child" || message.errorKind === "detached-child") workflowErrorKinds.set(error, message.errorKind);
|
|
970
1002
|
entry.reject(error);
|
|
971
1003
|
}
|
|
972
1004
|
return;
|
|
@@ -985,7 +1017,7 @@ parentPort.on("message", async (message) => {
|
|
|
985
1017
|
assertPortableWorkflowScript(message.script);
|
|
986
1018
|
compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js" });
|
|
987
1019
|
} catch (error) {
|
|
988
|
-
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) });
|
|
989
1021
|
return;
|
|
990
1022
|
}
|
|
991
1023
|
const nativePromisePrototype = vm.runInContext("(async () => {})().constructor.prototype", context);
|
|
@@ -1049,19 +1081,23 @@ parentPort.on("message", async (message) => {
|
|
|
1049
1081
|
try {
|
|
1050
1082
|
assertJsonValue(persistedValue, "return");
|
|
1051
1083
|
} catch (error) {
|
|
1052
|
-
parentPort.postMessage({ type: "error", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
|
|
1084
|
+
parentPort.postMessage({ type: "error", errorKind: "return-serialization", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
|
|
1053
1085
|
return;
|
|
1054
1086
|
}
|
|
1055
1087
|
parentPort.postMessage({ type: "complete", value: persistedValue });
|
|
1056
1088
|
} catch (error) {
|
|
1057
|
-
|
|
1089
|
+
postWorkflowError(error);
|
|
1058
1090
|
}
|
|
1059
1091
|
});
|
|
1060
1092
|
`;
|
|
1061
1093
|
|
|
1062
1094
|
export interface WorkflowScriptChildResult {
|
|
1063
1095
|
key: string;
|
|
1096
|
+
/** True only for successfully completed child work, never for a launch receipt. */
|
|
1064
1097
|
ok: boolean;
|
|
1098
|
+
/** An explicit async launch returned before a final child result was available. */
|
|
1099
|
+
state?: "running";
|
|
1100
|
+
asyncDir?: string;
|
|
1065
1101
|
lane?: import("../shared/types.ts").WorkflowLaneMetadata;
|
|
1066
1102
|
terminalOutcome?: import("../shared/types.ts").WorkflowTerminalOutcome;
|
|
1067
1103
|
stopped?: boolean;
|
|
@@ -1076,6 +1112,8 @@ export interface WorkflowScriptChildResult {
|
|
|
1076
1112
|
requestedContext?: "fresh" | "fork";
|
|
1077
1113
|
resolvedContext?: "fresh" | "fork" | "mixed";
|
|
1078
1114
|
outputReference?: string;
|
|
1115
|
+
/** A file produced by the child runtime (output or worktree handoff), not its job directory. */
|
|
1116
|
+
outputArtifactPath?: string;
|
|
1079
1117
|
recovery?: AcceptanceRecoveryMetadata;
|
|
1080
1118
|
outputPathMapping?: { requestedPath: string; savedPath: string };
|
|
1081
1119
|
externalAdapter?: import("../shared/types.ts").ExternalCliReceiptMetadata;
|
|
@@ -1083,6 +1121,8 @@ export interface WorkflowScriptChildResult {
|
|
|
1083
1121
|
continuation?: { runIds: string[] };
|
|
1084
1122
|
artifactPaths: string[];
|
|
1085
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;
|
|
1086
1126
|
}
|
|
1087
1127
|
|
|
1088
1128
|
export interface WorkflowScriptTraceEntry {
|
|
@@ -1100,6 +1140,8 @@ export interface WorkflowScriptTraceEntry {
|
|
|
1100
1140
|
generatedLaneKey?: string;
|
|
1101
1141
|
lane?: import("../shared/types.ts").WorkflowLaneMetadata;
|
|
1102
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;
|
|
1103
1145
|
}
|
|
1104
1146
|
|
|
1105
1147
|
/** Bounded plan metadata emitted when a workflow materializes a runs.lanes graph. */
|
|
@@ -1152,12 +1194,20 @@ export interface WorkflowScriptResult {
|
|
|
1152
1194
|
children: WorkflowScriptChildResult[];
|
|
1153
1195
|
}
|
|
1154
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
|
+
|
|
1155
1205
|
export class WorkflowScriptError extends Error {
|
|
1156
1206
|
readonly partial: Omit<WorkflowScriptResult, "value">;
|
|
1157
|
-
readonly errorKind?:
|
|
1207
|
+
readonly errorKind?: WorkflowScriptFailureKind;
|
|
1158
1208
|
|
|
1159
|
-
constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?:
|
|
1160
|
-
super(message);
|
|
1209
|
+
constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: WorkflowScriptFailureKind, options?: ErrorOptions) {
|
|
1210
|
+
super(message, options);
|
|
1161
1211
|
this.name = "WorkflowScriptError";
|
|
1162
1212
|
this.partial = partial;
|
|
1163
1213
|
this.errorKind = errorKind;
|
|
@@ -1174,6 +1224,8 @@ export interface WorkflowChildSettledNotification {
|
|
|
1174
1224
|
outputReference?: string;
|
|
1175
1225
|
error?: string;
|
|
1176
1226
|
workflowRunning: boolean;
|
|
1227
|
+
/** The script-visible result, exactly as returned to the script. */
|
|
1228
|
+
result: WorkflowScriptChildResult;
|
|
1177
1229
|
}
|
|
1178
1230
|
|
|
1179
1231
|
export interface RunWorkflowScriptOptions {
|
|
@@ -1354,8 +1406,7 @@ function isExplicitReadOnlyRecoveryReview(params: Record<string, unknown>): bool
|
|
|
1354
1406
|
&& !RECOVERY_REVIEW_DELEGATION_PATTERN.test(taskMutationText)
|
|
1355
1407
|
&& !RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN.test(taskMutationText)
|
|
1356
1408
|
&& !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskMutationText)
|
|
1357
|
-
&& !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText)
|
|
1358
|
-
&& classifyTaskMutationIntent(agent, task).kind === "read-only";
|
|
1409
|
+
&& !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText);
|
|
1359
1410
|
}
|
|
1360
1411
|
|
|
1361
1412
|
function recoveryBarrierMessage(sourceKey: string, target: string): string {
|
|
@@ -1430,7 +1481,9 @@ export function formatWorkflowJsonPreview(value: unknown, maxLength: number): st
|
|
|
1430
1481
|
try {
|
|
1431
1482
|
assertWorkflowJsonValue(value);
|
|
1432
1483
|
const serialized = JSON.stringify(value);
|
|
1433
|
-
|
|
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;
|
|
1434
1487
|
} catch {
|
|
1435
1488
|
return undefined;
|
|
1436
1489
|
}
|
|
@@ -1442,7 +1495,7 @@ function workflowReturnRecoveryHint(children: WorkflowScriptChildResult[]): stri
|
|
|
1442
1495
|
const fields = [child.runId ? `runId=${child.runId.slice(0, 500)}` : undefined, child.outputReference ? `outputReference=${child.outputReference.slice(0, 500)}` : undefined, child.artifactPaths[0] ? `artifact=${child.artifactPaths[0].slice(0, 500)}` : undefined].filter((field): field is string => field !== undefined);
|
|
1443
1496
|
return `'${child.key}'${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`;
|
|
1444
1497
|
});
|
|
1445
|
-
return ` Child work completed before return serialization failed. Recover outputs from: ${references.join(", ")}${children.length > references.length ? `, and ${children.length - references.length} more` : ""}. Return a plain projection such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.`;
|
|
1498
|
+
return ` ${children.some((child) => child.state === "running") ? "Child calls returned before return serialization failed; launch receipts do not prove completion." : "Child work completed before return serialization failed."} Recover outputs from: ${references.join(", ")}${children.length > references.length ? `, and ${children.length - references.length} more` : ""}. Return a plain projection such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.`;
|
|
1446
1499
|
}
|
|
1447
1500
|
|
|
1448
1501
|
export interface SimpleWorkflowRunPreview {
|
|
@@ -1481,6 +1534,11 @@ function canonicalRunParams(params: Record<string, unknown>): Record<string, unk
|
|
|
1481
1534
|
return withoutAcceptance;
|
|
1482
1535
|
}
|
|
1483
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
|
+
|
|
1484
1542
|
function validateKey(value: unknown, owner = "runs.run"): string {
|
|
1485
1543
|
if (typeof value !== "string" || !KEY_PATTERN.test(value)) {
|
|
1486
1544
|
throw new Error(`${owner} key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.`);
|
|
@@ -1568,6 +1626,62 @@ function walkAst(node: unknown, visit: (node: AstNode) => void, includeNestedFun
|
|
|
1568
1626
|
}
|
|
1569
1627
|
}
|
|
1570
1628
|
|
|
1629
|
+
function bindingPatternContainsName(node: unknown, name: string): boolean {
|
|
1630
|
+
if (!astNode(node)) return false;
|
|
1631
|
+
if (node.type === "Identifier") return node.name === name;
|
|
1632
|
+
if (node.type === "RestElement") return bindingPatternContainsName(node.argument, name);
|
|
1633
|
+
if (node.type === "AssignmentPattern") return bindingPatternContainsName(node.left, name);
|
|
1634
|
+
if (node.type === "ArrayPattern" && Array.isArray(node.elements)) return node.elements.some((element) => bindingPatternContainsName(element, name));
|
|
1635
|
+
if (node.type === "ObjectPattern" && Array.isArray(node.properties)) return node.properties.some((property) => {
|
|
1636
|
+
if (!astNode(property)) return false;
|
|
1637
|
+
return property.type === "RestElement"
|
|
1638
|
+
? bindingPatternContainsName(property.argument, name)
|
|
1639
|
+
: property.type === "Property" && bindingPatternContainsName(property.value, name);
|
|
1640
|
+
});
|
|
1641
|
+
return false;
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
function definitelyReassignsBinding(node: unknown, name: string): boolean {
|
|
1645
|
+
let assignment = node;
|
|
1646
|
+
while (astNode(assignment) && assignment.type === "AssignmentExpression" && assignment.operator !== "&&=" && assignment.operator !== "||=" && assignment.operator !== "??=") {
|
|
1647
|
+
if (bindingPatternContainsName(assignment.left, name)) return true;
|
|
1648
|
+
assignment = assignment.right;
|
|
1649
|
+
}
|
|
1650
|
+
return false;
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
function lexicalDeclarationContainsName(node: unknown, name: string): boolean {
|
|
1654
|
+
if (!astNode(node)) return false;
|
|
1655
|
+
if (node.type === "VariableDeclaration" && node.kind !== "var" && Array.isArray(node.declarations)) {
|
|
1656
|
+
return node.declarations.some((declaration) => astNode(declaration) && bindingPatternContainsName(declaration.id, name));
|
|
1657
|
+
}
|
|
1658
|
+
return (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && bindingPatternContainsName(node.id, name);
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
function scopeShadowsIdentifier(node: AstNode, name: string): boolean {
|
|
1662
|
+
if (node.type === "BlockStatement" && Array.isArray(node.body)) return node.body.some((statement) => lexicalDeclarationContainsName(statement, name));
|
|
1663
|
+
if (node.type === "CatchClause") return bindingPatternContainsName(node.param, name);
|
|
1664
|
+
if (node.type === "ForStatement") return lexicalDeclarationContainsName(node.init, name);
|
|
1665
|
+
if (node.type === "ForInStatement" || node.type === "ForOfStatement") return lexicalDeclarationContainsName(node.left, name);
|
|
1666
|
+
if (node.type === "SwitchStatement" && Array.isArray(node.cases)) {
|
|
1667
|
+
return node.cases.some((entry) => astNode(entry) && Array.isArray(entry.consequent) && entry.consequent.some((statement) => lexicalDeclarationContainsName(statement, name)));
|
|
1668
|
+
}
|
|
1669
|
+
return false;
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
function walkAstWithoutShadowedIdentifier(node: unknown, name: string, visit: (node: AstNode) => void): void {
|
|
1673
|
+
if (Array.isArray(node)) {
|
|
1674
|
+
for (const item of node) walkAstWithoutShadowedIdentifier(item, name, visit);
|
|
1675
|
+
return;
|
|
1676
|
+
}
|
|
1677
|
+
if (!astNode(node) || scopeShadowsIdentifier(node, name)) return;
|
|
1678
|
+
visit(node);
|
|
1679
|
+
if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return;
|
|
1680
|
+
for (const [key, child] of Object.entries(node)) {
|
|
1681
|
+
if (!AST_LOCATION_KEYS.has(key)) walkAstWithoutShadowedIdentifier(child, name, visit);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1571
1685
|
function definitelyNonJson(node: AstNode, normalizeUndefined = false): string | undefined {
|
|
1572
1686
|
if (node.type === "Literal") {
|
|
1573
1687
|
if (typeof node.bigint === "string") return "BigInt values are not JSON-representable";
|
|
@@ -1636,6 +1750,43 @@ function validateStaticBaseRef(params: AstNode, owner: string): WorkflowScriptVa
|
|
|
1636
1750
|
return [];
|
|
1637
1751
|
}
|
|
1638
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
|
+
|
|
1639
1790
|
function directRunsAllKeys(call: AstNode): Array<{ key: string; node: AstNode }> {
|
|
1640
1791
|
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
1641
1792
|
const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
|
|
@@ -1780,6 +1931,8 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
|
|
|
1780
1931
|
? root.body[0].expression.callee
|
|
1781
1932
|
: undefined;
|
|
1782
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;
|
|
1783
1936
|
walkAst(workflowBody, (node) => {
|
|
1784
1937
|
if (node !== wrapper && node.async === true && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) {
|
|
1785
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) });
|
|
@@ -1807,6 +1960,7 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
|
|
|
1807
1960
|
}
|
|
1808
1961
|
}
|
|
1809
1962
|
if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
|
|
1963
|
+
if (agentNameError) errors.push(...validateStaticChildAgents(node, agentNameError));
|
|
1810
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])
|
|
1811
1965
|
? node.arguments[0]
|
|
1812
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])
|
|
@@ -1830,16 +1984,20 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
|
|
|
1830
1984
|
for (const declaration of statement.declarations) {
|
|
1831
1985
|
if (!astNode(declaration) || !astNode(declaration.id) || declaration.id.type !== "Identifier" || !astNode(declaration.init) || declaration.init.type !== "AwaitExpression" || !astNode(declaration.init.argument) || !directRunsCall(declaration.init.argument, "all")) continue;
|
|
1832
1986
|
const name = declaration.id.name as string;
|
|
1987
|
+
const laterStatements = workflowBody.body.slice(statementIndex + 1);
|
|
1833
1988
|
const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
|
|
1834
1989
|
if (keys.size === 0) continue;
|
|
1835
1990
|
const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
|
|
1836
1991
|
const itemCount = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements.length : 0;
|
|
1837
1992
|
const arrayResultShape = Array.from({ length: itemCount });
|
|
1838
|
-
for (const later of
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1993
|
+
for (const later of laterStatements) {
|
|
1994
|
+
walkAstWithoutShadowedIdentifier(later, name, (node) => {
|
|
1995
|
+
if (node.type !== "MemberExpression" || !astNode(node.object) || node.object.type !== "Identifier" || node.object.name !== name) return;
|
|
1996
|
+
const property = node.computed === true ? literalString(node.property) : astNode(node.property) && node.property.type === "Identifier" ? node.property.name as string : undefined;
|
|
1997
|
+
if (property && keys.has(property) && !(property in arrayResultShape)) errors.push({ message: `runs.all returns an ordered array; '${name}.${property}' is keyed access. Use an index, destructuring, or map(...).`, ...nodeLocation(node) });
|
|
1998
|
+
});
|
|
1999
|
+
if (statement.kind !== "const" && astNode(later) && later.type === "ExpressionStatement" && definitelyReassignsBinding(later.expression, name)) break;
|
|
2000
|
+
}
|
|
1843
2001
|
}
|
|
1844
2002
|
}
|
|
1845
2003
|
}
|
|
@@ -1905,11 +2063,11 @@ function isZeroUsage(usage: unknown): boolean {
|
|
|
1905
2063
|
}
|
|
1906
2064
|
|
|
1907
2065
|
function setupAbortResumeParams(params: Record<string, unknown>, result: WorkflowScriptChildResult, signal: AbortSignal): Record<string, unknown> | undefined {
|
|
1908
|
-
if (signal.aborted || result.ok || result.stopped || result.interrupted || !result.runId) return undefined;
|
|
2066
|
+
if (signal.aborted || result.state === "running" || result.ok || result.stopped || result.interrupted || !result.runId) return undefined;
|
|
1909
2067
|
const childResult = Array.isArray(result.results) && result.results.length === 1 && isRecord(result.results[0]) ? result.results[0] : undefined;
|
|
1910
2068
|
const error = typeof childResult?.error === "string" ? childResult.error : result.error;
|
|
1911
2069
|
if (error !== "This operation was aborted" || !isZeroUsage(childResult?.usage)) return undefined;
|
|
1912
|
-
const messages = Array.isArray(childResult?.messages) ? childResult.messages : [];
|
|
2070
|
+
const messages: unknown[] = Array.isArray(childResult?.messages) ? childResult.messages : [];
|
|
1913
2071
|
const message = messages.findLast((entry) => isRecord(entry) && entry.role === "assistant");
|
|
1914
2072
|
if (message !== undefined) {
|
|
1915
2073
|
if (!isRecord(message)) return undefined;
|
|
@@ -1928,10 +2086,11 @@ function setupAbortResumeParams(params: Record<string, unknown>, result: Workflo
|
|
|
1928
2086
|
}
|
|
1929
2087
|
|
|
1930
2088
|
export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
|
|
1931
|
-
|
|
1932
|
-
if (options.
|
|
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");
|
|
1933
2092
|
if (options.globalConcurrencyLimit !== undefined && (!Number.isSafeInteger(options.globalConcurrencyLimit) || options.globalConcurrencyLimit < 1)) {
|
|
1934
|
-
throw new
|
|
2093
|
+
throw new WorkflowScriptError("workflow script global concurrency limit must be a positive integer.", emptyPartial(), "runtime");
|
|
1935
2094
|
}
|
|
1936
2095
|
const launchSemaphore = new Semaphore(options.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
|
|
1937
2096
|
|
|
@@ -1941,7 +2100,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1941
2100
|
realpathSync(process.cwd());
|
|
1942
2101
|
} catch (error) {
|
|
1943
2102
|
const code = typeof error === "object" && error !== null && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
|
|
1944
|
-
if (code !== "ENOENT") throw new
|
|
2103
|
+
if (code !== "ENOENT") throw new WorkflowScriptError("Workflow current cwd could not be validated.", emptyPartial(), "runtime", { cause: error });
|
|
1945
2104
|
staleCwd = true;
|
|
1946
2105
|
}
|
|
1947
2106
|
try {
|
|
@@ -1957,7 +2116,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1957
2116
|
}
|
|
1958
2117
|
} catch (error) {
|
|
1959
2118
|
const detail = error instanceof Error ? error.message : String(error);
|
|
1960
|
-
throw new
|
|
2119
|
+
throw new WorkflowScriptError(`Workflow process cwd is unavailable: ${options.processCwd}: ${detail}`, emptyPartial(), "runtime", { cause: error });
|
|
1961
2120
|
}
|
|
1962
2121
|
}
|
|
1963
2122
|
|
|
@@ -1965,9 +2124,14 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1965
2124
|
try {
|
|
1966
2125
|
acornPath = resolveWorkflowParserEntry();
|
|
1967
2126
|
} catch (error) {
|
|
1968
|
-
throw new
|
|
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 });
|
|
1969
2134
|
}
|
|
1970
|
-
const worker = new Worker(WORKER_SOURCE, { eval: true, workerData: { acornPath } });
|
|
1971
2135
|
const emits: unknown[] = [];
|
|
1972
2136
|
const consoleEntries: WorkflowScriptResult["console"] = [];
|
|
1973
2137
|
const trace: WorkflowScriptTraceEntry[] = [];
|
|
@@ -2052,7 +2216,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2052
2216
|
return true;
|
|
2053
2217
|
};
|
|
2054
2218
|
const notifyChildSettled = (key: string, result: WorkflowScriptChildResult): void => {
|
|
2055
|
-
if (!options.onChildSettled || !options.workflowRunId) return;
|
|
2219
|
+
if (result.state === "running" || !options.onChildSettled || !options.workflowRunId) return;
|
|
2056
2220
|
const outcome: WorkflowChildSettledOutcome = result.ok
|
|
2057
2221
|
? "completed"
|
|
2058
2222
|
: result.stopped
|
|
@@ -2060,7 +2224,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2060
2224
|
: result.detached
|
|
2061
2225
|
? "paused"
|
|
2062
2226
|
: "failed";
|
|
2063
|
-
const outputReference = result.outputReference ?? result.
|
|
2227
|
+
const outputReference = result.outputReference ?? result.outputArtifactPath;
|
|
2064
2228
|
try {
|
|
2065
2229
|
options.onChildSettled({
|
|
2066
2230
|
workflowRunId: options.workflowRunId,
|
|
@@ -2070,6 +2234,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2070
2234
|
...(outputReference ? { outputReference } : {}),
|
|
2071
2235
|
...(!result.ok && result.error ? { error: result.error } : {}),
|
|
2072
2236
|
workflowRunning: !settled && !finishing,
|
|
2237
|
+
result,
|
|
2073
2238
|
});
|
|
2074
2239
|
} catch (error) {
|
|
2075
2240
|
console.error("Workflow onChildSettled callback failed:", error);
|
|
@@ -2104,8 +2269,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2104
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;
|
|
2105
2270
|
})()
|
|
2106
2271
|
: undefined;
|
|
2107
|
-
|
|
2108
|
-
|
|
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"));
|
|
2109
2275
|
else resolve({ value: outcome.value, ...partial() });
|
|
2110
2276
|
});
|
|
2111
2277
|
};
|
|
@@ -2125,7 +2291,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2125
2291
|
mayFlushAssembly = options.continueAfterAbortWhenChildrenSettled?.(error) === true;
|
|
2126
2292
|
} catch (callbackError) {
|
|
2127
2293
|
const callbackMessage = callbackError instanceof Error ? callbackError.message : String(callbackError);
|
|
2128
|
-
return finish({ error:
|
|
2294
|
+
return finish({ error: taggedWorkflowError(`Workflow assembly flush eligibility failed: ${callbackMessage}`, "runtime") });
|
|
2129
2295
|
}
|
|
2130
2296
|
if (mayFlushAssembly && allChildrenSettled) {
|
|
2131
2297
|
// A reloaded async workflow may already be past its last child launch.
|
|
@@ -2157,16 +2323,14 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2157
2323
|
const timer = options.timeoutMs === undefined
|
|
2158
2324
|
? undefined
|
|
2159
2325
|
: setTimeout(() => {
|
|
2160
|
-
|
|
2161
|
-
error.workflowErrorKind = "timeout";
|
|
2162
|
-
finish({ error });
|
|
2326
|
+
finish({ error: taggedWorkflowError(`Workflow script timed out after ${options.timeoutMs}ms.`, "timeout") });
|
|
2163
2327
|
}, options.timeoutMs);
|
|
2164
2328
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2165
2329
|
if (options.signal?.aborted) return onAbort();
|
|
2166
2330
|
|
|
2167
|
-
worker.on("error", (error) => finish({ error:
|
|
2331
|
+
worker.on("error", (error) => finish({ error: taggedWorkflowError(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`, "runtime") }));
|
|
2168
2332
|
worker.on("exit", (code) => {
|
|
2169
|
-
if (!settled && code !== 0) finish({ error:
|
|
2333
|
+
if (!settled && code !== 0) finish({ error: taggedWorkflowError(`Workflow worker exited with code ${code}.`, "runtime") });
|
|
2170
2334
|
});
|
|
2171
2335
|
worker.on("message", (message: Record<string, unknown>) => {
|
|
2172
2336
|
if (settled) return;
|
|
@@ -2178,7 +2342,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2178
2342
|
try {
|
|
2179
2343
|
assertWorkflowJsonValue(message.value, "emit");
|
|
2180
2344
|
} catch (error) {
|
|
2181
|
-
finish({ error:
|
|
2345
|
+
finish({ error: taggedWorkflowError(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`, "runtime") });
|
|
2182
2346
|
return;
|
|
2183
2347
|
}
|
|
2184
2348
|
emits.push(message.value);
|
|
@@ -2186,7 +2350,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2186
2350
|
options.onEmit?.([...emits]);
|
|
2187
2351
|
} catch (error) {
|
|
2188
2352
|
emits.pop();
|
|
2189
|
-
finish({ error:
|
|
2353
|
+
finish({ error: taggedWorkflowError(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`, "runtime") });
|
|
2190
2354
|
}
|
|
2191
2355
|
return;
|
|
2192
2356
|
}
|
|
@@ -2199,16 +2363,14 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2199
2363
|
try {
|
|
2200
2364
|
assertWorkflowJsonValue(message.value, "return");
|
|
2201
2365
|
} catch (error) {
|
|
2202
|
-
return finish({ error:
|
|
2366
|
+
return finish({ error: taggedWorkflowError(`Workflow return could not be persisted: ${error instanceof Error ? error.message : String(error)}`, "return-serialization") });
|
|
2203
2367
|
}
|
|
2204
2368
|
return finish({ value: message.value });
|
|
2205
2369
|
}
|
|
2206
2370
|
if (message.type === "error") {
|
|
2207
2371
|
const rawError = typeof message.error === "string" ? message.error : "Workflow script failed.";
|
|
2208
2372
|
const text = message.errorPhase === "return-serialization" ? `${rawError}${workflowReturnRecoveryHint(partial().children)}` : rawError;
|
|
2209
|
-
|
|
2210
|
-
if (message.errorKind === "detached-child") workflowError.workflowErrorKind = "detached-child";
|
|
2211
|
-
return finish({ error: workflowError });
|
|
2373
|
+
return finish({ error: isWorkflowScriptFailureKind(message.errorKind) ? taggedWorkflowError(text, message.errorKind) : new Error(text) });
|
|
2212
2374
|
}
|
|
2213
2375
|
if (message.type === "callObserved" && typeof message.callId === "number") {
|
|
2214
2376
|
const key = typeof message.key === "string" ? message.key : undefined;
|
|
@@ -2248,7 +2410,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2248
2410
|
}
|
|
2249
2411
|
},
|
|
2250
2412
|
(error: unknown) => {
|
|
2251
|
-
if (!settled)
|
|
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
|
+
}
|
|
2252
2417
|
},
|
|
2253
2418
|
);
|
|
2254
2419
|
};
|
|
@@ -2387,14 +2552,12 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2387
2552
|
: promise.then((result) => {
|
|
2388
2553
|
const recoverableAcceptanceMetadata = result.recovery?.status === "available-for-review"
|
|
2389
2554
|
&& result.recovery.reason === "acceptance-metadata-rejected";
|
|
2390
|
-
if (!result.ok && !result.stopped && !recoverableAcceptanceMetadata) {
|
|
2391
|
-
|
|
2392
|
-
if (result.detached) childError.workflowErrorKind = "detached-child";
|
|
2393
|
-
throw childError;
|
|
2555
|
+
if (!result.ok && result.state !== "running" && !result.stopped && !recoverableAcceptanceMetadata) {
|
|
2556
|
+
throw taggedWorkflowError(`Run '${key}' ${result.detached ? "detached" : "failed"}: ${result.error ?? result.output}`, result.detached ? "detached-child" : "child");
|
|
2394
2557
|
}
|
|
2395
2558
|
return result;
|
|
2396
2559
|
});
|
|
2397
|
-
const fingerprint =
|
|
2560
|
+
const fingerprint = workflowRunParamsFingerprint(params);
|
|
2398
2561
|
const existing = launches.get(key);
|
|
2399
2562
|
if (existing) {
|
|
2400
2563
|
if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
|
|
@@ -2418,8 +2581,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2418
2581
|
if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) {
|
|
2419
2582
|
return respond(Promise.reject(new Error(`runs.run('${key}') ${BASE_REF_VALIDATION_ERROR}`)));
|
|
2420
2583
|
}
|
|
2421
|
-
if (params.gate !== undefined
|
|
2422
|
-
|
|
2584
|
+
if (params.gate !== undefined) {
|
|
2585
|
+
const parsedGate = parseGateInput(params.gate);
|
|
2586
|
+
if (!parsedGate.ok) return respond(Promise.reject(new Error(`runs.run('${key}') ${parsedGate.error}`)));
|
|
2423
2587
|
}
|
|
2424
2588
|
if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) {
|
|
2425
2589
|
return respond(Promise.reject(new Error(`runs.run('${key}') gate cannot be combined with acceptance; use one gate command or acceptance.verify.` + describeGateAcceptanceConflict(params.gate, params.acceptance))));
|
|
@@ -2517,7 +2681,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2517
2681
|
const reason = childController.signal.reason;
|
|
2518
2682
|
return stoppedChildResult(key, reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
2519
2683
|
}).then((result) => {
|
|
2520
|
-
let normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
|
|
2684
|
+
let normalized = !result.ok && result.state !== "running" && !result.error ? { ...result, error: result.output } : result;
|
|
2521
2685
|
if (resolvedResumeLineage?.length && normalized.runId) {
|
|
2522
2686
|
normalized = { ...normalized, continuation: { runIds: [...new Set([...resolvedResumeLineage, normalized.runId])] } };
|
|
2523
2687
|
}
|
|
@@ -2525,8 +2689,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2525
2689
|
if (stoppedLaunches.has(key)) return children.get(key) ?? normalized;
|
|
2526
2690
|
children.set(key, normalized);
|
|
2527
2691
|
recordAcceptanceRecoveryBarrier(key, normalized);
|
|
2528
|
-
const state = normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
|
|
2529
|
-
|
|
2692
|
+
const state = normalized.state === "running" ? "started" : normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
|
|
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);
|
|
2530
2696
|
traceChanged();
|
|
2531
2697
|
notifyChildSettled(key, normalized);
|
|
2532
2698
|
return normalized;
|