@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
@@ -3,12 +3,10 @@ import { AgentDoc, MemoryStorage, type Storage } from "@earendil-works/pi-durabl
3
3
  import { CodemodeSandbox } from "@earendil-works/pi-codemode";
4
4
  import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
5
5
  import type { Message } from "@earendil-works/pi-ai";
6
- import { mkdtemp } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
9
6
  import { assert, it } from "@effect/vitest";
7
+ import { makeTempDir } from "../../../test-support/platform.ts";
10
8
  import { rejects, throws } from "../../../test-support/assertions.ts";
11
- import { Effect } from "effect";
9
+ import { Effect, Layer, Ref } from "effect";
12
10
  import { stubHostSource, type StubModelSource } from "../../../test-support/stub-model-source.ts";
13
11
  import { createCatalogue, defineAgent, decodeInlineDefinition } from "../definitions.ts";
14
12
  import { RUN_TOOL_NAMES, CODING_EXTENSION } from "../names.ts";
@@ -18,7 +16,7 @@ import { ToolkitDoc, ToolkitUnresolved, bindToolkit, type ToolkitResolver } from
18
16
  import { HostModelAdapter } from "../../runtime/models.ts";
19
17
  import {
20
18
  openReadOnlyRuntime,
21
- openSessionRuntime,
19
+ SessionRuntimeTag,
22
20
  type SessionRuntime,
23
21
  } from "../../runtime/session.ts";
24
22
  import { viewRun, viewSession } from "../view.ts";
@@ -30,7 +28,19 @@ import {
30
28
  launch,
31
29
  type HostDefaults,
32
30
  } from "./launch.ts";
33
- import { WorkflowService, WorkflowRefused, type WorkflowError } from "./workflow.ts";
31
+ import {
32
+ runTools,
33
+ settleOutcome,
34
+ WorkflowService,
35
+ WorkflowRefused,
36
+ type WorkflowError,
37
+ } from "./workflow.ts";
38
+ import { openTestSession, type TestSession } from "../../../test-support/seams.ts";
39
+ import type { SessionHandle } from "../../runtime/handle.ts";
40
+
41
+ /** The layer the session graph provides, with this test's runtime standing in. */
42
+ const workflowLayerFor = (runtime: SessionRuntime) =>
43
+ WorkflowService.layer.pipe(Layer.provide(Layer.succeed(SessionRuntimeTag, runtime)));
34
44
 
35
45
  const host: HostDefaults = {
36
46
  model: { provider: "stub", modelId: "stub-1" },
@@ -50,7 +60,7 @@ const composer = defineAgent({
50
60
  const catalogue = createCatalogue([composer]);
51
61
 
52
62
  const identityFor = async (sessionId: string) => {
53
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-workflow-"));
63
+ const sessionDir = await makeTempDir("delegates-workflow-");
54
64
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
55
65
  };
56
66
 
@@ -61,8 +71,8 @@ const open = async (options: {
61
71
  readonly catalogue?: typeof catalogue;
62
72
  readonly sandbox?: CodemodeSandboxBase;
63
73
  readonly store?: boolean;
64
- }): Promise<SessionRuntime> =>
65
- openSessionRuntime({
74
+ }): Promise<TestSession> =>
75
+ openTestSession({
66
76
  identity: await identityFor(options.sessionId ?? "s-1"),
67
77
  models: new HostModelAdapter(options.source),
68
78
  ...((options.store ?? false) ? {} : { storage: options.storage ?? new MemoryStorage() }),
@@ -831,7 +841,7 @@ it("a service method refuses an unknown run", async () => {
831
841
  BACKGROUND_CONTEXT,
832
842
  ),
833
843
  );
834
- }).pipe(Effect.provide(WorkflowService.layer({ runtime: () => runtime }))),
844
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
835
845
  );
836
846
  assert.ok(error instanceof RunNotFound, String(error));
837
847
  assert.ok(error.message.includes("run:missing#1"), error.message);
@@ -851,7 +861,7 @@ const waitFor = async <A>(probe: () => Promise<A | undefined>): Promise<A> => {
851
861
  };
852
862
 
853
863
  const restartIdentity = async (sessionId: string) => {
854
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-restart-"));
864
+ const sessionDir = await makeTempDir("delegates-restart-");
855
865
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
856
866
  };
857
867
 
@@ -894,7 +904,7 @@ it("a restart mid-script reattaches without duplicating or re-claiming children"
894
904
  );
895
905
  const identity = await restartIdentity("s-restart");
896
906
  const openWith = () =>
897
- openSessionRuntime({
907
+ openTestSession({
898
908
  identity,
899
909
  models: new HostModelAdapter(source),
900
910
  catalogue,
@@ -1126,7 +1136,7 @@ it("a script gate survives a restart without a duplicate", async () => {
1126
1136
  const identity = await restartIdentity("s-gate-restart");
1127
1137
  const source = scriptedSource(gateScript, (task) => `answer ${task}`);
1128
1138
  const openWith = () =>
1129
- openSessionRuntime({
1139
+ openTestSession({
1130
1140
  identity,
1131
1141
  models: new HostModelAdapter(source),
1132
1142
  catalogue,
@@ -1251,7 +1261,7 @@ it("a gate is refused when the conversation has no toolkit", async () => {
1251
1261
  BACKGROUND_CONTEXT,
1252
1262
  ),
1253
1263
  );
1254
- }).pipe(Effect.provide(WorkflowService.layer({ runtime: () => runtime }))),
1264
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
1255
1265
  );
1256
1266
  assert.ok(error instanceof WorkflowRefused, String(error));
1257
1267
  assert.strictEqual(error.reason, "unknown-gate");
@@ -1288,7 +1298,7 @@ it("a script steers and stops a child", async () => {
1288
1298
  Effect.gen(function* () {
1289
1299
  const service = yield* WorkflowService;
1290
1300
  return yield* use(service);
1291
- }).pipe(Effect.provide(WorkflowService.layer({ runtime: () => runtime }))),
1301
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
1292
1302
  );
1293
1303
 
1294
1304
  await runService((service) =>
@@ -1327,7 +1337,7 @@ it("a script steers and stops a child", async () => {
1327
1337
  BACKGROUND_CONTEXT,
1328
1338
  ),
1329
1339
  );
1330
- }).pipe(Effect.provide(WorkflowService.layer({ runtime: () => runtime }))),
1340
+ }).pipe(Effect.provide(workflowLayerFor(runtime))),
1331
1341
  );
1332
1342
  assert.ok(refused instanceof RunNotRunning, String(refused));
1333
1343
  } finally {
@@ -1423,3 +1433,134 @@ it("stopping an already stopped run answers success", async () => {
1423
1433
  await runtime.close();
1424
1434
  }
1425
1435
  }, 60_000);
1436
+
1437
+ it("the settle outcome classifies a refusal as a Result when the effect refuses", async () => {
1438
+ const refusal = RunNotFound.make({ message: "Run r-1 not found." });
1439
+ const failing = Effect.fail(refusal);
1440
+ const result = (await settleOutcome(failing)) as {
1441
+ readonly _tag?: string;
1442
+ readonly failure?: { readonly output?: readonly { readonly text: string }[] };
1443
+ };
1444
+ assert.strictEqual(result._tag, "Failure");
1445
+ assert.strictEqual(result.failure?.output?.[0]?.text, "Run r-1 not found.");
1446
+ await rejects(settleOutcome(Effect.die(new Error("boom"))), /boom/);
1447
+ });
1448
+
1449
+ /**
1450
+ * One scripted workflow whose child generations are held: only the workflow's
1451
+ * own generations run. The gate is chosen per generation from the system prompt,
1452
+ * so a child holds and the workflow never does.
1453
+ */
1454
+ const heldChildrenSource = (script: string) => {
1455
+ let release = (): void => {};
1456
+ const held = new Promise<void>((resolve) => {
1457
+ release = resolve;
1458
+ });
1459
+ let gate: Promise<void> = Promise.resolve();
1460
+ const source = stubHostSource({
1461
+ hold: () => gate,
1462
+ respond: ({ systemPrompt, messages }) => {
1463
+ const workflow = systemPrompt.includes("verbatim");
1464
+ gate = workflow ? Promise.resolve() : held;
1465
+ if (!workflow) return { text: "child" };
1466
+ const answered = messages.some((message) => message.role === "toolResult");
1467
+ return answered
1468
+ ? { text: lastToolText(messages) }
1469
+ : { toolCall: { name: "codemode", arguments: { code: script } } };
1470
+ },
1471
+ });
1472
+ return { source, release: () => release() };
1473
+ };
1474
+
1475
+ it("a detached script launch returns the run id, status and an empty answer", async () => {
1476
+ const script =
1477
+ 'const a = await tools.launch({ agent: "scout", task: "slow", execution: "detached" }); ' +
1478
+ 'return [a.run, a.answer === "" ? "empty" : a.answer, a.status].join("|");';
1479
+ const { source, release } = heldChildrenSource(script);
1480
+ const runtime = await open({ source });
1481
+ try {
1482
+ const launched = launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1483
+ // The script reached its next effect while the child's generation is held: the run exists.
1484
+ const parent = await waitFor(async () => {
1485
+ try {
1486
+ const run = await workflowRun(runtime);
1487
+ return run.childRunIds.length === 1 ? run : undefined;
1488
+ } catch {
1489
+ return undefined;
1490
+ }
1491
+ });
1492
+ const childRunId = parent.childRunIds[0] ?? "";
1493
+ const opening = await viewRun(childRunId, runtime);
1494
+ assert.strictEqual(opening.answer, null);
1495
+ assert.strictEqual((await runDoc(runtime, childRunId))?.execution, "detached");
1496
+
1497
+ release();
1498
+ const result = await launched;
1499
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1500
+ assert.match(result.view.answer ?? "", /\|empty\|queued$/);
1501
+ } finally {
1502
+ await runtime.close();
1503
+ }
1504
+ }, 60_000);
1505
+
1506
+ it("a detached script group returns one empty-answer entry per child", async () => {
1507
+ const script =
1508
+ 'const r = await tools.launch_many({ children: [{ agent: "scout", task: "a" }, ' +
1509
+ '{ agent: "scout", task: "b" }], execution: "detached" }); ' +
1510
+ 'return r.runs.map((x) => (x.answer === "" ? "empty" : x.answer) + ":" + x.status).join(",");';
1511
+ const { source, release } = heldChildrenSource(script);
1512
+ const runtime = await open({ source });
1513
+ try {
1514
+ const launched = launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1515
+ const parent = await waitFor(async () => {
1516
+ try {
1517
+ const run = await workflowRun(runtime);
1518
+ return run.childRunIds.length === 2 ? run : undefined;
1519
+ } catch {
1520
+ return undefined;
1521
+ }
1522
+ });
1523
+ for (const runId of parent.childRunIds) {
1524
+ assert.strictEqual((await runDoc(runtime, runId))?.execution, "detached");
1525
+ }
1526
+
1527
+ release();
1528
+ const result = await launched;
1529
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1530
+ const answer = result.view.answer ?? "";
1531
+ assert.ok(answer.includes("empty:queued,empty:queued"), answer);
1532
+ const last = answer.trimEnd().split("\n").at(-1) ?? "";
1533
+ assert.strictEqual(last.split(",").length, 2, answer);
1534
+ } finally {
1535
+ await runtime.close();
1536
+ }
1537
+ }, 60_000);
1538
+
1539
+ it("a script launch budgets per child", async () => {
1540
+ const script =
1541
+ 'await tools.launch_many({ children: [{ agent: "scout", task: "a", maxTurns: 60 }, ' +
1542
+ '{ agent: "scout", task: "b" }] }); return "done";';
1543
+ const runtime = await open({ source: scriptedSource(script, (task) => `answer ${task}`) });
1544
+ try {
1545
+ const result = await launch({ kind: "workflow", agent: "composer", script }, deps(runtime));
1546
+ assert.strictEqual(result.view.status, "answered", result.view.diagnostic ?? "");
1547
+ const parent = await workflowRun(runtime);
1548
+ const docs = await children(runtime, parent);
1549
+ assert.deepStrictEqual(
1550
+ docs.map((entry) => entry.doc?.maxTurns),
1551
+ [60, 120],
1552
+ );
1553
+ } finally {
1554
+ await runtime.close();
1555
+ }
1556
+ }, 60_000);
1557
+
1558
+ it("the script tool descriptions state the detached answer", () => {
1559
+ const current = Ref.makeUnsafe<SessionHandle | undefined>(undefined);
1560
+ const descriptions = new Map(runTools(current).map((tool) => [tool.name, tool.description]));
1561
+ for (const name of ["launch", "launch_many"]) {
1562
+ const description = descriptions.get(name) ?? "";
1563
+ assert.ok(description.includes('execution: "detached"'), description);
1564
+ assert.ok(description.includes("empty"), description);
1565
+ }
1566
+ });