The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | retainedTerminalHistory, |
| 3 | TERMINAL_SEQUENCE_GROUND, |
| 4 | terminalSequenceEnd, |
| 5 | terminalSequenceStateAfter, |
| 6 | } from "@t3tools/contracts"; |
| 7 | |
| 8 | export interface TerminalOutputChunk { |
| 9 | readonly startOffset: number; |
| 10 | readonly data: string; |
| 11 | readonly byteLength: number; |
| 12 | } |
| 13 | |
| 14 | export interface TerminalOutputState { |
| 15 | readonly generation: number; |
| 16 | readonly chunks: ReadonlyArray<TerminalOutputChunk>; |
| 17 | readonly retainedBytes: number; |
| 18 | readonly resetVersion: number; |
| 19 | readonly nextOffset: number; |
| 20 | // The terminal parser's state at the first retained code unit. Trimming can cut a control |
| 21 | // sequence, and a replay has to skip the rest of it instead of printing it. |
| 22 | readonly sequenceState: number; |
| 23 | /** Chunks before this offset are replayed to emulators but are no longer displayed text. */ |
| 24 | readonly textStartOffset: number; |
| 25 | } |
| 26 | |
| 27 | export interface TerminalOutputCursor { |
| 28 | readonly generation: number; |
| 29 | readonly resetVersion: number; |
| 30 | readonly offset: number; |
| 31 | // The cut control sequence still open at `offset`, which the reader's terminal never entered. |
| 32 | readonly sequenceState: number; |
| 33 | } |
| 34 | |
| 35 | export const INITIAL_TERMINAL_OUTPUT_CURSOR = Object.freeze<TerminalOutputCursor>({ |
| 36 | generation: -1, |
| 37 | resetVersion: -1, |
| 38 | offset: 0, |
| 39 | sequenceState: TERMINAL_SEQUENCE_GROUND, |
| 40 | }); |
| 41 | |
| 42 | export type TerminalOutputUpdate = |
| 43 | | { |
| 44 | readonly type: "none"; |
| 45 | readonly cursor: TerminalOutputCursor; |
| 46 | } |
| 47 | | { |
| 48 | readonly type: "reset"; |
| 49 | readonly data: string; |
| 50 | readonly cursor: TerminalOutputCursor; |
| 51 | } |
| 52 | | { |
| 53 | readonly type: "append"; |
| 54 | readonly cursor: TerminalOutputCursor; |
| 55 | readonly data: string; |
| 56 | }; |
| 57 | |
| 58 | const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024; |
| 59 | const MAX_TERMINAL_OUTPUT_CHUNKS = 1_024; |
| 60 | const textEncoder = new TextEncoder(); |
| 61 | // A BOM at a retained chunk boundary is terminal data, not an encoding marker. |
| 62 | const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); |
| 63 | |
| 64 | export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze<TerminalOutputState>({ |
| 65 | generation: 0, |
| 66 | chunks: Object.freeze([]), |
| 67 | retainedBytes: 0, |
| 68 | resetVersion: 0, |
| 69 | nextOffset: 0, |
| 70 | sequenceState: TERMINAL_SEQUENCE_GROUND, |
| 71 | textStartOffset: 0, |
| 72 | }); |
| 73 | |
| 74 | interface Utf8Chunk { |
| 75 | readonly data: string; |
| 76 | readonly byteLength: number; |
| 77 | } |
| 78 | |
| 79 | function splitStringByUtf8Bytes(data: string, maxBytes: number): ReadonlyArray<Utf8Chunk> { |
| 80 | if (data.length === 0) return []; |
| 81 | |
| 82 | const encoded = textEncoder.encode(data); |
| 83 | if (encoded.byteLength <= maxBytes) { |
| 84 | return [{ data, byteLength: encoded.byteLength }]; |
| 85 | } |
| 86 | |
| 87 | const chunks: Utf8Chunk[] = []; |
| 88 | let offset = 0; |
| 89 | while (offset < encoded.byteLength) { |
| 90 | let end = Math.min(offset + maxBytes, encoded.byteLength); |
| 91 | while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) { |
| 92 | end -= 1; |
| 93 | } |
| 94 | // A degenerate budget smaller than one code point still has to advance: |
| 95 | // include the whole code point rather than looping forever. |
| 96 | if (end === offset) { |
| 97 | end = Math.min(offset + maxBytes, encoded.byteLength); |
| 98 | while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) { |
| 99 | end += 1; |
| 100 | } |
| 101 | } |
| 102 | const bytes = encoded.subarray(offset, end); |
| 103 | chunks.push({ data: textDecoder.decode(bytes), byteLength: bytes.byteLength }); |
| 104 | offset = end; |
| 105 | } |
| 106 | |
| 107 | return chunks; |
| 108 | } |
| 109 | |
| 110 | function splitOutputChunks( |
| 111 | data: string, |
| 112 | firstOffset: number, |
| 113 | maxChunkBytes = DEFAULT_TERMINAL_CHUNK_BYTES, |
| 114 | ): { |
| 115 | readonly chunks: ReadonlyArray<TerminalOutputChunk>; |
| 116 | readonly nextOffset: number; |
| 117 | readonly byteLength: number; |
| 118 | } { |
| 119 | const split = splitStringByUtf8Bytes(data, maxChunkBytes); |
| 120 | let byteLength = 0; |
| 121 | let nextOffset = firstOffset; |
| 122 | const chunks = split.map((chunk) => { |
| 123 | byteLength += chunk.byteLength; |
| 124 | const startOffset = nextOffset; |
| 125 | nextOffset += chunk.data.length; |
| 126 | return { |
| 127 | startOffset, |
| 128 | data: chunk.data, |
| 129 | byteLength: chunk.byteLength, |
| 130 | }; |
| 131 | }); |
| 132 | |
| 133 | return { |
| 134 | chunks, |
| 135 | nextOffset, |
| 136 | byteLength, |
| 137 | }; |
| 138 | } |
| 139 | |
| 140 | function compactRetainedChunks(chunks: ReadonlyArray<TerminalOutputChunk>) { |
| 141 | const compacted: TerminalOutputChunk[] = []; |
| 142 | for (const chunk of chunks) { |
| 143 | const previous = compacted.at(-1); |
| 144 | if ( |
| 145 | previous !== undefined && |
| 146 | previous.startOffset + previous.data.length === chunk.startOffset && |
| 147 | previous.byteLength + chunk.byteLength <= DEFAULT_TERMINAL_CHUNK_BYTES |
| 148 | ) { |
| 149 | compacted[compacted.length - 1] = { |
| 150 | startOffset: previous.startOffset, |
| 151 | data: `${previous.data}${chunk.data}`, |
| 152 | byteLength: previous.byteLength + chunk.byteLength, |
| 153 | }; |
| 154 | } else { |
| 155 | compacted.push(chunk); |
| 156 | } |
| 157 | } |
| 158 | return compacted; |
| 159 | } |
| 160 | |
| 161 | function trimOutputChunkStart( |
| 162 | chunk: TerminalOutputChunk, |
| 163 | bytesToDrop: number, |
| 164 | ): TerminalOutputChunk { |
| 165 | let offset = 0; |
| 166 | let droppedBytes = 0; |
| 167 | while (droppedBytes < bytesToDrop && offset < chunk.data.length) { |
| 168 | const codepoint = chunk.data.codePointAt(offset)!; |
| 169 | droppedBytes += codepoint <= 0x7f ? 1 : codepoint <= 0x7ff ? 2 : codepoint <= 0xffff ? 3 : 4; |
| 170 | offset += codepoint <= 0xffff ? 1 : 2; |
| 171 | } |
| 172 | return { |
| 173 | ...chunk, |
| 174 | startOffset: chunk.startOffset + offset, |
| 175 | data: chunk.data.slice(offset), |
| 176 | byteLength: chunk.byteLength - droppedBytes, |
| 177 | }; |
| 178 | } |
| 179 | |
| 180 | function appendOutput( |
| 181 | current: TerminalOutputState, |
| 182 | data: string, |
| 183 | maxBufferBytes: number, |
| 184 | ): TerminalOutputState { |
| 185 | if (data.length === 0) return current; |
| 186 | if (maxBufferBytes <= 0) { |
| 187 | return { |
| 188 | generation: current.generation, |
| 189 | chunks: [], |
| 190 | retainedBytes: 0, |
| 191 | resetVersion: current.resetVersion + 1, |
| 192 | nextOffset: current.nextOffset + data.length, |
| 193 | sequenceState: TERMINAL_SEQUENCE_GROUND, |
| 194 | textStartOffset: current.textStartOffset, |
| 195 | }; |
| 196 | } |
| 197 | const appended = splitOutputChunks( |
| 198 | data, |
| 199 | current.nextOffset, |
| 200 | Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), |
| 201 | ); |
| 202 | |
| 203 | const chunks = [...current.chunks, ...appended.chunks]; |
| 204 | let retainedBytes = current.retainedBytes + appended.byteLength; |
| 205 | let sequenceState = current.sequenceState; |
| 206 | let firstRetainedIndex = 0; |
| 207 | while (retainedBytes > maxBufferBytes && firstRetainedIndex < chunks.length) { |
| 208 | const first = chunks[firstRetainedIndex]!; |
| 209 | const bytesToDrop = retainedBytes - maxBufferBytes; |
| 210 | if (bytesToDrop < first.byteLength) { |
| 211 | const trimmed = trimOutputChunkStart(first, bytesToDrop); |
| 212 | sequenceState = terminalSequenceStateAfter( |
| 213 | sequenceState, |
| 214 | first.data, |
| 215 | 0, |
| 216 | first.data.length - trimmed.data.length, |
| 217 | ); |
| 218 | retainedBytes -= first.byteLength - trimmed.byteLength; |
| 219 | if (trimmed.byteLength > 0) { |
| 220 | chunks[firstRetainedIndex] = trimmed; |
| 221 | } else { |
| 222 | firstRetainedIndex += 1; |
| 223 | } |
| 224 | break; |
| 225 | } |
| 226 | sequenceState = terminalSequenceStateAfter(sequenceState, first.data); |
| 227 | retainedBytes -= first.byteLength; |
| 228 | firstRetainedIndex += 1; |
| 229 | } |
| 230 | |
| 231 | let retainedChunks = firstRetainedIndex === 0 ? chunks : chunks.slice(firstRetainedIndex); |
| 232 | if (retainedChunks.length > MAX_TERMINAL_OUTPUT_CHUNKS) { |
| 233 | retainedChunks = compactRetainedChunks(retainedChunks); |
| 234 | const excessChunks = retainedChunks.length - MAX_TERMINAL_OUTPUT_CHUNKS; |
| 235 | if (excessChunks > 0) { |
| 236 | for (const chunk of retainedChunks.slice(0, excessChunks)) { |
| 237 | sequenceState = terminalSequenceStateAfter(sequenceState, chunk.data); |
| 238 | retainedBytes -= chunk.byteLength; |
| 239 | } |
| 240 | retainedChunks = retainedChunks.slice(excessChunks); |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | return { |
| 245 | generation: current.generation, |
| 246 | chunks: retainedChunks, |
| 247 | retainedBytes, |
| 248 | resetVersion: current.resetVersion, |
| 249 | nextOffset: appended.nextOffset, |
| 250 | sequenceState, |
| 251 | textStartOffset: current.textStartOffset, |
| 252 | }; |
| 253 | } |
| 254 | |
| 255 | function resetOutput( |
| 256 | current: TerminalOutputState, |
| 257 | data: string, |
| 258 | maxBufferBytes: number, |
| 259 | ): TerminalOutputState { |
| 260 | const retained = retainedTerminalHistory(data, maxBufferBytes); |
| 261 | const reset = splitOutputChunks( |
| 262 | retained, |
| 263 | 0, |
| 264 | Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), |
| 265 | ); |
| 266 | return { |
| 267 | generation: current.generation, |
| 268 | chunks: reset.chunks, |
| 269 | retainedBytes: reset.byteLength, |
| 270 | resetVersion: current.resetVersion + 1, |
| 271 | nextOffset: reset.nextOffset, |
| 272 | sequenceState: TERMINAL_SEQUENCE_GROUND, |
| 273 | textStartOffset: 0, |
| 274 | }; |
| 275 | } |
| 276 | |
| 277 | // Erases the screen and scrollback only. A full emulator reset would drop the |
| 278 | // screen and input modes the still-running program negotiated. |
| 279 | const CLEAR_TERMINAL_TEXT = "\u001b[H\u001b[2J\u001b[3J"; |
| 280 | |
| 281 | /** Earlier output stays retained so a replay from the start restores those modes. */ |
| 282 | function clearOutput(current: TerminalOutputState, maxBufferBytes: number): TerminalOutputState { |
| 283 | // The erase rides over the budget: trimming here would evict the output that set those modes. |
| 284 | const cleared = appendOutput( |
| 285 | current, |
| 286 | CLEAR_TERMINAL_TEXT, |
| 287 | maxBufferBytes <= 0 |
| 288 | ? maxBufferBytes |
| 289 | : Math.max(maxBufferBytes, current.retainedBytes + CLEAR_TERMINAL_TEXT.length), |
| 290 | ); |
| 291 | return { ...cleared, textStartOffset: cleared.nextOffset }; |
| 292 | } |
| 293 | |
| 294 | /** Everything a fresh emulator replays: retained output from outside any control sequence. */ |
| 295 | export function terminalOutputReplay(output: TerminalOutputState): string { |
| 296 | const text = output.chunks.map((chunk) => chunk.data).join(""); |
| 297 | return text.slice(terminalSequenceEnd(output.sequenceState, text)); |
| 298 | } |
| 299 | |
| 300 | /** The output as plain text, for surfaces that do not interpret escape sequences. */ |
| 301 | export function terminalOutputText(output: TerminalOutputState): string { |
| 302 | const text = output.chunks.map((chunk) => chunk.data).join(""); |
| 303 | const firstOffset = output.chunks[0]?.startOffset ?? output.nextOffset; |
| 304 | return text.slice( |
| 305 | Math.max(terminalSequenceEnd(output.sequenceState, text), output.textStartOffset - firstOffset), |
| 306 | ); |
| 307 | } |
| 308 | |
| 309 | export function readTerminalOutputUpdate( |
| 310 | output: TerminalOutputState, |
| 311 | cursor: TerminalOutputCursor, |
| 312 | ): TerminalOutputUpdate { |
| 313 | const position = { |
| 314 | generation: output.generation, |
| 315 | resetVersion: output.resetVersion, |
| 316 | offset: output.nextOffset, |
| 317 | }; |
| 318 | const firstChunk = output.chunks[0]; |
| 319 | if ( |
| 320 | cursor.generation !== output.generation || |
| 321 | cursor.resetVersion !== output.resetVersion || |
| 322 | cursor.offset < (firstChunk?.startOffset ?? output.nextOffset) |
| 323 | ) { |
| 324 | const text = output.chunks.map((chunk) => chunk.data).join(""); |
| 325 | const start = terminalSequenceEnd(output.sequenceState, text); |
| 326 | return { |
| 327 | type: "reset", |
| 328 | data: text.slice(start), |
| 329 | cursor: { |
| 330 | ...position, |
| 331 | sequenceState: terminalSequenceStateAfter(output.sequenceState, text, 0, start), |
| 332 | }, |
| 333 | }; |
| 334 | } |
| 335 | |
| 336 | // Appends and compaction preserve offset order, so unread chunks form a suffix. |
| 337 | let firstUnread = output.chunks.length; |
| 338 | while (firstUnread > 0) { |
| 339 | const chunk = output.chunks[firstUnread - 1]!; |
| 340 | if (!(chunk.startOffset + chunk.data.length > cursor.offset)) break; |
| 341 | firstUnread -= 1; |
| 342 | } |
| 343 | const text = output.chunks |
| 344 | .slice(firstUnread) |
| 345 | .map((chunk) => chunk.data.slice(Math.max(0, cursor.offset - chunk.startOffset))) |
| 346 | .join(""); |
| 347 | const start = terminalSequenceEnd(cursor.sequenceState, text); |
| 348 | const nextCursor = { |
| 349 | ...position, |
| 350 | sequenceState: terminalSequenceStateAfter(cursor.sequenceState, text, 0, start), |
| 351 | }; |
| 352 | if (start === text.length) { |
| 353 | return { type: "none", cursor: nextCursor }; |
| 354 | } |
| 355 | return { type: "append", data: text.slice(start), cursor: nextCursor }; |
| 356 | } |
| 357 | |
| 358 | export { appendOutput, clearOutput, resetOutput }; |