@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,685 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ ExtensionUIContext,
5
+ SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
+ import { VimRouter } from "@ftrdotdev/pi-tui";
9
+ import { Effect, Fiber, Predicate, Schema, Stream } from "effect";
10
+ import { readFile } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+ import { endNotice, InspectorReadFailed, type InspectorEnd } from "../presentation/inspector.ts";
13
+ import { openInspectorActivation, type InspectorActivation } from "../layers.ts";
14
+ import type { SessionHandle } from "../runtime/handle.ts";
15
+ import {
16
+ runInspectorAction,
17
+ targetLabel,
18
+ type ActionResult,
19
+ type ActionTarget,
20
+ } from "../presentation/actions.ts";
21
+ import {
22
+ makeDelegatesOverlay,
23
+ OVERLAY_OPTIONS,
24
+ type OverlayVerb,
25
+ } from "../presentation/overlay.ts";
26
+ import type { InspectorSnapshot } from "../presentation/snapshot.ts";
27
+ import { activeStatus, offStatus, STATUS_KEY } from "../presentation/status.ts";
28
+ import { makeDelegatesStrip, STRIP_KEY, STRIP_PLACEMENT } from "../presentation/strip.ts";
29
+ import {
30
+ gateAgentMessage,
31
+ gateNotice,
32
+ requestAgentMessage,
33
+ requestToastLine,
34
+ type GateNotice,
35
+ settleAgentMessage,
36
+ type RequestNotice,
37
+ } from "../presentation/wording.ts";
38
+ import type { SessionRuntime } from "../runtime/session.ts";
39
+ import { errorFields, nullLogSink, type LogSink } from "../runtime/log.ts";
40
+ import { DEFAULT_INSPECT_SHORTCUT } from "../presentation/shortcut.ts";
41
+ import type { ObservationSeam } from "../runtime/observe.ts";
42
+ import type { Timers } from "../runtime/clock.ts";
43
+ import { Ref } from "effect";
44
+ import type { SessionView } from "../domain/view.ts";
45
+ import type { GateAlertHost } from "./gate-alerts.ts";
46
+ import type { SettleAlertHost } from "./settle-alerts.ts";
47
+ import type { RequestAlertHost } from "./request-alerts.ts";
48
+
49
+ /** The session-metadata key. Entries are appended, never removed, so the **last** one wins. */
50
+ export const ACTIVATION_ENTRY = "delegates.inspector";
51
+
52
+ /** One announced gate id per entry; a reload reads them back before it starts the watcher. */
53
+ export const GATE_ALERT_ENTRY = "delegates.gate-alert";
54
+
55
+ /** One announced request id per entry, read back on a reload like the gate entries. */
56
+ export const REQUEST_ALERT_ENTRY = "delegates.request-alert";
57
+
58
+ /** The shared TUI settings file, owned by `packages/tui`. */
59
+ const TUI_CONFIG_FILE = "tui.json";
60
+
61
+ /**
62
+ * A flag read from parsed JSON. Only the boolean `true` counts as on: a
63
+ * missing, `"true"`, or `1` value reads as off.
64
+ */
65
+ const readFlag = Schema.is(Schema.Literal(true));
66
+
67
+ export const readActivation = (entries: readonly SessionEntry[]): boolean => {
68
+ const last = entries
69
+ .filter((entry) => entry.type === "custom" && entry.customType === ACTIVATION_ENTRY)
70
+ .at(-1);
71
+ const data = last?.type === "custom" ? last.data : undefined;
72
+ return Predicate.isObject(data) && readFlag(data.active);
73
+ };
74
+
75
+ /** True when the session carries at least one activation marker, on or off. */
76
+ export const hasActivationEntry = (entries: readonly SessionEntry[]): boolean => {
77
+ for (const entry of entries) {
78
+ if (entry.type === "custom" && entry.customType === ACTIVATION_ENTRY) return true;
79
+ }
80
+ return false;
81
+ };
82
+
83
+ /** Gate ids already announced through this session's metadata. */
84
+ export const readGateAlerts = (entries: readonly SessionEntry[]): ReadonlySet<string> => {
85
+ const ids = new Set<string>();
86
+ for (const entry of entries) {
87
+ if (entry.type !== "custom" || entry.customType !== GATE_ALERT_ENTRY) continue;
88
+ const data = entry.data;
89
+ if (Predicate.isObject(data) && typeof data.gateId === "string") ids.add(data.gateId);
90
+ }
91
+ return ids;
92
+ };
93
+
94
+ /** Request ids already announced through this session's metadata. */
95
+ export const readRequestAlerts = (entries: readonly SessionEntry[]): ReadonlySet<string> => {
96
+ const ids = new Set<string>();
97
+ for (const entry of entries) {
98
+ if (entry.type !== "custom" || entry.customType !== REQUEST_ALERT_ENTRY) continue;
99
+ const data = entry.data;
100
+ if (Predicate.isObject(data) && typeof data.requestId === "string") {
101
+ ids.add(data.requestId);
102
+ }
103
+ }
104
+ return ids;
105
+ };
106
+
107
+ export interface InspectorHost extends GateAlertHost, RequestAlertHost, SettleAlertHost {
108
+ readonly ui: Pick<ExtensionUIContext, "setWidget" | "custom" | "notify" | "setStatus">;
109
+ readonly mode: ExtensionContext["mode"];
110
+ readonly appendActivation: (active: boolean) => void;
111
+ readonly readActivation: () => boolean;
112
+ /** One warning toast and one parent-agent message per newly pending gate. */
113
+ readonly notifyGate: (gate: GateNotice, shortcut: string) => void;
114
+ }
115
+
116
+ export interface InspectorOverrides {
117
+ readonly observe?: ObservationSeam;
118
+ readonly now?: () => number;
119
+ readonly timers?: Timers;
120
+ readonly view?: () => Promise<SessionView>;
121
+ }
122
+
123
+ export interface InspectorCommandDeps {
124
+ /** The current handle; absent before a session opens or after it closes. */
125
+ readonly session: Ref.Ref<SessionHandle | undefined>;
126
+ readonly host: (ctx: ExtensionContext) => InspectorHost;
127
+ /** The resolved overlay shortcut; defaults to `ctrl+space`. */
128
+ readonly shortcut?: string;
129
+ /** Test seam: observation, clock and view overrides for the owner. */
130
+ readonly inspector?: InspectorOverrides;
131
+ /** Test seam: the write runner; defaults to `runInspectorAction`. */
132
+ readonly action?: (input: Parameters<typeof runInspectorAction>[0]) => Promise<ActionResult>;
133
+ }
134
+
135
+ /** One activation: one service, one subscription, one sink registry, one cached snapshot. */
136
+ interface Activation extends InspectorActivation {
137
+ readonly host: InspectorHost;
138
+ readonly shortcut: string;
139
+ readonly runtime: SessionRuntime;
140
+ readonly sinks: Map<string, () => void>;
141
+ latest: InspectorSnapshot;
142
+ /** The last footer line written, so an unchanged publication writes nothing. */
143
+ lastStatus: string | undefined;
144
+ /** The last action's line: persists until the next action or the overlay closes. */
145
+ statusLine: string | null;
146
+ subscription: Fiber.Fiber<void, never> | undefined;
147
+ stripMounted: boolean;
148
+ stripRender: (() => void) | undefined;
149
+ stripSink: (() => void) | undefined;
150
+ }
151
+
152
+ let activation: Activation | undefined;
153
+ /** One lifecycle operation at a time: activation, restore, branch sync and teardown. */
154
+ let operation: Promise<void> = Promise.resolve();
155
+
156
+ const serial = <T>(run: () => Promise<T>): Promise<T> => {
157
+ const next = operation.then(run, run);
158
+ operation = next.then(
159
+ () => undefined,
160
+ () => undefined,
161
+ );
162
+ return next;
163
+ };
164
+
165
+ /** The host seam: the extension API is the only writer of the marker. */
166
+ export const hostFor = (
167
+ pi: ExtensionAPI,
168
+ ctx: ExtensionContext,
169
+ log: () => LogSink = () => nullLogSink,
170
+ ): InspectorHost => ({
171
+ ui: ctx.ui,
172
+ mode: ctx.mode,
173
+ appendActivation: (active) => {
174
+ pi.appendEntry(ACTIVATION_ENTRY, { active });
175
+ },
176
+ readActivation: () => readActivation(ctx.sessionManager.getEntries()),
177
+ readGateAlerts: () => readGateAlerts(ctx.sessionManager.getEntries()),
178
+ appendGateAlert: (gateId) => {
179
+ pi.appendEntry(GATE_ALERT_ENTRY, { gateId });
180
+ },
181
+ readRequestAlerts: () => readRequestAlerts(ctx.sessionManager.getEntries()),
182
+ appendRequestAlert: (requestId) => {
183
+ pi.appendEntry(REQUEST_ALERT_ENTRY, { requestId });
184
+ },
185
+ notifyRequest: (notice: RequestNotice) => {
186
+ try {
187
+ ctx.ui.notify(requestToastLine(notice), "warning");
188
+ } catch (error) {
189
+ log().write("warn", "inspector.notify_failed", {
190
+ requestId: notice.requestId,
191
+ surface: "ui",
192
+ ...errorFields(error),
193
+ });
194
+ }
195
+ try {
196
+ pi.sendMessage(
197
+ {
198
+ customType: "delegates.request",
199
+ content: requestAgentMessage(notice),
200
+ display: true,
201
+ details: { runId: notice.runId, requestId: notice.requestId },
202
+ },
203
+ { deliverAs: "followUp", triggerTurn: true },
204
+ );
205
+ } catch (error) {
206
+ // The toast already landed; a host that refuses messages must not fail the view.
207
+ log().write("warn", "inspector.notify_failed", {
208
+ requestId: notice.requestId,
209
+ surface: "agent",
210
+ ...errorFields(error),
211
+ });
212
+ }
213
+ },
214
+ notifySettled: (notice, omitted = 0) => {
215
+ try {
216
+ pi.sendMessage(
217
+ {
218
+ customType: "delegates.settled",
219
+ content: settleAgentMessage(notice, omitted),
220
+ display: true,
221
+ details: { runIds: notice.rows.map((row) => row.runId) },
222
+ },
223
+ { deliverAs: "followUp", triggerTurn: false },
224
+ );
225
+ } catch (error) {
226
+ // `pi.sendMessage` is fire-and-forget: it returns a promise whose rejection the host
227
+ // swallows, so only a synchronous throw — an inactive session refusing the append —
228
+ // reaches this line.
229
+ log().write("warn", "settle.notify_failed", {
230
+ runs: notice.rows.map((row) => row.runId).join(","),
231
+ ...errorFields(error),
232
+ });
233
+ }
234
+ },
235
+ notifyGate: (gate, shortcut) => {
236
+ try {
237
+ ctx.ui.notify(gateNotice(gate), "warning");
238
+ } catch (error) {
239
+ log().write("warn", "inspector.notify_failed", {
240
+ gateId: gate.id,
241
+ surface: "ui",
242
+ ...errorFields(error),
243
+ });
244
+ }
245
+ try {
246
+ pi.sendMessage(
247
+ {
248
+ customType: "delegates.gate",
249
+ content: gateAgentMessage(gate, shortcut),
250
+ display: true,
251
+ details: { runId: gate.runId, gate: gate.gate },
252
+ },
253
+ { deliverAs: "followUp", triggerTurn: true },
254
+ );
255
+ } catch (error) {
256
+ // The toast already landed; a host that refuses messages must not fail the view.
257
+ log().write("warn", "inspector.notify_failed", {
258
+ gateId: gate.id,
259
+ surface: "agent",
260
+ ...errorFields(error),
261
+ });
262
+ }
263
+ },
264
+ });
265
+
266
+ const messageOf = (error: unknown): string => {
267
+ if (error instanceof Error) {
268
+ const cause = error.cause;
269
+ if (cause instanceof Error) return cause.message;
270
+ if (typeof cause === "string") return cause;
271
+ return error.message;
272
+ }
273
+ return String(error);
274
+ };
275
+
276
+ const readVimEnabled = async (): Promise<boolean> => {
277
+ try {
278
+ const raw = await readFile(join(getAgentDir(), TUI_CONFIG_FILE), "utf8");
279
+ const parsed: unknown = JSON.parse(raw);
280
+ return Predicate.isObject(parsed) && readFlag(parsed.vim);
281
+ } catch {
282
+ return false;
283
+ }
284
+ };
285
+
286
+ const readVimRouter = async (): Promise<VimRouter["Service"]> => {
287
+ const enabled = await readVimEnabled();
288
+ return VimRouter.make(() => enabled);
289
+ };
290
+
291
+ const registerSink = (current: Activation, key: string, sink: () => void): (() => void) => {
292
+ current.sinks.set(key, sink);
293
+ return () => {
294
+ if (current.sinks.get(key) === sink) current.sinks.delete(key);
295
+ };
296
+ };
297
+
298
+ const unmountStrip = (current: Activation): void => {
299
+ current.host.ui.setWidget(STRIP_KEY, undefined);
300
+ current.stripMounted = false;
301
+ current.stripRender = undefined;
302
+ current.stripSink?.();
303
+ current.stripSink = undefined;
304
+ };
305
+
306
+ const mountStrip = (current: Activation): void => {
307
+ current.stripMounted = true;
308
+ current.host.ui.setWidget(
309
+ STRIP_KEY,
310
+ (tui: { requestRender: () => void }, theme) => {
311
+ current.stripRender = () => tui.requestRender();
312
+ current.stripSink = registerSink(current, "strip", () => current.stripRender?.());
313
+ return makeDelegatesStrip({
314
+ getSnapshot: () => current.latest,
315
+ theme,
316
+ shortcut: current.shortcut,
317
+ });
318
+ },
319
+ { placement: STRIP_PLACEMENT },
320
+ );
321
+ };
322
+
323
+ /**
324
+ * Writes the footer line only when it changed. Both high-frequency paths — a
325
+ * publication and an activation — go through here; an unchanged snapshot costs
326
+ * no repaint. The restore path writes once per session bind and stays outside
327
+ * this cache: a reload clears the host footer, so the line must be re-asserted
328
+ * rather than skipped.
329
+ */
330
+ const writeStatus = (current: Activation, text: string): void => {
331
+ if (current.lastStatus === text) return;
332
+ current.lastStatus = text;
333
+ current.host.ui.setStatus(STATUS_KEY, text);
334
+ };
335
+
336
+ /** A gate is announced by the session watcher, not by an activation. */
337
+ const publish = (current: Activation, next: InspectorSnapshot): void => {
338
+ current.latest = next;
339
+ writeStatus(current, activeStatus(next.counts, current.shortcut));
340
+ // A publication repaints mounted surfaces; it never runs the overlay's close handle.
341
+ for (const [key, sink] of current.sinks) {
342
+ if (key !== "overlay:close") sink();
343
+ }
344
+ };
345
+
346
+ const activate = async (
347
+ deps: InspectorCommandDeps,
348
+ host: InspectorHost,
349
+ options: { readonly writeMarker: boolean },
350
+ ): Promise<void> => {
351
+ if (host.mode !== "tui") return;
352
+ const handle = Ref.getUnsafe(deps.session);
353
+ if (handle === undefined) return;
354
+ const runtime = handle.runtime;
355
+ const alreadyMarked = host.readActivation();
356
+ let opened: InspectorActivation;
357
+ let snapshot: InspectorSnapshot;
358
+ try {
359
+ opened = await Effect.runPromise(openInspectorActivation(handle, deps.inspector ?? {}));
360
+ snapshot = await Effect.runPromise(opened.service.snapshot);
361
+ } catch (error) {
362
+ // The failure keeps its type: a read that failed says so, in one log entry.
363
+ if (error instanceof InspectorReadFailed) {
364
+ runtime.log.write("error", "inspector.read_failed", errorFields(error));
365
+ }
366
+ const line = endNotice({
367
+ kind: "runtime-ended",
368
+ reason: `failed to start: ${messageOf(error)}`,
369
+ });
370
+ if (line !== undefined) host.ui.notify(line, "warning");
371
+ return;
372
+ }
373
+ const service = opened.service;
374
+
375
+ const current: Activation = {
376
+ host,
377
+ shortcut: deps.shortcut ?? DEFAULT_INSPECT_SHORTCUT,
378
+ service,
379
+ run: opened.run,
380
+ fork: opened.fork,
381
+ interrupt: opened.interrupt,
382
+ close: opened.close,
383
+ runtime,
384
+ sinks: new Map(),
385
+ latest: snapshot,
386
+ lastStatus: undefined,
387
+ statusLine: null,
388
+ subscription: undefined,
389
+ stripMounted: false,
390
+ stripRender: undefined,
391
+ stripSink: undefined,
392
+ };
393
+ activation = current;
394
+ if (options.writeMarker && !alreadyMarked) host.appendActivation(true);
395
+ writeStatus(current, activeStatus(snapshot.counts, current.shortcut));
396
+ mountStrip(current);
397
+ current.subscription = await current.fork(
398
+ Stream.runForEach(
399
+ // The replay is the snapshot this activation already shows; a publication that
400
+ // landed before the fork started is a replay too, so drop by revision, once.
401
+ Stream.dropWhile(service.changes, (next) => next.revision <= snapshot.revision),
402
+ (next) => Effect.sync(() => publish(current, next)),
403
+ ),
404
+ );
405
+ await current.fork(
406
+ Stream.runForEach(service.end, (end) => Effect.sync(() => handleEnd(current, end))),
407
+ );
408
+ };
409
+
410
+ /** The one forced-close notice, written once, before the layer is disposed. */
411
+ const announceEnd = (host: InspectorHost, end: InspectorEnd): void => {
412
+ const line = endNotice(end);
413
+ if (line !== undefined) host.ui.notify(line, "warning");
414
+ };
415
+
416
+ /** A runtime end writes one notice and tears every surface down once. */
417
+ const handleEnd = (current: Activation, end: InspectorEnd): void => {
418
+ if (activation !== current || end.kind !== "runtime-ended") return;
419
+ announceEnd(current.host, end);
420
+ void teardownInspector({ markOff: false });
421
+ };
422
+
423
+ /**
424
+ * Toggles: a live activation tears down, otherwise a fresh owner is
425
+ * provisioned, the marker is written and the strip is mounted.
426
+ */
427
+ export const runDelegatesCommand = async (
428
+ deps: InspectorCommandDeps,
429
+ ctx: ExtensionContext,
430
+ ): Promise<void> => {
431
+ await serial(async () => {
432
+ const host = deps.host(ctx);
433
+ if (host.mode !== "tui") return;
434
+ if (activation !== undefined) {
435
+ await teardownActivation();
436
+ return;
437
+ }
438
+ await activate(deps, host, { writeMarker: true });
439
+ });
440
+ };
441
+
442
+ /** The row a write addresses: a gate row names gate and run, a run row names its run. */
443
+ const targetOf = (snapshot: InspectorSnapshot, rowId: string): ActionTarget | undefined => {
444
+ const gate = snapshot.gates.find((candidate) => candidate.id === rowId);
445
+ if (gate !== undefined) return { rowId, runId: gate.runId, gate: gate.gate };
446
+ const row = snapshot.rows.find((candidate) => candidate.id === rowId);
447
+ if (row === undefined) return undefined;
448
+ // One gate on a waiting row is actionable there: route to the gate's owner run,
449
+ // which is the parent run for a fanout or review child.
450
+ if (row.gates.length === 1) {
451
+ const gateName = row.gates[0];
452
+ if (gateName === undefined) return undefined;
453
+ const owned = snapshot.gates.find(
454
+ (candidate) =>
455
+ candidate.gate === gateName &&
456
+ (candidate.runId === row.runId || candidate.childRunIds.includes(row.runId)),
457
+ );
458
+ if (owned !== undefined) return { rowId, runId: owned.runId, gate: owned.gate };
459
+ }
460
+ return { rowId, runId: row.runId };
461
+ };
462
+
463
+ /** One keypress, one write; the line lands when the write returns, never before. */
464
+ const dispatchAction = (
465
+ current: Activation,
466
+ action: (input: Parameters<typeof runInspectorAction>[0]) => Promise<ActionResult>,
467
+ rowId: string,
468
+ verb: OverlayVerb,
469
+ isOpen: () => boolean,
470
+ ): void => {
471
+ const target = targetOf(current.latest, rowId);
472
+ if (target === undefined) return;
473
+ void action({
474
+ runtime: current.runtime,
475
+ target,
476
+ verb,
477
+ refresh: () => current.run(current.service.refresh),
478
+ })
479
+ .then((result) => {
480
+ // The overlay may have closed, or the activation may have been replaced,
481
+ // while the write was in flight: a late line must not reappear.
482
+ if (!isOpen() || activation !== current) return;
483
+ current.statusLine = result.message;
484
+ current.sinks.get("overlay:render")?.();
485
+ })
486
+ .catch((error: unknown) => {
487
+ current.runtime.log.write("warn", "inspector.action_failed", {
488
+ target: targetLabel(target),
489
+ ...errorFields(error),
490
+ });
491
+ });
492
+ };
493
+
494
+ export type SessionStartReason = "startup" | "reload" | "new" | "resume" | "fork";
495
+
496
+ /** Restoring is a reason test plus the last marker entry, nothing else. */
497
+ export const shouldRestore = (
498
+ reason: SessionStartReason,
499
+ entries: readonly SessionEntry[],
500
+ ): boolean => reason !== "new" && reason !== "fork" && readActivation(entries);
501
+
502
+ /**
503
+ * Restore at session start: a fork copies the marker but shows nothing, so it
504
+ * appends `{ active: false }`; every other allowed reason provisions a fresh
505
+ * owner layer when the last marker is active.
506
+ */
507
+ export const restoreInspector = async (
508
+ deps: InspectorCommandDeps,
509
+ ctx: ExtensionContext,
510
+ event: { readonly reason: SessionStartReason },
511
+ ): Promise<void> => {
512
+ await serial(async () => {
513
+ const host = deps.host(ctx);
514
+ if (event.reason === "fork" && host.readActivation()) host.appendActivation(false);
515
+ if (host.mode !== "tui") return;
516
+ if (activation !== undefined) return;
517
+ const entries = ctx.sessionManager.getEntries();
518
+ if (shouldRestore(event.reason, entries)) {
519
+ await activate(deps, host, { writeMarker: false });
520
+ return;
521
+ }
522
+ // Only a session that opted in carries the hint; a fresh one writes no line.
523
+ if (hasActivationEntry(entries)) host.ui.setStatus(STATUS_KEY, offStatus());
524
+ });
525
+ };
526
+
527
+ /**
528
+ * Auto-activation for a delegate launch. A session with no marker turns the
529
+ * inspector on; an explicit off marker is left alone.
530
+ */
531
+ export const ensureInspector = async (
532
+ deps: InspectorCommandDeps,
533
+ ctx: ExtensionContext,
534
+ ): Promise<void> => {
535
+ await serial(async () => {
536
+ const host = deps.host(ctx);
537
+ if (host.mode !== "tui" || activation !== undefined) return;
538
+ const entries = ctx.sessionManager.getEntries();
539
+ if (hasActivationEntry(entries) && !readActivation(entries)) return;
540
+ try {
541
+ await activate(deps, host, { writeMarker: true });
542
+ } catch (error) {
543
+ const line = endNotice({
544
+ kind: "runtime-ended",
545
+ reason: `failed to start: ${messageOf(error)}`,
546
+ });
547
+ if (line !== undefined) host.ui.notify(line, "warning");
548
+ }
549
+ });
550
+ };
551
+
552
+ /** A branch move can change which entries the branch carries, including the marker. */
553
+ export const syncInspectorBranch = async (
554
+ deps: InspectorCommandDeps,
555
+ ctx: ExtensionContext,
556
+ ): Promise<void> => {
557
+ await serial(async () => {
558
+ const host = deps.host(ctx);
559
+ const active = host.readActivation();
560
+ if (active && activation === undefined) {
561
+ await activate(deps, host, { writeMarker: false });
562
+ return;
563
+ }
564
+ if (!active && activation !== undefined) await teardownActivation({ markOff: false });
565
+ });
566
+ };
567
+
568
+ /**
569
+ * Both doors to the overlay. Each refuses when the inspector is off: a silent
570
+ * shortcut reads as a broken key when the real answer is `/delegates`.
571
+ */
572
+ export const openInspectorOverlay = async (
573
+ deps: InspectorCommandDeps,
574
+ ctx: ExtensionContext,
575
+ options: { readonly refuse: boolean },
576
+ ): Promise<void> => {
577
+ const host = deps.host(ctx);
578
+ if (host.mode !== "tui") return;
579
+ const current = activation;
580
+ if (current === undefined) {
581
+ if (options.refuse) {
582
+ host.ui.notify("inspector is off — run /delegates to turn it on", "warning");
583
+ }
584
+ return;
585
+ }
586
+ const vim = await readVimRouter();
587
+ await host.ui.custom<undefined>(
588
+ (tui, theme, _kb, done) => {
589
+ let closed = false;
590
+ let unregister: (() => void) | undefined;
591
+ let unregisterRepaint: (() => void) | undefined;
592
+ let actionSequence = 0;
593
+ const close = (): void => {
594
+ if (closed) return;
595
+ closed = true;
596
+ unregister?.();
597
+ unregister = undefined;
598
+ unregisterRepaint?.();
599
+ unregisterRepaint = undefined;
600
+ current.statusLine = null;
601
+ done(undefined);
602
+ };
603
+ unregister = registerSink(current, "overlay:close", close);
604
+ unregisterRepaint = registerSink(current, "overlay:render", () => tui.requestRender());
605
+ const overlay = makeDelegatesOverlay({
606
+ getSnapshot: () => current.latest,
607
+ theme,
608
+ router: vim,
609
+ requestRender: () => tui.requestRender(),
610
+ statusLine: () => current.statusLine,
611
+ onAction: (rowId, verb) => {
612
+ actionSequence += 1;
613
+ const sequence = actionSequence;
614
+ // A second verb may overlap the first; only the latest dispatch may
615
+ // write the status line, whichever result arrives first.
616
+ dispatchAction(
617
+ current,
618
+ deps.action ?? runInspectorAction,
619
+ rowId,
620
+ verb,
621
+ () => !closed && sequence === actionSequence,
622
+ );
623
+ },
624
+ onClose: close,
625
+ });
626
+ return {
627
+ render: (width: number) => overlay.render(width),
628
+ invalidate: () => overlay.invalidate(),
629
+ handleInput: (data: string) => {
630
+ overlay.handleInput(data);
631
+ tui.requestRender();
632
+ },
633
+ };
634
+ },
635
+ { overlay: true, overlayOptions: () => OVERLAY_OPTIONS },
636
+ );
637
+ };
638
+
639
+ /** The only two registrations for the overlay: `/delegates:overlay` and the configured shortcut. */
640
+ export const registerInspectorOverlay = (pi: ExtensionAPI, deps: InspectorCommandDeps): void => {
641
+ pi.registerCommand("delegates:overlay", {
642
+ description: "Open the delegates inspector overlay",
643
+ handler: (_args, ctx) => openInspectorOverlay(deps, ctx, { refuse: true }),
644
+ });
645
+ pi.registerShortcut(
646
+ (deps.shortcut ?? DEFAULT_INSPECT_SHORTCUT) as Parameters<ExtensionAPI["registerShortcut"]>[0],
647
+ {
648
+ description: "Delegates: open the inspector overlay",
649
+ handler: (ctx) => openInspectorOverlay(deps, ctx, { refuse: true }),
650
+ },
651
+ );
652
+ };
653
+
654
+ /** Remove the overlay, the strip, the subscription, then close the activation's scope. Idempotent. */
655
+ const teardownActivation = async (
656
+ options: {
657
+ readonly markOff?: boolean;
658
+ } = {},
659
+ ): Promise<void> => {
660
+ const current = activation;
661
+ if (current === undefined) return;
662
+ activation = undefined;
663
+ if (options.markOff !== false) current.host.appendActivation(false);
664
+ const closeOverlay = current.sinks.get("overlay:close");
665
+ closeOverlay?.();
666
+ current.sinks.delete("overlay:close");
667
+ unmountStrip(current);
668
+ // A toggle leaves the hint; a reload, shutdown or runtime end clears the line.
669
+ current.host.ui.setStatus(STATUS_KEY, options.markOff === false ? undefined : offStatus());
670
+ for (const [key, sink] of current.sinks) {
671
+ if (key !== "overlay:close") sink();
672
+ }
673
+ current.sinks.clear();
674
+ if (current.subscription !== undefined) {
675
+ await current.interrupt(current.subscription).catch(() => undefined);
676
+ }
677
+ await current.close();
678
+ };
679
+
680
+ /** Remove the overlay, the strip, the subscription, then close the activation's scope. Idempotent. */
681
+ export const teardownInspector = (
682
+ options: {
683
+ readonly markOff?: boolean;
684
+ } = {},
685
+ ): Promise<void> => serial(() => teardownActivation(options));