Open History to see the last commit
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(
23 state: number,
24 unit: number,
25 onC1ReturnToGround?: (byte: number, remainingBytes: number) => void,
26): number {
27 if (unit === 0x1b) return SEQUENCE_ESCAPE;
28 if (state === TERMINAL_SEQUENCE_GROUND || unit === 0x18 || unit === 0x1a) {
29 return TERMINAL_SEQUENCE_GROUND;
30 }
31 let mode = state & 7;
32 if (unit < 0x80) {
33 switch (mode) {
34 case SEQUENCE_ESCAPE:
35 if (unit < 0x20 || unit === 0x7f) return mode;
36 if (unit < 0x30) return SEQUENCE_ESCAPE_INTERMEDIATE;
37 if (unit === 0x5b) return SEQUENCE_CSI;
38 if (unit === 0x5d) return SEQUENCE_OSC;
39 if (unit === 0x50) return SEQUENCE_DCS;
40 return unit === 0x58 || unit === 0x5e || unit === 0x5f
41 ? SEQUENCE_SOS_PM_APC
42 : TERMINAL_SEQUENCE_GROUND;
43 case SEQUENCE_ESCAPE_INTERMEDIATE:
44 return unit >= 0x30 && unit !== 0x7f ? TERMINAL_SEQUENCE_GROUND : mode;
45 case SEQUENCE_CSI:
46 return unit >= 0x40 && unit !== 0x7f ? TERMINAL_SEQUENCE_GROUND : mode;
47 case SEQUENCE_OSC:
48 return unit === 0x07 ? TERMINAL_SEQUENCE_GROUND : mode;
49 default:
50 return mode;
51 }
52 }
53 if (mode === SEQUENCE_OSC) return mode;
54 if (unit >= 0xd800 && unit <= 0xdbff) return mode | (unit << 3);
55 let codePoint = unit;
56 if (unit >= 0xdc00 && unit <= 0xdfff) {
57 if (state < 8) return mode;
58 codePoint = 0x10000 + (((state >> 3) - 0xd800) << 10) + (unit - 0xdc00);
59 }
60 // Outside ground and OSC the parser reads UTF-8 bytes one at a time, so a continuation
61 // byte in 0x80-0x9F acts as a C1 control: most end the sequence, five start another.
62 for (let shift = codePoint > 0xffff ? 12 : codePoint > 0x7ff ? 6 : 0; shift >= 0; shift -= 6) {
63 const byte = 0x80 | ((codePoint >> shift) & 0x3f);
64 if (byte >= 0xa0) continue;
65 if (byte === 0x9d) return SEQUENCE_OSC;
66 if (byte === 0x90) mode = SEQUENCE_DCS;
67 else if (byte === 0x9b) mode = SEQUENCE_CSI;
68 else if (byte === 0x98 || byte >= 0x9e) mode = SEQUENCE_SOS_PM_APC;
69 else {
70 onC1ReturnToGround?.(byte, shift / 6);
71 return TERMINAL_SEQUENCE_GROUND;
72 }
73 }
74 return mode;
75}
76
77/** The parser state after `text.slice(start, end)`, for a terminal that entered it in `state`. */
78export function terminalSequenceStateAfter(
79 state: number,
80 text: string,
81 start = 0,
82 end = text.length,
83): number {
84 if (end <= start) return state;
85 // ESC enters the escape state from every state, so only what follows the last one matters.
86 const escape = text.lastIndexOf("\u001b", end - 1);
87 if (escape >= start) {
88 state = SEQUENCE_ESCAPE;
89 start = escape + 1;
90 }
91 for (let index = start; index < end && state !== TERMINAL_SEQUENCE_GROUND; index += 1) {
92 state = nextTerminalSequenceState(state, text.charCodeAt(index));
93 }
94 return state;
95}
96
97/** Where in `text` a terminal that entered it in `state` is first back in ground state. */
98export function terminalSequenceEnd(state: number, text: string): number {
99 let index = 0;
100 while (state !== TERMINAL_SEQUENCE_GROUND && index < text.length) {
101 state = nextTerminalSequenceState(state, text.charCodeAt(index));
102 index += 1;
103 }
104 return index;
105}
106
107function scanSnapshotContinuation(state: number, data: string, limit = data.length) {
108 let control = "";
109 let replacementCount = 0;
110 const replayC1 = (byte: number, remainingBytes: number) => {
111 // Replay IND, NEL, HTS and RI from ground. Any bytes parsed after the control
112 // are now stray UTF-8 continuation bytes.
113 if (byte === 0x84 || byte === 0x85 || byte === 0x88 || byte === 0x8d) {
114 control = "\u001b" + String.fromCharCode(byte - 0x40);
115 }
116 replacementCount = remainingBytes;
117 };
118 // Inside a CSI Ghostty executes 0x00-0x0F as they arrive, so a dropped CSI keeps them.
119 let executed = "";
120 let end = 0;
121 while (state !== TERMINAL_SEQUENCE_GROUND && end < limit) {
122 const unit = data.charCodeAt(end);
123 if ((state & 7) === SEQUENCE_CSI && unit < 0x10) executed += data[end];
124 state = nextTerminalSequenceState(state, unit, replayC1);
125 end += 1;
126 }
127 return { state, end, control: executed + control, replacementCount };
128}
129
130/** Skip the continuation of an omitted snapshot prefix, retaining any new escape sequence. */
131export function skipTerminalSnapshotContinuation(state: number, data: string) {
132 if (data.length === 0) return { state, data };
133 if (state === SEQUENCE_ESCAPE) {
134 return {
135 state: TERMINAL_SEQUENCE_GROUND,
136 data: data[0] === "\\" ? data.slice(1) : "\u001b" + data,
137 };
138 }
139
140 const escape = data.indexOf("\u001b");
141 const {
142 state: next,
143 end,
144 control,
145 replacementCount,
146 } = scanSnapshotContinuation(state, data, escape < 0 ? data.length : escape);
147 if (next === TERMINAL_SEQUENCE_GROUND || end === data.length) {
148 return { state: next, data: control + "\ufffd".repeat(replacementCount) + data.slice(end) };
149 }
150 // Hold a final ESC until we know whether it starts a new sequence or completes ST.
151 if (end + 1 === data.length) return { state: SEQUENCE_ESCAPE, data: control };
152 return {
153 state: TERMINAL_SEQUENCE_GROUND,
154 data: control + data.slice(data[end + 1] === "\\" ? end + 2 : end),
155 };
156}
157
158/**
159 * The final `maxBytes` of UTF-8 a client retains, starting at a code point boundary and
160 * outside any control sequence the cut went through.
161 */
162export function retainedTerminalHistory(history: string, maxBytes: number): string {
163 if (maxBytes <= 0) {
164 return "";
165 }
166
167 const encoded = historyEncoder.encode(history);
168 if (encoded.byteLength <= maxBytes) {
169 return history;
170 }
171
172 let start = encoded.byteLength - maxBytes;
173 while (start < encoded.length) {
174 const byte = encoded[start];
175 if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000) {
176 break;
177 }
178 start += 1;
179 }
180
181 const retained = historyDecoder.decode(encoded.subarray(start));
182 const state = terminalSequenceStateAfter(
183 TERMINAL_SEQUENCE_GROUND,
184 history,
185 0,
186 history.length - retained.length,
187 );
188 const { end, control, replacementCount } = scanSnapshotContinuation(state, retained);
189 const tail = retained.slice(end);
190 if (replacementCount === 0) return control + tail;
191 // The two-byte ESC form fits where the consumed code point did. Each replacement
192 // glyph takes three bytes, so keep only as many as fit alongside the control and tail.
193 const available = maxBytes - historyEncoder.encode(tail).byteLength - control.length;
194 return control + "\ufffd".repeat(Math.min(replacementCount, Math.floor(available / 3))) + tail;
195}
196
197/** Keep a whole unfinished prefix when possible, or skip its continuation during replay. */
198export function retainTerminalSnapshotHistory(history: string, maxBytes: number) {
199 const retained = retainedTerminalHistory(history, maxBytes);
200 // The last ESC starts a sequence independently of the discarded prefix. Without one in
201 // the retained text, a history ending outside ground was cut inside its final sequence.
202 const start = history.lastIndexOf("\u001b");
203 if (start < 0 || retained.includes("\u001b")) return { history: retained };
204 const state = terminalSequenceStateAfter(TERMINAL_SEQUENCE_GROUND, history, start);
205 if (state === TERMINAL_SEQUENCE_GROUND) return { history: retained };
206 const pending = history.slice(start);
207 const pendingBytes = historyEncoder.encode(pending).byteLength;
208 if (pendingBytes > maxBytes) return { history: retained, historySequenceState: state };
209 // Keep controls recovered from the clipped prefix that still fit beside the pending sequence.
210 return {
211 history: retainedTerminalHistory(history.slice(0, start), maxBytes - pendingBytes) + pending,
212 };
213}
214
215const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
216const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(
217 Schema.isLessThanOrEqualTo(1000),
218);
219const TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(
220 Schema.isLessThanOrEqualTo(500),
221);
222const TerminalIdSchema = TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(128));
223const TerminalEnvKeySchema = Schema.String.check(
224 Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),
225).check(Schema.isMaxLength(128));
226const TerminalEnvValueSchema = Schema.String.check(Schema.isMaxLength(8_192));
227const TerminalEnvSchema = Schema.Record(TerminalEnvKeySchema, TerminalEnvValueSchema).check(
228 Schema.isMaxProperties(128),
229);
230
231export const TerminalThreadInput = Schema.Struct({
232 threadId: TrimmedNonEmptyStringSchema,
233});
234export type TerminalThreadInput = typeof TerminalThreadInput.Type;
235
236// Terminal ids are client-chosen; the server never allocates them.
237const TerminalSessionInput = Schema.Struct({
238 ...TerminalThreadInput.fields,
239 terminalId: TerminalIdSchema,
240});
241export type TerminalSessionInput = Schema.Codec.Encoded<typeof TerminalSessionInput>;
242
243export const TerminalOpenInput = Schema.Struct({
244 ...TerminalSessionInput.fields,
245 cwd: TrimmedNonEmptyStringSchema,
246 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
247 cols: Schema.optional(TerminalColsSchema),
248 rows: Schema.optional(TerminalRowsSchema),
249 env: Schema.optional(TerminalEnvSchema),
250 providerInstanceId: Schema.optional(ProviderInstanceId),
251 stopOnSettle: Schema.optional(Schema.Boolean),
252});
253export type TerminalOpenInput = typeof TerminalOpenInput.Type;
254
255export const TerminalObserveInput = Schema.Struct({
256 ...TerminalSessionInput.fields,
257 // The viewer can skip a discarded prefix using the snapshot's parser state.
258 supportsSnapshotSequenceState: Schema.optional(Schema.Boolean),
259});
260export type TerminalObserveInput = Schema.Codec.Encoded<typeof TerminalObserveInput>;
261
262export const TerminalAttachInput = Schema.Struct({
263 ...TerminalObserveInput.fields,
264 cwd: Schema.optional(TrimmedNonEmptyStringSchema),
265 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
266 cols: Schema.optional(TerminalColsSchema),
267 rows: Schema.optional(TerminalRowsSchema),
268 env: Schema.optional(TerminalEnvSchema),
269 providerInstanceId: Schema.optional(ProviderInstanceId),
270 stopOnSettle: Schema.optional(Schema.Boolean),
271 restartIfNotRunning: Schema.optional(Schema.Boolean),
272 // Resubscriptions preserve stopped terminals; unknown IDs recover after a server restart.
273 resume: Schema.optional(Schema.Boolean),
274 // Snapshots carry only the history a client this bounded keeps; older servers ignore it.
275 maxHistoryBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
276});
277export type TerminalAttachInput = typeof TerminalAttachInput.Type;
278
279/** Longest `data` one `terminal.write` carries, in UTF-16 code units. */
280export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
281
282export const TERMINAL_BRACKETED_PASTE_START = "\x1b[200~";
283export const TERMINAL_BRACKETED_PASTE_END = "\x1b[201~";
284
285export const TerminalWriteInput = Schema.Struct({
286 ...TerminalSessionInput.fields,
287 data: Schema.String.check(Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH)),
288 // Older servers ignore the phase and still receive the bracket markers in data.
289 bracketedPaste: Schema.optionalKey(Schema.Literals(["start", "continue", "end", "abort"])),
290 plainWrite: Schema.optionalKey(Schema.Literals(["start", "continue", "end", "abort"])),
291 // `data` holds one byte per UTF-16 code unit; older servers write it as UTF-8 text.
292 binary: Schema.optionalKey(Schema.Boolean),
293 // A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer
294 // answers, so the server passes on one viewer's replies; older servers ignore it.
295 reply: Schema.optionalKey(Schema.Boolean),
296 // Reject the write if the process that owns the paste has gone.
297 expectedPid: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
298}).check(
299 Schema.makeFilter(({ data, plainWrite }) => (plainWrite === "abort") === (data.length === 0)),
300);
301export type TerminalWriteInput = Schema.Codec.Encoded<typeof TerminalWriteInput>;
302
303/** Splits input into writes that fit `TerminalWriteInput`, never between a surrogate pair. */
304export function chunkTerminalWrite(data: string): ReadonlyArray<string> {
305 const chunks: string[] = [];
306 let start = 0;
307 while (start < data.length) {
308 let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
309 const last = data.charCodeAt(end - 1);
310 if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
311 end -= 1;
312 }
313 chunks.push(data.slice(start, end));
314 start = end;
315 }
316 return chunks;
317}
318
319export function terminalWritePhase(index: number, count: number) {
320 if (count <= 1) return undefined;
321 return index === 0 ? "start" : index === count - 1 ? "end" : "continue";
322}
323
324export const TerminalResizeInput = Schema.Struct({
325 ...TerminalSessionInput.fields,
326 cols: TerminalColsSchema,
327 rows: TerminalRowsSchema,
328});
329export type TerminalResizeInput = Schema.Codec.Encoded<typeof TerminalResizeInput>;
330
331export const TerminalClearInput = TerminalSessionInput;
332export type TerminalClearInput = Schema.Codec.Encoded<typeof TerminalClearInput>;
333
334export const TerminalCloseInput = Schema.Struct({
335 ...TerminalThreadInput.fields,
336 terminalId: Schema.optional(TerminalIdSchema),
337 deleteHistory: Schema.optional(Schema.Boolean),
338});
339export type TerminalCloseInput = typeof TerminalCloseInput.Type;
340
341export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
342export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
343
344export const TerminalSessionSnapshot = Schema.Struct({
345 threadId: Schema.String.check(Schema.isNonEmpty()),
346 terminalId: Schema.String.check(Schema.isNonEmpty()),
347 cwd: Schema.String.check(Schema.isNonEmpty()),
348 worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),
349 status: TerminalSessionStatus,
350 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
351 supportsConditionalWrites: Schema.optional(Schema.Boolean),
352 history: Schema.String,
353 // Parser state of an unfinished prefix omitted after the replayable history.
354 historySequenceState: Schema.optional(
355 Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: (0xdbff << 3) | SEQUENCE_OSC })),
356 ),
357 exitCode: Schema.NullOr(Schema.Int),
358 exitSignal: Schema.NullOr(Schema.Int),
359 label: Schema.String.check(Schema.isMaxLength(128)),
360 updatedAt: Schema.String,
361 sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
362 // The PTY grid every renderer of this terminal should draw; absent from older servers.
363 cols: Schema.optional(TerminalColsSchema),
364 rows: Schema.optional(TerminalRowsSchema),
365 // Why the shell failed to start, kept so later attachments can show it.
366 error: Schema.optional(Schema.String.check(Schema.isNonEmpty())),
367});
368export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;
369
370export const TerminalSummary = Schema.Struct({
371 threadId: Schema.String.check(Schema.isNonEmpty()),
372 terminalId: Schema.String.check(Schema.isNonEmpty()),
373 cwd: Schema.String.check(Schema.isNonEmpty()),
374 worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),
375 status: TerminalSessionStatus,
376 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
377 exitCode: Schema.NullOr(Schema.Int),
378 exitSignal: Schema.NullOr(Schema.Int),
379 hasRunningSubprocess: Schema.Boolean,
380 label: Schema.String.check(Schema.isMaxLength(128)),
381 updatedAt: Schema.String,
382});
383export type TerminalSummary = typeof TerminalSummary.Type;
384
385const TerminalMetadataSnapshotEvent = Schema.Struct({
386 type: Schema.Literal("snapshot"),
387 terminals: Schema.Array(TerminalSummary),
388 managerId: Schema.optional(Schema.String),
389});
390
391const TerminalMetadataUpsertEvent = Schema.Struct({
392 type: Schema.Literal("upsert"),
393 terminal: TerminalSummary,
394});
395
396const TerminalMetadataRemoveEvent = Schema.Struct({
397 type: Schema.Literal("remove"),
398 threadId: Schema.String.check(Schema.isNonEmpty()),
399 terminalId: Schema.String.check(Schema.isNonEmpty()),
400});
401
402export const TerminalMetadataStreamEvent = Schema.Union([
403 TerminalMetadataSnapshotEvent,
404 TerminalMetadataUpsertEvent,
405 TerminalMetadataRemoveEvent,
406]);
407export type TerminalMetadataStreamEvent = typeof TerminalMetadataStreamEvent.Type;
408
409const TerminalEventBaseSchema = Schema.Struct({
410 threadId: Schema.String.check(Schema.isNonEmpty()),
411 terminalId: Schema.String.check(Schema.isNonEmpty()),
412 sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
413});
414
415const TerminalStartedEvent = Schema.Struct({
416 ...TerminalEventBaseSchema.fields,
417 type: Schema.Literal("started"),
418 snapshot: TerminalSessionSnapshot,
419});
420
421const TerminalOutputEvent = Schema.Struct({
422 ...TerminalEventBaseSchema.fields,
423 type: Schema.Literal("output"),
424 data: Schema.String,
425});
426
427const TerminalExitedEvent = Schema.Struct({
428 ...TerminalEventBaseSchema.fields,
429 type: Schema.Literal("exited"),
430 exitCode: Schema.NullOr(Schema.Int),
431 exitSignal: Schema.NullOr(Schema.Int),
432});
433
434const TerminalClosedEvent = Schema.Struct({
435 ...TerminalEventBaseSchema.fields,
436 type: Schema.Literal("closed"),
437});
438
439const TerminalErrorEvent = Schema.Struct({
440 ...TerminalEventBaseSchema.fields,
441 type: Schema.Literal("error"),
442 message: Schema.String.check(Schema.isNonEmpty()),
443});
444
445const TerminalClearedEvent = Schema.Struct({
446 ...TerminalEventBaseSchema.fields,
447 type: Schema.Literal("cleared"),
448 pendingControlSequence: Schema.optionalKey(Schema.String),
449});
450
451const TerminalRestartedEvent = Schema.Struct({
452 ...TerminalEventBaseSchema.fields,
453 type: Schema.Literal("restarted"),
454 snapshot: TerminalSessionSnapshot,
455});
456
457const TerminalActivityEvent = Schema.Struct({
458 ...TerminalEventBaseSchema.fields,
459 type: Schema.Literal("activity"),
460 hasRunningSubprocess: Schema.Boolean,
461 label: Schema.String.check(Schema.isMaxLength(128)),
462 // Shared PTY grid changes ride on activity because older clients reject unknown event types.
463 cols: Schema.optional(TerminalColsSchema),
464 rows: Schema.optional(TerminalRowsSchema),
465});
466
467export const TerminalEvent = Schema.Union([
468 TerminalStartedEvent,
469 TerminalOutputEvent,
470 TerminalExitedEvent,
471 TerminalClosedEvent,
472 TerminalErrorEvent,
473 TerminalClearedEvent,
474 TerminalRestartedEvent,
475 TerminalActivityEvent,
476]);
477export type TerminalEvent = typeof TerminalEvent.Type;
478
479const TerminalAttachSnapshotEvent = Schema.Struct({
480 type: Schema.Literal("snapshot"),
481 snapshot: TerminalSessionSnapshot,
482});
483
484export const TerminalAttachStreamEvent = Schema.Union([
485 TerminalAttachSnapshotEvent,
486 TerminalOutputEvent,
487 TerminalExitedEvent,
488 TerminalClosedEvent,
489 TerminalErrorEvent,
490 TerminalClearedEvent,
491 TerminalRestartedEvent,
492 TerminalActivityEvent,
493]);
494export type TerminalAttachStreamEvent = typeof TerminalAttachStreamEvent.Type;
495
496export class TerminalCwdNotFoundError extends Schema.TaggedError<TerminalCwdNotFoundError>()(
497 "TerminalCwdNotFoundError",
498 {
499 cwd: Schema.String,
500 },
501) {
502 override get message() {
503 return `Terminal folder does not exist: ${this.cwd}. Restore the folder at this path before retrying.`;
504 }
505}
506
507export class TerminalCwdNotDirectoryError extends Schema.TaggedError<TerminalCwdNotDirectoryError>()(
508 "TerminalCwdNotDirectoryError",
509 {
510 cwd: Schema.String,
511 },
512) {
513 override get message() {
514 return `Terminal cwd is not a directory: ${this.cwd}`;
515 }
516}
517
518export class TerminalCwdStatError extends Schema.TaggedError<TerminalCwdStatError>()(
519 "TerminalCwdStatError",
520 {
521 cwd: Schema.String,
522 cause: Schema.Defect(),
523 },
524) {
525 override get message() {
526 return `Failed to access terminal cwd: ${this.cwd}`;
527 }
528}
529
530export const TerminalCwdError = Schema.Union([
531 TerminalCwdNotFoundError,
532 TerminalCwdNotDirectoryError,
533 TerminalCwdStatError,
534]);
535export type TerminalCwdError = typeof TerminalCwdError.Type;
536
537export class TerminalHistoryError extends Schema.TaggedError<TerminalHistoryError>()(
538 "TerminalHistoryError",
539 {
540 operation: Schema.Literals(["read", "truncate", "migrate"]),
541 threadId: Schema.String,
542 terminalId: Schema.String,
543 cause: Schema.optional(Schema.Defect()),
544 },
545) {
546 override get message() {
547 return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
548 }
549}
550
551export class TerminalSessionLookupError extends Schema.TaggedError<TerminalSessionLookupError>()(
552 "TerminalSessionLookupError",
553 {
554 threadId: Schema.String,
555 terminalId: Schema.String,
556 },
557) {
558 override get message() {
559 return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
560 }
561}
562
563export class TerminalProviderInstanceNotFoundError extends Schema.TaggedError<TerminalProviderInstanceNotFoundError>()(
564 "TerminalProviderInstanceNotFoundError",
565 {
566 providerInstanceId: ProviderInstanceId,
567 },
568) {
569 override get message() {
570 return `Provider instance is not available: ${this.providerInstanceId}`;
571 }
572}
573
574export class TerminalProviderEnvironmentError extends Schema.TaggedError<TerminalProviderEnvironmentError>()(
575 "TerminalProviderEnvironmentError",
576 {
577 providerInstanceId: ProviderInstanceId,
578 cause: Schema.Defect(),
579 },
580) {
581 override get message() {
582 return `Could not prepare the terminal environment for provider instance: ${this.providerInstanceId}`;
583 }
584}
585
586export class TerminalNotRunningError extends Schema.TaggedError<TerminalNotRunningError>()(
587 "TerminalNotRunningError",
588 {
589 threadId: Schema.String,
590 terminalId: Schema.String,
591 },
592) {
593 override get message() {
594 return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
595 }
596}
597
598export class TerminalWriteError extends Schema.TaggedError<TerminalWriteError>()(
599 "TerminalWriteError",
600 {
601 threadId: Schema.String,
602 terminalId: Schema.String,
603 terminalPid: Schema.Number,
604 cause: Schema.Defect(),
605 },
606) {
607 override get message() {
608 return `Failed to write to terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid}`;
609 }
610}
611
612export class TerminalResizeError extends Schema.TaggedError<TerminalResizeError>()(
613 "TerminalResizeError",
614 {
615 threadId: Schema.String,
616 terminalId: Schema.String,
617 terminalPid: Schema.Number,
618 cols: TerminalColsSchema,
619 rows: TerminalRowsSchema,
620 cause: Schema.Defect(),
621 },
622) {
623 override get message() {
624 return `Failed to resize terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid} to ${this.cols}x${this.rows}`;
625 }
626}
627
628export class TerminalProcessChangedError extends Schema.TaggedError<TerminalProcessChangedError>()(
629 "TerminalProcessChangedError",
630 {},
631) {}
632
633export const TerminalError = Schema.Union([
634 TerminalCwdError,
635 TerminalHistoryError,
636 TerminalSessionLookupError,
637 TerminalProviderInstanceNotFoundError,
638 TerminalProviderEnvironmentError,
639 TerminalNotRunningError,
640 TerminalProcessChangedError,
641 TerminalWriteError,
642 TerminalResizeError,
643]);
644export type TerminalError = typeof TerminalError.Type;