feat(shell): 抽出执行后端,Windows 用 git-bash / busybox 跑命令

POSIX 上 spawn('/bin/sh') + kill(-pid) 是刻意选的最强约束:/bin/sh 固定
(不读 $SHELL,否则用户把 shell 设成 fish 后模型写的 POSIX 语法全废),
进程组让「停止」能一次带走孙进程。Windows 这三样都没有,同一个写法从
「有效」变成「静默失效」,detached 还会多弹一个控制台。

把三种能力收敛到 app/server/shell.js(resolve / spawnShell / killTree),
terminal、技能、engine 的取消都改走它,上层不再出现 process.platform 分支:

  - POSIX 分支逐字节不变,Linux / macOS / OpenWrt 行为与拆分前一致
  - Windows 依次探测 git-bash、busybox-w32,都没有就明确报错,不静默退到
    cmd.exe——cmd 的语法与模型写的 POSIX 差太远,降级只会让它反复试错
  - killTree 在 Windows 走 taskkill /T:child.kill() 只杀 shell 本身,
    模型起的 node/python/ffmpeg 孙进程会留下来继续占端口
  - detached 在 Windows 关闭(会新建控制台,且让子进程脱离 taskkill 的父子树)
  - 三级覆盖:AGENT_SHELL > config.terminal.shell > 自动探测;
    AGENT_SHELL_ARGS 可改参数模板(bash 想读 rc 时写 -lc)

新增 local/start-win.mjs:start.sh 那 1100 多行 bash 靠 lsof / pgrep /
readlink -f / nohup / setsid / 进程组信号,Windows 一个都没有。启动器这层
本来就只做进程管理,用 Node 重写更省事;业务代码一行都不分平台。首次运行
自动把 busybox-w32(单文件 600KB)下到 local/bin/,生成 local/config.win.yml,
之后不再覆盖。

验证(macOS 实跑):普通命令 / 超时 704ms / 取消 403ms 三条路径正常,进程组
3 个进程 kill 后归 0,procs 无残留;真实 core 启动 health 200,日志多一行
terminal=/bin/sh -c ← default。win32 分支只做了逻辑模拟(无 shell 的报错
文案、有 busybox 时解析为 busybox sh -c),真机待验。

未做:Windows 启动器未拉起四个同栈 MCP 与 office 预览网关,配置里
mcp_servers 暂为空,terminal / 文件工具 / 技能不受影响。
This commit is contained in:
2026-11-19 11:27:17 +08:00
parent ae9b78c661
commit 29be7bd9d7
12 changed files with 639 additions and 15 deletions
+4
View File
@@ -59,6 +59,7 @@ AGENT_CONFIG=./config.yml node server/server.js
| `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) |
| `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) |
| `server/remote-exec.js` | 调 `agent-executor` 的 `/exec`(SSE)与预览槽清理 |
| `server/shell.js` | **执行后端**:解析用哪个 POSIX shell 跑命令(POSIX 直接 `/bin/sh`;Windows 依次 git-bash → busybox-w32)、跨平台杀进程树。平台差异只允许出现在这里 |
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
@@ -403,6 +404,9 @@ preview-proxy.mount(末尾兜底)
## 陷阱清单(都是踩过的)
- **平台差异只允许出现在 `server/shell.js`**:`terminal` / 技能 / `engine.killRunProcs` 一律走
`shell.spawnShell` / `shell.killTree`,上层不写 `process.platform` 分支。POSIX 分支的行为
(`/bin/sh -c` + 进程组 + `kill(-pid)`)不能变——它是「模型按 POSIX 写就一定能跑」的保证。
- **循环依赖**:`engine` 绝不 `require('./wechat')` 或 `require('./scheduler')`,否则拿到半成品
exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。
- **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父
+3
View File
@@ -33,6 +33,9 @@ log_level: "info" # debug < info < warn < error
terminal:
default_timeout_ms: 30000 # 命令默认超时(ms)
max_output_chars: 10000 # 回传模型的最大输出字符数
# shell: '' # 跑命令的 POSIX shell;空 = 自动探测
# POSIX:/bin/sh;Windows:git-bash → busybox-w32
# env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 可改参数模板
fetch:
timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完
+3 -1
View File
@@ -76,7 +76,9 @@ const DEFAULTS = {
db_path: '',
// executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate);
// 本配置文件内含密钥,只给 core 进程读,executor/wxbot 一律不挂不读。
terminal: { default_timeout_ms: 30000, max_output_chars: 10000 },
// terminal.shell:跑命令用的 POSIX shell(空 = 自动探测:POSIX 直接 /bin/sh;Windows 依次找
// git-bash、busybox-w32)。env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 覆盖参数模板(默认 -c)。
terminal: { default_timeout_ms: 30000, max_output_chars: 10000, shell: '' },
// fetch:timeout_ms 覆盖请求发出到 body 读完的全生命周期;max_bytes 为流式抓取字节上限(超限即断开)。
// 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时
// 夹在 max_chars_hard 硬帽内;超窗尾部提示 offset,续读走 ctx.run 上的回合缓存不重抓。
+3 -3
View File
@@ -8,6 +8,7 @@ const { executeTool, resolveInTask } = require('./tools/executor');
const publicFiles = require('./public-files');
const mcp = require('./mcp');
const rexec = require('./remote-exec');
const shell = require('./shell'); // 执行后端:killTree 的平台差异(进程组 / taskkill)不往引擎里渗
const log = require('./log');
const profile = require('./user-profile');
const memory = require('./memory');
@@ -568,9 +569,8 @@ function killRunProcs(run) {
for (const proc of run.procs) {
// 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。
if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; }
try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) {
try { proc.kill('SIGKILL'); } catch (__) {}
}
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T。
shell.killTree(proc);
}
run.procs.clear();
}
+5
View File
@@ -14,6 +14,7 @@ const wechat = require('./wechat');
const llm = require('./llm');
const mcp = require('./mcp');
const skills = require('./tools/skills');
const shellBackend = require('./shell');
const log = require('./log');
const cfg = loadConfig(process.env.AGENT_CONFIG);
@@ -243,6 +244,10 @@ mcp.init(cfg).then(async () => {
log.info('startup', ' auth=' + (auth.enabled ? 'login: ' + cfg.auth.users.map(u => u.user).join(', ') : '(disabled)'));
log.info('startup', ' wxbot=' + (cfg.wxbot.url && cfg.wxbot.token ? cfg.wxbot.url : '(未启用)'));
log.info('startup', ' log_level=' + cfg.log_level);
// 模型命令到底交给谁跑。硬定 shell 时这里是唯一的凭据(Windows 上尤其要看到);
// 探测不到就降成 warn——服务能起,但 terminal 工具会一片红。
if (shellBackend.resolve(cfg)) log.info('startup', ' terminal=' + shellBackend.describe(cfg));
else log.warn('startup', ' terminal=' + shellBackend.describe(cfg));
// 微信实例恢复 fire-and-forget:wxbot 没起只留日志,绝不阻塞/抛错影响启动。
wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e)));
// prompt dump 失败不影响服务:只是核对用产物。
+226
View File
@@ -0,0 +1,226 @@
// 执行后端:全仓唯一处理「用哪个 shell 跑命令」「怎么杀整棵进程树」的地方。
//
// 为什么单开一层:POSIX 上 spawn('/bin/sh') + kill(-pid) 是刻意选的最强约束——
// /bin/sh 固定(不读 $SHELL,否则用户把 shell 设成 fish 后模型写的 POSIX 语法全废),
// 进程组让「停止」能一次带走模型起的孙进程(npm / python / ffmpeg 留下的才是麻烦)。
// Windows 没有 /bin/sh、没有进程组、也没有可发送的信号:同一个写法在那边从「有效」
// 变成「静默失效」,detached 还会多弹一个控制台。三种能力收敛成
// resolve / spawnShell / killTree,上层(terminal、skill、engine 取消)就不必出现平台分支。
//
// 默认行为与拆分前逐字节一致:不配任何 env 时仍是 /bin/sh -c + 进程组 +
// process.kill(-pid)。Windows 才走探测分支,探测不到就明确报错,绝不静默退回
// cmd.exe——cmd 的语法与模型写的 POSIX 差太远,静默降级只会让模型在报错里反复试错。
//
// 解析顺序(前面的赢,结果进程内缓存一次,与 config.js 的冷加载约定一致):
// 1. env AGENT_SHELL 显式指定可执行文件(绝对路径或 PATH 里的名字)
// 2. config.terminal.shell 同上,给不想碰 env 的部署方式
// 3. 自动探测 Windows:git-bash → busybox-w32 → 无
// POSIX :/bin/sh
// 4. env AGENT_SHELL_ARGS 覆盖参数模板(默认 -c,如 bash 想读 rc 可写 -lc)
// 另:env AGENT_GIT_BASH / AGENT_BUSYBOX 可指定各自的固定位置(便携安装用)。
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const IS_WIN = process.platform === 'win32';
const INSTALL_HINT = IS_WIN
? 'Windows 需要 POSIX shell:装 Git for Windows(自带 bash),或把 busybox-w32 放到 local/bin/busybox.exe,'
+ '或用环境变量 AGENT_SHELL 指定 shell 路径'
: '需要 POSIX shell(/bin/sh 不存在)';
// MSYS(Git for Windows)默认会把「看起来像 Unix 路径」的参数改写成 Windows 路径
// (/c/foo → C:\foo)。模型的命令里 /tmp、/c、相对路径都可能被它悄悄改掉,
// 排查起来像"命令没生效"。关掉自动转换,让字节原样过去。
const MSYS_ENV = {
MSYS_NO_PATHCONV: '1', // Git for Windows 旧变量
MSYS2_ARG_CONV_EXCL: '*', // MSYS2 新变量
};
let cacheKey = null;
let cached; // 解析结果;null = 解析过但没有可用 shell
function trimStr(v) { return typeof v === 'string' ? v.trim() : ''; }
// 参数模板按 shell 习惯切成数组(支持引号),默认 ['-c']。
function splitArgs(s) {
const out = [];
let cur = '';
let quote = null;
for (const ch of String(s)) {
if (quote) { if (ch === quote) quote = null; else cur += ch; continue; }
if (ch === '"' || ch === "'") { quote = ch; continue; }
if (/\s/.test(ch)) { if (cur) { out.push(cur); cur = ''; } continue; }
cur += ch;
}
if (cur) out.push(cur);
return out;
}
function shellArgs() {
const custom = trimStr(process.env.AGENT_SHELL_ARGS);
return custom ? splitArgs(custom) : ['-c'];
}
function existsExec(p) {
try {
if (!fs.statSync(p).isFile()) return false;
if (!IS_WIN) fs.accessSync(p, fs.constants.X_OK);
return true;
} catch (_) {
return false;
}
}
// 自己遍历 PATH,不调 where.exe:少一次进程启动,也避开 where 的输出编码差异。
function whichWin(name) {
const exts = /\.\w+$/.test(name) ? [''] : ['', '.exe', '.cmd', '.bat'];
for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
if (!dir) continue;
for (const ext of exts) {
const p = path.join(dir, name + ext);
if (existsExec(p)) return p;
}
}
return null;
}
// Git for Windows 的 bash。C:\Windows\System32\bash.exe 是 WSL 启动器,明确排除:
// 它的 -c 之后是 Linux 命令,路径全在另一个文件系统里,拿它当 shell 会让每个命令都跑偏。
function findGitBash() {
const e = process.env;
const cands = [
e.AGENT_GIT_BASH,
e.ProgramFiles && path.join(e.ProgramFiles, 'Git', 'bin', 'bash.exe'),
e['ProgramFiles(x86)'] && path.join(e['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'),
e.LOCALAPPDATA && path.join(e.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'),
e.USERPROFILE && path.join(e.USERPROFILE, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
e.ProgramData && path.join(e.ProgramData, 'chocolatey', 'bin', 'bash.exe'),
whichWin('bash.exe'),
];
for (const c of cands) {
if (!c) continue;
if (/\\windows\\(system32|winsxs)\\/i.test(c) || /\\windowsapps\\/i.test(c)) continue;
if (existsExec(c)) return c;
}
return null;
}
// busybox-w32:单文件原生 exe(约 600KB),需要 `busybox sh -c` 的 applet 形式。
// 固定位置放在仓库 local/bin/,由启动器下载——不进系统 PATH,卸载即净。
function findBusybox() {
const e = process.env;
const cands = [
e.AGENT_BUSYBOX,
path.join(__dirname, '..', '..', 'local', 'bin', 'busybox.exe'),
whichWin('busybox.exe'),
];
for (const c of cands) {
if (c && existsExec(c)) return c;
}
return null;
}
function posixDefault() {
return { cmd: '/bin/sh', args: shellArgs(), kind: 'sh', source: 'default', env: null, detached: true };
}
function fromExplicit(p) {
const args = shellArgs();
const busybox = /busybox/i.test(path.basename(p));
return {
cmd: p,
// busybox 是多 applet 单文件:必须点名 sh,否则 argv[0] 是 busybox 时它会当自己的子命令解析。
args: busybox ? ['sh', ...args] : args,
kind: busybox ? 'busybox' : 'bash',
source: 'explicit',
env: IS_WIN ? MSYS_ENV : null,
// POSIX 必须 detached(进程组是 killTree 的抓手);Windows 上开 detached 会新建控制台
// 并让子进程脱离 taskkill /T 的父子树,所以那边明确关掉。
detached: !IS_WIN,
};
}
function detectWindows() {
const bash = findGitBash();
if (bash) {
return { cmd: bash, args: shellArgs(), kind: 'bash', source: 'git-bash', env: MSYS_ENV, detached: false };
}
const bb = findBusybox();
if (bb) {
return { cmd: bb, args: ['sh', ...shellArgs()], kind: 'busybox', source: 'busybox-w32', env: null, detached: false };
}
return null;
}
function detect(cfg) {
const explicit = trimStr(process.env.AGENT_SHELL)
|| trimStr(cfg && cfg.terminal && cfg.terminal.shell);
if (explicit) return fromExplicit(explicit);
if (!IS_WIN) return posixDefault();
return detectWindows();
}
// 解析结果(对象形态,含 cmd/args/kind/source/env/detached)。没有可用 shell 时返回 null。
// 缓存键跟着「显式指定」的三个来源走:同一个进程里 cfg 或 env 变了会重新探测,
// 避免第一次调用(可能没有 cfg,比如技能层)把结果钉死。
function resolve(cfg) {
const key = [
trimStr(process.env.AGENT_SHELL),
trimStr(process.env.AGENT_SHELL_ARGS),
trimStr(cfg && cfg.terminal && cfg.terminal.shell),
].join('\u0000');
if (cacheKey !== key) {
cacheKey = key;
cached = detect(cfg);
}
return cached;
}
// 重新探测(测试与「改完立即生效」用;正常运行不需要调)。
function reset() { cacheKey = null; cached = undefined; }
function spawnShell(cfg, command, opts) {
const o = opts || {};
const sh = resolve(cfg);
if (!sh) throw new Error('执行后端不可用:' + INSTALL_HINT);
const env = sh.env ? { ...process.env, ...sh.env, ...(o.env || {}) } : { ...process.env, ...(o.env || {}) };
return spawn(sh.cmd, [...sh.args, String(command)], {
cwd: o.cwd,
env,
detached: sh.detached,
// 仅 Windows 生效:detached 之外的第二道保险,避免每条命令弹一个控制台窗口。
windowsHide: true,
});
}
// 杀整棵进程树。POSIX 走进程组(原来那两行原样保留);Windows 没有进程组,
// 用 taskkill /T 按父子树杀——不能用 child.kill(),那只会杀 shell 本身,
// 模型起的 node/python/ffmpeg 孙进程会留下来继续占端口。
function killTree(child) {
if (!child || !child.pid) return false;
if (!IS_WIN) {
try { process.kill(-child.pid, 'SIGKILL'); return true; } catch (_) {
try { child.kill('SIGKILL'); return true; } catch (__) { return false; }
}
}
try {
const p = spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true });
p.on('error', () => {});
p.unref();
return true;
} catch (_) {
try { child.kill(); return true; } catch (__) { return false; }
}
}
// 一行诊断(启动日志 / 健康检查用):告诉人「模型命令到底交给谁跑」。
function describe(cfg) {
const sh = resolve(cfg);
if (!sh) return '未找到(' + INSTALL_HINT + ')';
const args = sh.args.join(' ');
return sh.cmd + ' ' + args + ' ← ' + sh.source;
}
module.exports = { resolve, reset, spawnShell, killTree, describe, INSTALL_HINT };
+5 -7
View File
@@ -5,7 +5,7 @@ const path = require('path');
const net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
const fsp = require('fs').promises;
const { spawn } = require('child_process');
const shell = require('../shell'); // 执行后端:shell 解析 + 进程树 kill(平台差异只在那边,这里不做分支)
const mcp = require('../mcp');
const skills = require('./skills');
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
@@ -764,7 +764,7 @@ function selectOutput(text, head, tail) {
return parts.join('\n\n');
}
// terminal:spawn + 进程组 kill + 超时 + 输出截断
// terminal:交执行后端起 shell(POSIX 默认 /bin/sh -c,Windows 由 shell.js 探测)+ 超时 + 输出截断
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
@@ -809,7 +809,7 @@ async function toolTerminal(ctx, args) {
}
return new Promise((resolve) => {
const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
const child = shell.spawnShell(cfg, args.command, { cwd });
ctx.run.procs.add(child);
let out = '';
let killedBy = null; // 'timeout' | 'cancelled'
@@ -853,10 +853,8 @@ async function toolTerminal(ctx, args) {
}
function killGroup(child) {
if (!child.pid) return;
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
try { child.kill('SIGKILL'); } catch (__) {}
}
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T 杀进程树。
shell.killTree(child);
}
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
+5 -3
View File
@@ -14,6 +14,7 @@ const { spawn } = require('child_process');
const YAML = require('yaml');
const log = require('../log');
const rexec = require('../remote-exec');
const shell = require('../shell'); // 本地 spawn 技能时的进程树 kill(平台差异只在 shell.js)
// mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。
const mcp = require('../mcp');
@@ -187,7 +188,8 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
});
}
return new Promise((resolve, reject) => {
const child = spawn(entry, args, { cwd, env: process.env, detached: true });
// windowsHide:Windows 上 detached 之外的第二道保险,避免弹控制台;POSIX 忽略该选项。
const child = spawn(entry, args, { cwd, env: process.env, detached: true, windowsHide: true });
if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
let out = '';
let settled = false;
@@ -200,7 +202,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
settled = true;
clearInterval(cancelCheck);
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
shell.killTree(child);
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
}, timeoutMs);
@@ -209,7 +211,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
settled = true;
clearTimeout(timer);
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
shell.killTree(child);
reject(new SkillExecutionError('技能执行被用户终止', -1));
}
}, 200);