@zhuxixi/pi-agent-board 0.13.0 → 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 (91) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +37 -12
  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-26-issue-245-key-hints-doc-sync.md +244 -0
  6. package/docs/superpowers/plans/2026-10-27-issue-172-fullscreen-selection-clear.md +344 -0
  7. package/docs/superpowers/plans/2026-10-27-issue-252-select-key-hints.md +209 -0
  8. package/docs/superpowers/plans/2026-10-28-issue-255-coordinator-endpoint-zombie.md +442 -0
  9. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  10. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  11. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  12. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  13. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  14. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  15. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  16. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  17. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  18. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  19. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  20. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  21. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  22. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  23. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  24. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  25. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  26. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  27. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  28. package/docs/superpowers/specs/2026-10-26-issue-245-key-hints-doc-sync-design.md +72 -0
  29. package/docs/superpowers/specs/2026-10-27-issue-172-fullscreen-selection-clear-design.md +248 -0
  30. package/docs/superpowers/specs/2026-10-27-issue-252-select-key-hints-design.md +95 -0
  31. package/docs/superpowers/specs/2026-10-28-issue-255-coordinator-endpoint-zombie-design.md +380 -0
  32. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  33. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  34. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  35. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  36. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  37. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  38. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  39. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  40. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  41. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  42. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  43. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  44. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  45. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  46. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  47. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  48. package/package.json +1 -1
  49. package/runner/pty-runner.mjs +526 -63
  50. package/runner/state-coordinator.mjs +62 -5
  51. package/runner/title-runner.mjs +33 -24
  52. package/src/commands/agent-board.ts +5 -1
  53. package/src/core/attach-detach.mjs +27 -0
  54. package/src/core/attach-frame-proof.mjs +897 -0
  55. package/src/core/attach-frame-reporter.mjs +738 -0
  56. package/src/core/attach-frame-stream.mjs +266 -0
  57. package/src/core/attach-pr-label.mjs +12 -0
  58. package/src/core/attach-recovery.mjs +239 -0
  59. package/src/core/attach-screen-owner.mjs +55 -0
  60. package/src/core/attach-view-proof.mjs +709 -0
  61. package/src/core/auto-state.mjs +6 -1
  62. package/src/core/cwd-stats.mjs +3 -1
  63. package/src/core/dashboard-prefs.mjs +31 -0
  64. package/src/core/derive.mjs +8 -1
  65. package/src/core/events.mjs +127 -1
  66. package/src/core/foreground-projection-cache.mjs +1 -0
  67. package/src/core/frame-witness-update.mjs +35 -0
  68. package/src/core/fullscreen-selection.mjs +60 -0
  69. package/src/core/host-coordination.mjs +48 -0
  70. package/src/core/host-protocol.mjs +13 -2
  71. package/src/core/hosted-frame-witness.mjs +60 -0
  72. package/src/core/paths.mjs +10 -3
  73. package/src/core/pty-attach-render.mjs +239 -0
  74. package/src/core/pty-kitty-images.mjs +237 -0
  75. package/src/core/pty-scroll.mjs +8 -8
  76. package/src/core/rows.mjs +43 -7
  77. package/src/core/session-entries.mjs +82 -0
  78. package/src/core/session-launch-prefs.mjs +45 -0
  79. package/src/core/session-view.mjs +3 -63
  80. package/src/core/store.mjs +1 -0
  81. package/src/core/terminal-attach-client.mjs +199 -20
  82. package/src/core/terminal-attach-protocol.mjs +221 -7
  83. package/src/core/terminal-model.mjs +24 -3
  84. package/src/core/terminal-snapshot.mjs +10 -0
  85. package/src/core/title-flow.mjs +66 -0
  86. package/src/core/title.mjs +101 -0
  87. package/src/core/types.mjs +17 -0
  88. package/src/index.ts +85 -0
  89. package/src/runtime/service.mjs +87 -18
  90. package/src/ui/dashboard.ts +206 -49
  91. package/src/ui/pty-attach.ts +1472 -99
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Shared session-JSONL structure primitives — the single source of branch
3
+ * semantics for everything agent-board reads out of a pi session file.
4
+ * Extracted verbatim from session-view.mjs (issue #286); display code and
5
+ * launch-prefs policy both consume these so they can never drift apart.
6
+ *
7
+ * The file is a tree: every entry has `id` + `parentId`; the active branch is
8
+ * the root→leaf path ending at the last entry (pi's SessionManager.getBranch
9
+ * picks the same leaf when no explicit leaf is recorded).
10
+ */
11
+
12
+ /**
13
+ * Parse raw JSONL text into a header plus a tree index.
14
+ * Malformed lines, non-objects, and id-less entries are skipped.
15
+ * @param {string} text
16
+ * @returns {{ header: { id: string, cwd: string } | null, entries: any[], byId: Map<string, any> }}
17
+ */
18
+ export function parseSessionEntries(text) {
19
+ /** @type {{ id: string, cwd: string } | null} */
20
+ let header = null;
21
+ /** @type {any[]} */
22
+ const entries = [];
23
+ /** @type {Map<string, any>} */
24
+ const byId = new Map();
25
+
26
+ for (const rawLine of String(text || "").split(/\r?\n/)) {
27
+ const line = rawLine.trim();
28
+ if (!line) continue;
29
+ let entry;
30
+ try {
31
+ entry = JSON.parse(line);
32
+ } catch {
33
+ continue;
34
+ }
35
+ if (entry?.type === "session") {
36
+ header = { id: String(entry.id || ""), cwd: String(entry.cwd || "") };
37
+ continue;
38
+ }
39
+ if (!entry || typeof entry !== "object" || typeof entry.id !== "string") continue;
40
+ entries.push(entry);
41
+ byId.set(entry.id, entry);
42
+ }
43
+
44
+ return { header, entries, byId };
45
+ }
46
+
47
+ /**
48
+ * Walk from the last entry to the root following parentId pointers.
49
+ * Root→leaf order. A broken parentId ends the walk; a seen-set guards cycles.
50
+ * @param {any[]} entries
51
+ * @param {Map<string, any>} byId
52
+ * @returns {any[]}
53
+ */
54
+ export function activeBranchEntries(entries, byId) {
55
+ if (!entries.length) return [];
56
+ /** @type {any[]} */
57
+ const out = [];
58
+ const seen = new Set();
59
+ let cur = entries[entries.length - 1];
60
+ while (cur && typeof cur.id === "string" && !seen.has(cur.id)) {
61
+ out.push(cur);
62
+ seen.add(cur.id);
63
+ cur = cur.parentId ? byId.get(cur.parentId) ?? null : null;
64
+ }
65
+ out.reverse();
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Convert Pi message/content blocks to plain text.
71
+ * @param {any} content
72
+ * @returns {string}
73
+ */
74
+ export function contentText(content) {
75
+ if (typeof content === "string") return content.trim();
76
+ if (!Array.isArray(content)) return "";
77
+ return content
78
+ .filter((b) => b && b.type === "text" && typeof b.text === "string")
79
+ .map((b) => b.text)
80
+ .join("\n")
81
+ .trim();
82
+ }
@@ -0,0 +1,45 @@
1
+ import { activeBranchEntries, parseSessionEntries } from "./session-entries.mjs";
2
+
3
+ /**
4
+ * Pure launch-prefs policy (issue #286): decide per dimension whether an
5
+ * explicit --model / --thinking flag must be passed when spawning a child pi,
6
+ * or whether the flag must be omitted so pi restores the session's own last
7
+ * selection (pi only restores a dimension when no explicit flag is given).
8
+ *
9
+ * Mirrors pi 1.5.0 createAgentSession's restore gates on the normal path:
10
+ * - model restores when the branch has >=1 message entry AND (a model_change
11
+ * entry OR an assistant message entry);
12
+ * - thinking restores (to the session's own value) only when the branch has a
13
+ * thinking_level_change entry (otherwise pi would restore the SETTINGS
14
+ * default, not the view's defaultThinking — keep passing the explicit flag).
15
+ * Pure policy: no fs, no clock. The caller owns reading the session file.
16
+ * @param {{ model: string|null, thinkingLevel: string|null }} defaults view launch defaults (meta.defaultModel/defaultThinking)
17
+ * @param {string|null} text raw session JSONL, or null when unreadable/missing
18
+ */
19
+ export function resolveLaunchModelPrefs(defaults, text) {
20
+ const model = defaults?.model ?? null;
21
+ const thinkingLevel = defaults?.thinkingLevel ?? null;
22
+ let droppedModel = false;
23
+ let droppedThinking = false;
24
+
25
+ if (text) {
26
+ const { entries, byId } = parseSessionEntries(text);
27
+ const branch = activeBranchEntries(entries, byId);
28
+ const hasMessage = branch.some((e) => e.type === "message");
29
+ if (hasMessage) {
30
+ const modelRestorable = branch.some(
31
+ (e) => e.type === "model_change" || (e.type === "message" && e.message?.role === "assistant"),
32
+ );
33
+ const thinkingRestorable = branch.some((e) => e.type === "thinking_level_change");
34
+ droppedModel = modelRestorable && model !== null;
35
+ droppedThinking = thinkingRestorable && thinkingLevel !== null;
36
+ }
37
+ }
38
+
39
+ return {
40
+ model: droppedModel ? null : model,
41
+ thinkingLevel: droppedThinking ? null : thinkingLevel,
42
+ droppedModel,
43
+ droppedThinking,
44
+ };
45
+ }
@@ -7,6 +7,7 @@
7
7
  * then render messages / visible custom messages / summaries on that branch.
8
8
  */
9
9
  import { existsSync, readFileSync } from "node:fs";
10
+ import { activeBranchEntries, contentText, parseSessionEntries } from "./session-entries.mjs";
10
11
 
11
12
  /**
12
13
  * @typedef {Object} SessionViewItem
@@ -51,59 +52,13 @@ export function loadSessionView(sessionFile) {
51
52
  * @returns {SessionViewData}
52
53
  */
53
54
  export function parseSessionText(text) {
54
- /** @type {{ id:string, cwd:string }|null} */
55
- let header = null;
56
- /** @type {any[]} */
57
- const entries = [];
58
- /** @type {Map<string, any>} */
59
- const byId = new Map();
60
-
61
- for (const rawLine of String(text || "").split(/\r?\n/)) {
62
- const line = rawLine.trim();
63
- if (!line) continue;
64
- let entry;
65
- try {
66
- entry = JSON.parse(line);
67
- } catch {
68
- continue;
69
- }
70
- if (entry?.type === "session") {
71
- header = { id: String(entry.id || ""), cwd: String(entry.cwd || "") };
72
- continue;
73
- }
74
- if (!entry || typeof entry !== "object" || typeof entry.id !== "string") continue;
75
- entries.push(entry);
76
- byId.set(entry.id, entry);
77
- }
78
-
55
+ const { header, entries, byId } = parseSessionEntries(text);
79
56
  if (entries.length === 0) return { header, items: [], error: null };
80
-
81
- const leaf = entries[entries.length - 1];
82
- const branch = activeBranch(leaf, byId);
57
+ const branch = activeBranchEntries(entries, byId);
83
58
  const items = branch.flatMap(displayItemsForEntry);
84
59
  return { header, items, error: null };
85
60
  }
86
61
 
87
- /**
88
- * Walk from `leaf` to root following parentId pointers.
89
- * @param {any} leaf
90
- * @param {Map<string, any>} byId
91
- * @returns {any[]}
92
- */
93
- function activeBranch(leaf, byId) {
94
- /** @type {any[]} */
95
- const out = [];
96
- const seen = new Set();
97
- let cur = leaf;
98
- while (cur && typeof cur.id === "string" && !seen.has(cur.id)) {
99
- out.push(cur);
100
- seen.add(cur.id);
101
- cur = cur.parentId ? byId.get(cur.parentId) ?? null : null;
102
- }
103
- out.reverse();
104
- return out;
105
- }
106
-
107
62
  /**
108
63
  * @param {any} entry
109
64
  * @returns {SessionViewItem[]}
@@ -157,18 +112,3 @@ function displayItemsForEntry(entry) {
157
112
  return [];
158
113
  }
159
114
  }
160
-
161
- /**
162
- * Convert Pi message/content blocks to plain text.
163
- * @param {any} content
164
- * @returns {string}
165
- */
166
- function contentText(content) {
167
- if (typeof content === "string") return content.trim();
168
- if (!Array.isArray(content)) return "";
169
- return content
170
- .filter((b) => b && b.type === "text" && typeof b.text === "string")
171
- .map((b) => b.text)
172
- .join("\n")
173
- .trim();
174
- }
@@ -510,6 +510,7 @@ export function createView(root, opts) {
510
510
  hasError: false,
511
511
  latestAssistantPreview: "",
512
512
  latestTool: null,
513
+ compaction: null,
513
514
  question: null,
514
515
  pendingQuestions: [],
515
516
  error: null,
@@ -90,6 +90,11 @@
90
90
  * terminals), or loading baseline for `empty`. Empty baselines carry no frame.
91
91
  * - `output` — live/replay chunk data (protocol-managed only), including gate
92
92
  * strays emitted during `reconciling`.
93
+ * - `viewProofRecord` — sanitized S/F/A view-proof record from live/catch-up/replay,
94
+ * in receive order. It is an independent fact, never readiness.
95
+ * - `viewProof` — sanitized current coverage from `view_proof_state` (replay end or
96
+ * reporter reset). Optional `snapshotReady.viewProof` is the snapshot_end coverage
97
+ * with begin/state fallback; both are independent of transport validation.
93
98
  * - `resubscribing` — the client sent a recovery subscribe itself. The plan
94
99
  * contract originally made resubscribe UI-actionable; it is internal now
95
100
  * (send is injected and socket-scoped) so the UI wiring stays minimal —
@@ -127,7 +132,12 @@
127
132
  * escape hatch and deterministic legacy-test switch.
128
133
  */
129
134
 
130
- import { TERMINAL_FRAME_VERSION } from "./terminal-attach-protocol.mjs";
135
+ import {
136
+ MAX_VIEW_PROOF_RECORDS,
137
+ TERMINAL_FRAME_VERSION,
138
+ VIEW_PROOF_PROTOCOL_VERSION,
139
+ sanitizeViewProofRecord,
140
+ } from "./terminal-attach-protocol.mjs";
131
141
  import { classifyCommandAck, encodeCommand, CONTROL_ERROR_CODES, TERMINAL_ERROR_CODES } from "./control-protocol.mjs";
132
142
 
133
143
  /**
@@ -136,8 +146,8 @@ import { classifyCommandAck, encodeCommand, CONTROL_ERROR_CODES, TERMINAL_ERROR_
136
146
 
137
147
  /**
138
148
  * @typedef {(
139
- * event: "mode" | "snapshotBegin" | "snapshotReady" | "output" | "resubscribing" | "protocolError" |
140
- * "cmdAck" | "reconciled" | "epochReset",
149
+ * event: "mode" | "snapshotBegin" | "snapshotReady" | "output" | "viewProof" | "viewProofRecord" |
150
+ * "resubscribing" | "protocolError" | "cmdAck" | "reconciled" | "epochReset",
141
151
  * payload?: any,
142
152
  * ) => void} AttachClientEmit
143
153
  */
@@ -156,6 +166,42 @@ const RESIZE_RETRY_DELAY_MS = 300;
156
166
  * }} AttachClientOptions
157
167
  */
158
168
 
169
+ const VIEW_PROOF_STATUSES = new Set(["covered", "unavailable", "unknown"]);
170
+
171
+ function unknownViewProof(reason) {
172
+ return { status: "unknown", reason, proof: null, throughSeq: null, cursorVisible: null };
173
+ }
174
+
175
+ /** Bounded coverage sanitizer: accepts only tracker-shaped fields and a valid F proof. */
176
+ export function sanitizeViewProofCoverage(value) {
177
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
178
+ if (!VIEW_PROOF_STATUSES.has(value.status)) return null;
179
+ if (value.reason !== null && value.reason !== undefined && typeof value.reason !== "string") return null;
180
+ if (value.throughSeq !== null && value.throughSeq !== undefined && (!Number.isInteger(value.throughSeq) || value.throughSeq < 0)) return null;
181
+ if (value.cursorVisible !== null && value.cursorVisible !== undefined && typeof value.cursorVisible !== "boolean") return null;
182
+ const status = value.status;
183
+ let proof = null;
184
+ if (value.proof !== null && value.proof !== undefined) {
185
+ proof = sanitizeViewProofRecord(value.proof);
186
+ if (proof === null || proof.marker !== "F") return null;
187
+ }
188
+ if (status === "covered" && (proof === null || !Number.isInteger(value.throughSeq))) return null;
189
+ if (status === "covered" && proof.seq > value.throughSeq) return null;
190
+ let previousComplete = null;
191
+ if (value.previousComplete !== null && value.previousComplete !== undefined) {
192
+ previousComplete = sanitizeViewProofRecord(value.previousComplete);
193
+ if (previousComplete === null || previousComplete.marker !== "F") return null;
194
+ }
195
+ return {
196
+ status,
197
+ reason: typeof value.reason === "string" ? value.reason : null,
198
+ proof,
199
+ throughSeq: Number.isInteger(value.throughSeq) ? value.throughSeq : null,
200
+ cursorVisible: typeof value.cursorVisible === "boolean" ? value.cursorVisible : null,
201
+ ...(previousComplete === null ? {} : { previousComplete }),
202
+ };
203
+ }
204
+
159
205
  /** @type {NonNullable<AttachClientOptions["scheduleTimeout"]>} */
160
206
  const defaultScheduleTimeout = (delayMs, fn) => {
161
207
  const t = setTimeout(fn, delayMs);
@@ -238,14 +284,33 @@ export function createTerminalAttachClient({
238
284
  // catch-up flush outputs, then end — one microtask batch, tiny by contract
239
285
  // (ring pressure during capture yields resnapshot_required, not an
240
286
  // unbounded flush). Buffered here so the UI applies frame-then-flush in
241
- // exact order after snapshotReady.
242
- /** @type {{ frame: string | null, empty: boolean, resnapshot: boolean, beginSeq: number, flush: { seq: number, data: string }[] }} */
243
- let partial = { frame: null, empty: false, resnapshot: false, beginSeq: 0, flush: [] };
287
+ // exact order after snapshotReady. View-proof facts are bounded and cleared
288
+ // with every new capture/resync.
289
+ const emptyPartial = () => ({
290
+ frame: null,
291
+ empty: false,
292
+ resnapshot: false,
293
+ beginSeq: 0,
294
+ flush: [],
295
+ viewProofBegin: null,
296
+ viewProofState: null,
297
+ viewProofRecords: [],
298
+ viewProofRecordsDropped: false,
299
+ });
300
+ /** @type {ReturnType<typeof emptyPartial>} */
301
+ let partial = emptyPartial();
244
302
 
245
303
  const send = (msg) => {
246
304
  rawSend(msg);
247
305
  };
248
306
 
307
+ const subscribeMessage = (extra = {}) => ({
308
+ type: "subscribe_terminal",
309
+ frameVersion: TERMINAL_FRAME_VERSION,
310
+ viewProof: VIEW_PROOF_PROTOCOL_VERSION,
311
+ ...extra,
312
+ });
313
+
249
314
  const fireProbeTimer = () => {
250
315
  cancelProbeTimer();
251
316
  probeTimer = scheduleTimeout(probeTimeoutMs, () => {
@@ -300,9 +365,9 @@ export function createTerminalAttachClient({
300
365
  // not strand the client outside both paths. Once protocol is decided the
301
366
  // timer is meaningless and gets cancelled.
302
367
  if (modeDecided) cancelProbeTimer();
303
- partial = { frame: null, empty: false, resnapshot: false, beginSeq: 0, flush: [] };
368
+ partial = emptyPartial();
304
369
  state = "resyncing";
305
- send({ type: "subscribe_terminal", frameVersion: TERMINAL_FRAME_VERSION });
370
+ send(subscribeMessage());
306
371
  emit("resubscribing", { reason });
307
372
  };
308
373
 
@@ -352,13 +417,9 @@ export function createTerminalAttachClient({
352
417
  reconnectFromGeneration = null;
353
418
  cancelReconcileTimer();
354
419
  lastSeq = effective;
355
- partial = { frame: null, empty: false, resnapshot: false, beginSeq: 0, flush: [] };
420
+ partial = emptyPartial();
356
421
  state = "resyncing";
357
- send(
358
- effective > 0
359
- ? { type: "subscribe_terminal", frameVersion: TERMINAL_FRAME_VERSION, sinceSeq: effective }
360
- : { type: "subscribe_terminal", frameVersion: TERMINAL_FRAME_VERSION },
361
- );
422
+ send(effective > 0 ? subscribeMessage({ sinceSeq: effective }) : subscribeMessage());
362
423
  return cursor;
363
424
  };
364
425
 
@@ -446,18 +507,43 @@ export function createTerminalAttachClient({
446
507
  const beginCollecting = (msg) => {
447
508
  decideProtocol();
448
509
  cancelProbeTimer();
510
+ // Issue #278: optional screen-owner fact. Validate before emitting; an
511
+ // invalid value is reported (never coerced, never resynced over) and the
512
+ // key is simply omitted from the payload, like an absent one.
513
+ const external = msg.externalOutputActive;
514
+ const externalValid = external === undefined || typeof external === "boolean";
515
+ if (!externalValid) {
516
+ emit("protocolError", {
517
+ code: "external_output_active_invalid",
518
+ message: "snapshot_begin.externalOutputActive",
519
+ });
520
+ }
449
521
  // Size-sync hook (CR R1 blocking): every begin carries the runner's
450
522
  // captured geometry — empty baselines included, so a child that has not
451
523
  // produced output yet still gets corrected BEFORE its first bytes land.
452
524
  if (typeof msg.cols === "number" && typeof msg.rows === "number") {
453
- emit("snapshotBegin", { cols: msg.cols, rows: msg.rows });
525
+ emit("snapshotBegin", {
526
+ cols: msg.cols,
527
+ rows: msg.rows,
528
+ ...(msg.empty === true ? { empty: true } : {}),
529
+ ...(typeof msg.generation === "string" ? { generation: msg.generation } : {}),
530
+ ...(typeof external === "boolean" ? { externalOutputActive: external } : {}),
531
+ });
532
+ }
533
+ let beginCoverage = null;
534
+ if (msg.viewProof !== undefined) {
535
+ beginCoverage = sanitizeViewProofCoverage(msg.viewProof);
536
+ if (beginCoverage === null) {
537
+ emit("protocolError", { code: "view_proof_invalid", message: "snapshot_begin.viewProof" });
538
+ beginCoverage = unknownViewProof("invalid-view-proof");
539
+ }
454
540
  }
455
541
  partial = {
456
- frame: null,
542
+ ...emptyPartial(),
457
543
  empty: msg.empty === true,
458
544
  resnapshot: msg.resnapshot === true,
459
545
  beginSeq: typeof msg.snapshotSeq === "number" ? msg.snapshotSeq : 0,
460
- flush: [],
546
+ viewProofBegin: beginCoverage,
461
547
  };
462
548
  state = "collecting";
463
549
  if (partial.empty) {
@@ -485,6 +571,29 @@ export function createTerminalAttachClient({
485
571
  return;
486
572
  }
487
573
  snapshotFailures = 0; // a verified snapshot pays back the recovery budget
574
+ let endCoverage = null;
575
+ if (msg.viewProof !== undefined) {
576
+ endCoverage = sanitizeViewProofCoverage(msg.viewProof);
577
+ if (endCoverage === null) {
578
+ emit("protocolError", { code: "view_proof_invalid", message: "snapshot_end.viewProof" });
579
+ endCoverage = unknownViewProof("invalid-view-proof");
580
+ }
581
+ }
582
+ let viewProof = endCoverage ?? partial.viewProofState ?? partial.viewProofBegin;
583
+ let viewProofRecords = partial.viewProofRecords;
584
+ if (viewProof !== null && viewProof.status === "covered" && viewProof.throughSeq > nextSeq - 1) {
585
+ viewProof = unknownViewProof("view-proof-future");
586
+ }
587
+ if (partial.viewProofRecordsDropped) {
588
+ viewProof = unknownViewProof("records-dropped");
589
+ viewProofRecords = [];
590
+ } else if (viewProofRecords.length > 0) {
591
+ // A record after the baseline needs its catch-up output segment. Missing it
592
+ // means the client cannot prove the receipt order; never keep "covered".
593
+ const flushSeqs = new Set(partial.flush.map((chunk) => chunk.seq));
594
+ const missing = viewProofRecords.some((record) => record.seq > partial.beginSeq && !flushSeqs.has(record.seq));
595
+ if (missing && (viewProof === null || viewProof.status === "covered")) viewProof = unknownViewProof("proof-output-gap");
596
+ }
488
597
  emit("snapshotReady", {
489
598
  frame: partial.frame ?? undefined,
490
599
  empty: partial.empty || undefined,
@@ -493,6 +602,8 @@ export function createTerminalAttachClient({
493
602
  // Optional field: omit the key for a runner that predates it, so the
494
603
  // event shape stays exactly what old consumers assert on.
495
604
  ...(typeof msg.scrollbackLines === "number" ? { scrollbackLines: msg.scrollbackLines } : {}),
605
+ ...(viewProof === null ? {} : { viewProof }),
606
+ ...(viewProofRecords.length > 0 ? { viewProofRecords } : {}),
496
607
  });
497
608
  for (const chunk of partial.flush) emit("output", chunk.data);
498
609
  lastSeq = nextSeq - 1;
@@ -545,6 +656,11 @@ export function createTerminalAttachClient({
545
656
  fallbackToLegacy("frame_version_mismatch");
546
657
  return true;
547
658
  }
659
+ if (msg.code === "view_proof_version_mismatch") {
660
+ // Conservative: never fake modern proof for an incompatible runner.
661
+ fallbackToLegacy("view_proof_version_mismatch");
662
+ return true;
663
+ }
548
664
  if (msg.code === "snapshot_failed" || msg.code === "invalid_since_seq") {
549
665
  if (state === "probing" || state === "resyncing" || state === "collecting") {
550
666
  resyncOrFail(msg.code);
@@ -585,6 +701,56 @@ export function createTerminalAttachClient({
585
701
  }
586
702
  return false; // UI-owned status errors
587
703
  }
704
+ case "view_proof": {
705
+ const record = sanitizeViewProofRecord(msg.record);
706
+ if (record === null) {
707
+ emit("protocolError", { code: "view_proof_invalid", message: "view_proof.record" });
708
+ return true;
709
+ }
710
+ if (state === "collecting") {
711
+ if (partial.viewProofRecords.length >= MAX_VIEW_PROOF_RECORDS) partial.viewProofRecordsDropped = true;
712
+ else partial.viewProofRecords.push(record);
713
+ return true;
714
+ }
715
+ if (state === "live" || state === "resyncing") {
716
+ if (record.seq > lastSeq) {
717
+ emit("protocolError", { code: "view_proof_future", message: `seq ${record.seq} > ${lastSeq}` });
718
+ return true;
719
+ }
720
+ emit("viewProofRecord", record);
721
+ return true;
722
+ }
723
+ return true; // probing/reconciling: pre-subscribe stray
724
+ }
725
+ case "view_proof_state": {
726
+ let coverage = sanitizeViewProofCoverage(msg.viewProof);
727
+ if (coverage === null) {
728
+ emit("protocolError", { code: "view_proof_invalid", message: "view_proof_state.viewProof" });
729
+ coverage = unknownViewProof("invalid-view-proof");
730
+ }
731
+ if ((state === "live" || state === "resyncing") && coverage.status === "covered" && coverage.throughSeq > lastSeq) {
732
+ emit("protocolError", { code: "view_proof_future", message: `throughSeq ${coverage.throughSeq} > ${lastSeq}` });
733
+ coverage = unknownViewProof("view-proof-future");
734
+ }
735
+ if (state === "collecting") {
736
+ partial.viewProofState = coverage;
737
+ return true;
738
+ }
739
+ if (state === "resyncing") {
740
+ // Zero-output replay completion: the state message is the only
741
+ // proof-bearing completion signal. Normal replay completes on output.
742
+ decideProtocol();
743
+ snapshotFailures = 0;
744
+ state = "live";
745
+ emit("viewProof", coverage);
746
+ return true;
747
+ }
748
+ if (state === "live") {
749
+ emit("viewProof", coverage);
750
+ return true;
751
+ }
752
+ return true; // probing/reconciling: pre-subscribe stray
753
+ }
588
754
  case "snapshot_begin": {
589
755
  if (typeof msg.generation === "string" && msg.generation) generation = msg.generation;
590
756
  if (state === "probing" || state === "resyncing") {
@@ -710,7 +876,7 @@ export function createTerminalAttachClient({
710
876
  return;
711
877
  }
712
878
  if (state !== "probing") return;
713
- send({ type: "subscribe_terminal", frameVersion: TERMINAL_FRAME_VERSION });
879
+ send(subscribeMessage());
714
880
  fireProbeTimer();
715
881
  }
716
882
 
@@ -729,13 +895,13 @@ export function createTerminalAttachClient({
729
895
  function reconnect(cursorSeq) {
730
896
  if (state === "closed" || state === "legacy") return;
731
897
  if (state === "probing") {
732
- send({ type: "subscribe_terminal", frameVersion: TERMINAL_FRAME_VERSION });
898
+ send(subscribeMessage());
733
899
  fireProbeTimer();
734
900
  return;
735
901
  }
736
902
  seq = 0; // per-connection ordering resets with the socket (spec D4)
737
903
  snapshotFailures = 0; // fresh connection, fresh recovery budget
738
- partial = { frame: null, empty: false, resnapshot: false, beginSeq: 0, flush: [] };
904
+ partial = emptyPartial();
739
905
  if (!instanceId) {
740
906
  issueReconnectSubscribe(cursorSeq);
741
907
  return;
@@ -792,6 +958,19 @@ export function createTerminalAttachClient({
792
958
  onDisconnect,
793
959
  handleMessage,
794
960
  close,
961
+ /** Bounded fresh seq-less resync request (no timer/retry loop here). */
962
+ requestResync(reason = "requested") {
963
+ if (state === "closed" || state === "legacy") return false;
964
+ resync(reason);
965
+ return true;
966
+ },
967
+ /** Conservative public legacy decision (used for observer-unavailable). */
968
+ forceLegacy(reason = "forced") {
969
+ if (state === "closed") return false;
970
+ if (state === "legacy") return true;
971
+ fallbackToLegacy(reason);
972
+ return true;
973
+ },
795
974
  /** @returns {"probing" | "protocol" | "legacy" | "closed"} UI-facing mode */
796
975
  getMode() {
797
976
  if (state === "collecting" || state === "live" || state === "resyncing" || state === "reconciling") return "protocol";