@xzzpig/pi-subagents 0.4.1 → 0.5.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 +175 -0
- package/README.md +4 -0
- package/agents/oracle.md +3 -1
- package/agents/reviewer.md +1 -0
- package/agents/scout.md +2 -2
- package/agents/worker.md +2 -1
- package/async-retention-discovery-worker.mjs +180 -0
- package/docs/agents.md +41 -3
- package/docs/configuration.md +41 -13
- package/docs/extension-api.md +65 -2
- package/docs/models.md +2 -0
- package/docs/observability.md +41 -5
- package/docs/tool-reference.md +38 -39
- package/docs/workflows.md +173 -3
- package/package.json +14 -10
- package/prompts/council.md +48 -0
- package/skills/council-mode/SKILL.md +230 -0
- package/skills/pi-subagents/SKILL.md +8 -4
- package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
- package/skills/pi-subagents/references/execution-controls.md +40 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
- package/src/agents/agent-management.ts +471 -377
- package/src/agents/agent-serializer.ts +2 -0
- package/src/agents/agents.ts +186 -44
- package/src/agents/builtin-names.ts +9 -0
- package/src/agents/runtime-agent-registry.ts +418 -0
- package/src/agents/skills.ts +1 -1
- package/src/api/agent-management.ts +9 -0
- package/src/api/agents.ts +7 -0
- package/src/api/external-job-provider.ts +186 -0
- package/src/api/preflight.ts +45 -13
- package/src/api/shared-types.ts +2 -0
- package/src/extension/config.ts +6 -3
- package/src/extension/doctor.ts +4 -6
- package/src/extension/fanout-child.ts +2 -2
- package/src/extension/index.ts +183 -90
- package/src/extension/public-execution.ts +31 -2
- package/src/extension/rpc.ts +41 -1
- package/src/extension/schemas.ts +17 -37
- package/src/extension/tool-description.ts +35 -24
- package/src/inspectors/herdr/actions.ts +2 -2
- package/src/inspectors/herdr/inspector-runner.ts +2 -1
- package/src/inspectors/herdr/project-panes.ts +2 -2
- package/src/intercom/native-supervisor-channel.ts +32 -10
- package/src/missions/lifecycle.ts +6 -1
- package/src/missions/store.ts +4 -9
- package/src/missions/workflow-state.ts +2 -2
- package/src/profiles/profiles.ts +3 -1
- package/src/runs/background/active-run-index.ts +31 -8
- package/src/runs/background/async-execution.ts +70 -41
- package/src/runs/background/async-job-tracker.ts +24 -7
- package/src/runs/background/async-resume.ts +49 -16
- package/src/runs/background/async-retention.ts +886 -0
- package/src/runs/background/async-status-snapshot.ts +14 -5
- package/src/runs/background/async-status.ts +39 -53
- package/src/runs/background/auto-drain.ts +1 -0
- package/src/runs/background/chain-append.ts +3 -33
- package/src/runs/background/completion-dedupe.ts +5 -1
- package/src/runs/background/completion-replay.ts +22 -12
- package/src/runs/background/control-channel.ts +14 -68
- package/src/runs/background/fleet-view.ts +68 -19
- package/src/runs/background/index-segment.ts +59 -0
- package/src/runs/background/inspect-rpc.ts +443 -0
- package/src/runs/background/notify.ts +31 -5
- package/src/runs/background/result-files.ts +158 -90
- package/src/runs/background/result-watcher.ts +124 -20
- package/src/runs/background/resume-guidance.ts +8 -5
- package/src/runs/background/retained-children.ts +13 -3
- package/src/runs/background/run-id-query.ts +7 -0
- package/src/runs/background/run-id-resolver.ts +11 -9
- package/src/runs/background/run-status.ts +27 -18
- package/src/runs/background/scheduled-runs.ts +24 -4
- package/src/runs/background/stale-run-reconciler.ts +6 -3
- package/src/runs/background/steering.ts +11 -1
- package/src/runs/background/subagent-runner.ts +260 -144
- package/src/runs/background/subagent-wait.ts +17 -13
- package/src/runs/background/terminal-run-index.ts +138 -0
- package/src/runs/background/wait-completions.ts +21 -4
- package/src/runs/background/wait-subscriptions.ts +81 -2
- package/src/runs/background/wait-tool.ts +1 -0
- package/src/runs/foreground/async-steering-action.ts +21 -14
- package/src/runs/foreground/execution.ts +104 -71
- package/src/runs/foreground/subagent-executor.ts +816 -1593
- package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
- package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
- package/src/runs/shared/acceptance.ts +48 -5
- package/src/runs/shared/chain-outputs.ts +1 -3
- package/src/runs/shared/external-job-bridge.ts +444 -0
- package/src/runs/shared/external-job-runner.ts +286 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
- package/src/runs/shared/model-exclusions.ts +242 -0
- package/src/runs/shared/model-fallback.ts +153 -40
- package/src/runs/shared/orca-progress-tabs.ts +84 -22
- package/src/runs/shared/parallel-handoff.ts +46 -4
- package/src/runs/shared/parallel-utils.ts +4 -15
- package/src/runs/shared/permissions.ts +5 -1
- package/src/runs/shared/pi-args.ts +8 -1
- package/src/runs/shared/session-lease.ts +0 -6
- package/src/runs/shared/subagent-control.ts +51 -7
- package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
- package/src/runs/shared/workflow-graph.ts +1 -23
- package/src/runs/shared/worktree.ts +14 -2
- package/src/shared/atomic-json.ts +22 -2
- package/src/shared/capacity-resilient-json.ts +102 -0
- package/src/shared/completion-owner.ts +14 -0
- package/src/shared/file-system-retry.ts +49 -1
- package/src/shared/fork-context.ts +59 -1
- package/src/shared/model-info.ts +20 -0
- package/src/shared/prompt-resources.ts +0 -40
- package/src/shared/settings.ts +5 -29
- package/src/shared/types.ts +106 -26
- package/src/shared/utils.ts +8 -0
- package/src/shared/watch-strategy.ts +10 -0
- package/src/slash/slash-bridge.ts +2 -1
- package/src/slash/slash-commands.ts +47 -7
- package/src/slash/slash-live-state.ts +3 -3
- package/src/tui/fleet-status.ts +86 -1
- package/src/tui/fleet.ts +117 -16
- package/src/tui/render.ts +73 -3
- package/src/watchdog/change-signature.ts +1 -1
- package/src/watchdog/lsp-diagnostics.ts +1 -0
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +320 -79
- package/src/workflows/workflow-receipt.ts +140 -0
- package/src/runs/foreground/chain-clarify.ts +0 -1354
- package/src/runs/foreground/chain-execution.ts +0 -1581
|
@@ -1,14 +1,31 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { dirname, resolve as resolvePath } from "node:path";
|
|
1
4
|
import { Worker } from "node:worker_threads";
|
|
2
5
|
|
|
3
6
|
const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
7
|
+
const requireFromPackage = createRequire(import.meta.url);
|
|
4
8
|
|
|
5
9
|
const WORKER_SOURCE = String.raw`
|
|
6
|
-
const { parentPort } = require("node:worker_threads");
|
|
7
|
-
const { promiseHooks } = require("node:v8");
|
|
10
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
8
11
|
const vm = require("node:vm");
|
|
9
12
|
const { inspect } = require("node:util");
|
|
13
|
+
const { parse } = require(workerData.acornPath);
|
|
10
14
|
|
|
11
|
-
|
|
15
|
+
let promiseHooks;
|
|
16
|
+
try {
|
|
17
|
+
({ promiseHooks } = require("node:v8"));
|
|
18
|
+
} catch {}
|
|
19
|
+
|
|
20
|
+
function createWorkflowPromiseHook(callbacks) {
|
|
21
|
+
if (!promiseHooks || typeof promiseHooks.createHook !== "function") return () => {};
|
|
22
|
+
try {
|
|
23
|
+
return promiseHooks.createHook(callbacks);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error?.name !== "NotImplementedError") throw error;
|
|
26
|
+
return () => {};
|
|
27
|
+
}
|
|
28
|
+
}
|
|
12
29
|
|
|
13
30
|
let nextCallId = 0;
|
|
14
31
|
let topLevelWorkflowPromise;
|
|
@@ -20,7 +37,7 @@ const trackedPromiseTrackers = new WeakMap();
|
|
|
20
37
|
const trackedPromiseTargets = new WeakMap();
|
|
21
38
|
let nativePromiseTrackers = new WeakMap();
|
|
22
39
|
let nativePromiseParents = new WeakMap();
|
|
23
|
-
const
|
|
40
|
+
const observedCallIds = new Set();
|
|
24
41
|
|
|
25
42
|
function stableRunJson(value) {
|
|
26
43
|
if (Array.isArray(value)) return "[" + value.map(stableRunJson).join(",") + "]";
|
|
@@ -79,7 +96,7 @@ function mergeObservations(...groups) {
|
|
|
79
96
|
const merged = [];
|
|
80
97
|
for (const group of groups) {
|
|
81
98
|
for (const observation of group) {
|
|
82
|
-
if (!observation || typeof observation.callId !== "number" || typeof observation.key !== "string" || seen.has(observation.callId)) continue;
|
|
99
|
+
if (!observation || typeof observation.callId !== "number" || typeof observation.key !== "string" || typeof observation.operation !== "string" || seen.has(observation.callId)) continue;
|
|
83
100
|
seen.add(observation.callId);
|
|
84
101
|
merged.push(observation);
|
|
85
102
|
}
|
|
@@ -99,9 +116,9 @@ function addTrackedObservations(tracker, observations) {
|
|
|
99
116
|
tracker.observations = mergeObservations(tracker.observations, observations);
|
|
100
117
|
if (!tracker.consumed) return;
|
|
101
118
|
for (const observation of tracker.observations) {
|
|
102
|
-
if (
|
|
103
|
-
|
|
104
|
-
parentPort.postMessage({ type: "
|
|
119
|
+
if (observedCallIds.has(observation.callId)) continue;
|
|
120
|
+
observedCallIds.add(observation.callId);
|
|
121
|
+
parentPort.postMessage({ type: "callObserved", callId: observation.callId, key: observation.key, operation: observation.operation });
|
|
105
122
|
}
|
|
106
123
|
}
|
|
107
124
|
|
|
@@ -211,8 +228,8 @@ function hostCall(method, args, observation) {
|
|
|
211
228
|
pending.set(callId, { resolve, reject });
|
|
212
229
|
parentPort.postMessage({ type: "call", callId, method, args });
|
|
213
230
|
});
|
|
214
|
-
return observation && typeof observation.key === "string"
|
|
215
|
-
? trackRunObservation([{ key: observation.key, callId }], promise)
|
|
231
|
+
return observation && typeof observation.key === "string" && typeof observation.operation === "string"
|
|
232
|
+
? trackRunObservation([{ key: observation.key, operation: observation.operation, callId }], promise)
|
|
216
233
|
: promise;
|
|
217
234
|
}
|
|
218
235
|
|
|
@@ -232,7 +249,7 @@ function formatRef(result) {
|
|
|
232
249
|
return "[" + parts.join("; ") + "]";
|
|
233
250
|
}
|
|
234
251
|
|
|
235
|
-
|
|
252
|
+
let runFingerprints = new Map();
|
|
236
253
|
|
|
237
254
|
function validateRunCall(key, params, label, fingerprints) {
|
|
238
255
|
if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
|
|
@@ -241,11 +258,21 @@ function validateRunCall(key, params, label, fingerprints) {
|
|
|
241
258
|
const hint = label === "runs.run" ? "; use runs.all(...) and JavaScript control flow for orchestration." : ".";
|
|
242
259
|
throw new Error(label + " accepts one child via { agent, task } and execution controls only" + hint);
|
|
243
260
|
}
|
|
261
|
+
if (Object.prototype.hasOwnProperty.call(params, "clarify")) throw new Error(label + " does not support clarify UI.");
|
|
244
262
|
if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
|
|
245
263
|
if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) throw new Error(label + " gate must be a non-empty command string.");
|
|
246
264
|
if (params.gate !== undefined && params.acceptance !== undefined) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify.");
|
|
247
265
|
if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
|
|
248
|
-
if (params.resume !== undefined &&
|
|
266
|
+
if (params.resume !== undefined && typeof params.resume !== "string") {
|
|
267
|
+
const reference = params.resume;
|
|
268
|
+
if (!reference || typeof reference !== "object" || Array.isArray(reference)) throw new Error(label + " resume must be a retained run id or keyed workflow receipt reference.");
|
|
269
|
+
const fields = Object.keys(reference);
|
|
270
|
+
if (fields.some((field) => field !== "workflowRunId" && field !== "key" && field !== "latest")) throw new Error(label + " keyed resume contains unsupported fields.");
|
|
271
|
+
if (typeof reference.workflowRunId !== "string" || !reference.workflowRunId.trim()) throw new Error(label + " keyed resume workflowRunId must be non-empty.");
|
|
272
|
+
if (typeof reference.key !== "string" || !runKeyPattern.test(reference.key)) throw new Error(label + " keyed resume key is invalid.");
|
|
273
|
+
if (reference.latest !== true) throw new Error(label + " keyed resume requires latest: true.");
|
|
274
|
+
}
|
|
275
|
+
if (typeof params.resume === "string" && !params.resume.trim()) throw new Error(label + " resume must be a non-empty retained run id.");
|
|
249
276
|
if (params.resume !== undefined && params.agent !== undefined) throw new Error(label + " resume and agent are mutually exclusive.");
|
|
250
277
|
if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) throw new Error(label + " resume requires a non-empty task follow-up.");
|
|
251
278
|
assertJsonValue(params, label + " params");
|
|
@@ -258,7 +285,7 @@ function validateRunCall(key, params, label, fingerprints) {
|
|
|
258
285
|
const runs = Object.freeze({
|
|
259
286
|
run(key, params) {
|
|
260
287
|
validateRunCall(key, params, "runs.run", runFingerprints);
|
|
261
|
-
return hostCall("run", { key, params }, { key });
|
|
288
|
+
return hostCall("run", { key, params }, { key, operation: "run" });
|
|
262
289
|
},
|
|
263
290
|
all(items) {
|
|
264
291
|
if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
|
|
@@ -272,10 +299,21 @@ const runs = Object.freeze({
|
|
|
272
299
|
validateRunCall(key, params, "runs.all item " + index, fingerprints);
|
|
273
300
|
calls.push({ key, params });
|
|
274
301
|
}
|
|
275
|
-
|
|
302
|
+
runFingerprints = fingerprints;
|
|
276
303
|
const batch = { id: "batch-" + (++nextCallId), calls };
|
|
277
304
|
const launched = calls.map(({ key, params }) => runHostCall(key, params, true, batch));
|
|
278
|
-
return trackRunObservation(launched.map(({ key, callId }) => ({ key, callId })), Promise.all(launched.map(({ promise }) => promise)));
|
|
305
|
+
return trackRunObservation(launched.map(({ key, callId }) => ({ key, operation: "run", callId })), Promise.all(launched.map(({ promise }) => promise)));
|
|
306
|
+
},
|
|
307
|
+
steer(key, message, options = {}) {
|
|
308
|
+
if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error("runs.steer has an invalid key.");
|
|
309
|
+
if (typeof message !== "string" || !message.trim()) throw new Error("runs.steer message must be a non-empty string.");
|
|
310
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("runs.steer options must be an object.");
|
|
311
|
+
const allowed = new Set(["mode", "index", "ackTimeoutMs"]);
|
|
312
|
+
for (const option of Object.keys(options)) if (!allowed.has(option)) throw new Error("runs.steer options contain unsupported field '" + option + "'.");
|
|
313
|
+
if (options.mode !== undefined && options.mode !== "steer" && options.mode !== "follow_up" && options.mode !== "auto") throw new Error("runs.steer mode must be 'steer', 'follow_up', or 'auto'.");
|
|
314
|
+
if (options.index !== undefined && (!Number.isInteger(options.index) || options.index < 0 || options.index > 1000000)) throw new Error("runs.steer index must be an integer between 0 and 1000000.");
|
|
315
|
+
if (options.ackTimeoutMs !== undefined && (!Number.isInteger(options.ackTimeoutMs) || options.ackTimeoutMs < 1)) throw new Error("runs.steer ackTimeoutMs must be a positive integer.");
|
|
316
|
+
return hostCall("steer", { key, message: message.trim(), options }, { key, operation: "steer" });
|
|
279
317
|
},
|
|
280
318
|
status(keyOrRunId) { return hostCall("status", { keyOrRunId }); },
|
|
281
319
|
ref: formatRef,
|
|
@@ -299,14 +337,6 @@ const state = Object.freeze({
|
|
|
299
337
|
},
|
|
300
338
|
});
|
|
301
339
|
|
|
302
|
-
const prompts = Object.freeze({
|
|
303
|
-
render(ref, vars) {
|
|
304
|
-
if (typeof ref !== "string" || !ref.trim()) throw new Error("prompts.render(ref, vars) requires a non-empty ref string.");
|
|
305
|
-
if (vars !== undefined) assertJsonValue(vars, "prompts.render vars");
|
|
306
|
-
return hostCall("prompts.render", { ref, vars });
|
|
307
|
-
},
|
|
308
|
-
});
|
|
309
|
-
|
|
310
340
|
let contextObjectPrototype;
|
|
311
341
|
|
|
312
342
|
const capturedConsole = Object.freeze(Object.fromEntries(
|
|
@@ -316,7 +346,7 @@ const capturedConsole = Object.freeze(Object.fromEntries(
|
|
|
316
346
|
));
|
|
317
347
|
|
|
318
348
|
function formatWorkflowScriptSyntaxError(error) {
|
|
319
|
-
const details =
|
|
349
|
+
const details = formatWorkflowScriptError(error);
|
|
320
350
|
return [
|
|
321
351
|
"workflowScript must be valid JavaScript.",
|
|
322
352
|
"If task text contains Markdown fences or backticks, use an array joined with \"\\n\" or escaped strings instead of a raw backtick template literal.",
|
|
@@ -326,6 +356,52 @@ function formatWorkflowScriptSyntaxError(error) {
|
|
|
326
356
|
].join("\n");
|
|
327
357
|
}
|
|
328
358
|
|
|
359
|
+
function formatWorkflowScriptError(error) {
|
|
360
|
+
const message = error && typeof error.message === "string" ? error.message : String(error);
|
|
361
|
+
const stack = error && typeof error.stack === "string" ? error.stack : "";
|
|
362
|
+
if (!stack) return message;
|
|
363
|
+
return stack.includes(message) ? stack : message + "\n" + stack;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function isSyntaxError(error) {
|
|
367
|
+
return error instanceof SyntaxError || error?.name === "SyntaxError";
|
|
368
|
+
}
|
|
369
|
+
|
|
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.";
|
|
371
|
+
const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
|
|
372
|
+
|
|
373
|
+
function assertPortableWorkflowScript(source) {
|
|
374
|
+
const wrapped = "(async () => {\n" + source + "\n})()";
|
|
375
|
+
const ast = parse(wrapped, { ecmaVersion: "latest", sourceType: "script" });
|
|
376
|
+
const wrapper = workflowWrapperFunction(ast);
|
|
377
|
+
walkWorkflowAst(wrapper.body, wrapper);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function workflowWrapperFunction(ast) {
|
|
381
|
+
const wrapper = ast.body?.[0]?.expression?.callee;
|
|
382
|
+
if (!wrapper || wrapper.type !== "ArrowFunctionExpression") throw new Error("workflowScript wrapper parse invariant failed.");
|
|
383
|
+
return wrapper;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function isAsyncFunctionNode(node) {
|
|
387
|
+
return node.async === true && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression");
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function walkWorkflowAst(node, allowedAsyncFunction) {
|
|
391
|
+
if (!node || typeof node !== "object") return;
|
|
392
|
+
if (Array.isArray(node)) {
|
|
393
|
+
for (const item of node) walkWorkflowAst(item, allowedAsyncFunction);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
if (node !== allowedAsyncFunction && isAsyncFunctionNode(node)) {
|
|
397
|
+
throw new Error(NESTED_ASYNC_WORKFLOW_ERROR);
|
|
398
|
+
}
|
|
399
|
+
for (const [key, child] of Object.entries(node)) {
|
|
400
|
+
if (AST_SCALAR_KEYS.has(key)) continue;
|
|
401
|
+
walkWorkflowAst(child, allowedAsyncFunction);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
329
405
|
function assertJsonValue(value, path = "emit", seen = new Set()) {
|
|
330
406
|
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
331
407
|
if (typeof value === "number") {
|
|
@@ -383,16 +459,16 @@ parentPort.on("message", async (message) => {
|
|
|
383
459
|
}
|
|
384
460
|
if (message.type !== "start") return;
|
|
385
461
|
try {
|
|
386
|
-
const sandbox = { runs,
|
|
462
|
+
const sandbox = { runs, Promise: workflowPromise, emit(value) { assertJsonValue(value); parentPort.postMessage({ type: "emit", value }); }, console: capturedConsole };
|
|
387
463
|
if (message.stateEnabled) sandbox.state = state;
|
|
388
464
|
const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
|
|
389
465
|
contextObjectPrototype = vm.runInContext("Object.prototype", context);
|
|
390
466
|
let compiled;
|
|
391
467
|
try {
|
|
468
|
+
assertPortableWorkflowScript(message.script);
|
|
392
469
|
compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js" });
|
|
393
470
|
} catch (error) {
|
|
394
|
-
|
|
395
|
-
parentPort.postMessage({ type: "error", error: formatWorkflowScriptSyntaxError(error) });
|
|
471
|
+
parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
|
|
396
472
|
return;
|
|
397
473
|
}
|
|
398
474
|
const nativePromisePrototype = vm.runInContext("(async () => {})().constructor.prototype", context);
|
|
@@ -411,7 +487,7 @@ parentPort.on("message", async (message) => {
|
|
|
411
487
|
return Reflect.apply(nativeThen, this, args);
|
|
412
488
|
},
|
|
413
489
|
});
|
|
414
|
-
stopWorkflowPromiseHook =
|
|
490
|
+
stopWorkflowPromiseHook = createWorkflowPromiseHook({
|
|
415
491
|
before(promise) {
|
|
416
492
|
activeNativePromises.push(promise);
|
|
417
493
|
},
|
|
@@ -456,7 +532,7 @@ parentPort.on("message", async (message) => {
|
|
|
456
532
|
assertJsonValue(persistedValue, "return");
|
|
457
533
|
parentPort.postMessage({ type: "complete", value: persistedValue });
|
|
458
534
|
} catch (error) {
|
|
459
|
-
parentPort.postMessage({ type: "error", error: error
|
|
535
|
+
parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), ...(error && error.workflowErrorKind === "detached-child" ? { errorKind: "detached-child" } : {}) });
|
|
460
536
|
}
|
|
461
537
|
});
|
|
462
538
|
`;
|
|
@@ -471,14 +547,19 @@ export interface WorkflowScriptChildResult {
|
|
|
471
547
|
error?: string;
|
|
472
548
|
detached?: boolean;
|
|
473
549
|
structuredOutput?: unknown;
|
|
550
|
+
requestedContext?: "fresh" | "fork";
|
|
551
|
+
resolvedContext?: "fresh" | "fork" | "mixed";
|
|
552
|
+
outputReference?: string;
|
|
553
|
+
resumability?: { state: "resumable" } | { state: "not-resumable"; reason: string };
|
|
554
|
+
continuation?: { runIds: string[] };
|
|
474
555
|
artifactPaths: string[];
|
|
475
556
|
results?: unknown[];
|
|
476
557
|
}
|
|
477
558
|
|
|
478
559
|
export interface WorkflowScriptTraceEntry {
|
|
479
|
-
operation: "run" | "status";
|
|
560
|
+
operation: "run" | "status" | "steer";
|
|
480
561
|
key: string;
|
|
481
|
-
state: "started" | "completed" | "failed" | "detached" | "stopped" | "reused";
|
|
562
|
+
state: "started" | "completed" | "failed" | "detached" | "stopped" | "reused" | "queued" | "delivered" | "missed";
|
|
482
563
|
/** Canonical child agent name when resolved launch or result data is available. */
|
|
483
564
|
agent?: string;
|
|
484
565
|
runId?: string;
|
|
@@ -488,6 +569,32 @@ export interface WorkflowScriptTraceEntry {
|
|
|
488
569
|
error?: string;
|
|
489
570
|
}
|
|
490
571
|
|
|
572
|
+
export interface WorkflowSteerOptions {
|
|
573
|
+
mode?: "steer" | "follow_up" | "auto";
|
|
574
|
+
index?: number;
|
|
575
|
+
ackTimeoutMs?: number;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
export interface WorkflowSteerResult {
|
|
579
|
+
key: string;
|
|
580
|
+
state: "queued" | "delivered" | "missed" | "failed";
|
|
581
|
+
requestId?: string;
|
|
582
|
+
deliveryStatus?: "queued" | "delivered";
|
|
583
|
+
targets?: Array<{ index: number; state: string; reason?: string }>;
|
|
584
|
+
error?: string;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
export interface WorkflowReceiptResumeReference {
|
|
588
|
+
workflowRunId: string;
|
|
589
|
+
key: string;
|
|
590
|
+
latest: true;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
export interface WorkflowResolvedResumeReference {
|
|
594
|
+
runId: string;
|
|
595
|
+
runIds?: string[];
|
|
596
|
+
}
|
|
597
|
+
|
|
491
598
|
export interface WorkflowScriptResult {
|
|
492
599
|
value: unknown;
|
|
493
600
|
emits: unknown[];
|
|
@@ -514,14 +621,13 @@ export interface RunWorkflowScriptOptions {
|
|
|
514
621
|
signal?: AbortSignal;
|
|
515
622
|
admit?: (calls: Array<{ key: string; params: Record<string, unknown> }>) => void | Promise<void>;
|
|
516
623
|
launch: (key: string, params: Record<string, unknown>, signal: AbortSignal, admission: { admitted: boolean }) => Promise<WorkflowScriptChildResult>;
|
|
624
|
+
resolveResume?: (reference: WorkflowReceiptResumeReference, signal: AbortSignal) => string | WorkflowResolvedResumeReference | Promise<string | WorkflowResolvedResumeReference>;
|
|
517
625
|
status: (keyOrRunId: string, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
|
|
626
|
+
steer?: (key: string, message: string, options: WorkflowSteerOptions, signal: AbortSignal) => Promise<WorkflowSteerResult>;
|
|
518
627
|
state?: {
|
|
519
628
|
get: (key: string) => unknown | Promise<unknown>;
|
|
520
629
|
set: (key: string, value: unknown) => void | Promise<void>;
|
|
521
630
|
};
|
|
522
|
-
prompts?: {
|
|
523
|
-
render: (ref: string, vars?: unknown) => string | Promise<string>;
|
|
524
|
-
};
|
|
525
631
|
onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
|
|
526
632
|
onEmit?: (emits: unknown[]) => void;
|
|
527
633
|
}
|
|
@@ -536,6 +642,16 @@ function isPlainJsonObject(value: unknown): value is Record<string, unknown> {
|
|
|
536
642
|
return prototype === null || prototype === Object.prototype;
|
|
537
643
|
}
|
|
538
644
|
|
|
645
|
+
function parseWorkflowResumeReference(value: unknown): WorkflowReceiptResumeReference | undefined {
|
|
646
|
+
if (!isRecord(value)) return undefined;
|
|
647
|
+
const fields = Object.keys(value);
|
|
648
|
+
if (fields.some((field) => field !== "workflowRunId" && field !== "key" && field !== "latest")) throw new Error("keyed resume contains unsupported fields.");
|
|
649
|
+
if (typeof value.workflowRunId !== "string" || !value.workflowRunId.trim()) throw new Error("keyed resume workflowRunId must be non-empty.");
|
|
650
|
+
const key = validateKey(value.key, "keyed resume");
|
|
651
|
+
if (value.latest !== true) throw new Error("keyed resume requires latest: true.");
|
|
652
|
+
return { workflowRunId: value.workflowRunId.trim(), key, latest: true };
|
|
653
|
+
}
|
|
654
|
+
|
|
539
655
|
function omitUndefinedWorkflowValues(value: unknown, seen = new Set<object>()): unknown {
|
|
540
656
|
if (value === null || typeof value !== "object") return value;
|
|
541
657
|
if (seen.has(value)) return value;
|
|
@@ -549,6 +665,18 @@ function omitUndefinedWorkflowValues(value: unknown, seen = new Set<object>()):
|
|
|
549
665
|
return normalized;
|
|
550
666
|
}
|
|
551
667
|
|
|
668
|
+
function omitNonJsonWorkflowResultMetadata(value: unknown): unknown {
|
|
669
|
+
const normalized = omitUndefinedWorkflowValues(value);
|
|
670
|
+
if (!isPlainJsonObject(normalized) || !Object.hasOwn(normalized, "results")) return normalized;
|
|
671
|
+
try {
|
|
672
|
+
assertWorkflowJsonValue(normalized.results, "runs.run result.results");
|
|
673
|
+
return normalized;
|
|
674
|
+
} catch {
|
|
675
|
+
const { results: _results, ...safeResult } = normalized;
|
|
676
|
+
return safeResult;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
552
680
|
export function assertWorkflowJsonValue(value: unknown, path = "value", seen = new Set<object>()): void {
|
|
553
681
|
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
554
682
|
if (typeof value === "number") {
|
|
@@ -629,44 +757,92 @@ function workflowStringMetadata(params: Record<string, unknown>): Pick<WorkflowS
|
|
|
629
757
|
};
|
|
630
758
|
}
|
|
631
759
|
|
|
760
|
+
function resolveWorkflowParserEntry(): string {
|
|
761
|
+
try {
|
|
762
|
+
return requireFromPackage.resolve("acorn");
|
|
763
|
+
} catch (primaryError) {
|
|
764
|
+
// Some runtimes (e.g. Bun-compiled single-file binaries) fail bare
|
|
765
|
+
// package-specifier resolution through createRequire while subpath
|
|
766
|
+
// resolution still works. Resolve the manifest and derive the
|
|
767
|
+
// CommonJS entry from its "main" field instead.
|
|
768
|
+
try {
|
|
769
|
+
const manifestPath = requireFromPackage.resolve("acorn/package.json");
|
|
770
|
+
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { main?: unknown };
|
|
771
|
+
const entry = typeof manifest.main === "string" && manifest.main ? manifest.main : "./dist/acorn.js";
|
|
772
|
+
return resolvePath(dirname(manifestPath), entry);
|
|
773
|
+
} catch {
|
|
774
|
+
throw primaryError;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
632
779
|
export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
|
|
633
780
|
if (!options.script.trim()) throw new Error("workflowScript must not be empty.");
|
|
634
781
|
if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) throw new Error("workflow script timeout must be a positive integer.");
|
|
635
782
|
|
|
636
|
-
|
|
783
|
+
let acornPath: string;
|
|
784
|
+
try {
|
|
785
|
+
acornPath = resolveWorkflowParserEntry();
|
|
786
|
+
} catch (error) {
|
|
787
|
+
throw new Error("Workflow parser dependency 'acorn' is unavailable from pi-subagents. Reinstall pi-subagents dependencies before launching workflowScript.", { cause: error });
|
|
788
|
+
}
|
|
789
|
+
const worker = new Worker(WORKER_SOURCE, { eval: true, workerData: { acornPath } });
|
|
637
790
|
const emits: unknown[] = [];
|
|
638
791
|
const consoleEntries: WorkflowScriptResult["console"] = [];
|
|
639
792
|
const trace: WorkflowScriptTraceEntry[] = [];
|
|
640
793
|
const children = new Map<string, WorkflowScriptChildResult>();
|
|
641
794
|
const childOrder: string[] = [];
|
|
642
795
|
const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult>; observed: boolean }>();
|
|
796
|
+
const steers = new Map<number, { key: string; promise: Promise<WorkflowSteerResult>; observed: boolean }>();
|
|
643
797
|
const stoppedLaunches = new Set<string>();
|
|
644
798
|
const batchAdmissions = new Map<string, Promise<void>>();
|
|
645
799
|
const observedRunCalls = new Set<number>();
|
|
800
|
+
const observedSteerCalls = new Set<number>();
|
|
646
801
|
const childController = new AbortController();
|
|
647
802
|
let settled = false;
|
|
803
|
+
let finishing = false;
|
|
648
804
|
|
|
649
805
|
const partial = (): Omit<WorkflowScriptResult, "value"> => ({ emits, console: consoleEntries, trace, children: childOrder.flatMap((key) => {
|
|
650
806
|
const child = children.get(key);
|
|
651
807
|
return child ? [child] : [];
|
|
652
808
|
}) });
|
|
653
|
-
|
|
809
|
+
// Hosts use onTrace to persist a progress journal, and it is invoked from inside
|
|
810
|
+
// the run-promise handlers below. A throw here would reject the child promise the
|
|
811
|
+
// script is awaiting, so a single failed status write could mark a completed child
|
|
812
|
+
// failed and abort its siblings through Promise.all. Telemetry must not decide
|
|
813
|
+
// workflow outcomes, so a failing callback is reported and the run continues.
|
|
814
|
+
const traceChanged = () => {
|
|
815
|
+
try {
|
|
816
|
+
options.onTrace?.([...trace]);
|
|
817
|
+
} catch (error) {
|
|
818
|
+
console.error("Workflow onTrace callback failed:", error);
|
|
819
|
+
}
|
|
820
|
+
};
|
|
654
821
|
|
|
655
822
|
return await new Promise<WorkflowScriptResult>((resolve, reject) => {
|
|
656
823
|
const finish = (outcome: { value: unknown } | { error: Error & { workflowErrorKind?: unknown } }) => {
|
|
657
|
-
if (settled) return;
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
824
|
+
if (settled || finishing) return;
|
|
825
|
+
finishing = true;
|
|
826
|
+
childController.abort("error" in outcome ? outcome.error : new Error("Workflow script completed."));
|
|
827
|
+
void Promise.allSettled([...steers.values()].map(({ promise }) => promise)).then(() => {
|
|
828
|
+
if (settled) return;
|
|
829
|
+
settled = true;
|
|
830
|
+
if (timer) clearTimeout(timer);
|
|
831
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
832
|
+
void worker.terminate();
|
|
833
|
+
const unobservedKeys = "value" in outcome ? [...launches].filter(([, launch]) => !launch.observed).map(([key]) => key) : [];
|
|
834
|
+
const completionError = unobservedKeys.length > 0
|
|
835
|
+
? new Error(`workflowScript completed with unawaited runs.run launch(es): ${unobservedKeys.map((key) => `'${key}'`).join(", ")}. For ordinary parallel fanout use await runs.all([{key, agent, task}, ...]); do not read .output from unawaited launches.`)
|
|
836
|
+
: "value" in outcome
|
|
837
|
+
? (() => {
|
|
838
|
+
const unobservedSteers = [...steers.values()].filter((steer) => !steer.observed).map((steer) => steer.key);
|
|
839
|
+
return unobservedSteers.length > 0 ? new Error(`workflowScript completed with unawaited runs.steer call(s): ${unobservedSteers.map((key) => `'${key}'`).join(", ")}. Await or return each call.`) : undefined;
|
|
840
|
+
})()
|
|
841
|
+
: undefined;
|
|
842
|
+
if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), outcome.error.workflowErrorKind === "detached-child" ? "detached-child" : undefined));
|
|
843
|
+
else if (completionError) reject(new WorkflowScriptError(completionError.message, partial()));
|
|
844
|
+
else resolve({ value: outcome.value, ...partial() });
|
|
845
|
+
});
|
|
670
846
|
};
|
|
671
847
|
const onAbort = () => {
|
|
672
848
|
const signalReason = options.signal?.reason;
|
|
@@ -738,37 +914,42 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
738
914
|
if (message.errorKind === "detached-child") workflowError.workflowErrorKind = "detached-child";
|
|
739
915
|
return finish({ error: workflowError });
|
|
740
916
|
}
|
|
741
|
-
if (message.type === "
|
|
917
|
+
if (message.type === "callObserved" && typeof message.callId === "number") {
|
|
742
918
|
const key = typeof message.key === "string" ? message.key : undefined;
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
919
|
+
if (message.operation === "run") {
|
|
920
|
+
const launch = key ? launches.get(key) : undefined;
|
|
921
|
+
if (launch) launch.observed = true;
|
|
922
|
+
else observedRunCalls.add(message.callId);
|
|
923
|
+
} else if (message.operation === "steer") {
|
|
924
|
+
const steer = steers.get(message.callId);
|
|
925
|
+
if (steer) steer.observed = true;
|
|
926
|
+
else observedSteerCalls.add(message.callId);
|
|
927
|
+
}
|
|
746
928
|
return;
|
|
747
929
|
}
|
|
748
930
|
if (message.type !== "call" || typeof message.callId !== "number" || typeof message.method !== "string" || !isRecord(message.args)) return;
|
|
749
931
|
|
|
750
|
-
const respond = (promise: Promise<unknown
|
|
932
|
+
const respond = (promise: Promise<unknown>, responsePath?: string) => {
|
|
751
933
|
void promise.then(
|
|
752
934
|
(value) => {
|
|
753
|
-
if (
|
|
935
|
+
if (settled) return;
|
|
936
|
+
const normalized = responsePath ? omitNonJsonWorkflowResultMetadata(value) : omitUndefinedWorkflowValues(value);
|
|
937
|
+
if (!responsePath) {
|
|
938
|
+
worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
try {
|
|
942
|
+
assertWorkflowJsonValue(normalized, responsePath);
|
|
943
|
+
worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
|
|
944
|
+
} catch (error) {
|
|
945
|
+
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
|
+
}
|
|
754
947
|
},
|
|
755
948
|
(error: unknown) => {
|
|
756
949
|
if (!settled) worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...(error instanceof Error && (error as { workflowErrorKind?: unknown }).workflowErrorKind === "detached-child" ? { errorKind: "detached-child" } : {}) });
|
|
757
950
|
},
|
|
758
951
|
);
|
|
759
952
|
};
|
|
760
|
-
|
|
761
|
-
if (message.method === "prompts.render") {
|
|
762
|
-
if (!options.prompts) return respond(Promise.reject(new Error("Workflow prompt rendering is unavailable.")));
|
|
763
|
-
const ref = message.args.ref;
|
|
764
|
-
const vars = message.args.vars;
|
|
765
|
-
if (typeof ref !== "string" || !ref.trim()) return respond(Promise.reject(new Error("prompts.render(ref, vars) requires a non-empty ref string.")));
|
|
766
|
-
return respond(Promise.resolve().then(() => options.prompts!.render(ref, vars)).then((rendered) => {
|
|
767
|
-
if (typeof rendered !== "string") throw new Error("prompts.render must return task text.");
|
|
768
|
-
return rendered;
|
|
769
|
-
}));
|
|
770
|
-
}
|
|
771
|
-
|
|
772
953
|
if (message.method === "state.get" || message.method === "state.set") {
|
|
773
954
|
if (!options.state) return respond(Promise.reject(new Error("Workflow state is unavailable without a mission.")));
|
|
774
955
|
let key: string;
|
|
@@ -794,9 +975,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
794
975
|
const target = known?.runId ?? keyOrRunId;
|
|
795
976
|
trace.push({ operation: "status", key: keyOrRunId, state: "started", ...(known?.runId ? { runId: known.runId } : {}) });
|
|
796
977
|
traceChanged();
|
|
797
|
-
if (settled) return;
|
|
978
|
+
if (settled || finishing) return;
|
|
798
979
|
respond(options.status(target, childController.signal).then((result) => {
|
|
799
|
-
if (settled) return result;
|
|
980
|
+
if (settled || finishing) return result;
|
|
800
981
|
trace.push({ operation: "status", key: keyOrRunId, state: result.ok ? "completed" : "failed", ...(result.runId ? { runId: result.runId } : {}), ...(!result.ok ? { error: result.output } : {}) });
|
|
801
982
|
traceChanged();
|
|
802
983
|
if (!result.ok) throw new Error(`Status '${keyOrRunId}' failed: ${result.output}`);
|
|
@@ -804,6 +985,37 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
804
985
|
}));
|
|
805
986
|
return;
|
|
806
987
|
}
|
|
988
|
+
if (message.method === "steer") {
|
|
989
|
+
let key: string;
|
|
990
|
+
try {
|
|
991
|
+
key = validateKey(message.args.key, "runs.steer");
|
|
992
|
+
} catch (error) {
|
|
993
|
+
return respond(Promise.reject(error));
|
|
994
|
+
}
|
|
995
|
+
const steerMessage = message.args.message;
|
|
996
|
+
if (typeof steerMessage !== "string" || !steerMessage.trim()) return respond(Promise.reject(new Error(`runs.steer('${key}') requires a non-empty message.`)));
|
|
997
|
+
const steerOptions = isRecord(message.args.options) ? message.args.options as WorkflowSteerOptions : {};
|
|
998
|
+
const startedAt = Date.now();
|
|
999
|
+
trace.push({ operation: "steer", key, state: "started" });
|
|
1000
|
+
traceChanged();
|
|
1001
|
+
const promise = Promise.resolve().then(() => {
|
|
1002
|
+
if (!launches.has(key)) throw new Error(`runs.steer('${key}') requires a prior runs.run/runs.all launch with that key.`);
|
|
1003
|
+
if (!options.steer) throw new Error("Workflow steering is unavailable in this host.");
|
|
1004
|
+
return options.steer(key, steerMessage.trim(), steerOptions, childController.signal);
|
|
1005
|
+
}).then((receipt) => {
|
|
1006
|
+
trace.push({ operation: "steer", key, state: receipt.state, durationMs: Date.now() - startedAt, ...(receipt.error ? { error: receipt.error } : {}) });
|
|
1007
|
+
traceChanged();
|
|
1008
|
+
return receipt;
|
|
1009
|
+
}, (error: unknown) => {
|
|
1010
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
1011
|
+
trace.push({ operation: "steer", key, state: "failed", durationMs: Date.now() - startedAt, error: text });
|
|
1012
|
+
traceChanged();
|
|
1013
|
+
throw error;
|
|
1014
|
+
});
|
|
1015
|
+
steers.set(message.callId, { key, promise, observed: observedSteerCalls.delete(message.callId) });
|
|
1016
|
+
respond(promise);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
807
1019
|
if (message.method !== "run") return respond(Promise.reject(new Error(`Unknown runs API method '${message.method}'.`)));
|
|
808
1020
|
|
|
809
1021
|
let key: string;
|
|
@@ -831,9 +1043,13 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
831
1043
|
if (params.gate !== undefined && params.resume !== undefined) {
|
|
832
1044
|
return respond(Promise.reject(new Error(`runs.run('${key}') gate is not supported with retained resume.`)));
|
|
833
1045
|
}
|
|
834
|
-
|
|
835
|
-
|
|
1046
|
+
let resumeReference: WorkflowReceiptResumeReference | undefined;
|
|
1047
|
+
try {
|
|
1048
|
+
if (params.resume !== undefined && typeof params.resume !== "string") resumeReference = parseWorkflowResumeReference(params.resume);
|
|
1049
|
+
} catch (error) {
|
|
1050
|
+
return respond(Promise.reject(new Error(`runs.run('${key}') ${error instanceof Error ? error.message : String(error)}`)));
|
|
836
1051
|
}
|
|
1052
|
+
if (typeof params.resume === "string" && !params.resume.trim()) return respond(Promise.reject(new Error(`runs.run('${key}') resume must be a non-empty retained run id.`)));
|
|
837
1053
|
if (params.resume !== undefined && params.agent !== undefined) {
|
|
838
1054
|
return respond(Promise.reject(new Error(`runs.run('${key}') resume and agent are mutually exclusive.`)));
|
|
839
1055
|
}
|
|
@@ -859,7 +1075,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
859
1075
|
if (callObserved) existing.observed = true;
|
|
860
1076
|
trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params) });
|
|
861
1077
|
traceChanged();
|
|
862
|
-
return respond(deliver(existing.promise));
|
|
1078
|
+
return respond(deliver(existing.promise), `runs.run('${key}') result`);
|
|
863
1079
|
}
|
|
864
1080
|
|
|
865
1081
|
const startedAt = Date.now();
|
|
@@ -870,25 +1086,50 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
870
1086
|
if (!admission) {
|
|
871
1087
|
const seenKeys = new Set<string>();
|
|
872
1088
|
const calls = (batch?.calls ?? [{ key, params }]).filter((call) => {
|
|
873
|
-
if (seenKeys.has(call.key) || launches.has(call.key)
|
|
1089
|
+
if (seenKeys.has(call.key) || launches.has(call.key)) return false;
|
|
874
1090
|
seenKeys.add(call.key);
|
|
875
1091
|
return true;
|
|
876
1092
|
});
|
|
877
1093
|
admission = Promise.resolve().then(() => {
|
|
878
|
-
if (settled) return;
|
|
1094
|
+
if (settled || finishing) return;
|
|
879
1095
|
return options.admit?.(calls);
|
|
880
1096
|
});
|
|
881
1097
|
if (batch) batchAdmissions.set(batch.id, admission);
|
|
882
1098
|
}
|
|
883
|
-
|
|
884
|
-
|
|
1099
|
+
let resolvedResumeLineage: string[] | undefined;
|
|
1100
|
+
const promise = admission.then(async () => {
|
|
1101
|
+
if (settled || finishing || stoppedLaunches.has(key)) {
|
|
885
1102
|
const reason = childController.signal.reason;
|
|
886
1103
|
const text = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.";
|
|
887
1104
|
return { key, ok: false, output: text, error: text, artifactPaths: [] };
|
|
888
1105
|
}
|
|
889
|
-
|
|
1106
|
+
const resolvedResumeValue = resumeReference
|
|
1107
|
+
? await Promise.resolve().then(() => {
|
|
1108
|
+
if (!options.resolveResume) throw new Error("Keyed workflow receipt resume is unavailable in this host.");
|
|
1109
|
+
return options.resolveResume(resumeReference, childController.signal);
|
|
1110
|
+
})
|
|
1111
|
+
: undefined;
|
|
1112
|
+
const resolvedResume = typeof resolvedResumeValue === "string"
|
|
1113
|
+
? resolvedResumeValue
|
|
1114
|
+
: isRecord(resolvedResumeValue) && typeof resolvedResumeValue.runId === "string"
|
|
1115
|
+
? resolvedResumeValue.runId
|
|
1116
|
+
: undefined;
|
|
1117
|
+
if (resumeReference && (typeof resolvedResume !== "string" || !resolvedResume.trim())) throw new Error("Keyed workflow receipt resume resolved without a retained run id.");
|
|
1118
|
+
const resolvedResumeId = resolvedResume?.trim();
|
|
1119
|
+
if (isRecord(resolvedResumeValue)) {
|
|
1120
|
+
const lineage = Array.isArray(resolvedResumeValue.runIds)
|
|
1121
|
+
? resolvedResumeValue.runIds.filter((runId): runId is string => typeof runId === "string" && Boolean(runId.trim())).map((runId) => runId.trim())
|
|
1122
|
+
: [];
|
|
1123
|
+
resolvedResumeLineage = [...new Set(lineage.length ? lineage : [resolvedResumeId!])];
|
|
1124
|
+
if (resolvedResumeLineage.at(-1) !== resolvedResumeId) resolvedResumeLineage.push(resolvedResumeId!);
|
|
1125
|
+
}
|
|
1126
|
+
const launchParams = resolvedResumeId ? { ...params, resume: resolvedResumeId } : params;
|
|
1127
|
+
return options.launch(key, { ...launchParams, async: launchParams.async ?? false }, childController.signal, { admitted: true });
|
|
890
1128
|
}).then((result) => {
|
|
891
|
-
|
|
1129
|
+
let normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
|
|
1130
|
+
if (resolvedResumeLineage?.length && normalized.runId) {
|
|
1131
|
+
normalized = { ...normalized, continuation: { runIds: [...new Set([...resolvedResumeLineage, normalized.runId])] } };
|
|
1132
|
+
}
|
|
892
1133
|
if (stoppedLaunches.has(key)) return normalized;
|
|
893
1134
|
children.set(key, normalized);
|
|
894
1135
|
const state = normalized.ok ? "completed" : normalized.detached ? "detached" : "failed";
|
|
@@ -908,7 +1149,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
908
1149
|
childOrder.push(key);
|
|
909
1150
|
trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params) });
|
|
910
1151
|
traceChanged();
|
|
911
|
-
respond(deliver(promise));
|
|
1152
|
+
respond(deliver(promise), `runs.run('${key}') result`);
|
|
912
1153
|
});
|
|
913
1154
|
|
|
914
1155
|
worker.postMessage({ type: "start", script: options.script, stateEnabled: options.state !== undefined });
|