@zhuxixi/pi-agent-board 0.13.1 → 0.14.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 (80) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +15 -8
  3. package/docs/SECTION_FOLDING.md +53 -0
  4. package/docs/superpowers/plans/2026-10-23-issue-222-attach-ready.md +290 -0
  5. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  6. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  7. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  8. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  9. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  10. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  11. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  12. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  13. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  14. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  15. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  16. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  17. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  18. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  19. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  20. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  21. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  22. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  23. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  24. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  25. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  26. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  27. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  28. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  29. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  30. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  31. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  32. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  33. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  34. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  35. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  36. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  37. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  38. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  39. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  40. package/package.json +1 -1
  41. package/runner/pty-runner.mjs +526 -63
  42. package/runner/title-runner.mjs +33 -24
  43. package/src/commands/agent-board.ts +5 -1
  44. package/src/core/attach-detach.mjs +27 -0
  45. package/src/core/attach-frame-proof.mjs +897 -0
  46. package/src/core/attach-frame-reporter.mjs +738 -0
  47. package/src/core/attach-frame-stream.mjs +266 -0
  48. package/src/core/attach-pr-label.mjs +12 -0
  49. package/src/core/attach-recovery.mjs +239 -0
  50. package/src/core/attach-screen-owner.mjs +55 -0
  51. package/src/core/attach-view-proof.mjs +709 -0
  52. package/src/core/auto-state.mjs +6 -1
  53. package/src/core/cwd-stats.mjs +3 -1
  54. package/src/core/dashboard-prefs.mjs +31 -0
  55. package/src/core/derive.mjs +8 -1
  56. package/src/core/events.mjs +127 -1
  57. package/src/core/foreground-projection-cache.mjs +1 -0
  58. package/src/core/frame-witness-update.mjs +35 -0
  59. package/src/core/fullscreen-selection.mjs +60 -0
  60. package/src/core/host-protocol.mjs +13 -2
  61. package/src/core/hosted-frame-witness.mjs +60 -0
  62. package/src/core/paths.mjs +10 -3
  63. package/src/core/pty-attach-render.mjs +239 -0
  64. package/src/core/pty-kitty-images.mjs +237 -0
  65. package/src/core/rows.mjs +43 -7
  66. package/src/core/session-entries.mjs +82 -0
  67. package/src/core/session-launch-prefs.mjs +45 -0
  68. package/src/core/session-view.mjs +3 -63
  69. package/src/core/store.mjs +1 -0
  70. package/src/core/terminal-attach-client.mjs +199 -20
  71. package/src/core/terminal-attach-protocol.mjs +221 -7
  72. package/src/core/terminal-model.mjs +24 -3
  73. package/src/core/terminal-snapshot.mjs +10 -0
  74. package/src/core/title-flow.mjs +66 -0
  75. package/src/core/title.mjs +101 -0
  76. package/src/core/types.mjs +17 -0
  77. package/src/index.ts +85 -0
  78. package/src/runtime/service.mjs +87 -18
  79. package/src/ui/dashboard.ts +198 -44
  80. package/src/ui/pty-attach.ts +1462 -117
@@ -0,0 +1,738 @@
1
+ /**
2
+ * Public-API child adapter for the attach frame witness (issue #222, step 23a).
3
+ *
4
+ * The adapter is inert until a runner explicitly enables it: it sends a `hello`
5
+ * carrying `clientId:"frame-reporter"` and `frameWitness:{protocol:1}`, and only a
6
+ * `{type:"frame_witness_enable", protocol:1, token}` reply turns the capability on.
7
+ * Old or silent runners therefore see byte-identical behaviour: no widget, no
8
+ * wrappers, no markers. Current runners may negotiate the capability explicitly;
9
+ * the adapter never enables itself merely because the extension loaded.
10
+ *
11
+ * ## Interface discipline (converged contract §2.1)
12
+ *
13
+ * - One zero-height belowEditor sentinel registered with the public `ctx.ui.setWidget`.
14
+ * It never changes focus, input, visible rows or editor content.
15
+ * - INSTANCE-OWN shadows only: `columns`/`rows` accessors, `write`/`hideCursor`/
16
+ * `showCursor` methods and the `start`/`stop` lifecycle. Prototype descriptors are
17
+ * recorded before shadowing, descriptor kinds are preserved, original `this`, args,
18
+ * return values and exceptions are passed through unchanged, and restore removes an
19
+ * own shadow ONLY while it is still this adapter's own function.
20
+ * - Focus comes from a runtime feature-detected `getFocusedComponent()`; when it is
21
+ * absent the capability reports `unsupported` instead of guessing from pixels.
22
+ * - Markers are written through the ORIGINAL (pre-shadow) terminal write, in order,
23
+ * with a reentrancy guard, and never enter candidate accounting. A marker failure
24
+ * turns the capability off and reports UNKNOWN; it never blocks or alters the
25
+ * original child output, and no later `F` is written as if the frame completed.
26
+ *
27
+ * Production wiring lives in `src/index.ts` and `runner/pty-runner.mjs`; the
28
+ * per-runner enable handshake remains mandatory on every path.
29
+ */
30
+ import {
31
+ FRAME_REPORTER_CLIENT_ID,
32
+ FRAME_WITNESS_PROTOCOL,
33
+ FrameCandidateEvaluator,
34
+ MAX_FRAME_MARKER_BYTES,
35
+ encodeFrameMarkerA,
36
+ encodeFrameMarkerF,
37
+ encodeFrameMarkerS,
38
+ isValidFrameWitnessToken,
39
+ } from "./attach-frame-proof.mjs";
40
+
41
+ export const ATTACH_FRAME_WIDGET_KEY = "agent-board-frame-witness";
42
+
43
+ const SENTINEL_KEYS = ["columns", "rows", "write", "hideCursor", "showCursor", "start", "stop"];
44
+ const MODES = new Set(["fullscreen", "regular"]);
45
+
46
+ function ownDescriptor(target, key) {
47
+ return Object.getOwnPropertyDescriptor(target, key);
48
+ }
49
+
50
+ function protoDescriptorOf(target, key) {
51
+ const proto = Object.getPrototypeOf(target);
52
+ return proto === null ? undefined : Object.getOwnPropertyDescriptor(proto, key);
53
+ }
54
+
55
+ /**
56
+ * Restore an adapter-owned shadow. If the adapter's shadow is still current, the
57
+ * PRE-EXISTING own descriptor is reinstalled when there was one (never erased), and the
58
+ * property is deleted only when no own property existed before. A third party's later
59
+ * replacement is left untouched.
60
+ */
61
+ function restoreOwnShadow(terminal, entry) {
62
+ const current = ownDescriptor(terminal, entry.key);
63
+ const installed = entry.installed;
64
+ const stillOurs = current !== undefined && (typeof installed === "function" ? current.get === installed || current.value === installed : current.value === installed);
65
+ if (!stillOurs) return current === undefined ? "already-absent" : "shadow-replaced-not-restored";
66
+ if (entry.ownBefore === undefined) delete terminal[entry.key];
67
+ else Object.defineProperty(terminal, entry.key, entry.ownBefore);
68
+ return "restored";
69
+ }
70
+
71
+ /**
72
+ * Capability negotiation. Returns `{status, reason}`; only an exact well-formed enable
73
+ * message with a valid token turns the reporter on.
74
+ */
75
+ export function negotiateFrameWitness(message) {
76
+ if (message === null || typeof message !== "object") return { status: "ignored", reason: "not-an-object" };
77
+ if (message.type !== "frame_witness_enable") return { status: "ignored", reason: "not-enable" };
78
+ if (message.protocol !== FRAME_WITNESS_PROTOCOL) return { status: "unsupported", reason: "protocol" };
79
+ if (!isValidFrameWitnessToken(message.token)) return { status: "unsupported", reason: "token" };
80
+ return { status: "enabled", reason: "ok", token: message.token };
81
+ }
82
+
83
+ /**
84
+ * The reporter. All I/O is injected so unit tests can drive it with public-shaped
85
+ * doubles while the real extension passes the live `ctx.ui` and reporters socket.
86
+ */
87
+ export class AttachFrameReporter {
88
+ #ui;
89
+ #send;
90
+ #mode;
91
+ #rendererEpoch;
92
+ #sessionEpoch;
93
+ #now;
94
+ #state = "idle"; // idle | announced | enabled | unsupported | failed | disposed
95
+ #token = null;
96
+ #frameIdCounter = { value: 0 };
97
+ #evaluator;
98
+ #terminal = null;
99
+ #terminalWrite = null;
100
+ #shadows = [];
101
+ #sentinelTui = null;
102
+ #focusApi = "unknown";
103
+ #renderPasses = 0;
104
+ #markerCount = 0;
105
+ #markerFailure = null;
106
+ #unknown = [];
107
+ #inMarker = false;
108
+ #lastMetadata = null;
109
+ #suspensions = 0;
110
+ #latestFact = null;
111
+ #superseding = false;
112
+ #instanceId = null;
113
+ #intentRequestId = null;
114
+ #geometryRevision = -1;
115
+ #intentsRejected = 0;
116
+ #intentsApplied = 0;
117
+ #seenRequestIds = new Set();
118
+ #consumedRequestIds = new Set();
119
+ #intentId = 0;
120
+ #writtenFrames = new Set(); // frameId where S was successfully written to underlying terminal
121
+ #onUnavailable = () => {};
122
+ #failCapabilityCalled = false;
123
+ #stashedEvaluator = null; // old evaluator with deferred decisions, drained after #attachTerminal
124
+
125
+ constructor({ ui, send = (_message) => {}, mode = "fullscreen", rendererEpoch = 1, sessionEpoch = 0, now = () => Date.now(), onUnavailable = () => {} }) {
126
+ if (!ui || typeof ui.setWidget !== "function") throw new Error("AttachFrameReporter requires ctx.ui.setWidget");
127
+ if (!MODES.has(mode)) throw new Error(`unknown renderer mode: ${mode}`);
128
+ this.#ui = ui;
129
+ this.#send = send;
130
+ this.#mode = mode;
131
+ this.#rendererEpoch = rendererEpoch;
132
+ this.#sessionEpoch = sessionEpoch;
133
+ this.#now = now;
134
+ this.#onUnavailable = onUnavailable;
135
+ this.#evaluator = new FrameCandidateEvaluator({ mode, rendererEpoch, sessionEpoch, frameIdCounter: this.#frameIdCounter });
136
+ }
137
+
138
+ get state() {
139
+ return this.#state;
140
+ }
141
+
142
+ get capabilityEnabled() {
143
+ return this.#state === "enabled";
144
+ }
145
+
146
+ get markerCount() {
147
+ return this.#markerCount;
148
+ }
149
+
150
+ get markerFailure() {
151
+ return this.#markerFailure;
152
+ }
153
+
154
+ get instanceId() {
155
+ return this.#instanceId;
156
+ }
157
+
158
+ get geometryRevision() {
159
+ return this.#geometryRevision;
160
+ }
161
+
162
+ get intentStats() {
163
+ return {
164
+ applied: this.#intentsApplied,
165
+ rejected: this.#intentsRejected,
166
+ geometryRevision: this.#geometryRevision,
167
+ requestId: this.#intentRequestId,
168
+ intentId: this.#intentId,
169
+ consumedRequestIds: [...this.#consumedRequestIds],
170
+ };
171
+ }
172
+
173
+ /**
174
+ * First matching complete F consumes the current intent: later frames with the same
175
+ * nonce may update the view but never consume it again (and duplicate requestIds stay
176
+ * rejected). Applied is never completion.
177
+ */
178
+ consumeIntentOnce() {
179
+ if (this.#intentRequestId === null || this.#consumedRequestIds.has(this.#intentRequestId)) return false;
180
+ this.#consumedRequestIds.add(this.#intentRequestId);
181
+ return true;
182
+ }
183
+
184
+ get unknown() {
185
+ return this.#unknown.slice();
186
+ }
187
+
188
+ get decisions() {
189
+ return this.#evaluator.decisions;
190
+ }
191
+
192
+ get frameIdCounter() {
193
+ return this.#frameIdCounter;
194
+ }
195
+
196
+ get installedKeys() {
197
+ return this.#shadows.map((entry) => entry.key);
198
+ }
199
+
200
+ /** Renderer-stops observed (a mode switch suspends and then re-arms the adapter). */
201
+ get suspensions() {
202
+ return this.#suspensions;
203
+ }
204
+
205
+ /** Resident-socket greeting. Sent once; never retried automatically. */
206
+ announce() {
207
+ if (this.#state !== "idle") return this.#state;
208
+ this.#state = "announced";
209
+ this.#send({
210
+ type: "hello",
211
+ clientId: FRAME_REPORTER_CLIENT_ID,
212
+ frameWitness: { protocol: FRAME_WITNESS_PROTOCOL, sessionEpoch: this.#sessionEpoch },
213
+ });
214
+ return this.#state;
215
+ }
216
+
217
+ /**
218
+ * Handle one reporter message. Disabled/old runners leave the adapter in
219
+ * `unsupported` with NO widget, NO wrappers and NO markers.
220
+ */
221
+ handleMessage(message) {
222
+ const negotiation = negotiateFrameWitness(message);
223
+ if (negotiation.status !== "enabled") {
224
+ if (this.#state !== "enabled") this.#state = negotiation.status === "unsupported" ? "unsupported" : this.#state;
225
+ return negotiation;
226
+ }
227
+ // P2: the enable must carry the reporter's ACTUAL session epoch; a missing,
228
+ // invalid or mismatched epoch is unsupported rather than silently accepted.
229
+ const epoch = message.sessionEpoch;
230
+ if (!Number.isInteger(epoch) || epoch < 0 || epoch !== this.#sessionEpoch) {
231
+ if (this.#state !== "enabled") this.#state = "unsupported";
232
+ return { status: "unsupported", reason: "sessionEpoch" };
233
+ }
234
+ this.#token = negotiation.token;
235
+ if (typeof message.instanceId === "string" && message.instanceId.length > 0) this.#instanceId = message.instanceId;
236
+ this.#state = "enabled";
237
+ return negotiation;
238
+ }
239
+
240
+ /** Register the belowEditor sentinel; the terminal is attached from its TuiRef. */
241
+ install() {
242
+ if (this.#state !== "enabled") return false;
243
+ if (this.#sentinelTui !== null) return false;
244
+ // Re-registration disposes the previous component synchronously; mark that window
245
+ // so a superseded sentinel does not tear the whole reporter down.
246
+ this.#superseding = true;
247
+ try {
248
+ this.#ui.setWidget(ATTACH_FRAME_WIDGET_KEY, (tui) => this.#createSentinel(tui), { placement: "belowEditor" });
249
+ } finally {
250
+ this.#superseding = false;
251
+ }
252
+ return this.#terminal !== null;
253
+ }
254
+
255
+ /**
256
+ * Runner frame-witness intent (FW-04). Validated strictly: a wrong instance, a
257
+ * non-string requestId, a non-monotonic geometryRevision or non-positive dims are
258
+ * rejected without touching the renderer. A valid intent is stored and a NORMAL
259
+ * public `tui.requestRender()` is requested — never a private doRender, force reset
260
+ * or extra resize. `applied` from the runner is NOT completion; only the complete
261
+ * target-geometry frame can prove.
262
+ */
263
+ applyIntent(message) {
264
+ if (this.#state !== "enabled") return { ok: false, reason: "capability-off" };
265
+ if (message === null || typeof message !== "object" || message.type !== "frame_witness_intent") return { ok: false, reason: "not-intent" };
266
+ if (this.#instanceId !== null && message.instanceId !== this.#instanceId) {
267
+ this.#intentsRejected += 1;
268
+ return { ok: false, reason: "instance" };
269
+ }
270
+ if (typeof message.requestId !== "string" || message.requestId.length === 0) {
271
+ this.#intentsRejected += 1;
272
+ return { ok: false, reason: "requestId" };
273
+ }
274
+ if (this.#seenRequestIds.has(message.requestId)) {
275
+ this.#intentsRejected += 1;
276
+ return { ok: false, reason: "duplicate-requestId" };
277
+ }
278
+ const match = /^fw-(\d+)$/.exec(message.requestId);
279
+ if (match === null || Number(match[1]) < 1) {
280
+ this.#intentsRejected += 1;
281
+ return { ok: false, reason: "requestId-format" };
282
+ }
283
+ if (!Number.isInteger(message.geometryRevision) || message.geometryRevision <= this.#geometryRevision) {
284
+ this.#intentsRejected += 1;
285
+ return { ok: false, reason: "geometryRevision" };
286
+ }
287
+ if (!Number.isInteger(message.cols) || message.cols < 1 || !Number.isInteger(message.rows) || message.rows < 1) {
288
+ this.#intentsRejected += 1;
289
+ return { ok: false, reason: "dims" };
290
+ }
291
+ this.#geometryRevision = message.geometryRevision;
292
+ this.#intentRequestId = message.requestId;
293
+ this.#intentId = Number(match[1]);
294
+ this.#seenRequestIds.add(message.requestId);
295
+ this.#intentsApplied += 1;
296
+ this.#evaluator.setIntent({ intentId: this.#intentId, geometryRevision: message.geometryRevision, cols: message.cols, rows: message.rows });
297
+ // Drain any abort decisions from setIntent (intent-superseded/intent-invalid)
298
+ this.#drainTerminalDecisions();
299
+ const requested = this.#requestRender();
300
+ return { ok: true, requested, geometryRevision: this.#geometryRevision };
301
+ }
302
+
303
+ #requestRender() {
304
+ const tui = this.#sentinelTui;
305
+ if (tui !== null && typeof tui.requestRender === "function") {
306
+ try {
307
+ tui.requestRender();
308
+ return true;
309
+ } catch {
310
+ return false;
311
+ }
312
+ }
313
+ return false;
314
+ }
315
+
316
+ /** Renderer mode change: carry the frameId counter, rebind the grammar.
317
+ * The old evaluator's deferred decisions are drained immediately if the terminal
318
+ * is already bound; otherwise stashed for #createSentinel to drain after attach. */
319
+ setMode(mode, { rendererEpoch = this.#rendererEpoch + 1 } = {}) {
320
+ if (!MODES.has(mode)) throw new Error(`unknown renderer mode: ${mode}`);
321
+ // Capture the old evaluator so its deferred decisions can be drained after
322
+ // the new one is installed and the terminal is re-bound.
323
+ const oldEvaluator = this.#evaluator;
324
+ oldEvaluator.abandonPendingEscape();
325
+ oldEvaluator.abort("mode-changed");
326
+ this.#mode = mode;
327
+ this.#rendererEpoch = rendererEpoch;
328
+ this.#evaluator = new FrameCandidateEvaluator({
329
+ mode,
330
+ rendererEpoch,
331
+ sessionEpoch: this.#sessionEpoch,
332
+ frameIdCounter: this.#frameIdCounter,
333
+ });
334
+ this.#sentinelTui = null;
335
+ this.#focusApi = "unknown";
336
+ // Drain immediately if terminal is bound; otherwise stash for later
337
+ if (this.#terminalWrite !== null) {
338
+ this.#drainTerminalDecisions(oldEvaluator);
339
+ } else {
340
+ this.#stashedEvaluator = oldEvaluator;
341
+ }
342
+ return [];
343
+ }
344
+
345
+ /** Session-scoped teardown: stop proving and restore every own shadow. */
346
+ dispose(reason = "dispose") {
347
+ this.#evaluator.stop();
348
+ // Drain stop decisions BEFORE flipping state to disposed (otherwise #emitA's enabled guard swallows them)
349
+ this.#drainTerminalDecisions();
350
+ const restores = this.#restoreShadows(reason);
351
+ this.#state = "disposed";
352
+ return { restores };
353
+ }
354
+
355
+ #createSentinel(tui) {
356
+ // F6: the renderer mode comes from the ACTUAL public `tui.mode`, never a hardcoded
357
+ // default. A mode change rebinds the grammar (carried frameId, same terminal); an
358
+ // unavailable/unknown mode is `unsupported`, not a fabricated value.
359
+ const observedMode = typeof tui?.mode === "string" ? tui.mode : null;
360
+ if (observedMode === null || !MODES.has(observedMode)) {
361
+ this.#unknown.push({ what: "mode", reason: "public tui.mode is unavailable or unknown; mode evidence unsupported" });
362
+ this.#state = "unsupported";
363
+ this.#sentinelTui = tui;
364
+ return { render: () => [], dispose: () => {} };
365
+ }
366
+ if (observedMode !== this.#mode) this.setMode(observedMode);
367
+ this.#sentinelTui = tui;
368
+ const maybe = tui?.getFocusedComponent;
369
+ this.#focusApi = typeof maybe === "function" ? "present" : "absent";
370
+ if (this.#focusApi === "absent") {
371
+ this.#unknown.push({ what: "focus", reason: "public TUI instance has no getFocusedComponent; focus evidence unsupported" });
372
+ if (this.#state === "enabled") this.#state = "unsupported";
373
+ }
374
+ this.#attachTerminal(tui);
375
+ // Drain any stashed old evaluator's deferred decisions AFTER the terminal is bound
376
+ if (this.#stashedEvaluator !== null) {
377
+ this.#stashedEvaluator.abandonPendingEscape();
378
+ this.#drainTerminalDecisions(this.#stashedEvaluator);
379
+ this.#stashedEvaluator = null;
380
+ }
381
+ return {
382
+ render: () => {
383
+ this.#renderPasses += 1;
384
+ if (this.#state !== "enabled") return [];
385
+ // Host 1.4.0 `switchTuiMode()` REUSES the existing widget component and never
386
+ // calls the factory again. A renderer stop suspends the binding, so the SAME
387
+ // component's next render is where the adapter must re-arm — no install() or
388
+ // setWidget() refresh, no test-only path.
389
+ if (this.#sentinelTui === null) this.#reactivate(tui);
390
+ if (this.#sentinelTui !== tui) return [];
391
+ const focus = this.#focusApi === "present" ? tui.getFocusedComponent?.() : undefined;
392
+ const overlayPresent = typeof tui?.hasOverlay === "function" ? Boolean(tui.hasOverlay()) : false;
393
+ this.#latestFact = { focusPresent: focus !== null && focus !== undefined, focusIdentity: focus, mode: this.#mode, overlayPresent };
394
+ this.#evaluator.sentinel(this.#latestFact);
395
+ return [];
396
+ },
397
+ dispose: () => {
398
+ if (this.#state !== "enabled") return;
399
+ // A disposed sentinel always aborts the open candidate. Only a REAL teardown
400
+ // (not the disposal that a re-registration triggers synchronously) stops
401
+ // proving and restores the wrappers.
402
+ this.#evaluator.abort("sentinel-dispose");
403
+ // Drain abort decisions before restoring shadows
404
+ this.#drainTerminalDecisions();
405
+ if (this.#superseding) return;
406
+ this.#restoreShadows("sentinel-dispose");
407
+ this.#terminal = null;
408
+ this.#terminalWrite = null;
409
+ this.#sentinelTui = null;
410
+ this.#state = "disposed";
411
+ },
412
+ };
413
+ }
414
+
415
+ /**
416
+ * Post-stop reactivation from the EXISTING sentinel component: rebind from the actual
417
+ * current public `tui.mode`, advance rendererEpoch EXACTLY once (same-mode stop/start
418
+ * included), rebuild the grammar on the carried frameId counter and reinstall the own
419
+ * shadows on the same shared terminal. Never used by disposed/unsupported/failed states.
420
+ */
421
+ #reactivate(tui) {
422
+ if (this.#state !== "enabled") return;
423
+ const observed = typeof tui?.mode === "string" ? tui.mode : null;
424
+ if (observed === null || !MODES.has(observed)) {
425
+ this.#unknown.push({ what: "mode", reason: "public tui.mode unavailable on reactivation" });
426
+ this.#state = "unsupported";
427
+ return;
428
+ }
429
+ // Capture the old evaluator before replacing it (may be a stashed one from stop)
430
+ const oldEvaluator = this.#stashedEvaluator ?? this.#evaluator;
431
+ this.#stashedEvaluator = null;
432
+ this.#rendererEpoch += 1;
433
+ this.#mode = observed;
434
+ this.#evaluator = new FrameCandidateEvaluator({
435
+ mode: observed,
436
+ rendererEpoch: this.#rendererEpoch,
437
+ sessionEpoch: this.#sessionEpoch,
438
+ frameIdCounter: this.#frameIdCounter,
439
+ });
440
+ this.#sentinelTui = tui;
441
+ this.#attachTerminal(tui);
442
+ // Drain the OLD evaluator's deferred decisions AFTER re-binding the terminal.
443
+ // Abandon any pending cross-write escape first so deferred decisions are not lost.
444
+ oldEvaluator.abandonPendingEscape();
445
+ this.#drainTerminalDecisions(oldEvaluator);
446
+ }
447
+
448
+ #attachTerminal(tui) {
449
+ if (this.#terminal !== null) {
450
+ // Re-registration after a mode switch must keep the SAME shared terminal.
451
+ const same = tui?.terminal === this.#terminal;
452
+ if (!same) this.#unknown.push({ what: "terminal", reason: "re-registration reported a different terminal instance" });
453
+ return;
454
+ }
455
+ const terminal = tui?.terminal;
456
+ if (terminal === undefined || terminal === null) {
457
+ this.#unknown.push({ what: "terminal", reason: "public TUI instance does not expose the shared terminal" });
458
+ if (this.#state === "enabled") this.#state = "unsupported";
459
+ return;
460
+ }
461
+ this.#terminal = terminal;
462
+ const proto = Object.getPrototypeOf(terminal);
463
+ // The raw, pre-shadow write is how markers reach the same ordered stream.
464
+ const protoWrite = proto === null ? undefined : protoDescriptorOf(terminal, "write")?.value;
465
+ this.#terminalWrite = typeof protoWrite === "function" ? protoWrite : null;
466
+ for (const key of ["columns", "rows"]) {
467
+ const descriptor = protoDescriptorOf(terminal, key);
468
+ const ownBefore = ownDescriptor(terminal, key);
469
+ if (ownBefore !== undefined && typeof ownBefore.get !== "function") {
470
+ // A pre-existing data property on the instance cannot be shadowed faithfully
471
+ // without erasing it on restore; refuse instead.
472
+ this.#unknown.push({ what: "shadow", reason: `pre-existing own data property ${key}` });
473
+ continue;
474
+ }
475
+ const getter = () => {
476
+ const value = ownBefore !== undefined ? ownBefore.get.call(terminal) : typeof descriptor?.get === "function" ? descriptor.get.call(terminal) : undefined;
477
+ this.#evaluator.sizeRead(key, value);
478
+ // Drain any abort decisions from sizeRead (resampled)
479
+ this.#drainTerminalDecisions();
480
+ return value;
481
+ };
482
+ try {
483
+ Object.defineProperty(terminal, key, { configurable: true, enumerable: ownBefore?.enumerable ?? false, get: getter });
484
+ this.#shadows.push({ key, installed: getter, ownBefore });
485
+ } catch {
486
+ this.#unknown.push({ what: "shadow", reason: `cannot shadow ${key}` });
487
+ }
488
+ }
489
+ for (const key of ["write", "hideCursor", "showCursor"]) {
490
+ const ownBefore = ownDescriptor(terminal, key);
491
+ const original = typeof ownBefore?.value === "function" ? ownBefore.value : protoDescriptorOf(terminal, key)?.value;
492
+ if (typeof original !== "function") continue;
493
+ const wrapper = (...args) => {
494
+ const text = typeof args[0] === "string" ? args[0] : "";
495
+ if (this.#state !== "enabled") return original.apply(terminal, args);
496
+ const { insertions } = this.#proveOnOperation(key, text);
497
+ let failed = false;
498
+ try {
499
+ if (insertions.length === 0) return original.apply(terminal, args);
500
+ // Split the write exactly at this frame's OPEN token: the prefix is written
501
+ // first, then S, then the remainder — so S never precedes a previous
502
+ // frame's CLOSE that shares the write. Only the LAST ordinary slice
503
+ // receives xterm's completion argument; intermediate slices take none.
504
+ const slices = [];
505
+ let sliceCursor = 0;
506
+ for (const insertion of insertions) {
507
+ if (insertion.offset > sliceCursor) {
508
+ slices.push(text.slice(sliceCursor, insertion.offset));
509
+ sliceCursor = insertion.offset;
510
+ }
511
+ }
512
+ if (sliceCursor < text.length) slices.push(text.slice(sliceCursor));
513
+ let sliceIndex = 0;
514
+ const writeSlice = (slice) => {
515
+ sliceIndex += 1;
516
+ return original.call(terminal, slice, ...(sliceIndex === slices.length ? args.slice(1) : []));
517
+ };
518
+ let cursor = 0;
519
+ let lastResult;
520
+ for (const insertion of insertions) {
521
+ if (insertion.offset > cursor) lastResult = writeSlice(text.slice(cursor, insertion.offset));
522
+ this.#emitS(insertion);
523
+ cursor = insertion.offset;
524
+ }
525
+ if (cursor < text.length) lastResult = writeSlice(text.slice(cursor));
526
+ return lastResult;
527
+ } catch (error) {
528
+ // A failed original write means the frame bytes were not delivered: abort
529
+ // instead of claiming completion (S, if any, must be closed by A), then
530
+ // rethrow the ORIGINAL error unchanged.
531
+ failed = true;
532
+ // Mark any unemitted S decisions as emitted before aborting:
533
+ // the S insertion point has passed and the S was never written, so the
534
+ // drain must not throw on them. Use the non-consuming decisions getter
535
+ // to avoid dropping deferred F/A decisions from earlier writes.
536
+ for (const decision of this.#evaluator.decisions) {
537
+ if (decision.kind === "S" && !decision.emitted) this.#evaluator.markEmitted(decision.seq);
538
+ }
539
+ this.#evaluator.abort("write-failed");
540
+ throw error;
541
+ } finally {
542
+ // NB: no `return` here — a return inside `finally` would swallow the
543
+ // original write error rethrown above.
544
+ if (!failed) {
545
+ // Completion rechecks the LATEST focus identity/mode/overlay before any F.
546
+ this.#evaluator.finishWrite(this.#latestFact);
547
+ // F/A decisions are now in the evaluator; drain them below.
548
+ }
549
+ // Drain all pending F/A decisions (including write-failed aborts).
550
+ this.#drainTerminalDecisions();
551
+ }
552
+ };
553
+ try {
554
+ Object.defineProperty(terminal, key, { configurable: true, enumerable: false, value: wrapper, writable: true });
555
+ this.#shadows.push({ key, installed: wrapper, ownBefore });
556
+ } catch {
557
+ this.#unknown.push({ what: "shadow", reason: `cannot shadow ${key}` });
558
+ }
559
+ }
560
+ for (const key of ["start", "stop"]) {
561
+ const original = protoDescriptorOf(terminal, key)?.value;
562
+ if (typeof original !== "function") continue;
563
+ const ownBefore = ownDescriptor(terminal, key);
564
+ const wrapper = (...args) => {
565
+ if (this.#state === "enabled") {
566
+ this.#evaluator.abort(`terminal-${key}`);
567
+ // If a cross-write escape is pending, the abort decision is deferred.
568
+ // Stash the evaluator so reactivation can drain it after re-binding.
569
+ if (this.#evaluator.pendingEscape) {
570
+ this.#stashedEvaluator = this.#evaluator;
571
+ }
572
+ // Drain abort decisions before restoring shadows (may be deferred by pendingEscape)
573
+ this.#drainTerminalDecisions();
574
+ if (key === "stop") {
575
+ // A renderer stop (mode switch / teardown) aborts the candidate and
576
+ // detaches the adapter, but the capability stays armed: the next
577
+ // registration on the new renderer re-installs on the SAME terminal.
578
+ this.#restoreShadows("terminal-stop");
579
+ this.#terminal = null;
580
+ this.#terminalWrite = null;
581
+ this.#sentinelTui = null;
582
+ this.#suspensions += 1;
583
+ }
584
+ }
585
+ const result = original.apply(terminal, args);
586
+ // Epoch advances only AFTER a successful start (a throw preserves both the
587
+ // old epoch and the original exception).
588
+ if (key === "start" && this.#state === "enabled") {
589
+ this.#rendererEpoch += 1;
590
+ this.#evaluator.setEpoch({ rendererEpoch: this.#rendererEpoch });
591
+ }
592
+ return result;
593
+ };
594
+ try {
595
+ Object.defineProperty(terminal, key, { configurable: true, enumerable: false, value: wrapper, writable: true });
596
+ this.#shadows.push({ key, installed: wrapper, ownBefore });
597
+ } catch {
598
+ this.#unknown.push({ what: "shadow", reason: `cannot shadow ${key}` });
599
+ }
600
+ }
601
+ }
602
+
603
+ #restoreShadows(reason) {
604
+ const restores = [];
605
+ for (const entry of this.#shadows) {
606
+ if (this.#terminal === null) break;
607
+ restores.push({ key: entry.key, result: restoreOwnShadow(this.#terminal, entry), restoredOwnBefore: entry.ownBefore !== undefined });
608
+ }
609
+ if (restores.length > 0) this.#shadows = [];
610
+ this.#lastMetadata = this.#lastMetadata === null ? null : { ...this.#lastMetadata, restoreReason: reason };
611
+ return restores;
612
+ }
613
+
614
+ #proveOnOperation(kind, text) {
615
+ const { insertions } = this.#evaluator.op({ kind, text });
616
+ return { insertions };
617
+ }
618
+
619
+ #writeMarker(text) {
620
+ if (this.#inMarker) {
621
+ this.#failCapability("marker-recursion");
622
+ return false;
623
+ }
624
+ if (this.#state !== "enabled") return false;
625
+ if (Buffer.byteLength(text, "utf8") > MAX_FRAME_MARKER_BYTES) {
626
+ this.#failCapability("marker-oversize");
627
+ return false;
628
+ }
629
+ if (this.#terminalWrite === null || this.#terminal === null) {
630
+ this.#failCapability("marker-no-raw-write");
631
+ return false;
632
+ }
633
+ this.#inMarker = true;
634
+ try {
635
+ // Raw, pre-shadow reference: never re-enters candidate accounting.
636
+ this.#terminalWrite.call(this.#terminal, text);
637
+ this.#markerCount += 1;
638
+ return true;
639
+ } catch (error) {
640
+ this.#failCapability(`marker-write-failed:${error instanceof Error ? error.message : String(error)}`);
641
+ return false;
642
+ } finally {
643
+ this.#inMarker = false;
644
+ }
645
+ }
646
+
647
+ #emitS(insertion) {
648
+ if (this.#token === null) return;
649
+ const frameId = insertion.frameId;
650
+ const decision = this.#evaluator.decisions.filter((entry) => entry.kind === "S" && entry.frameId === frameId).at(-1) ?? null;
651
+ try {
652
+ const success = this.#writeMarker(encodeFrameMarkerS({ token: this.#token, frameId, intentId: decision?.intentId ?? 0, sampledCols: decision?.cols }));
653
+ if (success) {
654
+ this.#writtenFrames.add(frameId);
655
+ // FIFO eviction to keep the set bounded (align with runner MAX_FINISHED_FRAME_IDS=4096)
656
+ if (this.#writtenFrames.size > 4096) {
657
+ const oldest = this.#writtenFrames.values().next().value;
658
+ this.#writtenFrames.delete(oldest);
659
+ }
660
+ }
661
+ } catch (error) {
662
+ this.#failCapability(`marker-encode-failed:${error instanceof Error ? error.message : String(error)}`);
663
+ } finally {
664
+ // Mark as emitted regardless of success: S can only be emitted at this write boundary.
665
+ // If write failed, the candidate will be aborted and A will be sent via drain.
666
+ if (decision?.seq !== undefined) this.#evaluator.markEmitted(decision.seq);
667
+ }
668
+ }
669
+
670
+ #emitF(decision) {
671
+ // Never write an F as if the frame completed once the capability failed.
672
+ if (this.#token === null || this.#state !== "enabled") return;
673
+ const frameId = decision.frameId;
674
+ const metadata = this.#evaluator.metadataFor(decision);
675
+ this.#lastMetadata = metadata;
676
+ try {
677
+ if (this.#writeMarker(encodeFrameMarkerF({ token: this.#token, frameId, metadata }))) {
678
+ // P2: consume only after the first matching F was actually written; later
679
+ // frames fall back to the ordinary intent 0 so they cannot masquerade as the
680
+ // completing frame. A failed write never consumes.
681
+ if (this.consumeIntentOnce()) this.#evaluator.setIntent(null);
682
+ }
683
+ } catch (error) {
684
+ this.#failCapability(`marker-encode-failed:${error instanceof Error ? error.message : String(error)}`);
685
+ }
686
+ }
687
+
688
+ #emitA(frameId, reason) {
689
+ if (this.#token === null || this.#state !== "enabled") return;
690
+ try {
691
+ this.#writeMarker(encodeFrameMarkerA({ token: this.#token, frameId, reason }));
692
+ } catch (error) {
693
+ this.#failCapability(`marker-encode-failed:${error instanceof Error ? error.message : String(error)}`);
694
+ }
695
+ }
696
+
697
+ /** Marker failure => capability OFF + UNKNOWN; original output keeps flowing. */
698
+ #failCapability(reason) {
699
+ if (this.#markerFailure === null) this.#markerFailure = { at: this.#now(), reason };
700
+ this.#unknown.push({ what: "marker", reason });
701
+ this.#state = "failed";
702
+ if (!this.#failCapabilityCalled) {
703
+ this.#failCapabilityCalled = true;
704
+ this.#onUnavailable(reason);
705
+ }
706
+ }
707
+
708
+ /** Drain pending F/A decisions from the given evaluator (defaults to current).
709
+ * S is emitted inline in the write wrapper and marked emitted immediately;
710
+ * F/A are only emitted here. Skips emission if a cross-write escape is pending
711
+ * or the terminal is not bound (deferred until #attachTerminal completes).
712
+ * Call abandonPendingEscape() first when replacing the evaluator to force-drain. */
713
+ #drainTerminalDecisions(evaluator = this.#evaluator) {
714
+ if (evaluator.pendingEscape) {
715
+ // A cross-write control sequence is unclosed; defer F/A emission to avoid
716
+ // inserting a marker mid-sequence (which would corrupt the stream).
717
+ return;
718
+ }
719
+ if (this.#terminalWrite === null) {
720
+ // Terminal is detached (e.g. after terminal-stop). Defer emission until
721
+ // #attachTerminal re-binds the raw write.
722
+ return;
723
+ }
724
+ const decisions = evaluator.collectTerminalDecisions();
725
+ for (const decision of decisions) {
726
+ if (decision.kind === "S") {
727
+ throw new Error("S decision in drain: programming error");
728
+ } else if (decision.kind === "F") {
729
+ this.#emitF(decision);
730
+ } else if (decision.kind === "A") {
731
+ if (this.#writtenFrames.has(decision.frameId)) {
732
+ this.#emitA(decision.frameId, decision.reason);
733
+ }
734
+ }
735
+ }
736
+ }
737
+ }
738
+