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