dsh-bash-terminal-ts 0.8.8 → 0.9.0
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.
- package/CHANGELOG.md +201 -190
- package/README.en.md +2 -1
- package/README.md +3 -2
- package/agent-presets/README.md +171 -170
- package/agent-presets/install-presets.mjs +180 -179
- package/agent-presets/standard-win-niu/agent.cordis.yml +271 -0
- package/agent-presets/standard-win-niu/preset.yml +2 -0
- package/cordis.patch.yml +84 -83
- package/dist/client.core.js +10 -1
- package/dist/client.js +10 -1
- package/docs/dsh-plugin-development.md +169 -0
- package/docs/niu-backend.md +197 -0
- package/dsh.plugin.json +3 -3
- package/lib/client.js +10 -1
- package/lib/dsh-types.d.ts +14 -2
- package/lib/index.d.ts +15 -2
- package/lib/index.js +43 -5
- package/lib/locales.js +9 -0
- package/lib/shell-id.d.ts +1 -1
- package/lib/shells.d.ts +1 -0
- package/lib/shells.js +8 -2
- package/lib/terminal.js +4 -0
- package/lib/webterminals/host.js +2 -2
- package/lib/webterminals/mount.js +1 -0
- package/locale/de.json +6 -6
- package/locale/en.json +6 -6
- package/locale/es.json +6 -6
- package/locale/fr.json +6 -6
- package/locale/it.json +6 -6
- package/locale/ja.json +6 -6
- package/locale/ko.json +6 -6
- package/locale/ru.json +6 -6
- package/locale/zh.json +6 -6
- package/package.json +151 -149
- package/scripts/check-artifacts.mjs +96 -96
- package/src/client.tsx +685 -685
- package/src/dsh-types.ts +332 -320
- package/src/index.ts +1316 -1275
- package/src/locales.ts +461 -452
- package/src/shell-id.ts +11 -11
- package/src/shells.ts +279 -272
- package/src/terminal.ts +616 -612
- package/src/webterminals/host.ts +361 -361
- package/src/webterminals/mount.ts +237 -236
package/src/webterminals/host.ts
CHANGED
|
@@ -1,361 +1,361 @@
|
|
|
1
|
-
// The host half of the browser terminal: one JSON route for the requests and the
|
|
2
|
-
// socket mount for the byte stream.
|
|
3
|
-
//
|
|
4
|
-
// Why a separate route from the existing `/api/bash-terminal/config` bridge: that
|
|
5
|
-
// bridge is the model tool's preference channel and works on all six host lines;
|
|
6
|
-
// this one serves a feature that must exist even on a line where the tool itself
|
|
7
|
-
// is not registered (the browser terminal is not a Windows-only idea - the tool
|
|
8
|
-
// is). Keeping them apart means the tool's behaviour cannot regress when the
|
|
9
|
-
// terminal ships, and each route can be probed separately in the settings page.
|
|
10
|
-
//
|
|
11
|
-
// The host, not the browser, decides which shell an allocation uses: it reads the
|
|
12
|
-
// catalog (activation + availability) and the fallback chain, so a client can
|
|
13
|
-
// never launch a shell the user disabled, and a stale `defaultShell` degrades
|
|
14
|
-
// visibly instead of failing.
|
|
15
|
-
|
|
16
|
-
import type { ServerResponse } from "node:http";
|
|
17
|
-
import type { CatalogFacts, ResolvedDefault, ShellEntry, ShellSwitches } from "../shells.js";
|
|
18
|
-
import type { SettingsSurface } from "../settings-surface.js";
|
|
19
|
-
import { resolveDefaultShell, uiArgv } from "../shells.js";
|
|
20
|
-
import type { ShellId } from "../shell-id.js";
|
|
21
|
-
import type { UiTerminalInfo } from "./protocol.js";
|
|
22
|
-
import { UiTerminalError } from "./registry.js";
|
|
23
|
-
import type { UiTerminalRegistry } from "./registry.js";
|
|
24
|
-
import { mountTerminalSocket, type UpgradeCapableServer } from "./ws.js";
|
|
25
|
-
|
|
26
|
-
/** The JSON route path (POST-only, loopback-gated like the config bridge). */
|
|
27
|
-
export const TERMINAL_API_PATH = "/api/bash-terminal/terminals";
|
|
28
|
-
|
|
29
|
-
/** What the caller must supply; everything fs/session-related stays outside this file. */
|
|
30
|
-
export interface UiBridgeDeps {
|
|
31
|
-
/** A live catalog (the caller owns the TTL cache). */
|
|
32
|
-
catalog(): ShellEntry[];
|
|
33
|
-
/** The catalog facts, for the paths the fallback chain still needs. */
|
|
34
|
-
paths(): CatalogFacts["paths"];
|
|
35
|
-
/** The stored default (`''` when the user never chose). */
|
|
36
|
-
configuredShell(): string;
|
|
37
|
-
/** The stored switches, already defaulted against discovery. */
|
|
38
|
-
switches(): ShellSwitches;
|
|
39
|
-
/** The stored WSL distro (`''` = the WSL default), echoed so the input can show it. */
|
|
40
|
-
wslDistro(): string;
|
|
41
|
-
/** The UI environment for one backend (process.env plus its own rules). */
|
|
42
|
-
env(id: ShellId): Record<string, string | undefined>;
|
|
43
|
-
/**
|
|
44
|
-
* The master switch. Off is not "no shells chosen": the child switches are hidden
|
|
45
|
-
* (a switch for something that cannot run is a lie), and no allocation is served.
|
|
46
|
-
*/
|
|
47
|
-
enabled(): boolean;
|
|
48
|
-
/**
|
|
49
|
-
* The opt-in that lets this plugin publish the `webTerminals` service for
|
|
50
|
-
* dsh-better-sidebar's OFFICIAL terminal row. Default false: on a host that ships
|
|
51
|
-
* its own terminal controller, the first client to `provide` that name wins and the
|
|
52
|
-
* loser's entry fails - and the controller's provide is unguarded, so an opt-out
|
|
53
|
-
* default would break the first-party terminal (measured on 0.2.0-rc.2).
|
|
54
|
-
*/
|
|
55
|
-
shimOfficialTerminal(): boolean;
|
|
56
|
-
/**
|
|
57
|
-
* Whether this host line renders a settings page at all (`src/settings-surface.ts`).
|
|
58
|
-
* The client cannot probe this and must not guess: on 0.1.0/0.1.1 the `settings.*` slot
|
|
59
|
-
* map exists but no page renders it, so a registered card is unreachable - and those are
|
|
60
|
-
* the only lines where the plugin's own floating panel is the way in.
|
|
61
|
-
*/
|
|
62
|
-
settingsSurface(): SettingsSurface;
|
|
63
|
-
/** Persist one config path (the caller wires `settings.mutate`). */
|
|
64
|
-
writeConfig(path: readonly string[], value: unknown): Promise<void>;
|
|
65
|
-
/** Allocate a terminal for one session; the host picks the shell. */
|
|
66
|
-
registry: UiTerminalRegistry;
|
|
67
|
-
/** The session's working directory ('' when the host cannot say). */
|
|
68
|
-
cwdFor(sessionId: string): string;
|
|
69
|
-
/** Why the bridge cannot serve a terminal, or 'ok'. */
|
|
70
|
-
unavailableReason(): string;
|
|
71
|
-
/** Loopback gate, shared with the config bridge's rule. */
|
|
72
|
-
isLoopback(request: { socket?: { remoteAddress?: string } }): boolean;
|
|
73
|
-
log?(level: "info" | "warn", message: string): void;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** One JSON request body, read structurally. */
|
|
77
|
-
interface RequestBody {
|
|
78
|
-
op?: unknown;
|
|
79
|
-
sessionId?: unknown;
|
|
80
|
-
terminalId?: unknown;
|
|
81
|
-
/** An explicit shell id for this allocation (validated against the catalog). */
|
|
82
|
-
shell?: unknown;
|
|
83
|
-
cols?: unknown;
|
|
84
|
-
rows?: unknown;
|
|
85
|
-
id?: unknown;
|
|
86
|
-
switches?: unknown;
|
|
87
|
-
wslDistro?: unknown;
|
|
88
|
-
defaultShell?: unknown;
|
|
89
|
-
enabled?: unknown;
|
|
90
|
-
shim?: unknown;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** Write one reply in the envelope the config bridge already uses. */
|
|
94
|
-
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
95
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
96
|
-
res.end(JSON.stringify(body));
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** Read one bounded JSON body. */
|
|
100
|
-
async function readBody(request: {
|
|
101
|
-
on(event: "data", cb: (chunk: Buffer) => void): void;
|
|
102
|
-
on(event: "end", cb: () => void): void;
|
|
103
|
-
on(event: "error", cb: (error: Error) => void): void;
|
|
104
|
-
}): Promise<RequestBody> {
|
|
105
|
-
const chunks: Buffer[] = [];
|
|
106
|
-
let size = 0;
|
|
107
|
-
const raw = await new Promise<Buffer>((resolve, reject) => {
|
|
108
|
-
request.on("data", (chunk: Buffer) => {
|
|
109
|
-
size += chunk.length;
|
|
110
|
-
if (size <= 65536) chunks.push(chunk);
|
|
111
|
-
});
|
|
112
|
-
request.on("end", () => { resolve(Buffer.concat(chunks)); });
|
|
113
|
-
request.on("error", reject);
|
|
114
|
-
});
|
|
115
|
-
if (raw.length === 0) return {};
|
|
116
|
-
return JSON.parse(raw.toString("utf8")) as RequestBody;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** Coerce a number field with a bound. */
|
|
120
|
-
function num(value: unknown, fallback: number, max: number): number {
|
|
121
|
-
return typeof value === "number" && Number.isFinite(value) ? Math.max(1, Math.min(max, Math.floor(value))) : fallback;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* The config field behind each switch, spelled out rather than derived.
|
|
126
|
-
*
|
|
127
|
-
* A computed name (`"shell" + cap(key)`) produces `shellGitbash` while the schema
|
|
128
|
-
* declares `shellGitBash` - the write would land on a key that does not exist,
|
|
129
|
-
* persist nothing, and look fine in the settings page. Two spellings of one fact
|
|
130
|
-
* always drift, so this table is the single place the name appears.
|
|
131
|
-
*/
|
|
132
|
-
const SWITCH_FIELD: Record<string, string> = { gitbash: "shellGitBash", msys2: "shellMsys2", wsl: "shellWsl", payload: "shellPayload" };
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Register the terminal routes.
|
|
136
|
-
* @param webServer - the host webserver (may lack upgrade support).
|
|
137
|
-
* @param deps - the wiring above.
|
|
138
|
-
* @returns a disposer, plus the reason when the host cannot carry a socket.
|
|
139
|
-
*/
|
|
140
|
-
export function registerUiTerminalRoutes(webServer: UpgradeCapableServer | undefined, deps: UiBridgeDeps): { dispose(): void; socket: "mounted" | "no-websocket-route" } {
|
|
141
|
-
const handler = async (request: { method?: string; socket?: { remoteAddress?: string } }, res: ServerResponse): Promise<void> => {
|
|
142
|
-
if (!deps.isLoopback(request)) {
|
|
143
|
-
json(res, 403, { ok: false, code: "loopback-only" });
|
|
144
|
-
return;
|
|
145
|
-
}
|
|
146
|
-
if (request.method !== "POST") {
|
|
147
|
-
json(res, 405, { ok: false, code: "method-not-allowed" });
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
let body: RequestBody;
|
|
151
|
-
try {
|
|
152
|
-
body = await readBody(request as never);
|
|
153
|
-
} catch {
|
|
154
|
-
json(res, 400, { ok: false, code: "bad-json" });
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
try {
|
|
158
|
-
const value = await dispatch(body, deps);
|
|
159
|
-
json(res, 200, { ok: true, value });
|
|
160
|
-
} catch (error) {
|
|
161
|
-
const code = error instanceof UiTerminalError ? error.code : error instanceof Error ? "failed" : "failed";
|
|
162
|
-
json(res, error instanceof UiTerminalError ? error.status : 500, {
|
|
163
|
-
ok: false,
|
|
164
|
-
code,
|
|
165
|
-
message: error instanceof Error ? error.message : String(error),
|
|
166
|
-
});
|
|
167
|
-
}
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
const disposers: Array<() => void> = [];
|
|
171
|
-
const registered = webServer?.register?.({ kind: "exact", path: TERMINAL_API_PATH, handler: handler as never });
|
|
172
|
-
if (typeof registered === "function") disposers.push(registered);
|
|
173
|
-
const mount = mountTerminalSocket(
|
|
174
|
-
{ registry: deps.registry, environmentFor: (cwd) => deps.registry.environment(cwd), isLoopback: (request) => deps.isLoopback(request) },
|
|
175
|
-
webServer,
|
|
176
|
-
);
|
|
177
|
-
if (mount.ok) disposers.push(mount.dispose);
|
|
178
|
-
return {
|
|
179
|
-
socket: mount.ok ? "mounted" : mount.reason,
|
|
180
|
-
dispose: () => {
|
|
181
|
-
for (const dispose of disposers) {
|
|
182
|
-
try {
|
|
183
|
-
dispose();
|
|
184
|
-
} catch { /* already gone */ }
|
|
185
|
-
}
|
|
186
|
-
},
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/** One request -> one reply. */
|
|
191
|
-
async function dispatch(body: RequestBody, deps: UiBridgeDeps): Promise<unknown> {
|
|
192
|
-
const op = typeof body.op === "string" ? body.op : "";
|
|
193
|
-
// Everything below the master switch is gated by it. `switches` is included: an
|
|
194
|
-
// off feature that still accepts child edits would store choices it ignores, and
|
|
195
|
-
// the settings row would show them as applied.
|
|
196
|
-
if (!deps.enabled() && op !== "get" && op !== "enabled") {
|
|
197
|
-
throw new UiTerminalError("disabled", "the bottom terminal is switched off in settings", 409);
|
|
198
|
-
}
|
|
199
|
-
switch (op) {
|
|
200
|
-
case "get": {
|
|
201
|
-
const catalog = deps.catalog();
|
|
202
|
-
return {
|
|
203
|
-
catalog,
|
|
204
|
-
effective: effectiveShell(deps),
|
|
205
|
-
switches: deps.switches(),
|
|
206
|
-
defaultShell: deps.configuredShell(),
|
|
207
|
-
wslDistro: deps.wslDistro(),
|
|
208
|
-
enabled: deps.enabled(),
|
|
209
|
-
shimOfficialTerminal: deps.shimOfficialTerminal(),
|
|
210
|
-
settingsSurface: deps.settingsSurface(),
|
|
211
|
-
// The master switch outranks the capability answers: "off" is the user's
|
|
212
|
-
// choice, and reporting `ok` next to a hidden panel would be the confusing
|
|
213
|
-
// half of the pair.
|
|
214
|
-
unavailable: deps.enabled() ? deps.unavailableReason() : "disabled",
|
|
215
|
-
terminals: deps.registry.count(),
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
case "shim": {
|
|
219
|
-
// Written, not inferred: whether the browser may claim the `webTerminals` name is
|
|
220
|
-
// a deployment fact only the operator knows, and the safe default is to not claim
|
|
221
|
-
// it. The client re-reads the service before publishing, so switching this on
|
|
222
|
-
// where a controller already exists cannot silently take the controller down.
|
|
223
|
-
const next = body.shim === true;
|
|
224
|
-
await deps.writeConfig(["shimOfficialTerminal"], next);
|
|
225
|
-
return { shimOfficialTerminal: deps.shimOfficialTerminal(), catalog: deps.catalog() };
|
|
226
|
-
}
|
|
227
|
-
case "enabled": {
|
|
228
|
-
// The master switch itself is always writable - refusing that would be a way
|
|
229
|
-
// to lock the feature off permanently.
|
|
230
|
-
const value = body.enabled === true;
|
|
231
|
-
await deps.writeConfig(["bottomTerminal"], value);
|
|
232
|
-
return { enabled: deps.enabled(), catalog: deps.catalog(), effective: effectiveShell(deps), switches: deps.switches() };
|
|
233
|
-
}
|
|
234
|
-
case "switches": {
|
|
235
|
-
const requested = body.switches;
|
|
236
|
-
if (requested === null || typeof requested !== "object") throw new UiTerminalError("bad-request", "switches must be an object");
|
|
237
|
-
const next = requested as Record<string, unknown>;
|
|
238
|
-
// Persist first, then answer with a rebuilt catalog: a switch that cannot be
|
|
239
|
-
// stored must not look applied in the settings row.
|
|
240
|
-
for (const key of ["gitbash", "msys2", "wsl", "payload"] as const) {
|
|
241
|
-
if (typeof next[key] === "boolean") await deps.writeConfig([SWITCH_FIELD[key]!], next[key]);
|
|
242
|
-
}
|
|
243
|
-
if (typeof body.wslDistro === "string") await deps.writeConfig(["wslDistro"], body.wslDistro);
|
|
244
|
-
return { catalog: deps.catalog(), effective: effectiveShell(deps), switches: deps.switches(), wslDistro: deps.wslDistro(), enabled: deps.enabled() };
|
|
245
|
-
}
|
|
246
|
-
case "default": {
|
|
247
|
-
const value = typeof body.defaultShell === "string" ? body.defaultShell : "";
|
|
248
|
-
const catalog = deps.catalog();
|
|
249
|
-
const row = catalog.find((entry) => entry.id === value);
|
|
250
|
-
if (row === undefined || !row.activated || !row.available) {
|
|
251
|
-
// Its own code, not a generic bad-request: the browser renders "enable that
|
|
252
|
-
// shell first" for this one and "malformed input" for the rest.
|
|
253
|
-
throw new UiTerminalError("shellNotActivated", `shell ${JSON.stringify(value)} is not an activated, available choice`, 400);
|
|
254
|
-
}
|
|
255
|
-
await deps.writeConfig(["defaultShell"], value);
|
|
256
|
-
return { catalog: deps.catalog(), effective: effectiveShell(deps) };
|
|
257
|
-
}
|
|
258
|
-
case "terminal.open": {
|
|
259
|
-
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
260
|
-
if (sessionId === "") throw new UiTerminalError("bad-request", "sessionId is required");
|
|
261
|
-
const cwd = deps.cwdFor(sessionId);
|
|
262
|
-
// An explicit `shell` is honoured ONLY when that row is activated and
|
|
263
|
-
// available: the same R4 rule the default choice obeys. This is what lets the
|
|
264
|
-
// multi-shell tab offer Git Bash and MSYS2 side by side - the host terminal
|
|
265
|
-
// controller cannot, because its menu de-duplicates shells by executable file
|
|
266
|
-
// name and both are `bash.exe`.
|
|
267
|
-
const asked = typeof body.shell === "string" ? body.shell.trim() : "";
|
|
268
|
-
const rows = deps.catalog();
|
|
269
|
-
let resolved = effectiveShell(deps);
|
|
270
|
-
if (asked !== "") {
|
|
271
|
-
const row = rows.find((entry) => entry.id === asked);
|
|
272
|
-
if (row === undefined || !row.activated || !row.available || row.path === undefined) {
|
|
273
|
-
throw new UiTerminalError("shellNotActivated", `shell ${JSON.stringify(asked)} is not an activated, available choice`, 400);
|
|
274
|
-
}
|
|
275
|
-
resolved = {
|
|
276
|
-
id: row.id,
|
|
277
|
-
path: row.path,
|
|
278
|
-
argv: row.argv ?? uiArgv(row.id, deps.paths(), ""),
|
|
279
|
-
fellBack: false,
|
|
280
|
-
floor: false,
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
const env = deps.env(resolved.id === "cmd" ? "powershell" : (resolved.id as ShellId));
|
|
284
|
-
return await openAndReport({
|
|
285
|
-
sessionId,
|
|
286
|
-
cwd,
|
|
287
|
-
resolved,
|
|
288
|
-
rows,
|
|
289
|
-
env,
|
|
290
|
-
body,
|
|
291
|
-
deps,
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
case "terminal.close": {
|
|
295
|
-
const id = typeof body.id === "string" ? body.id : "";
|
|
296
|
-
if (id === "") throw new UiTerminalError("bad-request", "id is required");
|
|
297
|
-
await deps.registry.close(id);
|
|
298
|
-
return { closed: true };
|
|
299
|
-
}
|
|
300
|
-
case "terminal.list": {
|
|
301
|
-
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
302
|
-
if (sessionId === "") throw new UiTerminalError("bad-request", "sessionId is required");
|
|
303
|
-
return { terminals: deps.registry.list(sessionId) satisfies UiTerminalInfo[] };
|
|
304
|
-
}
|
|
305
|
-
case "shells.discover": {
|
|
306
|
-
const catalog = deps.catalog();
|
|
307
|
-
const shells = catalog
|
|
308
|
-
.filter((entry) => entry.available && entry.path !== undefined)
|
|
309
|
-
.map((entry) => ({ path: entry.path!, args: entry.argv?.slice(1) ?? [], name: entry.label }));
|
|
310
|
-
return { shells, selected: deps.configuredShell() };
|
|
311
|
-
}
|
|
312
|
-
default:
|
|
313
|
-
throw new UiTerminalError("bad-request", `unknown op ${JSON.stringify(body.op)}`, 404);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/** The shell an allocation would use, recomputed from the live catalog. */
|
|
318
|
-
function effectiveShell(deps: UiBridgeDeps): ResolvedDefault {
|
|
319
|
-
return resolveDefaultShell(deps.catalog(), deps.configuredShell(), deps.paths());
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* Allocate one shell and answer in the shape the browser needs.
|
|
324
|
-
*
|
|
325
|
-
* Split out because two ops reach it (the fallback-chain default and an explicit
|
|
326
|
-
* per-tab shell choice) and the reply contract - `{info, environment}`, plus the
|
|
327
|
-
* argv slice that becomes the info's `shell` - must not be spelled twice.
|
|
328
|
-
*/
|
|
329
|
-
async function openAndReport(input: {
|
|
330
|
-
sessionId: string;
|
|
331
|
-
cwd: string;
|
|
332
|
-
resolved: ResolvedDefault;
|
|
333
|
-
rows: readonly ShellEntry[];
|
|
334
|
-
env: Record<string, string | undefined>;
|
|
335
|
-
body: RequestBody;
|
|
336
|
-
deps: UiBridgeDeps;
|
|
337
|
-
}): Promise<unknown> {
|
|
338
|
-
const { sessionId, cwd, resolved, rows, env, body, deps } = input;
|
|
339
|
-
const info = await deps.registry.open({
|
|
340
|
-
sessionId,
|
|
341
|
-
cwd,
|
|
342
|
-
shellId: resolved.id,
|
|
343
|
-
shellSpec: { path: resolved.path, args: resolved.argv.slice(1), name: labelOf(rows, resolved) },
|
|
344
|
-
title: labelOf(rows, resolved),
|
|
345
|
-
argv: [...resolved.argv],
|
|
346
|
-
env,
|
|
347
|
-
cols: num(body.cols, 80, 500),
|
|
348
|
-
rows: num(body.rows, 24, 200),
|
|
349
|
-
terminalId: typeof body.terminalId === "string" ? body.terminalId : undefined,
|
|
350
|
-
});
|
|
351
|
-
// `environment` travels with the info: the emulator cannot size itself until it
|
|
352
|
-
// has the limits, and asking for them in a second round trip would race the first
|
|
353
|
-
// output frame.
|
|
354
|
-
return { info, environment: deps.registry.environment(cwd) };
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
/** The display name of the resolved shell (the catalog label, else the id). */
|
|
358
|
-
function labelOf(catalog: readonly ShellEntry[], resolved: ResolvedDefault): string {
|
|
359
|
-
if (resolved.id === "cmd") return "cmd";
|
|
360
|
-
return catalog.find((entry) => entry.id === resolved.id)?.label ?? String(resolved.id);
|
|
361
|
-
}
|
|
1
|
+
// The host half of the browser terminal: one JSON route for the requests and the
|
|
2
|
+
// socket mount for the byte stream.
|
|
3
|
+
//
|
|
4
|
+
// Why a separate route from the existing `/api/bash-terminal/config` bridge: that
|
|
5
|
+
// bridge is the model tool's preference channel and works on all six host lines;
|
|
6
|
+
// this one serves a feature that must exist even on a line where the tool itself
|
|
7
|
+
// is not registered (the browser terminal is not a Windows-only idea - the tool
|
|
8
|
+
// is). Keeping them apart means the tool's behaviour cannot regress when the
|
|
9
|
+
// terminal ships, and each route can be probed separately in the settings page.
|
|
10
|
+
//
|
|
11
|
+
// The host, not the browser, decides which shell an allocation uses: it reads the
|
|
12
|
+
// catalog (activation + availability) and the fallback chain, so a client can
|
|
13
|
+
// never launch a shell the user disabled, and a stale `defaultShell` degrades
|
|
14
|
+
// visibly instead of failing.
|
|
15
|
+
|
|
16
|
+
import type { ServerResponse } from "node:http";
|
|
17
|
+
import type { CatalogFacts, ResolvedDefault, ShellEntry, ShellSwitches } from "../shells.js";
|
|
18
|
+
import type { SettingsSurface } from "../settings-surface.js";
|
|
19
|
+
import { resolveDefaultShell, uiArgv } from "../shells.js";
|
|
20
|
+
import type { ShellId } from "../shell-id.js";
|
|
21
|
+
import type { UiTerminalInfo } from "./protocol.js";
|
|
22
|
+
import { UiTerminalError } from "./registry.js";
|
|
23
|
+
import type { UiTerminalRegistry } from "./registry.js";
|
|
24
|
+
import { mountTerminalSocket, type UpgradeCapableServer } from "./ws.js";
|
|
25
|
+
|
|
26
|
+
/** The JSON route path (POST-only, loopback-gated like the config bridge). */
|
|
27
|
+
export const TERMINAL_API_PATH = "/api/bash-terminal/terminals";
|
|
28
|
+
|
|
29
|
+
/** What the caller must supply; everything fs/session-related stays outside this file. */
|
|
30
|
+
export interface UiBridgeDeps {
|
|
31
|
+
/** A live catalog (the caller owns the TTL cache). */
|
|
32
|
+
catalog(): ShellEntry[];
|
|
33
|
+
/** The catalog facts, for the paths the fallback chain still needs. */
|
|
34
|
+
paths(): CatalogFacts["paths"];
|
|
35
|
+
/** The stored default (`''` when the user never chose). */
|
|
36
|
+
configuredShell(): string;
|
|
37
|
+
/** The stored switches, already defaulted against discovery. */
|
|
38
|
+
switches(): ShellSwitches;
|
|
39
|
+
/** The stored WSL distro (`''` = the WSL default), echoed so the input can show it. */
|
|
40
|
+
wslDistro(): string;
|
|
41
|
+
/** The UI environment for one backend (process.env plus its own rules). */
|
|
42
|
+
env(id: ShellId): Record<string, string | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* The master switch. Off is not "no shells chosen": the child switches are hidden
|
|
45
|
+
* (a switch for something that cannot run is a lie), and no allocation is served.
|
|
46
|
+
*/
|
|
47
|
+
enabled(): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* The opt-in that lets this plugin publish the `webTerminals` service for
|
|
50
|
+
* dsh-better-sidebar's OFFICIAL terminal row. Default false: on a host that ships
|
|
51
|
+
* its own terminal controller, the first client to `provide` that name wins and the
|
|
52
|
+
* loser's entry fails - and the controller's provide is unguarded, so an opt-out
|
|
53
|
+
* default would break the first-party terminal (measured on 0.2.0-rc.2).
|
|
54
|
+
*/
|
|
55
|
+
shimOfficialTerminal(): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Whether this host line renders a settings page at all (`src/settings-surface.ts`).
|
|
58
|
+
* The client cannot probe this and must not guess: on 0.1.0/0.1.1 the `settings.*` slot
|
|
59
|
+
* map exists but no page renders it, so a registered card is unreachable - and those are
|
|
60
|
+
* the only lines where the plugin's own floating panel is the way in.
|
|
61
|
+
*/
|
|
62
|
+
settingsSurface(): SettingsSurface;
|
|
63
|
+
/** Persist one config path (the caller wires `settings.mutate`). */
|
|
64
|
+
writeConfig(path: readonly string[], value: unknown): Promise<void>;
|
|
65
|
+
/** Allocate a terminal for one session; the host picks the shell. */
|
|
66
|
+
registry: UiTerminalRegistry;
|
|
67
|
+
/** The session's working directory ('' when the host cannot say). */
|
|
68
|
+
cwdFor(sessionId: string): string;
|
|
69
|
+
/** Why the bridge cannot serve a terminal, or 'ok'. */
|
|
70
|
+
unavailableReason(): string;
|
|
71
|
+
/** Loopback gate, shared with the config bridge's rule. */
|
|
72
|
+
isLoopback(request: { socket?: { remoteAddress?: string } }): boolean;
|
|
73
|
+
log?(level: "info" | "warn", message: string): void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** One JSON request body, read structurally. */
|
|
77
|
+
interface RequestBody {
|
|
78
|
+
op?: unknown;
|
|
79
|
+
sessionId?: unknown;
|
|
80
|
+
terminalId?: unknown;
|
|
81
|
+
/** An explicit shell id for this allocation (validated against the catalog). */
|
|
82
|
+
shell?: unknown;
|
|
83
|
+
cols?: unknown;
|
|
84
|
+
rows?: unknown;
|
|
85
|
+
id?: unknown;
|
|
86
|
+
switches?: unknown;
|
|
87
|
+
wslDistro?: unknown;
|
|
88
|
+
defaultShell?: unknown;
|
|
89
|
+
enabled?: unknown;
|
|
90
|
+
shim?: unknown;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Write one reply in the envelope the config bridge already uses. */
|
|
94
|
+
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
95
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
96
|
+
res.end(JSON.stringify(body));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Read one bounded JSON body. */
|
|
100
|
+
async function readBody(request: {
|
|
101
|
+
on(event: "data", cb: (chunk: Buffer) => void): void;
|
|
102
|
+
on(event: "end", cb: () => void): void;
|
|
103
|
+
on(event: "error", cb: (error: Error) => void): void;
|
|
104
|
+
}): Promise<RequestBody> {
|
|
105
|
+
const chunks: Buffer[] = [];
|
|
106
|
+
let size = 0;
|
|
107
|
+
const raw = await new Promise<Buffer>((resolve, reject) => {
|
|
108
|
+
request.on("data", (chunk: Buffer) => {
|
|
109
|
+
size += chunk.length;
|
|
110
|
+
if (size <= 65536) chunks.push(chunk);
|
|
111
|
+
});
|
|
112
|
+
request.on("end", () => { resolve(Buffer.concat(chunks)); });
|
|
113
|
+
request.on("error", reject);
|
|
114
|
+
});
|
|
115
|
+
if (raw.length === 0) return {};
|
|
116
|
+
return JSON.parse(raw.toString("utf8")) as RequestBody;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Coerce a number field with a bound. */
|
|
120
|
+
function num(value: unknown, fallback: number, max: number): number {
|
|
121
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(1, Math.min(max, Math.floor(value))) : fallback;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The config field behind each switch, spelled out rather than derived.
|
|
126
|
+
*
|
|
127
|
+
* A computed name (`"shell" + cap(key)`) produces `shellGitbash` while the schema
|
|
128
|
+
* declares `shellGitBash` - the write would land on a key that does not exist,
|
|
129
|
+
* persist nothing, and look fine in the settings page. Two spellings of one fact
|
|
130
|
+
* always drift, so this table is the single place the name appears.
|
|
131
|
+
*/
|
|
132
|
+
const SWITCH_FIELD: Record<string, string> = { gitbash: "shellGitBash", msys2: "shellMsys2", wsl: "shellWsl", payload: "shellPayload", niu: "shellNiu" };
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Register the terminal routes.
|
|
136
|
+
* @param webServer - the host webserver (may lack upgrade support).
|
|
137
|
+
* @param deps - the wiring above.
|
|
138
|
+
* @returns a disposer, plus the reason when the host cannot carry a socket.
|
|
139
|
+
*/
|
|
140
|
+
export function registerUiTerminalRoutes(webServer: UpgradeCapableServer | undefined, deps: UiBridgeDeps): { dispose(): void; socket: "mounted" | "no-websocket-route" } {
|
|
141
|
+
const handler = async (request: { method?: string; socket?: { remoteAddress?: string } }, res: ServerResponse): Promise<void> => {
|
|
142
|
+
if (!deps.isLoopback(request)) {
|
|
143
|
+
json(res, 403, { ok: false, code: "loopback-only" });
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (request.method !== "POST") {
|
|
147
|
+
json(res, 405, { ok: false, code: "method-not-allowed" });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
let body: RequestBody;
|
|
151
|
+
try {
|
|
152
|
+
body = await readBody(request as never);
|
|
153
|
+
} catch {
|
|
154
|
+
json(res, 400, { ok: false, code: "bad-json" });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
const value = await dispatch(body, deps);
|
|
159
|
+
json(res, 200, { ok: true, value });
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const code = error instanceof UiTerminalError ? error.code : error instanceof Error ? "failed" : "failed";
|
|
162
|
+
json(res, error instanceof UiTerminalError ? error.status : 500, {
|
|
163
|
+
ok: false,
|
|
164
|
+
code,
|
|
165
|
+
message: error instanceof Error ? error.message : String(error),
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const disposers: Array<() => void> = [];
|
|
171
|
+
const registered = webServer?.register?.({ kind: "exact", path: TERMINAL_API_PATH, handler: handler as never });
|
|
172
|
+
if (typeof registered === "function") disposers.push(registered);
|
|
173
|
+
const mount = mountTerminalSocket(
|
|
174
|
+
{ registry: deps.registry, environmentFor: (cwd) => deps.registry.environment(cwd), isLoopback: (request) => deps.isLoopback(request) },
|
|
175
|
+
webServer,
|
|
176
|
+
);
|
|
177
|
+
if (mount.ok) disposers.push(mount.dispose);
|
|
178
|
+
return {
|
|
179
|
+
socket: mount.ok ? "mounted" : mount.reason,
|
|
180
|
+
dispose: () => {
|
|
181
|
+
for (const dispose of disposers) {
|
|
182
|
+
try {
|
|
183
|
+
dispose();
|
|
184
|
+
} catch { /* already gone */ }
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** One request -> one reply. */
|
|
191
|
+
async function dispatch(body: RequestBody, deps: UiBridgeDeps): Promise<unknown> {
|
|
192
|
+
const op = typeof body.op === "string" ? body.op : "";
|
|
193
|
+
// Everything below the master switch is gated by it. `switches` is included: an
|
|
194
|
+
// off feature that still accepts child edits would store choices it ignores, and
|
|
195
|
+
// the settings row would show them as applied.
|
|
196
|
+
if (!deps.enabled() && op !== "get" && op !== "enabled") {
|
|
197
|
+
throw new UiTerminalError("disabled", "the bottom terminal is switched off in settings", 409);
|
|
198
|
+
}
|
|
199
|
+
switch (op) {
|
|
200
|
+
case "get": {
|
|
201
|
+
const catalog = deps.catalog();
|
|
202
|
+
return {
|
|
203
|
+
catalog,
|
|
204
|
+
effective: effectiveShell(deps),
|
|
205
|
+
switches: deps.switches(),
|
|
206
|
+
defaultShell: deps.configuredShell(),
|
|
207
|
+
wslDistro: deps.wslDistro(),
|
|
208
|
+
enabled: deps.enabled(),
|
|
209
|
+
shimOfficialTerminal: deps.shimOfficialTerminal(),
|
|
210
|
+
settingsSurface: deps.settingsSurface(),
|
|
211
|
+
// The master switch outranks the capability answers: "off" is the user's
|
|
212
|
+
// choice, and reporting `ok` next to a hidden panel would be the confusing
|
|
213
|
+
// half of the pair.
|
|
214
|
+
unavailable: deps.enabled() ? deps.unavailableReason() : "disabled",
|
|
215
|
+
terminals: deps.registry.count(),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
case "shim": {
|
|
219
|
+
// Written, not inferred: whether the browser may claim the `webTerminals` name is
|
|
220
|
+
// a deployment fact only the operator knows, and the safe default is to not claim
|
|
221
|
+
// it. The client re-reads the service before publishing, so switching this on
|
|
222
|
+
// where a controller already exists cannot silently take the controller down.
|
|
223
|
+
const next = body.shim === true;
|
|
224
|
+
await deps.writeConfig(["shimOfficialTerminal"], next);
|
|
225
|
+
return { shimOfficialTerminal: deps.shimOfficialTerminal(), catalog: deps.catalog() };
|
|
226
|
+
}
|
|
227
|
+
case "enabled": {
|
|
228
|
+
// The master switch itself is always writable - refusing that would be a way
|
|
229
|
+
// to lock the feature off permanently.
|
|
230
|
+
const value = body.enabled === true;
|
|
231
|
+
await deps.writeConfig(["bottomTerminal"], value);
|
|
232
|
+
return { enabled: deps.enabled(), catalog: deps.catalog(), effective: effectiveShell(deps), switches: deps.switches() };
|
|
233
|
+
}
|
|
234
|
+
case "switches": {
|
|
235
|
+
const requested = body.switches;
|
|
236
|
+
if (requested === null || typeof requested !== "object") throw new UiTerminalError("bad-request", "switches must be an object");
|
|
237
|
+
const next = requested as Record<string, unknown>;
|
|
238
|
+
// Persist first, then answer with a rebuilt catalog: a switch that cannot be
|
|
239
|
+
// stored must not look applied in the settings row.
|
|
240
|
+
for (const key of ["gitbash", "msys2", "wsl", "payload", "niu"] as const) {
|
|
241
|
+
if (typeof next[key] === "boolean") await deps.writeConfig([SWITCH_FIELD[key]!], next[key]);
|
|
242
|
+
}
|
|
243
|
+
if (typeof body.wslDistro === "string") await deps.writeConfig(["wslDistro"], body.wslDistro);
|
|
244
|
+
return { catalog: deps.catalog(), effective: effectiveShell(deps), switches: deps.switches(), wslDistro: deps.wslDistro(), enabled: deps.enabled() };
|
|
245
|
+
}
|
|
246
|
+
case "default": {
|
|
247
|
+
const value = typeof body.defaultShell === "string" ? body.defaultShell : "";
|
|
248
|
+
const catalog = deps.catalog();
|
|
249
|
+
const row = catalog.find((entry) => entry.id === value);
|
|
250
|
+
if (row === undefined || !row.activated || !row.available) {
|
|
251
|
+
// Its own code, not a generic bad-request: the browser renders "enable that
|
|
252
|
+
// shell first" for this one and "malformed input" for the rest.
|
|
253
|
+
throw new UiTerminalError("shellNotActivated", `shell ${JSON.stringify(value)} is not an activated, available choice`, 400);
|
|
254
|
+
}
|
|
255
|
+
await deps.writeConfig(["defaultShell"], value);
|
|
256
|
+
return { catalog: deps.catalog(), effective: effectiveShell(deps) };
|
|
257
|
+
}
|
|
258
|
+
case "terminal.open": {
|
|
259
|
+
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
260
|
+
if (sessionId === "") throw new UiTerminalError("bad-request", "sessionId is required");
|
|
261
|
+
const cwd = deps.cwdFor(sessionId);
|
|
262
|
+
// An explicit `shell` is honoured ONLY when that row is activated and
|
|
263
|
+
// available: the same R4 rule the default choice obeys. This is what lets the
|
|
264
|
+
// multi-shell tab offer Git Bash and MSYS2 side by side - the host terminal
|
|
265
|
+
// controller cannot, because its menu de-duplicates shells by executable file
|
|
266
|
+
// name and both are `bash.exe`.
|
|
267
|
+
const asked = typeof body.shell === "string" ? body.shell.trim() : "";
|
|
268
|
+
const rows = deps.catalog();
|
|
269
|
+
let resolved = effectiveShell(deps);
|
|
270
|
+
if (asked !== "") {
|
|
271
|
+
const row = rows.find((entry) => entry.id === asked);
|
|
272
|
+
if (row === undefined || !row.activated || !row.available || row.path === undefined) {
|
|
273
|
+
throw new UiTerminalError("shellNotActivated", `shell ${JSON.stringify(asked)} is not an activated, available choice`, 400);
|
|
274
|
+
}
|
|
275
|
+
resolved = {
|
|
276
|
+
id: row.id,
|
|
277
|
+
path: row.path,
|
|
278
|
+
argv: row.argv ?? uiArgv(row.id, deps.paths(), ""),
|
|
279
|
+
fellBack: false,
|
|
280
|
+
floor: false,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const env = deps.env(resolved.id === "cmd" ? "powershell" : (resolved.id as ShellId));
|
|
284
|
+
return await openAndReport({
|
|
285
|
+
sessionId,
|
|
286
|
+
cwd,
|
|
287
|
+
resolved,
|
|
288
|
+
rows,
|
|
289
|
+
env,
|
|
290
|
+
body,
|
|
291
|
+
deps,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
case "terminal.close": {
|
|
295
|
+
const id = typeof body.id === "string" ? body.id : "";
|
|
296
|
+
if (id === "") throw new UiTerminalError("bad-request", "id is required");
|
|
297
|
+
await deps.registry.close(id);
|
|
298
|
+
return { closed: true };
|
|
299
|
+
}
|
|
300
|
+
case "terminal.list": {
|
|
301
|
+
const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
|
|
302
|
+
if (sessionId === "") throw new UiTerminalError("bad-request", "sessionId is required");
|
|
303
|
+
return { terminals: deps.registry.list(sessionId) satisfies UiTerminalInfo[] };
|
|
304
|
+
}
|
|
305
|
+
case "shells.discover": {
|
|
306
|
+
const catalog = deps.catalog();
|
|
307
|
+
const shells = catalog
|
|
308
|
+
.filter((entry) => entry.available && entry.path !== undefined)
|
|
309
|
+
.map((entry) => ({ path: entry.path!, args: entry.argv?.slice(1) ?? [], name: entry.label }));
|
|
310
|
+
return { shells, selected: deps.configuredShell() };
|
|
311
|
+
}
|
|
312
|
+
default:
|
|
313
|
+
throw new UiTerminalError("bad-request", `unknown op ${JSON.stringify(body.op)}`, 404);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The shell an allocation would use, recomputed from the live catalog. */
|
|
318
|
+
function effectiveShell(deps: UiBridgeDeps): ResolvedDefault {
|
|
319
|
+
return resolveDefaultShell(deps.catalog(), deps.configuredShell(), deps.paths());
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Allocate one shell and answer in the shape the browser needs.
|
|
324
|
+
*
|
|
325
|
+
* Split out because two ops reach it (the fallback-chain default and an explicit
|
|
326
|
+
* per-tab shell choice) and the reply contract - `{info, environment}`, plus the
|
|
327
|
+
* argv slice that becomes the info's `shell` - must not be spelled twice.
|
|
328
|
+
*/
|
|
329
|
+
async function openAndReport(input: {
|
|
330
|
+
sessionId: string;
|
|
331
|
+
cwd: string;
|
|
332
|
+
resolved: ResolvedDefault;
|
|
333
|
+
rows: readonly ShellEntry[];
|
|
334
|
+
env: Record<string, string | undefined>;
|
|
335
|
+
body: RequestBody;
|
|
336
|
+
deps: UiBridgeDeps;
|
|
337
|
+
}): Promise<unknown> {
|
|
338
|
+
const { sessionId, cwd, resolved, rows, env, body, deps } = input;
|
|
339
|
+
const info = await deps.registry.open({
|
|
340
|
+
sessionId,
|
|
341
|
+
cwd,
|
|
342
|
+
shellId: resolved.id,
|
|
343
|
+
shellSpec: { path: resolved.path, args: resolved.argv.slice(1), name: labelOf(rows, resolved) },
|
|
344
|
+
title: labelOf(rows, resolved),
|
|
345
|
+
argv: [...resolved.argv],
|
|
346
|
+
env,
|
|
347
|
+
cols: num(body.cols, 80, 500),
|
|
348
|
+
rows: num(body.rows, 24, 200),
|
|
349
|
+
terminalId: typeof body.terminalId === "string" ? body.terminalId : undefined,
|
|
350
|
+
});
|
|
351
|
+
// `environment` travels with the info: the emulator cannot size itself until it
|
|
352
|
+
// has the limits, and asking for them in a second round trip would race the first
|
|
353
|
+
// output frame.
|
|
354
|
+
return { info, environment: deps.registry.environment(cwd) };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** The display name of the resolved shell (the catalog label, else the id). */
|
|
358
|
+
function labelOf(catalog: readonly ShellEntry[], resolved: ResolvedDefault): string {
|
|
359
|
+
if (resolved.id === "cmd") return "cmd";
|
|
360
|
+
return catalog.find((entry) => entry.id === resolved.id)?.label ?? String(resolved.id);
|
|
361
|
+
}
|