pi-suite 0.0.0-stage → 0.3.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,646 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/runtime.ts (MIT).
2
+ import { Worker } from "node:worker_threads";
3
+ import { WORKFLOW_AGENT_CAP, WORKFLOW_ITEM_CAP, WORKFLOW_NESTED_CAP, workflowConcurrency, type RunWorkflowOptions, type WorkflowRunResult, type WorkflowSpawnResult, type WorkflowScriptSource, type WorkflowScriptRef } from "./types.ts";
4
+ import { assertBoundarySafe, validateScript, Semaphore, preview, derivedLabel, applySchema, applyGate, unawaitedLaunchMessage, type AgentCallPayload, type WorkerMessage, type CompletedChild } from "./helpers.ts";
5
+ import { journalKey, type JournalKeyInput, type WorkflowJournalEntry } from "../journal.ts";
6
+ import { compileJsonSchema, type CompiledSchema } from "../../output/schema.ts";
7
+ import type { WorkflowAgentEntry, WorkflowEntry } from "../progress/index.ts";
8
+ import { WORKER_SOURCE } from "../worker/index.ts";
9
+
10
+ /** Invalid input rejects before launch; a live run resolves with its progress and terminal status. */
11
+ export async function runWorkflow(options: RunWorkflowOptions): Promise<WorkflowRunResult> {
12
+ const { script, host } = options;
13
+
14
+ assertBoundarySafe(options.args, "args");
15
+
16
+ const { meta, body } = validateScript(script);
17
+ options.onMeta?.(meta);
18
+ const agentCap = options.agentCap ?? WORKFLOW_AGENT_CAP;
19
+ const itemCap = options.itemCap ?? WORKFLOW_ITEM_CAP;
20
+ const semaphore = new Semaphore(options.concurrency ?? workflowConcurrency());
21
+
22
+ const progress: WorkflowEntry[] = [];
23
+ const inflight = new Set<string>();
24
+ /** Label → the child that ran under it, last one wins. The `resume` handle. */
25
+ const completedByLabel = new Map<string, CompletedChild>();
26
+ /**
27
+ * Launches the host has accepted and not yet answered, in call order.
28
+ *
29
+ * This is the whole unawaited-launch mechanism: a script that drops an
30
+ * `agent()` promise still gets its call answered eventually, but it returns
31
+ * first — so anything left here when `complete` arrives is a result nobody is
32
+ * waiting for. Tracking it host-side avoids proxying `Promise` inside the
33
+ * realm, which §2.4 rules out, and reading stack traces, which is brittle.
34
+ */
35
+ const openLaunches = new Map<number, string>();
36
+ let agentCount = 0;
37
+ let aborted = false;
38
+ let settled = false;
39
+
40
+ /* --- resume state ---------------------------------------------------- */
41
+
42
+ const journalEntries = options.journal?.entries ?? [];
43
+ const recordJournal = options.journal?.append;
44
+ /**
45
+ * Whether the replayable prefix is still intact.
46
+ *
47
+ * Once a position misses — different key, a journaled failure, or nothing
48
+ * recorded there — every later call runs live, however well it matches.
49
+ * See the header of journal.ts for why this is a prefix and not a lookup.
50
+ */
51
+ // A journal from a run that used `agent({ resume })` is declined whole: see
52
+ // journal.ts on why a replayed agent leaves nothing for a later resume to
53
+ // continue. Declining up front beats stranding the first `resume` call
54
+ // partway through a run that has already spent its cheap half.
55
+ const journalResumes = journalEntries.some(entry => entry.resumed);
56
+ let prefixIntact = journalEntries.length > 0 && !journalResumes;
57
+ let replayedCount = 0;
58
+
59
+ /* --- live control ---------------------------------------------------- */
60
+
61
+ /**
62
+ * Agents that still have an unanswered `agent()` call, by index.
63
+ *
64
+ * The window in which skip and retry mean anything: before the entry appears
65
+ * there is nothing to act on, and after it is gone the script already has its
66
+ * value. `started` is what separates the two — a retry needs a child to stop.
67
+ */
68
+ interface LiveAgent {
69
+ agentId: string;
70
+ started: boolean;
71
+ intent?: "skip" | "retry";
72
+ /** Wakes it out of a pause hold, so a skip does not wait for a resume. */
73
+ wake?: () => void;
74
+ }
75
+ const liveAgents = new Map<number, LiveAgent>();
76
+
77
+ /**
78
+ * Output tokens this run has spent, mirrored to the script as
79
+ * `budget.spent()`.
80
+ *
81
+ * The host owns the number and every response carries it, rather than the
82
+ * worker accumulating its own: two counters would drift, and there is nothing
83
+ * to gain from the second one. Nor is there observable staleness — tokens
84
+ * only accrue through agents, and the script only learns anything through
85
+ * agent responses.
86
+ */
87
+ let spentOutputTokens = 0;
88
+
89
+ let paused = false;
90
+ /** Read through a call for the same reason `intent()` is — see below. */
91
+ const isPaused = () => paused;
92
+ const pauseWaiters = new Set<() => void>();
93
+ /** Release everyone held at a pause — on resume, and on the way out. */
94
+ function releasePause(): void {
95
+ for (const wake of [...pauseWaiters]) wake();
96
+ pauseWaiters.clear();
97
+ }
98
+ /** Park here while the run is paused, so no new agent is started. */
99
+ function pauseGate(live: LiveAgent): Promise<void> {
100
+ if (!paused || aborted || settled) return Promise.resolve();
101
+ return new Promise<void>(resolve => {
102
+ const wake = () => {
103
+ pauseWaiters.delete(wake);
104
+ live.wake = undefined;
105
+ resolve();
106
+ };
107
+ live.wake = wake;
108
+ pauseWaiters.add(wake);
109
+ });
110
+ }
111
+
112
+ options.onControl?.({
113
+ pause: () => { paused = true; },
114
+ resume: () => { paused = false; releasePause(); },
115
+ isPaused: () => paused,
116
+ skip: index => {
117
+ const live = liveAgents.get(index);
118
+ if (live === undefined || live.intent !== undefined) return false;
119
+ live.intent = "skip";
120
+ // A running child is stopped, which comes back as a skipped result; a
121
+ // held one is woken so it can bail at the gate it is parked on.
122
+ if (live.started) host.abortAgent(live.agentId);
123
+ else live.wake?.();
124
+ return true;
125
+ },
126
+ retry: index => {
127
+ const live = liveAgents.get(index);
128
+ if (live === undefined || !live.started || live.intent !== undefined) return false;
129
+ live.intent = "retry";
130
+ host.abortAgent(live.agentId);
131
+ return true;
132
+ },
133
+ });
134
+
135
+ /** The journal entry to reuse at `index`, or undefined to run it live. */
136
+ function replayAt(index: number, key: string): WorkflowJournalEntry | undefined {
137
+ if (!prefixIntact) return undefined;
138
+ const entry = journalEntries[index];
139
+ if (entry === undefined || entry.index !== index || entry.key !== key || !entry.ok) {
140
+ prefixIntact = false;
141
+ return undefined;
142
+ }
143
+ return entry;
144
+ }
145
+
146
+ const worker = new Worker(WORKER_SOURCE, {
147
+ eval: true,
148
+ workerData: {
149
+ body,
150
+ metaJson: JSON.stringify(meta),
151
+ argsJson: options.args === undefined ? undefined : JSON.stringify(options.args),
152
+ itemCap,
153
+ nestedCap: options.nestedCap ?? WORKFLOW_NESTED_CAP,
154
+ },
155
+ });
156
+
157
+ return await new Promise<WorkflowRunResult>(resolve => {
158
+ const emit = (entries: WorkflowEntry[]) => {
159
+ if (entries.length === 0) return;
160
+ progress.push(...entries);
161
+ options.onProgress?.(entries);
162
+ };
163
+
164
+ const respond = (callId: number, ok: boolean, value?: unknown, error?: string, fatal?: boolean, structured = false) => {
165
+ // Cleared before the settled check: a launch answered by a run that is
166
+ // already finishing is not an unawaited launch either.
167
+ openLaunches.delete(callId);
168
+ if (settled) return;
169
+ // `spent` rides on every response, so the worker's `budget.spent()` is a
170
+ // mirror of this number rather than a second tally of its own.
171
+ worker.postMessage({ type: "response", callId, ok, value, error, fatal, structured, spent: spentOutputTokens });
172
+ };
173
+
174
+ const finish = (result: Omit<WorkflowRunResult, "meta" | "progress" | "agentCount" | "replayedCount">) => {
175
+ if (settled) return;
176
+ settled = true;
177
+ options.signal?.removeEventListener("abort", onAbort);
178
+ // Symmetric with `semaphore.drain()` below: everything parked is woken so
179
+ // it observes the settle and unwinds. Nothing depends on it — the run's
180
+ // promise resolves either way — it just does not leave live-agent
181
+ // bookkeeping behind for a run that is over.
182
+ releasePause();
183
+ for (const agentId of inflight) host.abortAgent(agentId);
184
+ inflight.clear();
185
+ semaphore.drain();
186
+ // Resolve only once the thread is actually down, so a caller that awaits
187
+ // runWorkflow() is guaranteed not to be leaking one.
188
+ const settle = () => resolve({ ...result, meta, progress, agentCount, replayedCount });
189
+ void worker.terminate().then(settle, error => resolve({ ...result, status: "failed", error: `Workflow worker shutdown failed: ${String(error)}`, meta, progress, agentCount, replayedCount }));
190
+ };
191
+
192
+ function onAbort() {
193
+ aborted = true;
194
+ // terminate() is why this runs in a worker at all: it stops a script that
195
+ // is spinning or wedged mid-await, which an in-process vm cannot do.
196
+ finish({ status: "killed", error: "Workflow aborted." });
197
+ }
198
+
199
+ if (options.signal) {
200
+ if (options.signal.aborted) {
201
+ onAbort();
202
+ return;
203
+ }
204
+ options.signal.addEventListener("abort", onAbort, { once: true });
205
+ }
206
+
207
+ async function handleAgent(callId: number, payload: AgentCallPayload): Promise<void> {
208
+ // Bound now: the optional methods are checked once, up front, so a
209
+ // capability the host lacks fails before an agent is spawned rather than
210
+ // after — a gate that never ran must not be mistaken for a gate that
211
+ // passed.
212
+ const runGate = host.runGate?.bind(host);
213
+ const resumeAgent = host.resumeAgent?.bind(host);
214
+ if (payload.gate !== undefined && runGate === undefined) {
215
+ respond(callId, false, undefined, "This workflow host cannot run gate commands.", true);
216
+ return;
217
+ }
218
+ if (payload.resume !== undefined && resumeAgent === undefined) {
219
+ respond(callId, false, undefined, "This workflow host cannot resume agents.", true);
220
+ return;
221
+ }
222
+
223
+ let resumed: CompletedChild | undefined;
224
+ if (payload.resume !== undefined) {
225
+ resumed = completedByLabel.get(payload.resume);
226
+ if (resumed === undefined) {
227
+ const known = [...completedByLabel.keys()];
228
+ // Fatal: a typo'd label is a script bug, and folding it into a null
229
+ // would show up as an agent that mysteriously returned nothing.
230
+ //
231
+ // Unless agents were replayed, in which case it is not a script bug
232
+ // at all — the label's child came back from the journal and has no
233
+ // conversation here to continue. Saying "no agent has completed"
234
+ // would send the reader hunting for a typo that is not there.
235
+ respond(
236
+ callId,
237
+ false,
238
+ undefined,
239
+ replayedCount > 0 ?
240
+ `agent() opts.resume: "${payload.resume}" was replayed from the resume journal, not run, so there is ` +
241
+ "no conversation in this run to continue. Re-run without resumeFromRunId."
242
+ : `agent() opts.resume: no agent has completed under the label "${payload.resume}" in this run. ${
243
+ known.length === 0
244
+ ? "No agent has completed yet."
245
+ : `Known labels: ${known.map(label => `"${label}"`).join(", ")}.`
246
+ }`,
247
+ true,
248
+ );
249
+ return;
250
+ }
251
+ }
252
+
253
+ // Compiled before anything is scheduled. A schema the runtime cannot use
254
+ // is a script bug, so it is fatal like a typo'd resume label — folding it
255
+ // into a null would surface as an agent that mysteriously returned
256
+ // nothing, and it costs no model call to say so here.
257
+ let compiledSchema: CompiledSchema | undefined = resumed?.schema;
258
+ if (payload.schema !== undefined) {
259
+ const compilation = compileJsonSchema(payload.schema);
260
+ if (!compilation.ok) {
261
+ respond(callId, false, undefined, compilation.message, true);
262
+ return;
263
+ }
264
+ compiledSchema = compilation.compiled;
265
+ }
266
+
267
+ if (agentCount >= agentCap) {
268
+ // Fatal, so parallel()/pipeline() rethrow instead of folding it into a
269
+ // null. A cap that silently drops work is worse than no cap.
270
+ respond(callId, false, undefined, `Workflow exceeded its cap of ${agentCap} agents.`, true);
271
+ return;
272
+ }
273
+ const index = agentCount++;
274
+ // A resumed call is the same child again: it keeps the agent id, so an
275
+ // abort still reaches it, and it keeps its spawn contract, so the row
276
+ // reads the same as the row it continues.
277
+ const agentId = resumed?.agentId ?? `wf-agent-${index}`;
278
+ const label = payload.label ?? resumed?.label ?? derivedLabel(payload.prompt);
279
+ const agentType = resumed?.agentType ?? payload.agentType ?? "general-purpose";
280
+ const model = resumed !== undefined ? resumed.model : payload.model;
281
+ openLaunches.set(callId, label);
282
+
283
+ const base: WorkflowAgentEntry = {
284
+ type: "workflow_agent",
285
+ index,
286
+ label,
287
+ state: "start",
288
+ agentId,
289
+ agentType,
290
+ promptPreview: preview(payload.prompt),
291
+ ...(model !== undefined ? { model } : {}),
292
+ ...(payload.phaseIndex !== undefined ? { phaseIndex: payload.phaseIndex } : {}),
293
+ ...(payload.phaseTitle !== undefined ? { phaseTitle: payload.phaseTitle } : {}),
294
+ };
295
+
296
+ const queuedAt = Date.now();
297
+ emit([{ ...base, queuedAt }]);
298
+
299
+ // Replay before the semaphore, not after: a cached answer is not model
300
+ // running, so it must not hold a concurrency slot that a live agent
301
+ // could use. The row still appears in the tree — the run reads as the
302
+ // same shape it had the first time, just faster.
303
+ // The payload's `schema` is the raw object; the key wants it serialized,
304
+ // so the spread is narrowed rather than passed through.
305
+ const keyInput: JournalKeyInput = {
306
+ ...payload,
307
+ schema: payload.schema !== undefined ? JSON.stringify(payload.schema) : undefined,
308
+ };
309
+ let replayed = replayAt(index, journalKey(keyInput));
310
+ // A replayed answer still has to satisfy the schema. The key covers a
311
+ // schema that *changed*, but not a journal that was hand-edited, and not
312
+ // the empty text a torn entry leaves behind — either would hand the
313
+ // script a null from an entry the journal claims succeeded.
314
+ if (replayed !== undefined && compiledSchema !== undefined) {
315
+ const recheck = applySchema({ ok: true, text: replayed.text ?? "" }, compiledSchema);
316
+ if (!recheck.ok) {
317
+ prefixIntact = false;
318
+ replayed = undefined;
319
+ }
320
+ }
321
+ if (replayed !== undefined) {
322
+ replayedCount++;
323
+ const replayedText = replayed.text ?? "";
324
+ const at = Date.now();
325
+ emit([
326
+ {
327
+ ...base,
328
+ queuedAt,
329
+ startedAt: at,
330
+ lastProgressAt: at,
331
+ durationMs: 0,
332
+ state: "done",
333
+ // The row reads as done, because it is — `cached` is what tells the
334
+ // dialog to annotate it "from resume journal" rather than letting a
335
+ // 0ms agent look like one that did the work impossibly fast.
336
+ cached: true,
337
+ resultPreview: preview(replayedText),
338
+ },
339
+ ]);
340
+ openLaunches.delete(callId);
341
+ // Re-recorded so this run's journal is complete on its own terms: a
342
+ // resume of a resume must not have to walk back through a chain of
343
+ // earlier files to find the prefix.
344
+ recordJournal?.({ index, key: replayed.key, ok: true, text: replayedText });
345
+ respond(callId, true, replayedText, undefined, undefined, compiledSchema !== undefined);
346
+ return;
347
+ }
348
+
349
+ const key = journalKey(keyInput);
350
+ const resumeMark = payload.resume !== undefined ? ({ resumed: true } as const) : {};
351
+
352
+ /** A skip the user asked for, before the child ever started. */
353
+ const settleSkipped = (extra: Partial<WorkflowAgentEntry>) => {
354
+ recordJournal?.({ index, key, ok: false, ...resumeMark });
355
+ emit([{ ...base, queuedAt, ...extra, state: "error", skipped: true, error: "Skipped by user." }]);
356
+ // `null`, exactly as a terminal failure gives — a skipped agent is one
357
+ // the script's `.filter(Boolean)` was already written to survive.
358
+ respond(callId, true, null);
359
+ };
360
+
361
+ // Registered for exactly as long as the call is unanswered, which is the
362
+ // window in which skip and retry mean anything.
363
+ const live: LiveAgent = { agentId, started: false };
364
+ liveAgents.set(index, live);
365
+ // Read through a call, not off the field: `intent` is set from outside
366
+ // this function while it is suspended at an await, so control-flow
367
+ // narrowing across the awaits would be reasoning about a value that has
368
+ // since changed.
369
+ const intent = (): LiveAgent["intent"] => live.intent;
370
+ let attempt = 1;
371
+ let callTokens = 0, callToolCalls = 0;
372
+ try {
373
+ for (;;) {
374
+ // Held before the slot, not after: a paused run must not sit on
375
+ // concurrency it is not using while its running agents drain.
376
+ await pauseGate(live);
377
+ if (intent() === "skip") return settleSkipped({});
378
+
379
+ // A resumed agent waits its turn like any other: it is the same amount of
380
+ // model running at once.
381
+ await semaphore.acquire();
382
+ if (aborted || settled) {
383
+ semaphore.release();
384
+ respond(callId, false, undefined, "Workflow aborted.", true);
385
+ return;
386
+ }
387
+ // Paused while parked behind the limit: this agent was waiting for a
388
+ // permit when the pause landed, so it never passed the gate above.
389
+ // Hand the permit back and go wait at the gate like everything else,
390
+ // or a pause would leak exactly as many agents as were queued.
391
+ if (isPaused() && !aborted && !settled) {
392
+ semaphore.release();
393
+ continue;
394
+ }
395
+ // Skipped while parked behind the limit: the permit arrived, and the
396
+ // only thing left to do with it is give it back.
397
+ if (intent() === "skip") {
398
+ semaphore.release();
399
+ return settleSkipped({});
400
+ }
401
+
402
+ // Carried on every emit from here on, so a retried row keeps saying
403
+ // why it is on its second attempt instead of losing it to the next
404
+ // progress update.
405
+ const attemptMark =
406
+ attempt > 1 ? { attempt, lastAttemptReason: "user-retry" as const } : {};
407
+
408
+ const startedAt = Date.now();
409
+ base.gateJobId = undefined;
410
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark }]);
411
+
412
+ // Mutates `base` rather than emitting a standalone patch: every later
413
+ // emit spreads it, so the settle path carries the effective values
414
+ // without knowing they were ever corrected. Re-emitting under the
415
+ // same `index` is what the append-only, last-write-wins progress log
416
+ // is for — the row updates in place while the agent is still running.
417
+ const onResolved = (info: {
418
+ recordId?: string;
419
+ modelName?: string;
420
+ modelId?: string;
421
+ thinking?: string;
422
+ requestedThinking?: string;
423
+ requestedModel?: string;
424
+ }) => {
425
+ if (info.recordId !== undefined) base.recordId = info.recordId;
426
+ if (info.modelName !== undefined) base.model = info.modelName;
427
+ if (info.modelId !== undefined) base.modelId = info.modelId;
428
+ if (info.thinking !== undefined) base.thinking = info.thinking;
429
+ if (info.requestedThinking !== undefined) base.requestedThinking = info.requestedThinking;
430
+ if (info.requestedModel !== undefined) base.requestedModel = info.requestedModel;
431
+ // `base.state` is still "start", so emitting after the row reached a
432
+ // terminal state would revert it to running under last-write-wins.
433
+ // Not reachable from this repo's host, which reports during startup
434
+ // — but this is the host boundary, and every other promise it makes
435
+ // is checked rather than trusted.
436
+ if (!inflight.has(agentId)) return;
437
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark, lastProgressAt: Date.now() }]);
438
+ };
439
+ live.started = true;
440
+ inflight.add(agentId);
441
+
442
+ let result: WorkflowSpawnResult | undefined;
443
+ try {
444
+ result =
445
+ resumed !== undefined && resumeAgent !== undefined
446
+ ? await resumeAgent(resumed.agentId, payload.prompt, onResolved)
447
+ : await host.spawnAgent({
448
+ agentId,
449
+ index,
450
+ prompt: payload.prompt,
451
+ label,
452
+ agentType,
453
+ ...(model !== undefined ? { model } : {}),
454
+ ...(payload.effort !== undefined ? { effort: payload.effort } : {}),
455
+ ...(compiledSchema !== undefined ? { schema: compiledSchema } : {}),
456
+ ...(payload.phaseIndex !== undefined ? { phaseIndex: payload.phaseIndex } : {}),
457
+ ...(payload.phaseTitle !== undefined ? { phaseTitle: payload.phaseTitle } : {}),
458
+ onResolved,
459
+ });
460
+ if (result.ok) {
461
+ // Recorded before the gate runs: the child itself finished, so it is
462
+ // resumable even when its gate rejects the work — "here is what the
463
+ // gate said, fix it" is the loop this exists for.
464
+ completedByLabel.set(label, {
465
+ agentId,
466
+ label,
467
+ agentType,
468
+ ...(model !== undefined ? { model } : {}),
469
+ ...(compiledSchema !== undefined ? { schema: compiledSchema } : {}),
470
+ });
471
+ // Re-checked here, not just in the child's tool: this is the one
472
+ // place that decides the script's value matches the schema it
473
+ // asked for, so a host that ignored `schema` fails loudly instead
474
+ // of handing the script prose. Before the gate, because a gate
475
+ // verifies work and there is no work to verify if the shape is
476
+ // wrong — and the reader should see the schema error, not a gate
477
+ // error standing in front of it.
478
+ if (compiledSchema !== undefined && result.ok) {
479
+ result = applySchema(result, compiledSchema);
480
+ }
481
+ if (result.ok && payload.gate !== undefined && runGate !== undefined) {
482
+ result = await applyGate(result, payload.gate, agentId, runGate, jobId => {
483
+ base.gateJobId = jobId;
484
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark, lastProgressAt: Date.now() }]);
485
+ });
486
+ }
487
+ }
488
+ } catch (error) {
489
+ // A gate can throw after the child spent tokens; keep that usage on failure.
490
+ result = { ...result, ok: false, error: error instanceof Error ? error.message : String(error) };
491
+ } finally {
492
+ inflight.delete(agentId);
493
+ live.started = false;
494
+ semaphore.release();
495
+ }
496
+
497
+ if (settled) return;
498
+
499
+ // Every attempt costs tokens, including attempts a user retries. Charge before
500
+ // the retry branch, and keep the progress row's totals across those attempts.
501
+ spentOutputTokens += result.outputTokens ?? 0;
502
+ callTokens += result.tokens ?? 0; callToolCalls += result.toolCalls ?? 0;
503
+
504
+ // The stop that produced this result was ours, so run the same call
505
+ // again rather than reporting it. The script is still awaiting this
506
+ // `agent()`, which is the only reason a retry can mean anything.
507
+ if (intent() === "retry" && !aborted) {
508
+ live.intent = undefined;
509
+ attempt++;
510
+ emit([{ ...base, queuedAt, attempt, lastAttemptReason: "user-retry" }]);
511
+ continue;
512
+ }
513
+
514
+ const finishedAt = Date.now();
515
+ const common = {
516
+ ...base,
517
+ queuedAt,
518
+ startedAt,
519
+ ...attemptMark,
520
+ lastProgressAt: finishedAt,
521
+ durationMs: finishedAt - startedAt,
522
+ ...(callTokens > 0 ? { tokens: callTokens } : {}),
523
+ ...(callToolCalls > 0 ? { toolCalls: callToolCalls } : {}),
524
+ };
525
+
526
+ if (result.ok) {
527
+ const text = result.text ?? "";
528
+ emit([{ ...common, state: "done", resultPreview: preview(text) }]);
529
+ recordJournal?.({ index, key, ok: true, text, ...resumeMark });
530
+ respond(callId, true, text, undefined, undefined, compiledSchema !== undefined);
531
+ return;
532
+ }
533
+ // Recorded as a failure rather than left out: a gap would be read as an
534
+ // unchanged prefix on the next resume, silently skipping the retry this
535
+ // whole mechanism exists to make cheap.
536
+ recordJournal?.({ index, key, ok: false, ...resumeMark });
537
+ // A dead agent is a null in the script, not a thrown error: Claude Code
538
+ // scripts .filter(Boolean) rather than try/catch around every call.
539
+ emit([
540
+ {
541
+ ...common,
542
+ state: "error",
543
+ // A user skip reaches here as a stopped child, which the host
544
+ // already reports as skipped — the flag is taken from the result
545
+ // rather than from the intent so an abort mid-skip still reads
546
+ // as whatever actually happened to the child.
547
+ error: result.error ?? "Agent failed.",
548
+ ...(result.skipped ? { skipped: true } : {}),
549
+ },
550
+ ]);
551
+ respond(callId, true, null);
552
+ return;
553
+ }
554
+ } finally {
555
+ liveAgents.delete(index);
556
+ }
557
+ }
558
+
559
+ /**
560
+ * Resolve one `workflow(ref)` and hand the child's source back compiled.
561
+ *
562
+ * A script can catch a failed lookup and continue. A missing `loadWorkflow`
563
+ * hook is fatal, like a missing `runGate` or `resumeAgent`: the host cannot
564
+ * provide the capability the script requested.
565
+ */
566
+ async function handleLoadWorkflow(callId: number, ref: WorkflowScriptRef): Promise<void> {
567
+ const loadWorkflow = host.loadWorkflow?.bind(host);
568
+ if (loadWorkflow === undefined) {
569
+ respond(callId, false, undefined, "This workflow host cannot run nested workflows.", true);
570
+ return;
571
+ }
572
+ let source: WorkflowScriptSource;
573
+ try {
574
+ source = await loadWorkflow(ref);
575
+ } catch (error) {
576
+ respond(callId, false, undefined, error instanceof Error ? error.message : String(error));
577
+ return;
578
+ }
579
+ if (!source.ok) {
580
+ respond(callId, false, undefined, source.message);
581
+ return;
582
+ }
583
+ try {
584
+ const child = validateScript(source.script);
585
+ respond(callId, true, {
586
+ name: child.meta.name,
587
+ metaJson: JSON.stringify(child.meta),
588
+ body: child.body,
589
+ });
590
+ } catch (error) {
591
+ respond(callId, false, undefined, error instanceof Error ? error.message : String(error));
592
+ }
593
+ }
594
+
595
+ worker.on("message", (message: WorkerMessage) => {
596
+ if (settled) return;
597
+ try {
598
+ switch (message.type) {
599
+ case "progress":
600
+ emit(message.entries);
601
+ break;
602
+ case "call":
603
+ if (message.method === "workflow") {
604
+ void handleLoadWorkflow(message.callId, message.payload as WorkflowScriptRef).catch(error => finish({ status: "failed", error: error instanceof Error ? error.message : String(error) }));
605
+ break;
606
+ }
607
+ if (message.method !== "agent") {
608
+ respond(message.callId, false, undefined, `Unknown workflow host method "${message.method}".`, true);
609
+ break;
610
+ }
611
+ void handleAgent(message.callId, message.payload as AgentCallPayload).catch(error => finish({ status: "failed", error: error instanceof Error ? error.message : String(error) }));
612
+ break;
613
+ case "complete": {
614
+ // The script is done, so every launch it made should have been
615
+ // answered by now — a response is sent before the worker can post
616
+ // this, so anything still open was never awaited. finish() aborts
617
+ // those children on the way out.
618
+ const unawaited = [...openLaunches.values()];
619
+ if (unawaited.length > 0) {
620
+ finish({ status: "failed", error: unawaitedLaunchMessage(unawaited) });
621
+ break;
622
+ }
623
+ finish({
624
+ status: "completed",
625
+ ...(message.resultJson === undefined ? {} : { value: JSON.parse(message.resultJson) }),
626
+ });
627
+ break;
628
+ }
629
+ case "error":
630
+ finish({ status: "failed", error: message.message });
631
+ break;
632
+ }
633
+ } catch (error) { finish({ status: "failed", error: error instanceof Error ? error.message : String(error) }); }
634
+ });
635
+
636
+ worker.on("error", error => {
637
+ finish({ status: "failed", error: error instanceof Error ? error.message : String(error) });
638
+ });
639
+
640
+ worker.on("exit", () => {
641
+ // Only reachable when the worker dies without reporting — a terminate()
642
+ // we did not initiate, or a hard crash.
643
+ finish({ status: "failed", error: "Workflow worker exited before completing." });
644
+ });
645
+ });
646
+ }