@xzzpig/pi-subagents 0.7.0 → 0.9.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 +456 -4
- package/README.md +3 -3
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +43 -19
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +99 -18
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +278 -90
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1433 -166
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/permission-arbiter.ts +59 -52
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +1142 -69
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -858
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -2,9 +2,32 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { dirname, resolve as resolvePath } from "node:path";
|
|
4
4
|
import { Worker } from "node:worker_threads";
|
|
5
|
+
import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../runs/shared/parallel-utils.ts";
|
|
6
|
+
import { HOST_STEP_MAX_COUNT } from "../runs/shared/host-step-status.ts";
|
|
7
|
+
import { classifyTaskMutationIntent } from "../runs/shared/task-intent.ts";
|
|
8
|
+
import type { AcceptanceRecoveryMetadata, HostStepNodeV1, SingleResult } from "../shared/types.ts";
|
|
9
|
+
import { normalizeWorkflowHostCommandParams, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "./host-command.ts";
|
|
5
10
|
|
|
6
11
|
const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
12
|
+
function validGitRef(ref: unknown): ref is string {
|
|
13
|
+
if (typeof ref !== "string" || !ref || ref === "@" || Buffer.byteLength(ref, "utf-8") > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
|
|
14
|
+
if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
|
|
15
|
+
if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
|
|
16
|
+
return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
|
|
17
|
+
}
|
|
7
18
|
const requireFromPackage = createRequire(import.meta.url);
|
|
19
|
+
const WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5_000;
|
|
20
|
+
|
|
21
|
+
export interface WorkflowScriptValidationError {
|
|
22
|
+
message: string;
|
|
23
|
+
line?: number;
|
|
24
|
+
column?: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface WorkflowScriptValidationResult {
|
|
28
|
+
ok: boolean;
|
|
29
|
+
errors: WorkflowScriptValidationError[];
|
|
30
|
+
}
|
|
8
31
|
|
|
9
32
|
const WORKER_SOURCE = String.raw`
|
|
10
33
|
const { parentPort, workerData } = require("node:worker_threads");
|
|
@@ -33,6 +56,12 @@ let suppressNativePromiseConsumption = 0;
|
|
|
33
56
|
const activeNativePromises = [];
|
|
34
57
|
const pending = new Map();
|
|
35
58
|
const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
59
|
+
function validGitRef(ref) {
|
|
60
|
+
if (typeof ref !== "string" || !ref || ref === "@" || new TextEncoder().encode(ref).length > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
|
|
61
|
+
if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
|
|
62
|
+
if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
|
|
63
|
+
return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
|
|
64
|
+
}
|
|
36
65
|
const trackedPromiseTrackers = new WeakMap();
|
|
37
66
|
const trackedPromiseTargets = new WeakMap();
|
|
38
67
|
let nativePromiseTrackers = new WeakMap();
|
|
@@ -150,7 +179,15 @@ function trackObservationTracker(tracker, promise, allowFutureObservations = fal
|
|
|
150
179
|
get(promiseTarget, prop) {
|
|
151
180
|
if (prop === "then") return function promiseThen(onFulfilled, onRejected) {
|
|
152
181
|
consumeTrackedObservations(tracker);
|
|
153
|
-
|
|
182
|
+
const chainTracker = { observations: tracker.observations, consumed: false, dependencies: [tracker] };
|
|
183
|
+
const wrapHandler = (handler) => typeof handler === "function"
|
|
184
|
+
? function trackedThenHandler(...args) {
|
|
185
|
+
const value = handler.apply(this, args);
|
|
186
|
+
addTrackerDependency(chainTracker, promiseObservationTracker(value));
|
|
187
|
+
return trackedPromiseTarget(value);
|
|
188
|
+
}
|
|
189
|
+
: handler;
|
|
190
|
+
return trackObservationTracker(chainTracker, promiseTarget.then(wrapHandler(onFulfilled), wrapHandler(onRejected)), true);
|
|
154
191
|
};
|
|
155
192
|
if (prop === "catch") return function promiseCatch(onRejected) {
|
|
156
193
|
consumeTrackedObservations(tracker);
|
|
@@ -233,15 +270,287 @@ function hostCall(method, args, observation) {
|
|
|
233
270
|
: promise;
|
|
234
271
|
}
|
|
235
272
|
|
|
236
|
-
function runHostCall(key, params, collectFailure, batch) {
|
|
273
|
+
function runHostCall(key, params, collectFailure, batch, generatedLaneKey) {
|
|
237
274
|
const callId = ++nextCallId;
|
|
238
275
|
const promise = new Promise((resolve, reject) => {
|
|
239
276
|
pending.set(callId, { resolve, reject });
|
|
240
|
-
parentPort.postMessage({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}) } });
|
|
277
|
+
parentPort.postMessage({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}), ...(generatedLaneKey ? { generatedLaneKey } : {}) } });
|
|
241
278
|
});
|
|
242
279
|
return { key, callId, promise };
|
|
243
280
|
}
|
|
244
281
|
|
|
282
|
+
function isArrayIndexProperty(prop) {
|
|
283
|
+
if (!/^(0|[1-9]\d*)$/.test(prop)) return false;
|
|
284
|
+
const index = Number(prop);
|
|
285
|
+
return Number.isSafeInteger(index) && index >= 0 && index < 4294967295;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const runsAllResultTargets = new WeakMap();
|
|
289
|
+
|
|
290
|
+
const MAX_LANES = 32;
|
|
291
|
+
const MAX_LANE_STAGES = 16;
|
|
292
|
+
const MAX_LANE_STAGE_COUNT = 64;
|
|
293
|
+
const MAX_LANE_SPEC_BYTES = 64 * 1024;
|
|
294
|
+
const MAX_LANE_TASK_BYTES = 1024 * 1024;
|
|
295
|
+
const MAX_LANE_PATH_BYTES = 32 * 1024;
|
|
296
|
+
const MAX_LANE_BOARD_TEXT_BYTES = 256;
|
|
297
|
+
const LANE_PATH_FIELDS = new Set(["cwd", "output", "sessionDir"]);
|
|
298
|
+
|
|
299
|
+
function runsAllKeyAccessError(prop) {
|
|
300
|
+
return new Error("Cannot read runs.all result property '" + prop + "'. runs.all resolves to an ordered array, not a key map. Use results[0], array destructuring, or results.map((result) => result.output), not results." + prop + ".");
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function wrapRunsAllResults(results, keys) {
|
|
304
|
+
const keySet = new Set(keys);
|
|
305
|
+
const proxy = new Proxy(results, {
|
|
306
|
+
get(target, prop, receiver) {
|
|
307
|
+
if (typeof prop !== "string") return Reflect.get(target, prop, receiver);
|
|
308
|
+
if (prop === "then" || prop === "toJSON") return undefined;
|
|
309
|
+
if (prop in target || isArrayIndexProperty(prop)) return Reflect.get(target, prop, receiver);
|
|
310
|
+
if (keySet.has(prop)) throw runsAllKeyAccessError(prop);
|
|
311
|
+
throw runsAllKeyAccessError(prop);
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
runsAllResultTargets.set(proxy, results);
|
|
315
|
+
return proxy;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function laneByteLength(value) {
|
|
319
|
+
return new TextEncoder().encode(value).byteLength;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function laneBoardText(value) {
|
|
323
|
+
if (typeof value !== "string" || !value) return undefined;
|
|
324
|
+
if (laneByteLength(value) <= MAX_LANE_BOARD_TEXT_BYTES) return value;
|
|
325
|
+
const bytes = new TextEncoder().encode(value).subarray(0, MAX_LANE_BOARD_TEXT_BYTES - 3);
|
|
326
|
+
return new TextDecoder().decode(bytes) + "...";
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function laneBoardPath(value) {
|
|
330
|
+
if (typeof value !== "string" || !value || laneByteLength(value) > MAX_LANE_BOARD_TEXT_BYTES) return undefined;
|
|
331
|
+
return value;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function validateLaneStageBounds(params, label) {
|
|
335
|
+
if (typeof params.task === "string" && laneByteLength(params.task) > MAX_LANE_TASK_BYTES) throw new Error(label + " task exceeds 1 MiB when UTF-8 encoded.");
|
|
336
|
+
for (const field of LANE_PATH_FIELDS) if (typeof params[field] === "string" && laneByteLength(params[field]) > MAX_LANE_PATH_BYTES) throw new Error(label + " " + field + " exceeds 32 KiB when UTF-8 encoded.");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function validateLaneKey(value, owner) {
|
|
340
|
+
if (typeof value !== "string" || !runKeyPattern.test(value)) throw new Error(owner + " key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.");
|
|
341
|
+
return value;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function laneStageParams(stage, previous) {
|
|
345
|
+
const resume = stage.resume;
|
|
346
|
+
const params = { ...stage.params };
|
|
347
|
+
if (resume !== "previous") return params;
|
|
348
|
+
if (!previous || typeof previous.runId !== "string" || !previous.runId.trim()) return undefined;
|
|
349
|
+
return { ...params, resume: previous.runId.trim() };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function laneStageVerdict(result) {
|
|
353
|
+
const structured = result && typeof result === "object" && !Array.isArray(result) ? result.structuredOutput : undefined;
|
|
354
|
+
const verdict = structured && typeof structured === "object" && !Array.isArray(structured) ? structured.verdict : undefined;
|
|
355
|
+
return typeof verdict === "string" && verdict.trim() ? laneBoardText(verdict.trim()) : undefined;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function laneStageIsBlocked(result) {
|
|
359
|
+
const structured = result && typeof result === "object" && !Array.isArray(result) ? result.structuredOutput : undefined;
|
|
360
|
+
return structured && typeof structured === "object" && !Array.isArray(structured) && structured.verdict === "blocked";
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function laneStageRecord(stageKey, child, forcedState) {
|
|
364
|
+
const result = child && typeof child === "object" && !Array.isArray(child) ? child : undefined;
|
|
365
|
+
const ok = result?.ok === true;
|
|
366
|
+
const verdict = laneStageVerdict(result);
|
|
367
|
+
const blocked = laneStageIsBlocked(result);
|
|
368
|
+
const state = forcedState ?? (result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
|
|
369
|
+
const error = state !== "completed"
|
|
370
|
+
? state === "blocked" && blocked
|
|
371
|
+
? "Stage returned a blocked verdict."
|
|
372
|
+
: typeof result?.error === "string"
|
|
373
|
+
? result.error
|
|
374
|
+
: typeof result?.output === "string"
|
|
375
|
+
? result.output
|
|
376
|
+
: "Stage did not complete successfully."
|
|
377
|
+
: undefined;
|
|
378
|
+
return {
|
|
379
|
+
key: stageKey,
|
|
380
|
+
...(typeof result?.runId === "string" && result.runId.trim() ? { runId: laneBoardText(result.runId.trim()) } : {}),
|
|
381
|
+
...(result ? { ok } : {}),
|
|
382
|
+
state,
|
|
383
|
+
...(typeof result?.outputReference === "string" ? (laneBoardPath(result.outputReference) ? { outputReference: laneBoardPath(result.outputReference) } : {}) : {}),
|
|
384
|
+
...(verdict ? { verdict } : {}),
|
|
385
|
+
...(error ? { error: laneBoardText(error) } : {}),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function laneFailure(stageKey, error) {
|
|
390
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
391
|
+
return { key: stageKey, ok: false, output: text, error: text, artifactPaths: [] };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function runCollected(key, params, observe, generatedLaneKey) {
|
|
395
|
+
validateRunCall(key, params, "runs.lanes stage", runFingerprints);
|
|
396
|
+
const launched = runHostCall(key, params, true, undefined, generatedLaneKey);
|
|
397
|
+
observe([{ key, operation: "run", callId: launched.callId }]);
|
|
398
|
+
return launched.promise.then(decorateWorkflowChildResult);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function validateLaneSpecs(laneSpecs) {
|
|
402
|
+
if (!Array.isArray(laneSpecs)) throw new Error("runs.lanes(lanes) requires an array.");
|
|
403
|
+
if (laneSpecs.length === 0) throw new Error("runs.lanes(lanes) requires at least one lane.");
|
|
404
|
+
if (laneSpecs.length > MAX_LANES) throw new Error("runs.lanes supports at most " + MAX_LANES + " lanes.");
|
|
405
|
+
assertJsonValue(laneSpecs, "runs.lanes lanes");
|
|
406
|
+
if (laneByteLength(stableRunJson(laneSpecs)) > MAX_LANE_SPEC_BYTES) throw new Error("runs.lanes canonical JSON exceeds 64 KiB.");
|
|
407
|
+
const generatedKeys = new Set();
|
|
408
|
+
const validationFingerprints = new Map();
|
|
409
|
+
let stageCount = 0;
|
|
410
|
+
const normalized = [];
|
|
411
|
+
for (let laneIndex = 0; laneIndex < laneSpecs.length; laneIndex++) {
|
|
412
|
+
const lane = laneSpecs[laneIndex];
|
|
413
|
+
const laneLabel = "runs.lanes lane " + laneIndex;
|
|
414
|
+
if (!lane || typeof lane !== "object" || Array.isArray(lane)) throw new Error(laneLabel + " must be an object.");
|
|
415
|
+
const laneFields = Object.keys(lane);
|
|
416
|
+
if (laneFields.some((field) => field !== "key" && field !== "stages")) throw new Error(laneLabel + " contains unsupported fields.");
|
|
417
|
+
const laneKey = validateLaneKey(lane.key, laneLabel);
|
|
418
|
+
if (!Array.isArray(lane.stages) || lane.stages.length === 0) throw new Error(laneLabel + " stages must contain at least one stage.");
|
|
419
|
+
if (lane.stages.length > MAX_LANE_STAGES) throw new Error(laneLabel + " supports at most " + MAX_LANE_STAGES + " stages.");
|
|
420
|
+
const stageKeys = new Set();
|
|
421
|
+
const stages = [];
|
|
422
|
+
for (let stageIndex = 0; stageIndex < lane.stages.length; stageIndex++) {
|
|
423
|
+
stageCount++;
|
|
424
|
+
if (stageCount > MAX_LANE_STAGE_COUNT) throw new Error("runs.lanes supports at most " + MAX_LANE_STAGE_COUNT + " total stages.");
|
|
425
|
+
const stage = lane.stages[stageIndex];
|
|
426
|
+
const stageLabel = laneLabel + " stage " + stageIndex;
|
|
427
|
+
if (!stage || typeof stage !== "object" || Array.isArray(stage)) throw new Error(stageLabel + " must be an object.");
|
|
428
|
+
const stageKey = validateLaneKey(stage.key, stageLabel);
|
|
429
|
+
if (stageKeys.has(stageKey)) throw new Error(laneLabel + " contains duplicate stage key '" + stageKey + "'.");
|
|
430
|
+
stageKeys.add(stageKey);
|
|
431
|
+
const generatedKey = laneKey + "." + stageKey;
|
|
432
|
+
validateLaneKey(generatedKey, stageLabel + " generated");
|
|
433
|
+
if (generatedKeys.has(generatedKey)) throw new Error("runs.lanes generated child key '" + generatedKey + "' is duplicated.");
|
|
434
|
+
generatedKeys.add(generatedKey);
|
|
435
|
+
const resume = stage.resume;
|
|
436
|
+
if (resume !== undefined && resume !== "previous") {
|
|
437
|
+
if (stageIndex === 0 && typeof resume === "string") {
|
|
438
|
+
throw new Error(stageLabel + " cannot resume a retained run id in runs.lanes; use runs.run(key, { resume: id }) outside lanes, or start the lane with an agent stage and use resume: \"previous\" later.");
|
|
439
|
+
}
|
|
440
|
+
throw new Error(stageLabel + " resume must be 'previous'.");
|
|
441
|
+
}
|
|
442
|
+
if (stageIndex === 0 && resume === "previous") throw new Error(stageLabel + " cannot resume previous without a predecessor stage.");
|
|
443
|
+
const { key: _stageKey, resume: _resume, ...params } = stage;
|
|
444
|
+
const validationParams = resume === "previous" ? { ...params, resume: "retained-run-placeholder" } : params;
|
|
445
|
+
validateLaneStageBounds(validationParams, stageLabel);
|
|
446
|
+
validateRunCall(generatedKey, validationParams, stageLabel, validationFingerprints);
|
|
447
|
+
const existingFingerprint = runFingerprints.get(generatedKey);
|
|
448
|
+
if (existingFingerprint !== undefined && (resume === "previous" || existingFingerprint !== stableRunJson(params))) {
|
|
449
|
+
throw new Error("runs.lanes generated child key '" + generatedKey + "' is already used with incompatible launch params.");
|
|
450
|
+
}
|
|
451
|
+
stages.push({ key: stageKey, generatedKey, resume, params });
|
|
452
|
+
}
|
|
453
|
+
normalized.push({ key: laneKey, stages });
|
|
454
|
+
}
|
|
455
|
+
return normalized;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function runLane(lane, firstResult, observe) {
|
|
459
|
+
const records = [];
|
|
460
|
+
const appendSkipped = (start) => {
|
|
461
|
+
for (let index = start; index < lane.stages.length; index++) records.push({ key: lane.stages[index].key, state: "skipped" });
|
|
462
|
+
};
|
|
463
|
+
const finish = (state, failedStage) => ({ key: lane.key, state, ...(failedStage ? { failedStage } : {}), stages: records });
|
|
464
|
+
const visit = (index, previous) => {
|
|
465
|
+
if (index >= lane.stages.length) return Promise.resolve(finish("complete"));
|
|
466
|
+
const stage = lane.stages[index];
|
|
467
|
+
if (index === 0) {
|
|
468
|
+
const record = laneStageRecord(stage.key, previous);
|
|
469
|
+
records.push(record);
|
|
470
|
+
if (record.state !== "completed") {
|
|
471
|
+
appendSkipped(index + 1);
|
|
472
|
+
return Promise.resolve(finish("blocked", stage.key));
|
|
473
|
+
}
|
|
474
|
+
return visit(index + 1, previous);
|
|
475
|
+
}
|
|
476
|
+
if (stage.resume === "previous" && (!previous || typeof previous.runId !== "string" || !previous.runId.trim())) {
|
|
477
|
+
records.push({ key: stage.key, state: "blocked", error: "Previous stage did not return a retained run id." });
|
|
478
|
+
appendSkipped(index + 1);
|
|
479
|
+
return Promise.resolve(finish("blocked", stage.key));
|
|
480
|
+
}
|
|
481
|
+
if (!previous || previous.ok !== true || laneStageIsBlocked(previous)) {
|
|
482
|
+
records.push({ key: stage.key, state: "blocked", error: "Previous stage did not complete successfully." });
|
|
483
|
+
appendSkipped(index + 1);
|
|
484
|
+
return Promise.resolve(finish("blocked", stage.key));
|
|
485
|
+
}
|
|
486
|
+
const params = laneStageParams(stage, previous);
|
|
487
|
+
if (!params) {
|
|
488
|
+
records.push({ key: stage.key, state: "blocked", error: "Previous stage did not return a retained run id." });
|
|
489
|
+
appendSkipped(index + 1);
|
|
490
|
+
return Promise.resolve(finish("blocked", stage.key));
|
|
491
|
+
}
|
|
492
|
+
let launched;
|
|
493
|
+
try {
|
|
494
|
+
launched = runCollected(stage.generatedKey, params, observe, lane.key);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
const failed = laneFailure(stage.generatedKey, error);
|
|
497
|
+
records.push(laneStageRecord(stage.key, failed));
|
|
498
|
+
appendSkipped(index + 1);
|
|
499
|
+
return Promise.resolve(finish("blocked", stage.key));
|
|
500
|
+
}
|
|
501
|
+
return launched.then((result) => {
|
|
502
|
+
const record = laneStageRecord(stage.key, result);
|
|
503
|
+
records.push(record);
|
|
504
|
+
if (record.state === "completed") return visit(index + 1, result);
|
|
505
|
+
appendSkipped(index + 1);
|
|
506
|
+
return finish("blocked", stage.key);
|
|
507
|
+
}, (error) => {
|
|
508
|
+
const failed = laneFailure(stage.generatedKey, error);
|
|
509
|
+
records.push(laneStageRecord(stage.key, failed));
|
|
510
|
+
appendSkipped(index + 1);
|
|
511
|
+
return finish("blocked", stage.key);
|
|
512
|
+
});
|
|
513
|
+
};
|
|
514
|
+
return visit(0, firstResult);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function workflowPlanStringMetadata(params) {
|
|
518
|
+
return {
|
|
519
|
+
...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
|
|
520
|
+
...(typeof params.label === "string" && params.label.trim() ? { label: params.label.trim() } : {}),
|
|
521
|
+
...(typeof params.agent === "string" && params.agent.trim() ? { agent: params.agent.trim() } : {}),
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function runLanes(laneSpecs) {
|
|
526
|
+
const lanes = validateLaneSpecs(laneSpecs);
|
|
527
|
+
parentPort.postMessage({ type: "lanePlan", lanes: lanes.map((lane) => ({
|
|
528
|
+
key: lane.key,
|
|
529
|
+
stages: lane.stages.map((stage) => ({
|
|
530
|
+
key: stage.key,
|
|
531
|
+
generatedKey: stage.generatedKey,
|
|
532
|
+
...workflowPlanStringMetadata(stage.params),
|
|
533
|
+
...(typeof stage.params.as === "string" && stage.params.as.trim() ? { outputName: stage.params.as.trim() } : {}),
|
|
534
|
+
...(stage.params.outputSchema !== undefined ? { structured: true } : {}),
|
|
535
|
+
})),
|
|
536
|
+
})) });
|
|
537
|
+
const firstItems = lanes.map((lane) => {
|
|
538
|
+
const first = lane.stages[0];
|
|
539
|
+
return { key: first.generatedKey, ...first.params };
|
|
540
|
+
});
|
|
541
|
+
// Share the runs.all batch launcher while allowing each lane to advance independently.
|
|
542
|
+
const firstBatch = launchRunsAll(firstItems, lanes.map((lane) => lane.key));
|
|
543
|
+
const firstResults = firstBatch.launched.map(({ promise }) => promise.then(decorateWorkflowChildResult));
|
|
544
|
+
let trackedAggregate;
|
|
545
|
+
const observe = (observations) => trackRunObservation(observations, trackedAggregate);
|
|
546
|
+
const laneAggregate = Promise.all(lanes.map((lane, index) => firstResults[index].then(
|
|
547
|
+
(result) => runLane(lane, result, observe),
|
|
548
|
+
(error) => runLane(lane, laneFailure(lane.stages[0].generatedKey, error), observe),
|
|
549
|
+
)));
|
|
550
|
+
trackedAggregate = trackRunObservation(firstBatch.launched.map(({ key, callId }) => ({ key, operation: "run", callId })), laneAggregate);
|
|
551
|
+
return trackedAggregate;
|
|
552
|
+
}
|
|
553
|
+
|
|
245
554
|
function formatRef(result) {
|
|
246
555
|
if (!result || typeof result !== "object") throw new Error("runs.ref(result) requires a run result object.");
|
|
247
556
|
const parts = ["run " + (result.key || "unknown")];
|
|
@@ -249,20 +558,78 @@ function formatRef(result) {
|
|
|
249
558
|
return "[" + parts.join("; ") + "]";
|
|
250
559
|
}
|
|
251
560
|
|
|
561
|
+
function formatChildResultString(result) {
|
|
562
|
+
const output = typeof result?.output === "string" ? result.output.trim() : "";
|
|
563
|
+
return output || formatRef(result);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function decorateWorkflowChildResult(result) {
|
|
567
|
+
if (!result || typeof result !== "object" || Array.isArray(result)) return result;
|
|
568
|
+
Object.defineProperties(result, {
|
|
569
|
+
toString: { value() { return formatChildResultString(this); }, enumerable: false, configurable: true },
|
|
570
|
+
});
|
|
571
|
+
return result;
|
|
572
|
+
}
|
|
573
|
+
|
|
252
574
|
let runFingerprints = new Map();
|
|
253
575
|
|
|
576
|
+
function validateExtensionBindings(value, label) {
|
|
577
|
+
if (value === undefined) return;
|
|
578
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " extensionBindings must be a plain JSON object.");
|
|
579
|
+
const keys = Object.keys(value);
|
|
580
|
+
if (keys.length > 16) throw new Error(label + " extensionBindings supports at most 16 namespaces.");
|
|
581
|
+
for (const key of keys) if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62})\/[1-9][0-9]{0,8}$/.test(key)) throw new Error(label + " extensionBindings namespace '" + key + "' must use a package-like name followed by '/<positive-version>'.");
|
|
582
|
+
assertJsonValue(value, label + " extensionBindings");
|
|
583
|
+
let propertyCount = 0;
|
|
584
|
+
function visit(entry, depth) {
|
|
585
|
+
if (!entry || typeof entry !== "object") return;
|
|
586
|
+
if (depth > 16) throw new Error(label + " extensionBindings exceeds the maximum nesting depth of 16.");
|
|
587
|
+
if (Array.isArray(entry)) { for (const item of entry) visit(item, depth + 1); return; }
|
|
588
|
+
for (const child of Object.values(entry)) {
|
|
589
|
+
propertyCount++;
|
|
590
|
+
if (propertyCount > 256) throw new Error(label + " extensionBindings exceeds 256 total properties.");
|
|
591
|
+
visit(child, depth + 1);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
visit(value, 0);
|
|
595
|
+
if (new TextEncoder().encode(stableRunJson(value)).byteLength > 16384) throw new Error(label + " extensionBindings canonical JSON exceeds 16384 bytes.");
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function validateLaneMetadata(value, label, workflowKey) {
|
|
599
|
+
if (value === undefined) return;
|
|
600
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be a plain JSON object.");
|
|
601
|
+
const fields = Object.keys(value);
|
|
602
|
+
const allowed = ["version", "key", "mode", "sourceRef", "claims", "outputPaths"];
|
|
603
|
+
const unknown = fields.filter((field) => !allowed.includes(field));
|
|
604
|
+
if (unknown.length > 0) throw new Error(label + " has unsupported fields: " + unknown.join(", ") + ".");
|
|
605
|
+
if (value.version !== 1) throw new Error(label + ".version must be 1.");
|
|
606
|
+
if (typeof value.key !== "string" || !value.key.trim() || !runKeyPattern.test(value.key.trim())) throw new Error(label + ".key is invalid.");
|
|
607
|
+
if (workflowKey !== undefined && value.key.trim() !== workflowKey) throw new Error(label + ".key must match workflow key '" + workflowKey + "'.");
|
|
608
|
+
if (value.mode !== undefined && !["mutation", "review", "scout", "gate"].includes(value.mode)) throw new Error(label + ".mode is invalid.");
|
|
609
|
+
const bounded = (entry, maxBytes) => typeof entry === "string" && entry.trim() && new TextEncoder().encode(entry.trim()).byteLength <= maxBytes && !/[\r\n\u0000]/.test(entry);
|
|
610
|
+
if (value.sourceRef !== undefined && !bounded(value.sourceRef, 128)) throw new Error(label + ".sourceRef is invalid.");
|
|
611
|
+
for (const [name, maxItems, maxLength] of [["claims", 20, 160], ["outputPaths", 10, 256]]) {
|
|
612
|
+
if (value[name] === undefined) continue;
|
|
613
|
+
if (!Array.isArray(value[name]) || value[name].length > maxItems || value[name].some((entry) => !bounded(entry, maxLength))) throw new Error(label + "." + name + " is invalid.");
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
254
617
|
function validateRunCall(key, params, label, fingerprints) {
|
|
255
618
|
if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
|
|
619
|
+
if (hostKeys.has(key)) throw new Error("Workflow key '" + key + "' is already used by runs.host.");
|
|
256
620
|
if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error(label + " requires a params object.");
|
|
257
|
-
if (Object.prototype.hasOwnProperty.call(params, "action") || Object.prototype.hasOwnProperty.call(params, "workflowScript") || Object.prototype.hasOwnProperty.call(params, "tasks") || Object.prototype.hasOwnProperty.call(params, "chain") || Object.prototype.hasOwnProperty.call(params, "parallel") || Object.prototype.hasOwnProperty.call(params, "concurrency") || Object.prototype.hasOwnProperty.call(params, "chainDir")) {
|
|
621
|
+
if (Object.prototype.hasOwnProperty.call(params, "action") || Object.prototype.hasOwnProperty.call(params, "workflowScript") || Object.prototype.hasOwnProperty.call(params, "globalConcurrencyLimit") || Object.prototype.hasOwnProperty.call(params, "maxSubagentSpawnsPerRun") || Object.prototype.hasOwnProperty.call(params, "tasks") || Object.prototype.hasOwnProperty.call(params, "chain") || Object.prototype.hasOwnProperty.call(params, "parallel") || Object.prototype.hasOwnProperty.call(params, "concurrency") || Object.prototype.hasOwnProperty.call(params, "chainDir")) {
|
|
258
622
|
const hint = label === "runs.run" ? "; use runs.all(...) and JavaScript control flow for orchestration." : ".";
|
|
259
623
|
throw new Error(label + " accepts one child via { agent, task } and execution controls only" + hint);
|
|
260
624
|
}
|
|
261
625
|
if (Object.prototype.hasOwnProperty.call(params, "clarify")) throw new Error(label + " does not support clarify UI.");
|
|
262
626
|
if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
|
|
627
|
+
if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) throw new Error(label + " baseRef must be a valid Git ref.");
|
|
628
|
+
validateLaneMetadata(params.lane, label + " lane", key);
|
|
263
629
|
if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) throw new Error(label + " gate must be a non-empty command string.");
|
|
264
630
|
if (params.gate !== undefined && params.acceptance !== undefined) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify.");
|
|
265
631
|
if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
|
|
632
|
+
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.");
|
|
266
633
|
if (params.resume !== undefined && typeof params.resume !== "string") {
|
|
267
634
|
const reference = params.resume;
|
|
268
635
|
if (!reference || typeof reference !== "object" || Array.isArray(reference)) throw new Error(label + " resume must be a retained run id or keyed workflow receipt reference.");
|
|
@@ -275,6 +642,7 @@ function validateRunCall(key, params, label, fingerprints) {
|
|
|
275
642
|
if (typeof params.resume === "string" && !params.resume.trim()) throw new Error(label + " resume must be a non-empty retained run id.");
|
|
276
643
|
if (params.resume !== undefined && params.agent !== undefined) throw new Error(label + " resume and agent are mutually exclusive.");
|
|
277
644
|
if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) throw new Error(label + " resume requires a non-empty task follow-up.");
|
|
645
|
+
validateExtensionBindings(params.extensionBindings, label);
|
|
278
646
|
assertJsonValue(params, label + " params");
|
|
279
647
|
const fingerprint = stableRunJson(params);
|
|
280
648
|
const existing = fingerprints.get(key);
|
|
@@ -282,27 +650,65 @@ function validateRunCall(key, params, label, fingerprints) {
|
|
|
282
650
|
fingerprints.set(key, fingerprint);
|
|
283
651
|
}
|
|
284
652
|
|
|
653
|
+
const hostKeys = new Set();
|
|
654
|
+
|
|
655
|
+
function validateHostCommand(key, params) {
|
|
656
|
+
validateLaneKey(key, "runs.host");
|
|
657
|
+
if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("runs.host('" + key + "') params must be an object.");
|
|
658
|
+
const allowed = new Set(["kind", "command", "timeoutMs", "output", "role", "provider"]);
|
|
659
|
+
const unknown = Object.keys(params).filter((field) => !allowed.has(field));
|
|
660
|
+
if (unknown.length) {
|
|
661
|
+
const cwdHint = unknown.includes("cwd")
|
|
662
|
+
? " The host step does not accept per-step cwd; commands and relative output paths use the workflow cwd. Set cwd on the outer subagent request, or put a trusted directory change in command (for example, 'cd /path/to/worktree && npm test')."
|
|
663
|
+
: "";
|
|
664
|
+
throw new Error("runs.host('" + key + "') params have unsupported fields: " + unknown.join(", ") + "." + cwdHint);
|
|
665
|
+
}
|
|
666
|
+
if (params.kind !== "command") throw new Error("runs.host('" + key + "') kind must be 'command'.");
|
|
667
|
+
if (typeof params.command !== "string" || !params.command.trim() || params.command.includes("\u0000") || new TextEncoder().encode(params.command.trim()).byteLength > 16384) throw new Error("runs.host('" + key + "') command must be a non-empty string of at most 16384 bytes without NUL.");
|
|
668
|
+
if (!Number.isInteger(params.timeoutMs) || params.timeoutMs < 1 || params.timeoutMs > 86400000) throw new Error("runs.host('" + key + "') timeoutMs must be an integer from 1 to 86400000.");
|
|
669
|
+
if (params.output !== undefined && (typeof params.output !== "string" || !params.output.trim() || /^[/\\]|(?:^|[/\\])\.\.(?:[/\\]|$)/.test(params.output) || /[\u0000-\u001f\u007f]/.test(params.output) || new TextEncoder().encode(params.output.trim()).byteLength > 240)) throw new Error("runs.host('" + key + "') output must be a bounded relative path without traversal or control characters.");
|
|
670
|
+
if (params.role !== undefined && params.role !== "ci" && params.role !== "gate") throw new Error("runs.host('" + key + "') role must be 'ci' or 'gate'.");
|
|
671
|
+
if (params.provider !== undefined && (typeof params.provider !== "string" || !params.provider.trim() || /[\r\n\u0000]/.test(params.provider) || new TextEncoder().encode(params.provider.trim()).byteLength > 64)) throw new Error("runs.host('" + key + "') provider must be a non-empty single-line string of at most 64 bytes.");
|
|
672
|
+
assertJsonValue(params, "runs.host('" + key + "') params");
|
|
673
|
+
if (hostKeys.has(key) || runFingerprints.has(key)) throw new Error("Workflow key '" + key + "' is already in use.");
|
|
674
|
+
if (hostKeys.size >= 32) throw new Error("workflowScript supports at most 32 runs.host calls.");
|
|
675
|
+
hostKeys.add(key);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
function launchRunsAll(items, generatedLaneKeys) {
|
|
679
|
+
if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
|
|
680
|
+
const fingerprints = new Map(runFingerprints);
|
|
681
|
+
const calls = [];
|
|
682
|
+
for (let index = 0; index < items.length; index++) {
|
|
683
|
+
if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
|
|
684
|
+
const item = items[index];
|
|
685
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object.");
|
|
686
|
+
const { key, ...params } = item;
|
|
687
|
+
validateRunCall(key, params, "runs.all item " + index, fingerprints);
|
|
688
|
+
calls.push({ key, params });
|
|
689
|
+
}
|
|
690
|
+
runFingerprints = fingerprints;
|
|
691
|
+
const batch = { id: "batch-" + (++nextCallId), calls };
|
|
692
|
+
const launched = calls.map(({ key, params }, index) => runHostCall(key, params, true, batch, generatedLaneKeys?.[index]));
|
|
693
|
+
return { calls, launched };
|
|
694
|
+
}
|
|
695
|
+
|
|
285
696
|
const runs = Object.freeze({
|
|
286
697
|
run(key, params) {
|
|
287
698
|
validateRunCall(key, params, "runs.run", runFingerprints);
|
|
288
|
-
|
|
699
|
+
const launched = runHostCall(key, params, false);
|
|
700
|
+
return trackRunObservation([{ key, operation: "run", callId: launched.callId }], launched.promise.then(decorateWorkflowChildResult));
|
|
289
701
|
},
|
|
290
702
|
all(items) {
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
calls.push({ key, params });
|
|
301
|
-
}
|
|
302
|
-
runFingerprints = fingerprints;
|
|
303
|
-
const batch = { id: "batch-" + (++nextCallId), calls };
|
|
304
|
-
const launched = calls.map(({ key, params }) => runHostCall(key, params, true, batch));
|
|
305
|
-
return trackRunObservation(launched.map(({ key, callId }) => ({ key, operation: "run", callId })), Promise.all(launched.map(({ promise }) => promise)));
|
|
703
|
+
const { calls, launched } = launchRunsAll(items);
|
|
704
|
+
return trackRunObservation(launched.map(({ key, callId }) => ({ key, operation: "run", callId })), Promise.all(launched.map(({ promise }) => promise)).then((results) => wrapRunsAllResults(results.map(decorateWorkflowChildResult), calls.map(({ key }) => key))));
|
|
705
|
+
},
|
|
706
|
+
lanes(laneSpecs) {
|
|
707
|
+
return runLanes(laneSpecs);
|
|
708
|
+
},
|
|
709
|
+
host(key, params) {
|
|
710
|
+
validateHostCommand(key, params);
|
|
711
|
+
return hostCall("host", { key, params }, { key, operation: "host" });
|
|
306
712
|
},
|
|
307
713
|
steer(key, message, options = {}) {
|
|
308
714
|
if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error("runs.steer has an invalid key.");
|
|
@@ -367,7 +773,7 @@ function isSyntaxError(error) {
|
|
|
367
773
|
return error instanceof SyntaxError || error?.name === "SyntaxError";
|
|
368
774
|
}
|
|
369
775
|
|
|
370
|
-
const NESTED_ASYNC_WORKFLOW_ERROR = "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.";
|
|
776
|
+
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 } };";
|
|
371
777
|
const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
|
|
372
778
|
|
|
373
779
|
function assertPortableWorkflowScript(source) {
|
|
@@ -431,6 +837,31 @@ function isPlainWorkflowObject(value) {
|
|
|
431
837
|
return prototype === null || prototype === Object.prototype || prototype === contextObjectPrototype;
|
|
432
838
|
}
|
|
433
839
|
|
|
840
|
+
function unwrapRunsAllResults(value, seen = new Map()) {
|
|
841
|
+
if (value === null || typeof value !== "object") return value;
|
|
842
|
+
const runsAllTarget = runsAllResultTargets.get(value);
|
|
843
|
+
const target = runsAllTarget || value;
|
|
844
|
+
if (seen.has(target)) return seen.get(target);
|
|
845
|
+
if (Array.isArray(target)) {
|
|
846
|
+
const copy = [];
|
|
847
|
+
seen.set(target, copy);
|
|
848
|
+
let changed = !!runsAllTarget;
|
|
849
|
+
for (let index = 0; index < target.length; index++) {
|
|
850
|
+
copy[index] = unwrapRunsAllResults(target[index], seen);
|
|
851
|
+
changed ||= copy[index] !== target[index];
|
|
852
|
+
}
|
|
853
|
+
return changed ? copy : target;
|
|
854
|
+
}
|
|
855
|
+
if (!isPlainWorkflowObject(target) || Object.getOwnPropertySymbols(target).length > 0) return target;
|
|
856
|
+
let changed = false;
|
|
857
|
+
const entries = Object.entries(target).map(([key, entry]) => {
|
|
858
|
+
const unwrapped = unwrapRunsAllResults(entry, seen);
|
|
859
|
+
changed ||= unwrapped !== entry;
|
|
860
|
+
return [key, unwrapped];
|
|
861
|
+
});
|
|
862
|
+
return changed ? Object.fromEntries(entries) : target;
|
|
863
|
+
}
|
|
864
|
+
|
|
434
865
|
function omitUndefinedWorkflowValues(value, seen = new Set()) {
|
|
435
866
|
if (value === null || typeof value !== "object") return value;
|
|
436
867
|
if (seen.has(value)) return value;
|
|
@@ -459,7 +890,7 @@ parentPort.on("message", async (message) => {
|
|
|
459
890
|
}
|
|
460
891
|
if (message.type !== "start") return;
|
|
461
892
|
try {
|
|
462
|
-
const sandbox = { runs, Promise: workflowPromise, emit(value) {
|
|
893
|
+
const sandbox = { runs, Promise: workflowPromise, emit(value) { const emittedValue = unwrapRunsAllResults(value); assertJsonValue(emittedValue); parentPort.postMessage({ type: "emit", value: emittedValue }); }, console: capturedConsole };
|
|
463
894
|
if (message.stateEnabled) sandbox.state = state;
|
|
464
895
|
const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
|
|
465
896
|
contextObjectPrototype = vm.runInContext("Object.prototype", context);
|
|
@@ -529,7 +960,12 @@ parentPort.on("message", async (message) => {
|
|
|
529
960
|
}
|
|
530
961
|
}
|
|
531
962
|
const persistedValue = value === undefined ? null : omitUndefinedWorkflowValues(value);
|
|
532
|
-
|
|
963
|
+
try {
|
|
964
|
+
assertJsonValue(persistedValue, "return");
|
|
965
|
+
} catch (error) {
|
|
966
|
+
parentPort.postMessage({ type: "error", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
533
969
|
parentPort.postMessage({ type: "complete", value: persistedValue });
|
|
534
970
|
} catch (error) {
|
|
535
971
|
parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), ...(error && error.workflowErrorKind === "detached-child" ? { errorKind: "detached-child" } : {}) });
|
|
@@ -540,24 +976,31 @@ parentPort.on("message", async (message) => {
|
|
|
540
976
|
export interface WorkflowScriptChildResult {
|
|
541
977
|
key: string;
|
|
542
978
|
ok: boolean;
|
|
979
|
+
lane?: import("../shared/types.ts").WorkflowLaneMetadata;
|
|
980
|
+
terminalOutcome?: import("../shared/types.ts").WorkflowTerminalOutcome;
|
|
981
|
+
stopped?: boolean;
|
|
543
982
|
/** Canonical child agent name when launch resolution produced one. */
|
|
544
983
|
agent?: string;
|
|
545
984
|
runId?: string;
|
|
546
985
|
output: string;
|
|
547
986
|
error?: string;
|
|
548
987
|
detached?: boolean;
|
|
988
|
+
interrupted?: boolean;
|
|
549
989
|
structuredOutput?: unknown;
|
|
550
990
|
requestedContext?: "fresh" | "fork";
|
|
551
991
|
resolvedContext?: "fresh" | "fork" | "mixed";
|
|
552
992
|
outputReference?: string;
|
|
993
|
+
recovery?: AcceptanceRecoveryMetadata;
|
|
994
|
+
outputPathMapping?: { requestedPath: string; savedPath: string };
|
|
995
|
+
externalAdapter?: import("../shared/types.ts").ExternalCliReceiptMetadata;
|
|
553
996
|
resumability?: { state: "resumable" } | { state: "not-resumable"; reason: string };
|
|
554
997
|
continuation?: { runIds: string[] };
|
|
555
998
|
artifactPaths: string[];
|
|
556
|
-
results?:
|
|
999
|
+
results?: SingleResult[];
|
|
557
1000
|
}
|
|
558
1001
|
|
|
559
1002
|
export interface WorkflowScriptTraceEntry {
|
|
560
|
-
operation: "run" | "status" | "steer";
|
|
1003
|
+
operation: "run" | "status" | "steer" | "host";
|
|
561
1004
|
key: string;
|
|
562
1005
|
state: "started" | "completed" | "failed" | "detached" | "stopped" | "reused" | "queued" | "delivered" | "missed";
|
|
563
1006
|
/** Canonical child agent name when resolved launch or result data is available. */
|
|
@@ -567,6 +1010,26 @@ export interface WorkflowScriptTraceEntry {
|
|
|
567
1010
|
phase?: string;
|
|
568
1011
|
label?: string;
|
|
569
1012
|
error?: string;
|
|
1013
|
+
/** Internal provenance for a generated runs.lanes child key. */
|
|
1014
|
+
generatedLaneKey?: string;
|
|
1015
|
+
lane?: import("../shared/types.ts").WorkflowLaneMetadata;
|
|
1016
|
+
warning?: string;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** Bounded plan metadata emitted when a workflow materializes a runs.lanes graph. */
|
|
1020
|
+
export interface WorkflowLanePlanStage {
|
|
1021
|
+
key: string;
|
|
1022
|
+
generatedKey: string;
|
|
1023
|
+
agent?: string;
|
|
1024
|
+
phase?: string;
|
|
1025
|
+
label?: string;
|
|
1026
|
+
outputName?: string;
|
|
1027
|
+
structured?: boolean;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
export interface WorkflowLanePlan {
|
|
1031
|
+
key: string;
|
|
1032
|
+
stages: WorkflowLanePlanStage[];
|
|
570
1033
|
}
|
|
571
1034
|
|
|
572
1035
|
export interface WorkflowSteerOptions {
|
|
@@ -605,9 +1068,9 @@ export interface WorkflowScriptResult {
|
|
|
605
1068
|
|
|
606
1069
|
export class WorkflowScriptError extends Error {
|
|
607
1070
|
readonly partial: Omit<WorkflowScriptResult, "value">;
|
|
608
|
-
readonly errorKind?: "detached-child";
|
|
1071
|
+
readonly errorKind?: "detached-child" | "timeout";
|
|
609
1072
|
|
|
610
|
-
constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: "detached-child") {
|
|
1073
|
+
constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: "detached-child" | "timeout") {
|
|
611
1074
|
super(message);
|
|
612
1075
|
this.name = "WorkflowScriptError";
|
|
613
1076
|
this.partial = partial;
|
|
@@ -617,25 +1080,183 @@ export class WorkflowScriptError extends Error {
|
|
|
617
1080
|
|
|
618
1081
|
export interface RunWorkflowScriptOptions {
|
|
619
1082
|
script: string;
|
|
1083
|
+
/** Host-only first-slice admission context. It is never sent to the workflow worker. */
|
|
1084
|
+
oneUsePermit?: { claim: (key: string) => string | undefined };
|
|
620
1085
|
timeoutMs?: number;
|
|
621
1086
|
signal?: AbortSignal;
|
|
1087
|
+
/** Let an async workflow flush pure result assembly after reload once every child is terminal. */
|
|
1088
|
+
continueAfterAbortWhenChildrenSettled?: (abortError: Error) => boolean;
|
|
1089
|
+
/** Maximum children executing concurrently within this workflow. Defaults to 20. */
|
|
1090
|
+
globalConcurrencyLimit?: number;
|
|
622
1091
|
admit?: (calls: Array<{ key: string; params: Record<string, unknown> }>) => void | Promise<void>;
|
|
623
|
-
launch: (key: string, params: Record<string, unknown>, signal: AbortSignal, admission: { admitted: boolean }) => Promise<WorkflowScriptChildResult>;
|
|
1092
|
+
launch: (key: string, params: Record<string, unknown>, signal: AbortSignal, admission: { admitted: boolean; batch: boolean }) => Promise<WorkflowScriptChildResult>;
|
|
624
1093
|
resolveResume?: (reference: WorkflowReceiptResumeReference, signal: AbortSignal) => string | WorkflowResolvedResumeReference | Promise<string | WorkflowResolvedResumeReference>;
|
|
625
1094
|
status: (keyOrRunId: string, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
|
|
626
1095
|
steer?: (key: string, message: string, options: WorkflowSteerOptions, signal: AbortSignal) => Promise<WorkflowSteerResult>;
|
|
1096
|
+
host?: (key: string, params: WorkflowHostCommandParams, signal: AbortSignal) => Promise<WorkflowHostCommandResult>;
|
|
1097
|
+
onHostStep?: (hostStep: HostStepNodeV1) => void;
|
|
627
1098
|
state?: {
|
|
628
1099
|
get: (key: string) => unknown | Promise<unknown>;
|
|
629
1100
|
set: (key: string, value: unknown) => void | Promise<void>;
|
|
630
1101
|
};
|
|
1102
|
+
registerStopChild?: (stop: ((key: string, message?: string) => boolean) | undefined) => void;
|
|
631
1103
|
onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
|
|
1104
|
+
onLanePlan?: (lanes: WorkflowLanePlan[]) => void;
|
|
632
1105
|
onEmit?: (emits: unknown[]) => void;
|
|
633
1106
|
}
|
|
634
1107
|
|
|
1108
|
+
function combinedAbortSignal(signals: AbortSignal[]): AbortSignal {
|
|
1109
|
+
const controller = new AbortController();
|
|
1110
|
+
const abort = (signal: AbortSignal): void => {
|
|
1111
|
+
if (controller.signal.aborted) return;
|
|
1112
|
+
controller.abort(signal.reason);
|
|
1113
|
+
};
|
|
1114
|
+
for (const signal of signals) {
|
|
1115
|
+
if (signal.aborted) {
|
|
1116
|
+
abort(signal);
|
|
1117
|
+
break;
|
|
1118
|
+
}
|
|
1119
|
+
signal.addEventListener("abort", () => abort(signal), { once: true });
|
|
1120
|
+
}
|
|
1121
|
+
return controller.signal;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
635
1124
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
636
1125
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
637
1126
|
}
|
|
638
1127
|
|
|
1128
|
+
function isAcceptanceMetadataRecovery(result: WorkflowScriptChildResult): boolean {
|
|
1129
|
+
return !result.ok
|
|
1130
|
+
&& result.recovery?.status === "available-for-review"
|
|
1131
|
+
&& result.recovery.reason === "acceptance-metadata-rejected";
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
const RECOVERY_REVIEW_MUTATION_VERB_PATTERN = /\b(?:add(?:ing)?|append(?:ing)?|apply(?:ing)?|cherry[ -]pick(?:ing)?|change|changing|clean(?:ing)?|commit(?:ting)?|cop(?:y|ying)|create|creating|delete|deleting|edit(?:ing)?|fix(?:ing)?|implement(?:ing)?|insert(?:ing)?|make|making|merge|merging|mov(?:e|ing)|modify(?:ing)?|mutate|mutating|open(?:ing)?|patch(?:ing)?|prepend(?:ing)?|push(?:ing)?|rebase|rebasing|refactor(?:ing)?|remove|removing|rename|renaming|replace|replacing|revert(?:ing)?|revise|revising|rewrite|rewriting|sav(?:e|ing)|stag(?:e|ing)|stash(?:ing)?|tag(?:ging)?|touch(?:ing)?|update|updating|write|writing)\b/i;
|
|
1135
|
+
const RECOVERY_REVIEW_READ_ONLY_PATTERN = /\b(?:read[- ]only|review only|only return findings|return findings only|suggest fixes only|without\s+(?:editing|modifying|changing|writing|touching)|do not\s+(?:edit|modify|change|write|touch)|don't\s+(?:edit|modify|change|write|touch)|must not\s+(?:edit|modify|change|write|touch))\b/i;
|
|
1136
|
+
const RECOVERY_REVIEW_NO_MUTATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:edit|modify|change|write|touch)(?:\s+files?)?(?:\s*,\s*(?:commit|push|comment|merge|launch(?:\s+subagents?)?)(?=\s*(?:,|\bor\b|[.;!?\n)]|$)))*(?:\s*,?\s*or\s+(?:commit|push|comment|merge|launch(?:\s+subagents?)?)(?=\s*(?:[.;!?\n)]|$)))?/gi;
|
|
1137
|
+
const RECOVERY_REVIEW_DELIVERABLE_PATTERN = /\b(?:compose|create|draft|prepare|produce|write)\s+(?:(?:a|an|the|your)\s+)?(?:findings?|review|report|summary|analysis|recommendations?)(?:\s+(?:to|at|in)\s+\S+)?/gi;
|
|
1138
|
+
const RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN = /\breview\s+(?:(?:the|this|that|saved)\s+)?(?:patch|diff|changes?|implementation|report)\b/gi;
|
|
1139
|
+
const RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN = /\b(?:later\s+real\s+)?update\s+imperatives?\b/gi;
|
|
1140
|
+
const RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN = /\bthe\s+prior\s+fix\s+keeps\b/gi;
|
|
1141
|
+
const RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN = /\b(?:mutation\s+detection\s+now\s+includes\s+move\/rename\/copy\s+file\s+mutation\s+imperatives|delegation\s+detection\s+now\s+blocks\s+get\/let\/have\/tell\/ask\s+follow-up\s+forms)(?=[,.;!?\n]|\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b|$)/gi;
|
|
1142
|
+
const RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN = /\bRECOVERY_REVIEW_MUTATION_VERB_PATTERN\s+now\s+includes\s+append,\s+prepend,\s+and\s+sav(?:e|ing)\b(?=\s*(?:[,.;!?\n)]|$))/gi;
|
|
1143
|
+
const RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN = /\bfixed\s+mutating\s+git\s+follow-up\s+bypasses\b|\b(?:added|adding)\s+[a-z][a-z-]*(?:\/[a-z][a-z-]*)*(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)[a-z][a-z-]*(?:\/[a-z][a-z-]*)*)*\s+to\s+the\s+(?:mutation\s+imperative|mutating\s+git\s+command)\s+pattern\b|\band\s+[a-z][a-z-]*(?:\/[a-z][a-z-]*)*(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)[a-z][a-z-]*(?:\/[a-z][a-z-]*)*)*\s+to\s+the\s+mutating\s+git\s+command\s+pattern\b/gi;
|
|
1144
|
+
const RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN = /\bvalidation(?:\s+after\s+fix)?\s*:/gi;
|
|
1145
|
+
const RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN = /\b(?:do not|don't|must not)\s+(?:mutate\s+durable\s+state|launch\s+(?:mutating|destructive|mutating\/destructive)\s+work)(?:\s+or\s+(?:mutate\s+durable\s+state|launch\s+(?:mutating|destructive|mutating\/destructive)\s+work))*/gi;
|
|
1146
|
+
const RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN = /\bmay\s+only\s+launch\s+explicit\s+read-only\s+review\s+children\s+with\s+acceptance:false\b/gi;
|
|
1147
|
+
const RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN = /\bstate\.set, runs\.host, runs\.steer, ordinary\/mutating children, and destructive command wording are blocked(?=[,.;!?\n)\]}]|$)/gi;
|
|
1148
|
+
const RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN = /\b(?:existing regressions cover plain rm and git clean\/reset\/restore|prior regressions covering rm\/git clean as evidence only)(?=[,.;!?\n)\]}]|$)/gi;
|
|
1149
|
+
const RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN = /(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*\s+(?:is|are|remains?)\s+(?:blocked|(?:an?\s+)?blocked\s+examples?)(?=[,.;!?\n)\]}]|$)/gi;
|
|
1150
|
+
const RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN = /\b(?:examples?|phrasing|forms|variants):\s*(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*/gi;
|
|
1151
|
+
const RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN = /(?:^|[.;!?\n]\s*)blocked\s+examples:\s*(?:\r?\n[ \t]*(?:[-*]|\d+[.)])\s+[^\r\n]+)+/gim;
|
|
1152
|
+
const RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN = /\b(?:this\s+)?blocks?\s+examples?\s+like\s+(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*/gi;
|
|
1153
|
+
const RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN = /\bexamples?\s+like\s+(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*\s+(?:is|are|remains?)\s+blocked\b/gi;
|
|
1154
|
+
const RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN = /(?:\b(?:(?:the\s+)?examples?|commands?\s+hidden\s+in)\s+|(?:^|[\s([{]))(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+|or\s+)?|\s+(?:and|or)\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*\s+(?:(?:is|are|remains?)\s+)?visible\s+and\s+blocked\b/gi;
|
|
1155
|
+
const RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN = /\bdescribed\s+prompts?\s+like\s+Run\s+git\s+rebase\s+main,\s+git\s+rebase\s+main,\s+Run\s+git\s+cherry-pick\s+abc123,\s+cherry-pick\s+abc123,\s+and\s+Stage\s+the\s+changed\s+files\s+as\s+blocked\b/gi;
|
|
1156
|
+
const RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN = /\bpositive\s+git\s+mutations\s+are\s+broader:\s*git\s+branch\s+-D\s+old,\s+git\s+tag\s+-d\s+v1\.0,\s+git\s+stash,\s+git\s+revert\s+abc123,\s+and\s+natural\s+cherry\s+pick\s+abc123\s+now\s+trips?\s+the\s+recovery\s+barrier\b/gi;
|
|
1157
|
+
const RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN = /\bbroadened\s+positive\s+git\s+mutation\s+coverage\s+for\s+natural\s+`cherry\s+pick`,\s+`revert`,\s+`stash`,\s+`tag`,\s+plus\s+git\s+`branch\|revert\|stash\|tag`/gi;
|
|
1158
|
+
const RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN = /\b(?:added\s+)?exact\s+regressions?\s+for\s+(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*/gi;
|
|
1159
|
+
const RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN = /\b(?:added\s+)?exact\s+regressions?\s+for\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request))(?:[\s,]+(?:now|still|again|really|actually|immediately)){0,3}[\s,]+anyway(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request))(?:[\s,]+(?:now|still|again|really|actually|immediately)){0,3}[\s,]+anyway)*/gi;
|
|
1160
|
+
const RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN = /\badded\s+(?:exact\s+)?regressions?\s+for\s+quoted\s+rm\s+remaining\s+blocked\s+followed\s+by\s+execute\s+the\s+previous\s+command\b(?=\s*(?:[,.;!?\n)]|\bwhile\b|$))/gi;
|
|
1161
|
+
const RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_NAMED_RM_PATTERN = /\b(?:added\s+)?(?:exact\s+)?regressions?\s+for\s+quoted\s+rm\s+remaining\s+blocked\s+followed\s+by\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request))(?:[\s,]+(?:now|still|again|really|actually|immediately)){0,3}(?:[\s,]+anyway)?(?=\s*(?:[,.;!?\n)]|\bwhile\b|$))/gi;
|
|
1162
|
+
const RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN = /\b(?:while\s+)?keeping\s+live-command\s+variants\s+such\s+as\s+followed\s+by\s+execute\s+the\s+previous\s+command\s+then\s+update\s+tests\s+blocked\b(?=\s*(?:[,.;!?\n)]|$))/gi;
|
|
1163
|
+
const RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN = /\bdirect\s+anaphoric\s+references\s+now\s+include\s+numeric\s+and\s+word\s+ordinals\s+through\s+tenth\s+plus\s+one,\s+so\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?:[\s,]+(?:right|now|still|again|really|actually|immediately)){0,4}[\s,]+anyway(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?:[\s,]+(?:right|now|still|again|really|actually|immediately)){0,4}[\s,]+anyway)*\s+(?:is|are|remains?)\s+blocked\b(?:\s+after\s+quoted\s+destructive\s+examples\s+are\s+scrubbed)?/gi;
|
|
1164
|
+
const RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n—–-]){0,80}/gi;
|
|
1165
|
+
const RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:(?:launch|start|spawn|run)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)|(?:get|let|request|hand\s+off|assign|use|have|tell)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|(?:get|let|have|tell|request)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|with|via|by)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|ask\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|via)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)))\b/gi;
|
|
1166
|
+
const RECOVERY_REVIEW_DELEGATION_PATTERN = /\b(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|\b(?:delegate|hand\s+off|assign)\s+(?:remediation|implementation(?:\s+follow-up)?|changes?|fix(?:es)?|follow-up)\s+to\s+(?:(?:a|an|the)\s+)?(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|with|via|by)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\bask\b[^,.;!?\n]*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|via)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child))\b|\buse\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\s+(?:for|to)\s+(?:implementation|follow-up|remediation|fix|edit|write|modify|change|patch|update|delete|remove|create)\b/i;
|
|
1167
|
+
const RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN = /\b(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?!(?:\s+(?:(?:now|still|also|already)\s+)*(?:is|are|remains?)\s+blocked\b))(?:(?:[\s,]+\w+){0,4}[\s,]+anyway|(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n]){0,80})(?=\s*(?:[,.;!?\n)]|\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b|$))/i;
|
|
1168
|
+
const RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN = /(?:^|[\s;,.`'"([{])(?:\S*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b|\bgit\b(?:\s+(?:-[A-Za-z](?:\s+(?:"[^"\n]*"|'[^'\n]*'|\S+))?|--(?:git-dir|work-tree|namespace|exec-path|config-env)(?:=(?:"[^"\n]*"|'[^'\n]*'|\S+)|\s+(?:"[^"\n]*"|'[^'\n]*'|\S+))|--[A-Za-z0-9-]+(?:=(?:"[^"\n]*"|'[^'\n]*'|\S+))?))*\s+(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b/i;
|
|
1169
|
+
const RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)\s*(?:then\s+)?(?:(?:add|append|apply|change|cherry[ -]pick|clean|commit|copy|create|delete|edit|fix|implement|insert|make|merge|move|modify|mutate|open|patch|prepend|push|rebase|refactor|remove|rename|replace|revert|revise|rewrite|save|stage|stash|tag|touch|update|write)\b|(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|(?:\S*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b|git\b[^,.;!?\n]*\b(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b)/i;
|
|
1170
|
+
|
|
1171
|
+
function isExplicitReadOnlyRecoveryReview(params: Record<string, unknown>): boolean {
|
|
1172
|
+
const agent = typeof params.agent === "string" ? params.agent.trim() : "";
|
|
1173
|
+
const task = typeof params.task === "string" ? params.task.trim() : "";
|
|
1174
|
+
const taskDestructiveCommandText = task
|
|
1175
|
+
.replace(RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN, " ")
|
|
1176
|
+
.replace(RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN, " ")
|
|
1177
|
+
.replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1178
|
+
.replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1179
|
+
.replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ")
|
|
1180
|
+
.replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1181
|
+
.replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ")
|
|
1182
|
+
.replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ")
|
|
1183
|
+
.replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ")
|
|
1184
|
+
.replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ")
|
|
1185
|
+
.replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ")
|
|
1186
|
+
.replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_NAMED_RM_PATTERN, " ");
|
|
1187
|
+
const taskDashLiveActionText = task
|
|
1188
|
+
.replace(RECOVERY_REVIEW_DELIVERABLE_PATTERN, " ")
|
|
1189
|
+
.replace(RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN, " ")
|
|
1190
|
+
.replace(RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN, " ")
|
|
1191
|
+
.replace(RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN, " ")
|
|
1192
|
+
.replace(RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN, " ")
|
|
1193
|
+
.replace(RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
|
|
1194
|
+
.replace(RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
|
|
1195
|
+
.replace(RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN, " ")
|
|
1196
|
+
.replace(RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN, " ")
|
|
1197
|
+
.replace(RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN, " ")
|
|
1198
|
+
.replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1199
|
+
.replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1200
|
+
.replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ")
|
|
1201
|
+
.replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1202
|
+
.replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ")
|
|
1203
|
+
.replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ")
|
|
1204
|
+
.replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ")
|
|
1205
|
+
.replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ")
|
|
1206
|
+
.replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ")
|
|
1207
|
+
.replace(RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1208
|
+
.replace(RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN, " ")
|
|
1209
|
+
.replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN, " ")
|
|
1210
|
+
.replace(RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN, " ")
|
|
1211
|
+
.replace(RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN, " ");
|
|
1212
|
+
const taskMutationText = task
|
|
1213
|
+
.replace(RECOVERY_REVIEW_DELIVERABLE_PATTERN, " ")
|
|
1214
|
+
.replace(RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN, " ")
|
|
1215
|
+
.replace(RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN, " ")
|
|
1216
|
+
.replace(RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN, " ")
|
|
1217
|
+
.replace(RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN, " ")
|
|
1218
|
+
.replace(RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
|
|
1219
|
+
.replace(RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
|
|
1220
|
+
.replace(RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN, " ")
|
|
1221
|
+
.replace(RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN, " ")
|
|
1222
|
+
.replace(RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN, " ")
|
|
1223
|
+
.replace(RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN, " ")
|
|
1224
|
+
.replace(RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN, " ")
|
|
1225
|
+
.replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1226
|
+
.replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1227
|
+
.replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ")
|
|
1228
|
+
.replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1229
|
+
.replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ")
|
|
1230
|
+
.replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ")
|
|
1231
|
+
.replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ")
|
|
1232
|
+
.replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ")
|
|
1233
|
+
.replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ")
|
|
1234
|
+
.replace(RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN, " ")
|
|
1235
|
+
.replace(RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN, " ")
|
|
1236
|
+
.replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN, " ")
|
|
1237
|
+
.replace(RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN, " ")
|
|
1238
|
+
.replace(RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN, " ")
|
|
1239
|
+
.replace(RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN, " ")
|
|
1240
|
+
.replace(RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN, " ")
|
|
1241
|
+
.replace(RECOVERY_REVIEW_NO_MUTATION_CLAUSE_PATTERN, " ")
|
|
1242
|
+
.replace(new RegExp(RECOVERY_REVIEW_READ_ONLY_PATTERN.source, "gi"), " ");
|
|
1243
|
+
return params.acceptance === false
|
|
1244
|
+
&& agent !== ""
|
|
1245
|
+
&& /\b(?:advisor|oracle|review|reviewer)\b/i.test(agent)
|
|
1246
|
+
&& RECOVERY_REVIEW_READ_ONLY_PATTERN.test(task)
|
|
1247
|
+
&& !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskDestructiveCommandText)
|
|
1248
|
+
&& !RECOVERY_REVIEW_MUTATION_VERB_PATTERN.test(taskMutationText)
|
|
1249
|
+
&& !RECOVERY_REVIEW_DELEGATION_PATTERN.test(taskMutationText)
|
|
1250
|
+
&& !RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN.test(taskMutationText)
|
|
1251
|
+
&& !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskMutationText)
|
|
1252
|
+
&& !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText)
|
|
1253
|
+
&& classifyTaskMutationIntent(agent, task).kind === "read-only";
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
function recoveryBarrierMessage(sourceKey: string, target: string): string {
|
|
1257
|
+
return `Run '${target}' cannot launch after run '${sourceKey}' returned rejected acceptance recovery; only explicit read-only review children with acceptance:false may follow.`;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
639
1260
|
function isPlainJsonObject(value: unknown): value is Record<string, unknown> {
|
|
640
1261
|
if (!isRecord(value)) return false;
|
|
641
1262
|
const prototype = Object.getPrototypeOf(value);
|
|
@@ -710,6 +1331,15 @@ export function formatWorkflowJsonPreview(value: unknown, maxLength: number): st
|
|
|
710
1331
|
}
|
|
711
1332
|
}
|
|
712
1333
|
|
|
1334
|
+
function workflowReturnRecoveryHint(children: WorkflowScriptChildResult[]): string {
|
|
1335
|
+
if (children.length === 0) return " Return only plain JSON data. For a child result, select fields such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.";
|
|
1336
|
+
const references = children.slice(0, 10).map((child) => {
|
|
1337
|
+
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);
|
|
1338
|
+
return `'${child.key}'${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`;
|
|
1339
|
+
});
|
|
1340
|
+
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 }.`;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
713
1343
|
export interface SimpleWorkflowRunPreview {
|
|
714
1344
|
agent?: string;
|
|
715
1345
|
task?: string;
|
|
@@ -747,6 +1377,230 @@ function validateKey(value: unknown, owner = "runs.run"): string {
|
|
|
747
1377
|
return value;
|
|
748
1378
|
}
|
|
749
1379
|
|
|
1380
|
+
type AstNode = {
|
|
1381
|
+
type: string;
|
|
1382
|
+
loc?: { start: { line: number; column: number } };
|
|
1383
|
+
[key: string]: unknown;
|
|
1384
|
+
};
|
|
1385
|
+
|
|
1386
|
+
const AST_LOCATION_KEYS = new Set(["type", "start", "end", "loc", "range"]);
|
|
1387
|
+
|
|
1388
|
+
function astNode(value: unknown): value is AstNode {
|
|
1389
|
+
return Boolean(value) && typeof value === "object" && typeof (value as { type?: unknown }).type === "string";
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
function literalString(node: unknown): string | undefined {
|
|
1393
|
+
if (!astNode(node)) return undefined;
|
|
1394
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
1395
|
+
if (node.type === "TemplateLiteral" && Array.isArray(node.expressions) && node.expressions.length === 0 && Array.isArray(node.quasis)) {
|
|
1396
|
+
const first = node.quasis[0] as { value?: { cooked?: unknown } } | undefined;
|
|
1397
|
+
if (typeof first?.value?.cooked === "string") return first.value.cooked;
|
|
1398
|
+
}
|
|
1399
|
+
return undefined;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
function directRunsCall(node: unknown, method: "run" | "all" | "host"): node is AstNode {
|
|
1403
|
+
if (!astNode(node) || node.type !== "CallExpression" || !astNode(node.callee) || node.callee.type !== "MemberExpression") return false;
|
|
1404
|
+
const property = node.callee.computed === true ? literalString(node.callee.property) : astNode(node.callee.property) && node.callee.property.type === "Identifier" ? node.callee.property.name : undefined;
|
|
1405
|
+
return property === method && astNode(node.callee.object) && node.callee.object.type === "Identifier" && node.callee.object.name === "runs";
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
function validateStaticHostCall(call: AstNode): WorkflowScriptValidationError[] {
|
|
1409
|
+
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
1410
|
+
const keyNode = astNode(args[0]) ? args[0] : undefined;
|
|
1411
|
+
const params = astNode(args[1]) ? args[1] : undefined;
|
|
1412
|
+
const errors: WorkflowScriptValidationError[] = [];
|
|
1413
|
+
const key = literalString(keyNode);
|
|
1414
|
+
if (keyNode && key !== undefined && !KEY_PATTERN.test(key)) errors.push({ message: "runs.host key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(keyNode) });
|
|
1415
|
+
if (!params || params.type !== "ObjectExpression" || !Array.isArray(params.properties) || params.properties.some((property) => !astNode(property) || property.type !== "Property")) return errors;
|
|
1416
|
+
const allowed = new Set(["kind", "command", "timeoutMs", "output", "role", "provider"]);
|
|
1417
|
+
for (const property of params.properties) {
|
|
1418
|
+
if (!astNode(property)) continue;
|
|
1419
|
+
const name = staticPropertyKey(property);
|
|
1420
|
+
if (name !== undefined && !allowed.has(name)) errors.push({ message: name === "cwd" ? "runs.host params contain unsupported field 'cwd'. The host step does not accept per-step cwd; commands and relative output paths use the workflow cwd. Set cwd on the outer subagent request, or put a trusted directory change in command (for example, 'cd /path/to/worktree && npm test')." : `runs.host params contain unsupported field '${name}'.`, ...nodeLocation(property) });
|
|
1421
|
+
}
|
|
1422
|
+
const kindNode = directObjectPropertyValue(params, "kind");
|
|
1423
|
+
const commandNode = directObjectPropertyValue(params, "command");
|
|
1424
|
+
const timeoutNode = directObjectPropertyValue(params, "timeoutMs");
|
|
1425
|
+
const kind = literalString(kindNode);
|
|
1426
|
+
const command = literalString(commandNode);
|
|
1427
|
+
const timeout = astNode(timeoutNode) && timeoutNode.type === "Literal" ? timeoutNode.value : undefined;
|
|
1428
|
+
if (!kindNode) errors.push({ message: "runs.host params require kind: 'command'.", ...nodeLocation(params) });
|
|
1429
|
+
else if (kind !== undefined && kind !== "command") errors.push({ message: "runs.host params kind must be 'command'.", ...nodeLocation(kindNode) });
|
|
1430
|
+
if (!commandNode) errors.push({ message: "runs.host params require command.", ...nodeLocation(params) });
|
|
1431
|
+
else if (command !== undefined && !command.trim()) errors.push({ message: "runs.host params command must be non-empty.", ...nodeLocation(commandNode) });
|
|
1432
|
+
if (!timeoutNode) errors.push({ message: "runs.host params require timeoutMs.", ...nodeLocation(params) });
|
|
1433
|
+
else if (typeof timeout === "number" && (!Number.isInteger(timeout) || timeout < 1)) errors.push({ message: "runs.host params timeoutMs must be a positive integer.", ...nodeLocation(timeoutNode) });
|
|
1434
|
+
const outputNode = directObjectPropertyValue(params, "output");
|
|
1435
|
+
const output = literalString(outputNode);
|
|
1436
|
+
if (outputNode && output !== undefined && (!output.trim() || /^[/\\]|(?:^|[/\\])\.\.(?:[/\\]|$)/.test(output))) errors.push({ message: "runs.host params output must be a non-empty relative path without traversal.", ...nodeLocation(outputNode) });
|
|
1437
|
+
const roleNode = directObjectPropertyValue(params, "role");
|
|
1438
|
+
const role = literalString(roleNode);
|
|
1439
|
+
if (roleNode && role !== undefined && role !== "ci" && role !== "gate") errors.push({ message: "runs.host params role must be 'ci' or 'gate'.", ...nodeLocation(roleNode) });
|
|
1440
|
+
return errors;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
function nodeLocation(node: AstNode): Pick<WorkflowScriptValidationError, "line" | "column"> {
|
|
1444
|
+
return node.loc ? { line: Math.max(1, node.loc.start.line - 1), column: node.loc.start.column + 1 } : {};
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
function walkAst(node: unknown, visit: (node: AstNode) => void, includeNestedFunctions = true): void {
|
|
1448
|
+
if (Array.isArray(node)) {
|
|
1449
|
+
for (const item of node) walkAst(item, visit, includeNestedFunctions);
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
if (!astNode(node)) return;
|
|
1453
|
+
visit(node);
|
|
1454
|
+
if (!includeNestedFunctions && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) return;
|
|
1455
|
+
for (const [key, child] of Object.entries(node)) {
|
|
1456
|
+
if (!AST_LOCATION_KEYS.has(key)) walkAst(child, visit, includeNestedFunctions);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function definitelyNonJson(node: AstNode, normalizeUndefined = false): string | undefined {
|
|
1461
|
+
if (node.type === "Literal") {
|
|
1462
|
+
if (typeof node.bigint === "string") return "BigInt values are not JSON-representable";
|
|
1463
|
+
if (node.regex !== undefined) return "regular expressions are not JSON-representable";
|
|
1464
|
+
return undefined;
|
|
1465
|
+
}
|
|
1466
|
+
if (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return "functions are not JSON-representable";
|
|
1467
|
+
if (node.type === "Identifier" && node.name === "undefined") return normalizeUndefined ? undefined : "undefined is not JSON-representable";
|
|
1468
|
+
if (node.type === "UnaryExpression" && node.operator === "void") return normalizeUndefined ? undefined : "undefined is not JSON-representable";
|
|
1469
|
+
if (node.type === "ArrayExpression" && Array.isArray(node.elements)) {
|
|
1470
|
+
if (node.elements.some((entry) => entry === null)) return "sparse arrays are not JSON-representable";
|
|
1471
|
+
for (const entry of node.elements) if (astNode(entry)) {
|
|
1472
|
+
const error = definitelyNonJson(entry, normalizeUndefined);
|
|
1473
|
+
if (error) return error;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
if (node.type === "ObjectExpression" && Array.isArray(node.properties)) {
|
|
1477
|
+
const values = new Map<string, AstNode>();
|
|
1478
|
+
for (const property of node.properties) {
|
|
1479
|
+
if (!astNode(property) || property.type !== "Property" || !astNode(property.value)) return undefined;
|
|
1480
|
+
const key = staticPropertyKey(property);
|
|
1481
|
+
if (key === undefined) return undefined;
|
|
1482
|
+
values.set(key, property.value);
|
|
1483
|
+
}
|
|
1484
|
+
for (const value of values.values()) {
|
|
1485
|
+
const error = definitelyNonJson(value, normalizeUndefined);
|
|
1486
|
+
if (error) return error;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
return undefined;
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
function staticPropertyKey(property: AstNode): string | undefined {
|
|
1493
|
+
return property.computed === true
|
|
1494
|
+
? literalString(property.key)
|
|
1495
|
+
: literalString(property.key) ?? (astNode(property.key) && property.key.type === "Identifier" ? property.key.name as string : undefined);
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
function directObjectPropertyValue(node: AstNode, name: string): AstNode | undefined {
|
|
1499
|
+
if (node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return undefined;
|
|
1500
|
+
let value: AstNode | undefined;
|
|
1501
|
+
for (const property of node.properties) {
|
|
1502
|
+
if (!astNode(property) || property.type !== "Property" || !astNode(property.value)) continue;
|
|
1503
|
+
if (staticPropertyKey(property) === name) value = property.value;
|
|
1504
|
+
}
|
|
1505
|
+
return value;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
function directRunsAllKeys(call: AstNode): Array<{ key: string; node: AstNode }> {
|
|
1509
|
+
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
1510
|
+
const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
|
|
1511
|
+
return items.flatMap((item) => {
|
|
1512
|
+
if (!astNode(item)) return [];
|
|
1513
|
+
const keyNode = directObjectPropertyValue(item, "key");
|
|
1514
|
+
const key = literalString(keyNode);
|
|
1515
|
+
return keyNode && key !== undefined ? [{ key, node: keyNode }] : [];
|
|
1516
|
+
});
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
/** Parse a workflowScript and apply only rules that are decidable from its local syntax. */
|
|
1520
|
+
export function validateWorkflowScript(script: string): WorkflowScriptValidationResult {
|
|
1521
|
+
const errors: WorkflowScriptValidationError[] = [];
|
|
1522
|
+
if (!script.trim()) return { ok: false, errors: [{ message: "workflowScript must not be empty." }] };
|
|
1523
|
+
let root: AstNode;
|
|
1524
|
+
try {
|
|
1525
|
+
const parser = requireFromPackage(resolveWorkflowParserEntry()) as { parse(source: string, options: Record<string, unknown>): unknown };
|
|
1526
|
+
root = parser.parse(`(async () => {\n${script}\n})()`, { ecmaVersion: "latest", sourceType: "script", locations: true }) as AstNode;
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
const location = error && typeof error === "object" && "loc" in error && error.loc && typeof error.loc === "object"
|
|
1529
|
+
? error.loc as { line?: unknown; column?: unknown }
|
|
1530
|
+
: undefined;
|
|
1531
|
+
const message = (error instanceof Error ? error.message : String(error)).replace(/\s+\(\d+:\d+\)$/, "");
|
|
1532
|
+
return { ok: false, errors: [{ message, ...(typeof location?.line === "number" ? { line: Math.max(1, location.line - 1) } : {}), ...(typeof location?.column === "number" ? { column: location.column + 1 } : {}) }] };
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
const wrapper = astNode(root.body) ? undefined : Array.isArray(root.body) && astNode(root.body[0]) && astNode(root.body[0].expression) && astNode(root.body[0].expression.callee)
|
|
1536
|
+
? root.body[0].expression.callee
|
|
1537
|
+
: undefined;
|
|
1538
|
+
const workflowBody = wrapper && astNode(wrapper.body) ? wrapper.body : root;
|
|
1539
|
+
walkAst(workflowBody, (node) => {
|
|
1540
|
+
if (node !== wrapper && node.async === true && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) {
|
|
1541
|
+
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) });
|
|
1542
|
+
}
|
|
1543
|
+
if (directRunsCall(node, "run")) {
|
|
1544
|
+
const args = Array.isArray(node.arguments) ? node.arguments : [];
|
|
1545
|
+
const keyNode = astNode(args[0]) ? args[0] : undefined;
|
|
1546
|
+
const key = literalString(keyNode);
|
|
1547
|
+
if (keyNode && key !== undefined && !KEY_PATTERN.test(key)) errors.push({ message: "runs.run key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(keyNode) });
|
|
1548
|
+
if (astNode(args[1])) {
|
|
1549
|
+
const message = definitelyNonJson(args[1]);
|
|
1550
|
+
if (message) errors.push({ message: `runs.run params are invalid: ${message}.`, ...nodeLocation(args[1]) });
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
if (directRunsCall(node, "all")) {
|
|
1554
|
+
for (const entry of directRunsAllKeys(node)) if (!KEY_PATTERN.test(entry.key)) errors.push({ message: "runs.all item key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(entry.node) });
|
|
1555
|
+
const args = Array.isArray(node.arguments) ? node.arguments : [];
|
|
1556
|
+
if (astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements)) {
|
|
1557
|
+
for (const item of args[0].elements) if (astNode(item)) {
|
|
1558
|
+
const message = definitelyNonJson(item);
|
|
1559
|
+
if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
|
|
1564
|
+
const boundaryValue = node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "emit" && Array.isArray(node.arguments) && astNode(node.arguments[0])
|
|
1565
|
+
? node.arguments[0]
|
|
1566
|
+
: 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])
|
|
1567
|
+
? node.arguments[1]
|
|
1568
|
+
: undefined;
|
|
1569
|
+
if (boundaryValue) {
|
|
1570
|
+
const message = definitelyNonJson(boundaryValue);
|
|
1571
|
+
if (message) errors.push({ message: `workflowScript boundary value is invalid: ${message}.`, ...nodeLocation(boundaryValue) });
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
walkAst(workflowBody, (node) => {
|
|
1575
|
+
if (node.type !== "ReturnStatement" || !astNode(node.argument)) return;
|
|
1576
|
+
const message = definitelyNonJson(node.argument, true);
|
|
1577
|
+
if (message) errors.push({ message: `workflowScript boundary value is invalid: ${message}.`, ...nodeLocation(node.argument) });
|
|
1578
|
+
}, false);
|
|
1579
|
+
|
|
1580
|
+
if (workflowBody.type === "BlockStatement" && Array.isArray(workflowBody.body)) {
|
|
1581
|
+
for (let statementIndex = 0; statementIndex < workflowBody.body.length; statementIndex++) {
|
|
1582
|
+
const statement = workflowBody.body[statementIndex];
|
|
1583
|
+
if (!astNode(statement) || statement.type !== "VariableDeclaration" || !Array.isArray(statement.declarations)) continue;
|
|
1584
|
+
for (const declaration of statement.declarations) {
|
|
1585
|
+
if (!astNode(declaration) || !astNode(declaration.id) || declaration.id.type !== "Identifier" || !astNode(declaration.init) || declaration.init.type !== "AwaitExpression" || !directRunsCall(declaration.init.argument, "all")) continue;
|
|
1586
|
+
const name = declaration.id.name as string;
|
|
1587
|
+
const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
|
|
1588
|
+
if (keys.size === 0) continue;
|
|
1589
|
+
const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
|
|
1590
|
+
const itemCount = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements.length : 0;
|
|
1591
|
+
const arrayResultShape = Array.from({ length: itemCount });
|
|
1592
|
+
for (const later of workflowBody.body.slice(statementIndex + 1)) walkAst(later, (node) => {
|
|
1593
|
+
if (node.type !== "MemberExpression" || !astNode(node.object) || node.object.type !== "Identifier" || node.object.name !== name) return;
|
|
1594
|
+
const property = node.computed === true ? literalString(node.property) : astNode(node.property) && node.property.type === "Identifier" ? node.property.name as string : undefined;
|
|
1595
|
+
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) });
|
|
1596
|
+
}, false);
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
const unique = errors.filter((error, index) => errors.findIndex((candidate) => candidate.message === error.message && candidate.line === error.line && candidate.column === error.column) === index);
|
|
1602
|
+
return { ok: unique.length === 0, errors: unique };
|
|
1603
|
+
}
|
|
750
1604
|
function workflowStringMetadata(params: Record<string, unknown>): Pick<WorkflowScriptTraceEntry, "phase" | "label" | "agent"> {
|
|
751
1605
|
return {
|
|
752
1606
|
...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
|
|
@@ -776,9 +1630,48 @@ function resolveWorkflowParserEntry(): string {
|
|
|
776
1630
|
}
|
|
777
1631
|
}
|
|
778
1632
|
|
|
1633
|
+
const AUTO_RESUME_PARAM_KEYS = ["acceptance", "agentContract", "baseRef", "index", "intercomBridge", "label", "lane", "maxRuntimeMs", "output", "outputMode", "outputSchema", "phase", "skill", "skills", "task", "timeoutMs", "toolBudget", "worktree"] as const;
|
|
1634
|
+
|
|
1635
|
+
function isZeroUsage(usage: unknown): boolean {
|
|
1636
|
+
if (!isRecord(usage)) return false;
|
|
1637
|
+
const cost = usage.cost;
|
|
1638
|
+
return (usage.input ?? 0) === 0
|
|
1639
|
+
&& (usage.output ?? 0) === 0
|
|
1640
|
+
&& (usage.cacheRead ?? 0) === 0
|
|
1641
|
+
&& (usage.cacheWrite ?? 0) === 0
|
|
1642
|
+
&& (!isRecord(cost) || (cost.total ?? 0) === 0);
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
function setupAbortResumeParams(params: Record<string, unknown>, result: WorkflowScriptChildResult, signal: AbortSignal): Record<string, unknown> | undefined {
|
|
1646
|
+
if (signal.aborted || result.ok || result.stopped || result.interrupted || !result.runId) return undefined;
|
|
1647
|
+
const childResult = Array.isArray(result.results) && result.results.length === 1 && isRecord(result.results[0]) ? result.results[0] : undefined;
|
|
1648
|
+
const error = typeof childResult?.error === "string" ? childResult.error : result.error;
|
|
1649
|
+
if (error !== "This operation was aborted" || !isZeroUsage(childResult?.usage)) return undefined;
|
|
1650
|
+
const messages = Array.isArray(childResult?.messages) ? childResult.messages : [];
|
|
1651
|
+
const message = messages.findLast((entry) => isRecord(entry) && entry.role === "assistant");
|
|
1652
|
+
if (message !== undefined) {
|
|
1653
|
+
if (!isRecord(message)) return undefined;
|
|
1654
|
+
if (message.stopReason !== "error" || message.errorMessage !== error) return undefined;
|
|
1655
|
+
if (!Array.isArray(message.content) || message.content.length > 0 || !isZeroUsage(message.usage)) return undefined;
|
|
1656
|
+
if (Object.hasOwn(message, "diagnostics") || Object.hasOwn(message, "responseId")) return undefined;
|
|
1657
|
+
}
|
|
1658
|
+
const task = typeof params.task === "string" && params.task.trim() ? params.task.trim() : "Continue after the setup abort.";
|
|
1659
|
+
const resumeParams: Record<string, unknown> = { resume: result.runId, task };
|
|
1660
|
+
for (const key of AUTO_RESUME_PARAM_KEYS) {
|
|
1661
|
+
if (Object.hasOwn(params, key)) resumeParams[key] = params[key];
|
|
1662
|
+
}
|
|
1663
|
+
resumeParams.resume = result.runId;
|
|
1664
|
+
resumeParams.task = task;
|
|
1665
|
+
return resumeParams;
|
|
1666
|
+
}
|
|
1667
|
+
|
|
779
1668
|
export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
|
|
780
1669
|
if (!options.script.trim()) throw new Error("workflowScript must not be empty.");
|
|
781
1670
|
if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) throw new Error("workflow script timeout must be a positive integer.");
|
|
1671
|
+
if (options.globalConcurrencyLimit !== undefined && (!Number.isSafeInteger(options.globalConcurrencyLimit) || options.globalConcurrencyLimit < 1)) {
|
|
1672
|
+
throw new Error("workflow script global concurrency limit must be a positive integer.");
|
|
1673
|
+
}
|
|
1674
|
+
const launchSemaphore = new Semaphore(options.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
|
|
782
1675
|
|
|
783
1676
|
let acornPath: string;
|
|
784
1677
|
try {
|
|
@@ -792,15 +1685,22 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
792
1685
|
const trace: WorkflowScriptTraceEntry[] = [];
|
|
793
1686
|
const children = new Map<string, WorkflowScriptChildResult>();
|
|
794
1687
|
const childOrder: string[] = [];
|
|
795
|
-
const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult>; observed: boolean }>();
|
|
1688
|
+
const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult>; observed: boolean; generatedLaneKey?: string }>();
|
|
796
1689
|
const steers = new Map<number, { key: string; promise: Promise<WorkflowSteerResult>; observed: boolean }>();
|
|
1690
|
+
const hostCalls = new Map<number, { key: string; promise: Promise<WorkflowHostCommandResult>; observed: boolean }>();
|
|
797
1691
|
const stoppedLaunches = new Set<string>();
|
|
1692
|
+
const childStopControllers = new Map<string, AbortController>();
|
|
798
1693
|
const batchAdmissions = new Map<string, Promise<void>>();
|
|
799
1694
|
const observedRunCalls = new Set<number>();
|
|
800
1695
|
const observedSteerCalls = new Set<number>();
|
|
1696
|
+
const observedHostCalls = new Set<number>();
|
|
801
1697
|
const childController = new AbortController();
|
|
1698
|
+
let acceptanceRecoveryBarrier: { key: string } | undefined;
|
|
802
1699
|
let settled = false;
|
|
803
1700
|
let finishing = false;
|
|
1701
|
+
let assemblyAbortRequested = false;
|
|
1702
|
+
let assemblyFlushTimer: ReturnType<typeof setTimeout> | undefined;
|
|
1703
|
+
let abortError: Error | undefined;
|
|
804
1704
|
|
|
805
1705
|
const partial = (): Omit<WorkflowScriptResult, "value"> => ({ emits, console: consoleEntries, trace, children: childOrder.flatMap((key) => {
|
|
806
1706
|
const child = children.get(key);
|
|
@@ -818,15 +1718,66 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
818
1718
|
console.error("Workflow onTrace callback failed:", error);
|
|
819
1719
|
}
|
|
820
1720
|
};
|
|
1721
|
+
const lanePlanChanged = (lanes: WorkflowLanePlan[]) => {
|
|
1722
|
+
try {
|
|
1723
|
+
options.onLanePlan?.(lanes);
|
|
1724
|
+
} catch (error) {
|
|
1725
|
+
console.error("Workflow onLanePlan callback failed:", error);
|
|
1726
|
+
}
|
|
1727
|
+
};
|
|
1728
|
+
const hostStepChanged = (hostStep: HostStepNodeV1) => {
|
|
1729
|
+
try {
|
|
1730
|
+
options.onHostStep?.(hostStep);
|
|
1731
|
+
} catch (error) {
|
|
1732
|
+
console.error("Workflow onHostStep callback failed:", error);
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
const stoppedChildResult = (key: string, message: string): WorkflowScriptChildResult => ({ key, ok: false, stopped: true, output: message, error: message, artifactPaths: [] });
|
|
1736
|
+
const responseBoundaryFailure = (key: string, error: unknown): WorkflowScriptChildResult => {
|
|
1737
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
1738
|
+
return { key, ok: false, output: text, error: text, artifactPaths: [] };
|
|
1739
|
+
};
|
|
1740
|
+
const assertRecoveryBarrierAllowsRun = (key: string, params: Record<string, unknown>): void => {
|
|
1741
|
+
if (!acceptanceRecoveryBarrier || isExplicitReadOnlyRecoveryReview(params)) return;
|
|
1742
|
+
throw new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, key));
|
|
1743
|
+
};
|
|
1744
|
+
const recordAcceptanceRecoveryBarrier = (key: string, result: WorkflowScriptChildResult): void => {
|
|
1745
|
+
if (isAcceptanceMetadataRecovery(result)) acceptanceRecoveryBarrier = { key };
|
|
1746
|
+
};
|
|
1747
|
+
const stopChild = (key: string, message = `Workflow child '${key}' stopped by user.`): boolean => {
|
|
1748
|
+
if (!launches.has(key) || children.has(key)) return false;
|
|
1749
|
+
stoppedLaunches.add(key);
|
|
1750
|
+
children.set(key, stoppedChildResult(key, message));
|
|
1751
|
+
childStopControllers.get(key)?.abort(new Error(message));
|
|
1752
|
+
const started = trace.findLast((entry) => entry.operation === "run" && entry.key === key && entry.state === "started");
|
|
1753
|
+
trace.push({
|
|
1754
|
+
operation: "run",
|
|
1755
|
+
key,
|
|
1756
|
+
state: "stopped",
|
|
1757
|
+
...(started?.agent ? { agent: started.agent } : {}),
|
|
1758
|
+
...(started?.phase ? { phase: started.phase } : {}),
|
|
1759
|
+
...(started?.label ? { label: started.label } : {}),
|
|
1760
|
+
...(started?.generatedLaneKey ? { generatedLaneKey: started.generatedLaneKey } : {}),
|
|
1761
|
+
error: message,
|
|
1762
|
+
});
|
|
1763
|
+
traceChanged();
|
|
1764
|
+
return true;
|
|
1765
|
+
};
|
|
1766
|
+
options.registerStopChild?.(stopChild);
|
|
821
1767
|
|
|
822
1768
|
return await new Promise<WorkflowScriptResult>((resolve, reject) => {
|
|
823
1769
|
const finish = (outcome: { value: unknown } | { error: Error & { workflowErrorKind?: unknown } }) => {
|
|
824
1770
|
if (settled || finishing) return;
|
|
825
1771
|
finishing = true;
|
|
1772
|
+
if (assemblyFlushTimer !== undefined) {
|
|
1773
|
+
clearTimeout(assemblyFlushTimer);
|
|
1774
|
+
assemblyFlushTimer = undefined;
|
|
1775
|
+
}
|
|
826
1776
|
childController.abort("error" in outcome ? outcome.error : new Error("Workflow script completed."));
|
|
827
|
-
void Promise.allSettled([...steers.values()].map(({ promise }) => promise)).then(() => {
|
|
1777
|
+
void Promise.allSettled([...steers.values(), ...hostCalls.values()].map(({ promise }) => promise)).then(() => {
|
|
828
1778
|
if (settled) return;
|
|
829
1779
|
settled = true;
|
|
1780
|
+
options.registerStopChild?.(undefined);
|
|
830
1781
|
if (timer) clearTimeout(timer);
|
|
831
1782
|
options.signal?.removeEventListener("abort", onAbort);
|
|
832
1783
|
void worker.terminate();
|
|
@@ -836,10 +1787,12 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
836
1787
|
: "value" in outcome
|
|
837
1788
|
? (() => {
|
|
838
1789
|
const unobservedSteers = [...steers.values()].filter((steer) => !steer.observed).map((steer) => steer.key);
|
|
839
|
-
|
|
1790
|
+
if (unobservedSteers.length > 0) return new Error(`workflowScript completed with unawaited runs.steer call(s): ${unobservedSteers.map((key) => `'${key}'`).join(", ")}. Await or return each call.`);
|
|
1791
|
+
const unobservedHosts = [...hostCalls.values()].filter((host) => !host.observed).map((host) => host.key);
|
|
1792
|
+
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;
|
|
840
1793
|
})()
|
|
841
1794
|
: undefined;
|
|
842
|
-
if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), outcome.error.workflowErrorKind === "detached-child"
|
|
1795
|
+
if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), outcome.error.workflowErrorKind === "detached-child" || outcome.error.workflowErrorKind === "timeout" ? outcome.error.workflowErrorKind : undefined));
|
|
843
1796
|
else if (completionError) reject(new WorkflowScriptError(completionError.message, partial()));
|
|
844
1797
|
else resolve({ value: outcome.value, ...partial() });
|
|
845
1798
|
});
|
|
@@ -851,6 +1804,26 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
851
1804
|
: typeof signalReason === "string"
|
|
852
1805
|
? new Error(signalReason)
|
|
853
1806
|
: new Error("Workflow script aborted.");
|
|
1807
|
+
if (finishing) return;
|
|
1808
|
+
abortError = error;
|
|
1809
|
+
const allChildrenSettled = launches.size > 0
|
|
1810
|
+
&& [...launches.keys()].every((key) => children.has(key));
|
|
1811
|
+
let mayFlushAssembly = false;
|
|
1812
|
+
try {
|
|
1813
|
+
mayFlushAssembly = options.continueAfterAbortWhenChildrenSettled?.(error) === true;
|
|
1814
|
+
} catch (callbackError) {
|
|
1815
|
+
const callbackMessage = callbackError instanceof Error ? callbackError.message : String(callbackError);
|
|
1816
|
+
return finish({ error: new Error(`Workflow assembly flush eligibility failed: ${callbackMessage}`) });
|
|
1817
|
+
}
|
|
1818
|
+
if (mayFlushAssembly && allChildrenSettled) {
|
|
1819
|
+
// A reloaded async workflow may already be past its last child launch.
|
|
1820
|
+
// Keep the worker alive for pure result assembly, but abort the child
|
|
1821
|
+
// signal so any later launch or side effect cannot use stale context.
|
|
1822
|
+
assemblyAbortRequested = true;
|
|
1823
|
+
childController.abort(error);
|
|
1824
|
+
assemblyFlushTimer = setTimeout(() => finish({ error }), WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS);
|
|
1825
|
+
return;
|
|
1826
|
+
}
|
|
854
1827
|
for (const key of launches.keys()) {
|
|
855
1828
|
if (children.has(key)) continue;
|
|
856
1829
|
stoppedLaunches.add(key);
|
|
@@ -862,6 +1835,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
862
1835
|
...(started?.agent ? { agent: started.agent } : {}),
|
|
863
1836
|
...(started?.phase ? { phase: started.phase } : {}),
|
|
864
1837
|
...(started?.label ? { label: started.label } : {}),
|
|
1838
|
+
...(started?.generatedLaneKey ? { generatedLaneKey: started.generatedLaneKey } : {}),
|
|
865
1839
|
error: error.message,
|
|
866
1840
|
});
|
|
867
1841
|
}
|
|
@@ -870,7 +1844,11 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
870
1844
|
};
|
|
871
1845
|
const timer = options.timeoutMs === undefined
|
|
872
1846
|
? undefined
|
|
873
|
-
: setTimeout(() =>
|
|
1847
|
+
: setTimeout(() => {
|
|
1848
|
+
const error = new Error(`Workflow script timed out after ${options.timeoutMs}ms.`) as Error & { workflowErrorKind: "timeout" };
|
|
1849
|
+
error.workflowErrorKind = "timeout";
|
|
1850
|
+
finish({ error });
|
|
1851
|
+
}, options.timeoutMs);
|
|
874
1852
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
875
1853
|
if (options.signal?.aborted) return onAbort();
|
|
876
1854
|
|
|
@@ -880,6 +1858,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
880
1858
|
});
|
|
881
1859
|
worker.on("message", (message: Record<string, unknown>) => {
|
|
882
1860
|
if (settled) return;
|
|
1861
|
+
if (message.type === "lanePlan" && Array.isArray(message.lanes)) {
|
|
1862
|
+
lanePlanChanged(message.lanes as WorkflowLanePlan[]);
|
|
1863
|
+
return;
|
|
1864
|
+
}
|
|
883
1865
|
if (message.type === "emit") {
|
|
884
1866
|
try {
|
|
885
1867
|
assertWorkflowJsonValue(message.value, "emit");
|
|
@@ -910,7 +1892,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
910
1892
|
return finish({ value: message.value });
|
|
911
1893
|
}
|
|
912
1894
|
if (message.type === "error") {
|
|
913
|
-
const
|
|
1895
|
+
const rawError = typeof message.error === "string" ? message.error : "Workflow script failed.";
|
|
1896
|
+
const text = message.errorPhase === "return-serialization" ? `${rawError}${workflowReturnRecoveryHint(partial().children)}` : rawError;
|
|
1897
|
+
const workflowError = new Error(text) as Error & { workflowErrorKind?: "detached-child" };
|
|
914
1898
|
if (message.errorKind === "detached-child") workflowError.workflowErrorKind = "detached-child";
|
|
915
1899
|
return finish({ error: workflowError });
|
|
916
1900
|
}
|
|
@@ -924,12 +1908,17 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
924
1908
|
const steer = steers.get(message.callId);
|
|
925
1909
|
if (steer) steer.observed = true;
|
|
926
1910
|
else observedSteerCalls.add(message.callId);
|
|
1911
|
+
} else if (message.operation === "host") {
|
|
1912
|
+
const host = hostCalls.get(message.callId);
|
|
1913
|
+
if (host) host.observed = true;
|
|
1914
|
+
else observedHostCalls.add(message.callId);
|
|
927
1915
|
}
|
|
928
1916
|
return;
|
|
929
1917
|
}
|
|
930
1918
|
if (message.type !== "call" || typeof message.callId !== "number" || typeof message.method !== "string" || !isRecord(message.args)) return;
|
|
1919
|
+
if (assemblyAbortRequested) return finish({ error: abortError ?? new Error("Workflow context was replaced or reloaded.") });
|
|
931
1920
|
|
|
932
|
-
const respond = (promise: Promise<unknown>, responsePath?: string) => {
|
|
1921
|
+
const respond = (promise: Promise<unknown>, responsePath?: string, onBoundaryError?: (error: unknown) => void) => {
|
|
933
1922
|
void promise.then(
|
|
934
1923
|
(value) => {
|
|
935
1924
|
if (settled) return;
|
|
@@ -942,6 +1931,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
942
1931
|
assertWorkflowJsonValue(normalized, responsePath);
|
|
943
1932
|
worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
|
|
944
1933
|
} catch (error) {
|
|
1934
|
+
onBoundaryError?.(error);
|
|
945
1935
|
worker.postMessage({ type: "response", callId: message.callId, ok: false, error: `${responsePath} must contain only JSON data before it can be returned from workflowScript. Return a plain projection such as { runId, ok, output }. ${error instanceof Error ? error.message : String(error)}` });
|
|
946
1936
|
}
|
|
947
1937
|
},
|
|
@@ -959,6 +1949,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
959
1949
|
return respond(Promise.reject(error));
|
|
960
1950
|
}
|
|
961
1951
|
if (message.method === "state.get") return respond(Promise.resolve().then(() => options.state!.get(key)));
|
|
1952
|
+
if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `state.set('${key}')`))));
|
|
962
1953
|
const value = message.args.value;
|
|
963
1954
|
try {
|
|
964
1955
|
assertWorkflowJsonValue(value, `state.set('${key}') value`);
|
|
@@ -995,6 +1986,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
995
1986
|
const steerMessage = message.args.message;
|
|
996
1987
|
if (typeof steerMessage !== "string" || !steerMessage.trim()) return respond(Promise.reject(new Error(`runs.steer('${key}') requires a non-empty message.`)));
|
|
997
1988
|
const steerOptions = isRecord(message.args.options) ? message.args.options as WorkflowSteerOptions : {};
|
|
1989
|
+
if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.steer('${key}')`))));
|
|
998
1990
|
const startedAt = Date.now();
|
|
999
1991
|
trace.push({ operation: "steer", key, state: "started" });
|
|
1000
1992
|
traceChanged();
|
|
@@ -1016,6 +2008,53 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1016
2008
|
respond(promise);
|
|
1017
2009
|
return;
|
|
1018
2010
|
}
|
|
2011
|
+
if (message.method === "host") {
|
|
2012
|
+
let key: string;
|
|
2013
|
+
let params: WorkflowHostCommandParams;
|
|
2014
|
+
try {
|
|
2015
|
+
key = validateKey(message.args.key, "runs.host");
|
|
2016
|
+
params = normalizeWorkflowHostCommandParams(message.args.params, `runs.host('${key}') params`);
|
|
2017
|
+
} catch (error) {
|
|
2018
|
+
return respond(Promise.reject(error));
|
|
2019
|
+
}
|
|
2020
|
+
if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.host('${key}')`))));
|
|
2021
|
+
if (!options.host) return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
|
|
2022
|
+
if (hostCalls.size >= HOST_STEP_MAX_COUNT) return respond(Promise.reject(new Error(`workflowScript supports at most ${HOST_STEP_MAX_COUNT} runs.host calls.`)));
|
|
2023
|
+
const startedAt = Date.now();
|
|
2024
|
+
const startedStep: HostStepNodeV1 = {
|
|
2025
|
+
version: 1,
|
|
2026
|
+
kind: "host-step",
|
|
2027
|
+
monitorKind: "command",
|
|
2028
|
+
id: key,
|
|
2029
|
+
label: key,
|
|
2030
|
+
...(params.role ? { role: params.role } : {}),
|
|
2031
|
+
...(params.provider ? { provider: params.provider } : {}),
|
|
2032
|
+
state: "running",
|
|
2033
|
+
updatedAt: startedAt,
|
|
2034
|
+
deadlineAt: startedAt + params.timeoutMs,
|
|
2035
|
+
};
|
|
2036
|
+
hostStepChanged(startedStep);
|
|
2037
|
+
trace.push({ operation: "host", key, state: "started" });
|
|
2038
|
+
traceChanged();
|
|
2039
|
+
const promise = Promise.resolve().then(() => options.host!(key, params, childController.signal)).then((result) => {
|
|
2040
|
+
const state = result.state === "stopped" ? "cancelled" : result.ok ? "done" : "error";
|
|
2041
|
+
const detail = [result.error, result.stderr.trim() || result.stdout.trim()].filter(Boolean).join(" ").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
2042
|
+
hostStepChanged({ ...startedStep, state, ...(state === "done" ? { verdict: "pass" as const } : {}), ...(!result.ok ? { reasonCode: result.state === "timed-out" ? "timed_out" : result.state === "stopped" ? "aborted" : "command_failed" } : {}), ...(detail ? { detail } : {}), reportPath: params.output ?? result.outputPath.split(/[\\/]/).at(-1), exitCode: result.exitCode, updatedAt: Date.now() });
|
|
2043
|
+
trace.push({ operation: "host", key, state: result.ok ? "completed" : result.state === "stopped" ? "stopped" : "failed", durationMs: result.durationMs, ...(!result.ok ? { error: result.error ?? "Host command failed." } : {}) });
|
|
2044
|
+
traceChanged();
|
|
2045
|
+
if (!result.ok) throw new Error(`Host command '${key}' failed: ${detail || result.error || `exit code ${result.exitCode ?? "unknown"}`}`);
|
|
2046
|
+
return result;
|
|
2047
|
+
}, (error: unknown) => {
|
|
2048
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
2049
|
+
hostStepChanged({ ...startedStep, state: "error", reasonCode: "execution_failed", detail: text.replace(/\s+/g, " ").slice(0, 200), updatedAt: Date.now() });
|
|
2050
|
+
trace.push({ operation: "host", key, state: "failed", durationMs: Date.now() - startedAt, error: text });
|
|
2051
|
+
traceChanged();
|
|
2052
|
+
throw error;
|
|
2053
|
+
});
|
|
2054
|
+
hostCalls.set(message.callId, { key, promise, observed: observedHostCalls.delete(message.callId) });
|
|
2055
|
+
respond(promise, `runs.host('${key}') result`);
|
|
2056
|
+
return;
|
|
2057
|
+
}
|
|
1019
2058
|
if (message.method !== "run") return respond(Promise.reject(new Error(`Unknown runs API method '${message.method}'.`)));
|
|
1020
2059
|
|
|
1021
2060
|
let key: string;
|
|
@@ -1026,6 +2065,36 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1026
2065
|
}
|
|
1027
2066
|
const params = message.args.params;
|
|
1028
2067
|
if (!isRecord(params)) return respond(Promise.reject(new Error(`runs.run('${key}', params) requires a params object.`)));
|
|
2068
|
+
const generatedLaneKey = typeof message.args.generatedLaneKey === "string" && KEY_PATTERN.test(message.args.generatedLaneKey) && key.startsWith(`${message.args.generatedLaneKey}.`)
|
|
2069
|
+
? message.args.generatedLaneKey
|
|
2070
|
+
: undefined;
|
|
2071
|
+
const collectFailure = message.args.collectFailure === true;
|
|
2072
|
+
const callObserved = observedRunCalls.delete(message.callId);
|
|
2073
|
+
const deliver = (promise: Promise<WorkflowScriptChildResult>) => collectFailure
|
|
2074
|
+
? promise
|
|
2075
|
+
: promise.then((result) => {
|
|
2076
|
+
const recoverableAcceptanceMetadata = result.recovery?.status === "available-for-review"
|
|
2077
|
+
&& result.recovery.reason === "acceptance-metadata-rejected";
|
|
2078
|
+
if (!result.ok && !result.stopped && !recoverableAcceptanceMetadata) {
|
|
2079
|
+
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" };
|
|
2080
|
+
if (result.detached) childError.workflowErrorKind = "detached-child";
|
|
2081
|
+
throw childError;
|
|
2082
|
+
}
|
|
2083
|
+
return result;
|
|
2084
|
+
});
|
|
2085
|
+
const fingerprint = stableJson(params);
|
|
2086
|
+
const existing = launches.get(key);
|
|
2087
|
+
if (existing) {
|
|
2088
|
+
if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
|
|
2089
|
+
if (callObserved) existing.observed = true;
|
|
2090
|
+
trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params), ...(existing.generatedLaneKey ? { generatedLaneKey: existing.generatedLaneKey } : {}) });
|
|
2091
|
+
traceChanged();
|
|
2092
|
+
return respond(deliver(existing.promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
|
|
2093
|
+
}
|
|
2094
|
+
const permitError = options.oneUsePermit?.claim(key);
|
|
2095
|
+
if (permitError) return respond(Promise.reject(new Error(permitError)));
|
|
2096
|
+
if (options.oneUsePermit && message.args.batch !== undefined) return respond(Promise.reject(new Error("Workflow child permit does not support runs.all.")));
|
|
2097
|
+
if (options.oneUsePermit && params.resume !== undefined) return respond(Promise.reject(new Error("Workflow child permit does not support retained resume.")));
|
|
1029
2098
|
if (params.action !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') accepts execution params only; management action is not allowed.`)));
|
|
1030
2099
|
if (params.workflowScript !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') cannot start a nested workflow script.`)));
|
|
1031
2100
|
if (params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.concurrency !== undefined || params.chainDir !== undefined) {
|
|
@@ -1034,6 +2103,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1034
2103
|
if (params.worktree !== undefined && typeof params.worktree !== "boolean") {
|
|
1035
2104
|
return respond(Promise.reject(new Error(`runs.run('${key}') worktree must be true or false.`)));
|
|
1036
2105
|
}
|
|
2106
|
+
if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) {
|
|
2107
|
+
return respond(Promise.reject(new Error(`runs.run('${key}') baseRef must be a valid Git ref.`)));
|
|
2108
|
+
}
|
|
1037
2109
|
if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) {
|
|
1038
2110
|
return respond(Promise.reject(new Error(`runs.run('${key}') gate must be a non-empty command string.`)));
|
|
1039
2111
|
}
|
|
@@ -1056,28 +2128,6 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1056
2128
|
if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) {
|
|
1057
2129
|
return respond(Promise.reject(new Error(`runs.run('${key}') resume requires a non-empty task follow-up.`)));
|
|
1058
2130
|
}
|
|
1059
|
-
const collectFailure = message.args.collectFailure === true;
|
|
1060
|
-
const callObserved = observedRunCalls.delete(message.callId);
|
|
1061
|
-
const deliver = (promise: Promise<WorkflowScriptChildResult>) => collectFailure
|
|
1062
|
-
? promise
|
|
1063
|
-
: promise.then((result) => {
|
|
1064
|
-
if (!result.ok) {
|
|
1065
|
-
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" };
|
|
1066
|
-
if (result.detached) childError.workflowErrorKind = "detached-child";
|
|
1067
|
-
throw childError;
|
|
1068
|
-
}
|
|
1069
|
-
return result;
|
|
1070
|
-
});
|
|
1071
|
-
const fingerprint = stableJson(params);
|
|
1072
|
-
const existing = launches.get(key);
|
|
1073
|
-
if (existing) {
|
|
1074
|
-
if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
|
|
1075
|
-
if (callObserved) existing.observed = true;
|
|
1076
|
-
trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params) });
|
|
1077
|
-
traceChanged();
|
|
1078
|
-
return respond(deliver(existing.promise), `runs.run('${key}') result`);
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
2131
|
const startedAt = Date.now();
|
|
1082
2132
|
const batch = isRecord(message.args.batch) && typeof message.args.batch.id === "string" && Array.isArray(message.args.batch.calls)
|
|
1083
2133
|
? { id: message.args.batch.id, calls: message.args.batch.calls.filter((call): call is { key: string; params: Record<string, unknown> } => isRecord(call) && typeof call.key === "string" && isRecord(call.params)) }
|
|
@@ -1092,6 +2142,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1092
2142
|
});
|
|
1093
2143
|
admission = Promise.resolve().then(() => {
|
|
1094
2144
|
if (settled || finishing) return;
|
|
2145
|
+
for (const call of calls) assertRecoveryBarrierAllowsRun(call.key, call.params);
|
|
1095
2146
|
return options.admit?.(calls);
|
|
1096
2147
|
});
|
|
1097
2148
|
if (batch) batchAdmissions.set(batch.id, admission);
|
|
@@ -1100,13 +2151,16 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1100
2151
|
const promise = admission.then(async () => {
|
|
1101
2152
|
if (settled || finishing || stoppedLaunches.has(key)) {
|
|
1102
2153
|
const reason = childController.signal.reason;
|
|
1103
|
-
const text = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.";
|
|
1104
|
-
return
|
|
2154
|
+
const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
2155
|
+
return stoppedChildResult(key, text);
|
|
1105
2156
|
}
|
|
2157
|
+
const childStopController = new AbortController();
|
|
2158
|
+
childStopControllers.set(key, childStopController);
|
|
2159
|
+
const childSignal = combinedAbortSignal([childController.signal, childStopController.signal]);
|
|
1106
2160
|
const resolvedResumeValue = resumeReference
|
|
1107
2161
|
? await Promise.resolve().then(() => {
|
|
1108
2162
|
if (!options.resolveResume) throw new Error("Keyed workflow receipt resume is unavailable in this host.");
|
|
1109
|
-
return options.resolveResume(resumeReference,
|
|
2163
|
+
return options.resolveResume(resumeReference, childSignal);
|
|
1110
2164
|
})
|
|
1111
2165
|
: undefined;
|
|
1112
2166
|
const resolvedResume = typeof resolvedResumeValue === "string"
|
|
@@ -1124,32 +2178,51 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
1124
2178
|
if (resolvedResumeLineage.at(-1) !== resolvedResumeId) resolvedResumeLineage.push(resolvedResumeId!);
|
|
1125
2179
|
}
|
|
1126
2180
|
const launchParams = resolvedResumeId ? { ...params, resume: resolvedResumeId } : params;
|
|
1127
|
-
|
|
2181
|
+
await launchSemaphore.acquire();
|
|
2182
|
+
try {
|
|
2183
|
+
if (settled || finishing || stoppedLaunches.has(key) || childSignal.aborted) {
|
|
2184
|
+
const reason = childSignal.reason;
|
|
2185
|
+
const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
2186
|
+
return stoppedChildResult(key, text);
|
|
2187
|
+
}
|
|
2188
|
+
const result = await options.launch(key, launchParams, childSignal, { admitted: true, batch: batch !== undefined });
|
|
2189
|
+
const autoResumeParams = setupAbortResumeParams(params, result, childSignal);
|
|
2190
|
+
if (!autoResumeParams) return result;
|
|
2191
|
+
resolvedResumeLineage = [...new Set([...(resolvedResumeLineage ?? []), result.runId!])];
|
|
2192
|
+
trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(autoResumeParams), ...(generatedLaneKey ? { generatedLaneKey } : {}), phase: "auto-resume", runId: result.runId });
|
|
2193
|
+
traceChanged();
|
|
2194
|
+
return options.launch(key, autoResumeParams, childSignal, { admitted: true, batch: batch !== undefined });
|
|
2195
|
+
} finally {
|
|
2196
|
+
launchSemaphore.release();
|
|
2197
|
+
}
|
|
1128
2198
|
}).then((result) => {
|
|
1129
2199
|
let normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
|
|
1130
2200
|
if (resolvedResumeLineage?.length && normalized.runId) {
|
|
1131
2201
|
normalized = { ...normalized, continuation: { runIds: [...new Set([...resolvedResumeLineage, normalized.runId])] } };
|
|
1132
2202
|
}
|
|
1133
|
-
|
|
2203
|
+
childStopControllers.delete(key);
|
|
2204
|
+
if (stoppedLaunches.has(key)) return children.get(key) ?? normalized;
|
|
1134
2205
|
children.set(key, normalized);
|
|
1135
|
-
|
|
1136
|
-
|
|
2206
|
+
recordAcceptanceRecoveryBarrier(key, normalized);
|
|
2207
|
+
const state = normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
|
|
2208
|
+
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 ? { error: normalized.error ?? normalized.output } : {}) });
|
|
1137
2209
|
traceChanged();
|
|
1138
2210
|
return normalized;
|
|
1139
2211
|
}, (error: unknown) => {
|
|
1140
2212
|
const text = error instanceof Error ? error.message : String(error);
|
|
1141
2213
|
const failure: WorkflowScriptChildResult = { key, ok: false, output: text, error: text, artifactPaths: [] };
|
|
1142
|
-
|
|
2214
|
+
childStopControllers.delete(key);
|
|
2215
|
+
if (stoppedLaunches.has(key)) return children.get(key) ?? { ...failure, stopped: true };
|
|
1143
2216
|
children.set(key, failure);
|
|
1144
|
-
trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), error: text });
|
|
2217
|
+
trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), error: text });
|
|
1145
2218
|
traceChanged();
|
|
1146
2219
|
return failure;
|
|
1147
2220
|
});
|
|
1148
|
-
launches.set(key, { fingerprint, promise, observed: callObserved });
|
|
2221
|
+
launches.set(key, { fingerprint, promise, observed: callObserved, ...(generatedLaneKey ? { generatedLaneKey } : {}) });
|
|
1149
2222
|
childOrder.push(key);
|
|
1150
|
-
trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params) });
|
|
2223
|
+
trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}) });
|
|
1151
2224
|
traceChanged();
|
|
1152
|
-
respond(deliver(promise), `runs.run('${key}') result
|
|
2225
|
+
respond(deliver(promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
|
|
1153
2226
|
});
|
|
1154
2227
|
|
|
1155
2228
|
worker.postMessage({ type: "start", script: options.script, stateEnabled: options.state !== undefined });
|