@xzzpig/pi-subagents 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,140 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import type { Details } from "../shared/types.ts";
5
+
6
+ export const WORKFLOW_CHAT_PROGRESS_MODES = ["auto", "off", "live-card"] as const;
7
+ export type WorkflowChatProgressMode = typeof WORKFLOW_CHAT_PROGRESS_MODES[number];
8
+ export type ResolvedWorkflowChatProgressMode = Exclude<WorkflowChatProgressMode, "auto">;
9
+
10
+ export interface GitRepositoryIdentity {
11
+ root: string;
12
+ commonDir: string;
13
+ }
14
+
15
+ export interface WorkflowChatProgressProjection {
16
+ mode: ResolvedWorkflowChatProgressMode;
17
+ repoRelation: "same" | "other";
18
+ repoLabel?: string;
19
+ }
20
+
21
+ interface ResolveWorkflowChatProgressInput {
22
+ requested: unknown;
23
+ parentCwd: string;
24
+ workflowCwd: string;
25
+ background: boolean;
26
+ }
27
+
28
+ function git(cwd: string, args: string[]): string | undefined {
29
+ const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8" });
30
+ if (result.status !== 0) return undefined;
31
+ const output = result.stdout.trim();
32
+ return output || undefined;
33
+ }
34
+
35
+ function realPath(value: string): string {
36
+ try {
37
+ return fs.realpathSync.native(value);
38
+ } catch {
39
+ return path.resolve(value);
40
+ }
41
+ }
42
+
43
+ export function resolveGitRepositoryIdentity(cwd: string): GitRepositoryIdentity | undefined {
44
+ if (git(cwd, ["rev-parse", "--is-inside-work-tree"]) !== "true") return undefined;
45
+ const root = git(cwd, ["rev-parse", "--show-toplevel"]);
46
+ const commonDir = git(cwd, ["rev-parse", "--git-common-dir"]);
47
+ if (!root || !commonDir) return undefined;
48
+ const commonDirPath = path.isAbsolute(commonDir)
49
+ ? commonDir
50
+ : [path.resolve(cwd, commonDir), path.resolve(root, commonDir)].find((candidate) => fs.existsSync(candidate)) ?? path.resolve(root, commonDir);
51
+ return {
52
+ root: realPath(root),
53
+ commonDir: realPath(commonDirPath),
54
+ };
55
+ }
56
+
57
+ function isSameGitRepositoryIdentity(left: GitRepositoryIdentity | undefined, right: GitRepositoryIdentity | undefined): boolean {
58
+ if (!left || !right) return false;
59
+ return left.commonDir === right.commonDir || left.root === right.root;
60
+ }
61
+
62
+ export function isSameGitRepository(leftCwd: string, rightCwd: string): boolean {
63
+ return isSameGitRepositoryIdentity(resolveGitRepositoryIdentity(leftCwd), resolveGitRepositoryIdentity(rightCwd));
64
+ }
65
+
66
+ function normalizeRequestedMode(value: unknown): { mode?: WorkflowChatProgressMode; error?: string } {
67
+ if (value === undefined) return { mode: "auto" };
68
+ if (typeof value !== "string" || !WORKFLOW_CHAT_PROGRESS_MODES.includes(value as WorkflowChatProgressMode)) {
69
+ return { error: `chatProgress must be one of: ${WORKFLOW_CHAT_PROGRESS_MODES.join(", ")}.` };
70
+ }
71
+ return { mode: value as WorkflowChatProgressMode };
72
+ }
73
+
74
+ export function resolveWorkflowChatProgress(input: ResolveWorkflowChatProgressInput): { projection?: WorkflowChatProgressProjection; error?: string } {
75
+ const requested = normalizeRequestedMode(input.requested);
76
+ if (requested.error) return { error: requested.error };
77
+ const parentIdentity = resolveGitRepositoryIdentity(input.parentCwd);
78
+ const workflowIdentity = resolveGitRepositoryIdentity(input.workflowCwd);
79
+ const sameRepo = !!(
80
+ parentIdentity
81
+ && workflowIdentity
82
+ && (parentIdentity.commonDir === workflowIdentity.commonDir || parentIdentity.root === workflowIdentity.root)
83
+ );
84
+ const repoLabel = workflowIdentity ? path.basename(workflowIdentity.root) : undefined;
85
+ const repoRelation = sameRepo ? "same" : "other";
86
+
87
+ const requestedMode = requested.mode ?? "auto";
88
+ let mode: ResolvedWorkflowChatProgressMode;
89
+ if (requestedMode === "auto") mode = sameRepo && !input.background ? "live-card" : "off";
90
+ else mode = requestedMode;
91
+
92
+ if (mode === "live-card" && !sameRepo) return { error: "chatProgress: 'live-card' is only available for workflowScript runs in the same Git repository." };
93
+ if (mode === "live-card" && input.background) return { error: "chatProgress: 'live-card' requires a watched foreground workflow; pass async:false." };
94
+ return { projection: { mode, repoRelation, ...(repoLabel ? { repoLabel } : {}) } };
95
+ }
96
+
97
+ export interface WorkflowChatProgressRow {
98
+ key: string;
99
+ state: "running" | "complete" | "failed";
100
+ label?: string;
101
+ phase?: string;
102
+ runId?: string;
103
+ durationMs?: number;
104
+ error?: string;
105
+ }
106
+
107
+ function cleanLabel(value: unknown): string | undefined {
108
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
109
+ }
110
+
111
+ export function buildWorkflowChatProgressRows(trace: NonNullable<Details["workflow"]>["trace"]): WorkflowChatProgressRow[] {
112
+ const rows = new Map<string, WorkflowChatProgressRow>();
113
+ for (const entry of trace) {
114
+ if (entry.operation !== "run") continue;
115
+ const existing = rows.get(entry.key);
116
+ if (entry.state === "reused") {
117
+ if (existing) {
118
+ const label = cleanLabel(entry.label);
119
+ const phase = cleanLabel(entry.phase);
120
+ if (label) existing.label = label;
121
+ if (phase) existing.phase = phase;
122
+ }
123
+ continue;
124
+ }
125
+ const next: WorkflowChatProgressRow = existing ?? { key: entry.key, state: "running" };
126
+ next.state = entry.state === "completed" ? "complete" : entry.state === "failed" ? "failed" : "running";
127
+ const label = cleanLabel(entry.label);
128
+ const phase = cleanLabel(entry.phase);
129
+ if (label) next.label = label;
130
+ if (phase) next.phase = phase;
131
+ if (entry.runId === undefined) delete next.runId;
132
+ else next.runId = entry.runId;
133
+ if (entry.durationMs === undefined) delete next.durationMs;
134
+ else next.durationMs = entry.durationMs;
135
+ if (entry.error === undefined) delete next.error;
136
+ else next.error = entry.error;
137
+ rows.set(entry.key, next);
138
+ }
139
+ return [...rows.values()];
140
+ }
@@ -0,0 +1,506 @@
1
+ import { Worker } from "node:worker_threads";
2
+
3
+ const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
4
+
5
+ const WORKER_SOURCE = String.raw`
6
+ const { parentPort } = require("node:worker_threads");
7
+ const vm = require("node:vm");
8
+ const { inspect } = require("node:util");
9
+
10
+ let nextCallId = 0;
11
+ const pending = new Map();
12
+ const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
13
+
14
+ function stableRunJson(value) {
15
+ if (Array.isArray(value)) return "[" + value.map(stableRunJson).join(",") + "]";
16
+ if (value && typeof value === "object") return "{" + Object.keys(value).sort().map((key) => JSON.stringify(key) + ":" + stableRunJson(value[key])).join(",") + "}";
17
+ return JSON.stringify(value) ?? "undefined";
18
+ }
19
+
20
+ function hostCall(method, args) {
21
+ return new Promise((resolve, reject) => {
22
+ const callId = ++nextCallId;
23
+ pending.set(callId, { resolve, reject });
24
+ parentPort.postMessage({ type: "call", callId, method, args });
25
+ });
26
+ }
27
+
28
+ function formatRef(result) {
29
+ if (!result || typeof result !== "object") throw new Error("runs.ref(result) requires a run result object.");
30
+ const parts = ["run " + (result.key || "unknown")];
31
+ if (result.runId) parts.push("id=" + String(result.runId).slice(0, 8));
32
+ return "[" + parts.join("; ") + "]";
33
+ }
34
+
35
+ const runFingerprints = new Map();
36
+
37
+ function validateRunCall(key, params, label, fingerprints) {
38
+ if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
39
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error(label + " requires a params object.");
40
+ 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")) {
41
+ const hint = label === "runs.run" ? "; use runs.all(...) and JavaScript control flow for orchestration." : ".";
42
+ throw new Error(label + " accepts one child via { agent, task } and execution controls only" + hint);
43
+ }
44
+ if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
45
+ if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) throw new Error(label + " gate must be a non-empty command string.");
46
+ if (params.gate !== undefined && params.acceptance !== undefined) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify.");
47
+ if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
48
+ if (params.resume !== undefined && (typeof params.resume !== "string" || !params.resume.trim())) throw new Error(label + " resume must be a non-empty retained run id.");
49
+ if (params.resume !== undefined && params.agent !== undefined) throw new Error(label + " resume and agent are mutually exclusive.");
50
+ if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) throw new Error(label + " resume requires a non-empty task follow-up.");
51
+ assertJsonValue(params, label + " params");
52
+ const fingerprint = stableRunJson(params);
53
+ const existing = fingerprints.get(key);
54
+ if (existing !== undefined && existing !== fingerprint) throw new Error("Duplicate workflow key '" + key + "' used with incompatible launch params.");
55
+ fingerprints.set(key, fingerprint);
56
+ }
57
+
58
+ const runs = Object.freeze({
59
+ run(key, params) {
60
+ validateRunCall(key, params, "runs.run", runFingerprints);
61
+ return hostCall("run", { key, params });
62
+ },
63
+ all(items) {
64
+ if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
65
+ const fingerprints = new Map(runFingerprints);
66
+ const calls = [];
67
+ for (let index = 0; index < items.length; index++) {
68
+ if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
69
+ const item = items[index];
70
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object.");
71
+ const { key, ...params } = item;
72
+ validateRunCall(key, params, "runs.all item " + index, fingerprints);
73
+ calls.push({ key, params });
74
+ }
75
+ for (const { key, params } of calls) runFingerprints.set(key, stableRunJson(params));
76
+ return Promise.all(calls.map(({ key, params }) => hostCall("run", { key, params, collectFailure: true })));
77
+ },
78
+ status(keyOrRunId) { return hostCall("status", { keyOrRunId }); },
79
+ ref: formatRef,
80
+ refs(results) {
81
+ if (!Array.isArray(results)) throw new Error("runs.refs(results) requires an array.");
82
+ return results.map(formatRef).join("\n");
83
+ },
84
+ });
85
+
86
+ function validateStateKey(key) {
87
+ if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error("state key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.");
88
+ return key;
89
+ }
90
+
91
+ const state = Object.freeze({
92
+ get(key) { return hostCall("state.get", { key: validateStateKey(key) }); },
93
+ set(key, value) {
94
+ const validKey = validateStateKey(key);
95
+ assertJsonValue(value, "state.set('" + validKey + "') value");
96
+ return hostCall("state.set", { key: validKey, value });
97
+ },
98
+ });
99
+
100
+ let contextObjectPrototype;
101
+
102
+ const capturedConsole = Object.freeze(Object.fromEntries(
103
+ ["log", "info", "warn", "error"].map((level) => [level, (...args) => {
104
+ parentPort.postMessage({ type: "console", level, text: args.map((value) => typeof value === "string" ? value : inspect(value, { depth: 4, breakLength: 120 })).join(" ") });
105
+ }]),
106
+ ));
107
+
108
+ function assertJsonValue(value, path = "emit", seen = new Set()) {
109
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
110
+ if (typeof value === "number") {
111
+ if (!Number.isFinite(value)) throw new Error(path + " must contain only finite JSON numbers.");
112
+ return;
113
+ }
114
+ if (typeof value !== "object") throw new Error(path + " must be a JSON value; received " + typeof value + ".");
115
+ if (seen.has(value)) throw new Error(path + " must not contain cycles.");
116
+ seen.add(value);
117
+ if (Array.isArray(value)) {
118
+ for (let index = 0; index < value.length; index++) {
119
+ if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(path + " must not contain sparse array entries.");
120
+ assertJsonValue(value[index], path + "[" + index + "]", seen);
121
+ }
122
+ } else {
123
+ const prototype = Object.getPrototypeOf(value);
124
+ if (prototype !== null && prototype !== Object.prototype && prototype !== contextObjectPrototype) throw new Error(path + " must contain only plain JSON objects.");
125
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(path + " must not contain symbol keys.");
126
+ for (const [key, entry] of Object.entries(value)) assertJsonValue(entry, path + "." + key, seen);
127
+ }
128
+ seen.delete(value);
129
+ }
130
+
131
+ parentPort.on("message", async (message) => {
132
+ if (message.type === "response") {
133
+ const entry = pending.get(message.callId);
134
+ if (!entry) return;
135
+ pending.delete(message.callId);
136
+ if (message.ok) entry.resolve(message.value);
137
+ else entry.reject(new Error(message.error));
138
+ return;
139
+ }
140
+ if (message.type !== "start") return;
141
+ try {
142
+ const sandbox = { runs, emit(value) { assertJsonValue(value); parentPort.postMessage({ type: "emit", value }); }, console: capturedConsole };
143
+ if (message.stateEnabled) sandbox.state = state;
144
+ const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
145
+ contextObjectPrototype = vm.runInContext("Object.prototype", context);
146
+ const compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js" });
147
+ const value = await compiled.runInContext(context);
148
+ const persistedValue = value === undefined ? null : value;
149
+ assertJsonValue(persistedValue, "return");
150
+ parentPort.postMessage({ type: "complete", value: persistedValue });
151
+ } catch (error) {
152
+ parentPort.postMessage({ type: "error", error: error && error.stack ? error.stack : String(error) });
153
+ }
154
+ });
155
+ `;
156
+
157
+ export interface WorkflowScriptChildResult {
158
+ key: string;
159
+ ok: boolean;
160
+ runId?: string;
161
+ output: string;
162
+ error?: string;
163
+ structuredOutput?: unknown;
164
+ artifactPaths: string[];
165
+ results?: unknown[];
166
+ }
167
+
168
+ export interface WorkflowScriptTraceEntry {
169
+ operation: "run" | "status";
170
+ key: string;
171
+ state: "started" | "completed" | "failed" | "reused";
172
+ runId?: string;
173
+ durationMs?: number;
174
+ phase?: string;
175
+ label?: string;
176
+ error?: string;
177
+ }
178
+
179
+ export interface WorkflowScriptResult {
180
+ value: unknown;
181
+ emits: unknown[];
182
+ console: Array<{ level: "log" | "info" | "warn" | "error"; text: string }>;
183
+ trace: WorkflowScriptTraceEntry[];
184
+ children: WorkflowScriptChildResult[];
185
+ }
186
+
187
+ export class WorkflowScriptError extends Error {
188
+ readonly partial: Omit<WorkflowScriptResult, "value">;
189
+
190
+ constructor(message: string, partial: Omit<WorkflowScriptResult, "value">) {
191
+ super(message);
192
+ this.name = "WorkflowScriptError";
193
+ this.partial = partial;
194
+ }
195
+ }
196
+
197
+ export interface RunWorkflowScriptOptions {
198
+ script: string;
199
+ timeoutMs?: number;
200
+ signal?: AbortSignal;
201
+ launch: (key: string, params: Record<string, unknown>, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
202
+ status: (keyOrRunId: string, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
203
+ state?: {
204
+ get: (key: string) => unknown | Promise<unknown>;
205
+ set: (key: string, value: unknown) => void | Promise<void>;
206
+ };
207
+ onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
208
+ onEmit?: (emits: unknown[]) => void;
209
+ }
210
+
211
+ function isRecord(value: unknown): value is Record<string, unknown> {
212
+ return !!value && typeof value === "object" && !Array.isArray(value);
213
+ }
214
+
215
+ function isPlainJsonObject(value: unknown): value is Record<string, unknown> {
216
+ if (!isRecord(value)) return false;
217
+ const prototype = Object.getPrototypeOf(value);
218
+ return prototype === null || prototype === Object.prototype;
219
+ }
220
+
221
+ function omitUndefinedWorkflowValues(value: unknown, seen = new Set<object>()): unknown {
222
+ if (value === null || typeof value !== "object") return value;
223
+ if (seen.has(value)) return value;
224
+ seen.add(value);
225
+ const normalized = Array.isArray(value)
226
+ ? value.map((entry) => entry === undefined ? null : omitUndefinedWorkflowValues(entry, seen))
227
+ : isPlainJsonObject(value)
228
+ ? Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => entry === undefined ? [] : [[key, omitUndefinedWorkflowValues(entry, seen)]]))
229
+ : value;
230
+ seen.delete(value);
231
+ return normalized;
232
+ }
233
+
234
+ export function assertWorkflowJsonValue(value: unknown, path = "value", seen = new Set<object>()): void {
235
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
236
+ if (typeof value === "number") {
237
+ if (!Number.isFinite(value)) throw new Error(`${path} must contain only finite JSON numbers.`);
238
+ return;
239
+ }
240
+ if (typeof value !== "object") throw new Error(`${path} must be a JSON value; received ${typeof value}.`);
241
+ if (seen.has(value)) throw new Error(`${path} must not contain cycles.`);
242
+ seen.add(value);
243
+ if (Array.isArray(value)) {
244
+ for (let index = 0; index < value.length; index++) {
245
+ if (!Object.hasOwn(value, index)) throw new Error(`${path} must not contain sparse array entries.`);
246
+ assertWorkflowJsonValue(value[index], `${path}[${index}]`, seen);
247
+ }
248
+ } else {
249
+ const prototype = Object.getPrototypeOf(value);
250
+ if (prototype !== null && prototype !== Object.prototype) throw new Error(`${path} must contain only plain JSON objects.`);
251
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path} must not contain symbol keys.`);
252
+ for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${path}.${key}`, seen);
253
+ }
254
+ seen.delete(value);
255
+ }
256
+
257
+ export function formatWorkflowJsonPreview(value: unknown, maxLength: number): string | undefined {
258
+ try {
259
+ assertWorkflowJsonValue(value);
260
+ const serialized = JSON.stringify(value);
261
+ return typeof serialized === "string" ? serialized.slice(0, maxLength) : undefined;
262
+ } catch {
263
+ return undefined;
264
+ }
265
+ }
266
+
267
+ export interface SimpleWorkflowRunPreview {
268
+ agent?: string;
269
+ task?: string;
270
+ }
271
+
272
+ /** Display-only preview for the exact simple `return runs.run(key, {...})` form. */
273
+ export function previewSimpleWorkflowRun(script: string | undefined): SimpleWorkflowRunPreview | undefined {
274
+ const body = script?.match(/^\s*return\s+(?:await\s+)?runs\.run\s*\(\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`$\\]*`)\s*,\s*\{([\s\S]*)\}\s*\)\s*;?\s*$/)?.[1];
275
+ if (body === undefined) return undefined;
276
+ const readProperty = (name: "agent" | "task"): string | undefined => {
277
+ const match = body.match(new RegExp(`(?:^|,)\\s*(?:${name}|["']${name}["'])\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\u0060[^\u0060$\\\\]*\u0060)`));
278
+ if (!match?.[1]) return undefined;
279
+ const literal = match[1];
280
+ if (literal.startsWith('"')) {
281
+ try { return JSON.parse(literal) as string; } catch { return undefined; }
282
+ }
283
+ if (literal.slice(1, -1).includes("\\")) return undefined;
284
+ return literal.slice(1, -1);
285
+ };
286
+ const agent = readProperty("agent");
287
+ const task = readProperty("task");
288
+ return { ...(agent !== undefined ? { agent } : {}), ...(task !== undefined ? { task } : {}) };
289
+ }
290
+
291
+ function stableJson(value: unknown): string {
292
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
293
+ if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
294
+ return JSON.stringify(value) ?? "undefined";
295
+ }
296
+
297
+ function validateKey(value: unknown, owner = "runs.run"): string {
298
+ if (typeof value !== "string" || !KEY_PATTERN.test(value)) {
299
+ throw new Error(`${owner} key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.`);
300
+ }
301
+ return value;
302
+ }
303
+
304
+ function workflowStringMetadata(params: Record<string, unknown>): Pick<WorkflowScriptTraceEntry, "phase" | "label"> {
305
+ return {
306
+ ...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
307
+ ...(typeof params.label === "string" && params.label.trim() ? { label: params.label.trim() } : {}),
308
+ };
309
+ }
310
+
311
+ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
312
+ if (!options.script.trim()) throw new Error("workflowScript must not be empty.");
313
+ if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) throw new Error("workflow script timeout must be a positive integer.");
314
+
315
+ const worker = new Worker(WORKER_SOURCE, { eval: true });
316
+ const emits: unknown[] = [];
317
+ const consoleEntries: WorkflowScriptResult["console"] = [];
318
+ const trace: WorkflowScriptTraceEntry[] = [];
319
+ const children = new Map<string, WorkflowScriptChildResult>();
320
+ const childOrder: string[] = [];
321
+ const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult> }>();
322
+ const childController = new AbortController();
323
+ let settled = false;
324
+
325
+ const partial = (): Omit<WorkflowScriptResult, "value"> => ({ emits, console: consoleEntries, trace, children: childOrder.flatMap((key) => {
326
+ const child = children.get(key);
327
+ return child ? [child] : [];
328
+ }) });
329
+ const traceChanged = () => options.onTrace?.([...trace]);
330
+
331
+ return await new Promise<WorkflowScriptResult>((resolve, reject) => {
332
+ const finish = (outcome: { value: unknown } | { error: Error }) => {
333
+ if (settled) return;
334
+ settled = true;
335
+ if (timer) clearTimeout(timer);
336
+ options.signal?.removeEventListener("abort", onAbort);
337
+ void worker.terminate();
338
+ childController.abort("error" in outcome ? outcome.error : new Error("Workflow script completed; unawaited child launches are aborted."));
339
+ if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial()));
340
+ else resolve({ value: outcome.value, ...partial() });
341
+ };
342
+ const onAbort = () => finish({ error: new Error("Workflow script aborted.") });
343
+ const timer = options.timeoutMs === undefined
344
+ ? undefined
345
+ : setTimeout(() => finish({ error: new Error(`Workflow script timed out after ${options.timeoutMs}ms.`) }), options.timeoutMs);
346
+ options.signal?.addEventListener("abort", onAbort, { once: true });
347
+ if (options.signal?.aborted) return onAbort();
348
+
349
+ worker.on("error", (error) => finish({ error: new Error(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`) }));
350
+ worker.on("exit", (code) => {
351
+ if (!settled && code !== 0) finish({ error: new Error(`Workflow worker exited with code ${code}.`) });
352
+ });
353
+ worker.on("message", (message: Record<string, unknown>) => {
354
+ if (message.type === "emit") {
355
+ try {
356
+ assertWorkflowJsonValue(message.value, "emit");
357
+ } catch (error) {
358
+ finish({ error: new Error(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
359
+ return;
360
+ }
361
+ emits.push(message.value);
362
+ try {
363
+ options.onEmit?.([...emits]);
364
+ } catch (error) {
365
+ emits.pop();
366
+ finish({ error: new Error(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
367
+ }
368
+ return;
369
+ }
370
+ if (message.type === "console") {
371
+ const level = message.level;
372
+ if ((level === "log" || level === "info" || level === "warn" || level === "error") && typeof message.text === "string") consoleEntries.push({ level, text: message.text });
373
+ return;
374
+ }
375
+ if (message.type === "complete") {
376
+ try {
377
+ assertWorkflowJsonValue(message.value, "return");
378
+ } catch (error) {
379
+ return finish({ error: new Error(`Workflow return could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
380
+ }
381
+ return finish({ value: message.value });
382
+ }
383
+ if (message.type === "error") return finish({ error: new Error(typeof message.error === "string" ? message.error : "Workflow script failed.") });
384
+ if (message.type !== "call" || typeof message.callId !== "number" || typeof message.method !== "string" || !isRecord(message.args)) return;
385
+
386
+ const respond = (promise: Promise<unknown>) => {
387
+ void promise.then(
388
+ (value) => {
389
+ if (!settled) worker.postMessage({ type: "response", callId: message.callId, ok: true, value: omitUndefinedWorkflowValues(value) });
390
+ },
391
+ (error: unknown) => {
392
+ if (!settled) worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error) });
393
+ },
394
+ );
395
+ };
396
+
397
+ if (message.method === "state.get" || message.method === "state.set") {
398
+ if (!options.state) return respond(Promise.reject(new Error("Workflow state is unavailable without a mission.")));
399
+ let key: string;
400
+ try {
401
+ key = validateKey(message.args.key, "state");
402
+ } catch (error) {
403
+ return respond(Promise.reject(error));
404
+ }
405
+ if (message.method === "state.get") return respond(Promise.resolve().then(() => options.state!.get(key)));
406
+ const value = message.args.value;
407
+ try {
408
+ assertWorkflowJsonValue(value, `state.set('${key}') value`);
409
+ } catch (error) {
410
+ return respond(Promise.reject(error));
411
+ }
412
+ return respond(Promise.resolve().then(() => options.state!.set(key, value)));
413
+ }
414
+
415
+ if (message.method === "status") {
416
+ const keyOrRunId = message.args.keyOrRunId;
417
+ if (typeof keyOrRunId !== "string" || !keyOrRunId.trim()) return respond(Promise.reject(new Error("runs.status(keyOrRunId) requires a non-empty string.")));
418
+ const known = children.get(keyOrRunId);
419
+ const target = known?.runId ?? keyOrRunId;
420
+ trace.push({ operation: "status", key: keyOrRunId, state: "started", ...(known?.runId ? { runId: known.runId } : {}) });
421
+ traceChanged();
422
+ respond(options.status(target, childController.signal).then((result) => {
423
+ trace.push({ operation: "status", key: keyOrRunId, state: result.ok ? "completed" : "failed", ...(result.runId ? { runId: result.runId } : {}), ...(!result.ok ? { error: result.output } : {}) });
424
+ traceChanged();
425
+ if (!result.ok) throw new Error(`Status '${keyOrRunId}' failed: ${result.output}`);
426
+ return result;
427
+ }));
428
+ return;
429
+ }
430
+ if (message.method !== "run") return respond(Promise.reject(new Error(`Unknown runs API method '${message.method}'.`)));
431
+
432
+ let key: string;
433
+ try {
434
+ key = validateKey(message.args.key);
435
+ } catch (error) {
436
+ return respond(Promise.reject(error));
437
+ }
438
+ const params = message.args.params;
439
+ if (!isRecord(params)) return respond(Promise.reject(new Error(`runs.run('${key}', params) requires a params object.`)));
440
+ if (params.action !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') accepts execution params only; management action is not allowed.`)));
441
+ if (params.workflowScript !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') cannot start a nested workflow script.`)));
442
+ if (params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.concurrency !== undefined || params.chainDir !== undefined) {
443
+ return respond(Promise.reject(new Error(`runs.run('${key}') accepts one child via { agent, task }; use runs.all(...) and JavaScript control flow for orchestration.`)));
444
+ }
445
+ if (params.worktree !== undefined && typeof params.worktree !== "boolean") {
446
+ return respond(Promise.reject(new Error(`runs.run('${key}') worktree must be true or false.`)));
447
+ }
448
+ if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) {
449
+ return respond(Promise.reject(new Error(`runs.run('${key}') gate must be a non-empty command string.`)));
450
+ }
451
+ if (params.gate !== undefined && params.acceptance !== undefined) {
452
+ return respond(Promise.reject(new Error(`runs.run('${key}') gate cannot be combined with acceptance; use one gate command or acceptance.verify.`)));
453
+ }
454
+ if (params.gate !== undefined && params.resume !== undefined) {
455
+ return respond(Promise.reject(new Error(`runs.run('${key}') gate is not supported with retained resume.`)));
456
+ }
457
+ if (params.resume !== undefined && (typeof params.resume !== "string" || !params.resume.trim())) {
458
+ return respond(Promise.reject(new Error(`runs.run('${key}') resume must be a non-empty retained run id.`)));
459
+ }
460
+ if (params.resume !== undefined && params.agent !== undefined) {
461
+ return respond(Promise.reject(new Error(`runs.run('${key}') resume and agent are mutually exclusive.`)));
462
+ }
463
+ if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) {
464
+ return respond(Promise.reject(new Error(`runs.run('${key}') resume requires a non-empty task follow-up.`)));
465
+ }
466
+ const collectFailure = message.args.collectFailure === true;
467
+ const deliver = (promise: Promise<WorkflowScriptChildResult>) => collectFailure
468
+ ? promise
469
+ : promise.then((result) => {
470
+ if (!result.ok) throw new Error(`Run '${key}' failed: ${result.error ?? result.output}`);
471
+ return result;
472
+ });
473
+ const fingerprint = stableJson(params);
474
+ const existing = launches.get(key);
475
+ if (existing) {
476
+ if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
477
+ trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params) });
478
+ traceChanged();
479
+ return respond(deliver(existing.promise));
480
+ }
481
+
482
+ const startedAt = Date.now();
483
+ childOrder.push(key);
484
+ trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params) });
485
+ traceChanged();
486
+ const promise = Promise.resolve().then(() => options.launch(key, { ...params, async: params.async ?? false }, childController.signal)).then((result) => {
487
+ const normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
488
+ children.set(key, normalized);
489
+ trace.push({ operation: "run", key, state: normalized.ok ? "completed" : "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok ? { error: normalized.error ?? normalized.output } : {}) });
490
+ traceChanged();
491
+ return normalized;
492
+ }, (error: unknown) => {
493
+ const text = error instanceof Error ? error.message : String(error);
494
+ const failure: WorkflowScriptChildResult = { key, ok: false, output: text, error: text, artifactPaths: [] };
495
+ children.set(key, failure);
496
+ trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), error: text });
497
+ traceChanged();
498
+ return failure;
499
+ });
500
+ launches.set(key, { fingerprint, promise });
501
+ respond(deliver(promise));
502
+ });
503
+
504
+ worker.postMessage({ type: "start", script: options.script, stateEnabled: options.state !== undefined });
505
+ });
506
+ }