@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
@@ -1,11 +1,9 @@
1
1
  import { assert, it } from "@effect/vitest";
2
+ import { makeTempDir } from "../../test-support/platform.ts";
2
3
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
4
  import { AgentDoc, type TaskRecord } from "@earendil-works/pi-durable";
4
5
  import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
5
6
  import { taskStateArbitrary, type TaskStateSample } 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 { makeStubPi } from "../../test-support/stub-pi.ts";
11
9
  import { createCatalogue } from "./definitions.ts";
@@ -14,7 +12,11 @@ import { registerDelegateTools, renderStatusText } from "../extension/tools.ts";
14
12
  import { nullLogSink } from "../runtime/log.ts";
15
13
  import { HostModelAdapter } from "../runtime/models.ts";
16
14
  import { countingRuntime } from "../../test-support/counting-runtime.ts";
17
- import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
15
+ import { type SessionRuntime } from "../runtime/session.ts";
16
+ import type { SessionHandle } from "../runtime/handle.ts";
17
+ import { handleFor } from "../../test-support/session-handle.ts";
18
+ import { Ref } from "effect";
19
+
18
20
  import {
19
21
  laneViews,
20
22
  statusOf,
@@ -32,7 +34,8 @@ import {
32
34
  RequestIndexDoc,
33
35
  requestState,
34
36
  } from "./orchestration/requests.ts";
35
- import { RunDocV1, RunDocV1WithMode } from "../../test-support/run-doc-v1.ts";
37
+ import { RunDocV1, RunDocV1WithMode, RunDocV2 } from "../../test-support/run-doc-fixtures.ts";
38
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
36
39
 
37
40
  const host: HostDefaults = {
38
41
  model: { provider: "stub", modelId: "stub-1" },
@@ -127,6 +130,9 @@ it("a terminal view reports the fixed task duration", () => {
127
130
  task,
128
131
  missing: [],
129
132
  gates: [],
133
+ execution: "wait",
134
+ maxTurns: null,
135
+ failure: null,
130
136
  });
131
137
  assert.strictEqual(view.durationMs, 3_000);
132
138
  assert.strictEqual(view.children[0]?.durationMs, 3_000);
@@ -144,14 +150,17 @@ it("a live view has no fixed duration", () => {
144
150
  task: recordOf({ status: "running", signals: 0, outcome: "none" }),
145
151
  missing: [],
146
152
  gates: [],
153
+ execution: "wait",
154
+ maxTurns: null,
155
+ failure: null,
147
156
  });
148
157
  assert.strictEqual(view.durationMs, null);
149
158
  assert.strictEqual(view.children[0]?.durationMs, null);
150
159
  });
151
160
 
152
161
  it("status reports one row per child and lane counts", async () => {
153
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-view-"));
154
- const runtime = await openSessionRuntime({
162
+ const sessionDir = await makeTempDir("delegates-view-");
163
+ const runtime = await openTestSession({
155
164
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
156
165
  models: new HostModelAdapter(stubHostSource()),
157
166
  });
@@ -179,7 +188,7 @@ it("status reports one row per child and lane counts", async () => {
179
188
 
180
189
  const stub = makeStubPi({ settings: { packages: [] } });
181
190
  registerDelegateTools(stub.api, {
182
- runtime: () => runtime,
191
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
183
192
  catalogue: createCatalogue(),
184
193
  host,
185
194
  launchWaitMs: () => 20_000,
@@ -237,8 +246,8 @@ it("the status mapping covers every durable state", () => {
237
246
  });
238
247
 
239
248
  it("a run with a missing toolkit name reports the diagnostic", async () => {
240
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-view-"));
241
- const runtime = await openSessionRuntime({
249
+ const sessionDir = await makeTempDir("delegates-view-");
250
+ const runtime = await openTestSession({
242
251
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
243
252
  models: new HostModelAdapter(stubHostSource()),
244
253
  });
@@ -284,12 +293,17 @@ it("status text shows gates, missing names, children and reviews", () => {
284
293
  status: "waiting",
285
294
  answer: null,
286
295
  durationMs: null,
296
+ maxTurns: null,
297
+ failure: null,
287
298
  },
288
299
  ],
289
300
  missing: ["coding-tools"],
290
301
  gates: ["deploy"],
291
302
  requests: [],
292
303
  diagnostic: null,
304
+ execution: "wait",
305
+ maxTurns: null,
306
+ failure: null,
293
307
  };
294
308
  const text = renderStatusText({
295
309
  runs: [run],
@@ -338,9 +352,9 @@ it("status text shows gates, missing names, children and reviews", () => {
338
352
  }
339
353
  });
340
354
 
341
- const openView = async (): Promise<SessionRuntime> => {
342
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-view-"));
343
- return openSessionRuntime({
355
+ const openView = async (): Promise<TestSession> => {
356
+ const sessionDir = await makeTempDir("delegates-view-");
357
+ return openTestSession({
344
358
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
345
359
  models: new HostModelAdapter(stubHostSource()),
346
360
  });
@@ -439,7 +453,7 @@ it("the session status returns the newest 50 runs and counts the rest", async ()
439
453
  const counted = countingRuntime(runtime);
440
454
  const stub = makeStubPi({ settings: { packages: [] } });
441
455
  registerDelegateTools(stub.api, {
442
- runtime: () => counted.runtime,
456
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(counted.runtime)),
443
457
  catalogue: createCatalogue(),
444
458
  host,
445
459
  launchWaitMs: () => 5_000,
@@ -481,6 +495,12 @@ it("an old run document reads with mode single and no parent", async () => {
481
495
  const doc = await runtime.snapshot(RunDoc, "run:old");
482
496
  assert.strictEqual(doc?.mode, "single");
483
497
  assert.strictEqual(doc?.parentRunId, null);
498
+ assert.strictEqual(doc?.execution, "wait");
499
+ assert.strictEqual(doc?.maxTurns, null);
500
+ assert.strictEqual(doc?.resolution, null);
501
+ assert.strictEqual(doc?.failure, null);
502
+ assert.strictEqual(doc?.settledTaskId, null);
503
+ assert.strictEqual(doc?.retryCount, 0);
484
504
  } finally {
485
505
  await runtime.close();
486
506
  }
@@ -513,6 +533,9 @@ it("a version 1 workflow run keeps its mode and parent", async () => {
513
533
  const child = await runtime.snapshot(RunDoc, "run:wf#1");
514
534
  assert.strictEqual(child?.parentRunId, "run:wf");
515
535
  assert.strictEqual(child?.mode, "single");
536
+ assert.strictEqual(child?.execution, "wait");
537
+ assert.strictEqual(child?.resolution, null);
538
+ assert.strictEqual(child?.retryCount, 0);
516
539
  const session = await viewSession(runtime);
517
540
  assert.deepStrictEqual(
518
541
  session.runs.map((run) => run.runId),
@@ -523,6 +546,30 @@ it("a version 1 workflow run keeps its mode and parent", async () => {
523
546
  }
524
547
  });
525
548
 
549
+ it("an older run document reads with the new facts absent", async () => {
550
+ const runtime = await openView();
551
+ try {
552
+ await runtime.harness.commit(async (tx) => {
553
+ const doc = await tx.doc(RunDocV2, "run:v2", { definition: "scout", lane: "default" });
554
+ doc.requestedAgent = "scout";
555
+ const index = await tx.doc(RunIndexDoc);
556
+ index.runIds.push("run:v2");
557
+ }, BACKGROUND_CONTEXT);
558
+
559
+ const doc = await runtime.snapshot(RunDoc, "run:v2");
560
+ assert.strictEqual(doc?.maxTurns, null);
561
+ assert.strictEqual(doc?.resolution, null);
562
+ assert.strictEqual(doc?.failure, null);
563
+ assert.strictEqual(doc?.settledTaskId, null);
564
+ assert.strictEqual(doc?.retryCount, 0);
565
+ assert.strictEqual(doc?.execution, "wait");
566
+ const view = await viewRun("run:v2", runtime);
567
+ assert.strictEqual(view.status, "queued");
568
+ } finally {
569
+ await runtime.close();
570
+ }
571
+ });
572
+
526
573
  const viewRow = (runId: string, status: RunStatus): RunView => ({
527
574
  runId,
528
575
  definition: "scout",
@@ -538,6 +585,9 @@ const viewRow = (runId: string, status: RunStatus): RunView => ({
538
585
  gates: [],
539
586
  requests: [],
540
587
  diagnostic: null,
588
+ execution: "wait",
589
+ maxTurns: null,
590
+ failure: null,
541
591
  });
542
592
 
543
593
  it("status lists waiting runs before finished ones", () => {
@@ -698,6 +748,9 @@ it("a request-parked run reads waiting", () => {
698
748
  missing: [],
699
749
  gates: [],
700
750
  requests: ["12:c1"],
751
+ execution: "wait",
752
+ maxTurns: null,
753
+ failure: null,
701
754
  });
702
755
  assert.strictEqual(view.status, "waiting");
703
756
  assert.deepStrictEqual(view.requests, ["12:c1"]);
@@ -737,3 +790,14 @@ it("the view lists a run's pending requests", async () => {
737
790
  await runtime.close();
738
791
  }
739
792
  });
793
+
794
+ it("statusOf reports failed when a terminal outcome is orphaned", () => {
795
+ assert.strictEqual(
796
+ statusOf(recordOf({ status: "terminal", signals: 0, outcome: "orphaned" })),
797
+ "failed",
798
+ );
799
+ assert.strictEqual(
800
+ statusOf(recordOf({ status: "sleeping", signals: 0, outcome: "none" })),
801
+ "queued",
802
+ );
803
+ });
@@ -8,7 +8,7 @@ import type {
8
8
  SessionDocToken,
9
9
  } from "@earendil-works/pi-durable";
10
10
  import { AgentDoc, type TaskRecord } from "@earendil-works/pi-durable";
11
- import { Schema } from "effect";
11
+ import { Match, Schema } from "effect";
12
12
  import {
13
13
  answerText,
14
14
  resolverFor,
@@ -18,6 +18,7 @@ import {
18
18
  runResultOf,
19
19
  type RunResult,
20
20
  } from "./run-records.ts";
21
+ import type { SkillsCatalogue } from "./skills.ts";
21
22
  import { resolveStoredToolkit, ToolkitDoc, type ToolkitResolver } from "./toolkit.ts";
22
23
  import { GateDecision, GateRecord, pendingGates } from "./orchestration/gates.ts";
23
24
  import {
@@ -27,9 +28,9 @@ import {
27
28
  RequestRecord,
28
29
  } from "./orchestration/requests.ts";
29
30
  import { ReviewDoc, ReviewRecord } from "./orchestration/review.ts";
30
- import type { SkillsService } from "./skills.ts";
31
31
  import type { McpPresence } from "../runtime/mcp.ts";
32
32
  import { conversationId as toConversationId, taskId as toTaskId } from "./ids.ts";
33
+ import { Execution, FailureFact } from "./failure.ts";
33
34
 
34
35
  /**
35
36
  * Everything a listing reads. A live session and the read-only viewer both
@@ -38,7 +39,7 @@ import { conversationId as toConversationId, taskId as toTaskId } from "./ids.ts
38
39
  export interface ViewPort {
39
40
  readonly harness: Harness;
40
41
  readonly registry: Registry;
41
- readonly skills: SkillsService;
42
+ readonly skills: SkillsCatalogue["Service"];
42
43
  /** The live runtime's MCP presence; absent in a viewer, which connects to nothing. */
43
44
  readonly mcpPresence?: McpPresence;
44
45
  /** The clock a derived deadline reads; a viewer without one falls back to the wall clock. */
@@ -78,6 +79,10 @@ export const ChildView = Schema.Struct({
78
79
  answer: Schema.NullOr(Schema.String),
79
80
  /** `endedAt - startedAt` once terminal; null while live or without timestamps. */
80
81
  durationMs: Schema.NullOr(Schema.Finite),
82
+ /** The budget the child ran with; null while no claim resolved one. */
83
+ maxTurns: Schema.NullOr(Schema.Finite),
84
+ /** The recorded failure fact; null unless the run failed. */
85
+ failure: Schema.NullOr(FailureFact),
81
86
  });
82
87
  export type ChildView = typeof ChildView.Type;
83
88
 
@@ -109,6 +114,12 @@ export const RunView = Schema.Struct({
109
114
  /** Request ids the run waits on, oldest first; empty unless `status` is `waiting`. */
110
115
  requests: Schema.Array(Schema.String),
111
116
  diagnostic: Schema.NullOr(Schema.String),
117
+ /** The launch kind; `wait` for a document written before version 3. */
118
+ execution: Execution,
119
+ /** The budget the run's child ran with; null while no claim resolved one. */
120
+ maxTurns: Schema.NullOr(Schema.Finite),
121
+ /** The recorded failure fact; null unless the run failed. */
122
+ failure: Schema.NullOr(FailureFact),
112
123
  });
113
124
  export type RunView = typeof RunView.Type;
114
125
 
@@ -133,41 +144,46 @@ const resultOf = (
133
144
  : undefined;
134
145
  };
135
146
 
147
+ type TaskState = TaskRecord<unknown, unknown, unknown>["state"];
148
+ type TerminalOutcome = Extract<TaskState, { readonly status: "terminal" }>["outcome"];
149
+
150
+ /** A sleeping task's signals decide between queued, waiting and running. */
151
+ const sleepingStatus = (signals: readonly { readonly signal: string }[]): RunStatus => {
152
+ if (signals.length === 0) return "queued";
153
+ return signals.some(
154
+ (signal) => signal.signal === GateDecision.name || signal.signal === RequestDecided.name,
155
+ )
156
+ ? "waiting"
157
+ : "running";
158
+ };
159
+
160
+ /** A terminal outcome: an abort stopped the run; a fault or an orphan failed it. */
161
+ const terminalStatus = (outcome: TerminalOutcome): RunStatus => {
162
+ if (outcome.status === "aborted") return "stopped";
163
+ if (
164
+ outcome.status === "failed" ||
165
+ outcome.status === "faulted" ||
166
+ outcome.status === "orphaned"
167
+ ) {
168
+ return "failed";
169
+ }
170
+ return runResultOf(outcome.result)?.status ?? "failed";
171
+ };
172
+
136
173
  /** Durable task state → the one status a person reads. */
137
174
  export const statusOf = (task: TaskRecord<unknown, unknown, unknown> | undefined): RunStatus => {
138
175
  if (task === undefined) return "queued";
139
- const state = task.state;
140
- switch (state.status) {
141
- case "pending":
142
- return "queued";
143
- case "running":
144
- case "completing":
145
- return "running";
146
- case "waiting":
147
- return "waiting";
148
- case "sleeping": {
149
- const signals = state.signals ?? [];
150
- if (signals.length === 0) return "queued";
151
- return signals.some(
152
- (signal) => signal.signal === GateDecision.name || signal.signal === RequestDecided.name,
153
- )
154
- ? "waiting"
155
- : "running";
156
- }
157
- case "terminal": {
158
- const outcome = state.outcome;
159
- if (outcome.status === "aborted") return "stopped";
160
- if (
161
- outcome.status === "failed" ||
162
- outcome.status === "faulted" ||
163
- outcome.status === "orphaned"
164
- ) {
165
- return "failed";
166
- }
167
- const result = runResultOf(state.outcome.result);
168
- return result?.status ?? "failed";
169
- }
170
- }
176
+ return Match.value(task.state).pipe(
177
+ Match.discriminators("status")({
178
+ pending: () => "queued" as const,
179
+ running: () => "running" as const,
180
+ completing: () => "running" as const,
181
+ waiting: () => "waiting" as const,
182
+ sleeping: (state) => sleepingStatus(state.signals ?? []),
183
+ terminal: (state) => terminalStatus(state.outcome),
184
+ }),
185
+ Match.exhaustive,
186
+ );
171
187
  };
172
188
 
173
189
  export const isTerminalStatus = (status: RunStatus): boolean =>
@@ -208,6 +224,9 @@ export const viewOf = (input: {
208
224
  readonly children?: readonly ChildView[];
209
225
  readonly gates?: readonly string[];
210
226
  readonly requests?: readonly string[];
227
+ readonly execution: Execution;
228
+ readonly maxTurns: number | null;
229
+ readonly failure: FailureFact | null;
211
230
  }): RunView => {
212
231
  const recordedStatus = statusOf(input.task);
213
232
  const waiting = (input.gates?.length ?? 0) > 0 || (input.requests?.length ?? 0) > 0;
@@ -234,12 +253,17 @@ export const viewOf = (input: {
234
253
  status,
235
254
  answer,
236
255
  durationMs: durationOf(input.task),
256
+ maxTurns: input.maxTurns,
257
+ failure: input.failure,
237
258
  },
238
259
  ],
239
260
  missing: input.missing,
240
261
  gates: input.gates ?? [],
241
262
  requests: input.requests ?? [],
242
263
  diagnostic: diagnosticOf(input.task),
264
+ execution: input.execution,
265
+ maxTurns: input.maxTurns,
266
+ failure: input.failure,
243
267
  };
244
268
  };
245
269
 
@@ -293,6 +317,8 @@ const childView = async (
293
317
  status,
294
318
  answer: result?.status === "answered" ? result.answer : null,
295
319
  durationMs: durationOf(task),
320
+ maxTurns: doc?.maxTurns ?? null,
321
+ failure: doc?.failure ?? null,
296
322
  },
297
323
  missing,
298
324
  };
@@ -371,6 +397,9 @@ export const viewRun = async (
371
397
  children,
372
398
  gates,
373
399
  requests,
400
+ execution: doc.execution,
401
+ maxTurns: doc.maxTurns,
402
+ failure: doc.failure,
374
403
  });
375
404
  }
376
405
 
@@ -398,6 +427,9 @@ export const viewRun = async (
398
427
  missing,
399
428
  gates,
400
429
  requests,
430
+ execution: doc.execution,
431
+ maxTurns: doc.maxTurns,
432
+ failure: doc.failure,
401
433
  });
402
434
  };
403
435
 
@@ -1,21 +1,22 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { readFileSync } from "node:fs";
4
- import { mkdtemp } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
3
  import { assert, it } from "@effect/vitest";
4
+ import { join, makeTempDir, readText } from "../../test-support/platform.ts";
8
5
  import { stubHostSource } from "../../test-support/stub-model-source.ts";
9
6
  import { makeStubPi } from "../../test-support/stub-pi.ts";
10
7
  import { defineAgent } from "../domain/definitions.ts";
8
+ import { Ref } from "effect";
11
9
  import { RunDoc, RunIndexDoc } from "../domain/run-records.ts";
12
10
  import { RequestDoc, RequestIndexDoc } from "../domain/orchestration/requests.ts";
13
11
  import type { SessionView } from "../domain/view.ts";
14
12
  import { nullLogSink, type LogSink } from "../runtime/log.ts";
15
13
  import { HostModelAdapter } from "../runtime/models.ts";
16
- import { openSessionRuntime } from "../runtime/session.ts";
14
+
17
15
  import { noticeFor, type RefusedVerdict } from "./revocation.ts";
18
16
  import { printDelegatesListing, parseAnswerArgs, registerDelegatesCommand } from "./commands.ts";
17
+ import { openTestSession } from "../../test-support/seams.ts";
18
+ import type { SessionHandle } from "../runtime/handle.ts";
19
+ import { handleFor } from "../../test-support/session-handle.ts";
19
20
 
20
21
  const refused: RefusedVerdict = {
21
22
  kind: "refused",
@@ -40,6 +41,9 @@ const viewWithRun = (runId: string, diagnostic: string | null = null): SessionVi
40
41
  gates: [],
41
42
  requests: [],
42
43
  diagnostic,
44
+ execution: "wait",
45
+ maxTurns: null,
46
+ failure: null,
43
47
  },
44
48
  ],
45
49
  lanes: [],
@@ -83,8 +87,8 @@ it("the delegates command lists each definition's declared skills", async () =>
83
87
  });
84
88
 
85
89
  it("the listing prints each run's mode except for single", async () => {
86
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-command-"));
87
- const runtime = await openSessionRuntime({
90
+ const sessionDir = await makeTempDir("delegates-command-");
91
+ const runtime = await openTestSession({
88
92
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
89
93
  models: new HostModelAdapter(stubHostSource()),
90
94
  });
@@ -105,7 +109,7 @@ it("the listing prints each run's mode except for single", async () => {
105
109
  const stub = makeStubPi();
106
110
  await printDelegatesListing(stub.context as ExtensionContext, {
107
111
  definitions: [],
108
- runtime: () => runtime,
112
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
109
113
  log: () => nullLogSink,
110
114
  });
111
115
  const notice = stub.notices.at(-1)?.message ?? "";
@@ -171,7 +175,7 @@ it("a refused listing on a missing store prints the message alone", async () =>
171
175
  });
172
176
 
173
177
  it("a refused listing with a failing reader prints the message and one line", async () => {
174
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-command-"));
178
+ const sessionDir = await makeTempDir("delegates-command-");
175
179
  const stub = makeStubPi({ sessionDir, mode: "rpc" });
176
180
  registerDelegatesCommand(stub.api, {
177
181
  definitions: [],
@@ -187,7 +191,7 @@ it("a refused listing with a failing reader prints the message and one line", as
187
191
  assert.ok(notice.startsWith(refused.message), notice);
188
192
  assert.strictEqual(notice.split("\n").at(-1), "The stored runs could not be read.");
189
193
  assert.ok(notice.startsWith(noticeFor(refused)), notice);
190
- const entries = readFileSync(join(sessionDir, "delegates.log"), "utf8")
194
+ const entries = (await readText(join(sessionDir, "delegates.log")))
191
195
  .trim()
192
196
  .split("\n")
193
197
  .map((line) => JSON.parse(line) as { code: string });
@@ -257,8 +261,8 @@ it("the refused listing prints a pending request", async () => {
257
261
  });
258
262
 
259
263
  it("the listing adds a request line", async () => {
260
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-command-"));
261
- const runtime = await openSessionRuntime({
264
+ const sessionDir = await makeTempDir("delegates-command-");
265
+ const runtime = await openTestSession({
262
266
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
263
267
  models: new HostModelAdapter(stubHostSource()),
264
268
  now: () => 10_000,
@@ -288,7 +292,7 @@ it("the listing adds a request line", async () => {
288
292
  const stub = makeStubPi();
289
293
  await printDelegatesListing(stub.context as ExtensionContext, {
290
294
  definitions: [],
291
- runtime: () => runtime,
295
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
292
296
  log: () => nullLogSink,
293
297
  });
294
298
  const notice = stub.notices.at(-1)?.message ?? "";
@@ -300,7 +304,7 @@ it("the listing adds a request line", async () => {
300
304
  }, BACKGROUND_CONTEXT);
301
305
  await printDelegatesListing(stub.context as ExtensionContext, {
302
306
  definitions: [],
303
- runtime: () => runtime,
307
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
304
308
  log: () => nullLogSink,
305
309
  });
306
310
  const expired = stub.notices.at(-1)?.message ?? "";
@@ -311,8 +315,8 @@ it("the listing adds a request line", async () => {
311
315
  });
312
316
 
313
317
  it("the answer picker offers free text only when the request allows it", async () => {
314
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-answer-"));
315
- const runtime = await openSessionRuntime({
318
+ const sessionDir = await makeTempDir("delegates-answer-");
319
+ const runtime = await openTestSession({
316
320
  identity: { sessionId: "s-offer", sessionDir, cwd: sessionDir, agentDir: sessionDir },
317
321
  models: new HostModelAdapter(stubHostSource()),
318
322
  });
@@ -345,7 +349,7 @@ it("the answer picker offers free text only when the request allows it", async (
345
349
  registerDelegatesCommand(stub.api, {
346
350
  definitions: [],
347
351
  log: () => nullLogSink,
348
- runtime: () => runtime,
352
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
349
353
  });
350
354
  const handler = stub.registrations.commandHandlers.get("delegates:answer");
351
355
  assert.ok(handler !== undefined);
@@ -374,8 +378,8 @@ it("the answer picker offers free text only when the request allows it", async (
374
378
  }, 30_000);
375
379
 
376
380
  it("a failed direct answer writes one command.answer_failed line", async () => {
377
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-answer-"));
378
- const runtime = await openSessionRuntime({
381
+ const sessionDir = await makeTempDir("delegates-answer-");
382
+ const runtime = await openTestSession({
379
383
  identity: { sessionId: "s-direct", sessionDir, cwd: sessionDir, agentDir: sessionDir },
380
384
  models: new HostModelAdapter(stubHostSource()),
381
385
  });
@@ -386,7 +390,7 @@ it("a failed direct answer writes one command.answer_failed line", async () => {
386
390
  registerDelegatesCommand(stub.api, {
387
391
  definitions: [],
388
392
  log: () => log,
389
- runtime: () => runtime,
393
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
390
394
  });
391
395
  const handler = stub.registrations.commandHandlers.get("delegates:answer");
392
396
  assert.ok(handler !== undefined);
@@ -407,8 +411,8 @@ it("a failed direct answer writes one command.answer_failed line", async () => {
407
411
  }, 30_000);
408
412
 
409
413
  it("the answer command declines only when the answer dialog is cancelled", async () => {
410
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-answer-"));
411
- const runtime = await openSessionRuntime({
414
+ const sessionDir = await makeTempDir("delegates-answer-");
415
+ const runtime = await openTestSession({
412
416
  identity: { sessionId: "s-answer", sessionDir, cwd: sessionDir, agentDir: sessionDir },
413
417
  models: new HostModelAdapter(stubHostSource()),
414
418
  });
@@ -440,7 +444,7 @@ it("the answer command declines only when the answer dialog is cancelled", async
440
444
  registerDelegatesCommand(stub.api, {
441
445
  definitions: [],
442
446
  log: () => nullLogSink,
443
- runtime: () => runtime,
447
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
444
448
  });
445
449
  const handler = stub.registrations.commandHandlers.get("delegates:answer");
446
450
  assert.ok(handler !== undefined);
@@ -9,14 +9,16 @@ import {
9
9
  requestState,
10
10
  type RequestRecord,
11
11
  } from "../domain/orchestration/requests.ts";
12
- import { laneLine, runStatusLine } from "../presentation/wording.ts";
12
+ import { detachedPart, laneLine, runStatusLine } from "../presentation/wording.ts";
13
13
  import { errorFields, fileLogSink, type LogSink } from "../runtime/log.ts";
14
- import type { SessionRuntime } from "../runtime/session.ts";
14
+ import type { SessionHandle } from "../runtime/handle.ts";
15
+ import { Effect, Ref } from "effect";
15
16
  import { noticeFor, type RefusedVerdict } from "./revocation.ts";
16
17
 
17
18
  export interface CommandDeps {
18
19
  readonly definitions: readonly AgentDefinition[];
19
- readonly runtime?: () => SessionRuntime | undefined;
20
+ /** The current handle; absent before a session opens or after it closes. */
21
+ readonly session?: Ref.Ref<SessionHandle | undefined>;
20
22
  readonly log: () => LogSink;
21
23
  /** The TUI toggle; every other mode prints the listing below. */
22
24
  readonly inspector?: (ctx: ExtensionContext) => Promise<void>;
@@ -69,7 +71,7 @@ const answerFromCommand = async (
69
71
  deps: CommandDeps,
70
72
  text: string,
71
73
  ): Promise<void> => {
72
- const runtime = deps.runtime?.();
74
+ const runtime = deps.session === undefined ? undefined : Ref.getUnsafe(deps.session)?.runtime;
73
75
  if (runtime === undefined) {
74
76
  ctx.ui.notify("The delegation runtime is not ready.", "error");
75
77
  return;
@@ -121,7 +123,8 @@ const runLines = (runs: readonly RunView[]): string[] =>
121
123
  runs.map(
122
124
  (run) =>
123
125
  `${run.runId} ${runStatusLine(run)}` +
124
- (run.diagnostic === null ? "" : ` (${run.diagnostic})`),
126
+ (run.diagnostic === null ? "" : ` (${run.diagnostic})`) +
127
+ detachedPart(run.execution),
125
128
  );
126
129
 
127
130
  /** Pending requests as list lines, oldest first; a viewer derives expiry from the deadline. */
@@ -171,7 +174,7 @@ export const printDelegatesListing = async (
171
174
  ` — skills: ${(definition.skills ?? []).join(", ") || "none"}` +
172
175
  ` — gates: ${definition.approval.gates.map((gate) => gate.name).join(", ") || "none"}`,
173
176
  );
174
- const runtime = deps.runtime?.();
177
+ const runtime = deps.session === undefined ? undefined : Ref.getUnsafe(deps.session)?.runtime;
175
178
  if (runtime !== undefined) {
176
179
  try {
177
180
  const session = await viewSession(runtime);
@@ -181,7 +184,7 @@ export const printDelegatesListing = async (
181
184
  lines.push(`gate ${gate.gate} pending for ${gate.runId}`);
182
185
  }
183
186
  lines.push(...requestLines(session.requests, runtime.now()));
184
- for (const diagnostic of runtime.skills.diagnostics()) {
187
+ for (const diagnostic of Effect.runSync(runtime.skills.diagnostics)) {
185
188
  lines.push(`${diagnostic.code}: ${diagnostic.detail}`);
186
189
  }
187
190
  } catch (error) {