@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,700 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { assert, it } from "@effect/vitest";
3
+ import { Effect } from "effect";
4
+ import { mkdtemp } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { stubHostSource } from "../../../test-support/stub-model-source.ts";
8
+ import { HostModelAdapter } from "../../runtime/models.ts";
9
+ import {
10
+ openReadOnlyRuntime,
11
+ openSessionRuntime,
12
+ storePathFor,
13
+ type SessionIdentity,
14
+ } from "../../runtime/session.ts";
15
+ import { CODING_EXTENSION, QUESTIONS_EXTENSION } from "../names.ts";
16
+ import type { SessionRuntime } from "../../runtime/session.ts";
17
+ import { nullLogSink, type LogFields, type LogLevel, type LogSink } from "../../runtime/log.ts";
18
+ import { bindToolkit } from "../toolkit.ts";
19
+ import { defineAgent } from "../definitions.ts";
20
+ import { refusingSandbox } from "./workflow-section.ts";
21
+ import { createDelegatesRegistry } from "../../runtime/extensions.ts";
22
+ import type { AdmissionHost } from "./admission.ts";
23
+ import type { SkillsService } from "../skills.ts";
24
+ import { DAY_MS } from "./gates.ts";
25
+ import {
26
+ askTool,
27
+ PRUNE_AFTER_MS,
28
+ pendingRequests,
29
+ pruneRequests,
30
+ RequestDecided,
31
+ RequestDoc,
32
+ RequestIndexDoc,
33
+ requestKey,
34
+ requestRecords,
35
+ requestState,
36
+ type RequestIndexRow,
37
+ type RequestRecord,
38
+ } from "./requests.ts";
39
+
40
+ interface DocToken {
41
+ readonly definition: {
42
+ readonly kind: string;
43
+ readonly family?: true;
44
+ initial(seed?: never): Record<string, unknown>;
45
+ };
46
+ }
47
+
48
+ type ToolResult = {
49
+ readonly output?: readonly { readonly text?: string }[];
50
+ readonly structuredOutput?: unknown;
51
+ readonly isError?: boolean;
52
+ readonly sleep?: { readonly signals: readonly unknown[]; readonly until?: number };
53
+ };
54
+
55
+ const toolkitSeed = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
56
+ definition: "asker",
57
+ runId: "run:1",
58
+ runTaskId: 1,
59
+ childRunId: "run:1",
60
+ approval: { gates: [] },
61
+ skills: [],
62
+ ...overrides,
63
+ });
64
+
65
+ /** The store and the signal seam as an in-memory double; no harness is involved. */
66
+ const fakeSession = (
67
+ options: {
68
+ readonly toolkit?: Record<string, unknown> | false;
69
+ readonly now?: number;
70
+ readonly record?: Partial<RequestRecord>;
71
+ readonly row?: RequestIndexRow;
72
+ } = {},
73
+ ) => {
74
+ const docs = new Map<string, Record<string, unknown>>();
75
+ const memos = new Map<string, unknown>();
76
+ const toolkit = options.toolkit === false ? undefined : (options.toolkit ?? toolkitSeed());
77
+ const idOf = (token: DocToken, key?: string): string => `${token.definition.kind}:${key ?? ""}`;
78
+ const key = "12:c1";
79
+ if (toolkit !== undefined) docs.set("delegates.toolkit:12", toolkit);
80
+ if (options.record !== undefined) {
81
+ docs.set(`delegates.request:${key}`, {
82
+ runId: "run:1",
83
+ childRunId: "run:1",
84
+ requestId: key,
85
+ conversationId: 12,
86
+ prompt: "Which environment?",
87
+ options: [],
88
+ allowOther: true,
89
+ status: "pending",
90
+ taskIds: [7],
91
+ requestedAt: 0,
92
+ deadline: 0,
93
+ answer: null,
94
+ answeredBy: null,
95
+ reason: null,
96
+ ...options.record,
97
+ });
98
+ docs.set("delegates.request-index:", {
99
+ rows: [
100
+ options.row ?? {
101
+ key,
102
+ runId: "run:1",
103
+ requestId: key,
104
+ requestedAt: 0,
105
+ deadline: 0,
106
+ status: "pending",
107
+ },
108
+ ],
109
+ });
110
+ }
111
+ let commits = 0;
112
+ let beforeCommit: (() => void) | undefined;
113
+ const snapshot = async <T>(token: DocToken, docKey?: string): Promise<T | undefined> =>
114
+ docs.get(idOf(token, docKey)) as T | undefined;
115
+ const tx = {
116
+ doc: async (token: DocToken, docKey?: string, seed?: never) => {
117
+ const id = idOf(token, docKey);
118
+ const found = docs.get(id);
119
+ if (found !== undefined) return found;
120
+ const created = token.definition.initial(seed);
121
+ docs.set(id, created);
122
+ return created;
123
+ },
124
+ retireDoc: async (token: DocToken, docKey?: string) => {
125
+ docs.delete(idOf(token, docKey));
126
+ },
127
+ };
128
+ const commit = async <T>(change: (transaction: typeof tx) => T): Promise<T> => {
129
+ commits += 1;
130
+ beforeCommit?.();
131
+ return change(tx);
132
+ };
133
+ const api = {
134
+ conversationId: 12,
135
+ callId: "c1",
136
+ taskId: 7,
137
+ now: () => options.now ?? 1_000,
138
+ memo: async (name: string, candidate: unknown) => {
139
+ const found = memos.get(name);
140
+ if (found !== undefined) return found;
141
+ memos.set(name, candidate);
142
+ return candidate;
143
+ },
144
+ snapshot,
145
+ commit,
146
+ };
147
+ return {
148
+ api,
149
+ docs,
150
+ memos,
151
+ commits: () => commits,
152
+ beforeCommit: (hook: () => void) => {
153
+ beforeCommit = hook;
154
+ },
155
+ record: () => docs.get(`delegates.request:${key}`) as RequestRecord | undefined,
156
+ mutate: (change: (doc: Record<string, unknown>) => void) => {
157
+ const doc = docs.get(`delegates.request:${key}`);
158
+ if (doc !== undefined) change(doc);
159
+ },
160
+ rows: () =>
161
+ (docs.get("delegates.request-index:") as { rows: RequestIndexRow[] } | undefined)?.rows ?? [],
162
+ seed: (kind: string, docKey: string, value: Record<string, unknown>) => {
163
+ docs.set(`${kind}:${docKey}`, value);
164
+ },
165
+ };
166
+ };
167
+
168
+ const runAsk = (api: unknown, args: unknown): Promise<ToolResult> =>
169
+ (
170
+ askTool(nullLogSink).execute as unknown as (
171
+ args: unknown,
172
+ api: unknown,
173
+ context: unknown,
174
+ ) => Promise<ToolResult>
175
+ )(args, api, BACKGROUND_CONTEXT);
176
+
177
+ it("the ask tool commits a pending request and parks", async () => {
178
+ const session = fakeSession();
179
+ const result = await runAsk(session.api, {
180
+ prompt: "Which environment?",
181
+ options: [{ label: "staging" }, { label: "production" }],
182
+ });
183
+
184
+ assert.deepStrictEqual(result.sleep?.signals, [RequestDecided.key("12:c1")]);
185
+ const record = session.record();
186
+ assert.strictEqual(record?.status, "pending");
187
+ assert.strictEqual(record?.prompt, "Which environment?");
188
+ assert.deepStrictEqual(
189
+ record?.options.map((option) => option.label),
190
+ ["staging", "production"],
191
+ );
192
+ assert.strictEqual(record?.allowOther, true);
193
+ assert.strictEqual(record?.deadline, 1_000 + DAY_MS);
194
+ assert.strictEqual(record?.taskIds.length, 1);
195
+
196
+ const rows = session.rows();
197
+ assert.strictEqual(rows.length, 1);
198
+ assert.strictEqual(rows[0]?.key, "12:c1");
199
+ assert.strictEqual(rows[0]?.runId, "run:1");
200
+ assert.strictEqual(rows[0]?.deadline, 1_000 + DAY_MS);
201
+ assert.strictEqual(rows[0]?.status, "pending");
202
+ });
203
+
204
+ it("a replay of the same call returns the committed answer as user input", async () => {
205
+ const session = fakeSession({
206
+ record: {
207
+ status: "answered",
208
+ answer: "staging",
209
+ requestedAt: 1_000,
210
+ deadline: 1_000 + DAY_MS,
211
+ answeredBy: { sessionId: "s-1" },
212
+ },
213
+ });
214
+ const result = await runAsk(session.api, {
215
+ prompt: "Which environment?",
216
+ options: [{ label: "staging" }, { label: "production" }],
217
+ });
218
+
219
+ assert.strictEqual(result.output?.[0]?.text, "The user answered: staging");
220
+ assert.deepStrictEqual(result.structuredOutput, { answer: "staging", source: "user" });
221
+ assert.strictEqual(result.sleep, undefined);
222
+ });
223
+
224
+ it("a pending request past its deadline expires instead of parking", async () => {
225
+ const session = fakeSession({
226
+ now: 1_000,
227
+ record: { status: "pending", requestedAt: 0, deadline: 999 },
228
+ });
229
+ session.memos.set("request.deadline.12:c1", 999);
230
+ const result = await runAsk(session.api, { prompt: "Which environment?" });
231
+
232
+ assert.strictEqual(result.isError, true);
233
+ const text = result.output?.[0]?.text ?? "";
234
+ assert.ok(text.includes("12:c1"), text);
235
+ assert.ok(text.includes("999"), text);
236
+ assert.strictEqual(session.record()?.status, "expired");
237
+ assert.strictEqual(session.record()?.reason, "deadline");
238
+ });
239
+
240
+ it("the park takes its deadline from the record, not the memo", async () => {
241
+ const session = fakeSession({
242
+ now: 1_000,
243
+ record: { status: "pending", requestedAt: 1_000, deadline: 1_500 },
244
+ });
245
+ const result = await runAsk(session.api, { prompt: "Which environment?" });
246
+
247
+ assert.strictEqual(result.sleep?.until, 1_500);
248
+ assert.strictEqual(session.memos.size, 0);
249
+ });
250
+
251
+ it("a request outside a child conversation is refused and writes nothing", async () => {
252
+ const session = fakeSession({ toolkit: false });
253
+ const result = await runAsk(session.api, { prompt: "Which environment?" });
254
+
255
+ assert.strictEqual(result.isError, true);
256
+ assert.ok((result.output?.[0]?.text ?? "").includes("a child conversation"));
257
+ assert.strictEqual(session.rows().length, 0);
258
+ assert.strictEqual(session.record(), undefined);
259
+ });
260
+
261
+ it("an invalid option list writes nothing", async () => {
262
+ const cases: readonly { readonly options: readonly unknown[]; readonly names: string }[] = [
263
+ { options: [{ label: "only" }], names: "2-5" },
264
+ {
265
+ options: [
266
+ { label: "a" },
267
+ { label: "b" },
268
+ { label: "c" },
269
+ { label: "d" },
270
+ { label: "e" },
271
+ { label: "f" },
272
+ ],
273
+ names: "at most 5",
274
+ },
275
+ { options: [{ label: "prod" }, { label: "prod" }], names: "unique" },
276
+ {
277
+ options: [
278
+ { label: "a", recommended: true },
279
+ { label: "b", recommended: true },
280
+ ],
281
+ names: "recommended",
282
+ },
283
+ { options: [{ label: "" }, { label: "b" }], names: "empty label" },
284
+ ];
285
+ for (const entry of cases) {
286
+ const session = fakeSession();
287
+ const result = await runAsk(session.api, {
288
+ prompt: "Which environment?",
289
+ options: entry.options,
290
+ });
291
+ assert.strictEqual(result.isError, true, entry.names);
292
+ assert.ok((result.output?.[0]?.text ?? "").includes(entry.names), entry.names);
293
+ assert.strictEqual(session.record(), undefined, entry.names);
294
+ assert.strictEqual(session.rows().length, 0, entry.names);
295
+ }
296
+ });
297
+
298
+ it("a free-text request cannot forbid other answers", async () => {
299
+ const session = fakeSession();
300
+ const result = await runAsk(session.api, {
301
+ prompt: "Which environment?",
302
+ allowOther: false,
303
+ });
304
+ assert.strictEqual(result.isError, true);
305
+ assert.ok((result.output?.[0]?.text ?? "").includes("free text"));
306
+ assert.strictEqual(session.record(), undefined);
307
+ assert.strictEqual(session.rows().length, 0);
308
+ });
309
+
310
+ it("a field over its bound is refused", async () => {
311
+ const cases: readonly { readonly args: unknown; readonly names: string }[] = [
312
+ { args: { prompt: "x".repeat(4_097) }, names: "4096" },
313
+ {
314
+ args: {
315
+ prompt: "Which environment?",
316
+ options: [{ label: "x".repeat(129) }, { label: "production" }],
317
+ },
318
+ names: "128",
319
+ },
320
+ {
321
+ args: {
322
+ prompt: "Which environment?",
323
+ options: [{ label: "staging", description: "x".repeat(1_025) }, { label: "production" }],
324
+ },
325
+ names: "1024",
326
+ },
327
+ { args: { prompt: " " }, names: "prompt" },
328
+ ];
329
+ for (const entry of cases) {
330
+ const session = fakeSession();
331
+ const result = await runAsk(session.api, entry.args);
332
+ assert.strictEqual(result.isError, true, entry.names);
333
+ assert.ok((result.output?.[0]?.text ?? "").includes(entry.names), entry.names);
334
+ assert.strictEqual(session.record(), undefined, entry.names);
335
+ }
336
+ });
337
+
338
+ it("an answer that lands before the commit makes the tool return instead of parking", async () => {
339
+ const session = fakeSession({
340
+ record: { status: "pending", requestedAt: 1_000, deadline: 1_000 + DAY_MS },
341
+ });
342
+ session.beforeCommit(() => {
343
+ session.mutate((doc) => {
344
+ doc.status = "answered";
345
+ doc.answer = "staging";
346
+ });
347
+ });
348
+ const result = await runAsk(session.api, { prompt: "Which environment?" });
349
+
350
+ assert.strictEqual(result.sleep, undefined);
351
+ assert.strictEqual(result.output?.[0]?.text, "The user answered: staging");
352
+ assert.strictEqual(session.rows().length, 1);
353
+ });
354
+
355
+ it("the registry installs ask under the questions extension", async () => {
356
+ const skills: SkillsService = {
357
+ all: () => [],
358
+ find: () => undefined,
359
+ resolve: () => [],
360
+ render: () => "",
361
+ diagnostics: () => [],
362
+ reload: Effect.void,
363
+ };
364
+ const admission: AdmissionHost = {
365
+ inspect: () => Promise.reject(new Error("the install must not inspect the harness")),
366
+ caps: () => ({ laneCap: 1, sessionCeiling: 1 }),
367
+ pollMs: 10,
368
+ };
369
+ const registry = createDelegatesRegistry({
370
+ admission,
371
+ skills,
372
+ sandbox: refusingSandbox(),
373
+ }).registry;
374
+ const snapshot = registry.snapshot();
375
+ const extension = snapshot.extension(QUESTIONS_EXTENSION);
376
+ assert.ok(extension !== undefined);
377
+ assert.deepStrictEqual(
378
+ extension.tools?.map((tool) => tool.name),
379
+ ["ask"],
380
+ );
381
+ assert.notStrictEqual(extension.tools?.[0]?.deferred, true);
382
+
383
+ const definition = defineAgent({
384
+ name: "asker",
385
+ role: "Asks the user",
386
+ prompt: { role: "You ask." },
387
+ tools: ["ask"],
388
+ extensions: [QUESTIONS_EXTENSION, CODING_EXTENSION],
389
+ approval: { gates: [] },
390
+ });
391
+ const bound = await Effect.runPromise(
392
+ bindToolkit(definition, {
393
+ availableExtensions: snapshot.installed().map((entry) => entry.name),
394
+ availableTools: snapshot.tools().map((entry) => entry.tool.name),
395
+ availableSkills: [],
396
+ extension: (name) => snapshot.extension(name),
397
+ tool: (name) => snapshot.tools().find((entry) => entry.tool.name === name)?.tool,
398
+ skill: () => undefined,
399
+ mcpServers: [],
400
+ codemodeTools: [],
401
+ unconnected: undefined,
402
+ matchTools: () => [],
403
+ }),
404
+ );
405
+ assert.deepStrictEqual(bound.names.extensions, [QUESTIONS_EXTENSION, CODING_EXTENSION]);
406
+ assert.deepStrictEqual(bound.names.tools, ["ask"]);
407
+ });
408
+
409
+ it("a wake on a pending request re-parks without a second index row", async () => {
410
+ const session = fakeSession();
411
+ const args = { prompt: "Which environment?" };
412
+ await runAsk(session.api, args);
413
+ const first = session.record()?.prompt;
414
+ const result = await runAsk(session.api, args);
415
+
416
+ assert.notStrictEqual(result.sleep, undefined);
417
+ assert.strictEqual(session.rows().length, 1);
418
+ assert.strictEqual(session.record()?.prompt, first);
419
+ });
420
+
421
+ it("requestState derives expiry from the deadline", () => {
422
+ assert.strictEqual(requestState({ status: "pending", deadline: 10 }, 9), "pending");
423
+ assert.strictEqual(requestState({ status: "pending", deadline: 10 }, 10), "expired");
424
+ assert.strictEqual(requestState({ status: "answered", deadline: 10 }, 10), "answered");
425
+ });
426
+
427
+ it("requestRecords filters by run and orders by request time", async () => {
428
+ const later: RequestRecord = {
429
+ runId: "run:1",
430
+ childRunId: "run:1",
431
+ requestId: "12:c2",
432
+ conversationId: 12,
433
+ prompt: "second",
434
+ options: [],
435
+ allowOther: true,
436
+ status: "pending",
437
+ taskIds: [],
438
+ requestedAt: 2_000,
439
+ deadline: 3_000,
440
+ answer: null,
441
+ answeredBy: null,
442
+ reason: null,
443
+ };
444
+ const earlier: RequestRecord = {
445
+ ...later,
446
+ requestId: "12:c1",
447
+ prompt: "first",
448
+ requestedAt: 1_000,
449
+ };
450
+ const other: RequestRecord = { ...later, runId: "run:2", requestId: "13:c1" };
451
+ const rows: RequestIndexRow[] = [later, earlier, other].map((record) => ({
452
+ key: record.requestId,
453
+ runId: record.runId,
454
+ requestId: record.requestId,
455
+ requestedAt: record.requestedAt,
456
+ deadline: record.deadline,
457
+ status: record.status,
458
+ }));
459
+ const session = fakeSession();
460
+ session.seed("delegates.request-index", "", { rows });
461
+ for (const record of [later, earlier, other]) {
462
+ session.seed(
463
+ "delegates.request",
464
+ record.requestId,
465
+ record as unknown as Record<string, unknown>,
466
+ );
467
+ }
468
+ const runtime = {
469
+ snapshot: session.api.snapshot,
470
+ now: () => 1_000,
471
+ } as unknown as SessionRuntime;
472
+
473
+ const found = await requestRecords(runtime, "run:1");
474
+ assert.deepStrictEqual(
475
+ found.map((record) => record.requestId),
476
+ ["12:c1", "12:c2"],
477
+ );
478
+ });
479
+
480
+ it("requestKey names the conversation and the call", () => {
481
+ assert.strictEqual(requestKey(12, "c1"), "12:c1");
482
+ });
483
+
484
+ it("the tool's cancel hook commits the cancellation once", async () => {
485
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
486
+ const log: LogSink = {
487
+ write: (level, code, fields = {}) => {
488
+ entries.push({ level, code, fields });
489
+ },
490
+ };
491
+ const session = fakeSession({
492
+ record: { status: "pending", requestedAt: 1_000, deadline: 5_000 },
493
+ });
494
+ const tool = askTool(log);
495
+ const call =
496
+ tool.cancel === undefined
497
+ ? undefined
498
+ : (tool.cancel.bind(tool) as unknown as (
499
+ args: unknown,
500
+ api: unknown,
501
+ context: unknown,
502
+ ) => Promise<void>);
503
+ assert.ok(call !== undefined);
504
+ await call({}, session.api, BACKGROUND_CONTEXT);
505
+ await call({}, session.api, BACKGROUND_CONTEXT);
506
+
507
+ assert.strictEqual(session.record()?.status, "cancelled");
508
+ assert.strictEqual(session.record()?.reason, "stopped");
509
+ assert.strictEqual(session.record()?.prompt, "Which environment?");
510
+ assert.strictEqual(session.rows()[0]?.status, "cancelled");
511
+ assert.deepStrictEqual(entries, [
512
+ {
513
+ level: "info",
514
+ code: "request.cancelled",
515
+ fields: { runId: "run:1", requestId: "12:c1" },
516
+ },
517
+ ]);
518
+ });
519
+
520
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
521
+ const sessionDir = await mkdtemp(join(tmpdir(), "delegates-requests-"));
522
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
523
+ };
524
+
525
+ const openAt = (identity: SessionIdentity, now: () => number): Promise<SessionRuntime> =>
526
+ openSessionRuntime({
527
+ identity,
528
+ models: new HostModelAdapter(stubHostSource()),
529
+ now,
530
+ });
531
+
532
+ const seedLifecycle = async (
533
+ runtime: SessionRuntime,
534
+ input: {
535
+ readonly key: string;
536
+ readonly status: "pending" | "answered" | "cancelled";
537
+ readonly requestedAt: number;
538
+ readonly deadline: number;
539
+ },
540
+ ): Promise<void> => {
541
+ await runtime.run((context) =>
542
+ runtime.harness.commit(async (tx) => {
543
+ const record = await tx.doc(RequestDoc, input.key, { requestId: input.key });
544
+ record.runId = "run:1";
545
+ record.childRunId = "run:1";
546
+ record.conversationId = 12;
547
+ record.prompt = "Which environment?";
548
+ record.status = input.status;
549
+ record.requestedAt = input.requestedAt;
550
+ record.deadline = input.deadline;
551
+ const index = await tx.doc(RequestIndexDoc);
552
+ index.rows.push({
553
+ key: input.key,
554
+ runId: "run:1",
555
+ requestId: input.key,
556
+ requestedAt: input.requestedAt,
557
+ deadline: input.deadline,
558
+ status: input.status,
559
+ });
560
+ }, context),
561
+ );
562
+ };
563
+
564
+ const rowKeys = async (runtime: SessionRuntime): Promise<readonly string[]> => {
565
+ const index = await runtime.snapshot(RequestIndexDoc);
566
+ return (index?.rows ?? []).map((row) => row.key);
567
+ };
568
+
569
+ it("the sweep retires a decided request after 7 days", async () => {
570
+ const identity = await identityFor("s-prune");
571
+ const now = 1_800_000_000_000;
572
+ const clock = () => now;
573
+ const first = await openAt(identity, clock);
574
+ await seedLifecycle(first, {
575
+ key: "12:old",
576
+ status: "answered",
577
+ requestedAt: now - 8 * DAY_MS,
578
+ deadline: now - 7 * DAY_MS,
579
+ });
580
+ await seedLifecycle(first, {
581
+ key: "12:young",
582
+ status: "cancelled",
583
+ requestedAt: now - 6 * DAY_MS,
584
+ deadline: now + DAY_MS,
585
+ });
586
+ await seedLifecycle(first, {
587
+ key: "12:pending",
588
+ status: "pending",
589
+ requestedAt: now - 8 * DAY_MS,
590
+ deadline: now + DAY_MS,
591
+ });
592
+ await first.run((context) =>
593
+ first.harness.commit(async (tx) => {
594
+ const index = await tx.doc(RequestIndexDoc);
595
+ index.rows.push({
596
+ key: "12:stray",
597
+ runId: "run:1",
598
+ requestId: "12:stray",
599
+ requestedAt: 0,
600
+ deadline: 0,
601
+ status: "answered",
602
+ });
603
+ }, context),
604
+ );
605
+ await first.close();
606
+
607
+ const second = await openAt(identity, clock);
608
+ try {
609
+ assert.strictEqual(await second.snapshot(RequestDoc, "12:old"), undefined);
610
+ assert.deepStrictEqual(await rowKeys(second), ["12:young", "12:pending"]);
611
+ assert.ok((await second.snapshot(RequestDoc, "12:young")) !== undefined);
612
+ assert.ok((await second.snapshot(RequestDoc, "12:pending")) !== undefined);
613
+ assert.ok(PRUNE_AFTER_MS > 6 * DAY_MS);
614
+ } finally {
615
+ await second.close();
616
+ }
617
+
618
+ const third = await openAt(identity, clock);
619
+ try {
620
+ assert.deepStrictEqual(await rowKeys(third), ["12:young", "12:pending"]);
621
+ } finally {
622
+ await third.close();
623
+ }
624
+ }, 30_000);
625
+
626
+ it("the sweep counts retired records and drops stray rows without counting them", async () => {
627
+ const identity = await identityFor("s-prune-count");
628
+ const now = 1_800_000_000_000;
629
+ const runtime = await openAt(identity, () => now);
630
+ try {
631
+ await seedLifecycle(runtime, {
632
+ key: "12:old",
633
+ status: "answered",
634
+ requestedAt: now - 8 * DAY_MS,
635
+ deadline: now - 7 * DAY_MS,
636
+ });
637
+ await runtime.run((context) =>
638
+ runtime.harness.commit(async (tx) => {
639
+ const index = await tx.doc(RequestIndexDoc);
640
+ index.rows.push({
641
+ key: "12:stray",
642
+ runId: "run:1",
643
+ requestId: "12:stray",
644
+ requestedAt: 0,
645
+ deadline: 0,
646
+ status: "answered",
647
+ });
648
+ }, context),
649
+ );
650
+
651
+ assert.strictEqual(await pruneRequests(runtime), 1);
652
+ assert.deepStrictEqual(await rowKeys(runtime), []);
653
+ } finally {
654
+ await runtime.close();
655
+ }
656
+ }, 30_000);
657
+
658
+ it("a pending request past its deadline reads as expired without a write", async () => {
659
+ const identity = await identityFor("s-expired-read");
660
+ const runtime = await openAt(identity, () => 10_000);
661
+ try {
662
+ await seedLifecycle(runtime, {
663
+ key: "12:late",
664
+ status: "pending",
665
+ requestedAt: 1_000,
666
+ deadline: 9_000,
667
+ });
668
+ const record = await runtime.snapshot(RequestDoc, "12:late");
669
+ assert.ok(record !== undefined);
670
+ assert.strictEqual(requestState(record, runtime.now()), "expired");
671
+ assert.strictEqual((await pendingRequests(runtime)).length, 0);
672
+ assert.strictEqual(record.status, "pending");
673
+ } finally {
674
+ await runtime.close();
675
+ }
676
+ });
677
+
678
+ it("the viewer lists a pending request read-only", async () => {
679
+ const identity = await identityFor("s-viewer");
680
+ const runtime = await openAt(identity, () => 10_000);
681
+ await seedLifecycle(runtime, {
682
+ key: "12:waiting",
683
+ status: "pending",
684
+ requestedAt: 1_000,
685
+ deadline: 50_000,
686
+ });
687
+ await runtime.close();
688
+
689
+ const viewer = await openReadOnlyRuntime({
690
+ storePath: storePathFor(identity),
691
+ models: new HostModelAdapter(stubHostSource()),
692
+ });
693
+ try {
694
+ const records = await requestRecords(viewer);
695
+ assert.strictEqual(records.length, 1);
696
+ assert.strictEqual(records[0]?.status, "pending");
697
+ } finally {
698
+ await viewer.close();
699
+ }
700
+ });