Author SHA1 Message Date
kicer 29be7bd9d7 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 / 文件工具 / 技能不受影响。
2026-11-19 11:27:17 +08:00
12 changed files with 639 additions and 15 deletions
+3
View File
@@ -10,6 +10,9 @@ skills/*/.deps_installed
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md) # 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
local/.runtime/ local/.runtime/
local/config.local.yml local/config.local.yml
local/config.win.yml
# busybox-w32:Windows 启动器下载的 shell 二进制(不进 git)
local/bin/
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git # officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
skills/office/bin/ skills/office/bin/
skills/**/__pycache__/ skills/**/__pycache__/
+1 -1
View File
@@ -24,7 +24,7 @@
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` | | `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 | | `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 | | `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor),`start.sh` 负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` | | `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor)。`start.sh`(macOS/Linux)与 `start-win.mjs`(Windows)负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
| `tunnel/` | **反向隧道**:服务器端 `server.js` 按 Host / 固定端口 / 通配路由转发,本机 `client.js` 承接 | 独立 compose,见 `tunnel/README.md` | | `tunnel/` | **反向隧道**:服务器端 `server.js` 按 Host / 固定端口 / 通配路由转发,本机 `client.js` 承接 | 独立 compose,见 `tunnel/README.md` |
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** | | `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — | | `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
+4
View File
@@ -59,6 +59,7 @@ AGENT_CONFIG=./config.yml node server/server.js
| `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) | | `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) |
| `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) | | `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) |
| `server/remote-exec.js` | 调 `agent-executor` 的 `/exec`(SSE)与预览槽清理 | | `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/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) | | `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 | | `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')`,否则拿到半成品 - **循环依赖**:`engine` 绝不 `require('./wechat')` 或 `require('./scheduler')`,否则拿到半成品
exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。 exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。
- **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父 - **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父
+3
View File
@@ -33,6 +33,9 @@ log_level: "info" # debug < info < warn < error
terminal: terminal:
default_timeout_ms: 30000 # 命令默认超时(ms) default_timeout_ms: 30000 # 命令默认超时(ms)
max_output_chars: 10000 # 回传模型的最大输出字符数 max_output_chars: 10000 # 回传模型的最大输出字符数
# shell: '' # 跑命令的 POSIX shell;空 = 自动探测
# POSIX:/bin/sh;Windows:git-bash → busybox-w32
# env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 可改参数模板
fetch: fetch:
timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完 timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完
+3 -1
View File
@@ -76,7 +76,9 @@ const DEFAULTS = {
db_path: '', db_path: '',
// executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate); // executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate);
// 本配置文件内含密钥,只给 core 进程读,executor/wxbot 一律不挂不读。 // 本配置文件内含密钥,只给 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 为流式抓取字节上限(超限即断开)。 // fetch:timeout_ms 覆盖请求发出到 body 读完的全生命周期;max_bytes 为流式抓取字节上限(超限即断开)。
// 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时 // 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时
// 夹在 max_chars_hard 硬帽内;超窗尾部提示 offset,续读走 ctx.run 上的回合缓存不重抓。 // 夹在 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 publicFiles = require('./public-files');
const mcp = require('./mcp'); const mcp = require('./mcp');
const rexec = require('./remote-exec'); const rexec = require('./remote-exec');
const shell = require('./shell'); // 执行后端:killTree 的平台差异(进程组 / taskkill)不往引擎里渗
const log = require('./log'); const log = require('./log');
const profile = require('./user-profile'); const profile = require('./user-profile');
const memory = require('./memory'); const memory = require('./memory');
@@ -568,9 +569,8 @@ function killRunProcs(run) {
for (const proc of run.procs) { for (const proc of run.procs) {
// 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。 // 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。
if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; } if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; }
try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) { // 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T。
try { proc.kill('SIGKILL'); } catch (__) {} shell.killTree(proc);
}
} }
run.procs.clear(); run.procs.clear();
} }
+5
View File
@@ -14,6 +14,7 @@ const wechat = require('./wechat');
const llm = require('./llm'); const llm = require('./llm');
const mcp = require('./mcp'); const mcp = require('./mcp');
const skills = require('./tools/skills'); const skills = require('./tools/skills');
const shellBackend = require('./shell');
const log = require('./log'); const log = require('./log');
const cfg = loadConfig(process.env.AGENT_CONFIG); 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', ' 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', ' wxbot=' + (cfg.wxbot.url && cfg.wxbot.token ? cfg.wxbot.url : '(未启用)'));
log.info('startup', ' log_level=' + cfg.log_level); 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 没起只留日志,绝不阻塞/抛错影响启动。 // 微信实例恢复 fire-and-forget:wxbot 没起只留日志,绝不阻塞/抛错影响启动。
wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e))); wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e)));
// prompt dump 失败不影响服务:只是核对用产物。 // 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 net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定 const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
const fsp = require('fs').promises; const fsp = require('fs').promises;
const { spawn } = require('child_process'); const shell = require('../shell'); // 执行后端:shell 解析 + 进程树 kill(平台差异只在那边,这里不做分支)
const mcp = require('../mcp'); const mcp = require('../mcp');
const skills = require('./skills'); const skills = require('./skills');
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合) const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
@@ -764,7 +764,7 @@ function selectOutput(text, head, tail) {
return parts.join('\n\n'); return parts.join('\n\n');
} }
// terminal:spawn + 进程组 kill + 超时 + 输出截断 // terminal:交执行后端起 shell(POSIX 默认 /bin/sh -c,Windows 由 shell.js 探测)+ 超时 + 输出截断
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard // 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。 // (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。 // JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
@@ -809,7 +809,7 @@ async function toolTerminal(ctx, args) {
} }
return new Promise((resolve) => { 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); ctx.run.procs.add(child);
let out = ''; let out = '';
let killedBy = null; // 'timeout' | 'cancelled' let killedBy = null; // 'timeout' | 'cancelled'
@@ -853,10 +853,8 @@ async function toolTerminal(ctx, args) {
} }
function killGroup(child) { function killGroup(child) {
if (!child.pid) return; // 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T 杀进程树。
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { shell.killTree(child);
try { child.kill('SIGKILL'); } catch (__) {}
}
} }
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头); // fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
+5 -3
View File
@@ -14,6 +14,7 @@ const { spawn } = require('child_process');
const YAML = require('yaml'); const YAML = require('yaml');
const log = require('../log'); const log = require('../log');
const rexec = require('../remote-exec'); const rexec = require('../remote-exec');
const shell = require('../shell'); // 本地 spawn 技能时的进程树 kill(平台差异只在 shell.js)
// mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。 // mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。
const mcp = require('../mcp'); const mcp = require('../mcp');
@@ -187,7 +188,8 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
}); });
} }
return new Promise((resolve, reject) => { 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); if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
let out = ''; let out = '';
let settled = false; let settled = false;
@@ -200,7 +202,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
settled = true; settled = true;
clearInterval(cancelCheck); clearInterval(cancelCheck);
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child); 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)); reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
}, timeoutMs); }, timeoutMs);
@@ -209,7 +211,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
settled = true; settled = true;
clearTimeout(timer); clearTimeout(timer);
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child); 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)); reject(new SkillExecutionError('技能执行被用户终止', -1));
} }
}, 200); }, 200);
+57
View File
@@ -63,6 +63,63 @@ cd agent
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成; 这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
即使没自动弹出,文件也一直在那个路径。 即使没自动弹出,文件也一直在那个路径。
## Windows
需要 Node 20+(不需要 Docker,也不需要装 Git):
```bat
node local\start-win.mjs
node local\start-win.mjs --workspace=D:\AgentWork --port=8090
```
首次运行会:
1. 自检 Node 版本
2. **找命令执行环境**:优先用已装的 Git for Windows(自带 bash);没有再自动下载
[busybox-w32](https://frippery.org/busybox)(单文件约 600KB)到 `local/bin/busybox.exe`
3. 建工作目录(默认 `%USERPROFILE%\AgentWork`,`--workspace` 可改)下的 `tasks/` `data/` `skills/`
4. 生成 `local/config.win.yml`(**首次生成,之后永不覆盖**)
5. 把仓库 `skills/` 里的内置技能补过去(只补缺不覆盖)
6. `app/node_modules` 缺失时 `npm install`
7. 起 core 并守护(退出 3 秒后自动重启,连崩 5 次停)
浏览器开 `http://127.0.0.1:8090`,到「设置 → 模型池」加平台和 API Key。
**停止:Ctrl+C**(没有 `stop.sh`,启动器就是前台进程)。`--check` 只做自检不启动。
### 为什么 Windows 是另一条代码路径
`start.sh` 靠 `lsof` / `pgrep` / `readlink -f` / `nohup` / `setsid` / 进程组信号,Windows 一个都没有。
所以那 1100 多行 bash 没有移植,而是用 Node 重写了「启动器」这一层——它本来就只做进程管理,
不需要 shell。**业务代码一行都不分平台**:平台差异只落在两个文件里:
| 文件 | 负责 |
|---|---|
| `app/server/shell.js` | 用哪个 shell 跑命令、怎么杀进程树(POSIX 进程组 / Windows `taskkill /T`) |
| `local/start-win.mjs` | 探测、下载 busybox、生成配置、起进程、守护 |
### 覆盖与排错
| 变量 | 作用 |
|---|---|
| `AGENT_SHELL` | 直接指定 shell(绝对路径或 PATH 名),跳过一切探测 |
| `AGENT_SHELL_ARGS` | 参数模板,默认 `-c`(如 bash 想读 rc 可写 `-lc`) |
| `AGENT_GIT_BASH` | 指定 git-bash 位置(便携版/非标准安装路径) |
| `AGENT_BUSYBOX` | 指定 busybox.exe 位置 |
| `AGENT_BUSYBOX_URL` | 换 busybox 下载源(国内网络) |
命令到底交给了谁跑:启动日志里有一行 `terminal=...`,失败时会写成 `terminal=未找到(...)`。
### Windows 上仍有的限制
- **四个同栈 MCP 没有自动拉起**(配置里 `mcp_servers: []`):网页搜索/图片/视频/语音暂不可用,
`terminal`、文件工具、技能正常。
- **office 预览网关没起**:docx/xlsx/pptx 不能在线预览,但 `office` 技能生成文件不受影响。
- **没有沙箱**:和 macOS/Linux 本地模式一样,AI 的 `terminal` 就是你的 shell,能读写你有权限的任何文件。
工作目录选专用的,别选 `C:\` 或整个仓库。
- **`chmod` / `ln -s` 这类不生效**:Windows 没有 POSIX 权限位;模型写这类命令会“成功但什么都没做”。
- **`/tmp` 不是 Linux 的 `/tmp`**:busybox 会把它当当前盘根目录(`C:\tmp`),git-bash 映射到 `%TEMP%`。
模型最好用相对路径或会话目录。
## 可选能力 ## 可选能力
| 能力 | 需要 | 没有时的表现 | | 能力 | 需要 | 没有时的表现 |
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env node
// Windows 本机模式启动器(macOS / Linux 用 local/start.sh,两者注入同一组环境变量)。
//
// 为什么单独一个 Node 脚本:start.sh 那 1100 多行 bash 靠的是 lsof / pgrep / readlink -f /
// nohup / setsid / 进程组信号,Windows 一个都没有。与其在 Windows 上凑一套半残的 POSIX 环境,
// 不如用 Node 重写"启动器"这一层——它本来就只做进程管理,不需要 shell。
// 业务代码(app/server)一行都不分平台,平台差异只落在 app/server/shell.js 与这个文件里。
//
// 做的事,按顺序:
// 1. 自检(Node 20+)
// 2. 找 POSIX 命令执行环境:git-bash → 已有的 busybox-w32 → 都没有就下载 busybox-w32
// 3. 首次运行生成工作目录与 local/config.win.yml(之后永不覆盖)
// 4. 补技能(只补缺,不覆盖)
// 5. app/node_modules 缺失时 npm install
// 6. 拉起 core 并守护(退出自动重启)
//
// 用法:
// node local/start-win.mjs # 默认工作目录 %USERPROFILE%\AgentWork
// node local/start-win.mjs --workspace=D:\ai # 指定工作目录
// node local/start-win.mjs --check # 只做自检与探测,不启动
// node local/start-win.mjs --port=8090 --no-open
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn, spawnSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const shellBackend = require('../app/server/shell.js');
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const IS_WIN = process.platform === 'win32';
const BUSYBOX_PATH = path.join(ROOT, 'local', 'bin', 'busybox.exe');
const CONFIG_PATH = path.join(ROOT, 'local', 'config.win.yml');
// ---------- 小工具 ----------
const C = { ok: '\x1b[32m', warn: '\x1b[33m', err: '\x1b[31m', dim: '\x1b[2m', n: '\x1b[0m' };
const say = (s) => console.log(`${C.ok}==>${C.n} ${s}`);
const warn = (s) => console.log(`${C.warn}[!]${C.n} ${s}`);
const dim = (s) => console.log(`${C.dim} ${s}${C.n}`);
function die(s, hint) {
console.error(`${C.err}[x]${C.n} ${s}`);
if (hint) console.error(` ${hint}`);
process.exit(1);
}
// ---------- 参数 ----------
const opt = { workspace: '', port: 8090, open: true, check: false };
for (const a of process.argv.slice(2)) {
if (a.startsWith('--workspace=')) opt.workspace = a.slice('--workspace='.length);
else if (a.startsWith('--port=')) opt.port = Number(a.slice('--port='.length)) || 8090;
else if (a === '--no-open') opt.open = false;
else if (a === '--check') opt.check = true;
else if (a === '-h' || a === '--help') {
console.log('用法: node local/start-win.mjs [--workspace=<目录>] [--port=8090] [--no-open] [--check]');
process.exit(0);
} else die(`未知参数:${a}`);
}
// ---------- 1. 自检 ----------
function checkNode() {
const major = Number(String(process.versions.node).split('.')[0]);
if (major < 20) die(`需要 Node.js 20+,当前 ${process.version}`, '装新版:https://nodejs.org/ 或 winget install OpenJS.NodeJS.LTS');
say(`Node ${process.version}(${process.arch})`);
if (!IS_WIN) warn('当前不是 Windows:这个启动器只是 Windows 用;macOS/Linux 请用 local/start.sh');
}
// ---------- 2. 命令执行环境 ----------
// 优先级由 app/server/shell.js 决定(AGENT_SHELL > 配置 > git-bash > busybox-w32)。
// 这里只负责"没有就补一个":装到 local/bin/busybox.exe,core 那边按固定路径探测得到。
async function ensureShell() {
shellBackend.reset();
const found = shellBackend.resolve({});
if (found) {
say(`命令执行环境:${shellBackend.describe({})}`);
return found;
}
if (!IS_WIN) die('找不到 POSIX shell(/bin/sh)', '这个启动器是 Windows 用的;macOS/Linux 用 local/start.sh');
warn('没有找到 POSIX shell(git-bash 与 busybox-w32 都不在)');
say('下载 busybox-w32(单文件,约 600KB,不需要管理员权限)');
await downloadBusybox();
shellBackend.reset();
const after = shellBackend.resolve({});
if (!after) die('busybox-w32 装好了但仍探测不到', `检查文件是否存在且可执行:${BUSYBOX_PATH}`);
say(`命令执行环境:${shellBackend.describe({})}`);
return after;
}
// busybox-w32 官方发布页永远指向同一个 busybox.exe;国内下载不顺时可自行换源。
// 全部候选都失败就明确报错并给出"手动放文件"的一步操作,不静默降级到 cmd.exe。
async function downloadBusybox() {
const urls = [];
if (process.env.AGENT_BUSYBOX_URL) urls.push(process.env.AGENT_BUSYBOX_URL);
urls.push('https://frippery.org/files/busybox/busybox.exe');
// 备用源:GitHub Release(release 资产名固定为 busybox.exe)。国内直连 GitHub 慢时
// 自动走 gh-proxy 前缀重试,两者都失败才放弃。
try {
const gh = await githubBusyboxUrl();
if (gh) urls.push(gh, 'https://gh-proxy.com/' + gh);
} catch (_) { /* 拿不到 latest 就只试官方源 */ }
fs.mkdirSync(path.dirname(BUSYBOX_PATH), { recursive: true });
const tmp = BUSYBOX_PATH + '.download';
let lastErr = '';
for (const u of urls) {
try {
process.stdout.write(` ${u}\n `);
await fetchToFile(u, tmp);
// 只读前两个字节校验 PE 头,不把整个文件读进内存。
const fd = fs.openSync(tmp, 'r');
const head = Buffer.alloc(2);
fs.readSync(fd, head, 0, 2, 0);
fs.closeSync(fd);
if (head.toString('latin1') !== 'MZ') throw new Error('下载到的不是 Windows 可执行文件(缺 MZ 头)');
fs.renameSync(tmp, BUSYBOX_PATH);
console.log('');
say(`已安装 ${BUSYBOX_PATH}`);
return;
} catch (e) {
lastErr = e.message;
console.log(` 失败:${e.message}`);
try { fs.unlinkSync(tmp); } catch (_) { /* 没下载成功就没有临时文件 */ }
}
}
die('busybox-w32 下载失败:' + lastErr,
`手动下载 https://frippery.org/files/busybox/busybox.exe 存成 ${BUSYBOX_PATH} 后重跑本脚本;`
+ '或先装 Git for Windows(自带 bash,会被自动识别)');
}
async function githubBusyboxUrl() {
const r = await fetch('https://api.github.com/repos/rmyorston/busybox-w32/releases/latest', {
headers: { 'User-Agent': 'agent-local-launcher' },
signal: AbortSignal.timeout(8000),
});
if (!r.ok) return null;
const j = await r.json();
const asset = (j.assets || []).find(a => /busybox\.exe$/i.test(a.name));
return asset ? asset.browser_download_url : null;
}
// 带进度地下载(内容长度已知时打百分比;不知道就只打字节数)。
async function fetchToFile(url, dest) {
const r = await fetch(url, {
headers: { 'User-Agent': 'agent-local-launcher' },
signal: AbortSignal.timeout(120000),
redirect: 'follow',
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const total = Number(r.headers.get('content-length') || 0);
const out = fs.createWriteStream(dest);
let got = 0;
for await (const chunk of r.body) {
got += chunk.length;
if (!out.write(chunk)) await new Promise(res => out.once('drain', res));
if (total) process.stdout.write(`\r ${(got / 1024).toFixed(0)}KB / ${(total / 1024).toFixed(0)}KB`);
}
await new Promise((res, rej) => out.end(err => (err ? rej(err) : res())));
if (total && got !== total) throw new Error(`下载不完整(${got}/${total} 字节)`);
if (got < 200 * 1024) throw new Error(`文件太小(${got} 字节),大概率不是 busybox`);
}
// ---------- 3. 工作目录与配置 ----------
function ensureWorkspace() {
const ws = path.resolve(opt.workspace || path.join(os.homedir(), 'AgentWork'));
const dirs = {
root: ws,
tasks: path.join(ws, 'tasks'),
data: path.join(ws, 'data'),
skills: path.join(ws, 'skills'),
};
for (const d of [dirs.tasks, dirs.data, dirs.skills]) fs.mkdirSync(d, { recursive: true });
say(`工作目录:${ws}`);
return dirs;
}
function ensureConfig(dirs) {
if (fs.existsSync(CONFIG_PATH)) {
dim(`复用已有配置 ${CONFIG_PATH}(不会覆盖你在网页里改的模型与密钥)`);
return;
}
// YAML 里统一用正斜杠:Node 与 YAML 都不需要转义,反斜杠反而要写两遍。
const p = (s) => s.replace(/\\/g, '/');
const yml = `# 由 local/start-win.mjs 首次生成,之后不再覆盖。
# 字段含义与服务器版一致(见 app/config.example.yml),这里只列本机模式用到的部分。
port: ${opt.port}
# AI 的工作根:文件工具的根就是它,AI 看不到同级的 data/ 与 skills/。
workspace_root: "${p(dirs.tasks)}"
# SQLite(.agent.db)与启动 prompt dump。
data_root: "${p(dirs.data)}"
skills:
# 内置技能由启动器首次复制过来,之后只补缺不覆盖;pip 装的依赖落在同级的 deps/。
skills_root: "${p(dirs.skills)}"
# 留空:启动后到设置页添加平台与 API Key,再点「重启」(启动器负责把进程拉起来)。
platforms: []
log_level: info
# 同栈 MCP(网页搜索 / 图片 / 视频 / 语音)暂未由 Windows 启动器拉起,
# 需要时在设置页按卡片添加地址,或先用 local/start.sh 的机器上那份配置。
mcp_servers: []
`;
fs.writeFileSync(CONFIG_PATH, yml, 'utf8');
say(`已生成配置 ${CONFIG_PATH}`);
}
// ---------- 4. 技能 ----------
// 只补缺不覆盖:用户改过的技能、自己新建的技能都不能被启动器冲掉(与 start.sh 同语义)。
function syncSkills(dirs) {
const src = path.join(ROOT, 'skills');
if (!fs.existsSync(src)) return;
let copied = 0;
for (const name of fs.readdirSync(src)) {
if (name === 'deps' || name.startsWith('.')) continue; // deps 是依赖层,按技能各自安装
const from = path.join(src, name);
const to = path.join(dirs.skills, name);
if (!fs.statSync(from).isDirectory() || fs.existsSync(to)) continue;
fs.cpSync(from, to, { recursive: true });
copied++;
}
say(copied ? `补齐技能 ${copied} 个` : '技能已是最新(不覆盖已有目录)');
}
// ---------- 5. 依赖 ----------
function ensureDeps() {
const appDir = path.join(ROOT, 'app');
if (fs.existsSync(path.join(appDir, 'node_modules', 'better-sqlite3'))) return;
warn('首次运行需要安装 Node 依赖(app/node_modules 缺失)');
const npm = IS_WIN ? 'npm.cmd' : 'npm';
const r = spawnSync(npm, ['install'], { cwd: appDir, stdio: 'inherit', shell: IS_WIN });
if (r.status !== 0) {
die('npm install 失败',
'国内网络可先换源:npm config set registry https://registry.npmmirror.com 后重试');
}
}
// ---------- 6. 起 core 并守护 ----------
function envFor(shell, dirs) {
const deps = path.join(dirs.skills, 'deps');
fs.mkdirSync(deps, { recursive: true });
return {
...process.env,
PORT: String(opt.port),
HOST: '127.0.0.1', // 本机模式只听回环(与 start.sh 一致)
AGENT_CONFIG: CONFIG_PATH,
AGENT_FILE_SCOPE: 'workspace', // 文件工具的根放宽到工作目录(本地单用户形态)
AGENT_LOCAL_PICK: '1',
AGENT_IMAGE_INLINE: '1', // 回环地址厂商拉不到,读图改内联 base64
PYTHONPATH: deps,
AGENT_SKILLS_DEPS: deps,
// 启动器探测到的 shell 直接钉给 core:两边 PATH 可能略有差异,钉住可避免"启动器说
// 用 git-bash、core 里却探测成 busybox"这种难查的双份事实。
AGENT_SHELL: shell.cmd,
};
}
function openBrowser(url) {
if (!opt.open) return;
try {
if (IS_WIN) spawn('cmd', ['/c', 'start', '', url], { stdio: 'ignore', windowsHide: true, detached: true }).unref();
else if (process.platform === 'darwin') spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
else spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
} catch (_) { /* 打不开浏览器不影响服务 */ }
}
function startCore(shell, dirs) {
const env = envFor(shell, dirs);
const appDir = path.join(ROOT, 'app');
let stopping = false;
let restarts = 0;
let child = null;
const launch = () => {
child = spawn(process.execPath, ['server/server.js'], { cwd: appDir, env, stdio: 'inherit' });
child.on('exit', (code) => {
if (stopping) return;
restarts++;
// 连续崩 5 次就停:多半是配置错(端口被占 / 模型池空),无限重启只会刷屏。
if (restarts > 5) die(`core 连续退出 5 次(最后退出码 ${code})`, '看上面的报错;常见原因:端口被占用、config.win.yml 写错');
warn(`core 退出了(code=${code}),3 秒后重启(第 ${restarts} 次)`);
setTimeout(launch, 3000);
});
};
const stop = () => {
stopping = true;
if (child && child.pid) shellBackend.killTree(child);
process.exit(0);
};
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
launch();
const url = `http://127.0.0.1:${opt.port}`;
setTimeout(() => openBrowser(url), 1500);
say(`启动完成:${url}(Ctrl+C 停止)`);
}
// ---------- 主流程 ----------
(async () => {
checkNode();
const shell = await ensureShell();
const dirs = ensureWorkspace();
ensureConfig(dirs);
syncSkills(dirs);
if (opt.check) {
say('自检完成(--check 不启动服务)');
dim(`配置:${CONFIG_PATH}`);
dim(`命令执行环境:${shellBackend.describe({})}`);
return;
}
ensureDeps();
startCore(shell, dirs);
})();