@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
@@ -1,3 +1,4 @@
1
+ import { validateFrameMetadata } from "./attach-frame-proof.mjs";
1
2
  import { ringChunksAfter } from "./terminal-model.mjs";
2
3
  import {
3
4
  captureTerminalSnapshot,
@@ -38,9 +39,50 @@ import {
38
39
  * capture format, an internal artifact that never crosses the wire in Route B).
39
40
  */
40
41
  export const TERMINAL_FRAME_VERSION = 1;
42
+ /** Optional per-socket view-proof capability (issue #222 FW-06, step 23b2b). */
43
+ export const VIEW_PROOF_PROTOCOL_VERSION = 1;
44
+ /** Bounded per-socket capture queue for S/F/A marker records. */
45
+ export const MAX_VIEW_PROOF_RECORDS = 256;
41
46
 
42
47
  export { TERMINAL_SNAPSHOT_VERSION };
43
48
 
49
+ function unknownCoverage(reason) {
50
+ return { status: "unknown", reason, proof: null, throughSeq: null, cursorVisible: null };
51
+ }
52
+
53
+ function emptyBaselineCoverage() {
54
+ return unknownCoverage("empty-baseline");
55
+ }
56
+
57
+ /** Strip everything except the bounded view-proof record fields (never token/user text). */
58
+ export function sanitizeViewProofRecord(record) {
59
+ if (record === null || typeof record !== "object" || Array.isArray(record)) return null;
60
+ if (record.marker !== "S" && record.marker !== "F" && record.marker !== "A") return null;
61
+ if (!Number.isInteger(record.seq) || record.seq < 1) return null;
62
+ if (!Number.isInteger(record.frameId) || record.frameId < 1) return null;
63
+ if (record.sessionEpoch !== undefined && (!Number.isInteger(record.sessionEpoch) || record.sessionEpoch < 0)) return null;
64
+ const base = {
65
+ marker: record.marker,
66
+ seq: record.seq,
67
+ frameId: record.frameId,
68
+ ...(record.sessionEpoch === undefined ? {} : { sessionEpoch: record.sessionEpoch }),
69
+ };
70
+ if (record.marker === "S") {
71
+ return {
72
+ ...base,
73
+ ...(Number.isInteger(record.intentId) ? { intentId: record.intentId } : {}),
74
+ ...(Number.isInteger(record.sampledCols) ? { sampledCols: record.sampledCols } : {}),
75
+ };
76
+ }
77
+ if (record.marker === "F") {
78
+ const metadata = validateFrameMetadata(record.metadata);
79
+ if (!metadata.ok) return null;
80
+ if (record.sessionEpoch !== undefined && record.sessionEpoch !== metadata.value.sessionEpoch) return null;
81
+ return { ...base, metadata: metadata.value };
82
+ }
83
+ return { ...base, ...(typeof record.reason === "string" ? { reason: record.reason } : {}) };
84
+ }
85
+
44
86
  /**
45
87
  * @typedef {ReturnType<typeof createTerminalSubscription>} TerminalSubscription
46
88
  */
@@ -51,12 +93,20 @@ export { TERMINAL_SNAPSHOT_VERSION };
51
93
  * @param {{
52
94
  * model: import("./terminal-model.mjs").TerminalModel,
53
95
  * send: (msg: Record<string, unknown>) => void,
96
+ * viewProof?: { coverage: (seq: number) => any, replay: (fromSeq: number, throughSeq: number) => any },
54
97
  * }} opts
55
98
  */
56
- export function createTerminalSubscription({ model, send: rawSend, generation }) {
99
+ export function createTerminalSubscription({ model, send: rawSend, generation, viewProof = null }) {
57
100
  /** @type {"idle" | "capturing" | "live"} */
58
101
  let state = "idle";
59
102
  let lastSeq = 0;
103
+ // Optional FW-06 capability: negotiated per socket, never downgraded by a later
104
+ // subscribe_terminal without the field. Queued only while a capture is in flight.
105
+ let viewProofEnabled = false;
106
+ /** @type {any[]} */
107
+ let viewProofQueue = [];
108
+ let viewProofQueueDropped = false;
109
+ let captureViewProofReset = null;
60
110
  // Sticky protocol-ownership marker: set the moment a socket speaks
61
111
  // subscribe_terminal, never reset (not even by gap downgrade or snapshot
62
112
  // failure). The runner excludes subscribed sockets from the legacy output
@@ -87,6 +137,78 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
87
137
  send({ type: "error", code, ...extra });
88
138
  };
89
139
 
140
+ function coverageAt(seq, overrideReason = null) {
141
+ if (overrideReason !== null) return unknownCoverage(overrideReason);
142
+ if (seq === 0) return emptyBaselineCoverage();
143
+ const coverage = viewProof?.coverage?.(seq);
144
+ return coverage && typeof coverage === "object" ? coverage : unknownCoverage("no-frame-witness");
145
+ }
146
+
147
+ function clearCaptureViewProof(reason = null) {
148
+ viewProofQueue = [];
149
+ viewProofQueueDropped = false;
150
+ captureViewProofReset = reason;
151
+ }
152
+
153
+ function queueViewProofRecord(record) {
154
+ if (viewProofQueue.length >= MAX_VIEW_PROOF_RECORDS) {
155
+ viewProofQueueDropped = true;
156
+ return;
157
+ }
158
+ viewProofQueue.push(record);
159
+ }
160
+
161
+ /**
162
+ * Emit queued S/F/A records in seq order around the ring catch-up. Output at
163
+ * an equal seq is either already in the snapshot frame (seq <= snapshotSeq)
164
+ * or emitted first by the caller (seq > snapshotSeq).
165
+ */
166
+ function flushCaptureViewProofRecords(chunks, snapshotSeq) {
167
+ if (!viewProofEnabled) {
168
+ for (const chunk of chunks) {
169
+ send({ type: "output", seq: chunk.seq, data: chunk.data });
170
+ lastSeq = chunk.seq;
171
+ }
172
+ return;
173
+ }
174
+ if (viewProofQueueDropped) {
175
+ viewProofQueue = [];
176
+ for (const chunk of chunks) {
177
+ send({ type: "output", seq: chunk.seq, data: chunk.data });
178
+ lastSeq = chunk.seq;
179
+ }
180
+ return;
181
+ }
182
+ const records = viewProofQueue.slice();
183
+ viewProofQueue = [];
184
+ const beforeChunks = [];
185
+ const bySeq = new Map();
186
+ const afterChunks = [];
187
+ for (const record of records) {
188
+ if (record.seq <= snapshotSeq) beforeChunks.push(record);
189
+ else {
190
+ const list = bySeq.get(record.seq) ?? [];
191
+ list.push(record);
192
+ bySeq.set(record.seq, list);
193
+ }
194
+ }
195
+ for (const record of beforeChunks) send({ type: "view_proof", record });
196
+ const sentSeqs = new Set();
197
+ for (const chunk of chunks) {
198
+ send({ type: "output", seq: chunk.seq, data: chunk.data });
199
+ lastSeq = chunk.seq;
200
+ sentSeqs.add(chunk.seq);
201
+ for (const record of bySeq.get(chunk.seq) ?? []) send({ type: "view_proof", record });
202
+ }
203
+ for (const [seq, list] of bySeq) {
204
+ if (sentSeqs.has(seq)) continue;
205
+ for (const record of list) afterChunks.push(record);
206
+ }
207
+ // A record can only be missing its catch-up chunk if the ring lost data;
208
+ // do not pretend it was stitched. The end-state coverage marks UNKNOWN.
209
+ if (afterChunks.length > 0) viewProofQueueDropped = true;
210
+ }
211
+
90
212
  /**
91
213
  * Fresh-snapshot path (first subscribe or unrecoverable cursor). Frame
92
214
  * metadata comes from the captured DTO, so a resize racing the async
@@ -95,6 +217,7 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
95
217
  */
96
218
  async function startSnapshot({ resnapshot = false } = {}) {
97
219
  state = "capturing";
220
+ clearCaptureViewProof(null);
98
221
  try {
99
222
  const empty = model.lastSeq === 0;
100
223
  const begin = /** @type {Record<string, unknown>} */ ({
@@ -108,6 +231,9 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
108
231
  ...(generation ? { generation } : {}),
109
232
  });
110
233
  if (empty) {
234
+ // Issue #278: an empty model has parsed no output, so the screen-owner
235
+ // fact is always false here; sample it for shape uniformity.
236
+ begin.externalOutputActive = model.externalOutputActive === true;
111
237
  // Runner (re)started and the new child has produced no output yet:
112
238
  // the "host starting" baseline. No frame; live output starts at seq 1.
113
239
  // The resnapshot marker applies here too: a client presenting a stale
@@ -115,17 +241,30 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
115
241
  // marker contract must be consistent across resnapshot paths).
116
242
  begin.empty = true;
117
243
  if (resnapshot) begin.resnapshot = true;
244
+ if (viewProofEnabled) begin.viewProof = emptyBaselineCoverage();
118
245
  send(begin);
119
246
  lastSeq = 0;
120
- send({ type: "snapshot_end", nextSeq: lastSeq + 1, scrollbackLines: 0 });
247
+ send({
248
+ type: "snapshot_end",
249
+ nextSeq: lastSeq + 1,
250
+ scrollbackLines: 0,
251
+ ...(viewProofEnabled ? { viewProof: emptyBaselineCoverage() } : {}),
252
+ });
121
253
  if (!sendBroken) state = "live";
122
254
  return;
123
255
  }
124
256
  const dto = await captureTerminalSnapshot(model);
257
+ // Issue #278: sample the screen-owner fact WITH the snapshot metadata
258
+ // (after parser idle), never at capture start — a synchronized ?1049l
259
+ // landing inside the capture window is already part of the DTO, and the
260
+ // catch-up flush covers only chunks past dto.snapshotSeq, so a begin
261
+ // sampled at capture start would report stale false forever.
262
+ begin.externalOutputActive = model.externalOutputActive === true;
125
263
  begin.snapshotSeq = dto.snapshotSeq;
126
264
  begin.cols = dto.cols;
127
265
  begin.rows = dto.rows;
128
266
  if (resnapshot) begin.resnapshot = true;
267
+ if (viewProofEnabled) begin.viewProof = coverageAt(dto.snapshotSeq, captureViewProofReset);
129
268
  send(begin);
130
269
  send({
131
270
  type: "snapshot_frame",
@@ -139,21 +278,27 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
139
278
  if (after.evicted) {
140
279
  // Ring pressure during capture: refuse to stitch, ask for a redo.
141
280
  state = "idle";
281
+ clearCaptureViewProof(null);
142
282
  send({ type: "resnapshot_required", lastSeq, missing: dto.snapshotSeq + 1 });
143
283
  return;
144
284
  }
145
- for (const chunk of after.chunks) {
146
- send({ type: "output", seq: chunk.seq, data: chunk.data });
147
- lastSeq = chunk.seq;
148
- }
285
+ flushCaptureViewProofRecords(after.chunks, dto.snapshotSeq);
149
286
  if (after.chunks.length === 0) lastSeq = dto.snapshotSeq;
150
287
  // scrollbackLines is the runner-authoritative history count for the very
151
288
  // frame just sent (same capture): the client needs it to tell real history
152
289
  // from rows its local hydration scrolled out of the viewport (issue #205).
153
- send({ type: "snapshot_end", nextSeq: lastSeq + 1, scrollbackLines: dto.scrollback.length });
290
+ const endCoverageReason = captureViewProofReset ?? (viewProofQueueDropped ? "view-proof-records-dropped" : null);
291
+ send({
292
+ type: "snapshot_end",
293
+ nextSeq: lastSeq + 1,
294
+ scrollbackLines: dto.scrollback.length,
295
+ ...(viewProofEnabled ? { viewProof: coverageAt(lastSeq, endCoverageReason) } : {}),
296
+ });
297
+ clearCaptureViewProof(null);
154
298
  if (!sendBroken) state = "live";
155
299
  } catch (err) {
156
300
  state = "idle";
301
+ clearCaptureViewProof(null);
157
302
  fail("snapshot_failed", { message: err instanceof Error ? err.message : String(err) });
158
303
  }
159
304
  }
@@ -166,10 +311,44 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
166
311
  */
167
312
  function startReplay(sinceSeq) {
168
313
  const after = ringChunksAfter(model, sinceSeq);
314
+ if (after.evicted) {
315
+ state = "idle";
316
+ send({ type: "resnapshot_required", lastSeq, missing: sinceSeq + 1 });
317
+ return;
318
+ }
319
+ const hasRange = model.lastSeq > sinceSeq;
320
+ const replayResult = viewProofEnabled && hasRange ? viewProof?.replay?.(sinceSeq + 1, model.lastSeq) : null;
321
+ let proofBySeq = null;
322
+ let proofProblem = null;
323
+ if (viewProofEnabled && hasRange) {
324
+ if (replayResult === null || replayResult === undefined) proofProblem = "no-frame-witness";
325
+ else if (replayResult.status !== "ok") proofProblem = `proof-replay-${replayResult.reason ?? replayResult.status}`;
326
+ else if (replayResult.entries.some((entry) => entry.droppedProofs > 0 || entry.droppedEvents > 0)) proofProblem = "proof-replay-dropped";
327
+ else {
328
+ const chunkSeqs = new Set(after.chunks.map((chunk) => chunk.seq));
329
+ const map = new Map();
330
+ for (const entry of replayResult.entries) {
331
+ if (entry.proofs.length === 0) continue;
332
+ if (!chunkSeqs.has(entry.seq)) {
333
+ proofProblem = "proof-replay-gap";
334
+ break;
335
+ }
336
+ map.set(entry.seq, entry.proofs);
337
+ }
338
+ if (proofProblem === null) proofBySeq = map;
339
+ }
340
+ }
169
341
  for (const chunk of after.chunks) {
170
342
  send({ type: "output", seq: chunk.seq, data: chunk.data });
343
+ if (proofBySeq !== null) {
344
+ for (const proof of proofBySeq.get(chunk.seq) ?? []) {
345
+ const record = sanitizeViewProofRecord(proof);
346
+ if (record !== null) send({ type: "view_proof", record });
347
+ }
348
+ }
171
349
  }
172
350
  lastSeq = model.lastSeq;
351
+ if (viewProofEnabled) send({ type: "view_proof_state", viewProof: coverageAt(lastSeq, proofProblem) });
173
352
  if (!sendBroken) state = "live";
174
353
  }
175
354
 
@@ -193,6 +372,13 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
193
372
  fail("frame_version_mismatch", { supported: TERMINAL_FRAME_VERSION, received: msg.frameVersion });
194
373
  return true;
195
374
  }
375
+ if (msg.viewProof !== undefined) {
376
+ if (msg.viewProof !== VIEW_PROOF_PROTOCOL_VERSION) {
377
+ fail("view_proof_version_mismatch", { supported: VIEW_PROOF_PROTOCOL_VERSION, received: msg.viewProof });
378
+ return true;
379
+ }
380
+ viewProofEnabled = true;
381
+ }
196
382
  if (
197
383
  msg.sinceSeq !== undefined &&
198
384
  (!Number.isInteger(msg.sinceSeq) || msg.sinceSeq < 0)
@@ -238,18 +424,46 @@ export function createTerminalSubscription({ model, send: rawSend, generation })
238
424
  // Gap: never skip silently, never fabricate. One marker, then the client
239
425
  // must re-subscribe (fresh snapshot or replay from its real cursor).
240
426
  state = "idle";
427
+ clearCaptureViewProof(null);
241
428
  send({ type: "resnapshot_required", lastSeq, missing: seq });
242
429
  }
243
430
 
431
+ /** Live/capture delivery of one accepted S/F/A record (opt-in sockets only). */
432
+ function onViewProofRecord(record) {
433
+ if (!viewProofEnabled) return;
434
+ const clean = sanitizeViewProofRecord(record);
435
+ if (clean === null) return;
436
+ if (state === "live") send({ type: "view_proof", record: clean });
437
+ else if (state === "capturing") queueViewProofRecord(clean);
438
+ }
439
+
440
+ /**
441
+ * Reporter replacement/close: drop queued old-token records and force current
442
+ * view-proof state UNKNOWN. Never carries old proofs into a new reporter.
443
+ */
444
+ function onViewProofReset(reason) {
445
+ viewProofQueue = [];
446
+ viewProofQueueDropped = false;
447
+ if (!viewProofEnabled) return;
448
+ if (state === "capturing") {
449
+ captureViewProofReset = reason;
450
+ return;
451
+ }
452
+ if (state === "live") send({ type: "view_proof_state", viewProof: unknownCoverage(reason) });
453
+ }
454
+
244
455
  return {
245
456
  handleMessage,
246
457
  onOutput,
458
+ onViewProofRecord,
459
+ onViewProofReset,
247
460
  /** Sticky: true once the socket sent subscribe_terminal. The runner uses
248
461
  * this to keep the socket out of the legacy output broadcast. */
249
462
  subscribed: () => subscribed,
250
463
  /** Socket went away; the runner drops its reference. */
251
464
  detach() {
252
465
  state = "idle";
466
+ clearCaptureViewProof(null);
253
467
  },
254
468
  };
255
469
  }
@@ -1,4 +1,6 @@
1
1
  import xtermHeadless from "@xterm/headless";
2
+ import { installAttachScreenOwnerObservers } from "./attach-screen-owner.mjs";
3
+ import { createPtyKittyImages } from "./pty-kitty-images.mjs";
2
4
 
3
5
  // @xterm/headless is CommonJS; named import from ESM fails, so destructure.
4
6
  const { Terminal } = /** @type {any} */ (xtermHeadless);
@@ -30,7 +32,9 @@ export const DEFAULT_RING_BYTE_CAP = 4 * 1024 * 1024;
30
32
  * @param {{ cols: number, rows: number, scrollback: number }} opts
31
33
  */
32
34
  export function defaultParserFactory({ cols, rows, scrollback }) {
33
- return new Terminal({ cols, rows, scrollback, allowProposedApi: true });
35
+ const parser = new Terminal({ cols, rows, scrollback, allowProposedApi: true });
36
+ parser._agentBoardKittyImages = createPtyKittyImages(parser);
37
+ return parser;
34
38
  }
35
39
 
36
40
  /**
@@ -55,6 +59,9 @@ export function defaultParserFactory({ cols, rows, scrollback }) {
55
59
  * @property {RingChunk[]} ring oldest-first retained chunks
56
60
  * @property {number} ringBytes total buffered bytes across ring chunks
57
61
  * @property {number} evictedThrough highest seq evicted from the ring; 0 when nothing was evicted
62
+ * @property {boolean} externalOutputActive issue #278: true while an external
63
+ * editor owns the screen (synchronized ?1049l observed by the parser adapter);
64
+ * transported to attach clients via snapshot_begin
58
65
  */
59
66
 
60
67
  /**
@@ -80,7 +87,7 @@ export function createTerminalModel({
80
87
  ringByteCap = DEFAULT_RING_BYTE_CAP,
81
88
  parserFactory = defaultParserFactory,
82
89
  } = {}) {
83
- return {
90
+ const model = {
84
91
  parserFactory,
85
92
  parser: parserFactory({ cols, rows, scrollback }),
86
93
  cols,
@@ -94,7 +101,19 @@ export function createTerminalModel({
94
101
  ring: [],
95
102
  ringBytes: 0,
96
103
  evictedThrough: 0,
104
+ externalOutputActive: false,
97
105
  };
106
+ // Issue #278: observe ?2026/?1049 CSI traffic on the real parser and mirror
107
+ // the screen-owner fact onto the model. Read the fact from every transition
108
+ // callback (never from previous/current reference equality — `l`-final
109
+ // semantic no-ops may still allocate a fresh state object). Parsers without
110
+ // registerCsiHandler (test fakes) install no observers and keep the default.
111
+ installAttachScreenOwnerObservers(model.parser, {
112
+ onTransition: ({ current }) => {
113
+ model.externalOutputActive = current.externalOutputActive === true;
114
+ },
115
+ });
116
+ return model;
98
117
  }
99
118
 
100
119
  /**
@@ -117,7 +136,9 @@ export function feedOutput(model, data) {
117
136
  // Increment before write so a synchronously-firing callback still observes
118
137
  // consistent accounting.
119
138
  model.pendingWrites += 1;
120
- model.parser.write(data, () => {
139
+ // Preserve raw ring bytes for subscribers; track Kitty APCs in parser order
140
+ // so snapshots retain graphics that xterm/headless would otherwise discard.
141
+ model.parser.write(model.parser._agentBoardKittyImages?.transform(data) ?? data, () => {
121
142
  model.pendingWrites -= 1;
122
143
  if (model.pendingWrites === 0 && model.idleWaiters.length > 0) {
123
144
  const waiters = model.idleWaiters;
@@ -62,6 +62,7 @@ const RGB_MARKER = 0x1000000;
62
62
  * @property {SnapshotCell[][]} viewport rows of the viewport grid
63
63
  * @property {SnapshotCell[][]} scrollback up to scrollbackCap lines directly
64
64
  * above the viewport, oldest first
65
+ * @property {string[]} [kittyImageLines] graphical lines across scrollback + viewport
65
66
  * @property {boolean} scrollbackTruncated true when more scrollback existed
66
67
  * than the cap allowed
67
68
  */
@@ -153,6 +154,7 @@ export async function captureTerminalSnapshot(model, { scrollbackCap = DEFAULT_S
153
154
  /** @type {SnapshotCell[][]} */
154
155
  const scrollback = [];
155
156
  for (let k = take; k >= 1; k--) scrollback.push(captureLine(buffer, baseY - k, cols));
157
+ const kittyImageLines = parser._agentBoardKittyImages?.project(Array(take + rows).fill(""), baseY - take, take + rows);
156
158
  return {
157
159
  version: TERMINAL_SNAPSHOT_VERSION,
158
160
  kind: "terminal_snapshot",
@@ -164,6 +166,7 @@ export async function captureTerminalSnapshot(model, { scrollbackCap = DEFAULT_S
164
166
  viewport,
165
167
  scrollback,
166
168
  scrollbackTruncated: available > scrollbackCap,
169
+ ...(kittyImageLines?.some(Boolean) ? { kittyImageLines } : {}),
167
170
  };
168
171
  }
169
172
 
@@ -340,14 +343,21 @@ export async function synthesizeFullRedrawFrame(source) {
340
343
  // wrap-pending row advances exactly one line). The last viewport row gets
341
344
  // no trailing newline (it would fire an extra scroll); the cursor park
342
345
  // below positions the cursor afterwards.
346
+ // Emit graphics with their original rows. Historical placements then scroll
347
+ // into history with their text, rather than being CUP-positioned into the
348
+ // current viewport or lost at a resnapshot.
349
+ let imageRow = 0;
343
350
  for (const line of dto.scrollback) {
351
+ parts.push(dto.kittyImageLines?.[imageRow++] ?? "");
344
352
  emitRow(parts, line);
345
353
  parts.push("\r\n");
346
354
  }
347
355
  for (let y = 0; y < dto.rows - 1; y++) {
356
+ parts.push(dto.kittyImageLines?.[imageRow++] ?? "");
348
357
  emitRow(parts, dto.viewport[y] ?? []);
349
358
  parts.push("\r\n");
350
359
  }
360
+ parts.push(dto.kittyImageLines?.[imageRow] ?? "");
351
361
  emitRow(parts, dto.viewport[dto.rows - 1] ?? []);
352
362
  parts.push(modesSequence(dto.modes));
353
363
  parkCursor(parts, dto);
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Title-generation orchestration with fully injected effects (issue #295).
3
+ * The runner shell owns env resolution and real I/O; this module owns
4
+ * sequencing and the write-back guard so it is unit-testable with a fake clock.
5
+ */
6
+ import { firstSubstantiveUserPrompt, isGreetingPrompt, normalizeGeneratedTitle } from "./title.mjs";
7
+
8
+ /** Default poll interval while waiting for a substantive user message. */
9
+ export const TITLE_POLL_INTERVAL_MS = 15_000;
10
+
11
+ /** Default total budget for the greeting poll loop. */
12
+ export const TITLE_POLL_BUDGET_MS = 300_000;
13
+
14
+ /**
15
+ * @typedef {Object} TitleFlowDeps
16
+ * @property {() => number} now
17
+ * @property {(ms: number) => Promise<void>} sleep
18
+ * @property {(root: string, viewId: string) => any|null} readMeta
19
+ * @property {(meta: any) => void} commitMeta
20
+ * @property {(config: any) => string|null} readSessionText
21
+ * @property {(prompt: string) => Promise<string|null>} runOneShot
22
+ */
23
+
24
+ /**
25
+ * Generate a title for a view. Non-greeting prompts generate immediately
26
+ * (today's behavior). Greeting prompts poll the session file for the first
27
+ * substantive user message until the budget runs out, then exit quietly.
28
+ * @param {import("./types.mjs").TitleConfig} config
29
+ * @param {TitleFlowDeps} deps
30
+ */
31
+ export async function runTitleFlow(config, deps) {
32
+ if (!isGreetingPrompt(config.prompt)) {
33
+ await generateOnce(config, deps, config.prompt);
34
+ return;
35
+ }
36
+ const interval = config.pollIntervalMs ?? TITLE_POLL_INTERVAL_MS;
37
+ const deadline = deps.now() + (config.pollBudgetMs ?? TITLE_POLL_BUDGET_MS);
38
+ while (deps.now() < deadline) {
39
+ await deps.sleep(interval);
40
+ const text = deps.readSessionText(config);
41
+ const prompt = text ? firstSubstantiveUserPrompt(text) : null;
42
+ if (prompt) {
43
+ await generateOnce(config, deps, prompt);
44
+ return;
45
+ }
46
+ }
47
+ }
48
+
49
+ /**
50
+ * One guarded title generation: last-line extraction, normalize, fallback-only
51
+ * write (manual renames always win — meta is re-read right before the guard).
52
+ * @param {import("./types.mjs").TitleConfig} config
53
+ * @param {TitleFlowDeps} deps
54
+ * @param {string} prompt
55
+ */
56
+ async function generateOnce(config, deps, prompt) {
57
+ const out = await deps.runOneShot(prompt);
58
+ const last = out?.trim().split("\n").slice(-1)[0]?.trim() ?? "";
59
+ const title = normalizeGeneratedTitle(last, config.fallbackName);
60
+ if (!title || title === config.fallbackName) return;
61
+ const meta = deps.readMeta(config.root, config.viewId);
62
+ if (!meta) return;
63
+ if (meta.name !== config.fallbackName) return;
64
+ meta.name = title;
65
+ deps.commitMeta(meta);
66
+ }
@@ -1,5 +1,7 @@
1
1
  /** Title-generation helpers for session names. */
2
2
 
3
+ import { activeBranchEntries, contentText, parseSessionEntries } from "./session-entries.mjs";
4
+
3
5
  /** Default cheap model for session titles. Override via $AGENT_BOARD_TITLE_MODEL. */
4
6
  export const DEFAULT_TITLE_MODEL = "openai-codex/gpt-5.5";
5
7
 
@@ -41,3 +43,102 @@ export function normalizeGeneratedTitle(text, fallback, maxWords = 4) {
41
43
  const compact = words.join(" ").replace(/[.,;:!?]+$/g, "").trim();
42
44
  return compact || fallback;
43
45
  }
46
+
47
+ /** Characters stripped from the edges of a message before greeting matching. */
48
+ const GREETING_EDGE_PUNCT = "!!??。.,,、~~…;;::";
49
+
50
+ /** Multi-word/multi-char greeting vocabulary (greedy longest-match units). */
51
+ const GREETINGS = [
52
+ "good morning", "good afternoon", "good evening", "good day",
53
+ "hello", "hi", "hey", "hiya", "yo", "sup", "howdy", "greetings", "morning",
54
+ "你好", "您好", "嗨", "哈喽", "哈啰", "在吗", "在么",
55
+ "早上好", "上午好", "早安", "下午好", "晚上好", "晚安",
56
+ ];
57
+
58
+ /** Particles that may only appear after a greeting unit (suffix fillers). */
59
+ const GREETING_PARTICLES = ["there", "呀", "啊", "哦"];
60
+
61
+ const GREETING_SEPARATOR = new Set([" ", ...GREETING_EDGE_PUNCT.split("")]);
62
+
63
+ // Length-sorted match pools, precomputed once so longestUnitAt does not re-sort per position.
64
+ const GREETINGS_BY_LENGTH = [...GREETINGS].sort((a, b) => b.length - a.length);
65
+ const UNITS_BY_LENGTH = [...GREETINGS, ...GREETING_PARTICLES].sort((a, b) => b.length - a.length);
66
+
67
+ /**
68
+ * True iff the ENTIRE message is greeting material: a greeting-first greedy
69
+ * longest-match consume over the normalized string (issue #295). The first
70
+ * consumed unit must be a GREETINGS entry; later units may be GREETINGS or
71
+ * particles; adjacent duplicates need no separator.
72
+ * @param {string|null|undefined} text
73
+ * @returns {boolean}
74
+ */
75
+ export function isGreetingPrompt(text) {
76
+ const normalized = String(text ?? "")
77
+ .trim()
78
+ .toLowerCase()
79
+ .replace(/\s+/g, " ")
80
+ .replace(new RegExp(`^[${escapeForCharClass(GREETING_EDGE_PUNCT)} ]+|[${escapeForCharClass(GREETING_EDGE_PUNCT)} ]+$`, "g"), "");
81
+ if (!normalized) return false;
82
+ let i = 0;
83
+ let consumedGreeting = false;
84
+ let first = true;
85
+ while (i < normalized.length) {
86
+ if (GREETING_SEPARATOR.has(normalized[i])) {
87
+ i++;
88
+ continue;
89
+ }
90
+ const unit = longestUnitAt(normalized, i, first);
91
+ if (!unit) return false;
92
+ if (unit.fromGreetings) consumedGreeting = true;
93
+ first = false;
94
+ i += unit.text.length;
95
+ }
96
+ return consumedGreeting;
97
+ }
98
+
99
+ /** @param {string} s @param {number} i @param {boolean} first */
100
+ function longestUnitAt(s, i, first) {
101
+ const sorted = first ? GREETINGS_BY_LENGTH : UNITS_BY_LENGTH;
102
+ for (const candidate of sorted) {
103
+ if (s.startsWith(candidate, i)) return { text: candidate, fromGreetings: GREETINGS.includes(candidate) };
104
+ }
105
+ return null;
106
+ }
107
+
108
+ /** @param {string} chars */
109
+ function escapeForCharClass(chars) {
110
+ return chars.replace(/[\\\]^-]/g, "\\$&");
111
+ }
112
+
113
+ /**
114
+ * Resolve title-generation settings from env, preserving the runner's
115
+ * historical precedence exactly (issue #295): board var wins over the legacy
116
+ * view var; `off` disables even when a config model is set.
117
+ * @param {Record<string, string|undefined>} env
118
+ * @param {string|null|undefined} configModel
119
+ * @returns {{ enabled: boolean, model: string, thinking: string }}
120
+ */
121
+ export function resolveTitleSettings(env, configModel) {
122
+ const configured = env.AGENT_BOARD_TITLE_MODEL ?? env.AGENT_VIEW_TITLE_MODEL;
123
+ const thinking = env.AGENT_BOARD_TITLE_THINKING_LEVEL ?? env.AGENT_VIEW_TITLE_THINKING_LEVEL ?? DEFAULT_TITLE_THINKING_LEVEL;
124
+ if (configured === "off") return { enabled: false, model: "", thinking };
125
+ return { enabled: true, model: configModel ?? configured ?? DEFAULT_TITLE_MODEL, thinking };
126
+ }
127
+
128
+ /**
129
+ * First substantive (non-greeting, non-empty) user message on the active
130
+ * branch of a session JSONL, or null (issue #295). Tool-result user entries
131
+ * project to empty text and are skipped by contentText.
132
+ * @param {string} sessionJsonlText
133
+ * @returns {string|null}
134
+ */
135
+ export function firstSubstantiveUserPrompt(sessionJsonlText) {
136
+ const { entries, byId } = parseSessionEntries(sessionJsonlText);
137
+ for (const entry of activeBranchEntries(entries, byId)) {
138
+ if (entry?.type !== "message" || entry.message?.role !== "user") continue;
139
+ const text = contentText(entry.message?.content);
140
+ if (!text || isGreetingPrompt(text)) continue;
141
+ return text;
142
+ }
143
+ return null;
144
+ }
@@ -97,6 +97,18 @@ export const GROUP_LABELS = {
97
97
  * @property {"agent-board"} source
98
98
  */
99
99
 
100
+ /**
101
+ * Compaction window mirrored from pi (issue #297).
102
+ * @typedef {Object} CompactionWindow
103
+ * @property {"running"|"failed"} phase
104
+ * @property {"manual"|"threshold"|"overflow"} reason
105
+ * @property {number} startedAt
106
+ * @property {{semanticState:SemanticState, processState:ProcessState, summary:string, question:string|null, error:string|null}|null} previous
107
+ * Pre-compaction snapshot; kept on `failed` markers so a retry can restore the
108
+ * error the row carried before the window.
109
+ * @property {string|null} error pi's errorMessage, only on phase "failed".
110
+ */
111
+
100
112
  /**
101
113
  * Derived dashboard state for a row (`state.json`).
102
114
  * @typedef {Object} ViewState
@@ -112,6 +124,7 @@ export const GROUP_LABELS = {
112
124
  * @property {boolean} hasError
113
125
  * @property {string} latestAssistantPreview
114
126
  * @property {{name:string, path:string|null}|null} latestTool
127
+ * @property {CompactionWindow|null} [compaction] Compaction window mirrored from pi (issue #297).
115
128
  * @property {string|null} question
116
129
  * @property {Array<{toolCallId:string, question:string}>} pendingQuestions
117
130
  * @property {string|null} error
@@ -178,6 +191,7 @@ export const GROUP_LABELS = {
178
191
  * @property {string} summary
179
192
  * @property {number} lastActivityAt
180
193
  * @property {{name:string, path:string|null}|null} currentTool
194
+ * @property {CompactionWindow|null} [compaction] Compaction window mirrored from pi (issue #297).
181
195
  * @property {string} latestAssistantPreview
182
196
  * @property {string|null} question
183
197
  * @property {Array<{toolCallId:string, question:string}>} pendingQuestions
@@ -248,6 +262,9 @@ export const GROUP_LABELS = {
248
262
  * @property {string} piCommand
249
263
  * @property {string[]} piArgsPrefix
250
264
  * @property {string|null} model
265
+ * Optional poll tuning for tests; production never sets these (issue #295).
266
+ * @property {number} [pollIntervalMs]
267
+ * @property {number} [pollBudgetMs]
251
268
  */
252
269
 
253
270
  /**