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