@zergai/ztc 0.25.0-beta.1 → 0.26.0-beta.1

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 (38) hide show
  1. package/README.md +70 -0
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/app/emergency_exit.d.ts +14 -0
  8. package/dist/app/emergency_exit.js +36 -0
  9. package/dist/app/layout_change.d.ts +20 -0
  10. package/dist/app/layout_change.js +14 -0
  11. package/dist/app/workspace_topology.d.ts +8 -0
  12. package/dist/app/workspace_topology.js +8 -0
  13. package/dist/cli_main.js +2 -24
  14. package/dist/cli_ratatui.d.ts +70 -1
  15. package/dist/cli_ratatui.js +259 -53
  16. package/dist/desktop/daily/status_restore.js +6 -2
  17. package/dist/mcp/workspace_server.js +9 -2
  18. package/dist/ui/core/input_segments.d.ts +15 -0
  19. package/dist/ui/core/input_segments.js +22 -0
  20. package/dist/ui/core/layout_yoga.d.ts +7 -0
  21. package/dist/ui/core/layout_yoga.js +16 -0
  22. package/dist/ui/ratatui/owner_ping.d.ts +24 -0
  23. package/dist/ui/ratatui/owner_ping.js +18 -0
  24. package/dist/ui/ratatui/process.d.ts +2 -2
  25. package/dist/ui/ratatui/protocol.d.ts +80 -3
  26. package/dist/ui/ratatui/protocol.js +58 -0
  27. package/dist/ui/scrollback.d.ts +24 -0
  28. package/dist/ui/scrollback.js +53 -18
  29. package/dist/ui/terminal_image.js +17 -1
  30. package/dist/ui/transcript_bound.d.ts +41 -0
  31. package/dist/ui/transcript_bound.js +100 -0
  32. package/dist/ui/transcript_render_cache.d.ts +15 -4
  33. package/dist/ui/transcript_render_cache.js +39 -16
  34. package/dist/ui/views/app.js +3 -2
  35. package/dist/ui/views/input_area.d.ts +1 -0
  36. package/dist/ui/views/input_area.js +34 -8
  37. package/dist/zlm-embed.mjs +1 -1
  38. package/package.json +17 -9
@@ -1,4 +1,26 @@
1
1
  export const PASTE_BADGE_THRESHOLD = 4;
2
+ /**
3
+ * A paste this long is a badge whatever its line count (LS4). The composer wraps all of its text on every render to
4
+ * show the rows around the cursor, about 0.8 µs a character: a one-line paste of 2 MiB (a token, minified JSON, base64)
5
+ * made every render take 1.7 s. A paste shorter than this stays text the person can edit: a URL or a key, and a task of
6
+ * the desktop queue, which edits a task as text up to 64 KiB and keeps all of a longer one. This is twice that, so a
7
+ * render takes at most about 0.1 s for the text.
8
+ */
9
+ export const PASTE_BADGE_CHARS = 128 * 1024;
10
+ /** Whether a paste of `text` goes into the composer as a badge rather than as text. */
11
+ export function pasteBecomesBadge(text) {
12
+ return text.length >= PASTE_BADGE_CHARS || countLines(text, PASTE_BADGE_THRESHOLD) >= PASTE_BADGE_THRESHOLD;
13
+ }
14
+ /**
15
+ * How many lines `text` holds, its newlines and one, counted no further than `atMost`. A paste can hold millions of
16
+ * lines and the composer counts them on every render, where splitting it made a string of every line.
17
+ */
18
+ export function countLines(text, atMost = Number.POSITIVE_INFINITY) {
19
+ let lines = 1;
20
+ for (let at = text.indexOf('\n'); at !== -1 && lines < atMost; at = text.indexOf('\n', at + 1))
21
+ lines += 1;
22
+ return lines;
23
+ }
2
24
  export function normalizeSegments(segments) {
3
25
  const normalized = [];
4
26
  for (const segment of segments) {
@@ -16,4 +16,11 @@ export declare function measureText(node: TextNode, width?: number): {
16
16
  width: number;
17
17
  height: number;
18
18
  };
19
+ /**
20
+ * `frame` as ZTC writes it to its renderer: each box's node without its children, which the frame's own children are.
21
+ * computeLayout keeps every node whole, for the TypeScript that reads a frame either way; written as it is, each text
22
+ * goes out again at every level of the layout above it, and a render with a paste badge in the composer held five
23
+ * copies of the badge's text (LS2). Every renderer walks the frame's children.
24
+ */
25
+ export declare function frameForRenderer(frame: LayoutFrame): LayoutFrame;
19
26
  export declare function computeLayout(root: LayoutNode, width: number, height?: number): LayoutFrame;
@@ -115,6 +115,22 @@ function buildFrameTree(node, yogaNode) {
115
115
  children
116
116
  };
117
117
  }
118
+ /**
119
+ * `frame` as ZTC writes it to its renderer: each box's node without its children, which the frame's own children are.
120
+ * computeLayout keeps every node whole, for the TypeScript that reads a frame either way; written as it is, each text
121
+ * goes out again at every level of the layout above it, and a render with a paste badge in the composer held five
122
+ * copies of the badge's text (LS2). Every renderer walks the frame's children.
123
+ */
124
+ export function frameForRenderer(frame) {
125
+ return {
126
+ node: frame.node.type === 'box' ? { type: 'box', style: frame.node.style, children: [] } : frame.node,
127
+ x: frame.x,
128
+ y: frame.y,
129
+ width: frame.width,
130
+ height: frame.height,
131
+ children: frame.children.map(frameForRenderer),
132
+ };
133
+ }
118
134
  export function computeLayout(root, width, height) {
119
135
  const yogaRoot = buildYogaTree(root);
120
136
  yogaRoot.setWidth(width);
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The owner's liveness check (robustness spec P3a-0, RB5): ZTC pings a renderer that advertises owner_ping_v1 every 2 s,
3
+ * as ztc-core's Command::Ping says. ZTerm's socket reader answers each ping with pong at once, whatever its window is
4
+ * doing, and ZTerm takes an owner that has pinged and then goes 10 s without a ping (owner_watch.rs PING_SILENCE) for one
5
+ * that hangs: its banner says "ZTC (the agent runtime) isn't responding. Your panes keep running." and offers End ZTC
6
+ * (keeps panes). The pings run on ZTC's own event loop, so they stop exactly when it does; a ZTC that is only busy for
7
+ * less than ZTerm's silence keeps the banner away.
8
+ */
9
+ import type { OwnerPingCommand } from './protocol.js';
10
+ /** A renderer whose socket reader answers `ping` with `pong` at once (ZTerm 0.26). */
11
+ export declare const CAPABILITY_OWNER_PING = "owner_ping_v1";
12
+ /** How often the owner pings such a renderer: every 2 s, five pings to ZTerm's 10 s of silence. */
13
+ export declare const OWNER_PING_INTERVAL_MS = 2000;
14
+ /** What the pings need of the renderer's transport. */
15
+ export interface OwnerPingTransport {
16
+ hasCapability(name: string): boolean;
17
+ send(command: OwnerPingCommand): boolean;
18
+ }
19
+ /**
20
+ * Pings TRANSPORT's renderer every INTERVAL_MS while it advertises owner_ping_v1, each ping numbered after the last,
21
+ * from 1. A renderer that doesn't advertise it, such as zmux, ztc-tui or an older ZTerm, gets none, and a renderer that
22
+ * replaces it is asked again at each tick. The timer never keeps the process alive. Returns the function that stops it.
23
+ */
24
+ export declare function startOwnerPing(transport: OwnerPingTransport, intervalMs?: number): () => void;
@@ -0,0 +1,18 @@
1
+ /** A renderer whose socket reader answers `ping` with `pong` at once (ZTerm 0.26). */
2
+ export const CAPABILITY_OWNER_PING = 'owner_ping_v1';
3
+ /** How often the owner pings such a renderer: every 2 s, five pings to ZTerm's 10 s of silence. */
4
+ export const OWNER_PING_INTERVAL_MS = 2000;
5
+ /**
6
+ * Pings TRANSPORT's renderer every INTERVAL_MS while it advertises owner_ping_v1, each ping numbered after the last,
7
+ * from 1. A renderer that doesn't advertise it, such as zmux, ztc-tui or an older ZTerm, gets none, and a renderer that
8
+ * replaces it is asked again at each tick. The timer never keeps the process alive. Returns the function that stops it.
9
+ */
10
+ export function startOwnerPing(transport, intervalMs = OWNER_PING_INTERVAL_MS) {
11
+ let seq = 0;
12
+ const timer = setInterval(() => {
13
+ if (transport.hasCapability(CAPABILITY_OWNER_PING))
14
+ transport.send({ type: 'ping', seq: ++seq });
15
+ }, intervalMs);
16
+ timer.unref();
17
+ return () => clearInterval(timer);
18
+ }
@@ -8,7 +8,7 @@
8
8
  * When mux mode is enabled, zmux is spawned instead of ztc-tui. zmux provides
9
9
  * a fullscreen multiplexer with split panes (alternate screen mode).
10
10
  */
11
- import type { RustCommand, RustEvent } from './protocol.js';
11
+ import type { OwnerPingCommand, RustCommand, RustEvent } from './protocol.js';
12
12
  import { type DesktopRuntime } from '../../desktop/runtime.js';
13
13
  export type TuiEventHandler = (event: RustEvent) => void;
14
14
  /**
@@ -219,7 +219,7 @@ export declare class TuiProcess {
219
219
  /**
220
220
  * Send a command to the Rust process via socket
221
221
  */
222
- send(cmd: RustCommand): boolean;
222
+ send(cmd: RustCommand | OwnerPingCommand): boolean;
223
223
  /**
224
224
  * Check if the process is running and ready
225
225
  */
@@ -17,6 +17,12 @@ export interface ScrollbackLine {
17
17
  * `scrollback_anchor` capability ignore the field.
18
18
  */
19
19
  message_id?: string;
20
+ /**
21
+ * This row goes on from the row before it inside a word ZTC broke there (a soft wrap): its text goes on at this
22
+ * column, after the indent the rows share. The desktop app joins such rows to open a URL broken over them whole;
23
+ * zmux, ztc-tui and older desktop apps ignore it.
24
+ */
25
+ continues_from?: number;
20
26
  }
21
27
  /**
22
28
  * Logical anchor into the transcript for scroll-position preservation
@@ -145,6 +151,11 @@ export interface PaneInfo {
145
151
  activity_label?: string;
146
152
  /** Absent from renderers that don't track bells and notifications. */
147
153
  attention?: PaneAttention;
154
+ /**
155
+ * The place of the pane's tab in the strip, 1 for the first: the tab Cmd+1 reaches. At most 64. The strip runs in the
156
+ * order the person gave the tabs, not in the order of their ids. Absent from a renderer that doesn't report it.
157
+ */
158
+ tab_place?: number;
148
159
  /**
149
160
  * The agent CLI a command pane runs, which the renderer doesn't know: set by the main ZTC's pane relay on the pane
150
161
  * lists it passes to its children (PaneRelayServer's agentCliOf), from the panes it opened as agent panes.
@@ -191,6 +202,7 @@ export interface MuxWindowState {
191
202
  export interface MuxSessionState {
192
203
  schema_version?: 1;
193
204
  active_window_id?: number;
205
+ /** In the strip's order: no field holds it, so nothing that saves or restores the state may sort them. */
194
206
  windows?: MuxWindowState[];
195
207
  geometry?: {
196
208
  cols?: number;
@@ -438,6 +450,42 @@ export interface WindowClosedEvent {
438
450
  /** Why it refused, in the renderer's words. */
439
451
  message?: string;
440
452
  }
453
+ /** Who moved: the person, inside the renderer, or a command. */
454
+ export type LayoutChangedBy = 'person' | 'command';
455
+ export declare const LAYOUT_CHANGED_BY: readonly LayoutChangedBy[];
456
+ /** What came of a move: it changed the layout, it would have changed nothing, or it was refused (the message says why). */
457
+ export type LayoutChangeOutcome = 'changed' | 'unchanged' | 'refused';
458
+ export declare const LAYOUT_CHANGE_OUTCOMES: readonly LayoutChangeOutcome[];
459
+ /** What a move changed. */
460
+ export type LayoutChange = 'pane_moved' | 'panes_swapped' | 'tab_moved';
461
+ export declare const LAYOUT_CHANGES: readonly LayoutChange[];
462
+ /** The tabs a layout_changed's order lists at most: the most a workspace keeps. */
463
+ export declare const LAYOUT_CHANGED_MAX_TAB_ORDER = 64;
464
+ /** The bytes a layout_changed's message holds at most; its request id holds as many. */
465
+ export declare const LAYOUT_CHANGED_MAX_TEXT_BYTES = 256;
466
+ /**
467
+ * The renderer's report of a move: a pane went to another place, or a tab to another place in the strip, by the person's
468
+ * drag, keys or menus, or by a command (the legacy set_pane_window and swap_pane). Sent after the pane_state that shows
469
+ * it. A tab the move emptied is named in closed_window_id and gets no window_closed: treat it as closed.
470
+ */
471
+ export interface LayoutChangedEvent {
472
+ type: 'layout_changed';
473
+ request_id?: string;
474
+ by: LayoutChangedBy;
475
+ outcome: LayoutChangeOutcome;
476
+ change?: LayoutChange;
477
+ pane_id?: number;
478
+ /** A swap's other pane. */
479
+ with_pane_id?: number;
480
+ /** The pane's tab now, or the tab moved. */
481
+ window_id?: number;
482
+ /** The tab the move emptied, which closed. */
483
+ closed_window_id?: number;
484
+ /** The strip after the move, in its order. */
485
+ tab_order: number[];
486
+ /** Why nothing moved, in the renderer's words. */
487
+ message?: string;
488
+ }
441
489
  export type RustCommand = {
442
490
  type: 'render';
443
491
  frame: LayoutFrame;
@@ -458,6 +506,11 @@ export type RustCommand = {
458
506
  type: 'replace_scrollback_with_anchor';
459
507
  lines: ScrollbackLine[];
460
508
  anchor?: TranscriptAnchor;
509
+ /**
510
+ * How many rows of the first line's message ZTC left out ahead of it: ZTC ships only the rows the renderer keeps
511
+ * (ui/transcript_bound.ts), and anchors count rows within the whole message. Absent when nothing was left out.
512
+ */
513
+ head_line_offset?: number;
461
514
  } | {
462
515
  type: 'resize_fence';
463
516
  width: number;
@@ -676,6 +729,15 @@ export type RustCommand = {
676
729
  type: 'set_wheel_capture';
677
730
  active: boolean;
678
731
  };
732
+ /**
733
+ * The owner's liveness check, every 2 s, to a renderer that advertises owner_ping_v1 (owner_ping.ts): its socket reader
734
+ * answers at once with `pong` and the same `seq`. Not a RustCommand: only the owner's own connection carries one, so the
735
+ * pane relay, whose table classifies every RustCommand, refuses it from a child as a command it doesn't know.
736
+ */
737
+ export type OwnerPingCommand = {
738
+ type: 'ping';
739
+ seq: number;
740
+ };
679
741
  export type RustEvent = DesktopTaskAction | DesktopRuntimeAction | DesktopSessionShareAction | {
680
742
  type: 'ready';
681
743
  version: string;
@@ -709,10 +771,13 @@ export type RustEvent = DesktopTaskAction | DesktopRuntimeAction | DesktopSessio
709
771
  request_id: string;
710
772
  text: string | null;
711
773
  error?: string | null;
712
- } | {
774
+ }
775
+ /** `code` names a refusal (RZ0): `busy`, `expired`, `too_long` (a command line over the renderer's cap), and others. */
776
+ | {
713
777
  type: 'error';
714
778
  message: string;
715
779
  request_id?: string;
780
+ code?: string;
716
781
  } | {
717
782
  type: 'quit_requested';
718
783
  } | {
@@ -826,7 +891,7 @@ export type RustEvent = DesktopTaskAction | DesktopRuntimeAction | DesktopSessio
826
891
  } | {
827
892
  type: 'window_switched';
828
893
  window_id: number;
829
- } | WindowClosedEvent | {
894
+ } | WindowClosedEvent | LayoutChangedEvent | {
830
895
  type: 'show_pane_picker';
831
896
  } | {
832
897
  type: 'show_new_pane_picker';
@@ -845,11 +910,16 @@ export type RustEvent = DesktopTaskAction | DesktopRuntimeAction | DesktopSessio
845
910
  } | {
846
911
  type: 'mirror_detached';
847
912
  reason?: string;
913
+ } | {
914
+ type: 'pong';
915
+ seq: number;
916
+ ui_oldest_ms: number;
917
+ out_bytes: number;
848
918
  };
849
919
  /**
850
920
  * Serialize a command to JSON for sending to Rust
851
921
  */
852
- export declare function serializeCommand(cmd: RustCommand): string;
922
+ export declare function serializeCommand(cmd: RustCommand | OwnerPingCommand): string;
853
923
  /**
854
924
  * Parse an event from Rust
855
925
  */
@@ -861,6 +931,13 @@ export declare function parseEvent(json: string): RustEvent | null;
861
931
  * as null.
862
932
  */
863
933
  export declare function isWindowClosed(value: unknown): value is WindowClosedEvent;
934
+ /**
935
+ * Whether VALUE is a well-formed layout_changed: integer ids a u32 holds; an order of at most 64 distinct tabs; a mover,
936
+ * outcome and change among those ZTerm sends; a request id of 1 to 256 bytes and a message of at most 256, neither with a
937
+ * control character. Only the keys it knows are checked: a newer renderer's own are ignored (workspace spec §13). An absent
938
+ * field may come as null.
939
+ */
940
+ export declare function isLayoutChanged(value: unknown): value is LayoutChangedEvent;
864
941
  /** Sharing intents carry only bounded identities and an explicit save destination. */
865
942
  export declare function isDesktopSessionShareAction(value: unknown): value is DesktopSessionShareAction;
866
943
  /**
@@ -57,6 +57,13 @@ export const WINDOW_CLOSE_OUTCOMES = Object.freeze(['closed', 'partly_closed', '
57
57
  export const WINDOW_CLOSED_MAX_PANE_IDS = 1024;
58
58
  /** The bytes window_closed's message holds at most; its request id holds as many. */
59
59
  export const WINDOW_CLOSED_MAX_TEXT_BYTES = 256;
60
+ export const LAYOUT_CHANGED_BY = Object.freeze(['person', 'command']);
61
+ export const LAYOUT_CHANGE_OUTCOMES = Object.freeze(['changed', 'unchanged', 'refused']);
62
+ export const LAYOUT_CHANGES = Object.freeze(['pane_moved', 'panes_swapped', 'tab_moved']);
63
+ /** The tabs a layout_changed's order lists at most: the most a workspace keeps. */
64
+ export const LAYOUT_CHANGED_MAX_TAB_ORDER = 64;
65
+ /** The bytes a layout_changed's message holds at most; its request id holds as many. */
66
+ export const LAYOUT_CHANGED_MAX_TEXT_BYTES = 256;
60
67
  // ============================================================================
61
68
  // Serialization helpers
62
69
  // ============================================================================
@@ -83,6 +90,8 @@ export function parseEvent(json) {
83
90
  return null;
84
91
  if (parsed.type === 'window_closed')
85
92
  return isWindowClosed(parsed) ? windowClosedFields(parsed) : null;
93
+ if (parsed.type === 'layout_changed')
94
+ return isLayoutChanged(parsed) ? layoutChangedFields(parsed) : null;
86
95
  return parsed;
87
96
  }
88
97
  catch {
@@ -132,6 +141,55 @@ function windowClosedFields(event) {
132
141
  ...(typeof message === 'string' ? { message } : {}),
133
142
  };
134
143
  }
144
+ /** Text of at most LAYOUT_CHANGED_MAX_TEXT_BYTES, with no C0 or C1 control. */
145
+ function isLayoutChangedText(value) {
146
+ return typeof value === 'string' && Buffer.byteLength(value, 'utf8') <= LAYOUT_CHANGED_MAX_TEXT_BYTES
147
+ && !/[\u0000-\u001f\u007f-\u009f]/.test(value);
148
+ }
149
+ /** An absent id, which may come as null, or one a u32 holds. */
150
+ function isOptionalU32(value) {
151
+ return value === undefined || value === null || isU32(value);
152
+ }
153
+ /**
154
+ * Whether VALUE is a well-formed layout_changed: integer ids a u32 holds; an order of at most 64 distinct tabs; a mover,
155
+ * outcome and change among those ZTerm sends; a request id of 1 to 256 bytes and a message of at most 256, neither with a
156
+ * control character. Only the keys it knows are checked: a newer renderer's own are ignored (workspace spec §13). An absent
157
+ * field may come as null.
158
+ */
159
+ export function isLayoutChanged(value) {
160
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
161
+ return false;
162
+ const event = value;
163
+ const order = event.tab_order;
164
+ return event.type === 'layout_changed'
165
+ && LAYOUT_CHANGED_BY.includes(event.by)
166
+ && LAYOUT_CHANGE_OUTCOMES.includes(event.outcome)
167
+ && (event.change === undefined || event.change === null || LAYOUT_CHANGES.includes(event.change))
168
+ && isOptionalU32(event.pane_id) && isOptionalU32(event.with_pane_id)
169
+ && isOptionalU32(event.window_id) && isOptionalU32(event.closed_window_id)
170
+ && Array.isArray(order) && order.length <= LAYOUT_CHANGED_MAX_TAB_ORDER && order.every(isU32)
171
+ && new Set(order).size === order.length
172
+ && (event.request_id === undefined || event.request_id === null
173
+ || (isLayoutChangedText(event.request_id) && event.request_id.length > 0))
174
+ && (event.message === undefined || event.message === null || isLayoutChangedText(event.message));
175
+ }
176
+ /** EVENT's known fields alone, leaving out those that came as null. */
177
+ function layoutChangedFields(event) {
178
+ const field = (key) => (event[key] === undefined || event[key] === null ? {} : { [key]: event[key] });
179
+ return {
180
+ type: 'layout_changed',
181
+ ...field('request_id'),
182
+ by: event.by,
183
+ outcome: event.outcome,
184
+ ...field('change'),
185
+ ...field('pane_id'),
186
+ ...field('with_pane_id'),
187
+ ...field('window_id'),
188
+ ...field('closed_window_id'),
189
+ tab_order: [...event.tab_order],
190
+ ...field('message'),
191
+ };
192
+ }
135
193
  /** Sharing intents carry only bounded identities and an explicit save destination. */
136
194
  export function isDesktopSessionShareAction(value) {
137
195
  if (value === null || typeof value !== 'object' || Array.isArray(value))
@@ -25,6 +25,12 @@ export interface ScrollbackBodyOptions {
25
25
  readout?: boolean;
26
26
  }
27
27
  export { displayWidth, normalizeTranscriptText, padEndDisplay };
28
+ /** A row `wordWrapAnsiRows` wrapped a line into. */
29
+ export interface WrappedRow {
30
+ text: string;
31
+ /** It goes on from the row before inside a word too long for a row: nothing between the two was left out. */
32
+ continues: boolean;
33
+ }
28
34
  /**
29
35
  * ANSI-aware word wrap. Splits text into lines whose display width does
30
36
  * not exceed `width`, preserving SGR state across line breaks: each line
@@ -33,6 +39,12 @@ export { displayWidth, normalizeTranscriptText, padEndDisplay };
33
39
  * hard-broken at the display-width boundary.
34
40
  */
35
41
  export declare function wordWrapAnsi(text: string, width: number): string[];
42
+ /**
43
+ * `text` wrapped as `wordWrapAnsi` wraps it, each row saying whether it goes on from the row before inside a word the
44
+ * wrap broke there (a soft wrap): a word too long for a row breaks with nothing left out, while a wrap at a space
45
+ * leaves the space out and a new line starts a row of its own.
46
+ */
47
+ export declare function wordWrapAnsiRows(text: string, width: number): WrappedRow[];
36
48
  /** A styled line for the scrollback buffer. */
37
49
  export interface ScrollbackLine {
38
50
  text: string;
@@ -47,7 +59,19 @@ export interface ScrollbackLine {
47
59
  * anchor across a rebuild. Phase 4 of always-scrolling rollout.
48
60
  */
49
61
  message_id?: string;
62
+ /**
63
+ * This row goes on from the row before it, inside a word too long for a row that the wrap broke there, so nothing
64
+ * between the two rows was left out: its text goes on at this column, after the indent the rows share. Absent for a
65
+ * row that starts a line, or that a wrap at a space starts. The desktop app joins such rows to open a URL whole.
66
+ */
67
+ continues_from?: number;
50
68
  }
69
+ /**
70
+ * Appends `rows` to `target` one by one. A message's rows can number in the hundreds of thousands (a pasted list, a
71
+ * table, a run of tool calls expanded), and `target.push(...rows)` passes each row as an argument: past about 110,000
72
+ * of them V8 throws `RangeError: Maximum call stack size exceeded`.
73
+ */
74
+ export declare function appendRows(target: ScrollbackLine[], rows: readonly ScrollbackLine[]): void;
51
75
  export declare function messageHeaderToScrollbackLine(message: Message, formatTime: (date: Date) => string, cols?: number, showTurnMetadata?: boolean): ScrollbackLine;
52
76
  /**
53
77
  * Highlight plan for a tool-trace message body, or undefined for any other
@@ -157,12 +157,20 @@ function toWrapUnits(tokens) {
157
157
  * hard-broken at the display-width boundary.
158
158
  */
159
159
  export function wordWrapAnsi(text, width) {
160
+ return wordWrapAnsiRows(text, width).map(row => row.text);
161
+ }
162
+ /**
163
+ * `text` wrapped as `wordWrapAnsi` wraps it, each row saying whether it goes on from the row before inside a word the
164
+ * wrap broke there (a soft wrap): a word too long for a row breaks with nothing left out, while a wrap at a space
165
+ * leaves the space out and a new line starts a row of its own.
166
+ */
167
+ export function wordWrapAnsiRows(text, width) {
160
168
  if (width <= 0)
161
- return [text];
169
+ return [{ text, continues: false }];
162
170
  const result = [];
163
171
  for (const paragraph of text.split('\n')) {
164
172
  if (displayWidth(paragraph) <= width) {
165
- result.push(paragraph);
173
+ result.push({ text: paragraph, continues: false });
166
174
  continue;
167
175
  }
168
176
  // Tokenize into text and ANSI escape segments.
@@ -183,6 +191,8 @@ export function wordWrapAnsi(text, width) {
183
191
  let line = '';
184
192
  let lineWidth = 0;
185
193
  let activeSgr = '';
194
+ // The row being built goes on from the row before, inside a word broken there.
195
+ let continues = false;
186
196
  const trackSgr = (token) => {
187
197
  if (token === '\x1b[0m')
188
198
  activeSgr = '';
@@ -195,7 +205,8 @@ export function wordWrapAnsi(text, width) {
195
205
  // trailing space that the reader would still copy.
196
206
  const visible = line.trimEnd();
197
207
  const closed = activeSgr && !visible.endsWith('\x1b[0m') ? visible + '\x1b[0m' : visible;
198
- result.push(closed);
208
+ result.push({ text: closed, continues });
209
+ continues = false;
199
210
  // Re-open SGR on next line.
200
211
  line = activeSgr;
201
212
  lineWidth = 0;
@@ -225,6 +236,9 @@ export function wordWrapAnsi(text, width) {
225
236
  line += buffered;
226
237
  lineWidth += bufferedWidth;
227
238
  flushLine();
239
+ // The next row goes on inside the word. A run of blanks broken here
240
+ // loses the ones the row it ends trims, so only a word goes on.
241
+ continues = !unit.whitespace;
228
242
  buffered = char;
229
243
  bufferedWidth = charWidth;
230
244
  }
@@ -258,11 +272,20 @@ export function wordWrapAnsi(text, width) {
258
272
  }
259
273
  if (line.length > 0) {
260
274
  const closed = activeSgr && !line.endsWith('\x1b[0m') ? line + '\x1b[0m' : line;
261
- result.push(closed.trimEnd());
275
+ result.push({ text: closed.trimEnd(), continues });
262
276
  }
263
277
  }
264
278
  return result;
265
279
  }
280
+ /**
281
+ * Appends `rows` to `target` one by one. A message's rows can number in the hundreds of thousands (a pasted list, a
282
+ * table, a run of tool calls expanded), and `target.push(...rows)` passes each row as an argument: past about 110,000
283
+ * of them V8 throws `RangeError: Maximum call stack size exceeded`.
284
+ */
285
+ export function appendRows(target, rows) {
286
+ for (const row of rows)
287
+ target.push(row);
288
+ }
266
289
  function sgr(text, color, options = {}) {
267
290
  const attrs = `${options.bold ? '\x1b[1m' : ''}${options.dim ? '\x1b[2m' : ''}`;
268
291
  return `${sgrForeground(color)}${attrs}${text}\x1b[0m`;
@@ -356,10 +379,11 @@ export function messageToScrollbackLines(message, formatTime, cols, options = {}
356
379
  const wrapWidth = cols > 0
357
380
  ? Math.max(8, bodyRowWidth(cols, '') - RECAP_CONTINUATION_INDENT.length)
358
381
  : 66;
359
- const wrappedLines = wordWrapAnsi(content, wrapWidth);
360
- return stamp(wrappedLines.map((line, index) => ({
361
- text: `${index === 0 ? RECAP_PREFIX : RECAP_CONTINUATION_INDENT}${line}`,
382
+ const wrappedLines = wordWrapAnsiRows(content, wrapWidth);
383
+ return stamp(wrappedLines.map((row, index) => ({
384
+ text: `${index === 0 ? RECAP_PREFIX : RECAP_CONTINUATION_INDENT}${row.text}`,
362
385
  style: { color: TERMINAL_THEME.muted, dimColor: true },
386
+ ...(row.continues ? { continues_from: displayWidth(RECAP_CONTINUATION_INDENT) } : {}),
363
387
  })));
364
388
  }
365
389
  // Assistant responses should retain the same markdown polish the
@@ -388,7 +412,7 @@ export function messageToScrollbackLines(message, formatTime, cols, options = {}
388
412
  bodyLines[i] = { ...bodyLines[i], style: { ...bodyLines[i].style, dimColor: true } };
389
413
  }
390
414
  }
391
- bodyLines.push(...imagesToScrollback(message, imageTokens.paths, cols));
415
+ appendRows(bodyLines, imagesToScrollback(message, imageTokens.paths, cols));
392
416
  // Phase 7: streaming messages show a blinking cursor at the end of
393
417
  // the last body line (matches live Ink render " ▌"). When the message
394
418
  // has no body yet (just started), emit the cursor as a standalone
@@ -617,8 +641,7 @@ export function renderBodyToScrollback(content, isToolTrace, cols, options = {})
617
641
  let tableBuffer = [];
618
642
  const flushTable = () => {
619
643
  if (tableBuffer.length > 0) {
620
- const tableLines = renderTableToScrollback(tableBuffer, cols, indent);
621
- result.push(...tableLines);
644
+ appendRows(result, renderTableToScrollback(tableBuffer, cols, indent));
622
645
  tableBuffer = [];
623
646
  }
624
647
  };
@@ -632,9 +655,14 @@ export function renderBodyToScrollback(content, isToolTrace, cols, options = {})
632
655
  const body = text.slice(leadingWhitespaceLength(text));
633
656
  const prefix = indent + nesting;
634
657
  const width = cols > 0 ? Math.max(1, bodyRowWidth(cols, indent) - displayWidth(prefix)) : 0;
635
- const chunks = width > 0 ? wordWrapAnsi(body, width) : [body];
658
+ const chunks = width > 0 ? wordWrapAnsiRows(body, width) : [{ text: body, continues: false }];
636
659
  for (const chunk of chunks) {
637
- result.push({ text: prefix + chunk, ...(style ? { style } : {}) });
660
+ result.push({
661
+ text: prefix + chunk.text,
662
+ ...(style ? { style } : {}),
663
+ // A row going on inside a word it broke goes on after the prefix it repeats.
664
+ ...(chunk.continues ? { continues_from: displayWidth(prefix) } : {}),
665
+ });
638
666
  }
639
667
  };
640
668
  /**
@@ -738,24 +766,28 @@ export function renderMarkdownToScrollback(content, cols = 0, options = {}) {
738
766
  if (pushOptions.maxWidth !== undefined) {
739
767
  width = width > 0 ? Math.min(width, pushOptions.maxWidth) : pushOptions.maxWidth;
740
768
  }
741
- const chunks = width > 0 ? wordWrapAnsi(body, width) : [body];
769
+ const chunks = width > 0 ? wordWrapAnsiRows(body, width) : [{ text: body, continues: false }];
742
770
  for (let index = 0; index < chunks.length; index++) {
743
771
  // A frame row fills its inner width and is closed by the right border, so
744
772
  // a short line still draws a complete box and a wrapped one keeps the
745
773
  // border on every continuation row.
746
774
  const text = pushOptions.closeFrame === undefined
747
- ? (index === 0 ? prefix : hang) + chunks[index]
748
- : padEndDisplay((index === 0 ? prefix : hang) + chunks[index], displayWidth(hang) + pushOptions.closeFrame) + FRAME_BORDER;
775
+ ? (index === 0 ? prefix : hang) + chunks[index].text
776
+ : padEndDisplay((index === 0 ? prefix : hang) + chunks[index].text, displayWidth(hang) + pushOptions.closeFrame) + FRAME_BORDER;
777
+ // A row going on inside a word it broke goes on after its hang; a frame
778
+ // row's border and padding sit between it and the row before, so the
779
+ // rows of a code block never say they go on.
780
+ const continues = chunks[index].continues && pushOptions.closeFrame === undefined;
749
781
  result.push({
750
782
  text,
751
783
  ...(style ? { style } : {}),
784
+ ...(continues ? { continues_from: displayWidth(hang) } : {}),
752
785
  });
753
786
  }
754
787
  };
755
788
  const flushTable = () => {
756
789
  if (tableBuffer.length > 0) {
757
- const tableLines = renderTableToScrollback(tableBuffer, cols, indent);
758
- result.push(...tableLines);
790
+ appendRows(result, renderTableToScrollback(tableBuffer, cols, indent));
759
791
  tableBuffer = [];
760
792
  }
761
793
  };
@@ -983,7 +1015,10 @@ export function renderTableToScrollback(tableLines, cols, indent = MESSAGE_BODY_
983
1015
  }
984
1016
  if (rows.length === 0)
985
1017
  return result;
986
- const colCount = Math.max(...rows.map(r => r.length));
1018
+ // A loop, not Math.max(...): a pasted table can hold more rows than a call takes arguments.
1019
+ let colCount = 0;
1020
+ for (const row of rows)
1021
+ colCount = Math.max(colCount, row.length);
987
1022
  const colWidths = new Array(colCount).fill(0);
988
1023
  for (const row of rows) {
989
1024
  for (let i = 0; i < row.length; i++) {
@@ -43,6 +43,13 @@ const MAX_HELD_GRAPHIC_BYTES = 128 * 1024 * 1024;
43
43
  const MAX_PLACEMENTS = 1024;
44
44
  /** The renderer refuses larger images; ZTC's previews stay far below it. */
45
45
  const MAX_GRAPHIC_SIDE = 8192;
46
+ /**
47
+ * The most pixels one upload carries, whatever the cell size: base64 of their deflated RGBA, which deflate may not
48
+ * shrink at all, then stays within the 16 MiB a command line of ZTC's carries (ui/transcript_bound.ts), a quarter of
49
+ * the renderers' cap. An 80 x 20-cell box of cells as large as 30 x 62 pixels holds fewer, so this binds only past
50
+ * that, where the terminal scales the image to its placement anyway.
51
+ */
52
+ const MAX_GRAPHIC_PIXELS = 3_000_000;
46
53
  const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
47
54
  /** Decode a PNG, JPEG or GIF (first frame). Anything else, or corrupt data, is null. */
48
55
  export function decodeImage(bytes) {
@@ -255,7 +262,16 @@ function thumbnailOf(key, bytes) {
255
262
  }
256
263
  /** The pixels for the largest box the transcript places an image in; the terminal scales them to each placement. */
257
264
  function kittyGraphic(image) {
258
- const fitted = fit(image, Math.min(MAX_GRAPHIC_SIDE, TRANSCRIPT_IMAGE_MAX_COLS * cellPixels.width), Math.min(MAX_GRAPHIC_SIDE, TRANSCRIPT_IMAGE_MAX_ROWS * cellPixels.height));
265
+ let maxWidth = Math.min(MAX_GRAPHIC_SIDE, TRANSCRIPT_IMAGE_MAX_COLS * cellPixels.width);
266
+ let maxHeight = Math.min(MAX_GRAPHIC_SIDE, TRANSCRIPT_IMAGE_MAX_ROWS * cellPixels.height);
267
+ const scale = Math.min(1, maxWidth / image.width, maxHeight / image.height);
268
+ const area = image.width * scale * image.height * scale;
269
+ if (area > MAX_GRAPHIC_PIXELS) {
270
+ const shrink = Math.sqrt(MAX_GRAPHIC_PIXELS / area);
271
+ maxWidth = Math.max(1, Math.floor(image.width * scale * shrink));
272
+ maxHeight = Math.max(1, Math.floor(image.height * scale * shrink));
273
+ }
274
+ const fitted = fit(image, maxWidth, maxHeight);
259
275
  const pixels = Buffer.from(fitted.data.buffer, fitted.data.byteOffset, fitted.data.byteLength);
260
276
  return { width: fitted.width, height: fitted.height, data: deflateSync(pixels).toString('base64') };
261
277
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What ZTC ships its renderer of Main's transcript (robustness spec VR2, RZ1, RX1).
3
+ *
4
+ * ZTerm and zmux keep the last 10,000 rows of the transcript (ZTerm's SCROLLBACK_LINES, zmux's MAX_SCROLLBACK) and
5
+ * drop any command line over 64 MiB with `too_long`. Shipping the whole transcript in every rebuild took 24 MB for a
6
+ * day-long session with its tool outputs expanded, and past the cap every rebuild was refused while Main stopped
7
+ * updating. So ZTC ships only the rows the renderer keeps, with `head_line_offset` saying how many rows of the first
8
+ * one's message it left out, as the renderer would have trimmed them itself; and at most TRANSCRIPT_LINE_BUDGET bytes
9
+ * of them, a quarter of the renderers' cap. Rows the budget leaves out that the renderer would have kept are never
10
+ * left out silently: the first row shipped says how many.
11
+ */
12
+ import type { ScrollbackLine } from './ratatui/protocol.js';
13
+ /** The rows of Main's transcript ZTerm and zmux keep: ZTerm's SCROLLBACK_LINES and zmux's MAX_SCROLLBACK. */
14
+ export declare const RENDERER_TRANSCRIPT_ROWS = 10000;
15
+ /**
16
+ * The most bytes ZTC ships of its transcript in one command line: a quarter of ZTerm's and zmux's 64 MiB line cap.
17
+ * The last 10,000 rows of a measured day-long session serialize to at most 5.1 MB; the rows that pass the budget are
18
+ * rows of images, 3.4 KB each at most.
19
+ */
20
+ export declare const TRANSCRIPT_LINE_BUDGET: number;
21
+ /** The smallest budget a renderer's too_long refusals halve ZTC's to. */
22
+ export declare const MIN_TRANSCRIPT_LINE_BUDGET: number;
23
+ export interface BoundedTranscript {
24
+ /** The rows to ship: the newest the renderer keeps, after a notice of the rows the budget left out, if any. */
25
+ lines: ScrollbackLine[];
26
+ /** How many rows of the first shipped row's message are left out ahead of it. */
27
+ headLineOffset: number;
28
+ /** The rows the budget left out that the renderer would have kept, which the first row tells of. */
29
+ overBudget: number;
30
+ }
31
+ /** `bytes` as people read sizes: MiB, KiB or bytes. */
32
+ export declare function sizeName(bytes: number): string;
33
+ /**
34
+ * The part of `lines` to ship a renderer that keeps `rows` rows, in a command line of at most `bytes` bytes: the newest
35
+ * `rows` rows, less the oldest of them while the line would pass `bytes`, those then told of by a first row of their
36
+ * own. That row takes the place of the last row left out of its message, so the message's rows keep their count.
37
+ */
38
+ export declare function boundTranscript(lines: ScrollbackLine[], limits: {
39
+ rows: number;
40
+ bytes: number;
41
+ }): BoundedTranscript;