dsh-bash-terminal-ts 0.5.1 → 0.5.2
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/README.en.md +5 -5
- package/README.md +15 -15
- package/cordis.patch.yml +2 -2
- package/dist/client.core.js +1 -1
- package/dist/client.js +2 -2
- package/dsh.plugin.json +3 -3
- package/lib/client.js +2 -2
- package/lib/dsh-types.d.ts +1 -1
- package/lib/dsh-types.js +9 -9
- package/lib/dsh.js +29 -29
- package/lib/index.js +6 -6
- package/lib/terminal.d.ts +110 -110
- package/lib/terminal.js +438 -438
- package/package.json +1 -1
- package/screenshots.json +5 -5
- package/scripts/build-client.mjs +2 -2
- package/src/client.tsx +2 -2
- package/src/dsh-types.ts +1 -1
- package/src/index.ts +6 -6
- package/src/terminal.ts +1 -1
- package/template/README.md +0 -82
- package/template/terminal-adapter.ts +0 -343
package/package.json
CHANGED
package/screenshots.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
{
|
|
2
|
-
"screenshots": [
|
|
3
|
-
"assets/shells.png"
|
|
4
|
-
]
|
|
5
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"screenshots": [
|
|
3
|
+
"assets/shells.png"
|
|
4
|
+
]
|
|
5
|
+
}
|
package/scripts/build-client.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Build the browser client bundle for dsh-bash-terminal.
|
|
1
|
+
// Build the browser client bundle for dsh-bash-terminal-ts.
|
|
2
2
|
// Output: lib/client.js (primary, consumed by DSH loader/reload precheck) and
|
|
3
3
|
// dist/client.js (legacy compatibility) — a __ModuleLoader__.load({ id, factory })
|
|
4
4
|
// wrapper around the esbuild CJS bundle; shared deps (react, @deepseek-ai/*)
|
|
@@ -33,7 +33,7 @@ await build({
|
|
|
33
33
|
|
|
34
34
|
const core = readFileSync(join(root, "dist", "client.core.js"), "utf8");
|
|
35
35
|
const wrapper = `window.__ModuleLoader__.load({
|
|
36
|
-
id: "dsh-bash-terminal",
|
|
36
|
+
id: "dsh-bash-terminal-ts",
|
|
37
37
|
factory: (require) => {
|
|
38
38
|
var module = { exports: {} };
|
|
39
39
|
var exports = module.exports;
|
package/src/client.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// dsh-bash-terminal client plugin: a "Default terminal" preference row in the
|
|
1
|
+
// dsh-bash-terminal-ts client plugin: a "Default terminal" preference row in the
|
|
2
2
|
// Web UI General settings, mirroring the shipped EnterBehaviorRow grammar
|
|
3
3
|
// (row layout, capsule selector with chevron, --dsw-* tokens).
|
|
4
4
|
//
|
|
@@ -32,7 +32,7 @@ const ROW_CSS =
|
|
|
32
32
|
".btChevron{flex:none}";
|
|
33
33
|
if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=\"bash-terminal-row\"]") === null) {
|
|
34
34
|
const tag = document.createElement("style");
|
|
35
|
-
tag.dataset.plugin = "dsh-bash-terminal";
|
|
35
|
+
tag.dataset.plugin = "dsh-bash-terminal-ts";
|
|
36
36
|
tag.dataset.pluginCss = "bash-terminal-row";
|
|
37
37
|
tag.textContent = ROW_CSS;
|
|
38
38
|
document.head.appendChild(tag);
|
package/src/dsh-types.ts
CHANGED
|
@@ -294,7 +294,7 @@ export interface ApprovalSeam {
|
|
|
294
294
|
// ---- plugin context (server side) ----------------------------------------------
|
|
295
295
|
|
|
296
296
|
/**
|
|
297
|
-
* The structural context face dsh-bash-terminal programs against: the union
|
|
297
|
+
* The structural context face dsh-bash-terminal-ts programs against: the union
|
|
298
298
|
* of every `ctx.*` member touched by src/index.ts and src/terminal.ts.
|
|
299
299
|
*/
|
|
300
300
|
export interface BashTerminalContext {
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// dsh-bash-terminal - one shell tool, four Windows terminals.
|
|
1
|
+
// dsh-bash-terminal-ts - one shell tool, four Windows terminals.
|
|
2
2
|
//
|
|
3
3
|
// Registers a model-facing shell tool. The terminal backend (powershell /
|
|
4
4
|
// gitbash / msys2 / wsl) is chosen by the USER in the Web UI settings (default
|
|
@@ -321,7 +321,7 @@ function spawnSpec(resolved: SpawnResolution, argv: string[], env: Record<string
|
|
|
321
321
|
function collectedOutput(handle: { collected: { stdout: unknown; stderr: unknown } }) {
|
|
322
322
|
const { stdout, stderr } = handle.collected;
|
|
323
323
|
if (!isCollectedStream(stdout) || !isCollectedStream(stderr)) {
|
|
324
|
-
throw new Error("dsh-bash-terminal: subprocess implementation dropped a requested collect stream");
|
|
324
|
+
throw new Error("dsh-bash-terminal-ts: subprocess implementation dropped a requested collect stream");
|
|
325
325
|
}
|
|
326
326
|
return { stdout, stderr };
|
|
327
327
|
}
|
|
@@ -392,7 +392,7 @@ async function runForeground(
|
|
|
392
392
|
function requireSubprocess(ctx: BashTerminalContext) {
|
|
393
393
|
const subprocess = ctx.subprocess;
|
|
394
394
|
if (subprocess === null) {
|
|
395
|
-
throw new Error("dsh-bash-terminal: ctx.subprocess seam unavailable (missing inject service)");
|
|
395
|
+
throw new Error("dsh-bash-terminal-ts: ctx.subprocess seam unavailable (missing inject service)");
|
|
396
396
|
}
|
|
397
397
|
return subprocess;
|
|
398
398
|
}
|
|
@@ -666,14 +666,14 @@ const BACKGROUND_OUTPUT_PROPERTIES: Record<string, JsonSchemaNode> = {
|
|
|
666
666
|
|
|
667
667
|
export function apply(ctx: BashTerminalContext, config: Partial<ConfigValues> = {}): void {
|
|
668
668
|
if (process.platform !== "win32") {
|
|
669
|
-
ctx.logger?.info?.("dsh-bash-terminal: only meaningful on win32; skipping tool registration");
|
|
669
|
+
ctx.logger?.info?.("dsh-bash-terminal-ts: only meaningful on win32; skipping tool registration");
|
|
670
670
|
return;
|
|
671
671
|
}
|
|
672
672
|
const backgroundEnabled = true;
|
|
673
673
|
const paths = resolveAllPaths(config);
|
|
674
674
|
const defaultShell = config.defaultShell ?? DEFAULT_SHELL;
|
|
675
675
|
if (!(SHELLS as readonly string[]).includes(defaultShell)) {
|
|
676
|
-
throw new Error(`dsh-bash-terminal: invalid defaultShell ${JSON.stringify(defaultShell)}`);
|
|
676
|
+
throw new Error(`dsh-bash-terminal-ts: invalid defaultShell ${JSON.stringify(defaultShell)}`);
|
|
677
677
|
}
|
|
678
678
|
const settingsScope = ctx.settings.register(
|
|
679
679
|
SETTINGS_NAMESPACE,
|
|
@@ -829,7 +829,7 @@ export function apply(ctx: BashTerminalContext, config: Partial<ConfigValues> =
|
|
|
829
829
|
const shell = settingsScope.get().defaultShell;
|
|
830
830
|
const argv0 = buildArgv(shell, v.command, paths, v.distro);
|
|
831
831
|
if (argv0[0] === undefined) {
|
|
832
|
-
throw new Error(`dsh-bash-terminal: ${shell} backend unavailable - executable not found. Install it or set the corresponding *Path config.`);
|
|
832
|
+
throw new Error(`dsh-bash-terminal-ts: ${shell} backend unavailable - executable not found. Install it or set the corresponding *Path config.`);
|
|
833
833
|
}
|
|
834
834
|
// Only element 0 (the resolved executable) can be undefined; guarded above.
|
|
835
835
|
const argv = argv0 as string[];
|
package/src/terminal.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// dsh-bash-terminal: interactive terminal tool over the official PTY seam.
|
|
1
|
+
// dsh-bash-terminal-ts: interactive terminal tool over the official PTY seam.
|
|
2
2
|
// ctx.subprocess.spawnTerminal (node-pty under the hood) allocates a real
|
|
3
3
|
// terminal; this module owns model-facing sessions: open / send / read /
|
|
4
4
|
// signal (Ctrl+C etc.) / close. The backend follows the user's default
|
package/template/README.md
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
# 终端适配模式模板
|
|
2
|
-
|
|
3
|
-
把 `dsh-bash-terminal-ts` 里那套「一个 `shell` 工具、多种本地终端」的做法抽出来,供你直接复用。
|
|
4
|
-
|
|
5
|
-
- [`terminal-adapter.ts`](./terminal-adapter.ts) — 四种模式已填好的适配器模块,零依赖(只用 `node:fs` / `node:path`),整份复制或只挑一种都行。
|
|
6
|
-
- 本文件 — 每种模式的要点、踩过的坑,以及怎么加第五种。
|
|
7
|
-
|
|
8
|
-
> **本目录已做过分发前清理**:不含作者本机路径、主机名、凭据。示例路径统一写成 `D:\workspace\your-plugin` 这类占位形式。
|
|
9
|
-
> 拷进你自己仓库前,请照做一遍。
|
|
10
|
-
|
|
11
|
-
## 四种模式
|
|
12
|
-
|
|
13
|
-
| 模式 | 实际执行 | 语法 / 路径 | 环境变量 | 可沙箱封闭 |
|
|
14
|
-
|------|----------|-------------|----------|------------|
|
|
15
|
-
| `powershell`(默认) | `pwsh -NoLogo -NoProfile -NonInteractive -Command <cmd>` | PowerShell;`C:\...` | `$env:NAME` | ✅ |
|
|
16
|
-
| `gitbash` | Git for Windows `bash -lc <cmd>` | POSIX;`/d/...`;PATH 含 `/usr/bin`、`/mingw64/bin` | `$NAME` | ❌ |
|
|
17
|
-
| `msys2` | MSYS2 `bash -lc <cmd>`(`C:\msys64\usr\bin\bash.exe`) | POSIX;`/c/...`;PATH 含 `/usr/bin`、`/mingw64/bin`(gcc / make) | `$NAME`(自动注入 `MSYSTEM=MINGW64`) | ❌ |
|
|
18
|
-
| `wsl` | `wsl [-d <distro>] -e bash -lc <cmd>` | Linux;`/mnt/d/...` | `$NAME`(经 `WSLENV`) | ❌(隔离即沙箱) |
|
|
19
|
-
|
|
20
|
-
## 每种模式的要点
|
|
21
|
-
|
|
22
|
-
### 1. Windows 标准模式(PowerShell)
|
|
23
|
-
|
|
24
|
-
- **探测顺序**:`%ProgramFiles%\PowerShell\7\pwsh.exe` → PATH 里各目录的 `pwsh.exe` → `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`。PowerShell 7 优先,5.1 只作兜底。
|
|
25
|
-
- **必须带 `-NonInteractive`**:否则命令里任何一处隐含提示都会把采集挂死。工具收到的是一条完整脚本,不是 REPL 会话。
|
|
26
|
-
- **唯一可被沙箱封闭的模式**。走你平台的沙箱门面包装 spawn argv;封闭模式拿不到可用后端时要 **fail-closed 抛错**,不要降级成不封闭。
|
|
27
|
-
|
|
28
|
-
### 2. Git Bash
|
|
29
|
-
|
|
30
|
-
- **`-lc` 不是 `-c`**:`-l` 会 source `/etc/profile`,`/usr/bin`、`/mingw64/bin` 才进 PATH。用裸 `-c`,`git`、`ssh`、`tr`、`sed` 全是 command not found。
|
|
31
|
-
- **必须排除 System32 的 `bash.exe`** —— 这是这套适配里最容易踩的坑。装了 WSL 的机器上 `C:\Windows\System32\bash.exe` 也存在,但它是 **WSL 转发器**,不是 Git Bash。一旦选中,Git Bash 模式的命令会被静默送进 Linux VM,`/d/...` 路径和 Git for Windows 的工具链全都不存在,而报错信息完全指不到根因。
|
|
32
|
-
- **不可沙箱封闭**:DSH 的 Windows ACL restricted-token runner 起不了 Cygwin/MSYS2 进程,bash 启动阶段就 `CreateFileMapping ... Win32 error 5` 中止。硬套沙箱 = 每条命令都失败。
|
|
33
|
-
- 安装位置:`%ProgramFiles%\Git\bin\bash.exe`、`%ProgramFiles%\Git\usr\bin\bash.exe`、`%LOCALAPPDATA%\Programs\Git\bin\bash.exe`(按用户安装)。
|
|
34
|
-
|
|
35
|
-
### 3. MSYS2
|
|
36
|
-
|
|
37
|
-
- **`-lc` 同 Git Bash**,理由一致。
|
|
38
|
-
- **`MSYSTEM=MINGW64` 要自动补上**:`/etc/profile` 靠它把 `/mingw64/bin`(gcc / make)挂进 PATH。不设的话 MSYS2 落在裸 MSYS 环境,工具链整个看不见。调用方显式传了值就尊重调用方。
|
|
39
|
-
- **`msys2.exe` 不能当后端**:它是分配控制台的 Cygwin 启动器,用管道 stdio spawn 出来会**退出码 0、stdout/stderr 都是零字节**——每条命令都"成功且无输出"。模板里把它留在候选表最后只作兜底,正常 `bash.exe` 永远优先。
|
|
40
|
-
- **不可沙箱封闭**,原因同 Git Bash(同一套 Cygwin/MSYS2 运行时)。
|
|
41
|
-
|
|
42
|
-
### 4. WSL
|
|
43
|
-
|
|
44
|
-
- **`-e bash -lc <cmd>`**:`-e` 直接执行、不经额外的 shell 包装,引号能原样穿过边界。指定发行版时插 `-d <distro>`。
|
|
45
|
-
- **`WSLENV` 是白名单,只能叠加、不能重建**:只有列在 `WSLENV` 里的变量才进得了 WSL。宿主本来可能已经有值(Windows Terminal 会导出 `WT_SESSION:WT_PROFILE_ID:`),重建会把这些静默丢掉,用户的终端会话变量就断了。
|
|
46
|
-
- **叠加时要按 `:` 切分再拼**,不能字符串直接拼——宿主值结尾带一个 `:`,直接拼会多出一个空条目。同时要把 `WSLENV` 这个 key 自己排除,否则会再加一条无意义条目。
|
|
47
|
-
- **`wsl.exe` 不用探测**:它是 Windows 组件,固定位置 `%SystemRoot%\System32\wsl.exe`,视为恒存在。
|
|
48
|
-
- **它的隔离本身就是沙箱**,再包一层是多余的;如实上报 `wsl-isolation`。
|
|
49
|
-
|
|
50
|
-
## 加第五种模式
|
|
51
|
-
|
|
52
|
-
以加一个 `cmd.exe` 为例:
|
|
53
|
-
|
|
54
|
-
1. 在 `SHELLS` 里加 id,`ShellId` 会自动带上它(`as const` 联合)。
|
|
55
|
-
2. 在 `ADAPTERS` 里补一条:`label`、`summary`、`toolDescription`、`candidates()`、`configKey`、`confinable`。
|
|
56
|
-
3. 在 `buildArgv` 里加一个 `case`。**保留 `default` 分支的 `never` 穷尽检查**——漏了分支会在编译期报错,而不是运行时掉进某个诡异的默认行为。
|
|
57
|
-
4. 在 `buildEnv` 里加该模式需要的环境修正(有就加,没有就跳过)。
|
|
58
|
-
5. 在 `confinementFor` / `shouldConfine` 里表个态:能不能封闭,不能的话上报哪个 `*-unconfined` 标签。
|
|
59
|
-
6. 配置 schema 里补对应的 `*Path` 覆盖项(可为空串 = 自动探测)。
|
|
60
|
-
7. 设置面板下拉里加一项,**顺序与 `SHELLS` 保持一致**。
|
|
61
|
-
8. 补测试:探测顺序、argv 组装、env 修正各至少一条。
|
|
62
|
-
|
|
63
|
-
## 接进 DSH
|
|
64
|
-
|
|
65
|
-
模板本身不依赖 DSH,接线时用到这几个接缝:
|
|
66
|
-
|
|
67
|
-
| 接缝 | 用途 |
|
|
68
|
-
|------|------|
|
|
69
|
-
| `ctx.subprocess.spawn` / `spawnTerminal` | 派生进程;进程树终止、SIGTERM→grace→SIGKILL、输出 spill |
|
|
70
|
-
| `ctx.jobs` | 后台任务句柄(`run_in_background` / `job_output` / `job_kill`) |
|
|
71
|
-
| `ctx.sandboxPolicy.resolve` | 每次调用解析当次沙箱策略 |
|
|
72
|
-
| `ctx.sandbox.confine` | 仅 PowerShell 走这里;失败要 fail-closed |
|
|
73
|
-
| `ctx.shellEnv.collect` | 采集要下发的环境变量 |
|
|
74
|
-
| `ctx.settings` + `settings.general.item` 槽 | 「默认终端」设置行 |
|
|
75
|
-
|
|
76
|
-
**设计上的一个刻意选择**:这套实现**不占用 `ctx.shell` 能力接缝**。平台自带的沙箱化 `pwsh` 工具保持原样可用,本工具是一个**额外的**、由用户选择的终端入口,两者并存。
|
|
77
|
-
|
|
78
|
-
**另一条硬规矩**:终端由**用户**在 Web UI 里选,模型不能改。工具不把终端参数暴露给模型——否则「用户设定」形同虚设。
|
|
79
|
-
|
|
80
|
-
## 许可
|
|
81
|
-
|
|
82
|
-
与仓库一致:MIT。
|
|
@@ -1,343 +0,0 @@
|
|
|
1
|
-
// Terminal adapter templates — four Windows terminal backends, ready to copy.
|
|
2
|
-
//
|
|
3
|
-
// Extracted from dsh-bash-terminal-ts `src/index.ts` and sanitised for reuse:
|
|
4
|
-
// no author-local paths, no host-specific values. Copy this file — or just the
|
|
5
|
-
// one adapter you need — into your own DSH plugin, then wire the seams listed
|
|
6
|
-
// under "Wiring into DSH" in ./README.md.
|
|
7
|
-
//
|
|
8
|
-
// powershell pwsh -NoLogo -NoProfile -NonInteractive -Command <cmd>
|
|
9
|
-
// gitbash Git for Windows bash -lc <cmd> POSIX; /d/... paths
|
|
10
|
-
// msys2 MSYS2 bash -lc <cmd> POSIX; /c/... paths, GCC/mingw64
|
|
11
|
-
// wsl wsl [-d <distro>] -e bash -lc <cmd> Linux; /mnt/d/... paths
|
|
12
|
-
//
|
|
13
|
-
// The flag choices here are not guesses: each non-obvious one was measured on
|
|
14
|
-
// Windows and carries its reason inline. Read the comment before changing a
|
|
15
|
-
// flag — several of them look arbitrary and are not.
|
|
16
|
-
//
|
|
17
|
-
// Node >= 22. No runtime dependencies beyond node:fs / node:path.
|
|
18
|
-
|
|
19
|
-
import { lstatSync } from "node:fs";
|
|
20
|
-
import { join } from "node:path";
|
|
21
|
-
|
|
22
|
-
/** The four backends, in the order they appear in the settings dropdown. */
|
|
23
|
-
export const SHELLS = ["powershell", "gitbash", "msys2", "wsl"] as const;
|
|
24
|
-
export type ShellId = (typeof SHELLS)[number];
|
|
25
|
-
|
|
26
|
-
/** Chosen when the user has never touched the setting. */
|
|
27
|
-
export const DEFAULT_SHELL: ShellId = "powershell";
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Forced into every child process. A shell tool feeds its output to a model, so
|
|
31
|
-
* pagers and colour codes are pure noise: `PAGER=cat` and `NO_COLOR=1` keep the
|
|
32
|
-
* captured stdout byte-for-byte the command's actual output.
|
|
33
|
-
*/
|
|
34
|
-
export const ENV_OVERRIDES: Record<string, string> = {
|
|
35
|
-
NO_COLOR: "1",
|
|
36
|
-
TERM: "dumb",
|
|
37
|
-
PAGER: "cat",
|
|
38
|
-
GIT_PAGER: "cat"
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
// ---- executable resolution -------------------------------------------------
|
|
42
|
-
|
|
43
|
-
function candidateExists(candidate: string): boolean {
|
|
44
|
-
try {
|
|
45
|
-
const stat = lstatSync(candidate);
|
|
46
|
-
return stat.isFile() || stat.isSymbolicLink();
|
|
47
|
-
} catch {
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** First candidate that exists on disk, or undefined when none does. */
|
|
53
|
-
export function resolveFromCandidates(candidates: readonly string[]): string | undefined {
|
|
54
|
-
for (const candidate of candidates) {
|
|
55
|
-
if (candidateExists(candidate)) return candidate;
|
|
56
|
-
}
|
|
57
|
-
return undefined;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Well-known PowerShell install locations, then PATH entries. Newest first. */
|
|
61
|
-
export function candidatePwshPaths(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
62
|
-
const programFiles = env.ProgramFiles ?? "C:\\Program Files";
|
|
63
|
-
const systemRoot = env.SystemRoot ?? "C:\\Windows";
|
|
64
|
-
// PowerShell 7 first: pwsh.exe is the cross-platform one and is what the
|
|
65
|
-
// -NoLogo/-NoProfile/-NonInteractive flag set is written against.
|
|
66
|
-
const candidates = [join(programFiles, "PowerShell", "7", "pwsh.exe")];
|
|
67
|
-
for (const entry of (env.PATH ?? "").split(";")) {
|
|
68
|
-
const trimmed = entry.trim().replace(/^"|"$/g, "");
|
|
69
|
-
if (trimmed.length === 0) continue;
|
|
70
|
-
candidates.push(join(trimmed, "pwsh.exe"));
|
|
71
|
-
}
|
|
72
|
-
// Windows PowerShell 5.1 as the floor — present on every Windows install.
|
|
73
|
-
candidates.push(join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"));
|
|
74
|
-
return candidates;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Git for Windows locations, then PATH `bash.exe` entries EXCLUDING the
|
|
79
|
-
* System32 launcher.
|
|
80
|
-
*
|
|
81
|
-
* That exclusion is the whole point of this function: `C:\Windows\System32\
|
|
82
|
-
* bash.exe` also exists on machines with WSL and is the **WSL forwarder**, not
|
|
83
|
-
* a Git Bash shell. Picking it up silently sends Git Bash commands into a Linux
|
|
84
|
-
* VM, where `/d/...` paths and the Git for Windows toolchain do not exist.
|
|
85
|
-
*/
|
|
86
|
-
export function candidateGitBashPaths(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
87
|
-
const programFiles = env.ProgramFiles ?? "C:\\Program Files";
|
|
88
|
-
const systemRoot = (env.SystemRoot ?? "C:\\Windows").toLowerCase();
|
|
89
|
-
const localAppData = env.LOCALAPPDATA ?? "";
|
|
90
|
-
const candidates = [
|
|
91
|
-
join(programFiles, "Git", "bin", "bash.exe"),
|
|
92
|
-
// usr\bin\bash.exe is the MSYS-rooted twin; some installs only expose this one.
|
|
93
|
-
join(programFiles, "Git", "usr", "bin", "bash.exe")
|
|
94
|
-
];
|
|
95
|
-
// Per-user installs land here.
|
|
96
|
-
if (localAppData.length > 0) candidates.push(join(localAppData, "Programs", "Git", "bin", "bash.exe"));
|
|
97
|
-
for (const entry of (env.PATH ?? "").split(";")) {
|
|
98
|
-
const trimmed = entry.trim().replace(/^"|"$/g, "");
|
|
99
|
-
if (trimmed.length === 0) continue;
|
|
100
|
-
if (trimmed.toLowerCase().includes(systemRoot)) continue; // ← the WSL forwarder
|
|
101
|
-
candidates.push(join(trimmed, "bash.exe"));
|
|
102
|
-
}
|
|
103
|
-
return candidates;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* MSYS2 locations, in preference order: the real `bash.exe` under usr\bin
|
|
108
|
-
* first, then bin\bash.exe, and `msys2.exe` dead last.
|
|
109
|
-
*
|
|
110
|
-
* `msys2.exe` is NOT a usable backend for piped execution. It is the
|
|
111
|
-
* console-allocating Cygwin launcher: spawned with piped stdio it returns exit
|
|
112
|
-
* 0 with zero bytes on both stdout and stderr, so every command looks like it
|
|
113
|
-
* succeeded and printed nothing. It stays in the list only as a last resort;
|
|
114
|
-
* a working `bash.exe` always wins.
|
|
115
|
-
*/
|
|
116
|
-
export function candidateMsys2Paths(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
117
|
-
const candidates = [
|
|
118
|
-
"C:\\msys64\\usr\\bin\\bash.exe",
|
|
119
|
-
"C:\\msys64\\bin\\bash.exe"
|
|
120
|
-
];
|
|
121
|
-
for (const entry of (env.PATH ?? "").split(";")) {
|
|
122
|
-
const trimmed = entry.trim().replace(/^"|"$/g, "");
|
|
123
|
-
if (trimmed.length === 0) continue;
|
|
124
|
-
const lower = trimmed.toLowerCase();
|
|
125
|
-
if (lower.includes("msys64") || lower.includes("mingw64")) {
|
|
126
|
-
candidates.push(join(trimmed, "bash.exe"));
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
candidates.push("C:\\msys64\\msys2.exe"); // last resort — see the note above
|
|
130
|
-
return candidates;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** `wsl.exe` always ships at this fixed location; it is never "not installed". */
|
|
134
|
-
export function defaultWslPath(env: NodeJS.ProcessEnv = process.env): string {
|
|
135
|
-
const systemRoot = env.SystemRoot ?? "C:\\Windows";
|
|
136
|
-
return join(systemRoot, "System32", "wsl.exe");
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
export interface ResolvedPaths {
|
|
140
|
-
pwsh?: string;
|
|
141
|
-
gitbash?: string;
|
|
142
|
-
msys2?: string;
|
|
143
|
-
wsl?: string;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** Per-backend executable overrides; an empty string means "auto-detect". */
|
|
147
|
-
export interface PathConfig {
|
|
148
|
-
pwshPath?: string;
|
|
149
|
-
gitBashPath?: string;
|
|
150
|
-
msys2Path?: string;
|
|
151
|
-
wslPath?: string;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* Resolve all four executables. A backend resolves to `undefined` when it is
|
|
156
|
-
* not installed — surface that as a loud per-call error rather than a silent
|
|
157
|
-
* fallback to another shell, or the user's explicit choice gets ignored.
|
|
158
|
-
*/
|
|
159
|
-
export function resolveAllPaths(config: PathConfig = {}, env: NodeJS.ProcessEnv = process.env): ResolvedPaths {
|
|
160
|
-
const pick = (override: string | undefined, candidates: readonly string[]): string | undefined =>
|
|
161
|
-
override !== undefined && override.trim().length > 0 ? override : resolveFromCandidates(candidates);
|
|
162
|
-
return {
|
|
163
|
-
pwsh: pick(config.pwshPath, candidatePwshPaths(env)),
|
|
164
|
-
gitbash: pick(config.gitBashPath, candidateGitBashPaths(env)),
|
|
165
|
-
msys2: pick(config.msys2Path, candidateMsys2Paths(env)),
|
|
166
|
-
// wsl.exe is not probed: it is a Windows component, so treat it as present.
|
|
167
|
-
wsl: config.wslPath !== undefined && config.wslPath.trim().length > 0 ? config.wslPath : defaultWslPath(env)
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// ---- argv construction -----------------------------------------------------
|
|
172
|
-
|
|
173
|
-
/** Prepend the backend-specific command flags. `command` always goes last. */
|
|
174
|
-
export function buildArgv(
|
|
175
|
-
shell: ShellId,
|
|
176
|
-
command: string,
|
|
177
|
-
paths: ResolvedPaths,
|
|
178
|
-
distro?: string
|
|
179
|
-
): Array<string | undefined> {
|
|
180
|
-
switch (shell) {
|
|
181
|
-
case "powershell":
|
|
182
|
-
// -NonInteractive so a stray prompt can never hang the capture; the
|
|
183
|
-
// model's command is one complete script, not a REPL session.
|
|
184
|
-
return [paths.pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command];
|
|
185
|
-
case "gitbash":
|
|
186
|
-
// -l (login shell) matters: it sources /etc/profile, which is what puts
|
|
187
|
-
// /usr/bin and /mingw64/bin on PATH. With a bare -c, `git`, `ssh` and
|
|
188
|
-
// friends are "command not found".
|
|
189
|
-
return [paths.gitbash, "-lc", command];
|
|
190
|
-
case "msys2":
|
|
191
|
-
// Same -l reasoning as gitbash, and it also picks up /etc/profile's
|
|
192
|
-
// MSYSTEM handling that puts gcc/make on PATH.
|
|
193
|
-
return [paths.msys2, "-lc", command];
|
|
194
|
-
case "wsl": {
|
|
195
|
-
const distroArg = distro !== undefined && distro.trim().length > 0 ? ["-d", distro.trim()] : [];
|
|
196
|
-
// `-e bash -lc` — not `wsl bash -lc`: `-e` runs the command directly and
|
|
197
|
-
// without a shell wrapper, so quoting survives intact.
|
|
198
|
-
return [paths.wsl, ...distroArg, "-e", "bash", "-lc", command];
|
|
199
|
-
}
|
|
200
|
-
default: {
|
|
201
|
-
const exhaustive: never = shell;
|
|
202
|
-
throw new Error(`invalid shell: ${JSON.stringify(exhaustive)} (expected one of ${SHELLS.join(", ")})`);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// ---- environment -----------------------------------------------------------
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* Merge the host environment with per-backend fixups.
|
|
211
|
-
*
|
|
212
|
-
* @param inheritedWslenv - the ambient WSLENV to layer onto. Callers that
|
|
213
|
-
* replace the child environment wholesale (a PTY path, say) must pass
|
|
214
|
-
* `process.env.WSLENV` explicitly, because the ambient value is not visible
|
|
215
|
-
* through `dshEnv`.
|
|
216
|
-
*/
|
|
217
|
-
export function buildEnv(
|
|
218
|
-
shell: ShellId,
|
|
219
|
-
hostEnv?: Record<string, string>,
|
|
220
|
-
inheritedWslenv: string | undefined = process.env.WSLENV
|
|
221
|
-
): Record<string, string | undefined> {
|
|
222
|
-
const env: Record<string, string | undefined> = { ...ENV_OVERRIDES, ...hostEnv };
|
|
223
|
-
if (shell === "msys2") {
|
|
224
|
-
// Selects the MINGW64 environment, so /mingw64/bin (gcc, make, ...) joins
|
|
225
|
-
// PATH via /etc/profile. Without it MSYS2 defaults to the bare MSYS
|
|
226
|
-
// environment and the toolchain is invisible. An explicit caller value wins.
|
|
227
|
-
if (env.MSYSTEM === undefined) env.MSYSTEM = "MINGW64";
|
|
228
|
-
}
|
|
229
|
-
if (shell === "wsl") {
|
|
230
|
-
const keys = Object.keys(hostEnv ?? {});
|
|
231
|
-
if (keys.length > 0) {
|
|
232
|
-
// WSLENV is an allow-list: only the variables named in it cross into WSL.
|
|
233
|
-
// LAYER onto the inherited value, never rebuild it — dropping inherited
|
|
234
|
-
// entries (Windows Terminal exports e.g. `WT_SESSION:WT_PROFILE_ID:`)
|
|
235
|
-
// would silently stop them crossing.
|
|
236
|
-
//
|
|
237
|
-
// The base is SPLIT on ":" rather than concatenated because the host
|
|
238
|
-
// value ends with a trailing ":", so string concatenation would produce a
|
|
239
|
-
// malformed empty entry.
|
|
240
|
-
const declared = Object.prototype.hasOwnProperty.call(hostEnv ?? {}, "WSLENV");
|
|
241
|
-
const base = declared
|
|
242
|
-
? env.WSLENV
|
|
243
|
-
: (typeof inheritedWslenv === "string" && inheritedWslenv.length > 0 ? inheritedWslenv : env.WSLENV);
|
|
244
|
-
const parts = typeof base === "string" ? base.split(":") : [];
|
|
245
|
-
env.WSLENV = [...parts, ...keys.filter((k) => k !== "WSLENV").flatMap((k) => k.split(":"))]
|
|
246
|
-
.map((p) => p.trim())
|
|
247
|
-
.filter((p) => p.length > 0)
|
|
248
|
-
.join(":");
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
return env;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// ---- sandbox confinement ---------------------------------------------------
|
|
255
|
-
|
|
256
|
-
export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* Whether a backend can be wrapped by your sandbox seam, and what to report
|
|
260
|
-
* when it cannot.
|
|
261
|
-
*
|
|
262
|
-
* Only PowerShell is confinable on Windows. Git Bash and MSYS2 must NOT be
|
|
263
|
-
* wrapped: DSH's Windows ACL restricted-token runner cannot start a
|
|
264
|
-
* Cygwin/MSYS2 process — bash aborts during startup with
|
|
265
|
-
* `CreateFileMapping ... Win32 error 5` — so wrapping them would abort every
|
|
266
|
-
* command instead of confining it. WSL is its own Linux VM; that isolation IS
|
|
267
|
-
* the sandbox, so wrapping it is redundant.
|
|
268
|
-
*
|
|
269
|
-
* Publish this honestly: report `*-unconfined` rather than claiming a
|
|
270
|
-
* confinement that did not happen.
|
|
271
|
-
*/
|
|
272
|
-
export function confinementFor(mode: SandboxMode, shell: ShellId): string {
|
|
273
|
-
if (shell === "wsl") return "wsl-isolation";
|
|
274
|
-
if (shell === "gitbash") return "gitbash-unconfined";
|
|
275
|
-
if (shell === "msys2") return "msys2-unconfined";
|
|
276
|
-
return mode === "danger-full-access" ? "none" : "powershell-confined";
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** True when the spawn argv must be passed through the sandbox facade. */
|
|
280
|
-
export function shouldConfine(mode: SandboxMode, shell: ShellId): boolean {
|
|
281
|
-
return mode !== "danger-full-access" && shell === "powershell";
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
// ---- the adapter table -----------------------------------------------------
|
|
285
|
-
|
|
286
|
-
export interface TerminalAdapter {
|
|
287
|
-
readonly id: ShellId;
|
|
288
|
-
/** Shown in the settings dropdown. */
|
|
289
|
-
readonly label: string;
|
|
290
|
-
/** One line describing the backend, suitable for a settings-row caption. */
|
|
291
|
-
readonly summary: string;
|
|
292
|
-
/** Model-facing tool description when this backend is active. */
|
|
293
|
-
readonly toolDescription: string;
|
|
294
|
-
/** Candidate executables, best first. */
|
|
295
|
-
candidates(env?: NodeJS.ProcessEnv): string[];
|
|
296
|
-
/** Path key in your config schema, or undefined when there is nothing to override. */
|
|
297
|
-
readonly configKey?: keyof PathConfig;
|
|
298
|
-
/** Whether this backend's spawn argv may be confined. */
|
|
299
|
-
readonly confinable: boolean;
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
export const ADAPTERS: Record<ShellId, TerminalAdapter> = {
|
|
303
|
-
powershell: {
|
|
304
|
-
id: "powershell",
|
|
305
|
-
label: "PowerShell",
|
|
306
|
-
summary: "PowerShell 7 (pwsh), the Windows default",
|
|
307
|
-
toolDescription:
|
|
308
|
-
"Execute a PowerShell command (pwsh -NoLogo -NoProfile -NonInteractive -Command <command>) and return its stdout/stderr. PowerShell syntax; native Windows paths (C:\\...); environment variables via $env:NAME.",
|
|
309
|
-
candidates: candidatePwshPaths,
|
|
310
|
-
configKey: "pwshPath",
|
|
311
|
-
confinable: true
|
|
312
|
-
},
|
|
313
|
-
gitbash: {
|
|
314
|
-
id: "gitbash",
|
|
315
|
-
label: "Git Bash",
|
|
316
|
-
summary: "Git for Windows bash — POSIX syntax, /d/... paths",
|
|
317
|
-
toolDescription:
|
|
318
|
-
"Execute a bash command (Git for Windows bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /d/workspace; PATH includes /usr/bin and /mingw64/bin so git, npm, ssh etc. work; environment variables via $NAME.",
|
|
319
|
-
candidates: candidateGitBashPaths,
|
|
320
|
-
configKey: "gitBashPath",
|
|
321
|
-
confinable: false
|
|
322
|
-
},
|
|
323
|
-
msys2: {
|
|
324
|
-
id: "msys2",
|
|
325
|
-
label: "MSYS2",
|
|
326
|
-
summary: "MSYS2 bash — POSIX syntax, /c/... paths, full GCC/mingw64 toolchain",
|
|
327
|
-
toolDescription:
|
|
328
|
-
"Execute a bash command (MSYS2 bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /c/...; PATH includes /usr/bin and /mingw64/bin so git, npm, gcc, make etc. work; environment variables via $NAME. MSYS2 provides a full GCC/mingw64 toolchain.",
|
|
329
|
-
candidates: candidateMsys2Paths,
|
|
330
|
-
configKey: "msys2Path",
|
|
331
|
-
confinable: false
|
|
332
|
-
},
|
|
333
|
-
wsl: {
|
|
334
|
-
id: "wsl",
|
|
335
|
-
label: "WSL",
|
|
336
|
-
summary: "WSL Linux — /mnt/d/... paths, optional distro",
|
|
337
|
-
toolDescription:
|
|
338
|
-
"Execute a bash command in WSL (wsl [-d <distro>] -e bash -lc <command>) and return its stdout/stderr. Linux syntax; paths like /mnt/d/workspace; environment variables via $NAME (crossing the boundary through WSLENV).",
|
|
339
|
-
candidates: (env = process.env) => [defaultWslPath(env)],
|
|
340
|
-
configKey: "wslPath",
|
|
341
|
-
confinable: false
|
|
342
|
-
}
|
|
343
|
-
};
|