Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminal.ts

532 lines18.0 KB

1import * as Schema from "effect/Schema";
2import { TrimmedNonEmptyString } from "./baseSchemas.ts";
3import { ProviderInstanceId } from "./providerInstance.ts";
4​
5export const DEFAULT_TERMINAL_ID = "term-1";
6export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024;
7​
8const historyEncoder = new TextEncoder();
9// A BOM at a retained chunk boundary is terminal data, not an encoding marker.
10const historyDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
11​
12// libghostty-vt's parser states, merged where the same input takes them back to ground.
13export const TERMINAL_SEQUENCE_GROUND = 0;
14const SEQUENCE_ESCAPE = 1;
15const SEQUENCE_ESCAPE_INTERMEDIATE = 2;
16const SEQUENCE_CSI = 3;
17const SEQUENCE_DCS = 4;
18const SEQUENCE_SOS_PM_APC = 5;
19const SEQUENCE_OSC = 6;
20​
21// Bits above the low three hold a high surrogate until its other half arrives.
22function nextTerminalSequenceState(state: number, unit: number): number {
23 if (unit === 0x1b) return SEQUENCE_ESCAPE;
24 if (state === TERMINAL_SEQUENCE_GROUND || unit === 0x18 || unit === 0x1a) {
25 return TERMINAL_SEQUENCE_GROUND;
26 }
27 let mode = state & 7;
28 if (unit < 0x80) {
29 switch (mode) {
30 case SEQUENCE_ESCAPE:
31 if (unit < 0x20 || unit === 0x7f) return mode;
32 if (unit < 0x30) return SEQUENCE_ESCAPE_INTERMEDIATE;
33 if (unit === 0x5b) return SEQUENCE_CSI;
34 if (unit === 0x5d) return SEQUENCE_OSC;
35 if (unit === 0x50) return SEQUENCE_DCS;
36 return unit === 0x58 || unit === 0x5e || unit === 0x5f
37 ? SEQUENCE_SOS_PM_APC
38 : TERMINAL_SEQUENCE_GROUND;
39 case SEQUENCE_ESCAPE_INTERMEDIATE:
40 return unit >= 0x30 && unit !== 0x7f ? TERMINAL_SEQUENCE_GROUND : mode;
41 case SEQUENCE_CSI:
42 return unit >= 0x40 && unit !== 0x7f ? TERMINAL_SEQUENCE_GROUND : mode;
43 case SEQUENCE_OSC:
44 return unit === 0x07 ? TERMINAL_SEQUENCE_GROUND : mode;
45 default:
46 return mode;
47 }
48 }
49 if (mode === SEQUENCE_OSC) return mode;
50 if (unit >= 0xd800 && unit <= 0xdbff) return mode | (unit << 3);
51 let codePoint = unit;
52 if (unit >= 0xdc00 && unit <= 0xdfff) {
53 if (state < 8) return mode;
54 codePoint = 0x10000 + (((state >> 3) - 0xd800) << 10) + (unit - 0xdc00);
55 }
56 // Outside ground and OSC the parser reads UTF-8 bytes one at a time, so a continuation
57 // byte in 0x80-0x9F acts as a C1 control: most end the sequence, five start another.
58 for (let shift = codePoint > 0xffff ? 12 : codePoint > 0x7ff ? 6 : 0; shift >= 0; shift -= 6) {
59 const byte = 0x80 | ((codePoint >> shift) & 0x3f);
60 if (byte >= 0xa0) continue;
61 if (byte === 0x9d) return SEQUENCE_OSC;
62 if (byte === 0x90) mode = SEQUENCE_DCS;
63 else if (byte === 0x9b) mode = SEQUENCE_CSI;
64 else if (byte === 0x98 || byte >= 0x9e) mode = SEQUENCE_SOS_PM_APC;
65 else return TERMINAL_SEQUENCE_GROUND;
66 }
67 return mode;
69​
70/** The parser state after `text.slice(start, end)`, for a terminal that entered it in `state`. */
71export function terminalSequenceStateAfter(
72 state: number,
73 text: string,
74 start = 0,
75 end = text.length,
76): number {
77 if (end <= start) return state;
78 // ESC enters the escape state from every state, so only what follows the last one matters.
79 const escape = text.lastIndexOf("\u001b", end - 1);
80 if (escape >= start) {
81 state = SEQUENCE_ESCAPE;
82 start = escape + 1;
83 }
84 for (let index = start; index < end && state !== TERMINAL_SEQUENCE_GROUND; index += 1) {
85 state = nextTerminalSequenceState(state, text.charCodeAt(index));
86 }
87 return state;
89​
90/** Where in `text` a terminal that entered it in `state` is first back in ground state. */
91export function terminalSequenceEnd(state: number, text: string): number {
92 let index = 0;
93 while (state !== TERMINAL_SEQUENCE_GROUND && index < text.length) {
94 state = nextTerminalSequenceState(state, text.charCodeAt(index));
95 index += 1;
96 }
97 return index;
99​
100/**
101 * The final `maxBytes` of UTF-8 a client retains, starting at a code point boundary and
102 * outside any control sequence the cut went through.
103 */
104export function retainedTerminalHistory(history: string, maxBytes: number): string {
105 if (maxBytes <= 0) {
106 return "";
107 }
108​
109 const encoded = historyEncoder.encode(history);
110 if (encoded.byteLength <= maxBytes) {
111 return history;
112 }
113​
114 let start = encoded.byteLength - maxBytes;
115 while (start < encoded.length) {
116 const byte = encoded[start];
117 if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000) {
118 break;
119 }
120 start += 1;
121 }
122​
123 const retained = historyDecoder.decode(encoded.subarray(start));
124 const state = terminalSequenceStateAfter(
125 TERMINAL_SEQUENCE_GROUND,
126 history,
127 0,
128 history.length - retained.length,
129 );
130 return retained.slice(terminalSequenceEnd(state, retained));
132​
133const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
134const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(
135 Schema.isLessThanOrEqualTo(1000),
136);
137const TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(
138 Schema.isLessThanOrEqualTo(500),
139);
140const TerminalIdSchema = TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(128));
141const TerminalEnvKeySchema = Schema.String.check(
142 Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),
143).check(Schema.isMaxLength(128));
144const TerminalEnvValueSchema = Schema.String.check(Schema.isMaxLength(8_192));
145const TerminalEnvSchema = Schema.Record(TerminalEnvKeySchema, TerminalEnvValueSchema).check(
146 Schema.isMaxProperties(128),
147);
148​
149export const TerminalThreadInput = Schema.Struct({
150 threadId: TrimmedNonEmptyStringSchema,
151});
152export type TerminalThreadInput = typeof TerminalThreadInput.Type;
153​
154// Terminal ids are client-chosen; the server never allocates them.
155const TerminalSessionInput = Schema.Struct({
156 ...TerminalThreadInput.fields,
157 terminalId: TerminalIdSchema,
158});
159export type TerminalSessionInput = Schema.Codec.Encoded<typeof TerminalSessionInput>;
160​
161export const TerminalOpenInput = Schema.Struct({
162 ...TerminalSessionInput.fields,
163 cwd: TrimmedNonEmptyStringSchema,
164 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
165 cols: Schema.optional(TerminalColsSchema),
166 rows: Schema.optional(TerminalRowsSchema),
167 env: Schema.optional(TerminalEnvSchema),
168 providerInstanceId: Schema.optional(ProviderInstanceId),
169 stopOnSettle: Schema.optional(Schema.Boolean),
170});
171export type TerminalOpenInput = typeof TerminalOpenInput.Type;
172​
173export const TerminalAttachInput = Schema.Struct({
174 ...TerminalSessionInput.fields,
175 cwd: Schema.optional(TrimmedNonEmptyStringSchema),
176 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
177 cols: Schema.optional(TerminalColsSchema),
178 rows: Schema.optional(TerminalRowsSchema),
179 env: Schema.optional(TerminalEnvSchema),
180 providerInstanceId: Schema.optional(ProviderInstanceId),
181 stopOnSettle: Schema.optional(Schema.Boolean),
182 restartIfNotRunning: Schema.optional(Schema.Boolean),
183 // Resubscriptions preserve stopped terminals; unknown IDs recover after a server restart.
184 resume: Schema.optional(Schema.Boolean),
185 // Snapshots carry only the history a client this bounded keeps; older servers ignore it.
186 maxHistoryBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
187});
188export type TerminalAttachInput = typeof TerminalAttachInput.Type;
189​
190export const TerminalObserveInput = TerminalSessionInput;
191export type TerminalObserveInput = Schema.Codec.Encoded<typeof TerminalObserveInput>;
192​
193/** Longest `data` one `terminal.write` carries, in UTF-16 code units. */
194export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
195​
196export const TerminalWriteInput = Schema.Struct({
197 ...TerminalSessionInput.fields,
198 data: Schema.String.check(Schema.isNonEmpty()).check(
199 Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH),
200 ),
201 // `data` holds one byte per UTF-16 code unit; older servers write it as UTF-8 text.
202 binary: Schema.optionalKey(Schema.Boolean),
203 // A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer
204 // answers, so the server passes on one viewer's replies; older servers ignore it.
205 reply: Schema.optionalKey(Schema.Boolean),
206});
207export type TerminalWriteInput = Schema.Codec.Encoded<typeof TerminalWriteInput>;
208​
209/** Splits input into writes that fit `TerminalWriteInput`, never between a surrogate pair. */
210export function chunkTerminalWrite(data: string): ReadonlyArray<string> {
211 const chunks: string[] = [];
212 let start = 0;
213 while (start < data.length) {
214 let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
215 const last = data.charCodeAt(end - 1);
216 if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
217 end -= 1;
218 }
219 chunks.push(data.slice(start, end));
220 start = end;
221 }
222 return chunks;
224​
225export const TerminalResizeInput = Schema.Struct({
226 ...TerminalSessionInput.fields,
227 cols: TerminalColsSchema,
228 rows: TerminalRowsSchema,
229});
230export type TerminalResizeInput = Schema.Codec.Encoded<typeof TerminalResizeInput>;
231​
232export const TerminalClearInput = TerminalSessionInput;
233export type TerminalClearInput = Schema.Codec.Encoded<typeof TerminalClearInput>;
234​
235export const TerminalCloseInput = Schema.Struct({
236 ...TerminalThreadInput.fields,
237 terminalId: Schema.optional(TerminalIdSchema),
238 deleteHistory: Schema.optional(Schema.Boolean),
239});
240export type TerminalCloseInput = typeof TerminalCloseInput.Type;
241​
242export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
243export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
244​
245export const TerminalSessionSnapshot = Schema.Struct({
246 threadId: Schema.String.check(Schema.isNonEmpty()),
247 terminalId: Schema.String.check(Schema.isNonEmpty()),
248 cwd: Schema.String.check(Schema.isNonEmpty()),
249 worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),
250 status: TerminalSessionStatus,
251 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
252 history: Schema.String,
253 exitCode: Schema.NullOr(Schema.Int),
254 exitSignal: Schema.NullOr(Schema.Int),
255 label: Schema.String.check(Schema.isMaxLength(128)),
256 updatedAt: Schema.String,
257 sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
258 // The PTY grid every renderer of this terminal should draw; absent from older servers.
259 cols: Schema.optional(TerminalColsSchema),
260 rows: Schema.optional(TerminalRowsSchema),
261 // Why the shell failed to start, kept so later attachments can show it.
262 error: Schema.optional(Schema.String.check(Schema.isNonEmpty())),
263});
264export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;
265​
266export const TerminalSummary = Schema.Struct({
267 threadId: Schema.String.check(Schema.isNonEmpty()),
268 terminalId: Schema.String.check(Schema.isNonEmpty()),
269 cwd: Schema.String.check(Schema.isNonEmpty()),
270 worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),
271 status: TerminalSessionStatus,
272 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
273 exitCode: Schema.NullOr(Schema.Int),
274 exitSignal: Schema.NullOr(Schema.Int),
275 hasRunningSubprocess: Schema.Boolean,
276 label: Schema.String.check(Schema.isMaxLength(128)),
277 updatedAt: Schema.String,
278});
279export type TerminalSummary = typeof TerminalSummary.Type;
280​
281const TerminalMetadataSnapshotEvent = Schema.Struct({
282 type: Schema.Literal("snapshot"),
283 terminals: Schema.Array(TerminalSummary),
284});
285​
286const TerminalMetadataUpsertEvent = Schema.Struct({
287 type: Schema.Literal("upsert"),
288 terminal: TerminalSummary,
289});
290​
291const TerminalMetadataRemoveEvent = Schema.Struct({
292 type: Schema.Literal("remove"),
293 threadId: Schema.String.check(Schema.isNonEmpty()),
294 terminalId: Schema.String.check(Schema.isNonEmpty()),
295});
296​
297export const TerminalMetadataStreamEvent = Schema.Union([
298 TerminalMetadataSnapshotEvent,
299 TerminalMetadataUpsertEvent,
300 TerminalMetadataRemoveEvent,
301]);
302export type TerminalMetadataStreamEvent = typeof TerminalMetadataStreamEvent.Type;
303​
304const TerminalEventBaseSchema = Schema.Struct({
305 threadId: Schema.String.check(Schema.isNonEmpty()),
306 terminalId: Schema.String.check(Schema.isNonEmpty()),
307 sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
308});
309​
310const TerminalStartedEvent = Schema.Struct({
311 ...TerminalEventBaseSchema.fields,
312 type: Schema.Literal("started"),
313 snapshot: TerminalSessionSnapshot,
314});
315​
316const TerminalOutputEvent = Schema.Struct({
317 ...TerminalEventBaseSchema.fields,
318 type: Schema.Literal("output"),
319 data: Schema.String,
320});
321​
322const TerminalExitedEvent = Schema.Struct({
323 ...TerminalEventBaseSchema.fields,
324 type: Schema.Literal("exited"),
325 exitCode: Schema.NullOr(Schema.Int),
326 exitSignal: Schema.NullOr(Schema.Int),
327});
328​
329const TerminalClosedEvent = Schema.Struct({
330 ...TerminalEventBaseSchema.fields,
331 type: Schema.Literal("closed"),
332});
333​
334const TerminalErrorEvent = Schema.Struct({
335 ...TerminalEventBaseSchema.fields,
336 type: Schema.Literal("error"),
337 message: Schema.String.check(Schema.isNonEmpty()),
338});
339​
340const TerminalClearedEvent = Schema.Struct({
341 ...TerminalEventBaseSchema.fields,
342 type: Schema.Literal("cleared"),
343});
344​
345const TerminalRestartedEvent = Schema.Struct({
346 ...TerminalEventBaseSchema.fields,
347 type: Schema.Literal("restarted"),
348 snapshot: TerminalSessionSnapshot,
349});
350​
351const TerminalActivityEvent = Schema.Struct({
352 ...TerminalEventBaseSchema.fields,
353 type: Schema.Literal("activity"),
354 hasRunningSubprocess: Schema.Boolean,
355 label: Schema.String.check(Schema.isMaxLength(128)),
356 // Shared PTY grid changes ride on activity because older clients reject unknown event types.
357 cols: Schema.optional(TerminalColsSchema),
358 rows: Schema.optional(TerminalRowsSchema),
359});
360​
361export const TerminalEvent = Schema.Union([
362 TerminalStartedEvent,
363 TerminalOutputEvent,
364 TerminalExitedEvent,
365 TerminalClosedEvent,
366 TerminalErrorEvent,
367 TerminalClearedEvent,
368 TerminalRestartedEvent,
369 TerminalActivityEvent,
370]);
371export type TerminalEvent = typeof TerminalEvent.Type;
372​
373const TerminalAttachSnapshotEvent = Schema.Struct({
374 type: Schema.Literal("snapshot"),
375 snapshot: TerminalSessionSnapshot,
376});
377​
378export const TerminalAttachStreamEvent = Schema.Union([
379 TerminalAttachSnapshotEvent,
380 TerminalOutputEvent,
381 TerminalExitedEvent,
382 TerminalClosedEvent,
383 TerminalErrorEvent,
384 TerminalClearedEvent,
385 TerminalRestartedEvent,
386 TerminalActivityEvent,
387]);
388export type TerminalAttachStreamEvent = typeof TerminalAttachStreamEvent.Type;
389​
390export class TerminalCwdNotFoundError extends Schema.TaggedError<TerminalCwdNotFoundError>()(
391 "TerminalCwdNotFoundError",
392 {
393 cwd: Schema.String,
394 },
395) {
396 override get message() {
397 return `Terminal folder does not exist: ${this.cwd}. Restore the folder at this path before retrying.`;
398 }
400​
401export class TerminalCwdNotDirectoryError extends Schema.TaggedError<TerminalCwdNotDirectoryError>()(
402 "TerminalCwdNotDirectoryError",
403 {
404 cwd: Schema.String,
405 },
406) {
407 override get message() {
408 return `Terminal cwd is not a directory: ${this.cwd}`;
409 }
411​
412export class TerminalCwdStatError extends Schema.TaggedError<TerminalCwdStatError>()(
413 "TerminalCwdStatError",
414 {
415 cwd: Schema.String,
416 cause: Schema.Defect(),
417 },
418) {
419 override get message() {
420 return `Failed to access terminal cwd: ${this.cwd}`;
421 }
423​
424export const TerminalCwdError = Schema.Union([
425 TerminalCwdNotFoundError,
426 TerminalCwdNotDirectoryError,
427 TerminalCwdStatError,
428]);
429export type TerminalCwdError = typeof TerminalCwdError.Type;
430​
431export class TerminalHistoryError extends Schema.TaggedError<TerminalHistoryError>()(
432 "TerminalHistoryError",
433 {
434 operation: Schema.Literals(["read", "truncate", "migrate"]),
435 threadId: Schema.String,
436 terminalId: Schema.String,
437 cause: Schema.optional(Schema.Defect()),
438 },
439) {
440 override get message() {
441 return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
442 }
444​
445export class TerminalSessionLookupError extends Schema.TaggedError<TerminalSessionLookupError>()(
446 "TerminalSessionLookupError",
447 {
448 threadId: Schema.String,
449 terminalId: Schema.String,
450 },
451) {
452 override get message() {
453 return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
454 }
456​
457export class TerminalProviderInstanceNotFoundError extends Schema.TaggedError<TerminalProviderInstanceNotFoundError>()(
458 "TerminalProviderInstanceNotFoundError",
459 {
460 providerInstanceId: ProviderInstanceId,
461 },
462) {
463 override get message() {
464 return `Provider instance is not available: ${this.providerInstanceId}`;
465 }
467​
468export class TerminalProviderEnvironmentError extends Schema.TaggedError<TerminalProviderEnvironmentError>()(
469 "TerminalProviderEnvironmentError",
470 {
471 providerInstanceId: ProviderInstanceId,
472 cause: Schema.Defect(),
473 },
474) {
475 override get message() {
476 return `Could not prepare the terminal environment for provider instance: ${this.providerInstanceId}`;
477 }
479​
480export class TerminalNotRunningError extends Schema.TaggedError<TerminalNotRunningError>()(
481 "TerminalNotRunningError",
482 {
483 threadId: Schema.String,
484 terminalId: Schema.String,
485 },
486) {
487 override get message() {
488 return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
489 }
491​
492export class TerminalWriteError extends Schema.TaggedError<TerminalWriteError>()(
493 "TerminalWriteError",
494 {
495 threadId: Schema.String,
496 terminalId: Schema.String,
497 terminalPid: Schema.Number,
498 cause: Schema.Defect(),
499 },
500) {
501 override get message() {
502 return `Failed to write to terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid}`;
503 }
505​
506export class TerminalResizeError extends Schema.TaggedError<TerminalResizeError>()(
507 "TerminalResizeError",
508 {
509 threadId: Schema.String,
510 terminalId: Schema.String,
511 terminalPid: Schema.Number,
512 cols: TerminalColsSchema,
513 rows: TerminalRowsSchema,
514 cause: Schema.Defect(),
515 },
516) {
517 override get message() {
518 return `Failed to resize terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid} to ${this.cols}x${this.rows}`;
519 }
521​
522export const TerminalError = Schema.Union([
523 TerminalCwdError,
524 TerminalHistoryError,
525 TerminalSessionLookupError,
526 TerminalProviderInstanceNotFoundError,
527 TerminalProviderEnvironmentError,
528 TerminalNotRunningError,
529 TerminalWriteError,
530 TerminalResizeError,
531]);
532export type TerminalError = typeof TerminalError.Type;