@ftrdotdev/pi-delegates 0.0.0-stage → 0.2.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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,1566 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { AgentDoc, MemoryStorage, type Storage } from "@earendil-works/pi-durable";
3
+ import { CodemodeSandbox } from "@earendil-works/pi-codemode";
4
+ import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
5
+ import type { Message } from "@earendil-works/pi-ai";
6
+ import { assert, it } from "@effect/vitest";
7
+ import { makeTempDir } from "../../../test-support/platform.ts";
8
+ import { rejects, throws } from "../../../test-support/assertions.ts";
9
+ import { Effect, Layer, Ref } from "effect";
10
+ import { stubHostSource, type StubModelSource } from "../../../test-support/stub-model-source.ts";
11
+ import { createCatalogue, defineAgent, decodeInlineDefinition } from "../definitions.ts";
12
+ import { RUN_TOOL_NAMES, CODING_EXTENSION } from "../names.ts";
13
+ import { RunDoc, RunIndexDoc } from "../run-records.ts";
14
+ import { GateDoc, GateIndexDoc } from "./gates.ts";
15
+ import { ToolkitDoc, ToolkitUnresolved, bindToolkit, type ToolkitResolver } from "../toolkit.ts";
16
+ import { HostModelAdapter } from "../../runtime/models.ts";
17
+ import {
18
+ openReadOnlyRuntime,
19
+ SessionRuntimeTag,
20
+ type SessionRuntime,
21
+ } from "../../runtime/session.ts";
22
+ import { viewRun, viewSession } from "../view.ts";
23
+ import { control, RunNotFound, RunNotRunning } from "./control.ts";
24
+ import {
25
+ WorkflowNotEnabled,
26
+ WorkflowOnly,
27
+ WorkflowTooLarge,
28
+ launch,
29
+ type HostDefaults,
30
+ } from "./launch.ts";
31
+ import {
32
+ runTools,
33
+ settleOutcome,
34
+ WorkflowService,
35
+ WorkflowRefused,
36
+ type WorkflowError,
37
+ } from "./workflow.ts";
38
+ import { openTestSession, type TestSession } from "../../../test-support/seams.ts";
39
+ import type { SessionHandle } from "../../runtime/handle.ts";
40
+
41
+ /** The layer the session graph provides, with this test's runtime standing in. */
42
+ const workflowLayerFor = (runtime: SessionRuntime) =>
43
+ WorkflowService.layer.pipe(Layer.provide(Layer.succeed(SessionRuntimeTag, runtime)));
44
+
45
+ const host: HostDefaults = {
46
+ model: { provider: "stub", modelId: "stub-1" },
47
+ thinkingLevel: "low",
48
+ };
49
+
50
+ const composer = defineAgent({
51
+ name: "composer",
52
+ role: "Workflow composer",
53
+ prompt: { role: "You compose workflows." },
54
+ tools: ["read"],
55
+ extensions: [CODING_EXTENSION],
56
+ approval: { gates: [] },
57
+ codemode: "runs",
58
+ });
59
+
60
+ const catalogue = createCatalogue([composer]);
61
+
62
+ const identityFor = async (sessionId: string) => {
63
+ const sessionDir = await makeTempDir("delegates-workflow-");
64
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
65
+ };
66
+
67
+ const open = async (options: {
68
+ readonly source: StubModelSource;
69
+ readonly storage?: Storage;
70
+ readonly sessionId?: string;
71
+ readonly catalogue?: typeof catalogue;
72
+ readonly sandbox?: CodemodeSandboxBase;
73
+ readonly store?: boolean;
74
+ }): Promise<TestSession> =>
75
+ openTestSession({
76
+ identity: await identityFor(options.sessionId ?? "s-1"),
77
+ models: new HostModelAdapter(options.source),
78
+ ...((options.store ?? false) ? {} : { storage: options.storage ?? new MemoryStorage() }),
79
+ catalogue: options.catalogue ?? catalogue,
80
+ host: () => host,
81
+ ...(options.sandbox === undefined ? {} : { sandbox: options.sandbox }),
82
+ });
83
+
84
+ const deps = (runtime: SessionRuntime, waitMs = 20_000) => ({
85
+ runtime,
86
+ catalogue,
87
+ host,
88
+ waitMs,
89
+ });
90
+
91
+ /** The stored extension selection, as names: `AgentState.extensions` is an array or an edit. */
92
+ const extensionsOf = (state: unknown): readonly string[] => {
93
+ const value = (state as { readonly extensions?: unknown } | undefined)?.extensions;
94
+ return Array.isArray(value) ? (value as readonly string[]) : [];
95
+ };
96
+
97
+ /** The last user turn's text: the task a child was given. */
98
+ const userText = (messages: readonly Message[]): string => {
99
+ const last = [...messages].reverse().find((message) => message.role === "user");
100
+ if (last === undefined) return "";
101
+ const content = last.content as unknown;
102
+ if (typeof content === "string") return content;
103
+ if (!Array.isArray(content)) return "";
104
+ return content
105
+ .map((part: { readonly type?: string; readonly text?: string }) =>
106
+ part.type === "text" ? (part.text ?? "") : "",
107
+ )
108
+ .join("");
109
+ };
110
+
111
+ /** The text of the newest tool result, so a scripted model can echo what a script returned. */
112
+ const lastToolText = (messages: readonly Message[]): string => {
113
+ const last = [...messages].reverse().find((message) => message.role === "toolResult");
114
+ const content = (last?.content ?? []) as readonly {
115
+ readonly type?: string;
116
+ readonly text?: string;
117
+ }[];
118
+ return content.map((part) => (part.type === "text" ? (part.text ?? "") : "")).join("");
119
+ };
120
+
121
+ /**
122
+ * One scripted workflow: the workflow conversation passes `script` to `codemode`
123
+ * and echoes the script's value; every child answers from its task text.
124
+ */
125
+ const scriptedSource = (script: string, answer: (task: string) => string): StubModelSource =>
126
+ stubHostSource({
127
+ respond: ({ systemPrompt, messages }) => {
128
+ if (!systemPrompt.includes("verbatim")) return { text: answer(userText(messages)) };
129
+ const answered = messages.some((message) => message.role === "toolResult");
130
+ return answered
131
+ ? { text: lastToolText(messages) }
132
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
133
+ },
134
+ });
135
+
136
+ type WorkflowRun = {
137
+ readonly runId: string;
138
+ readonly taskId: number;
139
+ readonly conversationId: number;
140
+ readonly childRunIds: readonly string[];
141
+ };
142
+
143
+ const workflowRun = async (runtime: SessionRuntime): Promise<WorkflowRun> => {
144
+ const index = await runtime.snapshot(RunIndexDoc);
145
+ for (const runId of index?.runIds ?? []) {
146
+ const doc = await runtime.snapshot(RunDoc, runId);
147
+ if (doc?.mode === "workflow") {
148
+ return {
149
+ runId,
150
+ taskId: doc.taskId as number,
151
+ conversationId: doc.childConversationId as number,
152
+ childRunIds: doc.childRunIds,
153
+ };
154
+ }
155
+ }
156
+ throw new Error("no workflow run");
157
+ };
158
+
159
+ const children = async (
160
+ runtime: SessionRuntime,
161
+ parent: WorkflowRun,
162
+ ): Promise<
163
+ readonly {
164
+ readonly runId: string;
165
+ readonly doc: Awaited<ReturnType<typeof runDoc>>;
166
+ }[]
167
+ > => {
168
+ const found = [];
169
+ for (const runId of parent.childRunIds) {
170
+ found.push({ runId, doc: await runDoc(runtime, runId) });
171
+ }
172
+ return found;
173
+ };
174
+
175
+ const runDoc = (runtime: SessionRuntime, runId: string) => runtime.snapshot(RunDoc, runId);
176
+
177
+ const countingSandbox = (order: string[] = []) => {
178
+ const events: string[] = [];
179
+ const inner = new CodemodeSandbox();
180
+ const sandbox = Object.create(inner) as CodemodeSandboxBase & { events: string[] };
181
+ Object.defineProperty(sandbox, "events", { value: events });
182
+ sandbox.start = (code, runOptions) => {
183
+ events.push("start");
184
+ order.push("start");
185
+ return inner.start(code, runOptions);
186
+ };
187
+ sandbox.close = async () => {
188
+ events.push("close");
189
+ order.push("close");
190
+ await inner.close();
191
+ };
192
+ return sandbox;
193
+ };
194
+
195
+ it("a workflow launch runs the script and returns its result", async () => {
196
+ const source = stubHostSource({
197
+ respond: ({ systemPrompt, messages }) => {
198
+ if (!systemPrompt.includes("verbatim")) return { text: "child answer" };
199
+ const answered = messages.some((message) => message.role === "toolResult");
200
+ return answered
201
+ ? { text: "42" }
202
+ : { toolCall: { name: "codemode", arguments: { code: "return 6 * 7" } } };
203
+ },
204
+ });
205
+ const runtime = await open({ source });
206
+ try {
207
+ const result = await launch(
208
+ { kind: "workflow", agent: "composer", script: "return 6 * 7" },
209
+ deps(runtime),
210
+ );
211
+ assert.strictEqual(result.view.status, "answered");
212
+ assert.strictEqual(result.view.answer, "42");
213
+ assert.strictEqual(result.view.mode, "workflow");
214
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
215
+ assert.strictEqual(doc?.mode, "workflow");
216
+ assert.strictEqual((await runtime.snapshot(RunIndexDoc))?.runIds.length, 1);
217
+ const agent = await runtime.harness.snapshot(
218
+ AgentDoc,
219
+ doc!.childConversationId as never,
220
+ BACKGROUND_CONTEXT,
221
+ );
222
+ assert.ok(extensionsOf(agent).includes("codemode"), JSON.stringify(extensionsOf(agent)));
223
+ assert.ok(extensionsOf(agent).includes("runs"), JSON.stringify(extensionsOf(agent)));
224
+ } finally {
225
+ await runtime.close();
226
+ }
227
+ }, 30_000);
228
+
229
+ it("a definition without code mode refuses a workflow launch", async () => {
230
+ const runtime = await open({
231
+ source: stubHostSource({ text: "ok" }),
232
+ catalogue: createCatalogue(),
233
+ });
234
+ try {
235
+ await rejects(
236
+ launch({ kind: "workflow", agent: "scout", script: "return 1" }, deps(runtime)),
237
+ (error: unknown) =>
238
+ error instanceof WorkflowNotEnabled &&
239
+ error.message.includes("scout") &&
240
+ error.message.includes('codemode: "runs"'),
241
+ );
242
+ assert.strictEqual(await runtime.snapshot(RunIndexDoc), undefined);
243
+ } finally {
244
+ await runtime.close();
245
+ }
246
+ });
247
+
248
+ it("an inline definition cannot enable code mode", () => {
249
+ throws(
250
+ () =>
251
+ decodeInlineDefinition({
252
+ name: "inline",
253
+ role: "Inline",
254
+ prompt: { role: "You inline." },
255
+ tools: [],
256
+ codemode: "runs",
257
+ }),
258
+ (error: unknown) =>
259
+ error instanceof Error &&
260
+ error.name === "DefinitionFieldNotAllowed" &&
261
+ (error as unknown as { field?: string }).field === "codemode",
262
+ );
263
+ });
264
+
265
+ it("the model sees codemode and not the run tools", async () => {
266
+ const runtime = await open({ source: workflowSource() });
267
+ try {
268
+ const result = await launch(
269
+ { kind: "workflow", agent: "composer", script: "return 6 * 7" },
270
+ deps(runtime),
271
+ );
272
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
273
+ const conversation = await runtime.run((context) =>
274
+ runtime.harness.conversation(doc!.childConversationId as never, context),
275
+ );
276
+ const agent = await runtime.run((context) => conversation!.agent(context));
277
+ const offered = agent.tools.map((tool) => tool.name);
278
+ assert.ok(offered.includes("codemode"), JSON.stringify(offered));
279
+ for (const name of RUN_TOOL_NAMES) {
280
+ assert.ok(!offered.includes(name), `${name} in ${JSON.stringify(offered)}`);
281
+ }
282
+ } finally {
283
+ await runtime.close();
284
+ }
285
+ }, 30_000);
286
+
287
+ it("a codemode definition refuses a single launch", async () => {
288
+ const runtime = await open({ source: stubHostSource({ text: "ok" }) });
289
+ try {
290
+ await rejects(
291
+ launch({ kind: "single", agent: "composer", task: "hello" }, deps(runtime)),
292
+ (error: unknown) =>
293
+ error instanceof WorkflowOnly &&
294
+ error.message.includes("composer") &&
295
+ error.message.includes('kind: "workflow"'),
296
+ );
297
+ assert.strictEqual(await runtime.snapshot(RunIndexDoc), undefined);
298
+ } finally {
299
+ await runtime.close();
300
+ }
301
+ });
302
+
303
+ it("a codemode definition refuses a fanout and a review launch", async () => {
304
+ const runtime = await open({ source: stubHostSource({ text: "ok" }) });
305
+ try {
306
+ await rejects(
307
+ launch(
308
+ { kind: "fanout", lane: "workflow", agents: [{ agent: "composer", task: "a" }] },
309
+ deps(runtime),
310
+ ),
311
+ (error: unknown) => error instanceof WorkflowOnly && error.message.includes("composer"),
312
+ );
313
+ await rejects(
314
+ launch({ kind: "review", task: "a", reviewers: [{ agent: "composer" }] }, deps(runtime)),
315
+ (error: unknown) => error instanceof WorkflowOnly && error.message.includes("composer"),
316
+ );
317
+ assert.strictEqual(await runtime.snapshot(RunIndexDoc), undefined);
318
+ } finally {
319
+ await runtime.close();
320
+ }
321
+ });
322
+
323
+ it("a script over 64 KiB is refused", async () => {
324
+ const runtime = await open({ source: workflowSource() });
325
+ try {
326
+ await rejects(
327
+ launch({ kind: "workflow", agent: "composer", script: "x".repeat(65_537) }, deps(runtime)),
328
+ (error: unknown) => error instanceof WorkflowTooLarge && error.message.includes("65536"),
329
+ );
330
+ assert.strictEqual(await runtime.snapshot(RunIndexDoc), undefined);
331
+ } finally {
332
+ await runtime.close();
333
+ }
334
+ });
335
+
336
+ it("codemode and runs are reserved extension names", async () => {
337
+ const resolver: ToolkitResolver = {
338
+ availableExtensions: [],
339
+ availableTools: [],
340
+ availableSkills: [],
341
+ extension: () => undefined,
342
+ tool: () => undefined,
343
+ skill: () => undefined,
344
+ mcpServers: [],
345
+ codemodeTools: [],
346
+ unconnected: undefined,
347
+ matchTools: () => [],
348
+ };
349
+ await rejects(
350
+ Effect.runPromise(
351
+ bindToolkit({ ...composer, codemode: undefined, extensions: ["runs"] }, resolver),
352
+ ),
353
+ (error: unknown) =>
354
+ error instanceof ToolkitUnresolved &&
355
+ error.message.includes("runs") &&
356
+ error.message.includes("codemode"),
357
+ );
358
+ });
359
+
360
+ it("the workflow section tells the model to pass the script", async () => {
361
+ const source = workflowSource();
362
+ const runtime = await open({ source });
363
+ try {
364
+ await launch({ kind: "workflow", agent: "composer", script: "return 6 * 7" }, deps(runtime));
365
+ const prompt = source.requests[0]?.systemPrompt ?? "";
366
+ assert.ok(prompt.includes("verbatim"), prompt);
367
+ assert.ok(prompt.includes("codemode"), prompt);
368
+ assert.ok(prompt.includes("runs"), prompt);
369
+ } finally {
370
+ await runtime.close();
371
+ }
372
+ }, 30_000);
373
+
374
+ it("a read-only runtime starts no worker", async () => {
375
+ const source = workflowSource();
376
+ // No `storage` override: the store must survive the first runtime for the viewer to read it.
377
+ const runtime = await open({ source, store: true });
378
+ let runId: string | undefined;
379
+ try {
380
+ const result = await launch(
381
+ { kind: "workflow", agent: "composer", script: "return 6 * 7" },
382
+ deps(runtime),
383
+ );
384
+ runId = result.view.runId;
385
+ } finally {
386
+ await runtime.close();
387
+ }
388
+
389
+ const sandbox = countingSandbox();
390
+ const readOnly = await openReadOnlyRuntime({
391
+ storePath: runtime.storePath,
392
+ models: new HostModelAdapter(stubHostSource()),
393
+ sandbox,
394
+ });
395
+ try {
396
+ const doc = await readOnly.harness.snapshot(RunDoc, runId!, BACKGROUND_CONTEXT);
397
+ assert.strictEqual(doc?.mode, "workflow");
398
+ assert.deepStrictEqual(sandbox.events, []);
399
+ } finally {
400
+ await readOnly.close();
401
+ }
402
+ }, 30_000);
403
+
404
+ it("closing a runtime closes its sandbox", async () => {
405
+ const order: string[] = [];
406
+ const sandbox = countingSandbox(order);
407
+ const source = workflowSource();
408
+ const runtime = await open({ source, sandbox });
409
+ void runtime.harness.closed.then(() => order.push("harness-close"));
410
+ void (await launch(
411
+ { kind: "workflow", agent: "composer", script: "return 6 * 7" },
412
+ deps(runtime),
413
+ ));
414
+ await runtime.close();
415
+ assert.deepStrictEqual(sandbox.events, ["start", "close"]);
416
+ assert.deepStrictEqual(order, ["start", "harness-close", "close"]);
417
+ }, 30_000);
418
+
419
+ const workflowSource = (): StubModelSource =>
420
+ stubHostSource({
421
+ respond: ({ systemPrompt, messages }) => {
422
+ if (!systemPrompt.includes("verbatim")) return { text: "child answer" };
423
+ const answered = messages.some((message) => message.role === "toolResult");
424
+ return answered
425
+ ? { text: "42" }
426
+ : { toolCall: { name: "codemode", arguments: { code: "return 6 * 7" } } };
427
+ },
428
+ });
429
+
430
+ it("a script launches two children and returns both answers", async () => {
431
+ const script =
432
+ 'const a = await tools.launch({ agent: "scout", task: "a" }); ' +
433
+ 'const b = await tools.launch({ agent: "scout", task: "b" }); ' +
434
+ "return [a.answer, b.answer].join('|');";
435
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
436
+ try {
437
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
438
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
439
+ assert.ok(result.view.answer?.includes("answer a"), result.view.answer ?? "");
440
+ assert.ok(result.view.answer?.includes("answer b"), result.view.answer ?? "");
441
+ const parent = await workflowRun(runtime);
442
+ assert.strictEqual(parent.childRunIds.length, 2);
443
+ const index = await runtime.snapshot(RunIndexDoc);
444
+ assert.strictEqual(index?.runIds.length, 3);
445
+ for (const runId of parent.childRunIds) {
446
+ const doc = await runDoc(runtime, runId);
447
+ assert.ok((doc?.childConversationId ?? null) !== null);
448
+ }
449
+ } finally {
450
+ await runtime.close();
451
+ }
452
+ }, 60_000);
453
+
454
+ it("two identical scripted launches create two children", async () => {
455
+ const script =
456
+ 'await tools.launch({ agent: "scout", task: "same" }); ' +
457
+ 'await tools.launch({ agent: "scout", task: "same" }); return "both";';
458
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
459
+ try {
460
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
461
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
462
+ const parent = await workflowRun(runtime);
463
+ assert.strictEqual(parent.childRunIds.length, 2);
464
+ assert.notStrictEqual(parent.childRunIds[0], parent.childRunIds[1]);
465
+ const conversations = new Set<number>();
466
+ for (const runId of parent.childRunIds) {
467
+ const doc = await runDoc(runtime, runId);
468
+ conversations.add(doc!.childConversationId as number);
469
+ }
470
+ assert.strictEqual(conversations.size, 2);
471
+ } finally {
472
+ await runtime.close();
473
+ }
474
+ }, 60_000);
475
+
476
+ it("a child run is owned by the workflow run and inherits its lane", async () => {
477
+ const script =
478
+ 'await tools.launch({ agent: "scout", task: "a" }); ' +
479
+ 'await tools.launch({ agent: "scout", task: "b" }); return "done";';
480
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
481
+ try {
482
+ await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
483
+ const parent = await workflowRun(runtime);
484
+ assert.strictEqual(parent.childRunIds.length, 2);
485
+ for (const { doc } of await children(runtime, parent)) {
486
+ assert.strictEqual(doc?.parentRunId, parent.runId);
487
+ assert.strictEqual(doc?.lane, "workflow");
488
+ const task = await runtime.run((context) =>
489
+ runtime.harness.getTask(doc!.taskId as never, context),
490
+ );
491
+ assert.strictEqual(task?.owner as unknown, parent.taskId);
492
+ }
493
+ } finally {
494
+ await runtime.close();
495
+ }
496
+ }, 60_000);
497
+
498
+ it("the run tools are exactly eight and never offered to the model", async () => {
499
+ const runtime = await open({ source: scriptedSource('return "done";', (task) => task) });
500
+ try {
501
+ const snapshotTools = runtime.registry
502
+ .snapshot()
503
+ .tools()
504
+ .filter((entry) => entry.tool.callers?.length === 1 && entry.tool.callers[0] === "tools")
505
+ .map((entry) => entry.tool.name)
506
+ .sort();
507
+ assert.deepStrictEqual(snapshotTools, [...RUN_TOOL_NAMES].sort());
508
+ } finally {
509
+ await runtime.close();
510
+ }
511
+ });
512
+
513
+ it("a script reads a lane and a status", async () => {
514
+ const script =
515
+ 'await tools.launch({ agent: "scout", task: "a" }); ' +
516
+ 'await tools.launch({ agent: "scout", task: "b" }); ' +
517
+ 'const lane = await tools.lane({ name: "workflow" }); ' +
518
+ "const status = await tools.status({}); " +
519
+ "return [lane.answered, typeof lane.running, typeof lane.queued, status.runs.length, " +
520
+ 'Object.keys(status.runs[0]).sort().join(",")].join("|");';
521
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
522
+ try {
523
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
524
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
525
+ assert.ok(
526
+ result.view.answer?.includes("2|number|number|3|definition,lane,run,status"),
527
+ result.view.answer ?? "",
528
+ );
529
+ } finally {
530
+ await runtime.close();
531
+ }
532
+ }, 60_000);
533
+
534
+ it("status narrows to one run", async () => {
535
+ const script =
536
+ 'const mine = (await tools.status({})).runs.find((run) => run.definition === "composer"); ' +
537
+ "const one = await tools.status({ run: mine.run }); " +
538
+ 'return [one.runs.length, one.runs[0].run === mine.run].join("|");';
539
+ const runtime = await open({ source: scriptedSource(script, (task) => task) });
540
+ try {
541
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
542
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
543
+ assert.ok(result.view.answer?.includes("1|true"), result.view.answer ?? "");
544
+ } finally {
545
+ await runtime.close();
546
+ }
547
+ }, 60_000);
548
+
549
+ it("status refuses an unknown run", async () => {
550
+ const script =
551
+ 'try { await tools.status({ run: "run:missing#1" }); return "listed"; } ' +
552
+ "catch (error) { return String(error && error.message ? error.message : error); }";
553
+ const runtime = await open({ source: scriptedSource(script, (task) => task) });
554
+ try {
555
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
556
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
557
+ assert.ok(result.view.answer?.includes("run:missing#1"), result.view.answer ?? "");
558
+ assert.ok(!(result.view.answer?.includes("listed") ?? false), result.view.answer ?? "");
559
+ } finally {
560
+ await runtime.close();
561
+ }
562
+ }, 60_000);
563
+
564
+ it("ref returns the run's conversation and gate run", async () => {
565
+ const script =
566
+ "const status = await tools.status({}); " +
567
+ 'const mine = status.runs.find((run) => run.definition === "composer"); ' +
568
+ "const r = await tools.ref({ run: mine.run }); " +
569
+ 'return [r.run === mine.run, typeof r.conversationId, r.gateRunId === mine.run].join("|");';
570
+ const runtime = await open({ source: scriptedSource(script, (task) => task) });
571
+ try {
572
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
573
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
574
+ assert.ok(result.view.answer?.includes("true|number|true"), result.view.answer ?? "");
575
+ } finally {
576
+ await runtime.close();
577
+ }
578
+ }, 60_000);
579
+
580
+ it("launch_many starts a group and returns one entry per child", async () => {
581
+ const script =
582
+ "const g = await tools.launch_many({ children: [" +
583
+ '{ agent: "scout", task: "a" }, { agent: "scout", task: "b" }] }); ' +
584
+ 'return g.runs.map((run) => run.status).join(",");';
585
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
586
+ try {
587
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
588
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
589
+ assert.ok(result.view.answer?.includes("answered,answered"), result.view.answer ?? "");
590
+ const parent = await workflowRun(runtime);
591
+ const index = await runtime.snapshot(RunIndexDoc);
592
+ let group: { readonly childRunIds: readonly string[] } | undefined;
593
+ for (const runId of index?.runIds ?? []) {
594
+ const doc = await runDoc(runtime, runId);
595
+ if (doc?.mode === "fanout") group = { childRunIds: doc.childRunIds };
596
+ }
597
+ assert.ok(group !== undefined, "no group run");
598
+ assert.deepStrictEqual([...parent.childRunIds].sort(), [...group!.childRunIds].sort());
599
+ for (const runId of parent.childRunIds) {
600
+ const childDoc = await runDoc(runtime, runId);
601
+ assert.strictEqual(childDoc?.parentRunId, parent.runId);
602
+ assert.strictEqual(childDoc?.gateRunId, parent.runId);
603
+ }
604
+ const view = await viewSession(runtime);
605
+ const workflow = view.runs.find((run) => run.runId === parent.runId);
606
+ assert.deepStrictEqual(
607
+ workflow?.children.map((child) => child.runId),
608
+ [...parent.childRunIds],
609
+ );
610
+ } finally {
611
+ await runtime.close();
612
+ }
613
+ }, 60_000);
614
+
615
+ it("a gated child of a group parks under the workflow", async () => {
616
+ const deployer = defineAgent({
617
+ name: "deployer",
618
+ role: "Deploy agent",
619
+ prompt: { role: "You deploy things." },
620
+ tools: ["bash"],
621
+ extensions: [CODING_EXTENSION],
622
+ approval: { gates: [{ name: "ship", tools: ["bash"], match: "deploy" }] },
623
+ });
624
+ const script =
625
+ 'const g = await tools.launch_many({ children: [{ agent: "deployer", task: "ship it" }] }); ' +
626
+ 'return g.runs.map((run) => run.status + ":" + run.answer).join("|");';
627
+ const source = stubHostSource({
628
+ respond: ({ systemPrompt, messages }) => {
629
+ if (systemPrompt.includes("verbatim")) {
630
+ const answered = messages.some((message) => message.role === "toolResult");
631
+ return answered
632
+ ? { text: lastToolText(messages) }
633
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
634
+ }
635
+ const ran = messages.some((message) => message.role === "toolResult");
636
+ return ran
637
+ ? { text: "deployed" }
638
+ : { toolCall: { name: "bash", arguments: { command: "deploy now" } } };
639
+ },
640
+ });
641
+ const runtime = await open({ source, catalogue: createCatalogue([composer, deployer]) });
642
+ try {
643
+ void launch({ kind: "workflow", agent: "composer", script }, deps(runtime, 500)).catch(
644
+ () => undefined,
645
+ );
646
+ const parent = await waitFor(async () => {
647
+ try {
648
+ return await workflowRun(runtime);
649
+ } catch {
650
+ return undefined;
651
+ }
652
+ });
653
+ const gate = await waitFor(async () => {
654
+ const record = await runtime.snapshot(GateDoc, gateKeyOf(parent.runId, "ship"));
655
+ return record?.status === "pending" ? record : undefined;
656
+ });
657
+ assert.strictEqual(gate.runId, parent.runId);
658
+ assert.strictEqual(gate.childRunIds.length, 1, JSON.stringify(gate.childRunIds));
659
+ const parkedParent = await workflowRun(runtime);
660
+ assert.ok(
661
+ parkedParent.childRunIds.includes(gate.childRunIds[0]!),
662
+ JSON.stringify(parkedParent.childRunIds),
663
+ );
664
+ const parkedView = await viewRun(parkedParent.runId, runtime);
665
+ assert.ok(
666
+ parkedView.children.some((child) => child.runId === gate.childRunIds[0]),
667
+ JSON.stringify(parkedView.children),
668
+ );
669
+
670
+ await control(
671
+ { action: "approve", run: parent.runId, gate: "ship" },
672
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
673
+ );
674
+ const done = await waitFor(async () => {
675
+ const view = await viewRun(parent.runId, runtime);
676
+ return view.status === "answered" ? view : undefined;
677
+ });
678
+ assert.ok(done.answer?.includes("answered:deployed"), done.answer ?? "");
679
+ const childId = gate.childRunIds[0]!;
680
+ const childDoc = await runDoc(runtime, childId);
681
+ assert.strictEqual(childDoc?.gateRunId, parent.runId);
682
+ assert.strictEqual(childDoc?.parentRunId, parent.runId);
683
+ } finally {
684
+ await runtime.close();
685
+ }
686
+ }, 60_000);
687
+
688
+ it("stopping a workflow mid-group keeps its child nested", async () => {
689
+ const script =
690
+ 'const g = await tools.launch_many({ children: [{ agent: "scout", task: "a" }] }); ' +
691
+ "return g.runs[0].status;";
692
+ let release: () => void = () => {};
693
+ const hold = { promise: new Promise<void>((resolve) => (release = resolve)) };
694
+ const source = stubHostSource({
695
+ hold: () => hold.promise,
696
+ holdAt: [2],
697
+ respond: ({ systemPrompt, messages }) => {
698
+ if (!systemPrompt.includes("verbatim")) return { text: "answer" };
699
+ const answered = messages.some((message) => message.role === "toolResult");
700
+ return answered
701
+ ? { text: lastToolText(messages) }
702
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
703
+ },
704
+ });
705
+ const runtime = await open({ source });
706
+ try {
707
+ void launch({ kind: "workflow", agent: "composer", script }, deps(runtime, 500)).catch(
708
+ () => undefined,
709
+ );
710
+ const parent = await waitFor(async () => {
711
+ try {
712
+ const run = await workflowRun(runtime);
713
+ return run.childRunIds.length === 1 ? run : undefined;
714
+ } catch {
715
+ return undefined;
716
+ }
717
+ });
718
+ const childId = parent.childRunIds[0]!;
719
+ await control(
720
+ { action: "stop", run: parent.runId },
721
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
722
+ );
723
+ const stopped = await viewRun(parent.runId, runtime);
724
+ assert.strictEqual(stopped.status, "stopped");
725
+ assert.ok(
726
+ stopped.children.some((child) => child.runId === childId),
727
+ JSON.stringify(stopped.children),
728
+ );
729
+ assert.strictEqual((await runDoc(runtime, childId))?.parentRunId, parent.runId);
730
+ release();
731
+ } finally {
732
+ await runtime.close();
733
+ }
734
+ }, 60_000);
735
+
736
+ it("a script cannot stop its own run", async () => {
737
+ const script =
738
+ 'const mine = (await tools.status({})).runs.find((run) => run.definition === "composer"); ' +
739
+ 'try { await tools.stop({ run: mine.run }); return "stopped"; } catch { return "refused"; }';
740
+ const runtime = await open({ source: scriptedSource(script, (task) => task) });
741
+ try {
742
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
743
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
744
+ assert.ok(result.view.answer?.includes("refused"), result.view.answer ?? "");
745
+ const session = await viewSession(runtime);
746
+ assert.strictEqual(session.runs.length, 1);
747
+ assert.strictEqual(session.runs[0]?.status, "answered");
748
+ } finally {
749
+ await runtime.close();
750
+ }
751
+ }, 60_000);
752
+
753
+ it("stopping the workflow stops its running children", async () => {
754
+ const script =
755
+ 'await tools.launch({ agent: "scout", task: "a" }); ' +
756
+ 'await tools.launch({ agent: "scout", task: "b" }); return "done";';
757
+ const source = stubHostSource({
758
+ hold: () => new Promise<void>(() => {}),
759
+ holdAt: [3],
760
+ respond: ({ systemPrompt, messages }) => {
761
+ if (!systemPrompt.includes("verbatim")) return { text: `answer ${userText(messages)}` };
762
+ const answered = messages.some((message) => message.role === "toolResult");
763
+ return answered
764
+ ? { text: lastToolText(messages) }
765
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
766
+ },
767
+ });
768
+ const runtime = await open({ source });
769
+ try {
770
+ const pending = launch({ kind: "workflow", agent: "composer", script }, deps(runtime, 30_000));
771
+ // Stop only once both children were claimed; the second one is held mid-generation.
772
+ const parent = await waitFor(async () => {
773
+ try {
774
+ const run = await workflowRun(runtime);
775
+ return run.childRunIds.length === 2 ? run : undefined;
776
+ } catch {
777
+ return undefined;
778
+ }
779
+ });
780
+ await control(
781
+ { action: "stop", run: parent.runId },
782
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
783
+ );
784
+ const result = await pending;
785
+ assert.strictEqual(result.view.status, "stopped");
786
+ const stoppedParent = await workflowRun(runtime);
787
+ assert.strictEqual(stoppedParent.childRunIds.length, 2);
788
+ const index = await runtime.snapshot(RunIndexDoc);
789
+ assert.strictEqual(index?.runIds.length, 3);
790
+ for (const { doc } of await children(runtime, stoppedParent)) {
791
+ const task = await runtime.run((context) =>
792
+ runtime.harness.getTask(doc!.taskId as never, context),
793
+ );
794
+ assert.notStrictEqual(task?.state.status, "running");
795
+ }
796
+ } finally {
797
+ await runtime.close();
798
+ }
799
+ }, 60_000);
800
+
801
+ it("the session view nests scripted children", async () => {
802
+ const script =
803
+ 'await tools.launch({ agent: "scout", task: "a" }); ' +
804
+ 'await tools.launch({ agent: "scout", task: "b" }); return "done";';
805
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
806
+ try {
807
+ await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
808
+ const parent = await workflowRun(runtime);
809
+ const view = await viewSession(runtime);
810
+ const workflow = view.runs.find((run) => run.runId === parent.runId);
811
+ assert.ok(workflow !== undefined, "workflow not in the view");
812
+ assert.strictEqual(workflow.mode, "workflow");
813
+ assert.deepStrictEqual(
814
+ workflow.children.map((child) => child.runId),
815
+ [...parent.childRunIds],
816
+ );
817
+ for (const runId of parent.childRunIds) {
818
+ assert.ok(!view.runs.some((run) => run.runId === runId), `${runId} is top level`);
819
+ }
820
+ } finally {
821
+ await runtime.close();
822
+ }
823
+ }, 60_000);
824
+
825
+ it("a service method refuses an unknown run", async () => {
826
+ const runtime = await open({ source: stubHostSource({ text: "ok" }) });
827
+ try {
828
+ const error = await Effect.runPromise(
829
+ Effect.gen(function* () {
830
+ const service = yield* WorkflowService;
831
+ return yield* Effect.flip(
832
+ service.stop(
833
+ { run: "run:missing#1" },
834
+ {
835
+ conversationId: runtime.root.id,
836
+ snapshot: async (token: unknown) =>
837
+ token === ToolkitDoc
838
+ ? { runId: "run:other#1", runTaskId: runtime.root.id }
839
+ : undefined,
840
+ } as never,
841
+ BACKGROUND_CONTEXT,
842
+ ),
843
+ );
844
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
845
+ );
846
+ assert.ok(error instanceof RunNotFound, String(error));
847
+ assert.ok(error.message.includes("run:missing#1"), error.message);
848
+ } finally {
849
+ await runtime.close();
850
+ }
851
+ });
852
+
853
+ /** Polls until `probe` returns a value; fails after a few seconds. */
854
+ const waitFor = async <A>(probe: () => Promise<A | undefined>): Promise<A> => {
855
+ for (let attempt = 0; attempt < 200; attempt += 1) {
856
+ const value = await probe();
857
+ if (value !== undefined) return value;
858
+ await new Promise((resolve) => setTimeout(resolve, 25));
859
+ }
860
+ throw new Error("timed out");
861
+ };
862
+
863
+ const restartIdentity = async (sessionId: string) => {
864
+ const sessionDir = await makeTempDir("delegates-restart-");
865
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
866
+ };
867
+
868
+ const terminal = (status: string): boolean =>
869
+ status === "answered" || status === "failed" || status === "stopped" || status === "denied";
870
+
871
+ /** A source whose third generation (the second child) is held until the test releases it. */
872
+ const twoChildSource = (
873
+ script: string,
874
+ hold: { readonly promise: Promise<void> },
875
+ generations: (task: string) => void,
876
+ ): StubModelSource =>
877
+ stubHostSource({
878
+ hold: () => hold.promise,
879
+ holdAt: [3],
880
+ respond: ({ systemPrompt, messages }) => {
881
+ if (systemPrompt.includes("verbatim")) {
882
+ const answered = messages.some((message) => message.role === "toolResult");
883
+ return answered
884
+ ? { text: lastToolText(messages) }
885
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
886
+ }
887
+ const task = userText(messages);
888
+ generations(task);
889
+ return { text: `answer ${task}` };
890
+ },
891
+ });
892
+
893
+ it("a restart mid-script reattaches without duplicating or re-claiming children", async () => {
894
+ const script =
895
+ 'await tools.launch({ agent: "scout", task: "a" }); ' +
896
+ 'await tools.launch({ agent: "scout", task: "b" }); return "both";';
897
+ let release: () => void = () => {};
898
+ const hold = { promise: new Promise<void>((resolve) => (release = resolve)) };
899
+ // The plan asked for a claimLaunch spy. The generation count proves the same
900
+ // fact at the model boundary: a re-claimed child would generate a second time.
901
+ const counts = new Map<string, number>();
902
+ const source = twoChildSource(script, hold, (task) =>
903
+ counts.set(task, (counts.get(task) ?? 0) + 1),
904
+ );
905
+ const identity = await restartIdentity("s-restart");
906
+ const openWith = () =>
907
+ openTestSession({
908
+ identity,
909
+ models: new HostModelAdapter(source),
910
+ catalogue,
911
+ host: () => host,
912
+ });
913
+
914
+ let runId: string | undefined;
915
+ let firstA: { readonly runId: string; readonly taskId: unknown } | undefined;
916
+ const first = await openWith();
917
+ try {
918
+ void launch(
919
+ { kind: "workflow", agent: "composer", script },
920
+ { ...deps(first), runtime: first },
921
+ ).catch(() => undefined);
922
+ const parent = await waitFor(async () => {
923
+ try {
924
+ const run = await workflowRun(first);
925
+ return run.childRunIds.length === 2 ? run : undefined;
926
+ } catch {
927
+ return undefined;
928
+ }
929
+ });
930
+ runId = parent.runId;
931
+ const a = await runDoc(first, parent.childRunIds[0]!);
932
+ firstA = { runId: parent.childRunIds[0]!, taskId: a?.taskId };
933
+ const before = await viewRun(runId, first);
934
+ assert.notStrictEqual(before.status, "answered", "the held child answered before the restart");
935
+ } finally {
936
+ await first.close();
937
+ }
938
+ release();
939
+
940
+ const second = await openWith();
941
+ try {
942
+ const view = await waitFor(async () => {
943
+ const current = await viewRun(runId!, second);
944
+ return terminal(current.status) ? current : undefined;
945
+ });
946
+ assert.strictEqual(view.status, "answered", view.diagnostic ?? "");
947
+ assert.ok(view.answer?.includes("both"), view.answer ?? "");
948
+ const parent = await workflowRun(second);
949
+ assert.strictEqual(parent.childRunIds.length, 2);
950
+ const answers: string[] = [];
951
+ for (const childRunId of parent.childRunIds) {
952
+ const childView = await viewRun(childRunId, second);
953
+ assert.strictEqual(childView.status, "answered", childView.diagnostic ?? "");
954
+ answers.push(childView.answer ?? "");
955
+ }
956
+ assert.deepStrictEqual(answers, ["answer a", "answer b"]);
957
+ const index = await second.snapshot(RunIndexDoc);
958
+ assert.strictEqual(index?.runIds.length, 3);
959
+ const conversations = new Set<number>();
960
+ for (const childRunId of parent.childRunIds) {
961
+ const doc = await runDoc(second, childRunId);
962
+ conversations.add(doc!.childConversationId as number);
963
+ }
964
+ assert.strictEqual(conversations.size, 2);
965
+ // The finished child kept its run and task, and was not generated again.
966
+ const resumedA = await runDoc(second, firstA!.runId);
967
+ assert.strictEqual(resumedA?.taskId, firstA!.taskId);
968
+ assert.strictEqual(counts.get("a"), 1);
969
+ // The held child's aborted generation is the one the restart ran again.
970
+ assert.strictEqual(counts.get("b"), 2);
971
+ } finally {
972
+ await second.close();
973
+ }
974
+ }, 60_000);
975
+
976
+ it("a sandbox that cannot start fails the script call with a diagnostic", async () => {
977
+ const sandbox = {
978
+ start: () => {
979
+ throw new Error("boom");
980
+ },
981
+ execute: async () => ({
982
+ ok: false as const,
983
+ error: { kind: "sandbox" as const, message: "boom" },
984
+ }),
985
+ close: async () => {},
986
+ } as unknown as CodemodeSandboxBase;
987
+ const script = 'return "never";';
988
+ const runtime = await open({ source: scriptedSource(script, (task) => task), sandbox });
989
+ try {
990
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
991
+ // A throwing tool is an error result the model sees; the run then answers the error text.
992
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
993
+ assert.ok(result.view.answer?.includes("workflow sandbox: boom"), result.view.answer ?? "");
994
+ const parent = await workflowRun(runtime);
995
+ const conversation = await runtime.run((context) =>
996
+ runtime.harness.conversation(parent.conversationId as never, context),
997
+ );
998
+ const transcript = await runtime.run((context) => conversation!.context(context));
999
+ const texts = transcript.messages.flatMap((message) =>
1000
+ message.role === "toolResult"
1001
+ ? (message.content as readonly { readonly type?: string; readonly text?: string }[]).map(
1002
+ (part) => (part.type === "text" ? (part.text ?? "") : ""),
1003
+ )
1004
+ : [],
1005
+ );
1006
+ assert.ok(
1007
+ texts.some((text) => text.includes("workflow sandbox: boom")),
1008
+ texts.join("\n"),
1009
+ );
1010
+ const index = await runtime.snapshot(RunIndexDoc);
1011
+ assert.strictEqual(index?.runIds.length, 1);
1012
+ } finally {
1013
+ await runtime.close();
1014
+ }
1015
+ }, 60_000);
1016
+
1017
+ it("resuming a workflow is refused", async () => {
1018
+ const runtime = await open({ source: stubHostSource({ hang: true }) });
1019
+ try {
1020
+ const result = await launch(
1021
+ { kind: "workflow", agent: "composer", script: "return 1" },
1022
+ deps(runtime, 100),
1023
+ );
1024
+ assert.strictEqual(result.view.status, "running");
1025
+ await control(
1026
+ { action: "stop", run: result.view.runId },
1027
+ { runtime, wait: { policy: "settle", waitMs: 5_000 } },
1028
+ );
1029
+ await rejects(
1030
+ control(
1031
+ { action: "resume", run: result.view.runId },
1032
+ { runtime, wait: { policy: "settle", waitMs: 0 } },
1033
+ ),
1034
+ (error: unknown) =>
1035
+ error instanceof Error &&
1036
+ error.name === "RunNotResumable" &&
1037
+ error.message.includes(result.view.runId) &&
1038
+ error.message.includes("workflow"),
1039
+ );
1040
+ } finally {
1041
+ await runtime.close();
1042
+ }
1043
+ }, 60_000);
1044
+
1045
+ it("resuming a stopped single run is unchanged", async () => {
1046
+ const runtime = await open({ source: stubHostSource({ hang: true }) });
1047
+ try {
1048
+ const result = await launch(
1049
+ { kind: "single", agent: "scout", task: "look" },
1050
+ deps(runtime, 100),
1051
+ );
1052
+ assert.strictEqual(result.view.status, "running");
1053
+ await control(
1054
+ { action: "stop", run: result.view.runId },
1055
+ { runtime, wait: { policy: "settle", waitMs: 5_000 } },
1056
+ );
1057
+ const resumed = await control(
1058
+ { action: "resume", run: result.view.runId },
1059
+ { runtime, wait: { policy: "settle", waitMs: 100 } },
1060
+ );
1061
+ assert.notStrictEqual(resumed.view!.status, "stopped");
1062
+ } finally {
1063
+ await runtime.close();
1064
+ }
1065
+ }, 60_000);
1066
+
1067
+ const gateKeyOf = (runId: string, name: string): string => `${runId}:${name}`;
1068
+
1069
+ const gateScript =
1070
+ 'const g = await tools.gate({ name: "ship" }); ' +
1071
+ 'if (g.decision !== "approved") return "blocked"; ' +
1072
+ 'return (await tools.launch({ agent: "scout", task: "go" })).answer;';
1073
+
1074
+ it("a gate created by a script parks the workflow", async () => {
1075
+ const runtime = await open({ source: scriptedSource(gateScript, (task) => `answer ${task}`) });
1076
+ try {
1077
+ const result = await launch(
1078
+ { kind: "workflow", agent: "composer", script: gateScript },
1079
+ deps(runtime, 20_000),
1080
+ );
1081
+ assert.strictEqual(result.view.status, "waiting");
1082
+ assert.deepStrictEqual(result.view.gates, ["script:ship"]);
1083
+ const parent = await workflowRun(runtime);
1084
+ const record = await runtime.snapshot(GateDoc, gateKeyOf(parent.runId, "script:ship"));
1085
+ assert.strictEqual(record?.status, "pending");
1086
+ assert.strictEqual(parent.childRunIds.length, 0);
1087
+ } finally {
1088
+ await runtime.close();
1089
+ }
1090
+ }, 60_000);
1091
+
1092
+ it("approving the gate releases the script", async () => {
1093
+ const runtime = await open({ source: scriptedSource(gateScript, (task) => `answer ${task}`) });
1094
+ try {
1095
+ const parked = await launch(
1096
+ { kind: "workflow", agent: "composer", script: gateScript },
1097
+ deps(runtime, 20_000),
1098
+ );
1099
+ const parent = await workflowRun(runtime);
1100
+ const decided = await control(
1101
+ { action: "approve", run: parent.runId, gate: "script:ship" },
1102
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
1103
+ );
1104
+ assert.ok(decided.view!.answer?.includes("answer go"), decided.view!.answer ?? "");
1105
+ const after = await workflowRun(runtime);
1106
+ assert.strictEqual(after.childRunIds.length, 1);
1107
+ const record = await runtime.snapshot(GateDoc, gateKeyOf(parked.view.runId, "script:ship"));
1108
+ assert.strictEqual(record?.status, "approved");
1109
+ } finally {
1110
+ await runtime.close();
1111
+ }
1112
+ }, 60_000);
1113
+
1114
+ it("denying the gate lets the script branch", async () => {
1115
+ const runtime = await open({ source: scriptedSource(gateScript, (task) => `answer ${task}`) });
1116
+ try {
1117
+ const parked = await launch(
1118
+ { kind: "workflow", agent: "composer", script: gateScript },
1119
+ deps(runtime, 20_000),
1120
+ );
1121
+ const decided = await control(
1122
+ { action: "deny", run: parked.view.runId, gate: "script:ship" },
1123
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
1124
+ );
1125
+ assert.ok(decided.view!.answer?.includes("blocked"), decided.view!.answer ?? "");
1126
+ const parent = await workflowRun(runtime);
1127
+ assert.strictEqual(parent.childRunIds.length, 0);
1128
+ const record = await runtime.snapshot(GateDoc, gateKeyOf(parent.runId, "script:ship"));
1129
+ assert.strictEqual(record?.status, "denied");
1130
+ } finally {
1131
+ await runtime.close();
1132
+ }
1133
+ }, 60_000);
1134
+
1135
+ it("a script gate survives a restart without a duplicate", async () => {
1136
+ const identity = await restartIdentity("s-gate-restart");
1137
+ const source = scriptedSource(gateScript, (task) => `answer ${task}`);
1138
+ const openWith = () =>
1139
+ openTestSession({
1140
+ identity,
1141
+ models: new HostModelAdapter(source),
1142
+ catalogue,
1143
+ host: () => host,
1144
+ });
1145
+
1146
+ const first = await openWith();
1147
+ let runId = "";
1148
+ let key = "";
1149
+ let taskIds: readonly number[] = [];
1150
+ try {
1151
+ const parked = await launch(
1152
+ { kind: "workflow", agent: "composer", script: gateScript },
1153
+ deps(first, 20_000),
1154
+ );
1155
+ assert.strictEqual(parked.view.status, "waiting");
1156
+ runId = parked.view.runId;
1157
+ key = gateKeyOf(runId, "script:ship");
1158
+ const record = await waitFor(async () => first.snapshot(GateDoc, key));
1159
+ assert.strictEqual(record.status, "pending");
1160
+ taskIds = [...record.taskIds];
1161
+ assert.strictEqual(taskIds.length, 1);
1162
+ } finally {
1163
+ await first.close();
1164
+ }
1165
+
1166
+ const second = await openWith();
1167
+ try {
1168
+ const pending = await waitFor(async () => second.snapshot(GateDoc, key));
1169
+ assert.strictEqual(pending.status, "pending");
1170
+ assert.deepStrictEqual(pending.taskIds, taskIds);
1171
+ const keys = (await second.snapshot(GateIndexDoc))?.keys ?? [];
1172
+ assert.deepStrictEqual(keys, [key]);
1173
+
1174
+ const decided = await control(
1175
+ { action: "approve", run: runId, gate: "script:ship" },
1176
+ { runtime: second, wait: { policy: "settle", waitMs: 20_000 } },
1177
+ );
1178
+ assert.ok(decided.view?.answer?.includes("answer go"), decided.view?.answer ?? "");
1179
+ const parent = await workflowRun(second);
1180
+ assert.strictEqual(parent.childRunIds.length, 1);
1181
+ const gate = await second.snapshot(GateDoc, key);
1182
+ assert.strictEqual(gate?.status, "approved");
1183
+ } finally {
1184
+ await second.close();
1185
+ }
1186
+ }, 60_000);
1187
+
1188
+ it("a repeated gate name in one script is refused", async () => {
1189
+ const script =
1190
+ 'try { await tools.gate({ name: "ship" }); await tools.gate({ name: "ship" }); ' +
1191
+ 'return "twice"; } catch { return "refused"; }';
1192
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
1193
+ try {
1194
+ const parked = await launch(
1195
+ { kind: "workflow", agent: "composer", script },
1196
+ deps(runtime, 20_000),
1197
+ );
1198
+ const decided = await control(
1199
+ { action: "approve", run: parked.view.runId, gate: "script:ship" },
1200
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
1201
+ );
1202
+ assert.ok(decided.view!.answer?.includes("refused"), decided.view!.answer ?? "");
1203
+ const keys = (await runtime.snapshot(GateIndexDoc))?.keys ?? [];
1204
+ assert.deepStrictEqual(keys, [gateKeyOf(parked.view.runId, "script:ship")]);
1205
+ } finally {
1206
+ await runtime.close();
1207
+ }
1208
+ }, 60_000);
1209
+
1210
+ it("a script gate does not collide with an approval rule of the same name", async () => {
1211
+ const script = 'const g = await tools.gate({ name: "ship" }); return g.decision;';
1212
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
1213
+ try {
1214
+ const parked = await launch(
1215
+ { kind: "workflow", agent: "composer", script },
1216
+ deps(runtime, 20_000),
1217
+ );
1218
+ const parent = await workflowRun(runtime);
1219
+ const ruleKey = gateKeyOf(parent.runId, "ship");
1220
+ await runtime.run((context) =>
1221
+ runtime.harness.commit(async (tx) => {
1222
+ const doc = await tx.doc(GateDoc, ruleKey, { runId: parent.runId, gate: "ship" });
1223
+ doc.status = "pending";
1224
+ doc.tool = "bash";
1225
+ doc.requestedAt = runtime.now();
1226
+ doc.deadline = runtime.now() + 60_000;
1227
+ const index = await tx.doc(GateIndexDoc);
1228
+ if (!index.keys.includes(ruleKey)) index.keys.push(ruleKey);
1229
+ }, context),
1230
+ );
1231
+
1232
+ const decided = await control(
1233
+ { action: "approve", run: parked.view.runId, gate: "script:ship" },
1234
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
1235
+ );
1236
+ assert.ok(decided.view!.answer?.includes("approved"), decided.view!.answer ?? "");
1237
+ const rule = await runtime.snapshot(GateDoc, ruleKey);
1238
+ assert.strictEqual(rule?.status, "pending");
1239
+ const scriptGate = await runtime.snapshot(GateDoc, gateKeyOf(parent.runId, "script:ship"));
1240
+ assert.strictEqual(scriptGate?.status, "approved");
1241
+ } finally {
1242
+ await runtime.close();
1243
+ }
1244
+ }, 60_000);
1245
+
1246
+ it("a gate is refused when the conversation has no toolkit", async () => {
1247
+ const runtime = await open({ source: stubHostSource({ text: "ok" }) });
1248
+ try {
1249
+ const error = await Effect.runPromise(
1250
+ Effect.gen(function* () {
1251
+ const service = yield* WorkflowService;
1252
+ return yield* Effect.flip(
1253
+ service.gate(
1254
+ { name: "ship" },
1255
+ {
1256
+ conversationId: runtime.root.id,
1257
+ snapshot: async () => undefined,
1258
+ taskId: runtime.root.id,
1259
+ now: () => runtime.now(),
1260
+ } as never,
1261
+ BACKGROUND_CONTEXT,
1262
+ ),
1263
+ );
1264
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
1265
+ );
1266
+ assert.ok(error instanceof WorkflowRefused, String(error));
1267
+ assert.strictEqual(error.reason, "unknown-gate");
1268
+ assert.strictEqual(await runtime.snapshot(GateIndexDoc), undefined);
1269
+ } finally {
1270
+ await runtime.close();
1271
+ }
1272
+ });
1273
+
1274
+ it("a script steers and stops a child", async () => {
1275
+ const holds: Array<() => void> = [];
1276
+ const source = stubHostSource({
1277
+ text: "done",
1278
+ hold: () => new Promise<void>((resolve) => holds.push(resolve)),
1279
+ holdAt: [1, 3],
1280
+ });
1281
+ const runtime = await open({ source });
1282
+ try {
1283
+ const work = await launch(
1284
+ { kind: "single", agent: "scout", task: "long" },
1285
+ { ...deps(runtime), waitMs: 100 },
1286
+ );
1287
+ assert.strictEqual(work.view.status, "running");
1288
+ const api = {
1289
+ conversationId: runtime.root.id,
1290
+ taskId: runtime.root.id,
1291
+ snapshot: async (token: unknown) =>
1292
+ token === ToolkitDoc ? { runId: "run:workflow#1", runTaskId: runtime.root.id } : undefined,
1293
+ };
1294
+ const runService = <A>(
1295
+ use: (service: WorkflowService["Service"]) => Effect.Effect<A, WorkflowError>,
1296
+ ) =>
1297
+ Effect.runPromise(
1298
+ Effect.gen(function* () {
1299
+ const service = yield* WorkflowService;
1300
+ return yield* use(service);
1301
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
1302
+ );
1303
+
1304
+ await runService((service) =>
1305
+ service.steer({ run: work.view.runId, message: "hurry" }, api as never, BACKGROUND_CONTEXT),
1306
+ );
1307
+ holds[0]!();
1308
+ const answered = await waitFor(async () => {
1309
+ const current = await viewRun(work.view.runId, runtime);
1310
+ return current.status === "answered" ? current : undefined;
1311
+ });
1312
+ assert.strictEqual(answered.answer, "done");
1313
+ const doc = await runDoc(runtime, work.view.runId);
1314
+ const conversation = await runtime.run((context) =>
1315
+ runtime.harness.conversation(doc!.childConversationId as never, context),
1316
+ );
1317
+ const transcript = await runtime.run((context) => conversation!.context(context));
1318
+ assert.ok(userText(transcript.messages).includes("hurry"), userText(transcript.messages));
1319
+
1320
+ const second = await launch(
1321
+ { kind: "single", agent: "scout", task: "long-2" },
1322
+ { ...deps(runtime), waitMs: 100 },
1323
+ );
1324
+ assert.strictEqual(second.view.status, "running");
1325
+ await runService((service) =>
1326
+ service.stop({ run: second.view.runId }, api as never, BACKGROUND_CONTEXT),
1327
+ );
1328
+ const stopped = await viewRun(second.view.runId, runtime);
1329
+ assert.strictEqual(stopped.status, "stopped");
1330
+ const refused = await Effect.runPromise(
1331
+ Effect.gen(function* () {
1332
+ const service = yield* WorkflowService;
1333
+ return yield* Effect.flip(
1334
+ service.steer(
1335
+ { run: second.view.runId, message: "again" },
1336
+ api as never,
1337
+ BACKGROUND_CONTEXT,
1338
+ ),
1339
+ );
1340
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
1341
+ );
1342
+ assert.ok(refused instanceof RunNotRunning, String(refused));
1343
+ } finally {
1344
+ await runtime.close();
1345
+ }
1346
+ }, 60_000);
1347
+
1348
+ it("a failed child comes back as a value the script branches on", async () => {
1349
+ const script =
1350
+ 'const a = await tools.launch({ agent: "scout", task: "broken" }); ' +
1351
+ 'if (a.status !== "failed") return "unexpected " + a.status; ' +
1352
+ 'return [a.status, a.answer === "" ? "empty" : "answer", typeof a.run].join("|");';
1353
+ const source = stubHostSource({
1354
+ // The workflow's generation passes the script; the child's generation fails.
1355
+ failAt: [2],
1356
+ respond: ({ systemPrompt, messages }) => {
1357
+ if (!systemPrompt.includes("verbatim")) return { text: "never" };
1358
+ const answered = messages.some((message) => message.role === "toolResult");
1359
+ return answered
1360
+ ? { text: lastToolText(messages) }
1361
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
1362
+ },
1363
+ });
1364
+ const runtime = await open({ source });
1365
+ try {
1366
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1367
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1368
+ assert.ok(result.view.answer?.includes("failed|empty|string"), result.view.answer ?? "");
1369
+ const parent = await workflowRun(runtime);
1370
+ assert.strictEqual(parent.childRunIds.length, 1);
1371
+ const child = await viewRun(parent.childRunIds[0]!, runtime);
1372
+ assert.strictEqual(child.status, "failed");
1373
+ } finally {
1374
+ await runtime.close();
1375
+ }
1376
+ }, 60_000);
1377
+
1378
+ it("a scripted launch records the lane it names", async () => {
1379
+ const script =
1380
+ 'const a = await tools.launch({ agent: "scout", task: "a", lane: "review" }); ' +
1381
+ "return a.status;";
1382
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
1383
+ try {
1384
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1385
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1386
+ const parent = await workflowRun(runtime);
1387
+ assert.strictEqual(parent.childRunIds.length, 1);
1388
+ const child = await runDoc(runtime, parent.childRunIds[0]!);
1389
+ assert.strictEqual(child?.lane, "review");
1390
+ const parentDoc = await runDoc(runtime, parent.runId);
1391
+ assert.strictEqual(parentDoc?.lane, "workflow");
1392
+ } finally {
1393
+ await runtime.close();
1394
+ }
1395
+ }, 60_000);
1396
+
1397
+ it("stopping an already stopped run answers success", async () => {
1398
+ let script = "";
1399
+ const source = stubHostSource({
1400
+ hold: () => new Promise<void>(() => {}),
1401
+ holdAt: [1],
1402
+ respond: ({ systemPrompt, messages }) => {
1403
+ if (!systemPrompt.includes("verbatim")) return { text: "done" };
1404
+ const answered = messages.some((message) => message.role === "toolResult");
1405
+ return answered
1406
+ ? { text: lastToolText(messages) }
1407
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
1408
+ },
1409
+ });
1410
+ const runtime = await open({ source });
1411
+ try {
1412
+ const stopped = await launch(
1413
+ { kind: "single", agent: "scout", task: "long" },
1414
+ { ...deps(runtime), waitMs: 100 },
1415
+ );
1416
+ assert.strictEqual(stopped.view.status, "running");
1417
+ await control(
1418
+ { action: "stop", run: stopped.view.runId },
1419
+ { runtime, wait: { policy: "settle", waitMs: 5_000 } },
1420
+ );
1421
+ assert.strictEqual((await viewRun(stopped.view.runId, runtime)).status, "stopped");
1422
+
1423
+ script = `const r = await tools.stop({ run: "${stopped.view.runId}" }); return "again";`;
1424
+ const workflow = await launch(
1425
+ { kind: "workflow", agent: "composer", script },
1426
+ { runtime, catalogue, host, waitMs: 20_000 },
1427
+ );
1428
+ assert.strictEqual(workflow.view.status, "answered", workflow.view.diagnostic ?? "");
1429
+ assert.ok(workflow.view.answer?.includes("again"), workflow.view.answer ?? "");
1430
+ assert.strictEqual((await viewRun(stopped.view.runId, runtime)).status, "stopped");
1431
+ assert.strictEqual((await viewRun(workflow.view.runId, runtime)).status, "answered");
1432
+ } finally {
1433
+ await runtime.close();
1434
+ }
1435
+ }, 60_000);
1436
+
1437
+ it("the settle outcome classifies a refusal as a Result when the effect refuses", async () => {
1438
+ const refusal = RunNotFound.make({ message: "Run r-1 not found." });
1439
+ const failing = Effect.fail(refusal);
1440
+ const result = (await settleOutcome(failing)) as {
1441
+ readonly _tag?: string;
1442
+ readonly failure?: { readonly output?: readonly { readonly text: string }[] };
1443
+ };
1444
+ assert.strictEqual(result._tag, "Failure");
1445
+ assert.strictEqual(result.failure?.output?.[0]?.text, "Run r-1 not found.");
1446
+ await rejects(settleOutcome(Effect.die(new Error("boom"))), /boom/);
1447
+ });
1448
+
1449
+ /**
1450
+ * One scripted workflow whose child generations are held: only the workflow's
1451
+ * own generations run. The gate is chosen per generation from the system prompt,
1452
+ * so a child holds and the workflow never does.
1453
+ */
1454
+ const heldChildrenSource = (script: string) => {
1455
+ let release = (): void => {};
1456
+ const held = new Promise<void>((resolve) => {
1457
+ release = resolve;
1458
+ });
1459
+ let gate: Promise<void> = Promise.resolve();
1460
+ const source = stubHostSource({
1461
+ hold: () => gate,
1462
+ respond: ({ systemPrompt, messages }) => {
1463
+ const workflow = systemPrompt.includes("verbatim");
1464
+ gate = workflow ? Promise.resolve() : held;
1465
+ if (!workflow) return { text: "child" };
1466
+ const answered = messages.some((message) => message.role === "toolResult");
1467
+ return answered
1468
+ ? { text: lastToolText(messages) }
1469
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
1470
+ },
1471
+ });
1472
+ return { source, release: () => release() };
1473
+ };
1474
+
1475
+ it("a detached script launch returns the run id, status and an empty answer", async () => {
1476
+ const script =
1477
+ 'const a = await tools.launch({ agent: "scout", task: "slow", execution: "detached" }); ' +
1478
+ 'return [a.run, a.answer === "" ? "empty" : a.answer, a.status].join("|");';
1479
+ const { source, release } = heldChildrenSource(script);
1480
+ const runtime = await open({ source });
1481
+ try {
1482
+ const launched = launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1483
+ // The script reached its next effect while the child's generation is held: the run exists.
1484
+ const parent = await waitFor(async () => {
1485
+ try {
1486
+ const run = await workflowRun(runtime);
1487
+ return run.childRunIds.length === 1 ? run : undefined;
1488
+ } catch {
1489
+ return undefined;
1490
+ }
1491
+ });
1492
+ const childRunId = parent.childRunIds[0] ?? "";
1493
+ const opening = await viewRun(childRunId, runtime);
1494
+ assert.strictEqual(opening.answer, null);
1495
+ assert.strictEqual((await runDoc(runtime, childRunId))?.execution, "detached");
1496
+
1497
+ release();
1498
+ const result = await launched;
1499
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1500
+ assert.match(result.view.answer ?? "", /\|empty\|queued$/);
1501
+ } finally {
1502
+ await runtime.close();
1503
+ }
1504
+ }, 60_000);
1505
+
1506
+ it("a detached script group returns one empty-answer entry per child", async () => {
1507
+ const script =
1508
+ 'const r = await tools.launch_many({ children: [{ agent: "scout", task: "a" }, ' +
1509
+ '{ agent: "scout", task: "b" }], execution: "detached" }); ' +
1510
+ 'return r.runs.map((x) => (x.answer === "" ? "empty" : x.answer) + ":" + x.status).join(",");';
1511
+ const { source, release } = heldChildrenSource(script);
1512
+ const runtime = await open({ source });
1513
+ try {
1514
+ const launched = launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1515
+ const parent = await waitFor(async () => {
1516
+ try {
1517
+ const run = await workflowRun(runtime);
1518
+ return run.childRunIds.length === 2 ? run : undefined;
1519
+ } catch {
1520
+ return undefined;
1521
+ }
1522
+ });
1523
+ for (const runId of parent.childRunIds) {
1524
+ assert.strictEqual((await runDoc(runtime, runId))?.execution, "detached");
1525
+ }
1526
+
1527
+ release();
1528
+ const result = await launched;
1529
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1530
+ const answer = result.view.answer ?? "";
1531
+ assert.ok(answer.includes("empty:queued,empty:queued"), answer);
1532
+ const last = answer.trimEnd().split("\n").at(-1) ?? "";
1533
+ assert.strictEqual(last.split(",").length, 2, answer);
1534
+ } finally {
1535
+ await runtime.close();
1536
+ }
1537
+ }, 60_000);
1538
+
1539
+ it("a script launch budgets per child", async () => {
1540
+ const script =
1541
+ 'await tools.launch_many({ children: [{ agent: "scout", task: "a", maxTurns: 60 }, ' +
1542
+ '{ agent: "scout", task: "b" }] }); return "done";';
1543
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
1544
+ try {
1545
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1546
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1547
+ const parent = await workflowRun(runtime);
1548
+ const docs = await children(runtime, parent);
1549
+ assert.deepStrictEqual(
1550
+ docs.map((entry) => entry.doc?.maxTurns),
1551
+ [60, 120],
1552
+ );
1553
+ } finally {
1554
+ await runtime.close();
1555
+ }
1556
+ }, 60_000);
1557
+
1558
+ it("the script tool descriptions state the detached answer", () => {
1559
+ const current = Ref.makeUnsafe<SessionHandle | undefined>(undefined);
1560
+ const descriptions = new Map(runTools(current).map((tool) => [tool.name, tool.description]));
1561
+ for (const name of ["launch", "launch_many"]) {
1562
+ const description = descriptions.get(name) ?? "";
1563
+ assert.ok(description.includes('execution: "detached"'), description);
1564
+ assert.ok(description.includes("empty"), description);
1565
+ }
1566
+ });