tmux-ide 2.9.25 → 2.9.27

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 (67) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +1577 -559
  3. package/package.json +3 -2
  4. package/packages/contracts/src/pane-stream.ts +28 -0
  5. package/packages/contracts/src/terminal-delivery.ts +122 -5
  6. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  7. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  8. package/packages/core/src/index.ts +1 -0
  9. package/packages/core/src/terminal-delivery-binary.ts +8 -7
  10. package/packages/core/src/terminal-delivery.ts +174 -3
  11. package/packages/core/src/terminal-partial-history.ts +152 -0
  12. package/packages/core/src/terminal-replica.ts +70 -1
  13. package/packages/daemon/dist/command-center/owner-keep-alive.js +30 -0
  14. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  15. package/packages/daemon/dist/command-center/server.js +3 -0
  16. package/packages/daemon/dist/command-center/tmux-server-attach.js +51 -0
  17. package/packages/daemon/dist/command-center/tmux-servers.js +95 -7
  18. package/packages/daemon/dist/doctor.js +4 -4
  19. package/packages/daemon/dist/lib/app-config.js +7 -0
  20. package/packages/daemon/dist/lib/node-requirement.js +20 -0
  21. package/packages/daemon/dist/lib/require-supported-node.js +8 -0
  22. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  23. package/packages/daemon/dist/lib/tmux-server-session-open.js +38 -12
  24. package/packages/daemon/dist/lib/workspace-promotion.js +4 -4
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  27. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  29. package/packages/daemon/dist/server/pane-stream-upgrade.js +39 -1
  30. package/packages/daemon/dist/terminal/mirror/session-channel.js +6 -1
  31. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  32. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +112 -22
  33. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  34. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  35. package/packages/daemon/dist/terminal/session-runtime/registry.js +2 -0
  36. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +571 -33
  37. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +2 -0
  38. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  39. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +76 -2
  40. package/packages/daemon/dist/tui/mirror/theme.js +8 -1
  41. package/packages/daemon/src/command-center/attach-window-rule.cases.json +84 -0
  42. package/packages/daemon/src/command-center/owner-keep-alive.ts +38 -0
  43. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  44. package/packages/daemon/src/command-center/server.ts +3 -0
  45. package/packages/daemon/src/command-center/tmux-server-attach.ts +75 -0
  46. package/packages/daemon/src/command-center/tmux-servers.ts +103 -6
  47. package/packages/daemon/src/doctor.ts +4 -4
  48. package/packages/daemon/src/lib/app-config.ts +15 -0
  49. package/packages/daemon/src/lib/node-requirement.ts +22 -0
  50. package/packages/daemon/src/lib/require-supported-node.ts +9 -0
  51. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  52. package/packages/daemon/src/lib/tmux-server-session-open.ts +53 -15
  53. package/packages/daemon/src/lib/workspace-promotion.ts +4 -4
  54. package/packages/daemon/src/server/pane-stream-upgrade.ts +41 -1
  55. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  56. package/packages/daemon/src/terminal/mirror/session-channel.ts +8 -1
  57. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  58. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +136 -20
  59. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  60. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  61. package/packages/daemon/src/terminal/session-runtime/registry.ts +2 -0
  62. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +696 -30
  63. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  64. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +2 -0
  65. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
  66. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +82 -2
  67. package/packages/daemon/src/tui/mirror/theme.ts +13 -1
@@ -3,6 +3,8 @@ import {
3
3
  TERMINAL_GRAPHICS_COMPRESSED_LOCAL_CAPABILITY_VERSION,
4
4
  TERMINAL_PROJECTION_CAPABILITY_VERSION,
5
5
  TERMINAL_PROJECTION_LOCAL_CAPABILITY_VERSION,
6
+ TERMINAL_DELIVERY_PARTIAL_HISTORY_CAPABILITY_VERSION,
7
+ type TerminalDeliveryHistoryCommitment,
6
8
  } from "@tmux-ide/contracts";
7
9
  import {
8
10
  BinaryTerminalWriter,
@@ -27,6 +29,9 @@ import {
27
29
  TerminalDeliveryNegotiatedSchemaZ,
28
30
  TerminalDeliveryNackSchemaZ,
29
31
  TerminalSemanticDeliveryPayloadSchemaZ,
32
+ TerminalSemanticHistoryPayloadSchemaZ,
33
+ TERMINAL_DELIVERY_HISTORY_CHUNK_MAX_ROWS,
34
+ type TerminalSemanticHistoryPayload,
30
35
  TerminalReplicaSnapshotSchemaZ,
31
36
  TerminalReplicaRowSchemaZ,
32
37
  TerminalReplicaPatchPayloadSchemaZ,
@@ -48,6 +53,7 @@ import {
48
53
  } from "@tmux-ide/contracts";
49
54
  import {
50
55
  applyTerminalReplicaPatch,
56
+ freezeTerminalReplicaRow,
51
57
  freezeTerminalReplicaSnapshot,
52
58
  hashTerminalReplicaSnapshot,
53
59
  hashTerminalReplicaTombstone,
@@ -56,6 +62,10 @@ import {
56
62
  terminalReplicaRowsEqual,
57
63
  } from "./terminal-replica.ts";
58
64
  import { grantCompactReplicaCapability } from "./terminal-compact-capability.ts";
65
+ import {
66
+ hashPartialTerminalReplicaSnapshot,
67
+ prependVerifiedTerminalHistory,
68
+ } from "./terminal-partial-history.ts";
59
69
  import {
60
70
  createDecodedTerminalReplicaRowBuilder,
61
71
  hashTerminalReplicaRowCooperatively,
@@ -107,12 +117,18 @@ export function negotiateTerminalDelivery(
107
117
  encoding !== "semantic-binary-v1"
108
118
  )
109
119
  return { accepted: false, reason: "unsupported-capability-combination" };
120
+ // Capability 122 (history on demand) replaces the alternate-screen projection.
121
+ const partialHistory =
122
+ offer.protocolVersions.includes(TERMINAL_DELIVERY_PARTIAL_HISTORY_CAPABILITY_VERSION) &&
123
+ (encoding === "semantic-compact-v1" || encoding === "semantic-binary-v1");
110
124
  return {
111
125
  accepted: true,
112
126
  negotiated: {
113
127
  protocolVersion: TERMINAL_DELIVERY_PROTOCOL_VERSION,
114
128
  encoding,
129
+ ...(partialHistory ? { partialHistory: "tail-v1" as const } : {}),
115
130
  ...(binary &&
131
+ !partialHistory &&
116
132
  offer.protocolVersions.some(
117
133
  (v) =>
118
134
  v === TERMINAL_PROJECTION_CAPABILITY_VERSION ||
@@ -458,6 +474,92 @@ function compactSemanticWire(input: TerminalSemanticDeliveryPayload) {
458
474
  return wire;
459
475
  }
460
476
 
477
+ // History rows the daemon owns are strictly validated once, like patch rows,
478
+ // with the strict schema's own issues; foreign rows are validated every time.
479
+ const HistoryEncodingPayloadSchema = TerminalSemanticHistoryPayloadSchemaZ.extend({
480
+ rows: z.array(CompactPatchEncodingRowSchema).min(1).max(TERMINAL_DELIVERY_HISTORY_CHUNK_MAX_ROWS),
481
+ });
482
+
483
+ /** Capability 122: encode a "history" frame's rows in the negotiated semantic encoding. */
484
+ export function encodeSemanticTerminalHistory(
485
+ input: TerminalSemanticHistoryPayload,
486
+ encoding: "semantic-v1" | "semantic-compact-v1" | "semantic-binary-v1",
487
+ ): Uint8Array {
488
+ const payload = HistoryEncodingPayloadSchema.parse(input);
489
+ if (encoding === "semantic-v1") {
490
+ const bytes = UTF8_ENCODER.encode(canonicalJson(payload));
491
+ assertRepresentationSize(bytes);
492
+ return bytes;
493
+ }
494
+ const rows = compactRows(payload.rows, null, {
495
+ rows: 0,
496
+ runs: 0,
497
+ cells: 0,
498
+ placements: 0,
499
+ maxCells: COMPACT_MAX_EXPANDED_CELLS,
500
+ reusedRows: 0,
501
+ allocatedCells: 0,
502
+ canonicalUtf8Allocations: 0,
503
+ canonicalUtf8Bytes: 0,
504
+ validatedCellAllocations: 0,
505
+ });
506
+ if (encoding === "semantic-compact-v1") {
507
+ const bytes = UTF8_ENCODER.encode(
508
+ JSON.stringify({ f: "h", h: rows, k: COMPACT_SEMANTIC_KIND, r: payload.revision, v: 1 }),
509
+ );
510
+ assertRepresentationSize(bytes);
511
+ return bytes;
512
+ }
513
+ const writer = new BinaryTerminalWriter();
514
+ try {
515
+ writer.header("history", payload.revision);
516
+ writer.value(rows);
517
+ return writer.finish();
518
+ } catch (error) {
519
+ if (error instanceof BinaryTerminalLimitError)
520
+ throw new TerminalDeliveryStateTooLargeError(TERMINAL_DELIVERY_MAX_REPRESENTATION_BYTES + 1);
521
+ throw error;
522
+ }
523
+ }
524
+
525
+ /** Capability 122: decode a "history" frame's rows. */
526
+ export function decodeSemanticTerminalHistory(
527
+ bytes: Uint8Array,
528
+ encoding: "semantic-v1" | "semantic-compact-v1" | "semantic-binary-v1",
529
+ ): TerminalSemanticHistoryPayload {
530
+ if (encoding === "semantic-v1")
531
+ return TerminalSemanticHistoryPayloadSchemaZ.parse(
532
+ JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)),
533
+ );
534
+ const budget = { ...compactDecodeBudget(bytes.length), maxCells: COMPACT_MAX_EXPANDED_CELLS };
535
+ let revision: number;
536
+ let value: unknown;
537
+ if (encoding === "semantic-compact-v1") {
538
+ const wire = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)) as unknown;
539
+ if (
540
+ typeof wire !== "object" ||
541
+ wire === null ||
542
+ Object.keys(wire).join(",") !== "f,h,k,r,v" ||
543
+ (wire as { f: unknown }).f !== "h" ||
544
+ (wire as { k: unknown }).k !== COMPACT_SEMANTIC_KIND ||
545
+ (wire as { v: unknown }).v !== 1
546
+ )
547
+ throw new TypeError("Invalid compact history payload");
548
+ revision = (wire as { r: number }).r;
549
+ value = (wire as { h: unknown }).h;
550
+ } else {
551
+ const decoded = decodeBinaryTerminalTuple(bytes);
552
+ if (decoded.frame !== "history") throw new TypeError("Invalid binary history payload");
553
+ revision = decoded.revision;
554
+ value = decoded.value;
555
+ }
556
+ return TerminalSemanticHistoryPayloadSchemaZ.parse({
557
+ frame: "history",
558
+ revision,
559
+ rows: expandRows(value, budget, null, TERMINAL_DELIVERY_HISTORY_CHUNK_MAX_ROWS, "history"),
560
+ });
561
+ }
562
+
461
563
  export function encodeBinarySemanticTerminalUpdate(
462
564
  input: TerminalSemanticDeliveryPayload,
463
565
  ): Uint8Array {
@@ -1627,6 +1729,8 @@ export function decodeVerifiedCompactSemanticTerminalUpdate(
1627
1729
  options?: {
1628
1730
  readonly grantReducerAdoption?: boolean;
1629
1731
  readonly onComplete?: (profile: CompactSemanticCommitProfile) => void;
1732
+ /** Capability 122: the snapshot holds only loaded history; hash with this commitment. */
1733
+ readonly historyUnloaded?: TerminalDeliveryHistoryCommitment;
1630
1734
  },
1631
1735
  ): Readonly<{
1632
1736
  payload: TerminalSemanticDeliveryPayload;
@@ -1646,7 +1750,9 @@ export function decodeVerifiedCompactSemanticTerminalUpdate(
1646
1750
  })()
1647
1751
  : null;
1648
1752
  const hash = snapshot
1649
- ? hashTerminalReplicaSnapshot(snapshot)
1753
+ ? options?.historyUnloaded
1754
+ ? hashPartialTerminalReplicaSnapshot(snapshot, options.historyUnloaded)
1755
+ : hashTerminalReplicaSnapshot(snapshot)
1650
1756
  : hashTerminalReplicaTombstone(
1651
1757
  payload.frame === "tombstone" ? payload.tombstone.reason : "protocol",
1652
1758
  );
@@ -3184,6 +3290,11 @@ export interface TerminalDeliveryClientState {
3184
3290
  readonly appliedRevision: number;
3185
3291
  readonly appliedHash: string | null;
3186
3292
  readonly canonicalSnapshot: TerminalReplicaSnapshot | null;
3293
+ /**
3294
+ * Capability 122: the history rows `canonicalSnapshot` does not hold, oldest
3295
+ * first. Null when the stream has no partial history.
3296
+ */
3297
+ readonly historyUnloaded: TerminalDeliveryHistoryCommitment | null;
3187
3298
  readonly inFlight: TerminalDeliveryEnvelope | null;
3188
3299
  readonly nextChunk: number;
3189
3300
  readonly receivedBytes: number;
@@ -3205,6 +3316,7 @@ export function createTerminalDeliveryClientState(
3205
3316
  appliedRevision: -1,
3206
3317
  appliedHash: null,
3207
3318
  canonicalSnapshot: null,
3319
+ historyUnloaded: null,
3208
3320
  inFlight: null,
3209
3321
  nextChunk: 0,
3210
3322
  receivedBytes: 0,
@@ -3231,6 +3343,21 @@ export function admitTerminalDeliveryEnvelope(
3231
3343
  state.semanticPaneId !== envelope.semanticPaneId
3232
3344
  )
3233
3345
  return failClient(state);
3346
+ // Capability 122: a partial history only on a stream that negotiated it, and
3347
+ // then on every seed, patch and history frame.
3348
+ if (
3349
+ (envelope.history === "partial") !==
3350
+ (state.negotiated.partialHistory === "tail-v1" && envelope.frame !== "tombstone")
3351
+ )
3352
+ return failClient(state);
3353
+ if (
3354
+ envelope.frame === "history" &&
3355
+ (state.historyUnloaded === null ||
3356
+ state.tombstoned ||
3357
+ envelope.canonicalRevision !== state.appliedRevision ||
3358
+ envelope.canonicalStateHash !== state.appliedHash)
3359
+ )
3360
+ return failClient(state);
3234
3361
  if (envelope.frame === "seed") {
3235
3362
  if (state.tombstoned && state.incarnation === envelope.incarnation) return failClient(state);
3236
3363
  if (
@@ -3389,7 +3516,47 @@ export function commitTerminalDelivery(
3389
3516
  throw new TypeError("Terminal delivery representation hash mismatch");
3390
3517
  let canonicalSnapshot = state.canonicalSnapshot;
3391
3518
  let semanticUpdate: TerminalSemanticDeliveryPayload | null = null;
3392
- if (
3519
+ const historyUnloaded = envelope.historyUnloaded ?? null;
3520
+ if (envelope.frame === "history") {
3521
+ // Capability 122: prepend proven rows; the canonical state is unchanged.
3522
+ if (
3523
+ !canonicalSnapshot ||
3524
+ !state.historyUnloaded ||
3525
+ !historyUnloaded ||
3526
+ envelope.encoding === "ansi-diff-v1" ||
3527
+ envelope.encoding === "ansi-raw-v1"
3528
+ )
3529
+ throw new TypeError("History frame without a partial history");
3530
+ const payload = decodeSemanticTerminalHistory(staged.bytes, envelope.encoding);
3531
+ if (payload.revision !== envelope.canonicalRevision)
3532
+ throw new TypeError("History frame revision mismatch");
3533
+ // The chunk chains to the old commitment, so the whole history's digest,
3534
+ // and with it the canonical hash, is the one this state was verified
3535
+ // against. Verify and freeze only the new rows: O(chunk), not O(loaded).
3536
+ if (envelope.canonicalStateHash !== state.appliedHash)
3537
+ throw new TypeError("Canonical state hash mismatch");
3538
+ const cols = canonicalSnapshot.cols;
3539
+ const added = payload.rows.map((row) => {
3540
+ if (row.cells.length !== cols) throw new TypeError("Malformed terminal replica row");
3541
+ return freezeTerminalReplicaRow(row);
3542
+ });
3543
+ const prepended = prependVerifiedTerminalHistory(
3544
+ canonicalSnapshot,
3545
+ state.historyUnloaded,
3546
+ added,
3547
+ historyUnloaded,
3548
+ );
3549
+ canonicalSnapshot = Object.freeze({
3550
+ ...prepended,
3551
+ history: Object.freeze(prepended.history),
3552
+ }) as TerminalReplicaSnapshot;
3553
+ } else if (
3554
+ historyUnloaded &&
3555
+ envelope.frame === "patch" &&
3556
+ (!state.historyUnloaded || historyUnloaded.rows > state.historyUnloaded.rows)
3557
+ ) {
3558
+ throw new TypeError("A patch cannot add unloaded history rows");
3559
+ } else if (
3393
3560
  envelope.encoding === "semantic-v1" ||
3394
3561
  envelope.encoding === "semantic-compact-v1" ||
3395
3562
  envelope.encoding === "semantic-binary-v1"
@@ -3402,6 +3569,7 @@ export function commitTerminalDelivery(
3402
3569
  staged.bytes,
3403
3570
  canonicalSnapshot,
3404
3571
  envelope.canonicalStateHash,
3572
+ historyUnloaded ? { historyUnloaded } : undefined,
3405
3573
  ).payload
3406
3574
  : decodeSemanticTerminalUpdate(staged.bytes);
3407
3575
  semanticUpdate = payload;
@@ -3427,7 +3595,9 @@ export function commitTerminalDelivery(
3427
3595
  canonicalSnapshot = applyTerminalReplicaPatch(canonicalSnapshot, payload.patch);
3428
3596
  } else canonicalSnapshot = null;
3429
3597
  const hash = canonicalSnapshot
3430
- ? hashTerminalReplicaSnapshot(canonicalSnapshot)
3598
+ ? historyUnloaded
3599
+ ? hashPartialTerminalReplicaSnapshot(canonicalSnapshot, historyUnloaded)
3600
+ : hashTerminalReplicaSnapshot(canonicalSnapshot)
3431
3601
  : hashTerminalReplicaTombstone(
3432
3602
  payload.frame === "tombstone" ? payload.tombstone.reason : "protocol",
3433
3603
  );
@@ -3445,6 +3615,7 @@ export function commitTerminalDelivery(
3445
3615
  appliedRevision: envelope.canonicalRevision,
3446
3616
  appliedHash: envelope.canonicalStateHash,
3447
3617
  canonicalSnapshot,
3618
+ historyUnloaded: envelope.frame === "tombstone" ? null : historyUnloaded,
3448
3619
  tombstoned: envelope.frame === "tombstone",
3449
3620
  inFlight: null,
3450
3621
  nextChunk: 0,
@@ -0,0 +1,152 @@
1
+ import {
2
+ TERMINAL_HISTORY_EMPTY_DIGEST,
3
+ type TerminalDeliveryHistoryCommitment,
4
+ type TerminalReplicaRow,
5
+ type TerminalReplicaSnapshot,
6
+ } from "@tmux-ide/contracts";
7
+ import {
8
+ concatTerminalReplicaRowsDigest,
9
+ dropTerminalReplicaRowsDigestPrefix,
10
+ popTerminalReplicaRowsDigestSuffix,
11
+ hashTerminalReplicaRows,
12
+ hashTerminalReplicaSnapshotWithHistoryDigest,
13
+ } from "./terminal-replica.ts";
14
+
15
+ /**
16
+ * History on demand (capability 122). A client holds the newest history rows
17
+ * and a commitment `{rows, digest}` to the older rows it has not loaded. The
18
+ * rows digest is a polynomial fold, so the commitment plus the loaded rows give
19
+ * the whole history's digest and the snapshot verifies against the full
20
+ * canonical state hash.
21
+ */
22
+
23
+ /** H(A ++ B) from H(A) and B. */
24
+ export function concatTerminalHistoryDigest(
25
+ prefixDigest: string,
26
+ suffix: readonly TerminalReplicaRow[],
27
+ ): string {
28
+ return concatTerminalReplicaRowsDigest(prefixDigest, suffix);
29
+ }
30
+
31
+ /** Frozen histories are immutable: a prefix digest computed once is reused. */
32
+ const PREFIX_COMMITMENTS = new WeakMap<
33
+ readonly TerminalReplicaRow[],
34
+ Map<number, TerminalDeliveryHistoryCommitment>
35
+ >();
36
+
37
+ /** The commitment to the oldest `unloadedRows` rows of a history (O(unloaded), cached). */
38
+ export function terminalHistoryPrefixCommitment(
39
+ history: readonly TerminalReplicaRow[],
40
+ unloadedRows: number,
41
+ ): TerminalDeliveryHistoryCommitment {
42
+ if (!Number.isSafeInteger(unloadedRows) || unloadedRows < 0 || unloadedRows > history.length)
43
+ throw new RangeError("Unloaded rows outside the history");
44
+ const cache = Object.isFrozen(history) ? PREFIX_COMMITMENTS.get(history) : undefined;
45
+ const cached = cache?.get(unloadedRows);
46
+ if (cached) return cached;
47
+ const commitment = Object.freeze({
48
+ rows: unloadedRows,
49
+ digest: hashTerminalReplicaRows(
50
+ unloadedRows === history.length ? history : history.slice(0, unloadedRows),
51
+ ),
52
+ });
53
+ if (Object.isFrozen(history)) {
54
+ const entries = cache ?? new Map<number, TerminalDeliveryHistoryCommitment>();
55
+ if (entries.size >= 8) entries.delete(entries.keys().next().value!);
56
+ entries.set(unloadedRows, commitment);
57
+ PREFIX_COMMITMENTS.set(history, entries);
58
+ }
59
+ return commitment;
60
+ }
61
+
62
+ /** The commitment once its oldest rows `dropped` are trimmed away: O(|dropped|). */
63
+ export function dropTerminalHistoryCommitmentPrefix(
64
+ commitment: TerminalDeliveryHistoryCommitment,
65
+ dropped: readonly TerminalReplicaRow[],
66
+ ): TerminalDeliveryHistoryCommitment {
67
+ if (dropped.length > commitment.rows) throw new RangeError("Dropped rows exceed the commitment");
68
+ const rows = commitment.rows - dropped.length;
69
+ return Object.freeze({
70
+ rows,
71
+ digest:
72
+ rows === 0
73
+ ? TERMINAL_HISTORY_EMPTY_DIGEST
74
+ : dropTerminalReplicaRowsDigestPrefix(commitment.digest, dropped, rows),
75
+ });
76
+ }
77
+
78
+ /** The commitment once its newest rows `taken` are sent as a chunk: O(|taken|). */
79
+ export function popTerminalHistoryCommitmentSuffix(
80
+ commitment: TerminalDeliveryHistoryCommitment,
81
+ taken: readonly TerminalReplicaRow[],
82
+ ): TerminalDeliveryHistoryCommitment {
83
+ if (taken.length > commitment.rows) throw new RangeError("Taken rows exceed the commitment");
84
+ const rows = commitment.rows - taken.length;
85
+ return Object.freeze({
86
+ rows,
87
+ digest:
88
+ rows === 0
89
+ ? TERMINAL_HISTORY_EMPTY_DIGEST
90
+ : popTerminalReplicaRowsDigestSuffix(commitment.digest, taken),
91
+ });
92
+ }
93
+
94
+ /** The canonical hash of a snapshot holding only its loaded history rows. */
95
+ export function hashPartialTerminalReplicaSnapshot(
96
+ snapshot: TerminalReplicaSnapshot,
97
+ unloaded: TerminalDeliveryHistoryCommitment,
98
+ ): string {
99
+ return hashTerminalReplicaSnapshotWithHistoryDigest(
100
+ snapshot,
101
+ concatTerminalHistoryDigest(unloaded.digest, snapshot.history),
102
+ );
103
+ }
104
+
105
+ /** Keep the newest `tailRows` history rows; commit to the rest. */
106
+ export function splitTerminalHistory(
107
+ snapshot: TerminalReplicaSnapshot,
108
+ tailRows: number,
109
+ ): { snapshot: TerminalReplicaSnapshot; unloaded: TerminalDeliveryHistoryCommitment } {
110
+ const unloadedRows = Math.max(0, snapshot.history.length - Math.max(0, Math.floor(tailRows)));
111
+ return {
112
+ snapshot:
113
+ unloadedRows === 0
114
+ ? snapshot
115
+ : { ...snapshot, history: snapshot.history.slice(unloadedRows) },
116
+ unloaded: terminalHistoryPrefixCommitment(snapshot.history, unloadedRows),
117
+ };
118
+ }
119
+
120
+ /** The newest `maxRows` rows of the unloaded part, oldest first, and what stays unloaded. */
121
+ export function takeTerminalHistoryChunk(
122
+ history: readonly TerminalReplicaRow[],
123
+ unloadedRows: number,
124
+ maxRows: number,
125
+ ): { rows: readonly TerminalReplicaRow[]; unloaded: TerminalDeliveryHistoryCommitment } {
126
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1) throw new RangeError("Invalid chunk size");
127
+ const remaining = Math.max(0, unloadedRows - maxRows);
128
+ return {
129
+ rows: history.slice(remaining, unloadedRows),
130
+ unloaded: terminalHistoryPrefixCommitment(history, remaining),
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Prepend a history chunk after proving it: the old commitment must equal the
136
+ * new commitment extended by exactly these rows.
137
+ */
138
+ export function prependVerifiedTerminalHistory(
139
+ snapshot: TerminalReplicaSnapshot,
140
+ unloaded: TerminalDeliveryHistoryCommitment,
141
+ rows: readonly TerminalReplicaRow[],
142
+ next: TerminalDeliveryHistoryCommitment,
143
+ ): TerminalReplicaSnapshot {
144
+ if (
145
+ rows.length === 0 ||
146
+ (next.rows === 0 && next.digest !== TERMINAL_HISTORY_EMPTY_DIGEST) ||
147
+ next.rows + rows.length !== unloaded.rows ||
148
+ concatTerminalHistoryDigest(next.digest, rows) !== unloaded.digest
149
+ )
150
+ throw new TypeError("The history chunk does not match the unloaded commitment");
151
+ return { ...snapshot, history: [...rows, ...snapshot.history] };
152
+ }
@@ -43,6 +43,13 @@ const ROW_ARRAY_HASH_CACHE = new WeakMap<
43
43
  { readonly hash: bigint; readonly length: number }
44
44
  >();
45
45
  const ROW_SEQUENCE_BASE = 0x100000001b3n;
46
+ /** ROW_SEQUENCE_BASE⁻¹ mod 2^64 (Newton's iteration; the base is odd). */
47
+ const ROW_SEQUENCE_BASE_INVERSE = (() => {
48
+ let inverse = ROW_SEQUENCE_BASE;
49
+ for (let step = 0; step < 6; step++)
50
+ inverse = BigInt.asUintN(64, inverse * (2n - ROW_SEQUENCE_BASE * inverse));
51
+ return inverse;
52
+ })();
46
53
 
47
54
  export interface TerminalReplicaState extends TerminalReplicaAddress {
48
55
  readonly generation: SessionRuntimeGeneration;
@@ -782,10 +789,72 @@ export function hashTerminalReplicaSnapshot(snapshot: TerminalReplicaSnapshot):
782
789
  return hashTerminalReplicaSnapshotProfiled(snapshot);
783
790
  }
784
791
 
792
+ /**
793
+ * Capability 122: the canonical hash of a snapshot whose `history` holds only
794
+ * the newest rows, given the digest of the whole history (see
795
+ * concatTerminalReplicaRowsDigest). Equal to the full snapshot's hash.
796
+ */
797
+ export function hashTerminalReplicaSnapshotWithHistoryDigest(
798
+ snapshot: TerminalReplicaSnapshot,
799
+ historyDigest: string,
800
+ ): string {
801
+ return hashTerminalReplicaSnapshotProfiled(snapshot, undefined, undefined, historyDigest);
802
+ }
803
+
804
+ /**
805
+ * The rows digest is a polynomial fold, H(A ++ B) = H(A)·P^|B| + H(B) mod 2^64,
806
+ * so the digest of older rows extends by newer rows without the older ones.
807
+ */
808
+ export function concatTerminalReplicaRowsDigest(
809
+ prefixDigest: string,
810
+ suffix: readonly TerminalReplicaRow[],
811
+ ): string {
812
+ if (!/^[0-9a-f]{16}$/u.test(prefixDigest)) throw new TypeError("Invalid rows digest");
813
+ const hash = BigInt.asUintN(
814
+ 64,
815
+ BigInt(`0x${prefixDigest}`) * pow64(ROW_SEQUENCE_BASE, suffix.length) +
816
+ BigInt(`0x${hashTerminalReplicaRows(suffix)}`),
817
+ );
818
+ return hash.toString(16).padStart(16, "0");
819
+ }
820
+
821
+ /**
822
+ * H(B) from H(A ++ B) and A: the digest left after dropping the oldest rows
823
+ * A of a rows sequence of `remaining` + |A| rows. H(A ++ B) = H(A)·P^|B| + H(B).
824
+ */
825
+ export function dropTerminalReplicaRowsDigestPrefix(
826
+ digest: string,
827
+ prefix: readonly TerminalReplicaRow[],
828
+ remaining: number,
829
+ ): string {
830
+ if (!/^[0-9a-f]{16}$/u.test(digest)) throw new TypeError("Invalid rows digest");
831
+ const hash = BigInt.asUintN(
832
+ 64,
833
+ BigInt(`0x${digest}`) -
834
+ BigInt(`0x${hashTerminalReplicaRows(prefix)}`) * pow64(ROW_SEQUENCE_BASE, remaining),
835
+ );
836
+ return hash.toString(16).padStart(16, "0");
837
+ }
838
+
839
+ /** H(A) from H(A ++ B) and B: P is odd, so P^|B| is invertible mod 2^64. */
840
+ export function popTerminalReplicaRowsDigestSuffix(
841
+ digest: string,
842
+ suffix: readonly TerminalReplicaRow[],
843
+ ): string {
844
+ if (!/^[0-9a-f]{16}$/u.test(digest)) throw new TypeError("Invalid rows digest");
845
+ const hash = BigInt.asUintN(
846
+ 64,
847
+ (BigInt(`0x${digest}`) - BigInt(`0x${hashTerminalReplicaRows(suffix)}`)) *
848
+ pow64(ROW_SEQUENCE_BASE_INVERSE, suffix.length),
849
+ );
850
+ return hash.toString(16).padStart(16, "0");
851
+ }
852
+
785
853
  function hashTerminalReplicaSnapshotProfiled(
786
854
  snapshot: TerminalReplicaSnapshot,
787
855
  profile?: MutableTerminalReplicaApplyProfile,
788
856
  instrumentation?: TerminalReplicaApplyOptions["instrumentation"],
857
+ historyDigest?: string,
789
858
  ): string {
790
859
  // Cross-language Merkle stream: each immutable row is FNV-1a over the
791
860
  // type-tagged UTF-8 cell stream, then the snapshot hashes fixed-order row
@@ -797,7 +866,7 @@ function hashTerminalReplicaSnapshotProfiled(
797
866
  snapshot.cols,
798
867
  snapshot.rows,
799
868
  hashTerminalReplicaRows(snapshot.grid, profile, instrumentation),
800
- hashTerminalReplicaRows(snapshot.history, profile, instrumentation),
869
+ historyDigest ?? hashTerminalReplicaRows(snapshot.history, profile, instrumentation),
801
870
  snapshot.cursor,
802
871
  snapshot.modes,
803
872
  snapshot.placements,
@@ -0,0 +1,30 @@
1
+ import { ownerBearerMatches } from "./owner-authority.js";
2
+ /**
3
+ * How long an owner-authenticated HTTP connection may sit idle before the
4
+ * daemon closes it. Node's default is 5 s, so a native app that paused for
5
+ * longer found its proven connection gone; over SSH every replacement costs
6
+ * a channel open and an identity proof (attach-rtt). The app keeps an idle
7
+ * connection for at most 60 s, below this.
8
+ */
9
+ export const OWNER_KEEP_ALIVE_MS = 65_000;
10
+ /**
11
+ * After a response to the owner bearer, keep that connection open for
12
+ * `timeoutMs` while idle. Every other connection keeps Node's default.
13
+ * Node arms its own keep-alive timer when the response finishes; this runs
14
+ * after it and replaces the bound for this socket only. The next request on
15
+ * the socket clears the timer as usual.
16
+ */
17
+ export function ownerKeepAlive(ownerToken, timeoutMs = OWNER_KEEP_ALIVE_MS) {
18
+ return async (c, next) => {
19
+ const bindings = c.env;
20
+ const outgoing = bindings?.outgoing;
21
+ const socket = bindings?.incoming?.socket;
22
+ if (outgoing && socket && ownerBearerMatches(c.req.header("Authorization"), ownerToken)) {
23
+ outgoing.once("finish", () => {
24
+ if (!socket.destroyed && outgoing.shouldKeepAlive)
25
+ socket.setTimeout(timeoutMs);
26
+ });
27
+ }
28
+ await next();
29
+ };
30
+ }
@@ -1,5 +1,5 @@
1
- import { TERMINAL_RUNTIME_INVENTORY_RESOURCE_VERSION, TerminalRuntimeInventoryProjectionV1SchemaZ, } from "@tmux-ide/contracts";
2
- import { projectApplicationShellResource } from "./application-shell.js";
1
+ import { TERMINAL_RUNTIME_INVENTORY_RESOURCE_VERSION, TerminalRuntimeInventoryProjectionV1SchemaZ, TerminalRuntimeInventoryProjectionV2SchemaZ, } from "@tmux-ide/contracts";
2
+ import { paneIdentities, projectApplicationShellResource } from "./application-shell.js";
3
3
  /** Pure, wire-safe agent-free topology projection. */
4
4
  export function projectTerminalRuntimeInventory(session, resourceRevision) {
5
5
  const shell = projectApplicationShellResource(session);
@@ -15,6 +15,46 @@ export function projectTerminalRuntimeInventory(session, resourceRevision) {
15
15
  ].sort(),
16
16
  });
17
17
  }
18
+ /**
19
+ * #806: version 1 plus each window and its panes, in tmux order. A window is
20
+ * named only when it has a verified window stamp and every pane in it is
21
+ * available, so its pane set is one a window-scoped issue can accept.
22
+ */
23
+ export function projectTerminalRuntimeInventoryV2(session, resourceRevision) {
24
+ const identities = paneIdentities(session);
25
+ const windows = new Map();
26
+ session.panes.forEach((pane, index) => {
27
+ if (pane.windowId === undefined)
28
+ return;
29
+ const stamp = pane.windowStamp ?? null;
30
+ const entry = windows.get(pane.windowId) ?? {
31
+ semanticWindowId: stamp,
32
+ active: false,
33
+ panes: [],
34
+ complete: true,
35
+ };
36
+ windows.set(pane.windowId, entry);
37
+ const attachability = identities[index].attachability;
38
+ if (attachability.status === "available")
39
+ entry.panes.push(attachability.semanticPaneId);
40
+ else
41
+ entry.complete = false;
42
+ if (pane.active)
43
+ entry.active = true;
44
+ });
45
+ return TerminalRuntimeInventoryProjectionV2SchemaZ.parse({
46
+ ...projectTerminalRuntimeInventory(session, resourceRevision),
47
+ windows: [...windows.values()].flatMap((window) => window.complete && window.semanticWindowId !== null && window.panes.length > 0
48
+ ? [
49
+ {
50
+ semanticWindowId: window.semanticWindowId,
51
+ active: window.active,
52
+ semanticPaneIds: [...window.panes].sort(),
53
+ },
54
+ ]
55
+ : []),
56
+ });
57
+ }
18
58
  export function terminalRuntimeInventoryEnvelope(daemon, session, resourceRevision) {
19
59
  return {
20
60
  version: TERMINAL_RUNTIME_INVENTORY_RESOURCE_VERSION,
@@ -68,6 +68,7 @@ import { mountWorkspaceResourceRoutes } from "./resources/workspace-resource-rou
68
68
  import { mountFleetResourceRoute } from "./resources/fleet-resource-route.js";
69
69
  import { mountWorkspaceMissionsRoute } from "./resources/workspace-missions-route.js";
70
70
  import { ownerAuthorityGate, requireOwnerAuthority } from "./owner-authority.js";
71
+ import { ownerKeepAlive } from "./owner-keep-alive.js";
71
72
  import { mountDiagnosticsRoute } from "./diagnostics.js";
72
73
  import { mountStartupReadinessRoute, } from "./resources/startup-readiness-route.js";
73
74
  import { readWidgetAsset } from "../lib/widget-asset-store.js";
@@ -338,6 +339,8 @@ export function createApp(options = {}) {
338
339
  const app = new Hono();
339
340
  // Allow cross-origin (Next.js dashboard, Tailscale, etc.)
340
341
  app.use("/*", cors());
342
+ // An owner connection stays open while idle for longer than Node's 5 s.
343
+ app.use("/*", ownerKeepAlive(options.remoteAccess?.ownerToken ?? null));
341
344
  if (options.tmuxServerOwners) {
342
345
  mountAutomationRoutes(app, {
343
346
  ownerToken: options.remoteAccess?.ownerToken ?? null,
@@ -0,0 +1,51 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * One request that opens a session, reads its inventory and issues its stream
4
+ * (attach-rtt). Before it the app sent three: open, inventory, issue. The app
5
+ * still checks the answer: it applies its own window rule to the returned
6
+ * inventory and uses the issued stream only when the daemon chose the same.
7
+ *
8
+ * `issue` is the body of an ordinary pane-stream issue request without the
9
+ * workspace name, the panes and the window, which only the daemon knows here.
10
+ */
11
+ export const TmuxServerAttachRequestSchemaZ = z
12
+ .object({
13
+ version: z.literal(1),
14
+ preferredPane: z.string().min(1).max(128).nullable(),
15
+ maxPanes: z.number().int().min(1).max(256),
16
+ issue: z
17
+ .object({
18
+ expectedDaemonInstanceId: z.uuid(),
19
+ stream: z.record(z.string(), z.unknown()),
20
+ })
21
+ .catchall(z.unknown()),
22
+ })
23
+ .strict();
24
+ /**
25
+ * The app's rule (browser_native_local_window.rs `scope`), here so the open
26
+ * and the issue can be one request: a session that fits streams whole;
27
+ * otherwise the window holding the preferred pane (else the active one) when
28
+ * it fits, else the active one, else the first in tmux order that fits. No
29
+ * selection when there is no pane or nothing fits: the app decides then.
30
+ */
31
+ export function chooseAttachSelection(inventory, preferredPane, maxPanes) {
32
+ const panes = inventory.semanticPaneIds;
33
+ if (panes.length === 0)
34
+ return null;
35
+ let semanticWindowId = null;
36
+ let chosen = panes;
37
+ if (panes.length > maxPanes) {
38
+ const fits = (window) => window !== undefined && window.semanticPaneIds.length <= maxPanes;
39
+ const active = inventory.windows.find((window) => window.active);
40
+ const wanted = (preferredPane !== null
41
+ ? inventory.windows.find((window) => window.semanticPaneIds.includes(preferredPane))
42
+ : undefined) ?? active;
43
+ const window = [wanted, active].find(fits) ?? inventory.windows.find(fits);
44
+ if (!window)
45
+ return null;
46
+ semanticWindowId = window.semanticWindowId;
47
+ chosen = window.semanticPaneIds;
48
+ }
49
+ const selectedPane = preferredPane !== null && chosen.includes(preferredPane) ? preferredPane : chosen[0];
50
+ return { semanticWindowId, panes: chosen, selectedPane };
51
+ }