@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 { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { AgentDoc, MemoryStorage, type Harness, type Storage } from "@earendil-works/pi-durable";
3
3
  import { compile } from "@earendil-works/pi-schema";
4
- import { mkdtemp } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
4
  import { assert, it } from "@effect/vitest";
8
5
  import { rejects } from "../../test-support/assertions.ts";
6
+ import { makeTempDir } from "../../test-support/platform.ts";
9
7
  import { countingRuntime } from "../../test-support/counting-runtime.ts";
10
8
  import { stubHostSource, type StubModelSource } from "../../test-support/stub-model-source.ts";
11
9
  import { makeStubPi } from "../../test-support/stub-pi.ts";
@@ -18,12 +16,11 @@ import { ToolkitDoc } from "../domain/toolkit.ts";
18
16
  import { CODING_EXTENSION, GATE_GUARD_EXTENSION } from "../domain/names.ts";
19
17
  import { nullLogSink, type LogFields, type LogLevel, type LogSink } from "../runtime/log.ts";
20
18
  import { HostModelAdapter } from "../runtime/models.ts";
21
- import {
22
- openSessionRuntime,
23
- storePathFor,
24
- type SessionIdentity,
25
- type SessionRuntime,
26
- } from "../runtime/session.ts";
19
+ import { storePathFor, type SessionIdentity, type SessionRuntime } from "../runtime/session.ts";
20
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
21
+ import type { SessionHandle } from "../runtime/handle.ts";
22
+ import { handleFor } from "../../test-support/session-handle.ts";
23
+ import { Effect, Ref } from "effect";
27
24
 
28
25
  const host: HostDefaults = {
29
26
  model: { provider: "stub", modelId: "stub-1" },
@@ -31,7 +28,7 @@ const host: HostDefaults = {
31
28
  };
32
29
 
33
30
  const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
34
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-launch-"));
31
+ const sessionDir = await makeTempDir("delegates-launch-");
35
32
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
36
33
  };
37
34
 
@@ -42,11 +39,13 @@ const open = async (
42
39
  readonly hang?: boolean;
43
40
  readonly text?: string;
44
41
  readonly failAt?: readonly number[];
42
+ readonly failMessage?: string;
43
+ readonly log?: LogSink;
45
44
  readonly catalogue?: DefinitionCatalogue;
46
45
  readonly source?: StubModelSource;
47
46
  } = {},
48
- ): Promise<SessionRuntime> =>
49
- openSessionRuntime({
47
+ ): Promise<TestSession> =>
48
+ openTestSession({
50
49
  identity: options.identity ?? (await identityFor("s-1")),
51
50
  models: new HostModelAdapter(
52
51
  options.source ??
@@ -54,9 +53,11 @@ const open = async (
54
53
  ...(options.hang === undefined ? {} : { hang: options.hang }),
55
54
  ...(options.text === undefined ? {} : { text: options.text }),
56
55
  ...(options.failAt === undefined ? {} : { failAt: options.failAt }),
56
+ ...(options.failMessage === undefined ? {} : { failMessage: options.failMessage }),
57
57
  }),
58
58
  ),
59
59
  ...(options.storage === undefined ? {} : { storage: options.storage }),
60
+ ...(options.log === undefined ? {} : { log: options.log }),
60
61
  ...(options.catalogue === undefined ? {} : { catalogue: options.catalogue }),
61
62
  });
62
63
 
@@ -73,7 +74,7 @@ const childAgent = (harness: Harness, childId: number) =>
73
74
  const registeredTools = (runtime: SessionRuntime, definitions = createCatalogue()) => {
74
75
  const stub = makeStubPi({ settings: { packages: [] } });
75
76
  registerDelegateTools(stub.api, {
76
- runtime: () => runtime,
77
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
77
78
  catalogue: definitions,
78
79
  host,
79
80
  launchWaitMs: () => 5_000,
@@ -130,6 +131,53 @@ it("delegate_launch accepts a workflow request", async () => {
130
131
  }
131
132
  }, 30_000);
132
133
 
134
+ /** Every `maxTurns` description the schema carries, wherever a request shape nests it. */
135
+ const maxTurnsDescriptions = (value: unknown, found: string[] = []): string[] => {
136
+ if (Array.isArray(value)) {
137
+ for (const item of value) maxTurnsDescriptions(item, found);
138
+ return found;
139
+ }
140
+ if (value === null || typeof value !== "object") return found;
141
+ const record = value as Record<string, unknown>;
142
+ const properties = record.properties;
143
+ if (properties !== null && typeof properties === "object") {
144
+ const budget = (properties as Record<string, unknown>).maxTurns;
145
+ if (budget !== null && typeof budget === "object") {
146
+ const description = (budget as Record<string, unknown>).description;
147
+ if (typeof description === "string") found.push(description);
148
+ }
149
+ }
150
+ for (const child of Object.values(record)) maxTurnsDescriptions(child, found);
151
+ return found;
152
+ };
153
+
154
+ it("the launch schema carries the budget floor on every maxTurns field", async () => {
155
+ // An agent sizes a budget from the wire text, so every budget field carries it.
156
+ const runtime = await open();
157
+ try {
158
+ const stub = registeredTools(runtime);
159
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
160
+ parameters: object;
161
+ };
162
+ const descriptions = maxTurnsDescriptions(tool.parameters);
163
+ // One per shape that takes a budget: single, fanout child, fanout request,
164
+ // reviewer and review request.
165
+ assert.strictEqual(descriptions.length, 5, "every request shape has one maxTurns field");
166
+ for (const description of descriptions) {
167
+ assert.ok(
168
+ description.includes("never goes below one round"),
169
+ `the budget description states the floor: ${description}`,
170
+ );
171
+ assert.ok(
172
+ description.includes("configured ceiling"),
173
+ `the budget description states the ceiling: ${description}`,
174
+ );
175
+ }
176
+ } finally {
177
+ await runtime.close();
178
+ }
179
+ });
180
+
133
181
  it("the control parameters require the field of each action", async () => {
134
182
  const runtime = await open();
135
183
  try {
@@ -176,6 +224,9 @@ it("the control card reads a decline or refusal line instead of a launch placeho
176
224
  gates: [],
177
225
  requests: [],
178
226
  diagnostic: null,
227
+ execution: "wait",
228
+ maxTurns: null,
229
+ failure: null,
179
230
  };
180
231
  assert.strictEqual(
181
232
  tool.renderResult({ content: [], details: { run } }, { expanded: false }).render()[0],
@@ -273,7 +324,9 @@ it("status prints the answer of an answered single run", async () => {
273
324
  stub.context,
274
325
  );
275
326
  assert.ok(
276
- (status.content[0]?.text ?? "").includes(`${result.view.runId} scout · answered: done`),
327
+ (status.content[0]?.text ?? "").includes(
328
+ `${result.view.runId} scout · answered · turns 120: done`,
329
+ ),
277
330
  status.content[0]?.text ?? "",
278
331
  );
279
332
  } finally {
@@ -339,7 +392,7 @@ it("launching a preset writes its toolkit into the child conversation", async ()
339
392
  assert.deepStrictEqual(agent?.extensions, [CODING_EXTENSION]);
340
393
  assert.deepStrictEqual(agent?.model, host.model);
341
394
  assert.strictEqual(agent?.thinkingLevel, "low");
342
- assert.strictEqual(agent?.maxTurns, 40);
395
+ assert.strictEqual(agent?.maxTurns, 120);
343
396
  assert.ok(agent?.instructions?.includes("You explore"), String(agent?.instructions));
344
397
 
345
398
  const toolkit = await runtime.harness.snapshot(
@@ -377,7 +430,7 @@ it("delegate_launch accepts an inline definition", async () => {
377
430
  try {
378
431
  const stub = makeStubPi({ settings: { packages: [] } });
379
432
  registerDelegateTools(stub.api, {
380
- runtime: () => runtime,
433
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
381
434
  catalogue: createCatalogue(),
382
435
  host,
383
436
  launchWaitMs: () => 5_000,
@@ -423,7 +476,7 @@ it("delegate_launch calls the inspector hook only after a run is committed", asy
423
476
  const seen: unknown[] = [];
424
477
  const stub = makeStubPi({ settings: { packages: [] } });
425
478
  registerDelegateTools(stub.api, {
426
- runtime: () => runtime,
479
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
427
480
  catalogue: createCatalogue(),
428
481
  host,
429
482
  launchWaitMs: () => 5_000,
@@ -515,7 +568,7 @@ it("an inline definition drops unknown fields before the request identity", asyn
515
568
  try {
516
569
  const stub = makeStubPi({ settings: { packages: [] } });
517
570
  registerDelegateTools(stub.api, {
518
- runtime: () => runtime,
571
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
519
572
  catalogue: createCatalogue(),
520
573
  host,
521
574
  launchWaitMs: () => 50,
@@ -790,9 +843,7 @@ it("each delegate tool logs its name and the error", async () => {
790
843
  const { sink, entries } = recordingSink();
791
844
  const stub = makeStubPi({ settings: { packages: [] } });
792
845
  registerDelegateTools(stub.api, {
793
- runtime: () => {
794
- throw new Error("runtime not ready");
795
- },
846
+ session: Ref.makeUnsafe<SessionHandle | undefined>(undefined),
796
847
  catalogue: createCatalogue(),
797
848
  host,
798
849
  launchWaitMs: () => 5_000,
@@ -809,7 +860,10 @@ it("each delegate tool logs its name and the error", async () => {
809
860
  ) => Promise<{ content: readonly { readonly text: string }[] }>;
810
861
  };
811
862
  const result = await tool.execute("", params, undefined, undefined, stub.context);
812
- assert.match(result.content[0]?.text ?? "", /runtime not ready/);
863
+ assert.match(
864
+ result.content[0]?.text ?? "",
865
+ /The delegation runtime is not ready; start a session first\./,
866
+ );
813
867
  };
814
868
 
815
869
  await execute("delegate_launch", {
@@ -835,7 +889,7 @@ it("malformed tool arguments are refused and logged", async () => {
835
889
  try {
836
890
  const stub = makeStubPi({ settings: { packages: [] } });
837
891
  registerDelegateTools(stub.api, {
838
- runtime: () => runtime,
892
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
839
893
  catalogue: createCatalogue(),
840
894
  host,
841
895
  launchWaitMs: () => 5_000,
@@ -908,7 +962,7 @@ it("status reads only the requested run", async () => {
908
962
  const counted = countingRuntime(runtime);
909
963
  const status = await runStatus(counted.runtime, { run: target.view.runId });
910
964
  const text = status.content[0]?.text ?? "";
911
- assert.ok(text.includes(`${target.view.runId} scout · answered: done`), text);
965
+ assert.ok(text.includes(`${target.view.runId} scout · answered · turns 120: done`), text);
912
966
  for (const other of [first.view.runId, third.view.runId]) {
913
967
  assert.strictEqual(counted.count("delegates.run", other), 0, other);
914
968
  }
@@ -977,6 +1031,9 @@ it("the launch card prints the run mode in both forms", async () => {
977
1031
  gates: [],
978
1032
  requests: [],
979
1033
  diagnostic: null,
1034
+ execution: "wait",
1035
+ maxTurns: null,
1036
+ failure: null,
980
1037
  };
981
1038
  assert.strictEqual(
982
1039
  tool.renderResult({ details: { run } }, { expanded: false }).render()[0],
@@ -991,3 +1048,247 @@ it("the launch card prints the run mode in both forms", async () => {
991
1048
  await runtime.close();
992
1049
  }
993
1050
  });
1051
+
1052
+ it("a tool call registered before a swap runs in the new session", async () => {
1053
+ const first = await open();
1054
+ const second = await open({ identity: await identityFor("s-2") });
1055
+ try {
1056
+ const stub = makeStubPi({ settings: { packages: [] } });
1057
+ const current = Ref.makeUnsafe<SessionHandle | undefined>(handleFor(first));
1058
+ registerDelegateTools(stub.api, {
1059
+ session: current,
1060
+ catalogue: createCatalogue(),
1061
+ host,
1062
+ launchWaitMs: () => 5_000,
1063
+ log: () => nullLogSink,
1064
+ });
1065
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
1066
+ execute: (
1067
+ id: string,
1068
+ params: unknown,
1069
+ signal: undefined,
1070
+ onUpdate: undefined,
1071
+ ctx: unknown,
1072
+ ) => Promise<{ details?: { readonly run?: { readonly runId: string } } }>;
1073
+ };
1074
+
1075
+ // The registration stays; only the Ref moves to the replacement session.
1076
+ const registered = tool.execute.bind(tool);
1077
+ await Effect.runPromise(Ref.set(current, handleFor(second)));
1078
+ const result = await registered(
1079
+ "",
1080
+ { request: { kind: "single", agent: "scout", task: "look around" } },
1081
+ undefined,
1082
+ undefined,
1083
+ stub.context,
1084
+ );
1085
+
1086
+ const runId = result.details?.run?.runId;
1087
+ assert.ok(runId !== undefined && runId.length > 0, JSON.stringify(result));
1088
+ assert.ok((await second.snapshot(RunDoc, runId)) !== undefined);
1089
+ assert.strictEqual(await first.snapshot(RunDoc, runId), undefined);
1090
+ } finally {
1091
+ await first.close();
1092
+ await second.close();
1093
+ }
1094
+ }, 20_000);
1095
+
1096
+ it("status prints the detail after the reason on the run and child lines", async () => {
1097
+ const { sink, entries } = recordingSink();
1098
+ const runtime = await open({
1099
+ text: "ok",
1100
+ failAt: [2],
1101
+ failMessage: "invalid request: unknown field",
1102
+ log: sink,
1103
+ });
1104
+ try {
1105
+ const fanout = await launch(
1106
+ {
1107
+ kind: "fanout",
1108
+ lane: "review",
1109
+ agents: [
1110
+ { agent: "scout", task: "first" },
1111
+ { agent: "scout", task: "second" },
1112
+ ],
1113
+ },
1114
+ depsFor(runtime),
1115
+ );
1116
+ const stub = registeredTools(runtime);
1117
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
1118
+ execute: (
1119
+ id: string,
1120
+ params: unknown,
1121
+ signal: undefined,
1122
+ onUpdate: undefined,
1123
+ ctx: unknown,
1124
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
1125
+ };
1126
+ const status = await statusTool.execute(
1127
+ "",
1128
+ { run: fanout.view.runId },
1129
+ undefined,
1130
+ undefined,
1131
+ stub.context,
1132
+ );
1133
+ const text = status.content[0]?.text ?? "";
1134
+ assert.ok(
1135
+ new RegExp(
1136
+ `child 1 ${fanout.view.runId}:child:1 scout failed \\(model_error\\): invalid request: unknown field`,
1137
+ ).test(text),
1138
+ text,
1139
+ );
1140
+ assert.strictEqual(text.split("failed (model_error)").length - 1, 1, text);
1141
+ assert.strictEqual(entries.filter((entry) => entry.code === "run.failed").length, 1);
1142
+ } finally {
1143
+ await runtime.close();
1144
+ }
1145
+ });
1146
+
1147
+ it("the launch wire schema accepts execution and rejects an unknown value", async () => {
1148
+ const runtime = await open();
1149
+ try {
1150
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_launch") as {
1151
+ parameters: object;
1152
+ };
1153
+ const validator = compile(tool.parameters);
1154
+ for (const execution of ["detached", "wait"]) {
1155
+ assert.strictEqual(
1156
+ validator.check({
1157
+ request: { kind: "single", agent: "scout", task: "look", execution },
1158
+ }),
1159
+ true,
1160
+ execution,
1161
+ );
1162
+ }
1163
+ assert.strictEqual(
1164
+ validator.check({
1165
+ request: { kind: "single", agent: "scout", task: "look", execution: "later" },
1166
+ }),
1167
+ false,
1168
+ );
1169
+ } finally {
1170
+ await runtime.close();
1171
+ }
1172
+ });
1173
+
1174
+ it("status prints the resolved budget on the child line", async () => {
1175
+ const runtime = await open({ text: "done" });
1176
+ try {
1177
+ const fanout = await launch(
1178
+ {
1179
+ kind: "fanout",
1180
+ lane: "review",
1181
+ agents: [
1182
+ { agent: "scout", task: "first" },
1183
+ { agent: "scout", task: "second" },
1184
+ ],
1185
+ },
1186
+ depsFor(runtime),
1187
+ );
1188
+ const stub = registeredTools(runtime);
1189
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
1190
+ execute: (
1191
+ id: string,
1192
+ params: unknown,
1193
+ signal: undefined,
1194
+ onUpdate: undefined,
1195
+ ctx: unknown,
1196
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
1197
+ };
1198
+ const status = await statusTool.execute(
1199
+ "",
1200
+ { run: fanout.view.runId },
1201
+ undefined,
1202
+ undefined,
1203
+ stub.context,
1204
+ );
1205
+ const text = status.content[0]?.text ?? "";
1206
+ for (const child of [0, 1]) {
1207
+ assert.ok(
1208
+ text.includes(
1209
+ `child ${child} ${fanout.view.runId}:child:${child} scout answered · turns 120`,
1210
+ ),
1211
+ text,
1212
+ );
1213
+ }
1214
+ } finally {
1215
+ await runtime.close();
1216
+ }
1217
+ });
1218
+
1219
+ it("status prints a single run's budget on its run line", async () => {
1220
+ const runtime = await open({ text: "done" });
1221
+ try {
1222
+ const single = await launch(
1223
+ { kind: "single", agent: "scout", task: "look", maxTurns: 60 },
1224
+ depsFor(runtime),
1225
+ );
1226
+ const stub = registeredTools(runtime);
1227
+ const statusTool = stub.registrations.toolDefinitions.get("delegate_status") as {
1228
+ execute: (
1229
+ id: string,
1230
+ params: unknown,
1231
+ signal: undefined,
1232
+ onUpdate: undefined,
1233
+ ctx: unknown,
1234
+ ) => Promise<{ content: readonly { readonly text: string }[] }>;
1235
+ };
1236
+ const status = await statusTool.execute(
1237
+ "",
1238
+ { run: single.view.runId },
1239
+ undefined,
1240
+ undefined,
1241
+ stub.context,
1242
+ );
1243
+ const text = status.content[0]?.text ?? "";
1244
+ // A single run prints no child line, so its budget rides on the run line.
1245
+ assert.ok(text.includes("scout · answered · turns 60: done"), text);
1246
+ } finally {
1247
+ await runtime.close();
1248
+ }
1249
+ });
1250
+
1251
+ it("the group wire schemas accept execution and a per-child budget", async () => {
1252
+ const runtime = await open();
1253
+ try {
1254
+ const tool = registeredTools(runtime).registrations.toolDefinitions.get("delegate_launch") as {
1255
+ parameters: object;
1256
+ };
1257
+ const validator = compile(tool.parameters);
1258
+ assert.strictEqual(
1259
+ validator.check({
1260
+ request: {
1261
+ kind: "fanout",
1262
+ lane: "review",
1263
+ agents: [{ agent: "scout", task: "a", maxTurns: 60 }],
1264
+ execution: "detached",
1265
+ },
1266
+ }),
1267
+ true,
1268
+ );
1269
+ assert.strictEqual(
1270
+ validator.check({
1271
+ request: {
1272
+ kind: "review",
1273
+ task: "review",
1274
+ reviewers: [{ agent: "reviewer", maxTurns: 40 }],
1275
+ execution: "detached",
1276
+ },
1277
+ }),
1278
+ true,
1279
+ );
1280
+ assert.strictEqual(
1281
+ validator.check({
1282
+ request: {
1283
+ kind: "fanout",
1284
+ lane: "review",
1285
+ agents: [{ agent: "scout", task: "a" }],
1286
+ execution: "later",
1287
+ },
1288
+ }),
1289
+ false,
1290
+ );
1291
+ } finally {
1292
+ await runtime.close();
1293
+ }
1294
+ });
@@ -1,9 +1,17 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { MODEL_THINKING_LEVELS } from "@earendil-works/pi-ai/providers/model-schema";
3
- import { arr, lit, obj, oneOf, opt, str, union, type Static } from "@earendil-works/pi-schema";
4
- import { Option, Predicate, Schema } from "effect";
3
+ import { arr, lit, num, obj, oneOf, opt, str, union, type Static } from "@earendil-works/pi-schema";
4
+ import { Option, Predicate, Ref, Schema } from "effect";
5
5
  import type { SessionRuntime } from "../runtime/session.ts";
6
- import { laneLine, omittedLine, runStatusLine } from "../presentation/wording.ts";
6
+ import type { SessionHandle } from "../runtime/handle.ts";
7
+ import {
8
+ detachedPart,
9
+ failurePart,
10
+ laneLine,
11
+ omittedLine,
12
+ runStatusLine,
13
+ turnsPart,
14
+ } from "../presentation/wording.ts";
7
15
  import { errorFields, type LogSink } from "../runtime/log.ts";
8
16
  import {
9
17
  assertInlineDefinition,
@@ -32,8 +40,8 @@ import { ReviewDoc } from "../domain/orchestration/review.ts";
32
40
  import { control, decodeControl } from "../domain/orchestration/control.ts";
33
41
 
34
42
  export interface ToolDeps {
35
- /** Resolved per call, so a reload's fresh runtime replaces the previous one. */
36
- readonly runtime: () => SessionRuntime;
43
+ /** The current handle: one read per call, so a reload's fresh runtime replaces the previous one. */
44
+ readonly session: Ref.Ref<SessionHandle | undefined>;
37
45
  readonly catalogue: DefinitionCatalogue;
38
46
  readonly host: HostDefaults;
39
47
  readonly launchWaitMs: () => number;
@@ -95,34 +103,57 @@ export type _DefinitionSchemaMatchesInline = Assert<
95
103
  : false
96
104
  >;
97
105
 
106
+ const executionSchema = opt(
107
+ oneOf(["wait", "detached"], {
108
+ description:
109
+ "Absent or wait: wait for the run. detached: return the run id at once and do other " +
110
+ "work; a status notice arrives when the run settles.",
111
+ }),
112
+ );
113
+
114
+ const budgetSchema = opt(
115
+ num({
116
+ description:
117
+ "The turn budget for this call or child: one round is one tool round. A child's value " +
118
+ "wins over the request's, which wins over the definition's; every value is clamped to " +
119
+ "the configured ceiling and never goes below one round.",
120
+ }),
121
+ );
122
+
98
123
  const singleRequestSchema = obj({
99
124
  kind: lit("single"),
100
125
  agent: str({ description: 'Registered agent or preset name, for example "scout".' }),
101
126
  task: str({ description: "The task the delegated agent must do." }),
102
127
  definition: opt(definitionSchema),
128
+ maxTurns: budgetSchema,
129
+ execution: executionSchema,
103
130
  });
104
131
 
105
132
  const fanoutRequestSchema = obj({
106
133
  kind: lit("fanout"),
107
134
  lane: str({ description: "The lane this fanout runs in." }),
108
- agents: arr(obj({ agent: str(), task: str() }), {
135
+ agents: arr(obj({ agent: str(), task: str(), maxTurns: budgetSchema }), {
109
136
  description: "One entry per child run, in order.",
110
137
  }),
138
+ maxTurns: budgetSchema,
111
139
  policy: opt(
112
140
  oneOf(["allSettled", "failFast"], {
113
141
  description:
114
142
  "Absent: allSettled. failFast aborts the other children after the first failing child.",
115
143
  }),
116
144
  ),
145
+ execution: executionSchema,
117
146
  });
118
147
 
119
148
  const reviewRequestSchema = obj({
120
149
  kind: lit("review"),
121
150
  task: str({ description: "What the reviewers review." }),
122
- reviewers: arr(obj({ agent: str() }), {
151
+ reviewers: arr(obj({ agent: str(), maxTurns: budgetSchema }), {
123
152
  description: "One reviewer per entry, in order.",
124
153
  }),
154
+ maxTurns: budgetSchema,
125
155
  lane: opt(str({ description: "The lane; default review." })),
156
+ execution: executionSchema,
126
157
  });
127
158
 
128
159
  const workflowRequestSchema = obj({
@@ -257,7 +288,14 @@ export const renderStatusText = (view: SessionView, lane?: string): string => {
257
288
  `${run.runId} ${runStatusLine(run)}` +
258
289
  (run.gates.length > 0 ? ` waiting on gate ${run.gates.join(", ")}` : "") +
259
290
  (run.requests.length > 0 ? ` waiting on request ${run.requests.join(", ")}` : "") +
260
- (run.diagnostic === null ? "" : ` (${run.diagnostic})`) +
291
+ (run.failure === null
292
+ ? run.diagnostic === null
293
+ ? ""
294
+ : ` (${run.diagnostic})`
295
+ : failurePart(run.failure)) +
296
+ detachedPart(run.execution) +
297
+ // A group's children carry their own budget; a single run has no child line.
298
+ (group ? "" : turnsPart(run.maxTurns)) +
261
299
  (run.children.length > 1 ? ` · ${run.children.length} children` : "") +
262
300
  (!group && run.answer !== null ? `: ${run.answer}` : ""),
263
301
  );
@@ -266,7 +304,8 @@ export const renderStatusText = (view: SessionView, lane?: string): string => {
266
304
  if (showChildren) {
267
305
  for (const child of run.children) {
268
306
  lines.push(
269
- ` child ${child.child} ${child.runId} ${child.agent} ${child.status}` +
307
+ ` child ${child.child} ${child.runId} ${child.agent} ${child.status}${failurePart(child.failure)}` +
308
+ `${turnsPart(child.maxTurns)}` +
270
309
  (child.answer === null ? "" : `: ${child.answer}`),
271
310
  );
272
311
  }
@@ -295,6 +334,15 @@ export const hostFrom = (ctx: ExtensionContext, fallback: HostDefaults): HostDef
295
334
  };
296
335
  };
297
336
 
337
+ /** One read per call; the same failure the tools always returned when no session exists. */
338
+ const currentRuntime = (deps: ToolDeps): SessionRuntime => {
339
+ const handle = Ref.getUnsafe(deps.session);
340
+ if (handle === undefined) {
341
+ throw new Error("The delegation runtime is not ready; start a session first.");
342
+ }
343
+ return handle.runtime;
344
+ };
345
+
298
346
  export const registerDelegateTools = (pi: ExtensionAPI, deps: ToolDeps): void => {
299
347
  pi.registerTool({
300
348
  name: "delegate_launch",
@@ -311,7 +359,7 @@ export const registerDelegateTools = (pi: ExtensionAPI, deps: ToolDeps): void =>
311
359
  assertInlineDefinition(rawRequest.definition);
312
360
  }
313
361
  const { request } = Schema.decodeUnknownSync(LaunchParams)(rawParams);
314
- const runtime = deps.runtime();
362
+ const runtime = currentRuntime(deps);
315
363
  const result = await launch(request, {
316
364
  runtime,
317
365
  catalogue: deps.catalogue,
@@ -359,7 +407,7 @@ export const registerDelegateTools = (pi: ExtensionAPI, deps: ToolDeps): void =>
359
407
  try {
360
408
  const params = decodeControl(rawParams);
361
409
  action = params.action;
362
- const runtime = deps.runtime();
410
+ const runtime = currentRuntime(deps);
363
411
  const result = await control(params, {
364
412
  runtime,
365
413
  wait: { policy: "settle", waitMs: deps.launchWaitMs() },
@@ -417,7 +465,7 @@ export const registerDelegateTools = (pi: ExtensionAPI, deps: ToolDeps): void =>
417
465
  try {
418
466
  const params = Schema.decodeUnknownSync(StatusParams)(rawParams);
419
467
  if (params.run !== undefined) {
420
- const runtime = deps.runtime();
468
+ const runtime = currentRuntime(deps);
421
469
  const doc = await runtime.snapshot(RunDoc, params.run);
422
470
  if (doc === undefined) {
423
471
  return {
@@ -448,7 +496,7 @@ export const registerDelegateTools = (pi: ExtensionAPI, deps: ToolDeps): void =>
448
496
  details: view,
449
497
  };
450
498
  }
451
- const session = await viewSession(deps.runtime());
499
+ const session = await viewSession(currentRuntime(deps));
452
500
  const runs =
453
501
  params.lane === undefined
454
502
  ? session.runs