@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
@@ -6,15 +6,12 @@ import type {
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
8
  import { VimRouter } from "@ftrdotdev/pi-tui";
9
- import { Effect, Fiber, ManagedRuntime, Predicate, Schema, Stream } from "effect";
9
+ import { Effect, Fiber, Predicate, Schema, Stream } from "effect";
10
10
  import { readFile } from "node:fs/promises";
11
11
  import { join } from "node:path";
12
- import {
13
- endNotice,
14
- Inspector,
15
- type InspectorEnd,
16
- type InspectorService,
17
- } from "../presentation/inspector.ts";
12
+ import { endNotice, InspectorReadFailed, type InspectorEnd } from "../presentation/inspector.ts";
13
+ import { openInspectorActivation, type InspectorActivation } from "../layers.ts";
14
+ import type { SessionHandle } from "../runtime/handle.ts";
18
15
  import {
19
16
  runInspectorAction,
20
17
  targetLabel,
@@ -27,27 +24,26 @@ import {
27
24
  type OverlayVerb,
28
25
  } from "../presentation/overlay.ts";
29
26
  import type { InspectorSnapshot } from "../presentation/snapshot.ts";
30
- import {
31
- makeDelegatesStrip,
32
- STRIP_KEY,
33
- STRIP_PLACEMENT,
34
- stripVisible,
35
- } from "../presentation/strip.ts";
27
+ import { activeStatus, offStatus, STATUS_KEY } from "../presentation/status.ts";
28
+ import { makeDelegatesStrip, STRIP_KEY, STRIP_PLACEMENT } from "../presentation/strip.ts";
36
29
  import {
37
30
  gateAgentMessage,
38
31
  gateNotice,
39
32
  requestAgentMessage,
40
33
  requestToastLine,
41
34
  type GateNotice,
35
+ settleAgentMessage,
42
36
  type RequestNotice,
43
37
  } from "../presentation/wording.ts";
44
38
  import type { SessionRuntime } from "../runtime/session.ts";
45
39
  import { errorFields, nullLogSink, type LogSink } from "../runtime/log.ts";
46
40
  import { DEFAULT_INSPECT_SHORTCUT } from "../presentation/shortcut.ts";
47
41
  import type { ObservationSeam } from "../runtime/observe.ts";
48
- import type { Timers } from "../runtime/timers.ts";
42
+ import type { Timers } from "../runtime/clock.ts";
43
+ import { Ref } from "effect";
49
44
  import type { SessionView } from "../domain/view.ts";
50
45
  import type { GateAlertHost } from "./gate-alerts.ts";
46
+ import type { SettleAlertHost } from "./settle-alerts.ts";
51
47
  import type { RequestAlertHost } from "./request-alerts.ts";
52
48
 
53
49
  /** The session-metadata key. Entries are appended, never removed, so the **last** one wins. */
@@ -108,8 +104,8 @@ export const readRequestAlerts = (entries: readonly SessionEntry[]): ReadonlySet
108
104
  return ids;
109
105
  };
110
106
 
111
- export interface InspectorHost extends GateAlertHost, RequestAlertHost {
112
- readonly ui: Pick<ExtensionUIContext, "setWidget" | "custom" | "notify">;
107
+ export interface InspectorHost extends GateAlertHost, RequestAlertHost, SettleAlertHost {
108
+ readonly ui: Pick<ExtensionUIContext, "setWidget" | "custom" | "notify" | "setStatus">;
113
109
  readonly mode: ExtensionContext["mode"];
114
110
  readonly appendActivation: (active: boolean) => void;
115
111
  readonly readActivation: () => boolean;
@@ -125,7 +121,8 @@ export interface InspectorOverrides {
125
121
  }
126
122
 
127
123
  export interface InspectorCommandDeps {
128
- readonly runtime: () => SessionRuntime | undefined;
124
+ /** The current handle; absent before a session opens or after it closes. */
125
+ readonly session: Ref.Ref<SessionHandle | undefined>;
129
126
  readonly host: (ctx: ExtensionContext) => InspectorHost;
130
127
  /** The resolved overlay shortcut; defaults to `ctrl+space`. */
131
128
  readonly shortcut?: string;
@@ -135,18 +132,18 @@ export interface InspectorCommandDeps {
135
132
  readonly action?: (input: Parameters<typeof runInspectorAction>[0]) => Promise<ActionResult>;
136
133
  }
137
134
 
138
- /** One activation: one layer, one subscription, one sink registry, one cached snapshot. */
139
- interface Activation {
135
+ /** One activation: one service, one subscription, one sink registry, one cached snapshot. */
136
+ interface Activation extends InspectorActivation {
140
137
  readonly host: InspectorHost;
141
138
  readonly shortcut: string;
142
- readonly layer: ManagedRuntime.ManagedRuntime<Inspector, unknown>;
143
- readonly service: InspectorService;
144
139
  readonly runtime: SessionRuntime;
145
140
  readonly sinks: Map<string, () => void>;
146
141
  latest: InspectorSnapshot;
142
+ /** The last footer line written, so an unchanged publication writes nothing. */
143
+ lastStatus: string | undefined;
147
144
  /** The last action's line: persists until the next action or the overlay closes. */
148
145
  statusLine: string | null;
149
- subscription: Fiber.Fiber<void, unknown> | undefined;
146
+ subscription: Fiber.Fiber<void, never> | undefined;
150
147
  stripMounted: boolean;
151
148
  stripRender: (() => void) | undefined;
152
149
  stripSink: (() => void) | undefined;
@@ -214,6 +211,27 @@ export const hostFor = (
214
211
  });
215
212
  }
216
213
  },
214
+ notifySettled: (notice, omitted = 0) => {
215
+ try {
216
+ pi.sendMessage(
217
+ {
218
+ customType: "delegates.settled",
219
+ content: settleAgentMessage(notice, omitted),
220
+ display: true,
221
+ details: { runIds: notice.rows.map((row) => row.runId) },
222
+ },
223
+ { deliverAs: "followUp", triggerTurn: false },
224
+ );
225
+ } catch (error) {
226
+ // `pi.sendMessage` is fire-and-forget: it returns a promise whose rejection the host
227
+ // swallows, so only a synchronous throw — an inactive session refusing the append —
228
+ // reaches this line.
229
+ log().write("warn", "settle.notify_failed", {
230
+ runs: notice.rows.map((row) => row.runId).join(","),
231
+ ...errorFields(error),
232
+ });
233
+ }
234
+ },
217
235
  notifyGate: (gate, shortcut) => {
218
236
  try {
219
237
  ctx.ui.notify(gateNotice(gate), "warning");
@@ -267,10 +285,7 @@ const readVimEnabled = async (): Promise<boolean> => {
267
285
 
268
286
  const readVimRouter = async (): Promise<VimRouter["Service"]> => {
269
287
  const enabled = await readVimEnabled();
270
- return Effect.service(VimRouter).pipe(
271
- Effect.provide(VimRouter.make(() => enabled)),
272
- Effect.runSync,
273
- );
288
+ return VimRouter.make(() => enabled);
274
289
  };
275
290
 
276
291
  const registerSink = (current: Activation, key: string, sink: () => void): (() => void) => {
@@ -305,14 +320,23 @@ const mountStrip = (current: Activation): void => {
305
320
  );
306
321
  };
307
322
 
323
+ /**
324
+ * Writes the footer line only when it changed. Both high-frequency paths — a
325
+ * publication and an activation — go through here; an unchanged snapshot costs
326
+ * no repaint. The restore path writes once per session bind and stays outside
327
+ * this cache: a reload clears the host footer, so the line must be re-asserted
328
+ * rather than skipped.
329
+ */
330
+ const writeStatus = (current: Activation, text: string): void => {
331
+ if (current.lastStatus === text) return;
332
+ current.lastStatus = text;
333
+ current.host.ui.setStatus(STATUS_KEY, text);
334
+ };
335
+
308
336
  /** A gate is announced by the session watcher, not by an activation. */
309
337
  const publish = (current: Activation, next: InspectorSnapshot): void => {
310
338
  current.latest = next;
311
- if (stripVisible(next)) {
312
- if (!current.stripMounted) mountStrip(current);
313
- } else if (current.stripMounted) {
314
- unmountStrip(current);
315
- }
339
+ writeStatus(current, activeStatus(next.counts, current.shortcut));
316
340
  // A publication repaints mounted surfaces; it never runs the overlay's close handle.
317
341
  for (const [key, sink] of current.sinks) {
318
342
  if (key !== "overlay:close") sink();
@@ -325,17 +349,20 @@ const activate = async (
325
349
  options: { readonly writeMarker: boolean },
326
350
  ): Promise<void> => {
327
351
  if (host.mode !== "tui") return;
328
- const runtime = deps.runtime();
329
- if (runtime === undefined) return;
352
+ const handle = Ref.getUnsafe(deps.session);
353
+ if (handle === undefined) return;
354
+ const runtime = handle.runtime;
330
355
  const alreadyMarked = host.readActivation();
331
- const layer = ManagedRuntime.make(Inspector.layer({ runtime, ...deps.inspector }));
332
- let service: InspectorService;
356
+ let opened: InspectorActivation;
333
357
  let snapshot: InspectorSnapshot;
334
358
  try {
335
- service = await layer.runPromise(Inspector);
336
- snapshot = await layer.runPromise(service.snapshot);
359
+ opened = await Effect.runPromise(openInspectorActivation(handle, deps.inspector ?? {}));
360
+ snapshot = await Effect.runPromise(opened.service.snapshot);
337
361
  } catch (error) {
338
- await layer.dispose().catch(() => undefined);
362
+ // The failure keeps its type: a read that failed says so, in one log entry.
363
+ if (error instanceof InspectorReadFailed) {
364
+ runtime.log.write("error", "inspector.read_failed", errorFields(error));
365
+ }
339
366
  const line = endNotice({
340
367
  kind: "runtime-ended",
341
368
  reason: `failed to start: ${messageOf(error)}`,
@@ -343,15 +370,20 @@ const activate = async (
343
370
  if (line !== undefined) host.ui.notify(line, "warning");
344
371
  return;
345
372
  }
373
+ const service = opened.service;
346
374
 
347
375
  const current: Activation = {
348
376
  host,
349
377
  shortcut: deps.shortcut ?? DEFAULT_INSPECT_SHORTCUT,
350
- layer,
351
378
  service,
379
+ run: opened.run,
380
+ fork: opened.fork,
381
+ interrupt: opened.interrupt,
382
+ close: opened.close,
352
383
  runtime,
353
384
  sinks: new Map(),
354
385
  latest: snapshot,
386
+ lastStatus: undefined,
355
387
  statusLine: null,
356
388
  subscription: undefined,
357
389
  stripMounted: false,
@@ -360,13 +392,17 @@ const activate = async (
360
392
  };
361
393
  activation = current;
362
394
  if (options.writeMarker && !alreadyMarked) host.appendActivation(true);
363
- if (stripVisible(snapshot)) mountStrip(current);
364
- current.subscription = layer.runFork(
365
- Stream.runForEach(Stream.drop(service.changes, 1), (next) =>
366
- Effect.sync(() => publish(current, next)),
395
+ writeStatus(current, activeStatus(snapshot.counts, current.shortcut));
396
+ mountStrip(current);
397
+ current.subscription = await current.fork(
398
+ Stream.runForEach(
399
+ // The replay is the snapshot this activation already shows; a publication that
400
+ // landed before the fork started is a replay too, so drop by revision, once.
401
+ Stream.dropWhile(service.changes, (next) => next.revision <= snapshot.revision),
402
+ (next) => Effect.sync(() => publish(current, next)),
367
403
  ),
368
404
  );
369
- layer.runFork(
405
+ await current.fork(
370
406
  Stream.runForEach(service.end, (end) => Effect.sync(() => handleEnd(current, end))),
371
407
  );
372
408
  };
@@ -438,7 +474,7 @@ const dispatchAction = (
438
474
  runtime: current.runtime,
439
475
  target,
440
476
  verb,
441
- refresh: () => current.layer.runPromise(current.service.refresh),
477
+ refresh: () => current.run(current.service.refresh),
442
478
  })
443
479
  .then((result) => {
444
480
  // The overlay may have closed, or the activation may have been replaced,
@@ -476,9 +512,15 @@ export const restoreInspector = async (
476
512
  await serial(async () => {
477
513
  const host = deps.host(ctx);
478
514
  if (event.reason === "fork" && host.readActivation()) host.appendActivation(false);
479
- if (!shouldRestore(event.reason, ctx.sessionManager.getEntries())) return;
515
+ if (host.mode !== "tui") return;
480
516
  if (activation !== undefined) return;
481
- await activate(deps, host, { writeMarker: false });
517
+ const entries = ctx.sessionManager.getEntries();
518
+ if (shouldRestore(event.reason, entries)) {
519
+ await activate(deps, host, { writeMarker: false });
520
+ return;
521
+ }
522
+ // Only a session that opted in carries the hint; a fresh one writes no line.
523
+ if (hasActivationEntry(entries)) host.ui.setStatus(STATUS_KEY, offStatus());
482
524
  });
483
525
  };
484
526
 
@@ -523,7 +565,10 @@ export const syncInspectorBranch = async (
523
565
  });
524
566
  };
525
567
 
526
- /** Both doors to the overlay: the command refuses when off, the shortcut is inert. */
568
+ /**
569
+ * Both doors to the overlay. Each refuses when the inspector is off: a silent
570
+ * shortcut reads as a broken key when the real answer is `/delegates`.
571
+ */
527
572
  export const openInspectorOverlay = async (
528
573
  deps: InspectorCommandDeps,
529
574
  ctx: ExtensionContext,
@@ -601,12 +646,12 @@ export const registerInspectorOverlay = (pi: ExtensionAPI, deps: InspectorComman
601
646
  (deps.shortcut ?? DEFAULT_INSPECT_SHORTCUT) as Parameters<ExtensionAPI["registerShortcut"]>[0],
602
647
  {
603
648
  description: "Delegates: open the inspector overlay",
604
- handler: (ctx) => openInspectorOverlay(deps, ctx, { refuse: false }),
649
+ handler: (ctx) => openInspectorOverlay(deps, ctx, { refuse: true }),
605
650
  },
606
651
  );
607
652
  };
608
653
 
609
- /** Remove the overlay, the strip, the subscription, then dispose the layer. Idempotent. */
654
+ /** Remove the overlay, the strip, the subscription, then close the activation's scope. Idempotent. */
610
655
  const teardownActivation = async (
611
656
  options: {
612
657
  readonly markOff?: boolean;
@@ -620,17 +665,19 @@ const teardownActivation = async (
620
665
  closeOverlay?.();
621
666
  current.sinks.delete("overlay:close");
622
667
  unmountStrip(current);
668
+ // A toggle leaves the hint; a reload, shutdown or runtime end clears the line.
669
+ current.host.ui.setStatus(STATUS_KEY, options.markOff === false ? undefined : offStatus());
623
670
  for (const [key, sink] of current.sinks) {
624
671
  if (key !== "overlay:close") sink();
625
672
  }
626
673
  current.sinks.clear();
627
674
  if (current.subscription !== undefined) {
628
- await current.layer.runPromise(Fiber.interrupt(current.subscription)).catch(() => undefined);
675
+ await current.interrupt(current.subscription).catch(() => undefined);
629
676
  }
630
- await current.layer.dispose();
677
+ await current.close();
631
678
  };
632
679
 
633
- /** Remove the overlay, the strip, the subscription, then dispose the layer. Idempotent. */
680
+ /** Remove the overlay, the strip, the subscription, then close the activation's scope. Idempotent. */
634
681
  export const teardownInspector = (
635
682
  options: {
636
683
  readonly markOff?: boolean;
@@ -1,8 +1,6 @@
1
1
  import { assert, it } from "@effect/vitest";
2
+ import { makeTempDir } from "../../test-support/platform.ts";
2
3
  import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
3
- import { mkdtemp } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
4
  import type { AgentDefinition } from "../domain/definitions.ts";
7
5
  import { defineAgent, presets } from "../domain/definitions.ts";
8
6
  import { presetListArbitrary } from "../../test-support/arbitraries.ts";
@@ -14,7 +12,7 @@ import { DELEGATES_SECTION, renderDelegatesSection, SECTION_BUDGET_CHARS } from
14
12
 
15
13
  /** Surfaces register at the first session start, so every test starts one. */
16
14
  const started = async (definitions?: readonly AgentDefinition[]) => {
17
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-prompt-"));
15
+ const sessionDir = await makeTempDir("delegates-prompt-");
18
16
  const stub = makeStubPi({
19
17
  settings: { packages: [] },
20
18
  sessionId: "s-1",
@@ -0,0 +1,292 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { fakeDocRuntime } from "../../test-support/fake-doc-runtime.ts";
3
+ import { waitFor } from "../../test-support/wait.ts";
4
+ import { stubHostSource } from "../../test-support/stub-model-source.ts";
5
+ import { makeTempDir } from "../../test-support/platform.ts";
6
+ import { createCatalogue } from "../domain/definitions.ts";
7
+ import { launch, type HostDefaults } from "../domain/orchestration/launch.ts";
8
+ import { RunDoc } from "../domain/run-records.ts";
9
+ import { statusOf } from "../domain/view.ts";
10
+ import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
11
+ import { HostModelAdapter } from "../runtime/models.ts";
12
+ import { taskId as toTaskId } from "../domain/ids.ts";
13
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
14
+ import { RETRY_RECONCILE_MS, startRetryObserver } from "./retry-observer.ts";
15
+
16
+ const host: HostDefaults = {
17
+ model: { provider: "stub", modelId: "stub-1" },
18
+ thinkingLevel: "low",
19
+ };
20
+
21
+ const recordingSink = () => {
22
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
23
+ const sink: LogSink = {
24
+ write: (level, code, fields = {}) => {
25
+ entries.push({ level, code, fields });
26
+ },
27
+ };
28
+ return { sink, entries };
29
+ };
30
+
31
+ const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
32
+
33
+ const runDoc = (input: Record<string, unknown> = {}): Record<string, unknown> => ({
34
+ definition: "scout",
35
+ mode: "single",
36
+ lane: "default",
37
+ requestedAgent: "scout",
38
+ task: "look",
39
+ requestId: "r",
40
+ attempt: 1,
41
+ childConversationId: 12,
42
+ taskId: 7,
43
+ gateRunId: "r#1",
44
+ parentRunId: null,
45
+ childRunIds: [],
46
+ diagnostics: [],
47
+ execution: "wait",
48
+ maxTurns: null,
49
+ resolution: null,
50
+ failure: null,
51
+ settledTaskId: null,
52
+ retryCount: 0,
53
+ ...input,
54
+ });
55
+
56
+ const live = (
57
+ retry: { readonly at: number; readonly error: string } | undefined,
58
+ text?: string,
59
+ ): Record<string, unknown> => ({
60
+ run: { turns: 1 },
61
+ generation: {
62
+ attempt: retry === undefined ? 1 : 2,
63
+ ...(text === undefined ? {} : { message: { role: "assistant", content: [] } }),
64
+ ...(retry === undefined ? {} : { retry }),
65
+ },
66
+ });
67
+
68
+ const store = (retry: { readonly at: number; readonly error: string } | undefined) => ({
69
+ "delegates.run-index": { runIds: ["r#1"] },
70
+ "delegates.run:r#1": runDoc(),
71
+ "pi.live:12": live(retry),
72
+ });
73
+
74
+ it("a scheduled retry writes one run.retry warning and one count", async () => {
75
+ const recorder = recordingSink();
76
+ const fake = fakeDocRuntime({ docs: store({ at: 5_000, error: "429: rate limited" }) });
77
+ const observer = startRetryObserver({ runtime: fake.runtime, log: recorder.sink });
78
+ try {
79
+ await flush();
80
+ assert.deepStrictEqual(
81
+ recorder.entries.map((entry) => [entry.level, entry.code, entry.fields]),
82
+ [["warn", "run.retry", { runId: "r#1", attempt: 2, at: 5_000, detail: "429: rate limited" }]],
83
+ );
84
+ assert.strictEqual((fake.doc("delegates.run:r#1") as { retryCount: number }).retryCount, 1);
85
+ } finally {
86
+ await observer.close();
87
+ }
88
+ });
89
+
90
+ it("one retry is counted once, not once per live change", async () => {
91
+ const recorder = recordingSink();
92
+ const fake = fakeDocRuntime({ docs: store({ at: 5_000, error: "429: rate limited" }) });
93
+ const observer = startRetryObserver({ runtime: fake.runtime, log: recorder.sink });
94
+ try {
95
+ await flush();
96
+ fake.commitDoc("pi.live:12", live({ at: 5_000, error: "429: rate limited" }, "partial"));
97
+ await flush();
98
+ fake.commitDoc("pi.live:12", live({ at: 5_000, error: "429: rate limited" }, "partial two"));
99
+ await flush();
100
+ fake.commitDoc("pi.live:12", live({ at: 9_000, error: "429: rate limited again" }));
101
+ await flush();
102
+
103
+ assert.strictEqual(recorder.entries.length, 2);
104
+ assert.deepStrictEqual(
105
+ recorder.entries.map((entry) => entry.fields.at),
106
+ [5_000, 9_000],
107
+ );
108
+ assert.strictEqual((fake.doc("delegates.run:r#1") as { retryCount: number }).retryCount, 2);
109
+ } finally {
110
+ await observer.close();
111
+ }
112
+ });
113
+
114
+ it("the observer writes no count for a run it cannot find", async () => {
115
+ const recorder = recordingSink();
116
+ const fake = fakeDocRuntime({
117
+ docs: {
118
+ "delegates.run-index": { runIds: ["r#1"] },
119
+ "pi.live:12": live({ at: 5_000, error: "429: rate limited" }),
120
+ },
121
+ });
122
+ const observer = startRetryObserver({ runtime: fake.runtime, log: recorder.sink });
123
+ try {
124
+ await flush();
125
+ assert.deepStrictEqual(recorder.entries, []);
126
+ assert.strictEqual(fake.doc("delegates.run:r#1"), undefined);
127
+ } finally {
128
+ await observer.close();
129
+ }
130
+ });
131
+
132
+ it("a retry seen before its document is readable is counted once it appears", async () => {
133
+ const recorder = recordingSink();
134
+ const fake = fakeDocRuntime({ docs: store({ at: 5_000, error: "429: rate limited" }) });
135
+ const observer = startRetryObserver({ runtime: fake.runtime, log: recorder.sink });
136
+ try {
137
+ await flush();
138
+ assert.strictEqual(recorder.entries.length, 1);
139
+
140
+ // The document vanishes while the second retry arrives: nothing to write to.
141
+ fake.removeDoc("delegates.run:r#1");
142
+ fake.commitDoc("pi.live:12", live({ at: 9_000, error: "429: rate limited again" }));
143
+ await flush();
144
+ assert.strictEqual(recorder.entries.length, 1);
145
+
146
+ // The document is back: the same retry must still be countable, not written off.
147
+ fake.commitDoc("delegates.run:r#1", runDoc({ retryCount: 1 }));
148
+ fake.commitDoc("pi.live:12", live({ at: 9_000, error: "429: rate limited again" }, "retry"));
149
+ await flush();
150
+ assert.deepStrictEqual(
151
+ recorder.entries.map((entry) => entry.fields.at),
152
+ [5_000, 9_000],
153
+ );
154
+ assert.strictEqual((fake.doc("delegates.run:r#1") as { retryCount: number }).retryCount, 2);
155
+ } finally {
156
+ await observer.close();
157
+ }
158
+ });
159
+
160
+ it("a group child's retry is counted through its parent document", async () => {
161
+ const recorder = recordingSink();
162
+ // A fanout child is never indexed; the group document is the only way to reach it.
163
+ const childRunId = "g#1:child:0";
164
+ const fake = fakeDocRuntime({
165
+ docs: {
166
+ "delegates.run-index": { runIds: ["g#1"] },
167
+ "delegates.run:g#1": runDoc({
168
+ definition: "fanout",
169
+ mode: "fanout",
170
+ requestedAgent: "fanout",
171
+ childConversationId: null,
172
+ gateRunId: "g#1",
173
+ taskId: 9,
174
+ childRunIds: [childRunId],
175
+ maxTurns: null,
176
+ }),
177
+ [`delegates.run:${childRunId}`]: runDoc({
178
+ parentRunId: "g#1",
179
+ gateRunId: "g#1",
180
+ taskId: 7,
181
+ childConversationId: 12,
182
+ }),
183
+ "pi.live:12": live({ at: 5_000, error: "429: rate limited" }),
184
+ },
185
+ });
186
+ const observer = startRetryObserver({ runtime: fake.runtime, log: recorder.sink });
187
+ try {
188
+ await flush();
189
+ assert.deepStrictEqual(
190
+ recorder.entries.map((entry) => [entry.code, entry.fields.runId]),
191
+ [["run.retry", childRunId]],
192
+ );
193
+ assert.strictEqual(
194
+ (fake.doc(`delegates.run:${childRunId}`) as { retryCount: number }).retryCount,
195
+ 1,
196
+ );
197
+ } finally {
198
+ await observer.close();
199
+ }
200
+ });
201
+
202
+ it("a child added after its parent was watched is still counted", async () => {
203
+ const recorder = recordingSink();
204
+ const childRunId = "w#1:child:0";
205
+ const fake = fakeDocRuntime({
206
+ docs: {
207
+ "delegates.run-index": { runIds: ["w#1"] },
208
+ // A workflow run: it has a conversation, so the observer watches it, and its
209
+ // fanout children reach it through childRunIds only after it starts.
210
+ "delegates.run:w#1": runDoc({ childConversationId: 11, childRunIds: [] }),
211
+ "pi.live:11": live(undefined),
212
+ },
213
+ });
214
+ const observer = startRetryObserver({ runtime: fake.runtime, log: recorder.sink });
215
+ try {
216
+ await flush();
217
+ assert.deepStrictEqual(fake.attached(), ["pi.live:11"]);
218
+ fake.fireDelay(RETRY_RECONCILE_MS);
219
+ await flush();
220
+ assert.deepStrictEqual(fake.attached(), ["pi.live:11"]);
221
+
222
+ // The script launches a child now, and the parent commits it to childRunIds.
223
+ fake.setDoc(
224
+ `delegates.run:${childRunId}`,
225
+ runDoc({ parentRunId: "w#1", gateRunId: "w#1", taskId: 7, childConversationId: 12 }),
226
+ );
227
+ fake.setDoc("pi.live:12", live({ at: 5_000, error: "429: rate limited" }));
228
+ fake.commitDoc(
229
+ "delegates.run:w#1",
230
+ runDoc({ childConversationId: 11, childRunIds: [childRunId] }),
231
+ );
232
+ await flush();
233
+ fake.fireDelay(RETRY_RECONCILE_MS);
234
+ await flush();
235
+
236
+ assert.deepStrictEqual(
237
+ recorder.entries.map((entry) => [entry.code, entry.fields.runId]),
238
+ [["run.retry", childRunId]],
239
+ );
240
+ assert.strictEqual(
241
+ (fake.doc(`delegates.run:${childRunId}`) as { retryCount: number }).retryCount,
242
+ 1,
243
+ );
244
+ } finally {
245
+ await observer.close();
246
+ }
247
+ });
248
+
249
+ const open = async (log?: LogSink): Promise<TestSession> => {
250
+ const sessionDir = await makeTempDir("delegates-retry-");
251
+ return openTestSession({
252
+ identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
253
+ models: new HostModelAdapter(
254
+ stubHostSource({ failAt: [1], failMessage: "429 rate limit exceeded", text: "ok" }),
255
+ ),
256
+ ...(log === undefined ? {} : { log }),
257
+ });
258
+ };
259
+
260
+ it("an observed throttle leaves one retry line and a persisted count", async () => {
261
+ const recorder = recordingSink();
262
+ const runtime = await open(recorder.sink);
263
+ const observer = startRetryObserver({ runtime, log: recorder.sink });
264
+ try {
265
+ const result = await launch(
266
+ { kind: "single", agent: "scout", task: "look" },
267
+ { runtime, catalogue: createCatalogue(), host, waitMs: 10_000 },
268
+ );
269
+
270
+ const retries = recorder.entries.filter((entry) => entry.code === "run.retry");
271
+ assert.strictEqual(retries.length, 1);
272
+ assert.strictEqual(retries[0]?.level, "warn");
273
+ assert.strictEqual(retries[0]?.fields.runId, result.view.runId);
274
+
275
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
276
+ assert.strictEqual(doc?.retryCount, 1);
277
+ assert.strictEqual(result.text, "ok");
278
+ assert.strictEqual(doc?.taskId !== null && doc?.taskId !== undefined, true);
279
+ const taskNumber = doc?.taskId ?? 0;
280
+ const task = await runtime.run((context) =>
281
+ runtime.harness.getTask(toTaskId(taskNumber), context),
282
+ );
283
+ assert.strictEqual(statusOf(task), "answered");
284
+ await waitFor(
285
+ () => recorder.entries.filter((entry) => entry.code === "run.retry").length === 1,
286
+ "one retry line",
287
+ );
288
+ } finally {
289
+ await observer.close();
290
+ await runtime.close();
291
+ }
292
+ });