@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -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 +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -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 +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,993 @@
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 { mkdtemp } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { assert, it } from "@effect/vitest";
8
+ import { rejects } from "../../test-support/assertions.ts";
9
+ import { countingRuntime } from "../../test-support/counting-runtime.ts";
10
+ import { stubHostSource, type StubModelSource } from "../../test-support/stub-model-source.ts";
11
+ import { makeStubPi } from "../../test-support/stub-pi.ts";
12
+ import { createCatalogue, defineAgent, type DefinitionCatalogue } from "../domain/definitions.ts";
13
+ import { registerDelegateTools } from "./tools.ts";
14
+ import type { RunView } from "../domain/view.ts";
15
+ import { launch, type HostDefaults } from "../domain/orchestration/launch.ts";
16
+ import { RunDoc, RunIndexDoc } from "../domain/run-records.ts";
17
+ import { ToolkitDoc } from "../domain/toolkit.ts";
18
+ import { CODING_EXTENSION, GATE_GUARD_EXTENSION } from "../domain/names.ts";
19
+ import { nullLogSink, type LogFields, type LogLevel, type LogSink } from "../runtime/log.ts";
20
+ import { HostModelAdapter } from "../runtime/models.ts";
21
+ import {
22
+ openSessionRuntime,
23
+ storePathFor,
24
+ type SessionIdentity,
25
+ type SessionRuntime,
26
+ } from "../runtime/session.ts";
27
+
28
+ const host: HostDefaults = {
29
+ model: { provider: "stub", modelId: "stub-1" },
30
+ thinkingLevel: "low",
31
+ };
32
+
33
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
34
+ const sessionDir = await mkdtemp(join(tmpdir(), "delegates-launch-"));
35
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
36
+ };
37
+
38
+ const open = async (
39
+ options: {
40
+ readonly identity?: SessionIdentity;
41
+ readonly storage?: Storage;
42
+ readonly hang?: boolean;
43
+ readonly text?: string;
44
+ readonly failAt?: readonly number[];
45
+ readonly catalogue?: DefinitionCatalogue;
46
+ readonly source?: StubModelSource;
47
+ } = {},
48
+ ): Promise<SessionRuntime> =>
49
+ openSessionRuntime({
50
+ identity: options.identity ?? (await identityFor("s-1")),
51
+ models: new HostModelAdapter(
52
+ options.source ??
53
+ stubHostSource({
54
+ ...(options.hang === undefined ? {} : { hang: options.hang }),
55
+ ...(options.text === undefined ? {} : { text: options.text }),
56
+ ...(options.failAt === undefined ? {} : { failAt: options.failAt }),
57
+ }),
58
+ ),
59
+ ...(options.storage === undefined ? {} : { storage: options.storage }),
60
+ ...(options.catalogue === undefined ? {} : { catalogue: options.catalogue }),
61
+ });
62
+
63
+ const depsFor = (runtime: SessionRuntime, waitMs = 5_000) => ({
64
+ runtime,
65
+ catalogue: createCatalogue(),
66
+ host,
67
+ waitMs,
68
+ });
69
+
70
+ const childAgent = (harness: Harness, childId: number) =>
71
+ harness.snapshot(AgentDoc, childId as never, BACKGROUND_CONTEXT);
72
+
73
+ const registeredTools = (runtime: SessionRuntime, definitions = createCatalogue()) => {
74
+ const stub = makeStubPi({ settings: { packages: [] } });
75
+ registerDelegateTools(stub.api, {
76
+ runtime: () => runtime,
77
+ catalogue: definitions,
78
+ host,
79
+ launchWaitMs: () => 5_000,
80
+ log: () => nullLogSink,
81
+ });
82
+ return stub;
83
+ };
84
+
85
+ it("delegate_launch accepts a workflow request", async () => {
86
+ const composer = defineAgent({
87
+ name: "composer",
88
+ role: "Workflow composer",
89
+ prompt: { role: "You compose workflows." },
90
+ tools: ["read"],
91
+ extensions: [CODING_EXTENSION],
92
+ approval: { gates: [] },
93
+ codemode: "runs",
94
+ });
95
+ const source = stubHostSource({
96
+ respond: ({ systemPrompt, messages }) => {
97
+ if (!systemPrompt.includes("verbatim")) return { text: "child" };
98
+ const answered = messages.some((message) => message.role === "toolResult");
99
+ return answered
100
+ ? { text: "42" }
101
+ : { toolCall: { name: "codemode", arguments: { code: "return 6 * 7" } } };
102
+ },
103
+ });
104
+ const runtime = await open({ source, catalogue: createCatalogue([composer]) });
105
+ try {
106
+ const stub = registeredTools(runtime, createCatalogue([composer]));
107
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
108
+ parameters: object;
109
+ execute: (
110
+ id: string,
111
+ params: unknown,
112
+ signal: undefined,
113
+ onUpdate: undefined,
114
+ ctx: unknown,
115
+ ) => Promise<{
116
+ content: readonly { readonly text: string }[];
117
+ details?: { readonly run?: { readonly mode: string } };
118
+ }>;
119
+ };
120
+ const validator = compile(tool.parameters);
121
+ const request = {
122
+ request: { kind: "workflow", agent: "composer", script: "return 6 * 7" },
123
+ };
124
+ assert.strictEqual(validator.check(request), true);
125
+ const result = await tool.execute("", request, undefined, undefined, stub.context);
126
+ assert.strictEqual(result.content[0]?.text, "42");
127
+ assert.strictEqual(result.details?.run?.mode, "workflow");
128
+ } finally {
129
+ await runtime.close();
130
+ }
131
+ }, 30_000);
132
+
133
+ it("the control parameters require the field of each action", async () => {
134
+ const runtime = await open();
135
+ try {
136
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_control") as {
137
+ parameters: object;
138
+ };
139
+ const validator = compile(tool.parameters);
140
+ assert.strictEqual(validator.check({ action: "steer", run: "r-1" }), false);
141
+ assert.strictEqual(validator.check({ action: "steer", run: "r-1", message: "go" }), true);
142
+ assert.strictEqual(validator.check({ action: "approve", run: "r-1" }), false);
143
+ assert.strictEqual(validator.check({ action: "deny", run: "r-1" }), false);
144
+ assert.strictEqual(validator.check({ action: "approve", run: "r-1", gate: "deploy" }), true);
145
+ assert.strictEqual(validator.check({ action: "stop", run: "r-1" }), true);
146
+ assert.strictEqual(validator.check({ action: "resume", run: "r-1" }), true);
147
+ } finally {
148
+ await runtime.close();
149
+ }
150
+ });
151
+
152
+ it("the control card reads a decline or refusal line instead of a launch placeholder", async () => {
153
+ const runtime = await open();
154
+ try {
155
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_control") as {
156
+ renderResult: (
157
+ result: {
158
+ readonly content: readonly { readonly type: string; readonly text: string }[];
159
+ readonly details?: unknown;
160
+ },
161
+ options: { readonly expanded: boolean },
162
+ ) => { readonly render: () => string[] };
163
+ };
164
+ const run: RunView = {
165
+ runId: "run:1",
166
+ definition: "scout",
167
+ mode: "single",
168
+ lane: "default",
169
+ conversationId: null,
170
+ taskId: null,
171
+ status: "answered",
172
+ answer: "done",
173
+ durationMs: null,
174
+ children: [],
175
+ missing: [],
176
+ gates: [],
177
+ requests: [],
178
+ diagnostic: null,
179
+ };
180
+ assert.strictEqual(
181
+ tool.renderResult({ content: [], details: { run } }, { expanded: false }).render()[0],
182
+ "Delegate scout single answered: done",
183
+ );
184
+ assert.strictEqual(
185
+ tool
186
+ .renderResult(
187
+ { content: [{ type: "text", text: "decline run:1: cancelled" }], details: {} },
188
+ { expanded: false },
189
+ )
190
+ .render()[0],
191
+ "decline run:1: cancelled",
192
+ );
193
+ assert.strictEqual(
194
+ tool
195
+ .renderResult(
196
+ {
197
+ content: [{ type: "text", text: "Run r-1 not found." }],
198
+ details: { error: "Run r-1 not found." },
199
+ },
200
+ { expanded: false },
201
+ )
202
+ .render()[0],
203
+ "Run r-1 not found.",
204
+ );
205
+ } finally {
206
+ await runtime.close();
207
+ }
208
+ });
209
+
210
+ it("a refused control returns one error row and the status still reads", async () => {
211
+ const runtime = await open({ text: "done" });
212
+ try {
213
+ const stub = registeredTools(runtime);
214
+ const controlTool = stub.registrations.toolDefinitions.get("delegate_control") as {
215
+ execute: (
216
+ id: string,
217
+ params: unknown,
218
+ signal: undefined,
219
+ onUpdate: undefined,
220
+ ctx: unknown,
221
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
222
+ };
223
+ const result = await controlTool.execute(
224
+ "",
225
+ { action: "steer", run: "r-1" },
226
+ undefined,
227
+ undefined,
228
+ stub.context,
229
+ );
230
+ assert.strictEqual(result.content.length, 1);
231
+ assert.match(result.content[0]?.text ?? "", /steer/);
232
+ assert.match(result.content[0]?.text ?? "", /message/);
233
+
234
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
235
+ execute: (
236
+ id: string,
237
+ params: unknown,
238
+ signal: undefined,
239
+ onUpdate: undefined,
240
+ ctx: unknown,
241
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
242
+ };
243
+ const status = await statusTool.execute("", {}, undefined, undefined, stub.context);
244
+ assert.strictEqual(status.content.length, 1);
245
+ assert.ok(!(status.content[0]?.text ?? "").includes("Session failed"));
246
+ } finally {
247
+ await runtime.close();
248
+ }
249
+ });
250
+
251
+ it("status prints the answer of an answered single run", async () => {
252
+ const runtime = await open({ text: "done" });
253
+ try {
254
+ const result = await launch(
255
+ { kind: "single", agent: "scout", task: "look around" },
256
+ depsFor(runtime),
257
+ );
258
+ const stub = registeredTools(runtime);
259
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
260
+ execute: (
261
+ id: string,
262
+ params: unknown,
263
+ signal: undefined,
264
+ onUpdate: undefined,
265
+ ctx: unknown,
266
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
267
+ };
268
+ const status = await statusTool.execute(
269
+ "",
270
+ { run: result.view.runId },
271
+ undefined,
272
+ undefined,
273
+ stub.context,
274
+ );
275
+ assert.ok(
276
+ (status.content[0]?.text ?? "").includes(`${result.view.runId} scout · answered: done`),
277
+ status.content[0]?.text ?? "",
278
+ );
279
+ } finally {
280
+ await runtime.close();
281
+ }
282
+ });
283
+
284
+ it("status for a single run prints no lane line", async () => {
285
+ const runtime = await open({ text: "done" });
286
+ try {
287
+ await launch({ kind: "single", agent: "scout", task: "look around" }, depsFor(runtime));
288
+ const fanout = await launch(
289
+ {
290
+ kind: "fanout",
291
+ lane: "review",
292
+ agents: [
293
+ { agent: "scout", task: "first" },
294
+ { agent: "scout", task: "second" },
295
+ ],
296
+ },
297
+ depsFor(runtime),
298
+ );
299
+ const stub = registeredTools(runtime);
300
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
301
+ execute: (
302
+ id: string,
303
+ params: unknown,
304
+ signal: undefined,
305
+ onUpdate: undefined,
306
+ ctx: unknown,
307
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
308
+ };
309
+ const status = await statusTool.execute(
310
+ "",
311
+ { run: fanout.view.runId },
312
+ undefined,
313
+ undefined,
314
+ stub.context,
315
+ );
316
+ const text = status.content[0]?.text ?? "";
317
+ assert.ok(!/running \d+, queued/.test(text), text);
318
+ assert.ok(!text.includes("review:"), text);
319
+ } finally {
320
+ await runtime.close();
321
+ }
322
+ });
323
+
324
+ it("launching a preset writes its toolkit into the child conversation", async () => {
325
+ const runtime = await open({ text: "hello" });
326
+ try {
327
+ const result = await launch(
328
+ { kind: "single", agent: "scout", task: "look around" },
329
+ depsFor(runtime),
330
+ );
331
+ assert.strictEqual(result.view.status, "answered");
332
+ assert.strictEqual(result.view.answer, "hello");
333
+
334
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
335
+ assert.ok(doc?.childConversationId !== null);
336
+ const childId = doc!.childConversationId!;
337
+ const agent = await childAgent(runtime.harness, childId);
338
+ assert.deepStrictEqual(agent?.tools, ["read"]);
339
+ assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION]);
340
+ assert.deepStrictEqual(agent?.model, host.model);
341
+ assert.strictEqual(agent?.thinkingLevel, "low");
342
+ assert.strictEqual(agent?.maxTurns, 40);
343
+ assert.ok(agent?.instructions?.includes("You explore"), String(agent?.instructions));
344
+
345
+ const toolkit = await runtime.harness.snapshot(
346
+ ToolkitDoc,
347
+ childId as never,
348
+ BACKGROUND_CONTEXT,
349
+ );
350
+ assert.strictEqual(toolkit?.definition, "scout");
351
+ assert.strictEqual(toolkit?.runId, result.view.runId);
352
+ assert.strictEqual(toolkit?.childRunId, result.view.runId);
353
+ assert.deepStrictEqual(toolkit?.approval.gates, []);
354
+ } finally {
355
+ await runtime.close();
356
+ }
357
+ });
358
+
359
+ it("an unknown definition name fails and lists the valid names", async () => {
360
+ const runtime = await open();
361
+ try {
362
+ await rejects(
363
+ launch({ kind: "single", agent: "nope", task: "look" }, depsFor(runtime)),
364
+ (error: unknown) =>
365
+ error instanceof Error &&
366
+ ["nope", "scout", "builder", "reviewer"].every((part) => error.message.includes(part)),
367
+ );
368
+ const index = await runtime.snapshot(RunIndexDoc);
369
+ assert.deepStrictEqual(index?.runIds ?? [], []);
370
+ } finally {
371
+ await runtime.close();
372
+ }
373
+ });
374
+
375
+ it("delegate_launch accepts an inline definition", async () => {
376
+ const runtime = await open({ text: "inline answer" });
377
+ try {
378
+ const stub = makeStubPi({ settings: { packages: [] } });
379
+ registerDelegateTools(stub.api, {
380
+ runtime: () => runtime,
381
+ catalogue: createCatalogue(),
382
+ host,
383
+ launchWaitMs: () => 5_000,
384
+ log: () => nullLogSink,
385
+ });
386
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
387
+ execute: (
388
+ id: string,
389
+ params: unknown,
390
+ signal: undefined,
391
+ onUpdate: undefined,
392
+ ctx: unknown,
393
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
394
+ };
395
+ const result = await tool.execute(
396
+ "",
397
+ {
398
+ request: {
399
+ kind: "single",
400
+ agent: "nomad",
401
+ task: "look",
402
+ definition: {
403
+ name: "nomad",
404
+ role: "auditor",
405
+ prompt: { role: "audit the repo" },
406
+ tools: ["read"],
407
+ },
408
+ },
409
+ },
410
+ undefined,
411
+ undefined,
412
+ stub.context,
413
+ );
414
+ assert.strictEqual(result.content[0]?.text, "inline answer");
415
+ } finally {
416
+ await runtime.close();
417
+ }
418
+ });
419
+
420
+ it("delegate_launch calls the inspector hook only after a run is committed", async () => {
421
+ const runtime = await open({ text: "ok" });
422
+ try {
423
+ const seen: unknown[] = [];
424
+ const stub = makeStubPi({ settings: { packages: [] } });
425
+ registerDelegateTools(stub.api, {
426
+ runtime: () => runtime,
427
+ catalogue: createCatalogue(),
428
+ host,
429
+ launchWaitMs: () => 5_000,
430
+ log: () => nullLogSink,
431
+ onRunCreated: (ctx) => {
432
+ seen.push(ctx);
433
+ },
434
+ });
435
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
436
+ execute: (
437
+ id: string,
438
+ params: unknown,
439
+ signal: undefined,
440
+ onUpdate: undefined,
441
+ ctx: unknown,
442
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
443
+ };
444
+ const result = await tool.execute(
445
+ "",
446
+ { request: { kind: "single", agent: "scout", task: "look" } },
447
+ undefined,
448
+ undefined,
449
+ stub.context,
450
+ );
451
+ assert.strictEqual(result.content[0]?.text, "ok");
452
+ assert.strictEqual(seen.length, 1);
453
+ assert.strictEqual(seen[0], stub.context);
454
+
455
+ const refused = await tool.execute(
456
+ "",
457
+ { request: { kind: "single", agent: "nope", task: "look" } },
458
+ undefined,
459
+ undefined,
460
+ stub.context,
461
+ );
462
+ assert.match(refused.content[0]?.text ?? "", /not found/);
463
+ assert.strictEqual(seen.length, 1);
464
+ } finally {
465
+ await runtime.close();
466
+ }
467
+ });
468
+
469
+ it("an inline definition tolerates unknown fields and names owner fields", async () => {
470
+ const runtime = await open({ text: "ok" });
471
+ try {
472
+ const stub = registeredTools(runtime);
473
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
474
+ parameters: object;
475
+ execute: (
476
+ id: string,
477
+ params: unknown,
478
+ signal: undefined,
479
+ onUpdate: undefined,
480
+ ctx: unknown,
481
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
482
+ };
483
+ const validator = compile(tool.parameters);
484
+ const definition = {
485
+ name: "nomad",
486
+ role: "auditor",
487
+ prompt: { role: "audit" },
488
+ tools: ["read"],
489
+ };
490
+ const request = (value: object) => ({
491
+ request: { kind: "single", agent: "nomad", task: "look", definition: value },
492
+ });
493
+ assert.strictEqual(validator.check(request({ ...definition, extra: true })), true);
494
+ assert.strictEqual(
495
+ validator.check(request({ ...definition, prompt: { ...definition.prompt, extra: true } })),
496
+ true,
497
+ );
498
+
499
+ const refused = await tool.execute(
500
+ "",
501
+ request({ ...definition, extensions: [] }),
502
+ undefined,
503
+ undefined,
504
+ stub.context,
505
+ );
506
+ assert.match(refused.content[0]?.text ?? "", /extensions/);
507
+ assert.match(refused.content[0]?.text ?? "", /only a registered definition/);
508
+ } finally {
509
+ await runtime.close();
510
+ }
511
+ });
512
+
513
+ it("an inline definition drops unknown fields before the request identity", async () => {
514
+ const runtime = await open({ hang: true });
515
+ try {
516
+ const stub = makeStubPi({ settings: { packages: [] } });
517
+ registerDelegateTools(stub.api, {
518
+ runtime: () => runtime,
519
+ catalogue: createCatalogue(),
520
+ host,
521
+ launchWaitMs: () => 50,
522
+ log: () => nullLogSink,
523
+ });
524
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
525
+ execute: (
526
+ id: string,
527
+ params: unknown,
528
+ signal: undefined,
529
+ onUpdate: undefined,
530
+ ctx: unknown,
531
+ ) => Promise<{
532
+ content: readonly { readonly text: string }[];
533
+ details?: { readonly run?: { readonly runId: string } };
534
+ }>;
535
+ };
536
+ const definition = {
537
+ name: "nomad",
538
+ role: "auditor",
539
+ prompt: { role: "audit" },
540
+ tools: ["read"],
541
+ };
542
+ const launchOnce = (value: object) =>
543
+ tool.execute(
544
+ "",
545
+ { request: { kind: "single", agent: "nomad", task: "look", definition: value } },
546
+ undefined,
547
+ undefined,
548
+ stub.context,
549
+ );
550
+ const first = await launchOnce({ ...definition, extra: true });
551
+ const second = await launchOnce(definition);
552
+ assert.ok(first.details?.run?.runId);
553
+ assert.ok(second.details?.run?.runId);
554
+ assert.strictEqual(first.details?.run?.runId, second.details?.run?.runId);
555
+ const index = await runtime.snapshot(RunIndexDoc);
556
+ assert.strictEqual(index?.runIds.length, 1);
557
+ } finally {
558
+ await runtime.close();
559
+ }
560
+ });
561
+
562
+ it("an unresolved toolkit name is refused at launch", async () => {
563
+ const runtime = await open();
564
+ try {
565
+ const definition = defineAgent({
566
+ name: "needs-missing",
567
+ role: "audit",
568
+ prompt: { role: "audit" },
569
+ tools: ["read"],
570
+ extensions: ["missing-extension"],
571
+ approval: { gates: [] },
572
+ });
573
+ await rejects(
574
+ launch(
575
+ { kind: "single", agent: definition.name, task: "look" },
576
+ { ...depsFor(runtime), catalogue: createCatalogue([definition]) },
577
+ ),
578
+ (error: unknown) => error instanceof Error && error.message.includes("missing-extension"),
579
+ );
580
+ const index = await runtime.snapshot(RunIndexDoc);
581
+ assert.deepStrictEqual(index?.runIds ?? [], []);
582
+ } finally {
583
+ await runtime.close();
584
+ }
585
+ });
586
+
587
+ it("a repeat of a terminal launch starts the next attempt", async () => {
588
+ const runtime = await open();
589
+ try {
590
+ const request = { kind: "single", agent: "scout", task: "look around" } as const;
591
+ const first = await launch(request, depsFor(runtime));
592
+ const second = await launch(request, depsFor(runtime));
593
+ assert.notStrictEqual(first.view.runId, second.view.runId);
594
+
595
+ const index = await runtime.snapshot(RunIndexDoc);
596
+ assert.strictEqual(index?.runIds.length, 2);
597
+ const firstDoc = await runtime.snapshot(RunDoc, first.view.runId);
598
+ const secondDoc = await runtime.snapshot(RunDoc, second.view.runId);
599
+ assert.notStrictEqual(firstDoc?.childConversationId, secondDoc?.childConversationId);
600
+ assert.strictEqual(secondDoc?.attempt, 2);
601
+ } finally {
602
+ await runtime.close();
603
+ }
604
+ });
605
+
606
+ it("a launch past the soft deadline returns running", async () => {
607
+ const runtime = await open({ hang: true });
608
+ try {
609
+ const result = await launch(
610
+ { kind: "single", agent: "scout", task: "look around" },
611
+ depsFor(runtime, 50),
612
+ );
613
+ assert.strictEqual(result.view.status, "running");
614
+ assert.ok(result.text.includes(result.view.runId), result.text);
615
+ const index = await runtime.snapshot(RunIndexDoc);
616
+ assert.strictEqual(index?.runIds.length, 1);
617
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
618
+ const task = await runtime.harness.getTask(doc!.taskId as never, BACKGROUND_CONTEXT);
619
+ assert.notStrictEqual(task?.state.status, "terminal");
620
+ } finally {
621
+ await runtime.close();
622
+ }
623
+ });
624
+
625
+ it("the same launch after reopen reuses the unfinished run", async () => {
626
+ const identity = await identityFor("s-1");
627
+ const request = { kind: "single", agent: "scout", task: "look around" } as const;
628
+
629
+ const first = await open({ identity, hang: true });
630
+ const firstResult = await launch(request, depsFor(first, 50));
631
+ const firstDoc = await first.snapshot(RunDoc, firstResult.view.runId);
632
+ await first.close();
633
+
634
+ const second = await open({ identity, hang: true });
635
+ try {
636
+ const secondResult = await launch(request, depsFor(second, 50));
637
+ assert.strictEqual(secondResult.view.status, "running");
638
+ assert.strictEqual(secondResult.view.runId, firstResult.view.runId);
639
+ const index = await second.snapshot(RunIndexDoc);
640
+ assert.strictEqual(index?.runIds.length, 1);
641
+ const secondDoc = await second.snapshot(RunDoc, secondResult.view.runId);
642
+ assert.strictEqual(secondDoc?.childConversationId, firstDoc?.childConversationId);
643
+ assert.ok(storePathFor(identity).endsWith("delegates-s-1.sqlite"));
644
+ } finally {
645
+ await second.close();
646
+ }
647
+ });
648
+
649
+ it("cancelling the launch aborts the run", async () => {
650
+ const runtime = await open({ hang: true });
651
+ try {
652
+ const controller = new AbortController();
653
+ const pending = launch(
654
+ { kind: "single", agent: "scout", task: "look around" },
655
+ { ...depsFor(runtime, 5_000), signal: controller.signal },
656
+ );
657
+ setTimeout(() => controller.abort(), 25);
658
+ const result = await pending;
659
+ assert.strictEqual(result.view.status, "stopped");
660
+ assert.ok(result.text.includes("is stopped"), result.text);
661
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
662
+ assert.ok(doc?.childConversationId !== null);
663
+ } finally {
664
+ await runtime.close();
665
+ }
666
+ });
667
+
668
+ it("a memory-backed runtime launches without touching a store file", async () => {
669
+ const storage = new MemoryStorage();
670
+ const runtime = await open({ storage, text: "hello" });
671
+ try {
672
+ const result = await launch(
673
+ { kind: "single", agent: "builder", task: "build it" },
674
+ depsFor(runtime),
675
+ );
676
+ assert.strictEqual(result.view.status, "answered");
677
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
678
+ const agent = await childAgent(runtime.harness, doc!.childConversationId!);
679
+ assert.deepStrictEqual(agent?.tools, ["read", "bash", "write", "edit"]);
680
+ } finally {
681
+ await runtime.close();
682
+ }
683
+ });
684
+
685
+ it("a definition that selects only coding still gets the gate guard", async () => {
686
+ const deployer = defineAgent({
687
+ name: "deployer",
688
+ role: "Deploy agent",
689
+ prompt: { role: "You deploy things." },
690
+ tools: ["read"],
691
+ extensions: [CODING_EXTENSION],
692
+ approval: { gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }] },
693
+ });
694
+ const runtime = await open({ text: "ready" });
695
+ try {
696
+ const result = await launch(
697
+ { kind: "single", agent: "deployer", task: "deploy it" },
698
+ { ...depsFor(runtime), catalogue: createCatalogue([deployer]) },
699
+ );
700
+ assert.strictEqual(result.view.status, "answered");
701
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
702
+ const childId = doc!.childConversationId!;
703
+ const agent = await childAgent(runtime.harness, childId);
704
+ assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION, GATE_GUARD_EXTENSION]);
705
+ const toolkit = await runtime.harness.snapshot(
706
+ ToolkitDoc,
707
+ childId as never,
708
+ BACKGROUND_CONTEXT,
709
+ );
710
+ assert.deepStrictEqual(toolkit?.approval.gates, deployer.approval.gates);
711
+ } finally {
712
+ await runtime.close();
713
+ }
714
+ });
715
+
716
+ it("an inline definition cannot remove a registered approval rule", async () => {
717
+ const auditor = defineAgent({
718
+ name: "auditor",
719
+ role: "Audit agent",
720
+ prompt: { role: "You audit things." },
721
+ tools: ["read"],
722
+ extensions: [CODING_EXTENSION],
723
+ approval: { gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }] },
724
+ });
725
+ const runtime = await open({ text: "audited" });
726
+ try {
727
+ const result = await launch(
728
+ {
729
+ kind: "single",
730
+ agent: "auditor",
731
+ task: "audit it",
732
+ definition: {
733
+ name: "auditor",
734
+ role: "narrowed",
735
+ prompt: { role: "narrowed" },
736
+ tools: ["read"],
737
+ },
738
+ },
739
+ { ...depsFor(runtime), catalogue: createCatalogue([auditor]) },
740
+ );
741
+ assert.strictEqual(result.view.status, "answered");
742
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
743
+ const childId = doc!.childConversationId!;
744
+ const agent = await childAgent(runtime.harness, childId);
745
+ assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION, GATE_GUARD_EXTENSION]);
746
+ assert.deepStrictEqual(agent?.tools, ["read"]);
747
+ const toolkit = await runtime.harness.snapshot(
748
+ ToolkitDoc,
749
+ childId as never,
750
+ BACKGROUND_CONTEXT,
751
+ );
752
+ assert.deepStrictEqual(toolkit?.approval.gates, auditor.approval.gates);
753
+ } finally {
754
+ await runtime.close();
755
+ }
756
+ });
757
+
758
+ it("a retry of a failed launch starts the next attempt", async () => {
759
+ const runtime = await open({ failAt: [1, 2] });
760
+ try {
761
+ const request = { kind: "single", agent: "scout", task: "look around" } as const;
762
+ const first = await launch(request, depsFor(runtime));
763
+ assert.strictEqual(first.view.status, "failed");
764
+ const second = await launch(request, depsFor(runtime));
765
+ assert.strictEqual(second.view.status, "failed");
766
+ assert.notStrictEqual(second.view.runId, first.view.runId);
767
+
768
+ const index = await runtime.snapshot(RunIndexDoc);
769
+ assert.deepStrictEqual(index?.runIds, [first.view.runId, second.view.runId]);
770
+ const firstDoc = await runtime.snapshot(RunDoc, first.view.runId);
771
+ const secondDoc = await runtime.snapshot(RunDoc, second.view.runId);
772
+ assert.strictEqual(secondDoc?.attempt, 2);
773
+ assert.notStrictEqual(secondDoc?.childConversationId, firstDoc?.childConversationId);
774
+ } finally {
775
+ await runtime.close();
776
+ }
777
+ });
778
+
779
+ const recordingSink = () => {
780
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
781
+ const sink: LogSink = {
782
+ write: (level, code, fields = {}) => {
783
+ entries.push({ level, code, fields });
784
+ },
785
+ };
786
+ return { sink, entries };
787
+ };
788
+
789
+ it("each delegate tool logs its name and the error", async () => {
790
+ const { sink, entries } = recordingSink();
791
+ const stub = makeStubPi({ settings: { packages: [] } });
792
+ registerDelegateTools(stub.api, {
793
+ runtime: () => {
794
+ throw new Error("runtime not ready");
795
+ },
796
+ catalogue: createCatalogue(),
797
+ host,
798
+ launchWaitMs: () => 5_000,
799
+ log: () => sink,
800
+ });
801
+ const execute = async (name: string, params: unknown) => {
802
+ const tool = stub.registrations.toolDefinitions.get(name) as {
803
+ execute: (
804
+ id: string,
805
+ params: unknown,
806
+ signal: undefined,
807
+ onUpdate: undefined,
808
+ ctx: unknown,
809
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
810
+ };
811
+ const result = await tool.execute("", params, undefined, undefined, stub.context);
812
+ assert.match(result.content[0]?.text ?? "", /runtime not ready/);
813
+ };
814
+
815
+ await execute("delegate_launch", {
816
+ request: { kind: "single", agent: "scout", task: "look" },
817
+ });
818
+ await execute("delegate_control", { action: "stop", run: "run:x" });
819
+ await execute("delegate_status", {});
820
+
821
+ assert.deepStrictEqual(
822
+ entries.map((entry) => [entry.level, entry.code, entry.fields.tool, entry.fields.action]),
823
+ [
824
+ ["error", "tool.not_ready", "delegate_launch", undefined],
825
+ ["error", "tool.not_ready", "delegate_control", "stop"],
826
+ ["error", "tool.not_ready", "delegate_status", undefined],
827
+ ],
828
+ );
829
+ for (const entry of entries) assert.strictEqual(entry.fields.error, "Error");
830
+ });
831
+
832
+ it("malformed tool arguments are refused and logged", async () => {
833
+ const { sink, entries } = recordingSink();
834
+ const runtime = await open();
835
+ try {
836
+ const stub = makeStubPi({ settings: { packages: [] } });
837
+ registerDelegateTools(stub.api, {
838
+ runtime: () => runtime,
839
+ catalogue: createCatalogue(),
840
+ host,
841
+ launchWaitMs: () => 5_000,
842
+ log: () => sink,
843
+ });
844
+ const execute = async (name: string, params: unknown) => {
845
+ const tool = stub.registrations.toolDefinitions.get(name) as {
846
+ execute: (
847
+ id: string,
848
+ params: unknown,
849
+ signal: undefined,
850
+ onUpdate: undefined,
851
+ ctx: unknown,
852
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
853
+ };
854
+ return tool.execute("", params, undefined, undefined, stub.context);
855
+ };
856
+
857
+ const launch = await execute("delegate_launch", {
858
+ request: { kind: "single", agent: 1, task: "look" },
859
+ });
860
+ assert.ok((launch.content[0]?.text ?? "").length > 0);
861
+ const control = await execute("delegate_control", { action: "stop", run: 5 });
862
+ assert.match(control.content[0]?.text ?? "", /run is required/);
863
+ const status = await execute("delegate_status", { run: 5 });
864
+ assert.ok((status.content[0]?.text ?? "").length > 0);
865
+
866
+ assert.deepStrictEqual(
867
+ entries.map((entry) => [entry.code, entry.fields.tool]),
868
+ [
869
+ ["tool.not_ready", "delegate_launch"],
870
+ ["tool.not_ready", "delegate_control"],
871
+ ["tool.not_ready", "delegate_status"],
872
+ ],
873
+ );
874
+ // A refused request never claims a run.
875
+ assert.deepStrictEqual((await runtime.snapshot(RunIndexDoc))?.runIds ?? [], []);
876
+ } finally {
877
+ await runtime.close();
878
+ }
879
+ });
880
+
881
+ const runStatus = async (runtime: SessionRuntime, params: unknown) => {
882
+ const stub = registeredTools(runtime);
883
+ const tool = stub.registrations.toolDefinitions.get("delegate_status") as {
884
+ execute: (
885
+ id: string,
886
+ params: unknown,
887
+ signal: undefined,
888
+ onUpdate: undefined,
889
+ ctx: unknown,
890
+ ) => Promise<{
891
+ content: readonly { readonly text: string }[];
892
+ details?: { readonly runs: readonly { readonly runId: string }[] };
893
+ }>;
894
+ };
895
+ return tool.execute("", params, undefined, undefined, stub.context);
896
+ };
897
+
898
+ it("status reads only the requested run", async () => {
899
+ const runtime = await open({ text: "done" });
900
+ try {
901
+ const first = await launch({ kind: "single", agent: "scout", task: "first" }, depsFor(runtime));
902
+ const target = await launch(
903
+ { kind: "single", agent: "scout", task: "second" },
904
+ depsFor(runtime),
905
+ );
906
+ const third = await launch({ kind: "single", agent: "scout", task: "third" }, depsFor(runtime));
907
+
908
+ const counted = countingRuntime(runtime);
909
+ const status = await runStatus(counted.runtime, { run: target.view.runId });
910
+ const text = status.content[0]?.text ?? "";
911
+ assert.ok(text.includes(`${target.view.runId} scout · answered: done`), text);
912
+ for (const other of [first.view.runId, third.view.runId]) {
913
+ assert.strictEqual(counted.count("delegates.run", other), 0, other);
914
+ }
915
+ } finally {
916
+ await runtime.close();
917
+ }
918
+ });
919
+
920
+ it("status shows the run's reviews without reading other reviews", async () => {
921
+ const runtime = await open({ text: '{"disposition":"accepted"}' });
922
+ try {
923
+ const reviewers = [{ agent: "reviewer" }, { agent: "reviewer" }];
924
+ const first = await launch(
925
+ { kind: "review", task: "first", reviewers },
926
+ depsFor(runtime, 20_000),
927
+ );
928
+ const second = await launch(
929
+ { kind: "review", task: "second", reviewers },
930
+ depsFor(runtime, 20_000),
931
+ );
932
+
933
+ const counted = countingRuntime(runtime);
934
+ const status = await runStatus(counted.runtime, { run: first.view.runId });
935
+ const text = status.content[0]?.text ?? "";
936
+ assert.ok(text.includes("reviewer 0"), text);
937
+ assert.ok(text.includes("reviewer 1"), text);
938
+ assert.strictEqual(counted.count("delegates.review", second.view.runId), 0);
939
+ } finally {
940
+ await runtime.close();
941
+ }
942
+ });
943
+
944
+ it("status for an unknown run returns not found", async () => {
945
+ const runtime = await open();
946
+ try {
947
+ const missing = await runStatus(runtime, { run: "run:missing" });
948
+ assert.strictEqual(missing.content[0]?.text, "Run run:missing not found.");
949
+ assert.deepStrictEqual(missing.details?.runs, []);
950
+ } finally {
951
+ await runtime.close();
952
+ }
953
+ });
954
+
955
+ it("the launch card prints the run mode in both forms", async () => {
956
+ const runtime = await open();
957
+ try {
958
+ const stub = registeredTools(runtime);
959
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
960
+ renderResult: (
961
+ result: { readonly details: { readonly run: RunView } },
962
+ options: { readonly expanded: boolean },
963
+ ) => { readonly render: () => string[] };
964
+ };
965
+ const run: RunView = {
966
+ runId: "run:wf#1",
967
+ definition: "composer",
968
+ mode: "workflow",
969
+ lane: "workflow",
970
+ conversationId: null,
971
+ taskId: null,
972
+ status: "answered",
973
+ answer: "42",
974
+ durationMs: null,
975
+ children: [],
976
+ missing: [],
977
+ gates: [],
978
+ requests: [],
979
+ diagnostic: null,
980
+ };
981
+ assert.strictEqual(
982
+ tool.renderResult({ details: { run } }, { expanded: false }).render()[0],
983
+ "Delegate composer workflow answered: 42",
984
+ );
985
+ const expanded = tool.renderResult({ details: { run } }, { expanded: true }).render()[0] ?? "";
986
+ assert.ok(
987
+ expanded.includes("definition composer · workflow · lane workflow · answered"),
988
+ expanded,
989
+ );
990
+ } finally {
991
+ await runtime.close();
992
+ }
993
+ });