@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,1294 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { AgentDoc, MemoryStorage, type Harness, type Storage } from "@earendil-works/pi-durable";
3
+ import { compile } from "@earendil-works/pi-schema";
4
+ import { assert, it } from "@effect/vitest";
5
+ import { rejects } from "../../test-support/assertions.ts";
6
+ import { makeTempDir } from "../../test-support/platform.ts";
7
+ import { countingRuntime } from "../../test-support/counting-runtime.ts";
8
+ import { stubHostSource, type StubModelSource } from "../../test-support/stub-model-source.ts";
9
+ import { makeStubPi } from "../../test-support/stub-pi.ts";
10
+ import { createCatalogue, defineAgent, type DefinitionCatalogue } from "../domain/definitions.ts";
11
+ import { registerDelegateTools } from "./tools.ts";
12
+ import type { RunView } from "../domain/view.ts";
13
+ import { launch, type HostDefaults } from "../domain/orchestration/launch.ts";
14
+ import { RunDoc, RunIndexDoc } from "../domain/run-records.ts";
15
+ import { ToolkitDoc } from "../domain/toolkit.ts";
16
+ import { CODING_EXTENSION, GATE_GUARD_EXTENSION } from "../domain/names.ts";
17
+ import { nullLogSink, type LogFields, type LogLevel, type LogSink } from "../runtime/log.ts";
18
+ import { HostModelAdapter } from "../runtime/models.ts";
19
+ import { storePathFor, type SessionIdentity, type SessionRuntime } from "../runtime/session.ts";
20
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
21
+ import type { SessionHandle } from "../runtime/handle.ts";
22
+ import { handleFor } from "../../test-support/session-handle.ts";
23
+ import { Effect, Ref } from "effect";
24
+
25
+ const host: HostDefaults = {
26
+ model: { provider: "stub", modelId: "stub-1" },
27
+ thinkingLevel: "low",
28
+ };
29
+
30
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
31
+ const sessionDir = await makeTempDir("delegates-launch-");
32
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
33
+ };
34
+
35
+ const open = async (
36
+ options: {
37
+ readonly identity?: SessionIdentity;
38
+ readonly storage?: Storage;
39
+ readonly hang?: boolean;
40
+ readonly text?: string;
41
+ readonly failAt?: readonly number[];
42
+ readonly failMessage?: string;
43
+ readonly log?: LogSink;
44
+ readonly catalogue?: DefinitionCatalogue;
45
+ readonly source?: StubModelSource;
46
+ } = {},
47
+ ): Promise<TestSession> =>
48
+ openTestSession({
49
+ identity: options.identity ?? (await identityFor("s-1")),
50
+ models: new HostModelAdapter(
51
+ options.source ??
52
+ stubHostSource({
53
+ ...(options.hang === undefined ? {} : { hang: options.hang }),
54
+ ...(options.text === undefined ? {} : { text: options.text }),
55
+ ...(options.failAt === undefined ? {} : { failAt: options.failAt }),
56
+ ...(options.failMessage === undefined ? {} : { failMessage: options.failMessage }),
57
+ }),
58
+ ),
59
+ ...(options.storage === undefined ? {} : { storage: options.storage }),
60
+ ...(options.log === undefined ? {} : { log: options.log }),
61
+ ...(options.catalogue === undefined ? {} : { catalogue: options.catalogue }),
62
+ });
63
+
64
+ const depsFor = (runtime: SessionRuntime, waitMs = 5_000) => ({
65
+ runtime,
66
+ catalogue: createCatalogue(),
67
+ host,
68
+ waitMs,
69
+ });
70
+
71
+ const childAgent = (harness: Harness, childId: number) =>
72
+ harness.snapshot(AgentDoc, childId as never, BACKGROUND_CONTEXT);
73
+
74
+ const registeredTools = (runtime: SessionRuntime, definitions = createCatalogue()) => {
75
+ const stub = makeStubPi({ settings: { packages: [] } });
76
+ registerDelegateTools(stub.api, {
77
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
78
+ catalogue: definitions,
79
+ host,
80
+ launchWaitMs: () => 5_000,
81
+ log: () => nullLogSink,
82
+ });
83
+ return stub;
84
+ };
85
+
86
+ it("delegate_launch accepts a workflow request", async () => {
87
+ const composer = defineAgent({
88
+ name: "composer",
89
+ role: "Workflow composer",
90
+ prompt: { role: "You compose workflows." },
91
+ tools: ["read"],
92
+ extensions: [CODING_EXTENSION],
93
+ approval: { gates: [] },
94
+ codemode: "runs",
95
+ });
96
+ const source = stubHostSource({
97
+ respond: ({ systemPrompt, messages }) => {
98
+ if (!systemPrompt.includes("verbatim")) return { text: "child" };
99
+ const answered = messages.some((message) => message.role === "toolResult");
100
+ return answered
101
+ ? { text: "42" }
102
+ : { toolCall: { name: "codemode", arguments: { code: "return 6 * 7" } } };
103
+ },
104
+ });
105
+ const runtime = await open({ source, catalogue: createCatalogue([composer]) });
106
+ try {
107
+ const stub = registeredTools(runtime, createCatalogue([composer]));
108
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
109
+ parameters: object;
110
+ execute: (
111
+ id: string,
112
+ params: unknown,
113
+ signal: undefined,
114
+ onUpdate: undefined,
115
+ ctx: unknown,
116
+ ) => Promise<{
117
+ content: readonly { readonly text: string }[];
118
+ details?: { readonly run?: { readonly mode: string } };
119
+ }>;
120
+ };
121
+ const validator = compile(tool.parameters);
122
+ const request = {
123
+ request: { kind: "workflow", agent: "composer", script: "return 6 * 7" },
124
+ };
125
+ assert.strictEqual(validator.check(request), true);
126
+ const result = await tool.execute("", request, undefined, undefined, stub.context);
127
+ assert.strictEqual(result.content[0]?.text, "42");
128
+ assert.strictEqual(result.details?.run?.mode, "workflow");
129
+ } finally {
130
+ await runtime.close();
131
+ }
132
+ }, 30_000);
133
+
134
+ /** Every `maxTurns` description the schema carries, wherever a request shape nests it. */
135
+ const maxTurnsDescriptions = (value: unknown, found: string[] = []): string[] => {
136
+ if (Array.isArray(value)) {
137
+ for (const item of value) maxTurnsDescriptions(item, found);
138
+ return found;
139
+ }
140
+ if (value === null || typeof value !== "object") return found;
141
+ const record = value as Record<string, unknown>;
142
+ const properties = record.properties;
143
+ if (properties !== null && typeof properties === "object") {
144
+ const budget = (properties as Record<string, unknown>).maxTurns;
145
+ if (budget !== null && typeof budget === "object") {
146
+ const description = (budget as Record<string, unknown>).description;
147
+ if (typeof description === "string") found.push(description);
148
+ }
149
+ }
150
+ for (const child of Object.values(record)) maxTurnsDescriptions(child, found);
151
+ return found;
152
+ };
153
+
154
+ it("the launch schema carries the budget floor on every maxTurns field", async () => {
155
+ // An agent sizes a budget from the wire text, so every budget field carries it.
156
+ const runtime = await open();
157
+ try {
158
+ const stub = registeredTools(runtime);
159
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
160
+ parameters: object;
161
+ };
162
+ const descriptions = maxTurnsDescriptions(tool.parameters);
163
+ // One per shape that takes a budget: single, fanout child, fanout request,
164
+ // reviewer and review request.
165
+ assert.strictEqual(descriptions.length, 5, "every request shape has one maxTurns field");
166
+ for (const description of descriptions) {
167
+ assert.ok(
168
+ description.includes("never goes below one round"),
169
+ `the budget description states the floor: ${description}`,
170
+ );
171
+ assert.ok(
172
+ description.includes("configured ceiling"),
173
+ `the budget description states the ceiling: ${description}`,
174
+ );
175
+ }
176
+ } finally {
177
+ await runtime.close();
178
+ }
179
+ });
180
+
181
+ it("the control parameters require the field of each action", async () => {
182
+ const runtime = await open();
183
+ try {
184
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_control") as {
185
+ parameters: object;
186
+ };
187
+ const validator = compile(tool.parameters);
188
+ assert.strictEqual(validator.check({ action: "steer", run: "r-1" }), false);
189
+ assert.strictEqual(validator.check({ action: "steer", run: "r-1", message: "go" }), true);
190
+ assert.strictEqual(validator.check({ action: "approve", run: "r-1" }), false);
191
+ assert.strictEqual(validator.check({ action: "deny", run: "r-1" }), false);
192
+ assert.strictEqual(validator.check({ action: "approve", run: "r-1", gate: "deploy" }), true);
193
+ assert.strictEqual(validator.check({ action: "stop", run: "r-1" }), true);
194
+ assert.strictEqual(validator.check({ action: "resume", run: "r-1" }), true);
195
+ } finally {
196
+ await runtime.close();
197
+ }
198
+ });
199
+
200
+ it("the control card reads a decline or refusal line instead of a launch placeholder", async () => {
201
+ const runtime = await open();
202
+ try {
203
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_control") as {
204
+ renderResult: (
205
+ result: {
206
+ readonly content: readonly { readonly type: string; readonly text: string }[];
207
+ readonly details?: unknown;
208
+ },
209
+ options: { readonly expanded: boolean },
210
+ ) => { readonly render: () => string[] };
211
+ };
212
+ const run: RunView = {
213
+ runId: "run:1",
214
+ definition: "scout",
215
+ mode: "single",
216
+ lane: "default",
217
+ conversationId: null,
218
+ taskId: null,
219
+ status: "answered",
220
+ answer: "done",
221
+ durationMs: null,
222
+ children: [],
223
+ missing: [],
224
+ gates: [],
225
+ requests: [],
226
+ diagnostic: null,
227
+ execution: "wait",
228
+ maxTurns: null,
229
+ failure: null,
230
+ };
231
+ assert.strictEqual(
232
+ tool.renderResult({ content: [], details: { run } }, { expanded: false }).render()[0],
233
+ "Delegate scout single answered: done",
234
+ );
235
+ assert.strictEqual(
236
+ tool
237
+ .renderResult(
238
+ { content: [{ type: "text", text: "decline run:1: cancelled" }], details: {} },
239
+ { expanded: false },
240
+ )
241
+ .render()[0],
242
+ "decline run:1: cancelled",
243
+ );
244
+ assert.strictEqual(
245
+ tool
246
+ .renderResult(
247
+ {
248
+ content: [{ type: "text", text: "Run r-1 not found." }],
249
+ details: { error: "Run r-1 not found." },
250
+ },
251
+ { expanded: false },
252
+ )
253
+ .render()[0],
254
+ "Run r-1 not found.",
255
+ );
256
+ } finally {
257
+ await runtime.close();
258
+ }
259
+ });
260
+
261
+ it("a refused control returns one error row and the status still reads", async () => {
262
+ const runtime = await open({ text: "done" });
263
+ try {
264
+ const stub = registeredTools(runtime);
265
+ const controlTool = stub.registrations.toolDefinitions.get("delegate_control") as {
266
+ execute: (
267
+ id: string,
268
+ params: unknown,
269
+ signal: undefined,
270
+ onUpdate: undefined,
271
+ ctx: unknown,
272
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
273
+ };
274
+ const result = await controlTool.execute(
275
+ "",
276
+ { action: "steer", run: "r-1" },
277
+ undefined,
278
+ undefined,
279
+ stub.context,
280
+ );
281
+ assert.strictEqual(result.content.length, 1);
282
+ assert.match(result.content[0]?.text ?? "", /steer/);
283
+ assert.match(result.content[0]?.text ?? "", /message/);
284
+
285
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
286
+ execute: (
287
+ id: string,
288
+ params: unknown,
289
+ signal: undefined,
290
+ onUpdate: undefined,
291
+ ctx: unknown,
292
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
293
+ };
294
+ const status = await statusTool.execute("", {}, undefined, undefined, stub.context);
295
+ assert.strictEqual(status.content.length, 1);
296
+ assert.ok(!(status.content[0]?.text ?? "").includes("Session failed"));
297
+ } finally {
298
+ await runtime.close();
299
+ }
300
+ });
301
+
302
+ it("status prints the answer of an answered single run", async () => {
303
+ const runtime = await open({ text: "done" });
304
+ try {
305
+ const result = await launch(
306
+ { kind: "single", agent: "scout", task: "look around" },
307
+ depsFor(runtime),
308
+ );
309
+ const stub = registeredTools(runtime);
310
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
311
+ execute: (
312
+ id: string,
313
+ params: unknown,
314
+ signal: undefined,
315
+ onUpdate: undefined,
316
+ ctx: unknown,
317
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
318
+ };
319
+ const status = await statusTool.execute(
320
+ "",
321
+ { run: result.view.runId },
322
+ undefined,
323
+ undefined,
324
+ stub.context,
325
+ );
326
+ assert.ok(
327
+ (status.content[0]?.text ?? "").includes(
328
+ `${result.view.runId} scout · answered · turns 120: done`,
329
+ ),
330
+ status.content[0]?.text ?? "",
331
+ );
332
+ } finally {
333
+ await runtime.close();
334
+ }
335
+ });
336
+
337
+ it("status for a single run prints no lane line", async () => {
338
+ const runtime = await open({ text: "done" });
339
+ try {
340
+ await launch({ kind: "single", agent: "scout", task: "look around" }, depsFor(runtime));
341
+ const fanout = await launch(
342
+ {
343
+ kind: "fanout",
344
+ lane: "review",
345
+ agents: [
346
+ { agent: "scout", task: "first" },
347
+ { agent: "scout", task: "second" },
348
+ ],
349
+ },
350
+ depsFor(runtime),
351
+ );
352
+ const stub = registeredTools(runtime);
353
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
354
+ execute: (
355
+ id: string,
356
+ params: unknown,
357
+ signal: undefined,
358
+ onUpdate: undefined,
359
+ ctx: unknown,
360
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
361
+ };
362
+ const status = await statusTool.execute(
363
+ "",
364
+ { run: fanout.view.runId },
365
+ undefined,
366
+ undefined,
367
+ stub.context,
368
+ );
369
+ const text = status.content[0]?.text ?? "";
370
+ assert.ok(!/running \d+, queued/.test(text), text);
371
+ assert.ok(!text.includes("review:"), text);
372
+ } finally {
373
+ await runtime.close();
374
+ }
375
+ });
376
+
377
+ it("launching a preset writes its toolkit into the child conversation", async () => {
378
+ const runtime = await open({ text: "hello" });
379
+ try {
380
+ const result = await launch(
381
+ { kind: "single", agent: "scout", task: "look around" },
382
+ depsFor(runtime),
383
+ );
384
+ assert.strictEqual(result.view.status, "answered");
385
+ assert.strictEqual(result.view.answer, "hello");
386
+
387
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
388
+ assert.ok(doc?.childConversationId !== null);
389
+ const childId = doc!.childConversationId!;
390
+ const agent = await childAgent(runtime.harness, childId);
391
+ assert.deepStrictEqual(agent?.tools, ["read"]);
392
+ assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION]);
393
+ assert.deepStrictEqual(agent?.model, host.model);
394
+ assert.strictEqual(agent?.thinkingLevel, "low");
395
+ assert.strictEqual(agent?.maxTurns, 120);
396
+ assert.ok(agent?.instructions?.includes("You explore"), String(agent?.instructions));
397
+
398
+ const toolkit = await runtime.harness.snapshot(
399
+ ToolkitDoc,
400
+ childId as never,
401
+ BACKGROUND_CONTEXT,
402
+ );
403
+ assert.strictEqual(toolkit?.definition, "scout");
404
+ assert.strictEqual(toolkit?.runId, result.view.runId);
405
+ assert.strictEqual(toolkit?.childRunId, result.view.runId);
406
+ assert.deepStrictEqual(toolkit?.approval.gates, []);
407
+ } finally {
408
+ await runtime.close();
409
+ }
410
+ });
411
+
412
+ it("an unknown definition name fails and lists the valid names", async () => {
413
+ const runtime = await open();
414
+ try {
415
+ await rejects(
416
+ launch({ kind: "single", agent: "nope", task: "look" }, depsFor(runtime)),
417
+ (error: unknown) =>
418
+ error instanceof Error &&
419
+ ["nope", "scout", "builder", "reviewer"].every((part) => error.message.includes(part)),
420
+ );
421
+ const index = await runtime.snapshot(RunIndexDoc);
422
+ assert.deepStrictEqual(index?.runIds ?? [], []);
423
+ } finally {
424
+ await runtime.close();
425
+ }
426
+ });
427
+
428
+ it("delegate_launch accepts an inline definition", async () => {
429
+ const runtime = await open({ text: "inline answer" });
430
+ try {
431
+ const stub = makeStubPi({ settings: { packages: [] } });
432
+ registerDelegateTools(stub.api, {
433
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
434
+ catalogue: createCatalogue(),
435
+ host,
436
+ launchWaitMs: () => 5_000,
437
+ log: () => nullLogSink,
438
+ });
439
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
440
+ execute: (
441
+ id: string,
442
+ params: unknown,
443
+ signal: undefined,
444
+ onUpdate: undefined,
445
+ ctx: unknown,
446
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
447
+ };
448
+ const result = await tool.execute(
449
+ "",
450
+ {
451
+ request: {
452
+ kind: "single",
453
+ agent: "nomad",
454
+ task: "look",
455
+ definition: {
456
+ name: "nomad",
457
+ role: "auditor",
458
+ prompt: { role: "audit the repo" },
459
+ tools: ["read"],
460
+ },
461
+ },
462
+ },
463
+ undefined,
464
+ undefined,
465
+ stub.context,
466
+ );
467
+ assert.strictEqual(result.content[0]?.text, "inline answer");
468
+ } finally {
469
+ await runtime.close();
470
+ }
471
+ });
472
+
473
+ it("delegate_launch calls the inspector hook only after a run is committed", async () => {
474
+ const runtime = await open({ text: "ok" });
475
+ try {
476
+ const seen: unknown[] = [];
477
+ const stub = makeStubPi({ settings: { packages: [] } });
478
+ registerDelegateTools(stub.api, {
479
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
480
+ catalogue: createCatalogue(),
481
+ host,
482
+ launchWaitMs: () => 5_000,
483
+ log: () => nullLogSink,
484
+ onRunCreated: (ctx) => {
485
+ seen.push(ctx);
486
+ },
487
+ });
488
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
489
+ execute: (
490
+ id: string,
491
+ params: unknown,
492
+ signal: undefined,
493
+ onUpdate: undefined,
494
+ ctx: unknown,
495
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
496
+ };
497
+ const result = await tool.execute(
498
+ "",
499
+ { request: { kind: "single", agent: "scout", task: "look" } },
500
+ undefined,
501
+ undefined,
502
+ stub.context,
503
+ );
504
+ assert.strictEqual(result.content[0]?.text, "ok");
505
+ assert.strictEqual(seen.length, 1);
506
+ assert.strictEqual(seen[0], stub.context);
507
+
508
+ const refused = await tool.execute(
509
+ "",
510
+ { request: { kind: "single", agent: "nope", task: "look" } },
511
+ undefined,
512
+ undefined,
513
+ stub.context,
514
+ );
515
+ assert.match(refused.content[0]?.text ?? "", /not found/);
516
+ assert.strictEqual(seen.length, 1);
517
+ } finally {
518
+ await runtime.close();
519
+ }
520
+ });
521
+
522
+ it("an inline definition tolerates unknown fields and names owner fields", async () => {
523
+ const runtime = await open({ text: "ok" });
524
+ try {
525
+ const stub = registeredTools(runtime);
526
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
527
+ parameters: object;
528
+ execute: (
529
+ id: string,
530
+ params: unknown,
531
+ signal: undefined,
532
+ onUpdate: undefined,
533
+ ctx: unknown,
534
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
535
+ };
536
+ const validator = compile(tool.parameters);
537
+ const definition = {
538
+ name: "nomad",
539
+ role: "auditor",
540
+ prompt: { role: "audit" },
541
+ tools: ["read"],
542
+ };
543
+ const request = (value: object) => ({
544
+ request: { kind: "single", agent: "nomad", task: "look", definition: value },
545
+ });
546
+ assert.strictEqual(validator.check(request({ ...definition, extra: true })), true);
547
+ assert.strictEqual(
548
+ validator.check(request({ ...definition, prompt: { ...definition.prompt, extra: true } })),
549
+ true,
550
+ );
551
+
552
+ const refused = await tool.execute(
553
+ "",
554
+ request({ ...definition, extensions: [] }),
555
+ undefined,
556
+ undefined,
557
+ stub.context,
558
+ );
559
+ assert.match(refused.content[0]?.text ?? "", /extensions/);
560
+ assert.match(refused.content[0]?.text ?? "", /only a registered definition/);
561
+ } finally {
562
+ await runtime.close();
563
+ }
564
+ });
565
+
566
+ it("an inline definition drops unknown fields before the request identity", async () => {
567
+ const runtime = await open({ hang: true });
568
+ try {
569
+ const stub = makeStubPi({ settings: { packages: [] } });
570
+ registerDelegateTools(stub.api, {
571
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
572
+ catalogue: createCatalogue(),
573
+ host,
574
+ launchWaitMs: () => 50,
575
+ log: () => nullLogSink,
576
+ });
577
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
578
+ execute: (
579
+ id: string,
580
+ params: unknown,
581
+ signal: undefined,
582
+ onUpdate: undefined,
583
+ ctx: unknown,
584
+ ) => Promise<{
585
+ content: readonly { readonly text: string }[];
586
+ details?: { readonly run?: { readonly runId: string } };
587
+ }>;
588
+ };
589
+ const definition = {
590
+ name: "nomad",
591
+ role: "auditor",
592
+ prompt: { role: "audit" },
593
+ tools: ["read"],
594
+ };
595
+ const launchOnce = (value: object) =>
596
+ tool.execute(
597
+ "",
598
+ { request: { kind: "single", agent: "nomad", task: "look", definition: value } },
599
+ undefined,
600
+ undefined,
601
+ stub.context,
602
+ );
603
+ const first = await launchOnce({ ...definition, extra: true });
604
+ const second = await launchOnce(definition);
605
+ assert.ok(first.details?.run?.runId);
606
+ assert.ok(second.details?.run?.runId);
607
+ assert.strictEqual(first.details?.run?.runId, second.details?.run?.runId);
608
+ const index = await runtime.snapshot(RunIndexDoc);
609
+ assert.strictEqual(index?.runIds.length, 1);
610
+ } finally {
611
+ await runtime.close();
612
+ }
613
+ });
614
+
615
+ it("an unresolved toolkit name is refused at launch", async () => {
616
+ const runtime = await open();
617
+ try {
618
+ const definition = defineAgent({
619
+ name: "needs-missing",
620
+ role: "audit",
621
+ prompt: { role: "audit" },
622
+ tools: ["read"],
623
+ extensions: ["missing-extension"],
624
+ approval: { gates: [] },
625
+ });
626
+ await rejects(
627
+ launch(
628
+ { kind: "single", agent: definition.name, task: "look" },
629
+ { ...depsFor(runtime), catalogue: createCatalogue([definition]) },
630
+ ),
631
+ (error: unknown) => error instanceof Error && error.message.includes("missing-extension"),
632
+ );
633
+ const index = await runtime.snapshot(RunIndexDoc);
634
+ assert.deepStrictEqual(index?.runIds ?? [], []);
635
+ } finally {
636
+ await runtime.close();
637
+ }
638
+ });
639
+
640
+ it("a repeat of a terminal launch starts the next attempt", async () => {
641
+ const runtime = await open();
642
+ try {
643
+ const request = { kind: "single", agent: "scout", task: "look around" } as const;
644
+ const first = await launch(request, depsFor(runtime));
645
+ const second = await launch(request, depsFor(runtime));
646
+ assert.notStrictEqual(first.view.runId, second.view.runId);
647
+
648
+ const index = await runtime.snapshot(RunIndexDoc);
649
+ assert.strictEqual(index?.runIds.length, 2);
650
+ const firstDoc = await runtime.snapshot(RunDoc, first.view.runId);
651
+ const secondDoc = await runtime.snapshot(RunDoc, second.view.runId);
652
+ assert.notStrictEqual(firstDoc?.childConversationId, secondDoc?.childConversationId);
653
+ assert.strictEqual(secondDoc?.attempt, 2);
654
+ } finally {
655
+ await runtime.close();
656
+ }
657
+ });
658
+
659
+ it("a launch past the soft deadline returns running", async () => {
660
+ const runtime = await open({ hang: true });
661
+ try {
662
+ const result = await launch(
663
+ { kind: "single", agent: "scout", task: "look around" },
664
+ depsFor(runtime, 50),
665
+ );
666
+ assert.strictEqual(result.view.status, "running");
667
+ assert.ok(result.text.includes(result.view.runId), result.text);
668
+ const index = await runtime.snapshot(RunIndexDoc);
669
+ assert.strictEqual(index?.runIds.length, 1);
670
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
671
+ const task = await runtime.harness.getTask(doc!.taskId as never, BACKGROUND_CONTEXT);
672
+ assert.notStrictEqual(task?.state.status, "terminal");
673
+ } finally {
674
+ await runtime.close();
675
+ }
676
+ });
677
+
678
+ it("the same launch after reopen reuses the unfinished run", async () => {
679
+ const identity = await identityFor("s-1");
680
+ const request = { kind: "single", agent: "scout", task: "look around" } as const;
681
+
682
+ const first = await open({ identity, hang: true });
683
+ const firstResult = await launch(request, depsFor(first, 50));
684
+ const firstDoc = await first.snapshot(RunDoc, firstResult.view.runId);
685
+ await first.close();
686
+
687
+ const second = await open({ identity, hang: true });
688
+ try {
689
+ const secondResult = await launch(request, depsFor(second, 50));
690
+ assert.strictEqual(secondResult.view.status, "running");
691
+ assert.strictEqual(secondResult.view.runId, firstResult.view.runId);
692
+ const index = await second.snapshot(RunIndexDoc);
693
+ assert.strictEqual(index?.runIds.length, 1);
694
+ const secondDoc = await second.snapshot(RunDoc, secondResult.view.runId);
695
+ assert.strictEqual(secondDoc?.childConversationId, firstDoc?.childConversationId);
696
+ assert.ok(storePathFor(identity).endsWith("delegates-s-1.sqlite"));
697
+ } finally {
698
+ await second.close();
699
+ }
700
+ });
701
+
702
+ it("cancelling the launch aborts the run", async () => {
703
+ const runtime = await open({ hang: true });
704
+ try {
705
+ const controller = new AbortController();
706
+ const pending = launch(
707
+ { kind: "single", agent: "scout", task: "look around" },
708
+ { ...depsFor(runtime, 5_000), signal: controller.signal },
709
+ );
710
+ setTimeout(() => controller.abort(), 25);
711
+ const result = await pending;
712
+ assert.strictEqual(result.view.status, "stopped");
713
+ assert.ok(result.text.includes("is stopped"), result.text);
714
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
715
+ assert.ok(doc?.childConversationId !== null);
716
+ } finally {
717
+ await runtime.close();
718
+ }
719
+ });
720
+
721
+ it("a memory-backed runtime launches without touching a store file", async () => {
722
+ const storage = new MemoryStorage();
723
+ const runtime = await open({ storage, text: "hello" });
724
+ try {
725
+ const result = await launch(
726
+ { kind: "single", agent: "builder", task: "build it" },
727
+ depsFor(runtime),
728
+ );
729
+ assert.strictEqual(result.view.status, "answered");
730
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
731
+ const agent = await childAgent(runtime.harness, doc!.childConversationId!);
732
+ assert.deepStrictEqual(agent?.tools, ["read", "bash", "write", "edit"]);
733
+ } finally {
734
+ await runtime.close();
735
+ }
736
+ });
737
+
738
+ it("a definition that selects only coding still gets the gate guard", async () => {
739
+ const deployer = defineAgent({
740
+ name: "deployer",
741
+ role: "Deploy agent",
742
+ prompt: { role: "You deploy things." },
743
+ tools: ["read"],
744
+ extensions: [CODING_EXTENSION],
745
+ approval: { gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }] },
746
+ });
747
+ const runtime = await open({ text: "ready" });
748
+ try {
749
+ const result = await launch(
750
+ { kind: "single", agent: "deployer", task: "deploy it" },
751
+ { ...depsFor(runtime), catalogue: createCatalogue([deployer]) },
752
+ );
753
+ assert.strictEqual(result.view.status, "answered");
754
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
755
+ const childId = doc!.childConversationId!;
756
+ const agent = await childAgent(runtime.harness, childId);
757
+ assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION, GATE_GUARD_EXTENSION]);
758
+ const toolkit = await runtime.harness.snapshot(
759
+ ToolkitDoc,
760
+ childId as never,
761
+ BACKGROUND_CONTEXT,
762
+ );
763
+ assert.deepStrictEqual(toolkit?.approval.gates, deployer.approval.gates);
764
+ } finally {
765
+ await runtime.close();
766
+ }
767
+ });
768
+
769
+ it("an inline definition cannot remove a registered approval rule", async () => {
770
+ const auditor = defineAgent({
771
+ name: "auditor",
772
+ role: "Audit agent",
773
+ prompt: { role: "You audit things." },
774
+ tools: ["read"],
775
+ extensions: [CODING_EXTENSION],
776
+ approval: { gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }] },
777
+ });
778
+ const runtime = await open({ text: "audited" });
779
+ try {
780
+ const result = await launch(
781
+ {
782
+ kind: "single",
783
+ agent: "auditor",
784
+ task: "audit it",
785
+ definition: {
786
+ name: "auditor",
787
+ role: "narrowed",
788
+ prompt: { role: "narrowed" },
789
+ tools: ["read"],
790
+ },
791
+ },
792
+ { ...depsFor(runtime), catalogue: createCatalogue([auditor]) },
793
+ );
794
+ assert.strictEqual(result.view.status, "answered");
795
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
796
+ const childId = doc!.childConversationId!;
797
+ const agent = await childAgent(runtime.harness, childId);
798
+ assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION, GATE_GUARD_EXTENSION]);
799
+ assert.deepStrictEqual(agent?.tools, ["read"]);
800
+ const toolkit = await runtime.harness.snapshot(
801
+ ToolkitDoc,
802
+ childId as never,
803
+ BACKGROUND_CONTEXT,
804
+ );
805
+ assert.deepStrictEqual(toolkit?.approval.gates, auditor.approval.gates);
806
+ } finally {
807
+ await runtime.close();
808
+ }
809
+ });
810
+
811
+ it("a retry of a failed launch starts the next attempt", async () => {
812
+ const runtime = await open({ failAt: [1, 2] });
813
+ try {
814
+ const request = { kind: "single", agent: "scout", task: "look around" } as const;
815
+ const first = await launch(request, depsFor(runtime));
816
+ assert.strictEqual(first.view.status, "failed");
817
+ const second = await launch(request, depsFor(runtime));
818
+ assert.strictEqual(second.view.status, "failed");
819
+ assert.notStrictEqual(second.view.runId, first.view.runId);
820
+
821
+ const index = await runtime.snapshot(RunIndexDoc);
822
+ assert.deepStrictEqual(index?.runIds, [first.view.runId, second.view.runId]);
823
+ const firstDoc = await runtime.snapshot(RunDoc, first.view.runId);
824
+ const secondDoc = await runtime.snapshot(RunDoc, second.view.runId);
825
+ assert.strictEqual(secondDoc?.attempt, 2);
826
+ assert.notStrictEqual(secondDoc?.childConversationId, firstDoc?.childConversationId);
827
+ } finally {
828
+ await runtime.close();
829
+ }
830
+ });
831
+
832
+ const recordingSink = () => {
833
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
834
+ const sink: LogSink = {
835
+ write: (level, code, fields = {}) => {
836
+ entries.push({ level, code, fields });
837
+ },
838
+ };
839
+ return { sink, entries };
840
+ };
841
+
842
+ it("each delegate tool logs its name and the error", async () => {
843
+ const { sink, entries } = recordingSink();
844
+ const stub = makeStubPi({ settings: { packages: [] } });
845
+ registerDelegateTools(stub.api, {
846
+ session: Ref.makeUnsafe<SessionHandle | undefined>(undefined),
847
+ catalogue: createCatalogue(),
848
+ host,
849
+ launchWaitMs: () => 5_000,
850
+ log: () => sink,
851
+ });
852
+ const execute = async (name: string, params: unknown) => {
853
+ const tool = stub.registrations.toolDefinitions.get(name) as {
854
+ execute: (
855
+ id: string,
856
+ params: unknown,
857
+ signal: undefined,
858
+ onUpdate: undefined,
859
+ ctx: unknown,
860
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
861
+ };
862
+ const result = await tool.execute("", params, undefined, undefined, stub.context);
863
+ assert.match(
864
+ result.content[0]?.text ?? "",
865
+ /The delegation runtime is not ready; start a session first\./,
866
+ );
867
+ };
868
+
869
+ await execute("delegate_launch", {
870
+ request: { kind: "single", agent: "scout", task: "look" },
871
+ });
872
+ await execute("delegate_control", { action: "stop", run: "run:x" });
873
+ await execute("delegate_status", {});
874
+
875
+ assert.deepStrictEqual(
876
+ entries.map((entry) => [entry.level, entry.code, entry.fields.tool, entry.fields.action]),
877
+ [
878
+ ["error", "tool.not_ready", "delegate_launch", undefined],
879
+ ["error", "tool.not_ready", "delegate_control", "stop"],
880
+ ["error", "tool.not_ready", "delegate_status", undefined],
881
+ ],
882
+ );
883
+ for (const entry of entries) assert.strictEqual(entry.fields.error, "Error");
884
+ });
885
+
886
+ it("malformed tool arguments are refused and logged", async () => {
887
+ const { sink, entries } = recordingSink();
888
+ const runtime = await open();
889
+ try {
890
+ const stub = makeStubPi({ settings: { packages: [] } });
891
+ registerDelegateTools(stub.api, {
892
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
893
+ catalogue: createCatalogue(),
894
+ host,
895
+ launchWaitMs: () => 5_000,
896
+ log: () => sink,
897
+ });
898
+ const execute = async (name: string, params: unknown) => {
899
+ const tool = stub.registrations.toolDefinitions.get(name) as {
900
+ execute: (
901
+ id: string,
902
+ params: unknown,
903
+ signal: undefined,
904
+ onUpdate: undefined,
905
+ ctx: unknown,
906
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
907
+ };
908
+ return tool.execute("", params, undefined, undefined, stub.context);
909
+ };
910
+
911
+ const launch = await execute("delegate_launch", {
912
+ request: { kind: "single", agent: 1, task: "look" },
913
+ });
914
+ assert.ok((launch.content[0]?.text ?? "").length > 0);
915
+ const control = await execute("delegate_control", { action: "stop", run: 5 });
916
+ assert.match(control.content[0]?.text ?? "", /run is required/);
917
+ const status = await execute("delegate_status", { run: 5 });
918
+ assert.ok((status.content[0]?.text ?? "").length > 0);
919
+
920
+ assert.deepStrictEqual(
921
+ entries.map((entry) => [entry.code, entry.fields.tool]),
922
+ [
923
+ ["tool.not_ready", "delegate_launch"],
924
+ ["tool.not_ready", "delegate_control"],
925
+ ["tool.not_ready", "delegate_status"],
926
+ ],
927
+ );
928
+ // A refused request never claims a run.
929
+ assert.deepStrictEqual((await runtime.snapshot(RunIndexDoc))?.runIds ?? [], []);
930
+ } finally {
931
+ await runtime.close();
932
+ }
933
+ });
934
+
935
+ const runStatus = async (runtime: SessionRuntime, params: unknown) => {
936
+ const stub = registeredTools(runtime);
937
+ const tool = stub.registrations.toolDefinitions.get("delegate_status") as {
938
+ execute: (
939
+ id: string,
940
+ params: unknown,
941
+ signal: undefined,
942
+ onUpdate: undefined,
943
+ ctx: unknown,
944
+ ) => Promise<{
945
+ content: readonly { readonly text: string }[];
946
+ details?: { readonly runs: readonly { readonly runId: string }[] };
947
+ }>;
948
+ };
949
+ return tool.execute("", params, undefined, undefined, stub.context);
950
+ };
951
+
952
+ it("status reads only the requested run", async () => {
953
+ const runtime = await open({ text: "done" });
954
+ try {
955
+ const first = await launch({ kind: "single", agent: "scout", task: "first" }, depsFor(runtime));
956
+ const target = await launch(
957
+ { kind: "single", agent: "scout", task: "second" },
958
+ depsFor(runtime),
959
+ );
960
+ const third = await launch({ kind: "single", agent: "scout", task: "third" }, depsFor(runtime));
961
+
962
+ const counted = countingRuntime(runtime);
963
+ const status = await runStatus(counted.runtime, { run: target.view.runId });
964
+ const text = status.content[0]?.text ?? "";
965
+ assert.ok(text.includes(`${target.view.runId} scout · answered · turns 120: done`), text);
966
+ for (const other of [first.view.runId, third.view.runId]) {
967
+ assert.strictEqual(counted.count("delegates.run", other), 0, other);
968
+ }
969
+ } finally {
970
+ await runtime.close();
971
+ }
972
+ });
973
+
974
+ it("status shows the run's reviews without reading other reviews", async () => {
975
+ const runtime = await open({ text: '{"disposition":"accepted"}' });
976
+ try {
977
+ const reviewers = [{ agent: "reviewer" }, { agent: "reviewer" }];
978
+ const first = await launch(
979
+ { kind: "review", task: "first", reviewers },
980
+ depsFor(runtime, 20_000),
981
+ );
982
+ const second = await launch(
983
+ { kind: "review", task: "second", reviewers },
984
+ depsFor(runtime, 20_000),
985
+ );
986
+
987
+ const counted = countingRuntime(runtime);
988
+ const status = await runStatus(counted.runtime, { run: first.view.runId });
989
+ const text = status.content[0]?.text ?? "";
990
+ assert.ok(text.includes("reviewer 0"), text);
991
+ assert.ok(text.includes("reviewer 1"), text);
992
+ assert.strictEqual(counted.count("delegates.review", second.view.runId), 0);
993
+ } finally {
994
+ await runtime.close();
995
+ }
996
+ });
997
+
998
+ it("status for an unknown run returns not found", async () => {
999
+ const runtime = await open();
1000
+ try {
1001
+ const missing = await runStatus(runtime, { run: "run:missing" });
1002
+ assert.strictEqual(missing.content[0]?.text, "Run run:missing not found.");
1003
+ assert.deepStrictEqual(missing.details?.runs, []);
1004
+ } finally {
1005
+ await runtime.close();
1006
+ }
1007
+ });
1008
+
1009
+ it("the launch card prints the run mode in both forms", async () => {
1010
+ const runtime = await open();
1011
+ try {
1012
+ const stub = registeredTools(runtime);
1013
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
1014
+ renderResult: (
1015
+ result: { readonly details: { readonly run: RunView } },
1016
+ options: { readonly expanded: boolean },
1017
+ ) => { readonly render: () => string[] };
1018
+ };
1019
+ const run: RunView = {
1020
+ runId: "run:wf#1",
1021
+ definition: "composer",
1022
+ mode: "workflow",
1023
+ lane: "workflow",
1024
+ conversationId: null,
1025
+ taskId: null,
1026
+ status: "answered",
1027
+ answer: "42",
1028
+ durationMs: null,
1029
+ children: [],
1030
+ missing: [],
1031
+ gates: [],
1032
+ requests: [],
1033
+ diagnostic: null,
1034
+ execution: "wait",
1035
+ maxTurns: null,
1036
+ failure: null,
1037
+ };
1038
+ assert.strictEqual(
1039
+ tool.renderResult({ details: { run } }, { expanded: false }).render()[0],
1040
+ "Delegate composer workflow answered: 42",
1041
+ );
1042
+ const expanded = tool.renderResult({ details: { run } }, { expanded: true }).render()[0] ?? "";
1043
+ assert.ok(
1044
+ expanded.includes("definition composer · workflow · lane workflow · answered"),
1045
+ expanded,
1046
+ );
1047
+ } finally {
1048
+ await runtime.close();
1049
+ }
1050
+ });
1051
+
1052
+ it("a tool call registered before a swap runs in the new session", async () => {
1053
+ const first = await open();
1054
+ const second = await open({ identity: await identityFor("s-2") });
1055
+ try {
1056
+ const stub = makeStubPi({ settings: { packages: [] } });
1057
+ const current = Ref.makeUnsafe<SessionHandle | undefined>(handleFor(first));
1058
+ registerDelegateTools(stub.api, {
1059
+ session: current,
1060
+ catalogue: createCatalogue(),
1061
+ host,
1062
+ launchWaitMs: () => 5_000,
1063
+ log: () => nullLogSink,
1064
+ });
1065
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
1066
+ execute: (
1067
+ id: string,
1068
+ params: unknown,
1069
+ signal: undefined,
1070
+ onUpdate: undefined,
1071
+ ctx: unknown,
1072
+ ) => Promise<{ details?: { readonly run?: { readonly runId: string } } }>;
1073
+ };
1074
+
1075
+ // The registration stays; only the Ref moves to the replacement session.
1076
+ const registered = tool.execute.bind(tool);
1077
+ await Effect.runPromise(Ref.set(current, handleFor(second)));
1078
+ const result = await registered(
1079
+ "",
1080
+ { request: { kind: "single", agent: "scout", task: "look around" } },
1081
+ undefined,
1082
+ undefined,
1083
+ stub.context,
1084
+ );
1085
+
1086
+ const runId = result.details?.run?.runId;
1087
+ assert.ok(runId !== undefined && runId.length > 0, JSON.stringify(result));
1088
+ assert.ok((await second.snapshot(RunDoc, runId)) !== undefined);
1089
+ assert.strictEqual(await first.snapshot(RunDoc, runId), undefined);
1090
+ } finally {
1091
+ await first.close();
1092
+ await second.close();
1093
+ }
1094
+ }, 20_000);
1095
+
1096
+ it("status prints the detail after the reason on the run and child lines", async () => {
1097
+ const { sink, entries } = recordingSink();
1098
+ const runtime = await open({
1099
+ text: "ok",
1100
+ failAt: [2],
1101
+ failMessage: "invalid request: unknown field",
1102
+ log: sink,
1103
+ });
1104
+ try {
1105
+ const fanout = await launch(
1106
+ {
1107
+ kind: "fanout",
1108
+ lane: "review",
1109
+ agents: [
1110
+ { agent: "scout", task: "first" },
1111
+ { agent: "scout", task: "second" },
1112
+ ],
1113
+ },
1114
+ depsFor(runtime),
1115
+ );
1116
+ const stub = registeredTools(runtime);
1117
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
1118
+ execute: (
1119
+ id: string,
1120
+ params: unknown,
1121
+ signal: undefined,
1122
+ onUpdate: undefined,
1123
+ ctx: unknown,
1124
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
1125
+ };
1126
+ const status = await statusTool.execute(
1127
+ "",
1128
+ { run: fanout.view.runId },
1129
+ undefined,
1130
+ undefined,
1131
+ stub.context,
1132
+ );
1133
+ const text = status.content[0]?.text ?? "";
1134
+ assert.ok(
1135
+ new RegExp(
1136
+ `child 1 ${fanout.view.runId}:child:1 scout failed \\(model_error\\): invalid request: unknown field`,
1137
+ ).test(text),
1138
+ text,
1139
+ );
1140
+ assert.strictEqual(text.split("failed (model_error)").length - 1, 1, text);
1141
+ assert.strictEqual(entries.filter((entry) => entry.code === "run.failed").length, 1);
1142
+ } finally {
1143
+ await runtime.close();
1144
+ }
1145
+ });
1146
+
1147
+ it("the launch wire schema accepts execution and rejects an unknown value", async () => {
1148
+ const runtime = await open();
1149
+ try {
1150
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_launch") as {
1151
+ parameters: object;
1152
+ };
1153
+ const validator = compile(tool.parameters);
1154
+ for (const execution of ["detached", "wait"]) {
1155
+ assert.strictEqual(
1156
+ validator.check({
1157
+ request: { kind: "single", agent: "scout", task: "look", execution },
1158
+ }),
1159
+ true,
1160
+ execution,
1161
+ );
1162
+ }
1163
+ assert.strictEqual(
1164
+ validator.check({
1165
+ request: { kind: "single", agent: "scout", task: "look", execution: "later" },
1166
+ }),
1167
+ false,
1168
+ );
1169
+ } finally {
1170
+ await runtime.close();
1171
+ }
1172
+ });
1173
+
1174
+ it("status prints the resolved budget on the child line", async () => {
1175
+ const runtime = await open({ text: "done" });
1176
+ try {
1177
+ const fanout = await launch(
1178
+ {
1179
+ kind: "fanout",
1180
+ lane: "review",
1181
+ agents: [
1182
+ { agent: "scout", task: "first" },
1183
+ { agent: "scout", task: "second" },
1184
+ ],
1185
+ },
1186
+ depsFor(runtime),
1187
+ );
1188
+ const stub = registeredTools(runtime);
1189
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
1190
+ execute: (
1191
+ id: string,
1192
+ params: unknown,
1193
+ signal: undefined,
1194
+ onUpdate: undefined,
1195
+ ctx: unknown,
1196
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
1197
+ };
1198
+ const status = await statusTool.execute(
1199
+ "",
1200
+ { run: fanout.view.runId },
1201
+ undefined,
1202
+ undefined,
1203
+ stub.context,
1204
+ );
1205
+ const text = status.content[0]?.text ?? "";
1206
+ for (const child of [0, 1]) {
1207
+ assert.ok(
1208
+ text.includes(
1209
+ `child ${child} ${fanout.view.runId}:child:${child} scout answered · turns 120`,
1210
+ ),
1211
+ text,
1212
+ );
1213
+ }
1214
+ } finally {
1215
+ await runtime.close();
1216
+ }
1217
+ });
1218
+
1219
+ it("status prints a single run's budget on its run line", async () => {
1220
+ const runtime = await open({ text: "done" });
1221
+ try {
1222
+ const single = await launch(
1223
+ { kind: "single", agent: "scout", task: "look", maxTurns: 60 },
1224
+ depsFor(runtime),
1225
+ );
1226
+ const stub = registeredTools(runtime);
1227
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
1228
+ execute: (
1229
+ id: string,
1230
+ params: unknown,
1231
+ signal: undefined,
1232
+ onUpdate: undefined,
1233
+ ctx: unknown,
1234
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
1235
+ };
1236
+ const status = await statusTool.execute(
1237
+ "",
1238
+ { run: single.view.runId },
1239
+ undefined,
1240
+ undefined,
1241
+ stub.context,
1242
+ );
1243
+ const text = status.content[0]?.text ?? "";
1244
+ // A single run prints no child line, so its budget rides on the run line.
1245
+ assert.ok(text.includes("scout · answered · turns 60: done"), text);
1246
+ } finally {
1247
+ await runtime.close();
1248
+ }
1249
+ });
1250
+
1251
+ it("the group wire schemas accept execution and a per-child budget", async () => {
1252
+ const runtime = await open();
1253
+ try {
1254
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_launch") as {
1255
+ parameters: object;
1256
+ };
1257
+ const validator = compile(tool.parameters);
1258
+ assert.strictEqual(
1259
+ validator.check({
1260
+ request: {
1261
+ kind: "fanout",
1262
+ lane: "review",
1263
+ agents: [{ agent: "scout", task: "a", maxTurns: 60 }],
1264
+ execution: "detached",
1265
+ },
1266
+ }),
1267
+ true,
1268
+ );
1269
+ assert.strictEqual(
1270
+ validator.check({
1271
+ request: {
1272
+ kind: "review",
1273
+ task: "review",
1274
+ reviewers: [{ agent: "reviewer", maxTurns: 40 }],
1275
+ execution: "detached",
1276
+ },
1277
+ }),
1278
+ true,
1279
+ );
1280
+ assert.strictEqual(
1281
+ validator.check({
1282
+ request: {
1283
+ kind: "fanout",
1284
+ lane: "review",
1285
+ agents: [{ agent: "scout", task: "a" }],
1286
+ execution: "later",
1287
+ },
1288
+ }),
1289
+ false,
1290
+ );
1291
+ } finally {
1292
+ await runtime.close();
1293
+ }
1294
+ });