@ftrdotdev/pi-delegates 0.1.0 → 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 (94) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/OPERATIONS.md +79 -6
  3. package/README.md +25 -17
  4. package/ROADMAP.md +21 -0
  5. package/TESTING.md +153 -318
  6. package/package.json +4 -3
  7. package/skills/pi-delegates/SKILL.md +29 -0
  8. package/skills/pi-delegates/references/launch.md +28 -0
  9. package/src/docs-contract.test.ts +106 -0
  10. package/src/domain/definitions.ts +3 -1
  11. package/src/domain/failure.ts +33 -0
  12. package/src/domain/model-source.ts +30 -0
  13. package/src/domain/orchestration/control.test.ts +69 -35
  14. package/src/domain/orchestration/control.ts +110 -89
  15. package/src/domain/orchestration/fanout.test.ts +125 -20
  16. package/src/domain/orchestration/fanout.ts +60 -22
  17. package/src/domain/orchestration/gates.test.ts +14 -15
  18. package/src/domain/orchestration/launch.test.ts +210 -11
  19. package/src/domain/orchestration/launch.ts +142 -32
  20. package/src/domain/orchestration/requests.test.ts +11 -16
  21. package/src/domain/orchestration/requests.ts +14 -1
  22. package/src/domain/orchestration/review.test.ts +89 -11
  23. package/src/domain/orchestration/run-wait.test.ts +4 -1
  24. package/src/domain/orchestration/run-wait.ts +1 -1
  25. package/src/domain/orchestration/workflow.test.ts +157 -16
  26. package/src/domain/orchestration/workflow.ts +269 -196
  27. package/src/domain/run-records.ts +214 -52
  28. package/src/domain/settlement.test.ts +186 -0
  29. package/src/domain/settlement.ts +137 -0
  30. package/src/domain/shapes.test.ts +20 -0
  31. package/src/domain/skills.test.ts +31 -20
  32. package/src/domain/skills.ts +36 -19
  33. package/src/domain/toolkit.test.ts +15 -1
  34. package/src/domain/toolkit.ts +8 -13
  35. package/src/domain/turn-budget.test.ts +37 -0
  36. package/src/domain/turn-budget.ts +23 -0
  37. package/src/domain/view.test.ts +78 -14
  38. package/src/domain/view.ts +67 -35
  39. package/src/extension/commands.test.ts +27 -23
  40. package/src/extension/commands.ts +10 -7
  41. package/src/extension/entry.test.ts +214 -56
  42. package/src/extension/entry.ts +78 -40
  43. package/src/extension/gate-alerts.test.ts +10 -8
  44. package/src/extension/inspector-command.test.ts +173 -21
  45. package/src/extension/inspector-command.ts +100 -53
  46. package/src/extension/prompt.test.ts +2 -4
  47. package/src/extension/retry-observer.test.ts +292 -0
  48. package/src/extension/retry-observer.ts +150 -0
  49. package/src/extension/settle-alerts.test.ts +579 -0
  50. package/src/extension/settle-alerts.ts +175 -0
  51. package/src/extension/shortcut.test.ts +6 -8
  52. package/src/extension/tools.test.ts +325 -24
  53. package/src/extension/tools.ts +61 -13
  54. package/src/extension/version.test.ts +21 -29
  55. package/src/goldens.test.ts +294 -0
  56. package/src/harness-policy.test.ts +13 -11
  57. package/src/layers.test.ts +309 -0
  58. package/src/layers.ts +405 -0
  59. package/src/package-manifest.test.ts +32 -19
  60. package/src/presentation/actions.test.ts +8 -8
  61. package/src/presentation/activity.test.ts +7 -8
  62. package/src/presentation/close.test.ts +14 -16
  63. package/src/presentation/inspector.test.ts +14 -11
  64. package/src/presentation/inspector.ts +27 -25
  65. package/src/presentation/overlay.test.ts +1 -3
  66. package/src/presentation/repaint.test.ts +226 -190
  67. package/src/presentation/snapshot.test.ts +5 -0
  68. package/src/presentation/status.test.ts +43 -0
  69. package/src/presentation/status.ts +30 -0
  70. package/src/presentation/strip.test.ts +13 -6
  71. package/src/presentation/strip.ts +7 -14
  72. package/src/presentation/wording.test.ts +153 -3
  73. package/src/presentation/wording.ts +78 -6
  74. package/src/runtime/bridge.ts +38 -44
  75. package/src/runtime/{timers.test.ts → clock.test.ts} +1 -1
  76. package/src/runtime/clock.ts +31 -0
  77. package/src/runtime/config.test.ts +26 -7
  78. package/src/runtime/config.ts +6 -1
  79. package/src/runtime/execution-env.test.ts +6 -8
  80. package/src/runtime/extensions.test.ts +4 -4
  81. package/src/runtime/extensions.ts +23 -11
  82. package/src/runtime/handle.ts +54 -0
  83. package/src/runtime/log.test.ts +19 -7
  84. package/src/runtime/log.ts +23 -0
  85. package/src/runtime/mcp.test.ts +29 -32
  86. package/src/runtime/mcp.ts +70 -3
  87. package/src/runtime/runtime-state.test.ts +25 -0
  88. package/src/runtime/runtime-state.ts +36 -0
  89. package/src/runtime/session-tag.ts +11 -0
  90. package/src/runtime/session.test.ts +24 -31
  91. package/src/runtime/session.ts +99 -261
  92. package/src/runtime/storage.ts +29 -0
  93. package/src/test-hygiene.test.ts +97 -0
  94. package/src/runtime/timers.ts +0 -10
@@ -13,15 +13,28 @@ import {
13
13
  } from "../run-records.ts";
14
14
  import { taskId as toTaskId } from "../ids.ts";
15
15
  import { ReviewDoc, reviewRecord, reviewRow } from "./review.ts";
16
+ import { Execution } from "../failure.ts";
17
+ import { nullSettleSignal, recordResolution, type SettleSignal } from "../settlement.ts";
16
18
 
17
19
  export type FanoutPolicy = "failFast" | "allSettled";
18
20
 
19
21
  export const FanoutRequest = Schema.Struct({
20
22
  kind: Schema.Literal("fanout"),
21
23
  lane: Schema.String,
22
- agents: Schema.Array(Schema.Struct({ agent: Schema.String, task: Schema.String })),
24
+ agents: Schema.Array(
25
+ Schema.Struct({
26
+ agent: Schema.String,
27
+ task: Schema.String,
28
+ /** This child's own budget; a request, definition or default value wins over nothing else. */
29
+ maxTurns: Schema.optional(Schema.Finite),
30
+ }),
31
+ ),
32
+ /** The budget for every child this request does not name one for. */
33
+ maxTurns: Schema.optional(Schema.Finite),
23
34
  /** Absent: `allSettled`. */
24
35
  policy: Schema.optional(Schema.Literals(["failFast", "allSettled"])),
36
+ /** Absent: `wait`. */
37
+ execution: Schema.optional(Execution),
25
38
  });
26
39
  export type FanoutRequest = typeof FanoutRequest.Type;
27
40
 
@@ -29,6 +42,8 @@ export interface FanoutChild {
29
42
  readonly agent: string;
30
43
  readonly task: string;
31
44
  readonly definition: AgentDefinition;
45
+ /** Resolved at the launch boundary, before the group input is built. */
46
+ readonly maxTurns: number;
32
47
  }
33
48
 
34
49
  export const FanoutInputSchema = Schema.Struct({
@@ -39,10 +54,15 @@ export const FanoutInputSchema = Schema.Struct({
39
54
  agent: Schema.String,
40
55
  task: Schema.String,
41
56
  definition: AgentDefinitionSchema,
57
+ /** The budget this child runs with, resolved by the launch. */
58
+ maxTurns: Schema.Finite,
42
59
  }),
43
60
  ),
44
61
  host: HostDefaultsSchema,
62
+ /** The group's fallback budget; each child's resolved value wins. */
45
63
  maxTurns: Schema.Finite,
64
+ /** The launch kind; the group and every child document record it. */
65
+ execution: Schema.optional(Execution),
46
66
  policy: Schema.Literals(["failFast", "allSettled"]),
47
67
  /** A review parses each child's answer into one disposition row. */
48
68
  review: Schema.Boolean,
@@ -121,9 +141,14 @@ const aggregate = (input: FanoutInput, outcomes: readonly TaskOutcome<unknown>[]
121
141
  return { status: "answered", answer: `${answered} children answered` };
122
142
  };
123
143
 
144
+ /** The seed for a group document; the claim already created it, so the seed is ignored. */
145
+ const groupSeed = (lane: string) => ({ definition: "fanout", lane });
146
+
124
147
  export const createFanoutTask = (
125
148
  host: AdmissionHost,
126
149
  runTask: Task<RunInput, RunState, RunResult, FanoutHooks>,
150
+ /** The in-process settle signal: the group is a run, so its end is announced too. */
151
+ settleSignal: SettleSignal = nullSettleSignal,
127
152
  ) =>
128
153
  defineTask<FanoutInput, FanoutState, RunResult, FanoutHooks>({
129
154
  name: "delegates.fanout",
@@ -165,13 +190,15 @@ export const createFanoutTask = (
165
190
  const childTaskIds = state.childTaskIds.filter((id): id is number => id !== null);
166
191
  const settled = await runtime.outcomes(childTaskIds.map(toTaskId), context);
167
192
  const result = aggregate(input, settled);
168
- await runtime.commit(
169
- () => ({
170
- status: "terminal",
171
- outcome: { status: "completed", result },
172
- }),
173
- context,
174
- );
193
+ await runtime.commit(async (tx) => {
194
+ const doc = await tx.doc(RunDoc, input.runId, groupSeed(input.lane));
195
+ recordResolution(doc, result.status);
196
+ return {
197
+ status: "terminal" as const,
198
+ outcome: { status: "completed" as const, result },
199
+ };
200
+ }, context);
201
+ settleSignal.emit({ runId: input.runId });
175
202
  return;
176
203
  }
177
204
  }
@@ -238,7 +265,7 @@ export const createFanoutTask = (
238
265
  task: child.task,
239
266
  host: input.host,
240
267
  lane: input.lane,
241
- maxTurns: input.maxTurns,
268
+ maxTurns: child.maxTurns,
242
269
  submissionKey: `${input.submissionKeyPrefix ?? input.runId}:child:${index}:task`,
243
270
  };
244
271
  const taskId = await tx.createTask(runTask, childInput, {
@@ -248,11 +275,14 @@ export const createFanoutTask = (
248
275
  const doc = await tx.doc(RunDoc, runId, {
249
276
  definition: child.definition.name,
250
277
  lane: input.lane,
251
- ...(input.parentRunId === undefined ? {} : { parentRunId: input.parentRunId }),
278
+ ...(input.execution === undefined ? {} : { execution: input.execution }),
279
+ // A session-level group is the child's parent too: the notice marks it that way.
280
+ parentRunId: input.parentRunId ?? input.runId,
252
281
  });
253
282
  doc.requestedAgent = child.agent;
254
283
  doc.task = child.task;
255
284
  doc.requestId = runId;
285
+ doc.maxTurns = childInput.maxTurns;
256
286
  doc.attempt = 1;
257
287
  doc.taskId = taskId;
258
288
  doc.gateRunId = input.parentRunId ?? input.runId;
@@ -303,6 +333,8 @@ export const createFanoutTask = (
303
333
  const doc = await tx.doc(ReviewDoc, task.input.runId, { runId: task.input.runId });
304
334
  doc.reviewers = [...record.reviewers];
305
335
  doc.aggregate = record.aggregate;
336
+ const run = await tx.doc(RunDoc, task.input.runId, groupSeed(task.input.lane));
337
+ recordResolution(run, "answered");
306
338
  return {
307
339
  status: "terminal" as const,
308
340
  outcome: {
@@ -311,23 +343,29 @@ export const createFanoutTask = (
311
343
  },
312
344
  };
313
345
  }, context);
346
+ settleSignal.emit({ runId: task.input.runId });
314
347
  return;
315
348
  }
316
349
  const result = aggregate(task.input, outcomes);
317
- await runtime.commit(
318
- () => ({ status: "terminal", outcome: { status: "completed", result } }),
319
- context,
320
- );
350
+ await runtime.commit(async (tx) => {
351
+ const doc = await tx.doc(RunDoc, task.input.runId, groupSeed(task.input.lane));
352
+ recordResolution(doc, result.status);
353
+ return { status: "terminal" as const, outcome: { status: "completed" as const, result } };
354
+ }, context);
355
+ settleSignal.emit({ runId: task.input.runId });
321
356
  },
322
357
  },
323
- abort: async (_task, runtime, context) =>
324
- runtime.commit(
325
- () => ({
326
- status: "terminal",
327
- outcome: { status: "aborted", reason: "stopped", result: { status: "stopped" } },
328
- }),
329
- context,
330
- ),
358
+ abort: async (task, runtime, context) => {
359
+ await runtime.commit(async (tx) => {
360
+ const doc = await tx.doc(RunDoc, task.input.runId, groupSeed(task.input.lane));
361
+ recordResolution(doc, "stopped");
362
+ return {
363
+ status: "terminal" as const,
364
+ outcome: { status: "aborted" as const, reason: "stopped", result: { status: "stopped" } },
365
+ };
366
+ }, context);
367
+ settleSignal.emit({ runId: task.input.runId });
368
+ },
331
369
  });
332
370
 
333
371
  /** A fanout document's seed; used where only a definition name is known. */
@@ -1,11 +1,9 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { assert, it } from "@effect/vitest";
3
+ import { makeTempDir } from "../../../test-support/platform.ts";
3
4
  import { rejects } from "../../../test-support/assertions.ts";
4
5
  import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
5
6
  import { ruleCallArbitrary, ruleListArbitrary } from "../../../test-support/arbitraries.ts";
6
- import { mkdtemp } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
9
7
  import { stubHostSource } from "../../../test-support/stub-model-source.ts";
10
8
  import { createCatalogue, defineAgent } from "../definitions.ts";
11
9
  import { CODING_EXTENSION } from "../names.ts";
@@ -27,7 +25,8 @@ import { RunDoc } from "../run-records.ts";
27
25
  import { viewRun } from "../view.ts";
28
26
  import { HostModelAdapter } from "../../runtime/models.ts";
29
27
  import { countingRuntime } from "../../../test-support/counting-runtime.ts";
30
- import { openSessionRuntime, type SessionIdentity } from "../../runtime/session.ts";
28
+ import { type SessionIdentity } from "../../runtime/session.ts";
29
+ import { openTestSession } from "../../../test-support/seams.ts";
31
30
 
32
31
  const host: HostDefaults = {
33
32
  model: { provider: "stub", modelId: "stub-1" },
@@ -55,7 +54,7 @@ const releaser = defineAgent({
55
54
  const catalogue = createCatalogue([deployer, releaser]);
56
55
 
57
56
  const identityFor = async (): Promise<SessionIdentity> => {
58
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-gates-"));
57
+ const sessionDir = await makeTempDir("delegates-gates-");
59
58
  return { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir };
60
59
  };
61
60
 
@@ -68,7 +67,7 @@ const deferred = (): { readonly promise: Promise<void>; readonly release: () =>
68
67
  };
69
68
 
70
69
  const waitForGateTasks = async (
71
- runtime: Awaited<ReturnType<typeof openSessionRuntime>>,
70
+ runtime: Awaited<ReturnType<typeof openTestSession>>,
72
71
  key: string,
73
72
  count: number,
74
73
  ): Promise<GateRecord> => {
@@ -85,8 +84,8 @@ const waitForGateTasks = async (
85
84
  const openRuntime = async (
86
85
  toolCall: boolean,
87
86
  now?: () => number,
88
- ): Promise<Awaited<ReturnType<typeof openSessionRuntime>>> =>
89
- openSessionRuntime({
87
+ ): Promise<Awaited<ReturnType<typeof openTestSession>>> =>
88
+ openTestSession({
90
89
  identity: await identityFor(),
91
90
  models: new HostModelAdapter(
92
91
  stubHostSource({
@@ -97,7 +96,7 @@ const openRuntime = async (
97
96
  ...(now === undefined ? {} : { now }),
98
97
  });
99
98
 
100
- const parkedRun = async (runtime: Awaited<ReturnType<typeof openSessionRuntime>>) => {
99
+ const parkedRun = async (runtime: Awaited<ReturnType<typeof openTestSession>>) => {
101
100
  const result = await launch(
102
101
  { kind: "single", agent: "deployer", task: "deploy it" },
103
102
  { runtime, catalogue, host, waitMs: 10_000 },
@@ -258,7 +257,7 @@ it("a denial ends the call blocked and does not run the tool", async () => {
258
257
  });
259
258
 
260
259
  it("a partial wake reports the ended task and wakes the rest", async () => {
261
- const runtime = await openSessionRuntime({
260
+ const runtime = await openTestSession({
262
261
  identity: await identityFor(),
263
262
  models: new HostModelAdapter(
264
263
  stubHostSource({
@@ -400,7 +399,7 @@ it("pending gates are visible from the view", async () => {
400
399
 
401
400
  it("only the child at a gate is reported waiting", async () => {
402
401
  const hold = deferred();
403
- const runtime = await openSessionRuntime({
402
+ const runtime = await openTestSession({
404
403
  identity: await identityFor(),
405
404
  models: new HostModelAdapter(
406
405
  stubHostSource({
@@ -446,7 +445,7 @@ it("only the child at a gate is reported waiting", async () => {
446
445
  }, 20_000);
447
446
 
448
447
  it("every task parked on one gate is signaled", async () => {
449
- const runtime = await openSessionRuntime({
448
+ const runtime = await openTestSession({
450
449
  identity: await identityFor(),
451
450
  models: new HostModelAdapter(
452
451
  stubHostSource({
@@ -568,7 +567,7 @@ it("a fanout child's gate belongs to the parent run and can be approved", async
568
567
 
569
568
  it("each fanout child settles on its own gate", async () => {
570
569
  const hold = deferred();
571
- const runtime = await openSessionRuntime({
570
+ const runtime = await openTestSession({
572
571
  identity: await identityFor(),
573
572
  models: new HostModelAdapter(
574
573
  stubHostSource({
@@ -632,7 +631,7 @@ it("each fanout child settles on its own gate", async () => {
632
631
  }, 20_000);
633
632
 
634
633
  it("a denial without an answer ends the run denied", async () => {
635
- const runtime = await openSessionRuntime({
634
+ const runtime = await openTestSession({
636
635
  identity: await identityFor(),
637
636
  models: new HostModelAdapter(
638
637
  stubHostSource({
@@ -655,7 +654,7 @@ it("a denial without an answer ends the run denied", async () => {
655
654
  });
656
655
 
657
656
  it("a gate query ignores other runs' keys", async () => {
658
- const runtime = await openSessionRuntime({
657
+ const runtime = await openTestSession({
659
658
  identity: await identityFor(),
660
659
  models: new HostModelAdapter(stubHostSource()),
661
660
  });
@@ -1,18 +1,21 @@
1
- import { MemoryStorage } from "@earendil-works/pi-durable";
2
- import { mkdtemp } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
1
+ import { AgentDoc, MemoryStorage } from "@earendil-works/pi-durable";
2
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
5
3
  import { assert, it } from "@effect/vitest";
4
+ import { makeTempDir } from "../../../test-support/platform.ts";
6
5
  import { rejects } from "../../../test-support/assertions.ts";
7
- import { stubHostSource } from "../../../test-support/stub-model-source.ts";
6
+ import { stubHostSource, type StubModelSource } from "../../../test-support/stub-model-source.ts";
7
+ import { waitFor } from "../../../test-support/wait.ts";
8
8
  import { createCatalogue, defineAgent } from "../definitions.ts";
9
- import { RunIndexDoc } from "../run-records.ts";
9
+ import { RunDoc, RunIndexDoc } from "../run-records.ts";
10
+ import { viewRun } from "../view.ts";
10
11
  import { CODING_EXTENSION } from "../names.ts";
11
12
  import { control } from "./control.ts";
12
13
  import { HostModelAdapter } from "../../runtime/models.ts";
13
14
  import type { LogFields, LogLevel, LogSink } from "../../runtime/log.ts";
14
- import { openSessionRuntime, type SessionRuntime } from "../../runtime/session.ts";
15
+ import { type SessionRuntime } from "../../runtime/session.ts";
16
+
15
17
  import { HostModelMissing, launch, type HostDefaults } from "./launch.ts";
18
+ import { openTestSession, type TestSession } from "../../../test-support/seams.ts";
16
19
 
17
20
  const host: HostDefaults = {
18
21
  model: { provider: "stub", modelId: "stub-1" },
@@ -30,6 +33,15 @@ const deployer = defineAgent({
30
33
 
31
34
  const catalogue = createCatalogue([deployer]);
32
35
 
36
+ const scoutDefinition = defineAgent({
37
+ name: "scout",
38
+ role: "Read-only explorer",
39
+ prompt: { role: "You explore the repository." },
40
+ tools: ["read"],
41
+ extensions: [CODING_EXTENSION],
42
+ approval: { gates: [] },
43
+ });
44
+
33
45
  const recordingSink = () => {
34
46
  const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
35
47
  const sink: LogSink = {
@@ -45,13 +57,15 @@ const open = async (
45
57
  options: {
46
58
  readonly hang?: boolean;
47
59
  readonly text?: string;
60
+ readonly source?: StubModelSource;
48
61
  readonly toolCall?: { readonly name: string; readonly arguments: Record<string, unknown> };
49
62
  } = {},
50
- ): Promise<SessionRuntime> => {
51
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-launch-"));
52
- return openSessionRuntime({
63
+ ): Promise<TestSession> => {
64
+ const sessionDir = await makeTempDir("delegates-launch-");
65
+ const { source, ...stub } = options;
66
+ return openTestSession({
53
67
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
54
- models: new HostModelAdapter(stubHostSource(options)),
68
+ models: new HostModelAdapter(source ?? stubHostSource(stub)),
55
69
  storage: new MemoryStorage(),
56
70
  ...(log === undefined ? {} : { log }),
57
71
  });
@@ -171,3 +185,188 @@ it("a cancelled launch logs aborted and ends stopped", async () => {
171
185
  await runtime.close();
172
186
  }
173
187
  });
188
+
189
+ it("a detached single launch returns before the child answers", async () => {
190
+ let release = (): void => {};
191
+ const held = new Promise<void>((resolve) => {
192
+ release = resolve;
193
+ });
194
+ const source = stubHostSource({ text: "late answer", hold: () => held, holdAt: [1] });
195
+ const runtime = await open(undefined, { source });
196
+ try {
197
+ const result = await launch(
198
+ { kind: "single", agent: "scout", task: "look", execution: "detached" },
199
+ deps(runtime),
200
+ );
201
+ assert.strictEqual(result.view.answer, null);
202
+ assert.ok(
203
+ result.view.status === "queued" || result.view.status === "running",
204
+ result.view.status,
205
+ );
206
+ assert.match(result.text, /^Run .* is (queued|running)\.$/);
207
+ await waitFor(() => source.active === 1, "the child generation started while held");
208
+ assert.ok(
209
+ result.view.status === "queued" || result.view.status === "running",
210
+ result.view.status,
211
+ );
212
+ release();
213
+ await waitFor(
214
+ async () => (await viewRun(result.view.runId, runtime)).status === "answered",
215
+ "the detached run settles",
216
+ );
217
+ } finally {
218
+ await runtime.close();
219
+ }
220
+ });
221
+
222
+ it("a detached launch arms no deadline and writes no wait line", async () => {
223
+ let release = (): void => {};
224
+ const held = new Promise<void>((resolve) => {
225
+ release = resolve;
226
+ });
227
+ const source = stubHostSource({ text: "done", hold: () => held, holdAt: [1] });
228
+ const { sink, entries } = recordingSink();
229
+ const runtime = await open(sink, { source });
230
+ try {
231
+ const result = await launch(
232
+ { kind: "single", agent: "scout", task: "look", execution: "detached" },
233
+ deps(runtime),
234
+ );
235
+ await waitFor(() => source.active === 1, "the child generation started while held");
236
+ release();
237
+ await waitFor(
238
+ async () => (await runtime.snapshot(RunDoc, result.view.runId))?.resolution === "answered",
239
+ "the detached run settles",
240
+ );
241
+ assert.deepStrictEqual(
242
+ entries.filter((entry) => entry.code.startsWith("wait.")).map((entry) => entry.code),
243
+ [],
244
+ );
245
+ } finally {
246
+ await runtime.close();
247
+ }
248
+ });
249
+
250
+ it("an absent execution and execution wait share one request identity", async () => {
251
+ let release = (): void => {};
252
+ const held = new Promise<void>((resolve) => {
253
+ release = resolve;
254
+ });
255
+ const source = stubHostSource({ text: "ok", hold: () => held, holdAt: [1] });
256
+ const runtime = await open(undefined, { source });
257
+ try {
258
+ const first = launch({ kind: "single", agent: "scout", task: "look" }, deps(runtime));
259
+ await waitFor(
260
+ async () => ((await runtime.snapshot(RunIndexDoc))?.runIds.length ?? 0) === 1,
261
+ "the first run is claimed",
262
+ );
263
+ const second = launch(
264
+ { kind: "single", agent: "scout", task: "look", execution: "wait" },
265
+ deps(runtime),
266
+ );
267
+ release();
268
+ const [absent, waited] = await Promise.all([first, second]);
269
+ assert.strictEqual(absent.view.runId, waited.view.runId);
270
+ assert.deepStrictEqual((await runtime.snapshot(RunIndexDoc))?.runIds, [absent.view.runId]);
271
+
272
+ const third = await launch({ kind: "single", agent: "scout", task: "look" }, deps(runtime));
273
+ assert.notStrictEqual(third.view.runId, absent.view.runId);
274
+ assert.ok(third.view.runId.endsWith("#2"), third.view.runId);
275
+ } finally {
276
+ await runtime.close();
277
+ }
278
+ });
279
+
280
+ it("a detached and a wait launch of one request are two runs", async () => {
281
+ const runtime = await open(undefined, { text: "ok" });
282
+ try {
283
+ const detached = await launch(
284
+ { kind: "single", agent: "scout", task: "look", execution: "detached" },
285
+ deps(runtime),
286
+ );
287
+ const waited = await launch({ kind: "single", agent: "scout", task: "look" }, deps(runtime));
288
+ assert.notStrictEqual(detached.view.runId, waited.view.runId);
289
+ const index = await runtime.snapshot(RunIndexDoc);
290
+ assert.deepStrictEqual(
291
+ [...(index?.runIds ?? [])].sort(),
292
+ [detached.view.runId, waited.view.runId].sort(),
293
+ );
294
+ assert.strictEqual(
295
+ (await runtime.snapshot(RunDoc, detached.view.runId))?.execution,
296
+ "detached",
297
+ );
298
+ assert.strictEqual((await runtime.snapshot(RunDoc, waited.view.runId))?.execution, "wait");
299
+ } finally {
300
+ await runtime.close();
301
+ }
302
+ });
303
+
304
+ it("a request without execution still waits for the answer", async () => {
305
+ const runtime = await open(undefined, { text: "hello" });
306
+ try {
307
+ const result = await launch({ kind: "single", agent: "scout", task: "look" }, deps(runtime));
308
+ assert.strictEqual(result.view.status, "answered");
309
+ assert.strictEqual(result.text, "hello");
310
+ } finally {
311
+ await runtime.close();
312
+ }
313
+ });
314
+
315
+ it("a detached launch refuses an unknown definition before claiming", async () => {
316
+ const runtime = await open(undefined, { text: "ok" });
317
+ try {
318
+ await rejects(
319
+ launch({ kind: "single", agent: "nope", task: "x", execution: "detached" }, deps(runtime)),
320
+ (error: unknown) => error instanceof Error && error.message.includes("nope"),
321
+ );
322
+ assert.deepStrictEqual((await runtime.snapshot(RunIndexDoc))?.runIds ?? [], []);
323
+ } finally {
324
+ await runtime.close();
325
+ }
326
+ });
327
+
328
+ const childAgentOf = async (runtime: TestSession, childId: number) =>
329
+ runtime.harness.snapshot(AgentDoc, childId as never, BACKGROUND_CONTEXT);
330
+
331
+ it("a request budget reaches the conversation and the document", async () => {
332
+ const runtime = await open(undefined, { text: "ok" });
333
+ try {
334
+ const result = await launch(
335
+ { kind: "single", agent: "scout", task: "look", maxTurns: 60 },
336
+ deps(runtime),
337
+ );
338
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
339
+ assert.strictEqual(doc?.maxTurns, 60);
340
+ assert.ok(doc?.childConversationId !== null && doc?.childConversationId !== undefined);
341
+ const agent = await childAgentOf(runtime, doc.childConversationId);
342
+ assert.strictEqual(agent?.maxTurns, 60);
343
+ } finally {
344
+ await runtime.close();
345
+ }
346
+ });
347
+
348
+ it("a definition budget applies and a request budget overrides it", async () => {
349
+ const runtime = await open(undefined, { text: "ok" });
350
+ const budgeted = createCatalogue([defineAgent({ ...scoutDefinition, maxTurns: 100 })]);
351
+ try {
352
+ const fromDefinition = await launch(
353
+ { kind: "single", agent: "scout", task: "look" },
354
+ { runtime, catalogue: budgeted, host, waitMs: 5_000 },
355
+ );
356
+ assert.strictEqual((await runtime.snapshot(RunDoc, fromDefinition.view.runId))?.maxTurns, 100);
357
+
358
+ const fromRequest = await launch(
359
+ { kind: "single", agent: "scout", task: "look", maxTurns: 60 },
360
+ { runtime, catalogue: budgeted, host, waitMs: 5_000 },
361
+ );
362
+ assert.strictEqual((await runtime.snapshot(RunDoc, fromRequest.view.runId))?.maxTurns, 60);
363
+
364
+ const fromDefault = await launch(
365
+ { kind: "single", agent: "scout", task: "another" },
366
+ deps(runtime),
367
+ );
368
+ assert.strictEqual((await runtime.snapshot(RunDoc, fromDefault.view.runId))?.maxTurns, 120);
369
+ } finally {
370
+ await runtime.close();
371
+ }
372
+ });