dsh-bash-terminal-ts 0.7.2-compat.2 → 0.8.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 (86) hide show
  1. package/README.de.md +3 -2
  2. package/README.en.md +102 -3
  3. package/README.es.md +3 -2
  4. package/README.fr.md +3 -2
  5. package/README.it.md +3 -2
  6. package/README.md +198 -4
  7. package/README.ru.md +3 -2
  8. package/cordis.patch.yml +66 -0
  9. package/dist/client.core.js +7888 -79
  10. package/dist/client.js +7888 -79
  11. package/dsh.plugin.json +22 -22
  12. package/lib/browser-i18n.d.ts +4 -0
  13. package/lib/browser-i18n.js +23 -0
  14. package/lib/client.js +7888 -79
  15. package/lib/dsh-types.d.ts +10 -0
  16. package/lib/dsh.d.ts +2 -0
  17. package/lib/index.d.ts +43 -0
  18. package/lib/index.js +176 -91
  19. package/lib/locales.d.ts +4 -0
  20. package/lib/locales.js +422 -0
  21. package/lib/settings-surface.d.ts +20 -0
  22. package/lib/settings-surface.js +49 -0
  23. package/lib/shell-id.d.ts +2 -0
  24. package/lib/shell-id.js +9 -0
  25. package/lib/shells.d.ts +114 -0
  26. package/lib/shells.js +187 -0
  27. package/lib/terminal.d.ts +30 -1
  28. package/lib/terminal.js +18 -5
  29. package/lib/webterminals/catalog.d.ts +36 -0
  30. package/lib/webterminals/catalog.js +93 -0
  31. package/lib/webterminals/host.d.ts +67 -0
  32. package/lib/webterminals/host.js +278 -0
  33. package/lib/webterminals/mount.d.ts +46 -0
  34. package/lib/webterminals/mount.js +171 -0
  35. package/lib/webterminals/protocol.d.ts +94 -0
  36. package/lib/webterminals/protocol.js +9 -0
  37. package/lib/webterminals/pty.d.ts +42 -0
  38. package/lib/webterminals/pty.js +64 -0
  39. package/lib/webterminals/registry.d.ts +139 -0
  40. package/lib/webterminals/registry.js +353 -0
  41. package/lib/webterminals/ws.d.ts +54 -0
  42. package/lib/webterminals/ws.js +140 -0
  43. package/locale/de.json +4 -0
  44. package/locale/en.json +4 -0
  45. package/locale/es.json +4 -0
  46. package/locale/fr.json +4 -0
  47. package/locale/it.json +4 -0
  48. package/locale/ja.json +4 -0
  49. package/locale/ko.json +4 -0
  50. package/locale/ru.json +4 -0
  51. package/locale/zh.json +4 -0
  52. package/package.json +131 -121
  53. package/scripts/build-browser-tests.mjs +36 -0
  54. package/scripts/build-client.mjs +10 -0
  55. package/scripts/check-artifacts.mjs +93 -0
  56. package/scripts/link-shells.mjs +75 -0
  57. package/src/browser-i18n.ts +27 -0
  58. package/src/client.tsx +539 -134
  59. package/src/dsh-types.ts +6 -0
  60. package/src/dsh.ts +2 -0
  61. package/src/index.ts +146 -35
  62. package/src/locales.ts +434 -0
  63. package/src/settings-surface.ts +59 -0
  64. package/src/shell-id.ts +11 -0
  65. package/src/shells.ts +250 -0
  66. package/src/terminal.ts +34 -5
  67. package/src/webterminals/browser/api.ts +212 -0
  68. package/src/webterminals/browser/bridge.ts +188 -0
  69. package/src/webterminals/browser/css.d.ts +16 -0
  70. package/src/webterminals/browser/face.ts +151 -0
  71. package/src/webterminals/browser/shell-picker.tsx +98 -0
  72. package/src/webterminals/browser/store.ts +40 -0
  73. package/src/webterminals/browser/tab.tsx +136 -0
  74. package/src/webterminals/browser/testkit.ts +21 -0
  75. package/src/webterminals/browser/url.ts +70 -0
  76. package/src/webterminals/browser/view.ts +381 -0
  77. package/src/webterminals/browser/xterm.ts +269 -0
  78. package/src/webterminals/catalog.ts +114 -0
  79. package/src/webterminals/host.ts +361 -0
  80. package/src/webterminals/mount.ts +227 -0
  81. package/src/webterminals/protocol.ts +78 -0
  82. package/src/webterminals/pty.ts +90 -0
  83. package/src/webterminals/registry.ts +447 -0
  84. package/src/webterminals/ws.ts +166 -0
  85. package/tsconfig.client.json +9 -1
  86. package/tsconfig.json +1 -1
package/src/shells.ts ADDED
@@ -0,0 +1,250 @@
1
+ // dsh-bash-terminal-ts: the shell catalog for the browser-side terminal.
2
+ //
3
+ // Why this file exists separately from `buildArgv` / `terminalArgv` / `buildEnv`
4
+ // in index.ts and terminal.ts: those three serve the MODEL tool, where a dumb
5
+ // terminal and a stripped environment are correct (no colour, no pager, one
6
+ // command per call). The browser terminal is the opposite contract - a real
7
+ // xterm emulator driven by a human who expects their profile, their prompt and
8
+ // their colours. Sharing the tool's argv/env would hand the user a shell with
9
+ // `TERM=dumb`, `NO_COLOR=1` and `-NoProfile`.
10
+ //
11
+ // So this module owns the UI-facing rules and REUSES the parts that are
12
+ // genuinely shared: the executable candidate lists (injected by index.ts, which
13
+ // keeps the dependency one-way and this file unit-testable), the MSYS2 `MSYSTEM`
14
+ // rule, and the WSL interactive argv shape.
15
+ //
16
+ // Everything here is pure: no fs, no child_process, no module-level cache. The
17
+ // caller injects `fsProbe` / `distros` and owns the TTL.
18
+
19
+ import type { ResolvedPaths } from "./dsh-types.js";
20
+ import type { ShellId } from "./shell-id.js";
21
+
22
+ /** Re-exported so existing importers keep working (see shell-id.ts for why). */
23
+ export type { ShellId };
24
+
25
+ /** Catalog order = fallback order: powershell is BOTH first choice and floor. */
26
+ export const SHELL_PRIORITY: readonly ShellId[] = ["powershell", "gitbash", "msys2", "wsl"];
27
+
28
+ /** Why one backend is not launchable (drives the settings-row badge). */
29
+ export type ShellUnavailable = "installed" | "not-installed" | "no-distro" | "launcher-only";
30
+
31
+ /** One catalog row: what the UI shows and what the host would spawn. */
32
+ export interface ShellEntry {
33
+ readonly id: ShellId;
34
+ /** Display label (a catalog constant, never inferred from the file name). */
35
+ readonly label: string;
36
+ /** Resolved executable, absent when the backend is not usable. */
37
+ readonly path?: string;
38
+ readonly available: boolean;
39
+ readonly reason: ShellUnavailable;
40
+ /** The activation switch state (powershell is always true: the floor). */
41
+ readonly activated: boolean;
42
+ /** False only for powershell, which the user cannot turn off. */
43
+ readonly togglable: boolean;
44
+ /** Interactive argv, present only when `available`. */
45
+ readonly argv?: readonly string[];
46
+ }
47
+
48
+ /** The activation switches as persisted in the plugin config. */
49
+ export interface ShellSwitches {
50
+ gitbash: boolean;
51
+ msys2: boolean;
52
+ wsl: boolean;
53
+ }
54
+
55
+ /** Everything the catalog builder needs from the outside world. */
56
+ export interface CatalogFacts {
57
+ /** Resolved executables (config override or candidate-list winner). */
58
+ paths: ResolvedPaths;
59
+ /** Whether one path is a launchable file. */
60
+ fsProbe(path: string): boolean;
61
+ /** `wsl -l -q` output. `undefined` means the probe could not answer (a timeout
62
+ * is not evidence of absence); `[]` means it answered "no distro installed". */
63
+ readonly distros: readonly string[] | undefined;
64
+ switches: ShellSwitches;
65
+ /** WSL distro override from config ('' = the WSL default). */
66
+ wslDistro: string;
67
+ }
68
+
69
+ /** Display labels. The catalog id/label pair is DECIDED BY THIS TABLE. */
70
+ const LABELS: Record<ShellId, string> = {
71
+ powershell: "PowerShell",
72
+ gitbash: "Git Bash",
73
+ msys2: "MSYS2",
74
+ wsl: "WSL bash",
75
+ };
76
+
77
+ /**
78
+ * `<SystemRoot>\System32\bash.exe` (and the sysnative mirror) is the deprecated
79
+ * WSL forwarder, not a shell. `candidateGitBashPaths` already skips it; this
80
+ * guard protects the second way a path reaches the catalog - a user-supplied
81
+ * `gitBashPath` / `msys2Path` config value.
82
+ */
83
+ export function isWslLegacyBash(path: string): boolean {
84
+ const stem = /([^\\/]+)\.exe$/i.exec(path)?.[1]?.toLowerCase();
85
+ if (stem !== "bash") return false;
86
+ return /\\(windows\\system32|sysnative)\\bash\.exe$/i.test(path.replace(/\//g, "\\"));
87
+ }
88
+
89
+ /**
90
+ * Console-allocating launchers: `git-bash.exe`, `msys2.exe`, `msys2_shell.cmd`.
91
+ * They open their own window and return zero bytes on a piped stdio (measured
92
+ * against MSYS2 with bash 5.3.15), so they can never host an embedded terminal.
93
+ */
94
+ export function isConsoleLauncher(path: string): boolean {
95
+ const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1).toLowerCase();
96
+ return name === "git-bash.exe" || name === "msys2.exe" || name === "msys2_shell.cmd";
97
+ }
98
+
99
+ /**
100
+ * Interactive argv for the BROWSER terminal.
101
+ *
102
+ * Differences from the tool's `terminalArgv`: PowerShell keeps its profile (the
103
+ * user's aliases and prompt are the point of a UI terminal), and the three bash
104
+ * families are unchanged because those rules are about the shell itself:
105
+ * Git Bash needs `-i`, MSYS2 needs `-l` and NEVER `-lc` (this argv carries no
106
+ * command, and `bash -lc` with no operand exits 2), WSL needs `-- bash -i` on the
107
+ * default distro (bare `-e` fails under ConPTY with RPC 0x8007072c).
108
+ */
109
+ export function uiArgv(shell: ShellId, paths: ResolvedPaths, wslDistro = ""): string[] {
110
+ switch (shell) {
111
+ case "powershell":
112
+ return [requirePath(paths.pwsh, shell), "-NoLogo"];
113
+ case "gitbash":
114
+ return [requirePath(paths.gitbash, shell), "-i"];
115
+ case "msys2":
116
+ return [requirePath(paths.msys2, shell), "-l"];
117
+ case "wsl": {
118
+ const distro = wslDistro.trim();
119
+ return distro.length > 0
120
+ ? [requirePath(paths.wsl, shell), "-d", distro, "-e", "bash", "-i"]
121
+ : [requirePath(paths.wsl, shell), "--", "bash", "-i"];
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Environment for the BROWSER terminal: the host process environment plus a real
128
+ * terminal type. `buildEnv` is deliberately NOT reused - it layers
129
+ * `TERM=dumb`/`NO_COLOR=1`/`PAGER=cat` over an agent-scoped map, which is right
130
+ * for a one-shot tool call and wrong for an interactive screen.
131
+ *
132
+ * The one rule carried over is MSYS2's `MSYSTEM`: without it MSYS2 starts in the
133
+ * bare MSYS environment and `/etc/profile` never puts `/mingw64/bin` on PATH, so
134
+ * gcc/make are missing in the very shell the user chose to get them from. An
135
+ * explicit value in the base environment wins, exactly as in `buildEnv`.
136
+ */
137
+ export function uiEnv(shell: ShellId, baseEnv: NodeJS.ProcessEnv): Record<string, string | undefined> {
138
+ const env: Record<string, string | undefined> = { ...baseEnv };
139
+ // A UI terminal is an xterm: the tool's `dumb` would kill colours, cursor
140
+ // control and full-screen programs.
141
+ env.TERM = "xterm-256color";
142
+ if (shell === "msys2" && env.MSYSTEM === undefined) env.MSYSTEM = "MINGW64";
143
+ return env;
144
+ }
145
+
146
+ function requirePath(path: string | undefined, shell: ShellId): string {
147
+ if (path === undefined || path.length === 0) {
148
+ throw new Error(`terminal: ${shell} backend unavailable - no executable resolved`);
149
+ }
150
+ return path;
151
+ }
152
+
153
+ /** One row's availability, given the injected facts. */
154
+ function probe(id: ShellId, facts: CatalogFacts): { available: boolean; reason: ShellUnavailable; path?: string } {
155
+ const path = id === "powershell" ? facts.paths.pwsh : id === "gitbash" ? facts.paths.gitbash : id === "msys2" ? facts.paths.msys2 : facts.paths.wsl;
156
+ if (path === undefined || path.length === 0) return { available: false, reason: "not-installed" };
157
+ // A configured path is honoured, but a launcher is not a shell: trusting the
158
+ // config here is how `msys2.exe` ends up in the menu and returns no output.
159
+ if (isConsoleLauncher(path)) return { available: false, reason: "launcher-only", path };
160
+ if (isWslLegacyBash(path)) return { available: false, reason: "launcher-only", path };
161
+ if (!facts.fsProbe(path)) return { available: false, reason: "not-installed", path };
162
+ if (id === "wsl" && facts.distros !== undefined && facts.distros.length === 0) return { available: false, reason: "no-distro", path };
163
+ return { available: true, reason: "installed", path };
164
+ }
165
+
166
+ /**
167
+ * The catalog the settings page and the spawn path both read.
168
+ *
169
+ * `powershell` is never `activated: false` even if a switch said so: it is the
170
+ * floor of the fallback chain (R2/R6), and a floor that can be removed is not a
171
+ * floor. The caller sees that through `togglable: false`.
172
+ */
173
+ export function buildCatalog(facts: CatalogFacts): ShellEntry[] {
174
+ return SHELL_PRIORITY.map((id) => {
175
+ const probed = probe(id, facts);
176
+ const activated = id === "powershell" ? true : probed.available && facts.switches[id] === true;
177
+ const argv = activated && probed.available ? uiArgv(id, facts.paths, facts.wslDistro) : undefined;
178
+ return {
179
+ id,
180
+ label: LABELS[id],
181
+ ...(probed.path !== undefined ? { path: probed.path } : {}),
182
+ available: probed.available,
183
+ reason: probed.reason,
184
+ activated,
185
+ // Only powershell is un-togglable, and that is the floor rule above.
186
+ togglable: id !== "powershell",
187
+ ...(argv !== undefined ? { argv } : {}),
188
+ };
189
+ });
190
+ }
191
+
192
+ /** The result of resolving which shell a terminal should start with. */
193
+ export interface ResolvedDefault {
194
+ readonly id: ShellId | "cmd";
195
+ readonly path: string;
196
+ readonly argv: readonly string[];
197
+ /** True when the stored value was replaced (the UI shows why). */
198
+ readonly fellBack: boolean;
199
+ /** True when nothing is activated and the floor was used. */
200
+ readonly floor: boolean;
201
+ /** The stored value that was not honoured, when there was one. */
202
+ readonly from?: string;
203
+ }
204
+
205
+ /**
206
+ * Decide the shell for one allocation (R4/R5/R6).
207
+ *
208
+ * Three distinct outcomes, because the UI has to say different things about them:
209
+ * - `""` means the user never chose: take the first candidate, no notice;
210
+ * - a non-empty value outside the candidates means the choice went stale (a
211
+ * switch was turned off, or a shell was uninstalled): fall back AND report
212
+ * `fellBack` with the original value;
213
+ * - no candidate at all: the floor is PowerShell's own chain (pwsh 7 -> Windows
214
+ * PowerShell), and `cmd.exe` is the last resort when even that is gone.
215
+ *
216
+ * The stored config is never rewritten here - a fallback that persists would
217
+ * silently eat the user's choice.
218
+ */
219
+ export function resolveDefaultShell(catalog: readonly ShellEntry[], configured: string, paths: ResolvedPaths): ResolvedDefault {
220
+ const usable = SHELL_PRIORITY
221
+ .map((id) => catalog.find((entry) => entry.id === id))
222
+ .filter((entry): entry is ShellEntry => entry !== undefined && entry.activated && entry.available && entry.path !== undefined);
223
+ const wanted = configured.trim();
224
+ const chosen = wanted.length === 0 ? undefined : usable.find((entry) => entry.id === wanted);
225
+ const picked = chosen ?? usable[0];
226
+ if (picked !== undefined) {
227
+ return {
228
+ id: picked.id,
229
+ path: picked.path!,
230
+ argv: picked.argv ?? uiArgv(picked.id, paths),
231
+ fellBack: chosen === undefined && wanted.length > 0,
232
+ floor: false,
233
+ ...(chosen === undefined && wanted.length > 0 ? { from: wanted } : {}),
234
+ };
235
+ }
236
+ // Nothing activated: the floor. `paths.pwsh` is already the candidate-list
237
+ // winner (pwsh 7 -> PATH pwsh -> Windows PowerShell 5.1), so the only step
238
+ // below it is cmd.exe, which exists on every Windows host and is enough to
239
+ // type in.
240
+ const floorPath = paths.pwsh ?? "C:\\Windows\\System32\\cmd.exe";
241
+ const isCmd = /\cmd\.exe$/i.test(floorPath);
242
+ return {
243
+ id: isCmd ? "cmd" : "powershell",
244
+ path: floorPath,
245
+ argv: isCmd ? [floorPath] : [floorPath, "-NoLogo"],
246
+ fellBack: wanted.length > 0,
247
+ floor: true,
248
+ ...(wanted.length > 0 ? { from: wanted } : {}),
249
+ };
250
+ }
package/src/terminal.ts CHANGED
@@ -128,6 +128,8 @@ function createBuffer(): TerminalBuffer {
128
128
  interface NodePtyTerm {
129
129
  pid: number;
130
130
  write(data: string): void;
131
+ /** Resize the PTY window (ConPTY propagates it to the foreground process). */
132
+ resize(cols: number, rows: number): void;
131
133
  kill(signal?: string): void;
132
134
  onData(callback: (chunk: string) => void): void;
133
135
  onExit(callback: (event: { exitCode: number; signal: unknown }) => void): void;
@@ -153,21 +155,45 @@ async function waitForPid(term: NodePtyTerm, timeoutMs = 5000): Promise<void> {
153
155
  }
154
156
  }
155
157
 
158
+ /** Terminal-emulator options for one PTY allocation. */
159
+ export interface PtyStyle {
160
+ /** The terminal type the PTY advertises (and the one `$TERM` should say). */
161
+ readonly name: string;
162
+ /**
163
+ * Variables forced into the child environment. The model tool pins
164
+ * `TERM=dumb`/`NO_COLOR=1` so output stays parseable; the browser terminal
165
+ * passes `{}` because its whole point is a coloured, cursor-controlled screen.
166
+ */
167
+ readonly forceEnv: Readonly<Record<string, string | undefined>>;
168
+ }
169
+
170
+ /** The tool's own style: a dumb, colourless, pager-free screen. */
171
+ export const TOOL_PTY_STYLE: PtyStyle = { name: "dumb", forceEnv: { TERM: "dumb", NO_COLOR: "1" } };
172
+
173
+ /** The browser terminal's style: a real xterm, colours and cursor control on. */
174
+ export const UI_PTY_STYLE: PtyStyle = { name: "xterm-256color", forceEnv: {} };
175
+
156
176
  /**
157
177
  * Direct node-pty handle with the same surface the official seam returns:
158
- * output (stream), pid, done, write / signalForeground / terminate. Used on
159
- * win32 where the official spawnTerminal's process inspector is unsupported.
178
+ * output (stream), pid, done, write / signalForeground / terminate, plus
179
+ * `resize` (which the seam only grew on newer host lines, so callers probe).
180
+ * Used on win32, where the official `spawnTerminal`'s process inspector is
181
+ * unsupported.
182
+ *
183
+ * `style` is a parameter rather than a constant because the ConPTY quirks below
184
+ * are shared by both consumers: a second copy of this function is how the
185
+ * browser terminal would end up with the tool's `TERM=dumb`.
160
186
  */
161
- async function spawnPtyHandle(spec: TerminalSpawnSpec): Promise<TerminalHandle> {
187
+ export async function spawnPtyHandle(spec: TerminalSpawnSpec, style: PtyStyle = TOOL_PTY_STYLE): Promise<TerminalHandle & { resize(cols: number, rows: number): void }> {
162
188
  const { argv, cwd, env, rows, cols } = spec;
163
189
  const mod = (await import("node-pty")) as unknown as { default?: { spawn: NodePtySpawn }; spawn: NodePtySpawn };
164
190
  const nodePty = mod.default ?? mod;
165
191
  const term = nodePty.spawn(argv[0]!, argv.slice(1), {
166
- name: "dumb",
192
+ name: style.name,
167
193
  cols,
168
194
  rows,
169
195
  cwd,
170
- env: { ...env, TERM: "dumb", NO_COLOR: "1" }
196
+ env: { ...env, ...style.forceEnv },
171
197
  });
172
198
  await waitForPid(term);
173
199
  const output = new PassThrough();
@@ -180,6 +206,9 @@ async function spawnPtyHandle(spec: TerminalSpawnSpec): Promise<TerminalHandle>
180
206
  output,
181
207
  done,
182
208
  write: (data) => term.write(data),
209
+ // ConPTY honours a real resize; the tool path never calls it, so this is the
210
+ // one seam capability the browser terminal adds on top of the same handle.
211
+ resize: (nextCols, nextRows) => term.resize(nextCols, nextRows),
183
212
  // node-pty accepts no named signals on Windows: Ctrl+C is the \x03 byte
184
213
  // (ConPTY delivers it to the foreground process), other signals degrade
185
214
  // to terminating the session.
@@ -0,0 +1,212 @@
1
+ // The browser-side caller of this plugin's host channels.
2
+ //
3
+ // Three transports, and the split is deliberate:
4
+ //
5
+ // - `/api/bash-terminal/config` is the **legacy** preference bridge. It predates
6
+ // this feature, answers `GET` with the current shell and `POST {defaultShell}`
7
+ // to write it, and works on all six host lines. Untouched by us, because the
8
+ // model tool and older hosts read it.
9
+ // - `/api/bash-terminal/terminals` is the **op** route (catalog, switches,
10
+ // allocate, close, list). It is POST-only and self-describing, so a host without
11
+ // it reports "not mounted" instead of pretending.
12
+ // - only the PTY byte stream gets a socket.
13
+ //
14
+ // Mixing them up is not a harmless refactor: posting `{op:"get"}` at the legacy
15
+ // bridge reads `defaultShell: undefined`, fails its enum check and returns
16
+ // `invalid-shell` - which is precisely the bug this file had for one revision.
17
+ //
18
+ // The URL shape comes from `url.ts`, so a reverse-proxy prefix and the `dsh-app:`
19
+ // shell both resolve correctly.
20
+
21
+ import { hostRouteUrl, hostWebSocketUrl } from "./url";
22
+
23
+ /** The legacy preference bridge (GET reads, POST `{defaultShell}` writes). */
24
+ const CONFIG_PATH = "api/bash-terminal/config";
25
+
26
+ /** The op route for everything the browser terminal owns. */
27
+ const TERMINALS_PATH = "api/bash-terminal/terminals";
28
+
29
+ /** The terminal socket path. */
30
+ const WS_PATH = "bash-terminal/ws";
31
+
32
+ /** One catalog row as the host reports it. */
33
+ export interface CatalogEntry {
34
+ readonly id: string;
35
+ readonly label: string;
36
+ readonly path?: string;
37
+ readonly available: boolean;
38
+ readonly reason: "installed" | "not-installed" | "no-distro" | "launcher-only";
39
+ readonly activated: boolean;
40
+ readonly togglable: boolean;
41
+ readonly argv?: readonly string[];
42
+ }
43
+
44
+ /** What an allocation would actually use, after the fallback chain. */
45
+ export interface EffectiveShell {
46
+ readonly id: string;
47
+ readonly fellBack: boolean;
48
+ readonly floor: boolean;
49
+ readonly from?: string;
50
+ }
51
+
52
+ /** The `GET config` payload. */
53
+ export interface ConfigSnapshot {
54
+ readonly defaultShell: string;
55
+ readonly shells: readonly string[];
56
+ readonly seam: { readonly spawn: string; readonly spawnTerminal: string };
57
+ readonly catalog?: readonly CatalogEntry[];
58
+ /** What an allocation WOULD use, after the fallback chain. */
59
+ readonly effective?: EffectiveShell;
60
+ readonly unavailable?: string;
61
+ /** The master switch (level 1). Absent only on a host without the op route. */
62
+ readonly enabled?: boolean;
63
+ /**
64
+ * The opt-in to publishing `webTerminals` for the official bottom row. False unless an
65
+ * operator turns it on - publishing it by default collides with the host's own terminal
66
+ * controller and fails that entry.
67
+ */
68
+ readonly shimOfficialTerminal?: boolean;
69
+ /**
70
+ * Whether the host renders a settings page (`"page"`), declares the slots but has no
71
+ * page (`"none"`, i.e. 0.1.0/0.1.1), or has not answered yet (`"unknown"`). The client
72
+ * shows its own floating panel only on `"none"` - everywhere else it would be a third
73
+ * settings surface, and on the oldest lines a registered card is unreachable.
74
+ */
75
+ readonly settingsSurface?: string;
76
+ /** The stored WSL distro, so the settings input can show the real value. */
77
+ readonly wslDistro?: string;
78
+ /** How many terminals the host still holds (an exited one counts until closed). */
79
+ readonly terminals?: number;
80
+ /** True when the host itself provides `webTerminals` and this shim stands down. */
81
+ readonly hostTerminals?: boolean;
82
+ }
83
+
84
+ /** One bridge reply, read structurally: `ok` decides the branch. */
85
+ interface MaybeReply {
86
+ ok?: unknown;
87
+ value?: unknown;
88
+ code?: unknown;
89
+ message?: unknown;
90
+ }
91
+
92
+ /** A refused bridge call, carrying the host's machine-readable code. */
93
+ export class BridgeError extends Error {
94
+ readonly code: string;
95
+
96
+ constructor(code: string, message: string) {
97
+ super(message);
98
+ this.name = "BridgeError";
99
+ this.code = code;
100
+ }
101
+ }
102
+
103
+ /** Unwrap one reply envelope. */
104
+ function unwrap(reply: MaybeReply): unknown {
105
+ if (reply.ok === true) return reply.value;
106
+ const code = typeof reply.code === "string" ? reply.code : typeof reply.message === "string" ? "failed" : "no-route";
107
+ const message = typeof reply.message === "string" ? reply.message : "the bridge refused the request";
108
+ throw new BridgeError(code, message);
109
+ }
110
+
111
+ /** POST one body to a path and return the unwrapped `value`. */
112
+ async function postTo<T>(path: string, body: Record<string, unknown>): Promise<T> {
113
+ const url = hostRouteUrl(path);
114
+ let response: Response;
115
+ try {
116
+ response = await fetch(url.toString(), {
117
+ method: "POST",
118
+ headers: { "content-type": "application/json" },
119
+ body: JSON.stringify(body),
120
+ credentials: "same-origin",
121
+ });
122
+ } catch (error) {
123
+ throw new BridgeError("no-route", `the bridge did not answer (${error instanceof Error ? error.message : String(error)})`);
124
+ }
125
+ let reply: MaybeReply;
126
+ try {
127
+ reply = (await response.json()) as MaybeReply;
128
+ } catch {
129
+ // An HTML 404 (route absent) or an empty 500 body both land here.
130
+ throw new BridgeError("no-route", `the bridge replied with a non-JSON body (HTTP ${response.status})`);
131
+ }
132
+ return unwrap(reply) as T;
133
+ }
134
+
135
+ /** POST one op to the terminal route. */
136
+ export function post<T>(body: Record<string, unknown>): Promise<T> {
137
+ return postTo<T>(TERMINALS_PATH, body);
138
+ }
139
+
140
+ /** Read the current config + catalog (`op: get`). */
141
+ export function readConfig(): Promise<ConfigSnapshot> {
142
+ return post<ConfigSnapshot>({ op: "get" });
143
+ }
144
+
145
+ /** Flip shell switches (persisted through the host's settings channel). */
146
+ export function writeSwitches(switches: Record<string, boolean>, wslDistro?: string): Promise<ConfigSnapshot> {
147
+ return post<ConfigSnapshot>({ op: "switches", switches, ...(wslDistro !== undefined ? { wslDistro } : {}) });
148
+ }
149
+
150
+ /**
151
+ * Choose the default shell, validated against the catalog server-side (R4): a
152
+ * disabled or unavailable choice is refused rather than silently stored.
153
+ */
154
+ export function writeDefaultShell(value: string): Promise<ConfigSnapshot> {
155
+ return post<ConfigSnapshot>({ op: "default", defaultShell: value });
156
+ }
157
+
158
+ /**
159
+ * Allocate (or adopt) one terminal.
160
+ * @param shell - omit to let the host apply the activation switches and the
161
+ * fallback chain; pass a catalog id (Git Bash / MSYS2 / WSL / PowerShell) to pick
162
+ * that row explicitly. The host validates either way, so a disabled or missing
163
+ * shell is refused rather than launched.
164
+ */
165
+ export function openTerminal(input: { sessionId: string; cwd?: string; shell?: string; terminalId?: string; cols: number; rows: number }): Promise<{ info: unknown; environment: unknown }> {
166
+ return post<{ info: unknown; environment: unknown }>({ op: "terminal.open", ...input });
167
+ }
168
+
169
+ /** End one terminal and free its quota slot. */
170
+ export function closeTerminal(id: string): Promise<{ closed: boolean }> {
171
+ return post<{ closed: boolean }>({ op: "terminal.close", id });
172
+ }
173
+
174
+ /** The session's live terminals (the `recover` face). */
175
+ export function listTerminals(sessionId: string): Promise<{ terminals: unknown[] }> {
176
+ return post<{ terminals: unknown[] }>({ op: "terminal.list", sessionId });
177
+ }
178
+
179
+ /** The shell picker's view of the catalog (the controller's `launchShells` face). */
180
+ export function discoverShellsForPicker(): Promise<{ shells: readonly { path: string; args: readonly string[]; name: string }[]; selected: string | undefined }> {
181
+ return post<{ shells: readonly { path: string; args: readonly string[]; name: string }[]; selected: string | undefined }>({ op: "shells.discover" });
182
+ }
183
+
184
+ /** The socket URL for one terminal. */
185
+ export function terminalSocketUrl(id: string): URL {
186
+ const url = hostWebSocketUrl(WS_PATH);
187
+ url.search = new URLSearchParams({ id }).toString();
188
+ return url;
189
+ }
190
+
191
+ /**
192
+ * The legacy bridge's own read (GET), kept for hosts where the terminal route is
193
+ * not mounted but the preference bridge is.
194
+ */
195
+ export async function readLegacyConfig(): Promise<ConfigSnapshot | null> {
196
+ try {
197
+ const response = await fetch(hostRouteUrl(CONFIG_PATH).toString(), { method: "GET", credentials: "same-origin" });
198
+ const reply = (await response.json()) as MaybeReply;
199
+ return reply.ok === true ? (reply.value as ConfigSnapshot) : null;
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Write the default shell through the legacy bridge, for hosts where the terminal
207
+ * route is not mounted. It does no catalog validation (it predates the feature),
208
+ * so prefer {@link writeDefaultShell} when the op route answers.
209
+ */
210
+ export function writeLegacyDefault(value: string): Promise<unknown> {
211
+ return postTo<unknown>(CONFIG_PATH, { defaultShell: value });
212
+ }