@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,1332 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { AgentDoc } from "@earendil-works/pi-durable";
3
+ import { assert, it } from "@effect/vitest";
4
+ import { Effect } from "effect";
5
+ import {
6
+ join,
7
+ makeDir,
8
+ makeTempDir,
9
+ removePath,
10
+ writeText,
11
+ } from "../../../test-support/platform.ts";
12
+ import { rejects, throws } from "../../../test-support/assertions.ts";
13
+ import { stubHostSource, type StubHostOptions } from "../../../test-support/stub-model-source.ts";
14
+ import { createCatalogue, defineAgent } from "../definitions.ts";
15
+ import { launch, type HostDefaults } from "./launch.ts";
16
+ import { CODING_EXTENSION, QUESTIONS_EXTENSION } from "../names.ts";
17
+ import {
18
+ answerText,
19
+ control,
20
+ decodeControl,
21
+ decodeStoredInput,
22
+ InvalidControlRequest,
23
+ RunNotResumable,
24
+ RunNotRunning,
25
+ } from "./control.ts";
26
+ import { FanoutInputSchema } from "./fanout.ts";
27
+ import {
28
+ answerRequest,
29
+ InvalidRequestAnswer,
30
+ normalizeAnswer,
31
+ RequestAlreadyAnswered,
32
+ RequestAlreadyDecided,
33
+ RequestDoc,
34
+ RequestIndexDoc,
35
+ RequestNotFound,
36
+ type RequestRecord,
37
+ } from "./requests.ts";
38
+ import { RunDoc, RunInputSchema } from "../run-records.ts";
39
+ import { ReviewDoc } from "./review.ts";
40
+ import { laneViews, viewRun, type RunStatus } from "../view.ts";
41
+ import { renderStatusText } from "../../extension/tools.ts";
42
+ import type { LogFields, LogLevel, LogSink } from "../../runtime/log.ts";
43
+ import { countingRuntime } from "../../../test-support/counting-runtime.ts";
44
+ import { HostModelAdapter } from "../../runtime/models.ts";
45
+ import { type SessionIdentity, type SessionRuntime } from "../../runtime/session.ts";
46
+ import { openTestSession, type TestSession } from "../../../test-support/seams.ts";
47
+
48
+ const host: HostDefaults = {
49
+ model: { provider: "stub", modelId: "stub-1" },
50
+ thinkingLevel: "low",
51
+ };
52
+
53
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
54
+ const sessionDir = await makeTempDir("delegates-control-");
55
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
56
+ };
57
+
58
+ const deferred = (): { readonly promise: Promise<void>; readonly release: () => void } => {
59
+ let release: () => void = () => {};
60
+ const promise = new Promise<void>((resolve) => {
61
+ release = resolve;
62
+ });
63
+ return { promise, release };
64
+ };
65
+
66
+ const waitForStatus = async (
67
+ runtime: SessionRuntime,
68
+ runId: string,
69
+ status: RunStatus,
70
+ timeoutMs = 10_000,
71
+ ): Promise<void> => {
72
+ const started = Date.now();
73
+ while (Date.now() - started < timeoutMs) {
74
+ const view = await viewRun(runId, runtime);
75
+ if (view.status === status) return;
76
+ await new Promise((resolve) => setTimeout(resolve, 25));
77
+ }
78
+ const last = await viewRun(runId, runtime);
79
+ throw new Error(`run ${runId} did not reach ${status}: ${JSON.stringify(last)}`);
80
+ };
81
+
82
+ const deps = (runtime: SessionRuntime) => ({ runtime, catalogue: createCatalogue(), host });
83
+
84
+ it("steering a running child delivers the message", async () => {
85
+ const hold = deferred();
86
+ const runtime = await openTestSession({
87
+ identity: await identityFor("s-1"),
88
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
89
+ });
90
+ try {
91
+ const result = await launch(
92
+ { kind: "single", agent: "scout", task: "look around" },
93
+ { ...deps(runtime), waitMs: 50 },
94
+ );
95
+ assert.strictEqual(result.view.status, "running");
96
+ await control(
97
+ { action: "steer", run: result.view.runId, message: "use pnpm" },
98
+ {
99
+ runtime,
100
+ wait: { policy: "settle", waitMs: 10_000 },
101
+ },
102
+ );
103
+ hold.release();
104
+ await waitForStatus(runtime, result.view.runId, "answered");
105
+
106
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
107
+ const conversation = await runtime.harness.conversation(
108
+ doc!.childConversationId as never,
109
+ BACKGROUND_CONTEXT,
110
+ );
111
+ const context = await conversation!.context(BACKGROUND_CONTEXT);
112
+ const contents = context.messages.map((message) =>
113
+ message.role === "user"
114
+ ? typeof message.content === "string"
115
+ ? message.content
116
+ : message.content.map((part) => (part.type === "text" ? part.text : "")).join("")
117
+ : "",
118
+ );
119
+ assert.ok(
120
+ contents.some((text) => text.includes("use pnpm")),
121
+ contents.join("\n"),
122
+ );
123
+ } finally {
124
+ await runtime.close();
125
+ }
126
+ }, 20_000);
127
+
128
+ it("a steer without a message is refused and the session still reads", async () => {
129
+ const runtime = await openTestSession({
130
+ identity: await identityFor("s-1"),
131
+ models: new HostModelAdapter(stubHostSource({ text: "done" })),
132
+ });
133
+ try {
134
+ const result = await launch(
135
+ { kind: "single", agent: "scout", task: "look around" },
136
+ { ...deps(runtime), waitMs: 10_000 },
137
+ );
138
+ await rejects(
139
+ control({ action: "steer", run: result.view.runId } as never, {
140
+ runtime,
141
+ wait: { policy: "settle", waitMs: 1_000 },
142
+ }),
143
+ (error: unknown) =>
144
+ error instanceof InvalidControlRequest &&
145
+ error.message.includes("steer") &&
146
+ error.message.includes("message"),
147
+ );
148
+ const view = await viewRun(result.view.runId, runtime);
149
+ assert.strictEqual(view.status, "answered");
150
+ assert.strictEqual(view.answer, "done");
151
+ } finally {
152
+ await runtime.close();
153
+ }
154
+ });
155
+
156
+ it("stopping ends the run as stopped and keeps its record", async () => {
157
+ const runtime = await openTestSession({
158
+ identity: await identityFor("s-1"),
159
+ models: new HostModelAdapter(stubHostSource({ hang: true })),
160
+ });
161
+ try {
162
+ const result = await launch(
163
+ { kind: "single", agent: "scout", task: "look around" },
164
+ { ...deps(runtime), waitMs: 50 },
165
+ );
166
+ const stopped = await control(
167
+ { action: "stop", run: result.view.runId },
168
+ {
169
+ runtime,
170
+ wait: { policy: "settle", waitMs: 10_000 },
171
+ },
172
+ );
173
+ assert.strictEqual(stopped.view!.status, "stopped");
174
+ assert.ok((await runtime.snapshot(RunDoc, result.view.runId)) !== undefined);
175
+ await rejects(
176
+ control(
177
+ { action: "steer", run: result.view.runId, message: "go on" },
178
+ {
179
+ runtime,
180
+ wait: { policy: "settle", waitMs: 1_000 },
181
+ },
182
+ ),
183
+ (error: unknown) => error instanceof Error && error.message.includes("stopped"),
184
+ );
185
+ } finally {
186
+ await runtime.close();
187
+ }
188
+ });
189
+
190
+ it("a stopped run is not restarted by reopen", async () => {
191
+ const identity = await identityFor("s-1");
192
+ const first = await openTestSession({
193
+ identity,
194
+ models: new HostModelAdapter(stubHostSource({ hang: true })),
195
+ });
196
+ const result = await launch(
197
+ { kind: "single", agent: "scout", task: "look around" },
198
+ { ...deps(first), waitMs: 50 },
199
+ );
200
+ await control(
201
+ { action: "stop", run: result.view.runId },
202
+ { runtime: first, wait: { policy: "settle", waitMs: 10_000 } },
203
+ );
204
+ await first.close();
205
+
206
+ const second = await openTestSession({
207
+ identity,
208
+ models: new HostModelAdapter(stubHostSource()),
209
+ });
210
+ try {
211
+ const view = await viewRun(result.view.runId, second);
212
+ assert.strictEqual(view.status, "stopped");
213
+ const doc = await second.snapshot(RunDoc, result.view.runId);
214
+ const task = await second.harness.getTask(doc!.taskId as never, BACKGROUND_CONTEXT);
215
+ assert.strictEqual(task?.state.status, "terminal");
216
+ } finally {
217
+ await second.close();
218
+ }
219
+ });
220
+
221
+ it("resume restarts a stopped fanout and signals every child", async () => {
222
+ const hold = deferred();
223
+ const runtime = await openTestSession({
224
+ identity: await identityFor("s-1"),
225
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
226
+ });
227
+ try {
228
+ const result = await launch(
229
+ {
230
+ kind: "fanout",
231
+ lane: "review",
232
+ agents: [
233
+ { agent: "scout", task: "first" },
234
+ { agent: "scout", task: "second" },
235
+ ],
236
+ },
237
+ { ...deps(runtime), waitMs: 50 },
238
+ );
239
+ assert.strictEqual(result.view.children.length, 2);
240
+ await control(
241
+ { action: "stop", run: result.view.runId },
242
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
243
+ );
244
+ hold.release();
245
+
246
+ const resumed = await control(
247
+ { action: "resume", run: result.view.runId },
248
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
249
+ );
250
+ assert.strictEqual(resumed.view!.status, "answered");
251
+ assert.strictEqual(resumed.view!.children.length, 2);
252
+ assert.deepStrictEqual(
253
+ resumed.view!.children.map((child) => child.status),
254
+ ["answered", "answered"],
255
+ );
256
+ } finally {
257
+ await runtime.close();
258
+ }
259
+ }, 30_000);
260
+
261
+ it("resume keeps answered fanout children and restarts the rest", async () => {
262
+ const hold = deferred();
263
+ const source = stubHostSource({
264
+ texts: ["one", "two", "three", "again"],
265
+ hold: () => hold.promise,
266
+ holdAt: [3],
267
+ });
268
+ const runtime = await openTestSession({
269
+ identity: await identityFor("s-1"),
270
+ models: new HostModelAdapter(source),
271
+ });
272
+ try {
273
+ const result = await launch(
274
+ {
275
+ kind: "fanout",
276
+ lane: "review",
277
+ agents: [
278
+ { agent: "scout", task: "first" },
279
+ { agent: "scout", task: "second" },
280
+ { agent: "scout", task: "third" },
281
+ ],
282
+ },
283
+ { ...deps(runtime), waitMs: 100 },
284
+ );
285
+ for (let i = 0; i < 400; i += 1) {
286
+ const view = await viewRun(result.view.runId, runtime);
287
+ if (view.children.filter((child) => child.status === "answered").length >= 2) break;
288
+ await new Promise((resolve) => setTimeout(resolve, 20));
289
+ }
290
+ await control(
291
+ { action: "stop", run: result.view.runId },
292
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
293
+ );
294
+ hold.release();
295
+
296
+ const callsBefore = source.calls.length;
297
+ const resumed = await control(
298
+ { action: "resume", run: result.view.runId },
299
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
300
+ );
301
+ assert.strictEqual(source.calls.length, callsBefore + 1);
302
+ assert.deepStrictEqual(
303
+ resumed.view!.children.map((child) => child.status),
304
+ ["answered", "answered", "answered"],
305
+ );
306
+ assert.deepStrictEqual(
307
+ resumed.view!.children.map((child) => child.answer),
308
+ ["one", "two", "again"],
309
+ );
310
+ } finally {
311
+ hold.release();
312
+ await runtime.close();
313
+ }
314
+ }, 30_000);
315
+
316
+ it("resume restarts a stopped review and rebuilds its dispositions", async () => {
317
+ const hold = deferred();
318
+ const runtime = await openTestSession({
319
+ identity: await identityFor("s-1"),
320
+ models: new HostModelAdapter(
321
+ stubHostSource({ text: '{"disposition":"accepted"}', hold: () => hold.promise }),
322
+ ),
323
+ });
324
+ try {
325
+ const result = await launch(
326
+ {
327
+ kind: "review",
328
+ reviewers: [{ agent: "reviewer" }, { agent: "reviewer" }],
329
+ task: "review the diff",
330
+ },
331
+ { ...deps(runtime), waitMs: 50 },
332
+ );
333
+ await control(
334
+ { action: "stop", run: result.view.runId },
335
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
336
+ );
337
+ hold.release();
338
+
339
+ const resumed = await control(
340
+ { action: "resume", run: result.view.runId },
341
+ { runtime, wait: { policy: "settle", waitMs: 20_000 } },
342
+ );
343
+ assert.strictEqual(resumed.view!.status, "answered");
344
+ assert.strictEqual(resumed.view!.answer, "accepted");
345
+ const record = await runtime.snapshot(ReviewDoc, result.view.runId);
346
+ assert.deepStrictEqual(
347
+ record?.reviewers.map((reviewer) => reviewer.disposition),
348
+ ["accepted", "accepted"],
349
+ );
350
+ } finally {
351
+ await runtime.close();
352
+ }
353
+ }, 30_000);
354
+
355
+ it("a stored resume input that no longer matches its shape is refused", () => {
356
+ const bad: unknown[] = [
357
+ undefined,
358
+ null,
359
+ { runId: "r" },
360
+ { runId: "r", lane: "l", children: [] },
361
+ { runId: "r", definition: { name: 1 } },
362
+ ];
363
+ for (const input of bad) {
364
+ const refused = (error: unknown): boolean => error instanceof RunNotResumable;
365
+ throws(() => decodeStoredInput(RunInputSchema, input, "r"), refused);
366
+ throws(() => decodeStoredInput(FanoutInputSchema, input, "r"), refused);
367
+ }
368
+ });
369
+
370
+ it("an interrupted run resumes by itself after reopen", async () => {
371
+ const identity = await identityFor("s-1");
372
+ const first = await openTestSession({
373
+ identity,
374
+ models: new HostModelAdapter(stubHostSource({ hang: true })),
375
+ });
376
+ const result = await launch(
377
+ { kind: "single", agent: "scout", task: "look around" },
378
+ { ...deps(first), waitMs: 50 },
379
+ );
380
+ const firstDoc = await first.snapshot(RunDoc, result.view.runId);
381
+ await first.close();
382
+
383
+ const second = await openTestSession({
384
+ identity,
385
+ models: new HostModelAdapter(stubHostSource({ text: "continued" })),
386
+ });
387
+ try {
388
+ await waitForStatus(second, result.view.runId, "answered");
389
+ const view = await viewRun(result.view.runId, second);
390
+ assert.strictEqual(view.answer, "continued");
391
+ const doc = await second.snapshot(RunDoc, result.view.runId);
392
+ assert.strictEqual(doc?.childConversationId, firstDoc?.childConversationId);
393
+ } finally {
394
+ await second.close();
395
+ }
396
+ });
397
+
398
+ it("resume continues a run stopped in this session", async () => {
399
+ const hold = deferred();
400
+ const runtime = await openTestSession({
401
+ identity: await identityFor("s-1"),
402
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
403
+ });
404
+ try {
405
+ const result = await launch(
406
+ { kind: "single", agent: "scout", task: "look around" },
407
+ { ...deps(runtime), waitMs: 50 },
408
+ );
409
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
410
+ const childId = doc!.childConversationId;
411
+ await control(
412
+ { action: "stop", run: result.view.runId },
413
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
414
+ );
415
+ hold.release();
416
+ const resumed = await control(
417
+ { action: "resume", run: result.view.runId },
418
+ {
419
+ runtime,
420
+ wait: { policy: "settle", waitMs: 10_000 },
421
+ },
422
+ );
423
+ assert.strictEqual(resumed.view!.status, "answered");
424
+ const after = await runtime.snapshot(RunDoc, result.view.runId);
425
+ assert.strictEqual(after?.childConversationId, childId);
426
+ } finally {
427
+ await runtime.close();
428
+ }
429
+ }, 20_000);
430
+
431
+ it("resume refuses a live run without waiting", async () => {
432
+ const hold = deferred();
433
+ const entries: { code: string }[] = [];
434
+ const runtime = await openTestSession({
435
+ identity: await identityFor("s-1"),
436
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
437
+ log: { write: (_level, code) => entries.push({ code }) },
438
+ });
439
+ try {
440
+ const result = await launch(
441
+ { kind: "single", agent: "scout", task: "look around" },
442
+ { ...deps(runtime), waitMs: 50 },
443
+ );
444
+ assert.strictEqual(result.view.status, "running");
445
+ entries.length = 0;
446
+ await rejects(
447
+ control(
448
+ { action: "resume", run: result.view.runId },
449
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
450
+ ),
451
+ (error: unknown) => error instanceof RunNotResumable && error.message.includes("running"),
452
+ );
453
+ assert.deepStrictEqual(
454
+ entries.filter((entry) => entry.code.startsWith("wait.")),
455
+ [],
456
+ );
457
+ const view = await viewRun(result.view.runId, runtime);
458
+ assert.strictEqual(view.status, "running");
459
+ } finally {
460
+ hold.release();
461
+ await runtime.close();
462
+ }
463
+ }, 20_000);
464
+
465
+ it("resume refuses a finished run naming its status", async () => {
466
+ const runtime = await openTestSession({
467
+ identity: await identityFor("s-1"),
468
+ models: new HostModelAdapter(stubHostSource()),
469
+ });
470
+ try {
471
+ const result = await launch(
472
+ { kind: "single", agent: "scout", task: "look around" },
473
+ { ...deps(runtime), waitMs: 10_000 },
474
+ );
475
+ await rejects(
476
+ control(
477
+ { action: "resume", run: result.view.runId },
478
+ { runtime, wait: { policy: "settle", waitMs: 1_000 } },
479
+ ),
480
+ (error: unknown) => error instanceof Error && error.message.includes("answered"),
481
+ );
482
+ } finally {
483
+ await runtime.close();
484
+ }
485
+ });
486
+
487
+ it("steering one fanout child uses its child run id", async () => {
488
+ const hold = deferred();
489
+ const runtime = await openTestSession({
490
+ identity: await identityFor("s-1"),
491
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
492
+ });
493
+ try {
494
+ const result = await launch(
495
+ {
496
+ kind: "fanout",
497
+ lane: "review",
498
+ agents: [
499
+ { agent: "scout", task: "first" },
500
+ { agent: "scout", task: "second" },
501
+ ],
502
+ },
503
+ { ...deps(runtime), waitMs: 50 },
504
+ );
505
+ const childRunId = result.view.children[0]?.runId;
506
+ assert.ok(childRunId !== undefined);
507
+ assert.notStrictEqual(childRunId, result.view.runId);
508
+
509
+ await control(
510
+ { action: "steer", run: childRunId, message: "use pnpm" },
511
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
512
+ );
513
+ hold.release();
514
+ await waitForStatus(runtime, result.view.runId, "answered");
515
+
516
+ const childDoc = await runtime.snapshot(RunDoc, childRunId);
517
+ const conversation = await runtime.harness.conversation(
518
+ childDoc!.childConversationId as never,
519
+ BACKGROUND_CONTEXT,
520
+ );
521
+ const context = await conversation!.context(BACKGROUND_CONTEXT);
522
+ assert.ok(
523
+ context.messages.some(
524
+ (message) =>
525
+ message.role === "user" &&
526
+ (typeof message.content === "string"
527
+ ? message.content
528
+ : message.content.map((part) => (part.type === "text" ? part.text : "")).join("")
529
+ ).includes("use pnpm"),
530
+ ),
531
+ );
532
+ } finally {
533
+ await runtime.close();
534
+ }
535
+ }, 20_000);
536
+
537
+ it("steering a run with a missing toolkit name names the alternatives", async () => {
538
+ const runtime = await openTestSession({
539
+ identity: await identityFor("s-1"),
540
+ models: new HostModelAdapter(stubHostSource()),
541
+ });
542
+ try {
543
+ const result = await launch(
544
+ { kind: "single", agent: "scout", task: "look around" },
545
+ { ...deps(runtime), waitMs: 10_000 },
546
+ );
547
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
548
+ await runtime.harness.commit(async (tx) => {
549
+ const agent = await tx.doc(AgentDoc, doc!.childConversationId as never);
550
+ agent.extensions = ["gone-extension"];
551
+ }, BACKGROUND_CONTEXT);
552
+ await rejects(
553
+ control(
554
+ { action: "steer", run: result.view.runId, message: "go on" },
555
+ { runtime, wait: { policy: "settle", waitMs: 1_000 } },
556
+ ),
557
+ (error: unknown) =>
558
+ error instanceof Error &&
559
+ error.message.includes("gone-extension") &&
560
+ error.message.includes("coding-tools"),
561
+ );
562
+ } finally {
563
+ await runtime.close();
564
+ }
565
+ });
566
+
567
+ it("a refused resume records the names that no longer resolve", async () => {
568
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
569
+ const sink: LogSink = {
570
+ write: (level, code, fields = {}) => {
571
+ entries.push({ level, code, fields });
572
+ },
573
+ };
574
+ const runtime = await openTestSession({
575
+ identity: await identityFor("s-1"),
576
+ models: new HostModelAdapter(stubHostSource({ hang: true })),
577
+ log: sink,
578
+ });
579
+ try {
580
+ const result = await launch(
581
+ { kind: "single", agent: "scout", task: "look around" },
582
+ { ...deps(runtime), waitMs: 50 },
583
+ );
584
+ await control(
585
+ { action: "stop", run: result.view.runId },
586
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
587
+ );
588
+
589
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
590
+ await runtime.harness.commit(async (tx) => {
591
+ const agent = await tx.doc(AgentDoc, doc!.childConversationId as never);
592
+ agent.tools = ["gone-tool"];
593
+ }, BACKGROUND_CONTEXT);
594
+
595
+ const refuse = () =>
596
+ rejects(
597
+ control(
598
+ { action: "resume", run: result.view.runId },
599
+ { runtime, wait: { policy: "settle", waitMs: 1_000 } },
600
+ ),
601
+ (error: unknown) => error instanceof RunNotResumable && error.message.includes("gone-tool"),
602
+ );
603
+ await refuse();
604
+ await refuse();
605
+
606
+ const stored = await runtime.snapshot(RunDoc, result.view.runId);
607
+ assert.deepStrictEqual(stored?.diagnostics, ["gone-tool"]);
608
+
609
+ const warnings = entries.filter((entry) => entry.code === "control.missing_names");
610
+ assert.strictEqual(warnings.length, 2);
611
+ assert.strictEqual(warnings[0]?.level, "warn");
612
+ assert.strictEqual(warnings[0]?.fields.runId, result.view.runId);
613
+ } finally {
614
+ await runtime.close();
615
+ }
616
+ });
617
+
618
+ it("control missing check reads no child runs", async () => {
619
+ const hold = deferred();
620
+ const runtime = await openTestSession({
621
+ identity: await identityFor("s-1"),
622
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
623
+ });
624
+ try {
625
+ const result = await launch(
626
+ {
627
+ kind: "fanout",
628
+ lane: "review",
629
+ agents: [
630
+ { agent: "scout", task: "first" },
631
+ { agent: "scout", task: "second" },
632
+ ],
633
+ },
634
+ { ...deps(runtime), waitMs: 50 },
635
+ );
636
+ const first = result.view.children[0]?.runId;
637
+ const second = result.view.children[1]?.runId;
638
+ assert.ok(first !== undefined && second !== undefined);
639
+
640
+ const counted = countingRuntime(runtime);
641
+ await control(
642
+ { action: "steer", run: first, message: "focus" },
643
+ { runtime: counted.runtime, wait: { policy: "settle", waitMs: 10_000 } },
644
+ );
645
+ assert.strictEqual(counted.count("delegates.run", second), 0);
646
+
647
+ hold.release();
648
+ await waitForStatus(runtime, first, "answered");
649
+ const doc = await runtime.snapshot(RunDoc, first);
650
+ const conversation = await runtime.harness.conversation(
651
+ doc!.childConversationId as never,
652
+ BACKGROUND_CONTEXT,
653
+ );
654
+ const context = await conversation!.context(BACKGROUND_CONTEXT);
655
+ assert.ok(
656
+ context.messages.some(
657
+ (message) =>
658
+ message.role === "user" &&
659
+ (typeof message.content === "string"
660
+ ? message.content
661
+ : message.content.map((part) => (part.type === "text" ? part.text : "")).join("")
662
+ ).includes("focus"),
663
+ ),
664
+ );
665
+ } finally {
666
+ hold.release();
667
+ await runtime.close();
668
+ }
669
+ }, 20_000);
670
+
671
+ it("a control wait timeout is logged and a settled wait is not", async () => {
672
+ const hold = deferred();
673
+ const entries: { code: string; fields: LogFields }[] = [];
674
+ const runtime = await openTestSession({
675
+ identity: await identityFor("s-1"),
676
+ models: new HostModelAdapter(stubHostSource({ hold: () => hold.promise })),
677
+ log: { write: (_level, code, fields = {}) => entries.push({ code, fields }) },
678
+ });
679
+ try {
680
+ const result = await launch(
681
+ { kind: "single", agent: "scout", task: "look around" },
682
+ { ...deps(runtime), waitMs: 50 },
683
+ );
684
+ const runId = result.view.runId;
685
+ entries.length = 0;
686
+
687
+ await control(
688
+ { action: "stop", run: runId },
689
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
690
+ );
691
+ assert.deepStrictEqual(
692
+ entries.filter((entry) => entry.code.startsWith("wait.")),
693
+ [],
694
+ );
695
+
696
+ const resumed = await control(
697
+ { action: "resume", run: runId },
698
+ { runtime, wait: { policy: "settle", waitMs: 1 } },
699
+ );
700
+ assert.strictEqual(resumed.view!.status, "running");
701
+ assert.deepStrictEqual(
702
+ entries
703
+ .filter((entry) => entry.code.startsWith("wait."))
704
+ .map((entry) => [entry.code, entry.fields.runId]),
705
+ [["wait.timeout", runId]],
706
+ );
707
+ } finally {
708
+ hold.release();
709
+ await runtime.close();
710
+ }
711
+ }, 20_000);
712
+
713
+ it("a steer refuses a run whose declared skill was deleted", async () => {
714
+ const root = await makeTempDir("delegates-control-skills-");
715
+ await makeDir(join(root, "alpha"));
716
+ await writeText(
717
+ join(root, "alpha", "SKILL.md"),
718
+ "---\nname: alpha\ndescription: The alpha skill\n---\n\nALPHA_BODY\n",
719
+ );
720
+ const identity = await identityFor("s-1");
721
+ const runtime = await openTestSession({
722
+ identity,
723
+ models: new HostModelAdapter(stubHostSource({ text: "done" })),
724
+ skills: { cwd: identity.cwd, agentDir: identity.agentDir, skillPaths: [root] },
725
+ });
726
+ try {
727
+ const definition = defineAgent({
728
+ name: "tester",
729
+ role: "Test agent",
730
+ prompt: { role: "You test." },
731
+ tools: ["read"],
732
+ extensions: [CODING_EXTENSION],
733
+ approval: { gates: [] },
734
+ skills: ["alpha"],
735
+ });
736
+ const result = await launch(
737
+ { kind: "single", agent: "tester", task: "look" },
738
+ { ...deps(runtime), catalogue: createCatalogue([definition]), waitMs: 10_000 },
739
+ );
740
+ await removePath(join(root, "alpha", "SKILL.md"));
741
+ await Effect.runPromise(runtime.skills.reload);
742
+
743
+ await rejects(
744
+ control(
745
+ { action: "steer", run: result.view.runId, message: "again" },
746
+ { runtime, wait: { policy: "settle", waitMs: 1_000 } },
747
+ ),
748
+ (error: unknown) => error instanceof RunNotRunning && error.message.includes("alpha"),
749
+ );
750
+ } finally {
751
+ await runtime.close();
752
+ }
753
+ });
754
+
755
+ const asker = defineAgent({
756
+ name: "asker",
757
+ role: "Asks the user",
758
+ prompt: { role: "Ask the user when the answer changes the next step." },
759
+ tools: ["ask"],
760
+ extensions: [QUESTIONS_EXTENSION],
761
+ approval: { gates: [] },
762
+ });
763
+
764
+ const askCatalogue = createCatalogue([asker]);
765
+
766
+ const openAsker = async (
767
+ source: StubHostOptions,
768
+ now?: () => number,
769
+ log?: LogSink,
770
+ ): Promise<TestSession> =>
771
+ openTestSession({
772
+ identity: await identityFor("s-1"),
773
+ models: new HostModelAdapter(stubHostSource(source)),
774
+ ...(now === undefined ? {} : { now }),
775
+ ...(log === undefined ? {} : { log }),
776
+ catalogue: askCatalogue,
777
+ });
778
+
779
+ const askOnce = {
780
+ respond: ({ messages }: { readonly messages: readonly { readonly role: string }[] }) =>
781
+ messages.some((message) => message.role === "toolResult")
782
+ ? { text: "done" }
783
+ : {
784
+ toolCall: {
785
+ name: "ask",
786
+ arguments: {
787
+ prompt: "Which environment?",
788
+ options: [{ label: "staging" }, { label: "production" }],
789
+ },
790
+ },
791
+ },
792
+ };
793
+
794
+ const askTwice = {
795
+ respond: ({ messages }: { readonly messages: readonly { readonly role: string }[] }) => {
796
+ const results = messages.filter((message) => message.role === "toolResult").length;
797
+ if (results === 0) {
798
+ return {
799
+ toolCall: {
800
+ name: "ask",
801
+ arguments: {
802
+ prompt: "Which environment?",
803
+ options: [{ label: "staging" }, { label: "production" }],
804
+ },
805
+ },
806
+ };
807
+ }
808
+ if (results === 1) {
809
+ return { toolCall: { name: "ask", arguments: { prompt: "Which region?" } } };
810
+ }
811
+ return { text: "done" };
812
+ },
813
+ };
814
+
815
+ it("answer commits the answer and wakes the parked call", async () => {
816
+ const runtime = await openAsker(askOnce);
817
+ try {
818
+ const launched = await launch(
819
+ { kind: "single", agent: "asker", task: "deploy it" },
820
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
821
+ );
822
+ assert.strictEqual(launched.view.status, "waiting");
823
+ const request = launched.view.requests[0];
824
+ assert.ok(request !== undefined, JSON.stringify(launched.view));
825
+
826
+ const result = await control(
827
+ { action: "answer", run: launched.view.runId, request, answer: "staging" },
828
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
829
+ );
830
+
831
+ assert.strictEqual(result.text, `answer ${launched.view.runId}: answered`);
832
+ assert.strictEqual(result.view?.status, "answered");
833
+ const record = await runtime.snapshot(RequestDoc, request as string);
834
+ assert.strictEqual(record?.status, "answered");
835
+ assert.strictEqual(record?.answer, "staging");
836
+ assert.strictEqual(record?.answeredBy?.sessionId, runtime.sessionId);
837
+ } finally {
838
+ await runtime.close();
839
+ }
840
+ }, 30_000);
841
+
842
+ it("stop cancels the parked request and logs it once", async () => {
843
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
844
+ const log: LogSink = {
845
+ write: (level, code, fields = {}) => {
846
+ entries.push({ level, code, fields });
847
+ },
848
+ };
849
+ const runtime = await openAsker(askOnce, undefined, log);
850
+ try {
851
+ const launched = await launch(
852
+ { kind: "single", agent: "asker", task: "deploy it" },
853
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
854
+ );
855
+ assert.strictEqual(launched.view.status, "waiting");
856
+ const request = launched.view.requests[0];
857
+ assert.ok(request !== undefined, JSON.stringify(launched.view));
858
+
859
+ await control(
860
+ { action: "stop", run: launched.view.runId },
861
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
862
+ );
863
+
864
+ const record = await runtime.snapshot(RequestDoc, request as string);
865
+ assert.strictEqual(record?.status, "cancelled");
866
+ assert.strictEqual(record?.reason, "stopped");
867
+ assert.deepStrictEqual(
868
+ entries.filter((entry) => entry.code === "request.cancelled"),
869
+ [
870
+ {
871
+ level: "info",
872
+ code: "request.cancelled",
873
+ fields: { runId: launched.view.runId, requestId: request },
874
+ },
875
+ ],
876
+ );
877
+ } finally {
878
+ await runtime.close();
879
+ }
880
+ }, 30_000);
881
+
882
+ it("the answer returns the child's next request", async () => {
883
+ const runtime = await openAsker(askTwice);
884
+ try {
885
+ const launched = await launch(
886
+ { kind: "single", agent: "asker", task: "deploy it" },
887
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
888
+ );
889
+ const first = launched.view.requests[0];
890
+ assert.ok(first !== undefined);
891
+
892
+ const result = await control(
893
+ { action: "answer", run: launched.view.runId, request: first, answer: "staging" },
894
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
895
+ );
896
+
897
+ const next = result.view?.requests[0];
898
+ assert.ok(next !== undefined, JSON.stringify(result.view));
899
+ assert.notStrictEqual(next, first);
900
+ assert.strictEqual(result.text, `answer ${launched.view.runId}: waits for request ${next}`);
901
+ } finally {
902
+ await runtime.close();
903
+ }
904
+ }, 30_000);
905
+
906
+ it("the answer addressed by a child run id returns at its next request", async () => {
907
+ const runtime = await openAsker(askTwice);
908
+ try {
909
+ const launched = await launch(
910
+ { kind: "fanout", lane: "default", agents: [{ agent: "asker", task: "deploy it" }] },
911
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
912
+ );
913
+ const childRunId = launched.view.children[0]?.runId;
914
+ const first = launched.view.requests[0];
915
+ assert.ok(childRunId !== undefined, JSON.stringify(launched.view));
916
+ assert.ok(first !== undefined, JSON.stringify(launched.view));
917
+
918
+ const result = await control(
919
+ { action: "answer", run: childRunId, request: first, answer: "staging" },
920
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
921
+ );
922
+
923
+ const next = result.view?.requests[0];
924
+ assert.ok(next !== undefined, JSON.stringify(result.view));
925
+ assert.notStrictEqual(next, first);
926
+ assert.strictEqual(result.text, `answer ${childRunId}: waits for request ${next}`);
927
+ } finally {
928
+ await runtime.close();
929
+ }
930
+ }, 30_000);
931
+
932
+ it("the answer text names the next request or falls back to the status", () => {
933
+ assert.strictEqual(answerText("run:1", "answered", []), "answer run:1: answered");
934
+ assert.strictEqual(
935
+ answerText("run:1", "waiting", ["12:c1", "12:c2"]),
936
+ "answer run:1: waits for request 12:c1, 12:c2",
937
+ );
938
+ });
939
+
940
+ it("a second answer is refused", async () => {
941
+ const runtime = await openAsker(askOnce);
942
+ try {
943
+ const launched = await launch(
944
+ { kind: "single", agent: "asker", task: "deploy it" },
945
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
946
+ );
947
+ const request = launched.view.requests[0] as string;
948
+ await answerRequest(
949
+ { run: launched.view.runId, request, answer: "staging", sessionId: runtime.sessionId },
950
+ runtime,
951
+ );
952
+ await rejects(
953
+ answerRequest(
954
+ { run: launched.view.runId, request, answer: "production", sessionId: runtime.sessionId },
955
+ runtime,
956
+ ),
957
+ (error) => error instanceof RequestAlreadyAnswered,
958
+ );
959
+ const record = await runtime.snapshot(RequestDoc, request);
960
+ assert.strictEqual(record?.answer, "staging");
961
+ } finally {
962
+ await runtime.close();
963
+ }
964
+ }, 30_000);
965
+
966
+ it("decline cancels the request without waiting", async () => {
967
+ const runtime = await openAsker(askOnce);
968
+ try {
969
+ const launched = await launch(
970
+ { kind: "single", agent: "asker", task: "deploy it" },
971
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
972
+ );
973
+ const request = launched.view.requests[0] as string;
974
+
975
+ const result = await control(
976
+ { action: "decline", run: launched.view.runId, request },
977
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
978
+ );
979
+
980
+ assert.strictEqual(result.view, undefined);
981
+ assert.strictEqual(result.text, `decline ${launched.view.runId}: cancelled`);
982
+ const record = await runtime.snapshot(RequestDoc, request);
983
+ assert.strictEqual(record?.status, "cancelled");
984
+ assert.strictEqual(record?.reason, "declined");
985
+
986
+ // The child wakes with an error and finishes; the run reads denied, not answered.
987
+ let view = await viewRun(launched.view.runId, runtime);
988
+ for (let attempt = 0; attempt < 200 && view.status !== "denied"; attempt += 1) {
989
+ await new Promise((resolve) => setTimeout(resolve, 25));
990
+ view = await viewRun(launched.view.runId, runtime);
991
+ }
992
+ assert.strictEqual(view.status, "denied");
993
+ assert.strictEqual(view.answer, null);
994
+ assert.ok(view.diagnostic?.includes(request), view.diagnostic ?? "");
995
+ assert.deepStrictEqual(laneViews([view]), [
996
+ { name: view.lane, running: 0, queued: 0, answered: 0 },
997
+ ]);
998
+ } finally {
999
+ await runtime.close();
1000
+ }
1001
+ }, 30_000);
1002
+
1003
+ it("an unknown request is refused", async () => {
1004
+ const runtime = await openAsker(askOnce);
1005
+ try {
1006
+ await rejects(
1007
+ answerRequest(
1008
+ { run: "run:9", request: "99:x", answer: "a", sessionId: runtime.sessionId },
1009
+ runtime,
1010
+ ),
1011
+ (error) => error instanceof RequestNotFound,
1012
+ );
1013
+ } finally {
1014
+ await runtime.close();
1015
+ }
1016
+ });
1017
+
1018
+ const seedRequest = async (
1019
+ runtime: SessionRuntime,
1020
+ input: {
1021
+ readonly key: string;
1022
+ readonly runId: string;
1023
+ readonly childRunId?: string;
1024
+ readonly status?: "pending" | "answered" | "cancelled";
1025
+ readonly deadline?: number;
1026
+ readonly reason?: string | null;
1027
+ readonly allowOther?: boolean;
1028
+ },
1029
+ ): Promise<void> => {
1030
+ const now = runtime.now();
1031
+ await runtime.run((context) =>
1032
+ runtime.harness.commit(async (tx) => {
1033
+ const record = await tx.doc(RequestDoc, input.key, { requestId: input.key });
1034
+ record.runId = input.runId;
1035
+ record.childRunId = input.childRunId ?? input.runId;
1036
+ record.conversationId = 12;
1037
+ record.prompt = "Which environment?";
1038
+ record.options = [
1039
+ { label: "staging", description: null, recommended: false },
1040
+ { label: "production", description: null, recommended: false },
1041
+ ];
1042
+ record.allowOther = input.allowOther ?? true;
1043
+ record.status = input.status ?? "pending";
1044
+ record.requestedAt = now;
1045
+ record.deadline = input.deadline ?? now + 60_000;
1046
+ record.reason = input.reason ?? null;
1047
+ const index = await tx.doc(RequestIndexDoc);
1048
+ index.rows.push({
1049
+ key: input.key,
1050
+ runId: input.runId,
1051
+ requestId: input.key,
1052
+ requestedAt: record.requestedAt,
1053
+ deadline: record.deadline,
1054
+ status: record.status,
1055
+ });
1056
+ }, context),
1057
+ );
1058
+ };
1059
+
1060
+ it("a run id or a child run id is accepted", async () => {
1061
+ const runtime = await openAsker(askOnce);
1062
+ try {
1063
+ await seedRequest(runtime, {
1064
+ key: "12:child",
1065
+ runId: "run:1",
1066
+ childRunId: "run:1:child:2",
1067
+ allowOther: false,
1068
+ });
1069
+ const first = await answerRequest(
1070
+ { run: "run:1:child:2", request: "12:child", answer: "1", sessionId: runtime.sessionId },
1071
+ runtime,
1072
+ );
1073
+ assert.strictEqual(first.record.answer, "staging");
1074
+
1075
+ await seedRequest(runtime, { key: "12:parent", runId: "run:1", childRunId: "run:1:child:2" });
1076
+ const second = await answerRequest(
1077
+ { run: "run:1", request: "12:parent", answer: "production", sessionId: runtime.sessionId },
1078
+ runtime,
1079
+ );
1080
+ assert.strictEqual(second.record.answer, "production");
1081
+
1082
+ await rejects(
1083
+ answerRequest(
1084
+ { run: "run:9", request: "12:parent", answer: "staging", sessionId: runtime.sessionId },
1085
+ runtime,
1086
+ ),
1087
+ (error) => error instanceof RequestNotFound,
1088
+ );
1089
+ } finally {
1090
+ await runtime.close();
1091
+ }
1092
+ });
1093
+
1094
+ it("a pending record past its deadline is refused and recorded expired", async () => {
1095
+ const runtime = await openAsker(askOnce, () => 1_000_000);
1096
+ try {
1097
+ await seedRequest(runtime, {
1098
+ key: "12:late",
1099
+ runId: "run:1",
1100
+ deadline: 999_000,
1101
+ });
1102
+ await rejects(
1103
+ answerRequest(
1104
+ { run: "run:1", request: "12:late", answer: "staging", sessionId: runtime.sessionId },
1105
+ runtime,
1106
+ ),
1107
+ (error) => error instanceof RequestAlreadyDecided,
1108
+ );
1109
+ const record = await runtime.snapshot(RequestDoc, "12:late");
1110
+ assert.strictEqual(record?.status, "expired");
1111
+ assert.strictEqual(record?.reason, "deadline");
1112
+ } finally {
1113
+ await runtime.close();
1114
+ }
1115
+ });
1116
+
1117
+ it("a declined request refuses the answer", async () => {
1118
+ const runtime = await openAsker(askOnce);
1119
+ try {
1120
+ await seedRequest(runtime, {
1121
+ key: "12:declined",
1122
+ runId: "run:1",
1123
+ status: "cancelled",
1124
+ reason: "declined",
1125
+ });
1126
+ await rejects(
1127
+ answerRequest(
1128
+ {
1129
+ run: "run:1",
1130
+ request: "12:declined",
1131
+ answer: "staging",
1132
+ sessionId: runtime.sessionId,
1133
+ },
1134
+ runtime,
1135
+ ),
1136
+ (error) =>
1137
+ error instanceof RequestAlreadyDecided && error.message.includes("cancelled: declined"),
1138
+ );
1139
+ } finally {
1140
+ await runtime.close();
1141
+ }
1142
+ });
1143
+
1144
+ it("an answer outside the options leaves the request pending", async () => {
1145
+ const strict = {
1146
+ respond: ({ messages }: { readonly messages: readonly { readonly role: string }[] }) =>
1147
+ messages.some((message) => message.role === "toolResult")
1148
+ ? { text: "done" }
1149
+ : {
1150
+ toolCall: {
1151
+ name: "ask",
1152
+ arguments: {
1153
+ prompt: "Which environment?",
1154
+ options: [{ label: "staging" }, { label: "production" }],
1155
+ allowOther: false,
1156
+ },
1157
+ },
1158
+ },
1159
+ };
1160
+ const runtime = await openAsker(strict);
1161
+ try {
1162
+ const launched = await launch(
1163
+ { kind: "single", agent: "asker", task: "deploy it" },
1164
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
1165
+ );
1166
+ const request = launched.view.requests[0];
1167
+ assert.ok(request !== undefined, JSON.stringify(launched.view));
1168
+
1169
+ await rejects(
1170
+ answerRequest(
1171
+ { run: launched.view.runId, request, answer: "qa", sessionId: runtime.sessionId },
1172
+ runtime,
1173
+ ),
1174
+ (error) =>
1175
+ error instanceof InvalidRequestAnswer && error.message.includes("staging, production"),
1176
+ );
1177
+
1178
+ const record = await runtime.snapshot(RequestDoc, request);
1179
+ assert.strictEqual(record?.status, "pending");
1180
+ } finally {
1181
+ await runtime.close();
1182
+ }
1183
+ }, 30_000);
1184
+
1185
+ it("the answer is normalized to the canonical label", () => {
1186
+ const record: RequestRecord = {
1187
+ runId: "run:1",
1188
+ childRunId: "run:1",
1189
+ requestId: "12:c1",
1190
+ conversationId: 12,
1191
+ prompt: "Which environment?",
1192
+ options: [
1193
+ { label: "staging", description: null, recommended: false },
1194
+ { label: "production", description: null, recommended: false },
1195
+ ],
1196
+ allowOther: false,
1197
+ status: "pending",
1198
+ taskIds: [],
1199
+ requestedAt: 0,
1200
+ deadline: 0,
1201
+ answer: null,
1202
+ answeredBy: null,
1203
+ reason: null,
1204
+ };
1205
+ assert.strictEqual(normalizeAnswer(record, "1. STAGING"), "staging");
1206
+ assert.strictEqual(normalizeAnswer(record, "staging "), "staging");
1207
+ assert.strictEqual(normalizeAnswer(record, "2"), "production");
1208
+ assert.strictEqual(normalizeAnswer(record, "Production"), "production");
1209
+ assert.strictEqual(normalizeAnswer({ ...record, allowOther: true }, " qa east "), "qa east");
1210
+ throws(
1211
+ () => normalizeAnswer(record, "qa"),
1212
+ (error) => {
1213
+ assert.ok(error instanceof InvalidRequestAnswer, String(error));
1214
+ assert.ok(error.message.includes("staging, production"), error.message);
1215
+ return true;
1216
+ },
1217
+ );
1218
+ throws(() => normalizeAnswer(record, "7"), /numbered 1-2/);
1219
+ throws(() => normalizeAnswer({ ...record, allowOther: true }, "x".repeat(4_097)), /4096/);
1220
+ throws(() => normalizeAnswer(record, " "), /required/);
1221
+ });
1222
+
1223
+ it("control decodes the new actions", () => {
1224
+ throws(() => decodeControl({ action: "answer", run: "r1" }), /request is required/);
1225
+ throws(
1226
+ () => decodeControl({ action: "answer", run: "r1", request: "12:c1" }),
1227
+ /answer is required/,
1228
+ );
1229
+ throws(() => decodeControl({ action: "decline", run: "r1" }), /request is required/);
1230
+ });
1231
+
1232
+ it("stop cancels the run's pending requests", async () => {
1233
+ const runtime = await openAsker(askOnce);
1234
+ try {
1235
+ const launched = await launch(
1236
+ { kind: "single", agent: "asker", task: "deploy it" },
1237
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
1238
+ );
1239
+ const request = launched.view.requests[0] as string;
1240
+
1241
+ await control(
1242
+ { action: "stop", run: launched.view.runId },
1243
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
1244
+ );
1245
+
1246
+ const record = await runtime.snapshot(RequestDoc, request);
1247
+ assert.strictEqual(record?.status, "cancelled");
1248
+ assert.strictEqual(record?.reason, "stopped");
1249
+ } finally {
1250
+ await runtime.close();
1251
+ }
1252
+ }, 30_000);
1253
+
1254
+ it("an expired request renders no waiting text", async () => {
1255
+ let now = 1_000;
1256
+ const runtime = await openAsker(askOnce, () => now);
1257
+ try {
1258
+ const launched = await launch(
1259
+ { kind: "single", agent: "asker", task: "deploy it" },
1260
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
1261
+ );
1262
+ const request = launched.view.requests[0];
1263
+ assert.ok(request !== undefined, JSON.stringify(launched.view));
1264
+ const record = await runtime.snapshot(RequestDoc, request);
1265
+ assert.ok(record !== undefined);
1266
+ now = record.deadline + 1;
1267
+
1268
+ const run = await viewRun(launched.view.runId, runtime);
1269
+ const text = renderStatusText({ runs: [run], lanes: [], gates: [], requests: [], reviews: [] });
1270
+
1271
+ assert.ok(!text.includes("waiting on request"), text);
1272
+ assert.ok(run.requests.length === 0, JSON.stringify(run));
1273
+ } finally {
1274
+ await runtime.close();
1275
+ }
1276
+ }, 30_000);
1277
+
1278
+ it("status names the waiting request", async () => {
1279
+ const runtime = await openAsker(askOnce);
1280
+ try {
1281
+ const launched = await launch(
1282
+ { kind: "single", agent: "asker", task: "deploy it" },
1283
+ { runtime, catalogue: askCatalogue, host, waitMs: 5_000 },
1284
+ );
1285
+ const request = launched.view.requests[0] as string;
1286
+ const run = await viewRun(launched.view.runId, runtime);
1287
+ const text = renderStatusText({
1288
+ runs: [run],
1289
+ lanes: [],
1290
+ gates: [],
1291
+ requests: [],
1292
+ reviews: [],
1293
+ });
1294
+
1295
+ assert.ok(text.includes(`waiting on request ${request}`), text);
1296
+ } finally {
1297
+ await runtime.close();
1298
+ }
1299
+ }, 30_000);
1300
+
1301
+ it("control names the action's own missing field before run when both are absent", async () => {
1302
+ const runtime = await openTestSession({
1303
+ identity: await identityFor("s-1"),
1304
+ models: new HostModelAdapter(stubHostSource({ text: "done" })),
1305
+ });
1306
+ try {
1307
+ await rejects(
1308
+ control({ action: "answer" }, { runtime, wait: { policy: "commit" } }),
1309
+ (error: unknown) =>
1310
+ error instanceof InvalidControlRequest &&
1311
+ error.message === 'Control action "answer" is invalid: request is required.',
1312
+ );
1313
+ } finally {
1314
+ await runtime.close();
1315
+ }
1316
+ });
1317
+
1318
+ it("control names run last when the action is complete but the run is absent", async () => {
1319
+ const runtime = await openTestSession({
1320
+ identity: await identityFor("s-1"),
1321
+ models: new HostModelAdapter(stubHostSource({ text: "done" })),
1322
+ });
1323
+ try {
1324
+ await rejects(
1325
+ control({ action: "approve", gate: "deploy" }, { runtime, wait: { policy: "commit" } }),
1326
+ (error: unknown) =>
1327
+ error instanceof InvalidControlRequest && error.message.endsWith("run is required."),
1328
+ );
1329
+ } finally {
1330
+ await runtime.close();
1331
+ }
1332
+ });