@ftrdotdev/pi-delegates 0.0.0-stage → 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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -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
+ });
@@ -0,0 +1,150 @@
1
+ import { LiveDoc, type LiveState } from "@earendil-works/pi-durable";
2
+ import { listedRuns, RunDoc } from "../domain/run-records.ts";
3
+ import { conversationId as toConversationId } from "../domain/ids.ts";
4
+ import { errorFields, type LogSink } from "../runtime/log.ts";
5
+ import type { SessionRuntime } from "../runtime/session.ts";
6
+
7
+ /** How often the observer looks for runs and child conversations it does not watch yet. */
8
+ export const RETRY_RECONCILE_MS = 1_000;
9
+
10
+ export interface RetryObserverDeps {
11
+ readonly runtime: SessionRuntime;
12
+ readonly log: LogSink;
13
+ }
14
+
15
+ export interface RetryObserverWatch {
16
+ readonly close: () => Promise<void>;
17
+ }
18
+
19
+ /**
20
+ * Counts each durable retry attempt on the run document and logs it once. It
21
+ * observes the decision; it never makes one, and never aborts or resumes a run.
22
+ * A retry is not a terminal fact, so the dedupe key lives in memory and the
23
+ * count on the document survives a restart.
24
+ */
25
+ export const startRetryObserver = (deps: RetryObserverDeps): RetryObserverWatch => {
26
+ let closed = false;
27
+ let armed: unknown;
28
+ let chain: Promise<void> = Promise.resolve();
29
+ const detaches = new Map<string, () => void>();
30
+ const seen = new Set<string>();
31
+
32
+ const log = (error: unknown): void => {
33
+ deps.log.write("warn", "retry.observer_failed", errorFields(error));
34
+ };
35
+
36
+ const enqueue = (task: () => Promise<void>): Promise<void> => {
37
+ chain = chain.then(task).catch(log);
38
+ return chain;
39
+ };
40
+
41
+ const count = async (
42
+ runId: string,
43
+ attempt: number,
44
+ at: number,
45
+ detail: string,
46
+ ): Promise<void> => {
47
+ const key = `${runId}:${attempt}:${at}`;
48
+ if (seen.has(key)) return;
49
+ // A writer that must not invent a document snapshots first. The key is only
50
+ // spent once the document exists, so a retry seen too early is still counted.
51
+ const doc = await deps.runtime.snapshot(RunDoc, runId);
52
+ if (doc === undefined) return;
53
+ seen.add(key);
54
+ await deps.runtime.run((context) =>
55
+ deps.runtime.harness.commit(async (tx) => {
56
+ const run = await tx.doc(RunDoc, runId, { definition: doc.definition, lane: doc.lane });
57
+ run.retryCount += 1;
58
+ }, context),
59
+ );
60
+ deps.log.write("warn", "run.retry", { runId, attempt, at, detail });
61
+ };
62
+
63
+ const onLive = (runId: string, live: Readonly<LiveState>): void => {
64
+ const generation = live.generation;
65
+ const retry = generation?.retry;
66
+ const attempt = generation?.attempt;
67
+ if (retry === undefined || attempt === undefined) return;
68
+ void enqueue(() => count(runId, attempt, retry.at, retry.error));
69
+ };
70
+
71
+ const attach = async (runId: string, conversationId: number): Promise<void> => {
72
+ if (closed || detaches.has(runId)) return;
73
+ let advanced = false;
74
+ let ended = false;
75
+ const observer = {
76
+ advance(call: { readonly kind: string; readonly value?: unknown }) {
77
+ if (call.kind !== "value" || ended) return;
78
+ advanced = true;
79
+ onLive(runId, call.value as Readonly<LiveState>);
80
+ },
81
+ end() {
82
+ ended = true;
83
+ detaches.delete(runId);
84
+ },
85
+ };
86
+ const observation = await deps.runtime.run((context) =>
87
+ deps.runtime.harness.observeDoc(LiveDoc, toConversationId(conversationId), observer, context),
88
+ );
89
+ if (observation === undefined) return;
90
+ detaches.set(runId, () => {
91
+ ended = true;
92
+ observation.detach();
93
+ detaches.delete(runId);
94
+ });
95
+ if (!advanced && !ended) onLive(runId, observation.value);
96
+ };
97
+
98
+ const reconcile = async (): Promise<void> => {
99
+ if (closed) return;
100
+ // Group children are reached through their parent document, never the index.
101
+ // Every indexed run is read on every tick, watched or not: a workflow commits
102
+ // its children to `childRunIds` after it starts, so a skipped parent read
103
+ // would hide each child that appears later. A child has no returned document
104
+ // and is read once, here.
105
+ // The read set is the whole index, not a window: a cap would drop the retry
106
+ // lines of an old live run, and the log promises one line per attempt. A
107
+ // loaded document is served from the session's in-memory cache, so a tick
108
+ // costs one lookup per run rather than one store read.
109
+ const { runIds, docs } = await listedRuns(deps.runtime);
110
+ for (const runId of runIds) {
111
+ if (closed) return;
112
+ if (detaches.has(runId)) continue;
113
+ const doc = docs.get(runId) ?? (await deps.runtime.snapshot(RunDoc, runId));
114
+ const conversationId = doc?.childConversationId;
115
+ if (conversationId === null || conversationId === undefined) continue;
116
+ await attach(runId, conversationId);
117
+ }
118
+ };
119
+
120
+ const schedule = (): void => {
121
+ if (closed) return;
122
+ armed = deps.runtime.timers.setTimeout(() => {
123
+ armed = undefined;
124
+ void enqueue(reconcile);
125
+ schedule();
126
+ }, RETRY_RECONCILE_MS);
127
+ };
128
+
129
+ void enqueue(reconcile);
130
+ schedule();
131
+
132
+ const unsubscribe = deps.runtime.onState((state) => {
133
+ if (state.kind === "closed" || state.kind === "failing") void close();
134
+ });
135
+
136
+ const close = async (): Promise<void> => {
137
+ if (closed) return;
138
+ closed = true;
139
+ unsubscribe();
140
+ if (armed !== undefined) {
141
+ deps.runtime.timers.clearTimeout(armed);
142
+ armed = undefined;
143
+ }
144
+ await chain;
145
+ for (const detach of detaches.values()) detach();
146
+ detaches.clear();
147
+ };
148
+
149
+ return { close };
150
+ };
@@ -0,0 +1,81 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import {
3
+ closeWithin,
4
+ droppedOwn,
5
+ noticeFor,
6
+ OWN_TOOL_NAMES,
7
+ stderrLineFor,
8
+ withoutOwn,
9
+ type RefusedVerdict,
10
+ } from "./revocation.ts";
11
+
12
+ const refused: RefusedVerdict = {
13
+ kind: "refused",
14
+ conflict: "pi-subagents",
15
+ message: "@ftrdotdev/pi-delegates cannot load while pi-subagents is enabled.",
16
+ };
17
+
18
+ it("the filter removes exactly the three own names", () => {
19
+ assert.deepStrictEqual(OWN_TOOL_NAMES, [
20
+ "delegate_launch",
21
+ "delegate_control",
22
+ "delegate_status",
23
+ ]);
24
+ assert.deepStrictEqual(
25
+ withoutOwn(["read", "delegate_launch", "delegate_control", "delegate_status", "bash"]),
26
+ ["read", "bash"],
27
+ );
28
+ });
29
+
30
+ it("the filter keeps the host order", () => {
31
+ assert.deepStrictEqual(withoutOwn(["bash", "delegate_status", "read"]), ["bash", "read"]);
32
+ });
33
+
34
+ it("the filter is pure", () => {
35
+ const active = ["read", "delegate_launch", "bash"];
36
+ const first = withoutOwn(active);
37
+ const second = withoutOwn(active);
38
+ assert.deepStrictEqual(first, ["read", "bash"]);
39
+ assert.deepStrictEqual(second, first);
40
+ assert.deepStrictEqual(active, ["read", "delegate_launch", "bash"]);
41
+ });
42
+
43
+ it("the notice states the shutdown and the readable runs", () => {
44
+ const notice = noticeFor(refused);
45
+ assert.ok(notice.startsWith(refused.message), notice);
46
+ assert.ok(notice.includes("resume"), notice);
47
+ assert.ok(!notice.includes("parked"), notice);
48
+ });
49
+
50
+ it("the stderr form of the notice is one line", () => {
51
+ const line = stderrLineFor(refused);
52
+ assert.ok(!line.includes("\n"), line);
53
+ assert.ok(line.startsWith(refused.message), line);
54
+ assert.ok(line.includes("resume"), line);
55
+ });
56
+
57
+ it("the filter reports the names it dropped", () => {
58
+ assert.deepStrictEqual(droppedOwn(["read", "delegate_launch"]), ["delegate_launch"]);
59
+ assert.deepStrictEqual(droppedOwn(["read", "bash"]), []);
60
+ });
61
+
62
+ it("closeWithin gives up on a close that never settles", async () => {
63
+ const overdue: Array<unknown> = [];
64
+ await closeWithin(
65
+ () => new Promise<void>(() => {}),
66
+ 5,
67
+ (error) => overdue.push(error),
68
+ );
69
+ assert.deepStrictEqual(overdue, [undefined]);
70
+ });
71
+
72
+ it("closeWithin reports a failing close", async () => {
73
+ const failure = new Error("the provider ignored its abort");
74
+ const overdue: Array<unknown> = [];
75
+ await closeWithin(
76
+ () => Promise.reject(failure),
77
+ 5,
78
+ (error) => overdue.push(error),
79
+ );
80
+ assert.deepStrictEqual(overdue, [failure]);
81
+ });
@@ -0,0 +1,84 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { LogSink } from "../runtime/log.ts";
3
+ import type { CoexistenceVerdict } from "./guard.ts";
4
+
5
+ export type RefusedVerdict = Extract<CoexistenceVerdict, { kind: "refused" }>;
6
+
7
+ export const OWN_TOOL_NAMES = ["delegate_launch", "delegate_control", "delegate_status"] as const;
8
+ const OWN: ReadonlySet<string> = new Set(OWN_TOOL_NAMES);
9
+
10
+ /** How long a refusal waits for the old runtime before the start carries on. */
11
+ export const REVOCATION_CLOSE_MS = 2_000;
12
+
13
+ export const withoutOwn = (active: readonly string[]): string[] =>
14
+ active.filter((name) => !OWN.has(name));
15
+
16
+ /** The names the filter removes; the report logs exactly these. */
17
+ export const droppedOwn = (active: readonly string[]): string[] =>
18
+ active.filter((name) => OWN.has(name));
19
+
20
+ export const revokeTools = (pi: ExtensionAPI): readonly string[] => {
21
+ const active = pi.getActiveTools();
22
+ pi.setActiveTools(withoutOwn(active));
23
+ return droppedOwn(active);
24
+ };
25
+
26
+ export interface RevocationState {
27
+ verdict?: RefusedVerdict;
28
+ }
29
+
30
+ export const noticeFor = (verdict: RefusedVerdict): string =>
31
+ `${verdict.message}\n` +
32
+ "Delegates is shutting down. Runs committed before this refusal stay readable and " +
33
+ "resume in a session without the conflict.";
34
+
35
+ /** The notice as one stderr line: a non-TUI consumer reads exactly one. */
36
+ export const stderrLineFor = (verdict: RefusedVerdict): string =>
37
+ noticeFor(verdict).replaceAll("\n", " ");
38
+
39
+ export interface RefusalReport {
40
+ readonly ctx: ExtensionContext;
41
+ readonly verdict: RefusedVerdict;
42
+ /** The tools this refusal removed from the active set; empty in the first-start shape. */
43
+ readonly removed: readonly string[];
44
+ readonly log: LogSink;
45
+ }
46
+
47
+ /** The one user-visible report: a notice, an stderr line off-TUI, and a log line. */
48
+ export const reportRefusal = ({ ctx, verdict, removed, log }: RefusalReport): void => {
49
+ const message = noticeFor(verdict);
50
+ ctx.ui.notify(message, "error");
51
+ if (ctx.mode === "print" || ctx.mode === "json") {
52
+ process.stderr.write(`${stderrLineFor(verdict)}\n`);
53
+ }
54
+ log.write("error", "coexistence.revoked", {
55
+ conflict: verdict.conflict,
56
+ ...(removed.length === 0 ? {} : { removed: removed.join(",") }),
57
+ });
58
+ };
59
+
60
+ /**
61
+ * Waits at most `ms` for `close`. A close that misses the bound or fails calls
62
+ * `onOverdue` and the start carries on; a late rejection is caught here.
63
+ */
64
+ export const closeWithin = async (
65
+ close: () => Promise<void>,
66
+ ms: number,
67
+ onOverdue: (error?: unknown) => void,
68
+ ): Promise<void> => {
69
+ const settling = close().then(
70
+ () => "closed" as const,
71
+ (error: unknown) => {
72
+ onOverdue(error);
73
+ return "failed" as const;
74
+ },
75
+ );
76
+ let timer: ReturnType<typeof setTimeout> | undefined;
77
+ const late = new Promise<"late">((resolve) => {
78
+ timer = setTimeout(() => resolve("late"), ms);
79
+ });
80
+ const outcome = await Promise.race([settling, late]);
81
+ if (timer !== undefined) clearTimeout(timer);
82
+ if (outcome !== "late") return;
83
+ onOverdue();
84
+ };