diff --git a/docs/local-mode.md b/docs/local-mode.md index 96e92dc..5b10e2e 100644 --- a/docs/local-mode.md +++ b/docs/local-mode.md @@ -21,7 +21,7 @@ 基线版本:`v2.5.0`(服务器端最后一个纯容器部署版本)。 -## 2. 与服务器形态的差异(只有五处) +## 2. 与服务器形态的差异(只有六处) | 差异 | 服务器 | 本地 | 由谁注入 | |---|---|---|---| @@ -30,8 +30,9 @@ | 监听地址 | `0.0.0.0` | `127.0.0.1` | `HOST=127.0.0.1` | | 对外链接(`mint_public_link` / `visit_url`) | `public_link.base_url` 拼公网短链 | 没有公网前缀时改拼 `http://127.0.0.1:/p/` | 复用 `localOrigin()`,靠 `HOST` 判断形态,不写配置 | | 读图回传给模型 | 签公网短链,上游服务器来拉 | 上游拉不到回环地址,改为内联 base64 `data:` URL | `AGENT_IMAGE_INLINE=1` | +| office 预览的后端 | executor 的 `:3100` 网关(mount/pid 牢笼) | `local/preview-gateway.js`(同机、无牢笼) | `PREVIEW_PROXIES` 注入 core 的反代注册表 | -后四项是本次新增的开关。**四个都不设置时,行为与 v2.5.0 完全一致**(容器部署不受影响)。 +后五项都由本地启动器注入。**都不注入时,行为与 v2.5.0 完全一致**(容器部署不受影响)。 ## 3. 本次改动清单 @@ -68,6 +69,7 @@ | `start.sh` | 主入口:探测 → 首次生成配置 → 装依赖 → 起 core + MCP → 守护重启。**后台化**:拉起真正的启动器就返回 | | `stop.sh` | 停止启动器(按 `supervisor.pid` → core 的父进程 → 占端口的进程,三级兜底),幂等 | | `config.example.yml` | **仅作参考,不被读取**;实际配置由 `start.sh` 生成到 `config.local.yml` | +| `preview-gateway.js` | 本地 office 预览网关(对位 executor 的 `:3100`,见 §4.15) | | `README.md` | 给使用者的说明(含安全边界、已知限制) | `.gitignore` 增加 `local/.runtime/`、`local/config.local.yml`。 @@ -321,8 +323,32 @@ health 只作为「端口上有服务但不是本启动器拉起的」兜底提 `soffice` 不在 PATH(在 app bundle 内),不探这几个默认位置,“装 LibreOffice 即可”就是假的。 另保留了 WeasyPrint 不可用时回落 LibreOffice,让本地只需一个后端而不是 pango + WeasyPrint 两套链。 -没做的是预览:预览卡片要 executor 的 `:3100` 网关,本地没有。要补相当于把 -`executor/preview.js` 的槽位管理搬进 core,不值得。 +没做的是预览:预览卡片要 executor 的 `:3100` 网关,本地没有——这一项后来补了,见 §4.15。 + +### 4.15 office 文档预览:本地自建一个薄网关 + +服务器上「点开 docx」是 core → 反代 `/preview` → executor 的 `:3100` 网关 → 网关按需 spawn +`officecli watch`。本地没有 executor,链路断在中间。补法不是改 core,而是在 `local/` 里放一个 +零依赖网关,用 `PREVIEW_PROXIES` 把它登记进 core 的反代注册表(`app/` 一行没改)。 + +**不复用 `executor/preview.js`**:那套 `unshare --mount --pid` + `nsenter` + `mount --bind` 是为 +「让沙箱内的命令和 watch 看见同一个世界」造的(vendor 靠 `TMPDIR` 下的句柄文件 + 回环 TCP 相互 +发现)。本地没有沙箱,命令和 watch 本来就同机同盘,那些系统调用不但用不上,有些平台根本没有。 +于是本地网关只剩数据面: + +- `/preview/<会话id>/<相对路径>` → 解析真实文件 → 确保有 watch → 剥前缀转发 +- `/events`(SSE)与 `/api/*`(选区回读、切换、发送)→ 按 `Referer` 认领槽位再转发 +- 4 个槽位,LRU 挤占 + 闲置回收;watch 端口从 26315 起按代轮转,跳过已被占用的 +- 缺 `officecli` 时给「安装说明页」,而不是无限转圈:服务器那份二进制是构建期必装的, + `preview.js` 从没为「没装」设计;本地全新 clone 一定没有,这是常态不是异常 + +于是本地 `office` 的体验与服务器一致:`create`/`open` 后聊天里出预览卡片,点开即右侧预览, +`get-pos` 能读到选区。技能侧因此不需要任何本地分支(`skills/office` 与服务器同源)。 + +平台差异都收在两处:进程回收(POSIX 杀进程组 / Windows `taskkill /T`)、二进制解析(`.exe`、 +POSIX 补 `chmod +x`、`officecli-*` 资产名也认)。其余只用 Node 内置能力。 + +已知:watch 没有 `--host` 参数,只能绑 `0.0.0.0`(与 `mcp_asr` 同类);网关与 core 只在回环上。 ## 5. 验证结果(macOS 12.7.6 / x86_64 / Node 22.21 / python3 3.10 / 本机无 ffmpeg) @@ -354,6 +380,11 @@ health 只作为「端口上有服务但不是本启动器拉起的」兜底提 | 无 node(PATH 里剥掉 node/npm):入口直接拦下,**不** 先让选目录、不生成配置;终端打出安装方式;状态页列出自检项(X Node.js / X npm) | 通过 | | 失败时只开一个状态页标签(不再两个) | 通过 | | 状态页:启动即弹出、每秒刷新、显示步骤/计时/日志尾巴;失败时保留错误与日志 | 通过 | +| 预览网关(直接打网关,临时 tasks 根):HEAD 探针 200、GET 200、自动起 watch @26315 | 通过 | +| 预览数据面:`/events` 是真 SSE、`/api/selection` 204、`/api/send` 200;无 `Referer` 404 | 通过 | +| 缺 `officecli`:给安装说明页,HEAD 仍 200(面板不闪死链) | 通过 | +| 网关退出:watch 端口释放,无残留进程 | 通过 | +| 经 core 的 `/preview` 端到端(含手选工作目录、`work_dir` 在 `tasks/` 外的会话) | 待复验 | | `osascript` 真实选目录弹窗 | 未验证(用桩跑的「没选→回落 `~/AgentWork`」分支) | | 真浏览器打开(`open`) | 未验证(用桩记录了被打开的 URL) | | 装 ffmpeg 之后:`ASR_URL` 注入、asr 子进程与麦克风一起出现 | 未验证(本机未装 ffmpeg) | @@ -396,7 +427,7 @@ tail -f local/.runtime/core.log # 以及 npm-install.log / mcp-*.log | 链接只在本机可达 | 本地没有公网前缀:`mint_public_link` / 页面访问地址都签成 `http://127.0.0.1:/...`,只能在这台机器上打开(这正是本地形态的预期)。要真正对外暴露才需在设置页填 `public_link.base_url` | | 技能依赖 | 本地不预装:缺包时模型会把包装进 `<工作目录>/skills/deps`(`$AGENT_SKILLS_DEPS`,已在该进程 `PYTHONPATH` 里,装完下次运行即生效);连 `python3` 都没有时也由它自己装。怎么装由模型自己决定。需要系统库的包(`weasyprint`→pango/cairo)pip 装不了,仍需手工 `brew install`。服务器上由 `agent-executor-init` 处理 | | `office` 二进制 | 不入库、也不预装:首次用到时报 `binary missing` 并给出该技能 `AGENTS.md` 的绝对路径,模型按它自己下载(`releases/latest`,~34MB,GitHub 慢就用 gh-proxy)。不需要 root、不需重启。officecli 会自更新到 latest,版本比服务器 pin 的新属正常 | -| `office` 预览 | 预览卡片走 core → executor 的 `:3100` 网关,本地没有这个网关 → 点开打不开。文档创建/编辑/读取不受影响 | +| `office` 预览 | 本地网关按需起 `officecli watch`,体验与服务器一致;但 watch 没有 `--host`,只能绑 `0.0.0.0`,且预览进程闲置 6h 回收(槽位 4 个) | | 首个 `npm install` 要联网 | 支持 `NPM_REGISTRY` 覆盖源;`app/package-lock.json` 的 `resolved` 已改指向公共 registry(原来钉在内网镜像,外部机器必失败) | ## 8. 回滚 diff --git a/local/README.md b/local/README.md index 30f32ef..8440e7d 100644 --- a/local/README.md +++ b/local/README.md @@ -69,7 +69,7 @@ cd agent |---|---|---| | 语音输入 | `ffmpeg` + 设置页给 `asr` 填上游(`X-ASR-Base-Url` / `X-ASR-Model`) | 麦克风入口自动隐藏(`/api/asr/status` 返回 `enabled:false`),`mcp_asr` 子进程也不启动 | | 技能 | `python3`(仅 Python 类技能需要) | 技能清单照常显示;调 `run.py` 类技能报「入口启动失败」,`office` 这类非 Python 技能不受影响 | -| Office 文档(docx/xlsx/pptx) | 首次用到时下载一次 officecli 二进制(约 34MB) | `office` 报 `binary missing` 并给出该技能 `AGENTS.md` 的路径,按它下载即可(不需 root、不需重启) | +| Office 文档(docx/xlsx/pptx) | 首次用到时下载一次 officecli 二进制(约 34MB) | `office` 报 `binary missing` 并给出该技能 `AGENTS.md` 的路径,按它下载即可(不需 root、不需重启);预览面板里直接显示同一份安装说明 | | 网页搜索 | 无 | 装了 Node 就有(内置免费后端) | | 图片 / 视频生成 | 设置页给对应 MCP 填上游 key | 调用时报明确的缺参错误 | @@ -90,7 +90,7 @@ cd agent 仓库里只有: - 生成的配置:`local/config.local.yml`(**首次生成,之后永不覆盖**,避免冲掉你在网页里配的模型与密钥) -- 运行期产物:`local/.runtime/`(`status.html` 状态页、`core.log`、`npm-install.log`、各 MCP 日志) +- 运行期产物:`local/.runtime/`(`status.html` 状态页、`core.log`、`npm-install.log`、`mcp-*.log`、`preview.log` + `watch-<端口>.log`) 想彻底重来:删掉 `local/config.local.yml` 再启动(工作目录里的数据不会动,重选一个目录就换一套)。 技能要跟着仓库更新:删掉 `<工作目录>/skills/<技能名>` 再启动,脚本会把新版补回来(你自建的技能不受影响)。 @@ -102,6 +102,7 @@ cd agent | `PORT` | `8090` | core 端口(别撞下面的 MCP 端口) | | `NPM_REGISTRY` | 空 | 手动指定 npm 源(默认自动探测;指定后不再自动换源) | | `MCP_WEB_PORT` / `MCP_IMAGE_PORT` / `MCP_VIDEO_PORT` / `MCP_ASR_PORT` | 8091~8094 | 四个 MCP 的端口(同机跑必须各占一个;改这里还要同步改配置里的 url) | +| `PREVIEW_PORT` | `3100` | office 文档预览网关的端口(被占时自动往后找);watch 自己的端口从 26315 起 | | `AGENT_LOCAL_UI` | `auto` | 是否自动打开状态页:`auto` = 仅 macOS,`1` 强制,`0` 关闭(页面无论如何都会生成) | | `AGENT_LOCAL_DETACH` | `1` | `1` = 后台启动后立即返回(用 `stop.sh` 停);`0` = 前台阻塞(看实时日志、`Ctrl-C` 停) | | `AGENT_LOCAL_CACHE` | `~/.cache/agent-local` | 依赖缓存的存放位置(多个 clone 共享) | @@ -155,8 +156,9 @@ git pull `http://127.0.0.1:/...`,在这台机器上点得开,发给别人打不开。要对外暴露再填 `public_link.base_url`(设置页)。本地监听回环地址,模型厂商也拉不到,所以读图回传改走内联 base64(`AGENT_IMAGE_INLINE=1`,启动器已注入)。 -- **`office` 文档没有预览**:预览卡片走 core → executor 的 `:3100` 网关,本地没有这个网关, - 点开得不到可用页面;文档本身的创建/编辑/读取完全正常。 +- **`office` 预览依赖 `officecli`**:网关按需起 `officecli watch`(最多 4 个,闲置 6 小时回收)。 + 没装二进制时预览面板会直接显示安装说明,不会无限转圈。watch 只能监听 `0.0.0.0`(它没有 + `--host` 参数),同机其它用户理论上能访问那几个端口。 - **技能依赖不预装**:本地没有 `agent-executor-init`,技能自带的 `requirements.txt` 不会在启动时 自动安装。缺包时会报 `ModuleNotFoundError`,模型会把缺的包装进 `<工作目录>/skills/deps` (`AGENT_SKILLS_DEPS` 指向它,且已在该进程的 `PYTHONPATH` 里,装完下次运行即生效)。 @@ -174,6 +176,7 @@ open local/.runtime/status.html # 启动状态页:步骤、失败原因 tail -f local/.runtime/core.log # core 日志(含 prompt dump 路径、MCP 发现结果) tail -f local/.runtime/npm-install.log # 装依赖的输出 tail -f local/.runtime/mcp-asr.log # 单个 MCP 的日志 +tail -f local/.runtime/preview.log # office 预览网关(watch 启动失败的原因也在这) ``` 启动失败时状态页会自己弹出(带错误说明和日志尾部);它是个静态页,所以改完环境要自己重跑脚本 @@ -183,4 +186,5 @@ tail -f local/.runtime/mcp-asr.log # 单个 MCP 的日志 ```bash lsof -nP -iTCP:8090-8094 -sTCP:LISTEN # core + 四个 MCP 的监听情况 +lsof -nP -iTCP:3100 -sTCP:LISTEN # 预览网关(没用 office 时不存在) ``` diff --git a/local/preview-gateway.js b/local/preview-gateway.js new file mode 100644 index 0000000..271da35 --- /dev/null +++ b/local/preview-gateway.js @@ -0,0 +1,430 @@ +#!/usr/bin/env node +// local/preview-gateway.js —— 本地 office 文档预览网关(对位服务器上 executor 的 :3100)。 +// +// 为什么要有它:服务器上「点开 docx」这条链路是 core → 反代 /preview → executor 预览网关 → +// 网关自己按需 spawn `officecli watch`。本地没有 executor,那条链路会断,面板里是个空 iframe。 +// 这里用零依赖 Node 复刻网关的数据面,但不复刻它的隔离层: +// 服务器给 watch 造 pid/mount ns 牢笼、bind 挂会话 .tmp 到 /tmp,是为了让**沙箱里的命令** +// 和 watch 看见同一个世界(vendor 用 TMPDIR 下的 .port 文件 + TCP 回环发现彼此)。 +// 本地既没有沙箱,命令和 watch 本来就在同一个文件系统、同一个临时目录里, +// 那些 unshare/nsenter 不但用不上,有些平台上根本不存在。于是这里只剩四件事: +// +// 1. /preview/<会话id>/<相对路径>/ → 解析成真实文件 → 确保它有 watch → 转发 +// 2. /events(SSE)与 /api/*(选区/改内容/切换)→ 按 Referer 找归属的 watch 转发 +// 3. 槽位:最多 N 个并发 watch,挤占最久未用的,闲置回收 +// 4. 缺 officecli 时给人能看懂的一页,而不是无限转圈(服务器那份二进制是构建期必装的, +// 所以它没为「没装」设计过;本地全新 clone 一定没有,这是常态不是异常) +// +// 平台:只用 Node 内置能力,进程回收/二进制名/可执行位都按平台分支,不假设 POSIX。 +// 监听回环(默认 127.0.0.1:3100),唯一入口仍是 core 的 /preview 反代(登录门禁在那边)。 +'use strict'; +const fs = require('node:fs'); +const fsp = require('node:fs').promises; +const http = require('node:http'); +const net = require('node:net'); +const os = require('node:os'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); + +const WIN = process.platform === 'win32'; + +const HOST = process.env.OFFICE_PREVIEW_HOST || '127.0.0.1'; +const PORT = Number(process.env.OFFICE_PREVIEW_PORT || 3100); +const PREFIX = (process.env.OFFICE_PREVIEW_PREFIX || '/preview').replace(/\/+$/, ''); +const SLOTS = Math.max(1, Number(process.env.OFFICE_SLOTS || 4)); +const WATCH_BASE = Number(process.env.OFFICE_WATCH_BASE || 26315); +const WATCH_SPAN = Math.max(SLOTS, Number(process.env.OFFICE_WATCH_SPAN || 64)); +const IDLE_MS = Number(process.env.OFFICE_IDLE_MS || 6 * 3600 * 1000); +const START_TIMEOUT_MS = Number(process.env.OFFICE_START_TIMEOUT_MS || 20000); // 冷启动实测 2~6s,大文档更久 +const NAV_WAIT_MS = Number(process.env.OFFICE_NAV_WAIT_MS || 8000); // 导航请求最多等这么久,超时给中转页 +const COOLDOWN_MS = Number(process.env.OFFICE_COOLDOWN_MS || 8000); // 启动失败后短期内不再重试 + +// 会话真实目录:默认 /<会话id>;手选过工作目录的会话要问 core 拿 work_dir(本地免鉴权)。 +// tasks 根就是配置里的 workspace_root(local 形态下它等于 <工作目录>/tasks)。 +const TASKS_ROOT = path.resolve(process.env.AGENT_TASKS_ROOT || process.cwd()); +const SKILLS_ROOT = path.resolve(process.env.AGENT_SKILLS_ROOT || path.join(TASKS_ROOT, '..', 'skills')); +const REPO_ROOT = path.resolve(process.env.AGENT_REPO_ROOT || path.join(__dirname, '..')); +const RUNTIME = path.resolve(process.env.AGENT_RUNTIME || path.join(__dirname, '.runtime')); +const CORE_URL = process.env.AGENT_CORE_URL || ''; +const EXTS = new Set(['.docx', '.xlsx', '.pptx']); +const SID_RE = /^task-[0-9A-Za-z_-]+$/; + +const slots = new Map(); // 文件绝对路径 → { port, child, lastUsed, conns } +const starting = new Map(); // 文件绝对路径 → Promise:同文件并发请求合并成一次 spawn +const cooldown = new Map(); // 文件绝对路径 → 冷却截止时间戳 +const dirCache = new Map(); // 会话id → 真实目录(只缓存命中,避免会话晚建时永久失效) +let portGen = 0; + +const log = (msg) => process.stdout.write(new Date().toISOString() + ' ' + msg + '\n'); + +// ---------- 小工具 ---------- +function escapeHtml(s) { + return String(s).replace(/&/g, '&').replace(//g, '>'); +} + +// 二进制解析:每次 spawn 时才做——AI 按技能 AGENTS.md 装好之后,用户点一下刷新就该能用,不该要求重启网关。 +// 名字不一定是 officecli:官方资产叫 officecli-<平台>-<架构>[.exe],AI 很可能原样下载,所以标准名之后 +// 再认同目录里任何 officecli* 可执行文件。可执行位只在 POSIX 上有意义,且 curl 下来的资产常常是 0644, +// 这里顺手补一下(不能要求调用者先 chmod)。 +function executable(p) { + if (WIN) { + try { return fs.statSync(p).isFile(); } catch (_) { return false; } + } + try { fs.accessSync(p, fs.constants.X_OK); return true; } catch (_) {} + try { fs.chmodSync(p, 0o755); fs.accessSync(p, fs.constants.X_OK); return true; } catch (_) { return false; } +} + +function binDirs() { + return [path.join(SKILLS_ROOT, 'office', 'bin'), path.join(REPO_ROOT, 'skills', 'office', 'bin')]; +} + +function resolveBin() { + const env = String(process.env.OFFICECLI_BIN || '').trim(); + if (env && executable(env)) return env; + const std = WIN ? ['officecli.exe', 'officecli'] : ['officecli']; + const dirs = binDirs(); + for (const d of dirs) { + for (const n of std) { + const p = path.join(d, n); + if (executable(p)) return p; + } + } + for (const d of dirs) { + let list = []; + try { list = fs.readdirSync(d).sort(); } catch (_) { continue; } + for (const n of list) { + if (!/^officecli/i.test(n)) continue; + if (WIN ? !/\.exe$/i.test(n) : /\.(?:log|txt|md|zip|tar|gz|sha\d*)$/i.test(n)) continue; + const p = path.join(d, n); + if (executable(p)) return p; + } + } + return null; +} + +function portListening(port) { + return new Promise((resolve) => { + const s = net.connect({ host: '127.0.0.1', port }); + s.setTimeout(400); + s.once('connect', () => { s.destroy(); resolve(true); }); + s.once('timeout', () => { s.destroy(); resolve(false); }); + s.once('error', () => resolve(false)); + }); +} + +// watch 端口按代轮转,跳过被占用的:AI 手动起的 watch 会占着固定口,不能硬撞。 +async function allocPort() { + for (let i = 0; i < WATCH_SPAN; i++) { + const p = WATCH_BASE + ((portGen + i) % WATCH_SPAN); + if (!(await portListening(p))) { portGen = (portGen + i + 1) % WATCH_SPAN; return p; } + } + throw new Error('没有空闲的 watch 端口(' + WATCH_BASE + '~' + (WATCH_BASE + WATCH_SPAN - 1) + ')'); +} + +// 回收 watch:POSIX 上它自成进程组(detached),按组杀才不会留下占端口的子进程; +// Windows 没有进程组信号,用 taskkill /T 连子树一起收。 +function killTree(child) { + if (!child || !child.pid) return; + if (WIN) { + try { spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }); return; } catch (_) {} + } else { + try { process.kill(-child.pid, 'SIGKILL'); return; } catch (_) {} + } + try { child.kill('SIGKILL'); } catch (_) {} +} + +function killSlot(abs) { + const s = slots.get(abs); + if (!s) return; + slots.delete(abs); + killTree(s.child); +} + +function evictOne(keep) { + const list = [...slots.entries()].filter(([k]) => k !== keep).sort((a, b) => a[1].lastUsed - b[1].lastUsed); + const idle = list.filter(([, s]) => !s.conns); + const victim = (idle.length ? idle : list)[0]; + if (!victim) return; + killSlot(victim[0]); + log('挤占槽位 ' + victim[0]); +} + +function htmlPage(res, title, body, autoRefresh) { + const html = '' + + '' + escapeHtml(title) + '' + + (autoRefresh ? '' : '') + + '' + + '

' + escapeHtml(title) + '

' + body + ''; + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); + res.end(html); +} + +function installPage(res) { + const bin = path.join(SKILLS_ROOT, 'office', 'bin', WIN ? 'officecli.exe' : 'officecli'); + htmlPage(res, 'office 预览组件未安装', + '

预览需要 officecli 二进制,这台机器上还没有。

' + + '

它应该放在 ' + escapeHtml(bin) + '。

' + + '

让 AI 打开一次这个文档即可(说「用 office 打开这个文档」)——它会按技能目录里的 ' + + 'AGENTS.md 自己下载好;装完点下面的按钮刷新,不用重启服务。

' + + '

'); +} + +// ---------- 会话目录解析 ---------- +function coreGet(pathname) { + return new Promise((resolve, reject) => { + if (!CORE_URL) return reject(new Error('未配置 AGENT_CORE_URL')); + const u = new URL(CORE_URL); + const req = http.request({ host: u.hostname, port: u.port, path: pathname, method: 'GET', timeout: 3000 }, (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (c) => { body += c; }); + res.on('end', () => { + if (res.statusCode !== 200) return reject(new Error('core ' + res.statusCode)); + try { resolve(JSON.parse(body)); } catch (e) { reject(e); } + }); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(new Error('core 超时')); }); + req.end(); + }); +} + +async function sessionDir(sid) { + if (dirCache.has(sid)) return dirCache.get(sid); + const plain = path.join(TASKS_ROOT, sid); + let dir = fs.existsSync(plain) ? plain : ''; + if (!dir) { + // 手选工作目录的会话:只有 core 知道真实路径(sessions.work_dir) + try { + const row = await coreGet('/api/sessions/' + encodeURIComponent(sid) + '?limit=1'); + // 接口回的是 { session, messages, ... },work_dir 在 session 里(limit=1 只为别把整段历史拉回来) + const wd = String((row && row.session && row.session.work_dir) || ''); + if (wd && fs.existsSync(wd)) dir = wd; + } catch (_) { /* core 没起来 / 会话不存在:下面按缺失处理 */ } + } + if (dir) dirCache.set(sid, dir); + return dir; +} + +// /preview// → { sid, dir, abs };逐段解码再拼(整串解码会把 %2F 变成路径分隔符)。 +// 越界(..、绝对路径)一律当不存在。 +async function resolvePreview(rawPath) { + const rest = rawPath.slice(PREFIX.length).replace(/^\/+/, ''); + const rawSeg = rest.split('/'); + const rawSid = rawSeg.shift() || ''; + let sid; + try { sid = decodeURIComponent(rawSid); } catch (_) { return null; } + if (!SID_RE.test(sid)) return null; + let rel; + try { rel = rawSeg.map(decodeURIComponent).join('/'); } catch (_) { return null; } + const dir = await sessionDir(sid); + if (!dir) return null; + const abs = path.resolve(dir, rel.replace(/\/+$/, '')); + if (abs !== dir && !abs.startsWith(dir + path.sep)) return null; + return { sid, dir, abs }; +} + +// ---------- watch 生命周期 ---------- +async function spawnWatch(abs, dir) { + const bin = resolveBin(); + if (!bin) { + const e = new Error('缺少 officecli 二进制'); + e.code = 'MISSING_BIN'; + throw e; + } + if (slots.size >= SLOTS) evictOne(abs); + const port = await allocPort(); + try { await fsp.mkdir(RUNTIME, { recursive: true }); } catch (_) {} + const logPath = path.join(RUNTIME, 'watch-' + port + '.log'); + const fd = fs.openSync(logPath, 'a'); + const child = spawn(bin, ['watch', abs, '--port', String(port)], { + cwd: dir, + detached: !WIN, // POSIX:自成进程组便于整组回收;Windows 靠 taskkill /T + windowsHide: true, + stdio: ['ignore', fd, fd], + env: Object.assign({}, process.env, { + // 与技能封装层同一组开关:无 ICU 环境跑 .NET 不变式模式、改动即落盘、关自动 resident + DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1', + OFFICECLI_NO_AUTO_RESIDENT: '1', + OFFICECLI_RESIDENT_FLUSH: 'each', + }), + }); + try { fs.closeSync(fd); } catch (_) {} + let exited = null; + child.on('exit', (code, sig) => { exited = { code, sig }; }); + child.on('error', (e) => { exited = { code: -1, sig: String((e && e.message) || e) }; }); + + const deadline = Date.now() + START_TIMEOUT_MS; + while (Date.now() < deadline) { + if (await portListening(port)) { + const entry = { port, child, lastUsed: Date.now(), conns: 0 }; + slots.set(abs, entry); + log('起 watch ' + path.basename(abs) + ' @' + port); + return entry; + } + if (exited) break; + await new Promise((r) => setTimeout(r, 250)); + } + killTree(child); + let tail = ''; + try { tail = fs.readFileSync(logPath, 'utf8').split('\n').slice(-4).join(' | ').trim(); } catch (_) {} + const e = new Error('watch 启动失败' + (exited ? '(进程已退出)' : '(超时)') + (tail ? ':' + tail : '')); + e.code = 'START_FAILED'; + e.logPath = logPath; + throw e; +} + +async function ensureWatch(abs, dir) { + const have = slots.get(abs); + if (have) { have.lastUsed = Date.now(); return have; } + const cool = cooldown.get(abs); + if (cool && Date.now() < cool) { + const e = new Error('刚才启动失败,稍后再试'); + e.code = 'COOLDOWN'; + throw e; + } + if (starting.has(abs)) return starting.get(abs); + const p = spawnWatch(abs, dir).then( + (entry) => { starting.delete(abs); cooldown.delete(abs); return entry; }, + (err) => { + starting.delete(abs); + cooldown.set(abs, Date.now() + COOLDOWN_MS); + log('watch 启动失败 ' + abs + ':' + err.message); + throw err; + }, + ); + starting.set(abs, p); + return p; +} + +// ---------- 转发 ---------- +const PASS_HEADERS = new Set(['accept', 'accept-encoding', 'cache-control', 'pragma', 'content-type', + 'content-length', 'if-modified-since', 'if-none-match', 'last-event-id', 'referer', 'user-agent']); + +function forward(port, req, res, outPath) { + const headers = {}; + for (const k of Object.keys(req.headers)) if (PASS_HEADERS.has(k)) headers[k] = req.headers[k]; + // watch 的同源校验只认回环:从别的名字(host 名解析到 127.0.0.1)打开 core 时会被 403。 + // 网关本身只监听回环、可达即本机,这里把 Origin 归一成上游自己的地址。 + if (req.headers.origin) headers.origin = 'http://127.0.0.1:' + port; + + const upstream = http.request({ host: '127.0.0.1', port, path: outPath, method: req.method, headers }, (up) => { + const h = Object.assign({}, up.headers); + delete h.connection; delete h['keep-alive']; + if (String(h['content-type'] || '').includes('text/event-stream')) { + h['cache-control'] = 'no-cache'; + h['x-accel-buffering'] = 'no'; + } + res.writeHead(up.statusCode || 502, h); + up.pipe(res); + }); + upstream.on('error', () => { + if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }).end('预览服务不可达'); + else res.destroy(); + }); + req.pipe(upstream); +} + +function notFound(res) { + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); + res.end('预览不存在'); +} + +// 数据请求(SSE / api):按 Referer 认领,和 core 反代那段兜底同一套信任模型。 +function refererPath(req) { + const ref = req.headers.referer || req.headers.referrer || ''; + if (!ref) return null; + try { + const p = new URL(ref).pathname; // 不解码:下面按段解,避免 %2F 被当成分隔符 + return p === PREFIX || p.startsWith(PREFIX + '/') ? p : null; + } catch (_) { return null; } +} + +const server = http.createServer((req, res) => { + (async () => { + let rawPath; + try { rawPath = new URL(req.url, 'http://127.0.0.1').pathname; } catch (_) { return notFound(res); } + + // ---- 预览入口 ---- + if (rawPath === PREFIX || rawPath.startsWith(PREFIX + '/')) { + const target = await resolvePreview(rawPath); + if (!target) return notFound(res); + if (!EXTS.has(path.extname(target.abs).toLowerCase())) return notFound(res); + let exists = true; + try { await fsp.access(target.abs); } catch (_) { exists = false; } + // HEAD 是面板的探针(判断「这份文档在不在」),立刻回,不陪着等冷启动。 + if (req.method === 'HEAD') { + if (exists) ensureWatch(target.abs, target.dir).catch(() => {}); + res.writeHead(exists ? 200 : 404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'content-length': '0' }); + return res.end(); + } + if (!exists) return notFound(res); + if (!resolveBin()) return installPage(res); + + let entry = null; + try { + entry = await Promise.race([ + ensureWatch(target.abs, target.dir), + new Promise((r) => setTimeout(() => r(null), NAV_WAIT_MS)), + ]); + } catch (e) { + // 启动失败:给人能看懂的一页(附日志位置),别让面板停在转圈上 + return htmlPage(res, '预览启动失败', + '

' + escapeHtml(e.message) + '

' + + (e.logPath ? '

日志:' + escapeHtml(e.logPath) + '

' : '') + + '

稍后点刷新即可重试。

', + Math.ceil(COOLDOWN_MS / 1000)); + } + if (!entry) { + // 冷启动还没完:给中转页自动刷新,别让 iframe 白屏干等 + return htmlPage(res, '正在准备预览…', '

首次打开需要启动预览进程(大文档要几秒)。

', 1); + } + entry.lastUsed = Date.now(); + return forward(entry.port, req, res, rawPath.slice(PREFIX.length) || '/'); + } + + // ---- 页内数据面:/events(SSE)与 /api/* 都是根绝对路径 ---- + if (rawPath === '/events' || rawPath.startsWith('/api/')) { + const refPath = refererPath(req); + if (!refPath) return notFound(res); + const target = await resolvePreview(refPath); + if (!target) return notFound(res); + const entry = slots.get(target.abs); + if (!entry) return notFound(res); // 槽位已被回收:页面下次导航会重新起 + entry.lastUsed = Date.now(); + return forward(entry.port, req, res, req.url); + } + + return notFound(res); + })().catch((e) => { + log('请求失败 ' + req.url + ':' + (e && e.message)); + if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('预览网关内部错误'); + }); +}); + +// 闲置回收:watch 是常驻进程,不回收会一直占着内存与端口(服务器那份是 6h) +const timer = setInterval(() => { + const now = Date.now(); + for (const [abs, s] of [...slots.entries()]) { + if (!s.conns && now - s.lastUsed > IDLE_MS) { killSlot(abs); log('回收闲置 watch ' + path.basename(abs)); } + } +}, 60000); +timer.unref(); + +function shutdown() { + for (const abs of [...slots.keys()]) killSlot(abs); + process.exit(0); +} +process.on('SIGTERM', shutdown); +process.on('SIGINT', shutdown); +// 退出/崩溃时别把 spawn 出去的 watch 养成孤儿 +process.on('exit', () => { for (const abs of [...slots.keys()]) killSlot(abs); }); +process.on('unhandledRejection', (e) => log('未处理的 Promise 拒绝:' + (e && e.message))); + +server.listen(PORT, HOST, () => { + log('预览网关 listening ' + HOST + ':' + PORT + ' prefix=' + PREFIX + '/' + + ' tasks=' + TASKS_ROOT + ' skills=' + SKILLS_ROOT + ' slots=' + SLOTS); +}); diff --git a/local/start.sh b/local/start.sh index 7aad70e..3b478c2 100755 --- a/local/start.sh +++ b/local/start.sh @@ -795,7 +795,7 @@ kill_tree_hard() { do_cleanup() { # 心跳子进程也得收掉,不然退出后它会继续每秒重绘页面。 ui_stop_ticker - rm -f "$RUNTIME/ui/busy" "$RUNTIME/supervisor.pid" + rm -f "$RUNTIME/ui/busy" "$RUNTIME/supervisor.pid" "$RUNTIME/preview.port" for p in $CORE_PID $MCP_PIDS; do kill_tree "$p"; done CORE_PID='' MCP_PIDS='' @@ -843,6 +843,34 @@ check_mcp() { fi } +# ---------- 预览网关:office 文档的 iframe 预览 ---------- +# 服务器上这条链是 core → 反代 /preview → executor 的 :3100 预览网关;本地没有 executor, +# 由 local/preview-gateway.js 顶上:收到预览请求就按需起 `officecli watch`,再转发页面与 SSE。 +# 端口默认 3100(与服务器一致),被占就往后找几个:本机可能已经有别的服务占着 3100。 +pick_preview_port() { + p="${PREVIEW_PORT:-3100}" + i=0 + while [ "$i" -lt 10 ]; do + port_open "$p" || { printf '%s' "$p"; return 0; } + p=$((p + 1)); i=$((i + 1)) + done + return 1 +} + +start_preview() { + printf '%s\n' "$PREVIEW_PORT" > "$RUNTIME/preview.port" + ( cd "$ROOT" && exec env \ + OFFICE_PREVIEW_HOST="$HOST_ADDR" \ + OFFICE_PREVIEW_PORT="$PREVIEW_PORT" \ + AGENT_TASKS_ROOT="$TASKS_DIR" \ + AGENT_SKILLS_ROOT="$SKILLS_DIR" \ + AGENT_REPO_ROOT="$ROOT" \ + AGENT_CORE_URL="http://$HOST_ADDR:$PORT" \ + AGENT_RUNTIME="$RUNTIME" \ + node local/preview-gateway.js >>"$RUNTIME/preview.log" 2>&1 ) & + MCP_PIDS="$MCP_PIDS $!" +} + start_core() { # PYTHONPATH 把技能依赖层 <工作目录>/skills/deps 放进 python 搜索路径(与服务器上 executor 容器 # 的 PYTHONPATH 对齐,那边由 compose 注入)。本地没有 agent-executor-init 替我们装包, @@ -860,6 +888,7 @@ start_core() { ASR_URL="$ASR_URL" \ PYTHONPATH="$SKILLS_DIR/deps" \ AGENT_SKILLS_DEPS="$SKILLS_DIR/deps" \ + PREVIEW_PROXIES="[{\"name\":\"office\",\"prefix\":\"/preview\",\"host\":\"$HOST_ADDR\",\"port\":${PREVIEW_PORT:-3100}}]" \ node server/server.js >>"$LOG" 2>&1 ) & CORE_PID=$! } @@ -998,6 +1027,19 @@ else ui_step '技能目录不可用(检查配置里的 skills_root)' warn fi +# 会话工作区:配置里的 workspace_root(local 形态 = <工作目录>/tasks);给预览网关解析会话目录用。 +TASKS_DIR=$(cfg_get workspace_root) +[ -n "$TASKS_DIR" ] || TASKS_DIR="$(dirname "$SKILLS_DIR")/tasks" + +if PREVIEW_PORT=$(pick_preview_port); then + start_preview + ui_step "预览网关:$HOST_ADDR:$PREVIEW_PORT(office 文档)" ok +else + PREVIEW_PORT='' + warn '找不到空闲的预览端口(3100-3109),office 文档的预览将不可用' + ui_step '预览网关未启动(3100-3109 都被占用)' warn +fi + # 语音:ffmpeg 在就启用,两条线都靠同一个开关: # ASR_URL 注入 → core 才挂 /api/asr、前端才显示麦克风 # mcp_asr 子进程 → 模型的 transcribe_audio 工具(它转码依赖 ffmpeg,没有就没意义) @@ -1044,6 +1086,10 @@ while :; do check_mcp "$MCP_IMAGE_PORT" image check_mcp "$MCP_VIDEO_PORT" video [ "$FF_OK" = 1 ] && check_mcp "$MCP_ASR_PORT" asr + # 预览网关挂了不会影响别的功能,但它静默失败时用户只会看到空白预览,所以点名。 + if [ -n "${PREVIEW_PORT:-}" ] && ! port_open "$PREVIEW_PORT"; then + warn "预览网关没起来(端口 $PREVIEW_PORT)——日志:local/.runtime/preview.log" + fi if [ "$FIRST_RUN" = 1 ]; then # 首次安装:停在状态页,给一个按钮让用户自己点(先看完「首次使用」提示再进去)。 ui_done "http://${HOST_ADDR}:${PORT}" click diff --git a/local/stop.sh b/local/stop.sh index a19edc9..6a15bd2 100755 --- a/local/stop.sh +++ b/local/stop.sh @@ -17,6 +17,9 @@ PIDFILE="$RUNTIME/supervisor.pid" PORT="${PORT:-8090}" # 与 start.sh 的默认值一致;用 MCP_*_PORT 改过端口时这里也要跟着改(否则兜底那步找不到它们)。 MCP_PORTS="${MCP_WEB_PORT:-8091} ${MCP_IMAGE_PORT:-8092} ${MCP_VIDEO_PORT:-8093} ${MCP_ASR_PORT:-8094}" +# 预览网关端口是启动时从 3100 往后找的第一个空闲口,只能读它写下的记录。 +pv_port=$(cat "$RUNTIME/preview.port" 2>/dev/null || printf '') +case "$pv_port" in ''|*[!0-9]*) pv_port='3100';; esac stopped=0 @@ -81,7 +84,7 @@ if [ "$stopped" = 0 ]; then fi # 3) 兜底:还占着端口的直接收(启动器已经死了,剩下的都是孤儿)。 -for p in "$PORT" $MCP_PORTS; do +for p in "$PORT" $MCP_PORTS "$pv_port"; do for pid in $(pids_on_port "$p"); do stop_pid "$pid" "端口 $p 上的进程" done @@ -89,7 +92,7 @@ done [ "$stopped" = 1 ] && sleep 2 # 4) 收尾:仍占着端口的强制结束,避免下次启动被判「端口被占用」。 -for p in "$PORT" $MCP_PORTS; do +for p in "$PORT" $MCP_PORTS "$pv_port"; do for pid in $(pids_on_port "$p"); do kill -KILL "$pid" 2>/dev/null || true done @@ -98,5 +101,5 @@ done if [ "$stopped" = 1 ]; then say '已停止' else - say "没有在运行($PORT 与 MCP 端口 $MCP_PORTS 都空闲)" + say "没有在运行($PORT、MCP 端口 $MCP_PORTS、预览端口 $pv_port 都空闲)" fi diff --git a/skills/office/SKILL.md b/skills/office/SKILL.md index 285584b..30a908f 100644 --- a/skills/office/SKILL.md +++ b/skills/office/SKILL.md @@ -31,9 +31,6 @@ office [args...] create/open 成功后,用户可自行查看该文档的实时预览(预览页上的选区、标注类交互之后都能被 get-pos 读到)。用户反馈"看第几段/选中了哪里/修改哪里"时,优先用 get-pos 读回选区再针对性改。 -本地直跑没有预览卡片时,用 `office watch ` 起自带预览页(立即返回本机地址), -`office unwatch ` 停。 - ## 注意 - 所有操作文档在任务目录里。 diff --git a/skills/office/scripts/office b/skills/office/scripts/office index 46ad1f4..00c1191 100755 --- a/skills/office/scripts/office +++ b/skills/office/scripts/office @@ -2,28 +2,22 @@ // office: officecli 的封装层(技能唯一入口)。 // - 二进制不进 PATH、SKILL.md 不提及:可见面 = 可调用面,模型只认识本脚本;路径可用 OFFICECLI_BIN 覆盖。 // - 命令治理移植自原 MCP 桥:隐去命令报原生风格 unrecognized;view 渲染族拦截给替代路径; -// watch 族在服务器形态不透传(预览由平台网关托管),本地直跑放行(见 LOCAL 分支)。 +// watch 族不透传(预览由平台托管)。 // - create/open 成功在 stdout 尾行发 ui_card marker(::ui_card {json}::):core 剥离后转聊天流卡片, -// 模型面不感知 marker;arg 为相对 cwd(会话目录)的文件路径。本地没有预览网关,不发卡片。 +// 模型面不感知 marker;arg 为相对 cwd(会话目录)的文件路径。 'use strict'; -const { spawn, spawnSync } = require('node:child_process'); +const { spawnSync } = require('node:child_process'); const path = require('node:path'); const http = require('node:http'); -const fs = require('node:fs'); -const net = require('node:net'); -const os = require('node:os'); const BIN = process.env.OFFICECLI_BIN || path.resolve(__dirname, '..', 'bin', 'officecli'); -// 本地直跑(local/start.sh 注入):没有 executor,也没有 /preview 网关, -// 预览卡片必然是死链、__pv-touch 打不通,watch 也就没有平台托管可言。 -const LOCAL = process.env.AGENT_LOCAL_PICK === '1'; // 本部署不合适的命令(自锁死 / 装配环境族):原生风格报错,help 清单同步删行(见 help 段)。 const unrecognized = (v) => "Unrecognized command or argument '" + v + "'."; const HIDDEN_TOP = /^(mcp|skills|install|plugins)(?:\s|$)/; const HIDDEN_LINE = /^ {2}(?:mcp|skills|install|plugins)\b/; // '\b' 绝不能用字符串拼 RegExp(会变退格符) const HELP_STRIP = /^ {2}(?:watch|unwatch)\b/; -const HIDDEN_SUBS = new Set(['mark', 'unmark', 'marks', 'goto']); // 标注/滚动族:预览交互由 get-pos 单点覆盖(本地有真实 watch,放行) +const HIDDEN_SUBS = new Set(['mark', 'unmark', 'marks', 'goto']); // 标注/滚动族:预览交互由 get-pos 单点覆盖 const VIEW_BLOCKED = new Set(['html', 'screenshot', 'svg', 'pdf', 'forms']); // 需无头浏览器/导出插件,本环境没有 const OFFICE_EXT_RE = /\.(?:docx|xlsx|pptx)$/i; const EDIT_RE = /^(set|add|remove|move|swap|raw-set|add-part|batch|import|merge|refresh)$/; @@ -66,8 +60,8 @@ const first = String(argv[0] || ''); // ---------- 命令面闸门 ---------- let m = HIDDEN_TOP.exec(cmd); if (m || (first === 'help' && HIDDEN_TOP.test(argv.slice(1).join(' ')))) err(unrecognized(m ? m[1] : argv[1])); -if (!LOCAL && HIDDEN_SUBS.has(first)) err(unrecognized(first)); -if (!LOCAL && (first === 'watch' || first === 'unwatch')) { +if (HIDDEN_SUBS.has(first)) err(unrecognized(first)); +if (first === 'watch' || first === 'unwatch') { err('Preview slots are managed by the platform: create/open a document, then click the preview card in the chat.'); } @@ -89,63 +83,6 @@ if (first === 'get-pos') { argv = ['get', file, 'selected', '--json']; } -// watch:原生是常驻 HTTP 预览服务,前台透传会一直阻塞到 terminal 超时。 -// 本地改成后台拉起 → 等端口就绪 → 报地址 → 立刻退出,预览页留在后台刷新(编辑通知走原生管道,同机可用)。 -function startWatch() { - const file = argv[1]; - if (!file) err('Usage: watch [--port ]'); - let port = 26315; - for (let i = 2; i < argv.length; i++) { - const a = String(argv[i]); - if (a === '--port') { port = Number(argv[i + 1]); break; } - if (a.startsWith('--port=')) { port = Number(a.slice(7)); break; } - } - if (!Number.isInteger(port) || port <= 0 || port > 65535) err('watch: --port 需要合法端口号'); - const url = 'http://127.0.0.1:' + port + '/'; - const report = () => { - process.stdout.write('预览地址:' + url + '\n停止预览:unwatch ' + file + '\n'); - process.exit(0); - }; - const probe = (cb) => { - const s = net.connect({ host: '127.0.0.1', port }); - s.setTimeout(300); - s.once('connect', () => { s.destroy(); cb(true); }); - s.once('timeout', () => { s.destroy(); cb(false); }); - s.once('error', () => cb(false)); - }; - probe((up) => { - if (up) return report(); - const logf = path.join(os.tmpdir(), 'officecli-watch-' + port + '.log'); - let fd; - try { fd = fs.openSync(logf, 'a'); } catch (e) { err('watch: 无法写日志 ' + logf + ': ' + (e && e.message || e)); } - const child = spawn(BIN, argv, { - cwd: process.cwd(), env: vendorEnv(), detached: true, stdio: ['ignore', fd, fd], - }); - try { fs.closeSync(fd); } catch (_) {} - child.on('error', (e) => { err('watch 启动失败:' + (e && e.message || e)); }); - child.unref(); - let tries = 0; - const tick = () => { - probe((ok) => { - if (ok) return report(); - if (++tries > 50) { - let tail = ''; - try { tail = fs.readFileSync(logf, 'utf8').split('\n').slice(-5).join('\n').trim(); } catch (_) {} - err('watch 未能在 5s 内就绪;日志:' + logf + (tail ? '\n' + tail : '')); - } - setTimeout(tick, 100); - }); - }; - setTimeout(tick, 100); - }); -} - -if (LOCAL && first === 'watch' && !helpCmd && !(argv[2] && HIDDEN_SUBS.has(String(argv[2])))) { - startWatch(); - // 不能落到下面的同步透传:spawnSync 会堵住事件循环,端口就绪的回调就再也跑不到 - return; -} - // ---------- 透传 ---------- let r; try { @@ -155,8 +92,7 @@ try { } if (r.error) { if (r.error.code === 'ENOENT') { - err('office.core binary missing: ' + BIN + '\nLocal env: ' + path.resolve(__dirname, '..', 'AGENTS.md') - + ' (server: docker compose up -d agent-executor-init)'); + err('office.core binary missing: ' + BIN + ' (install per ' + path.resolve(__dirname, '..', 'AGENTS.md') + ')'); } err(String(r.error.message || r.error)); } @@ -164,14 +100,13 @@ if (r.error) { let outRaw = scrub(r.stdout || ''); // help 文本对齐可调用面:隐去的命令删行(原生 cwd 已是会话目录,无扩展命令需补录) if (helpCmd && outRaw.includes('Commands:')) { - outRaw = outRaw.split('\n') - .filter((ln) => !HIDDEN_LINE.test(ln) && (LOCAL || !HELP_STRIP.test(ln))).join('\n'); + outRaw = outRaw.split('\n').filter((ln) => !HIDDEN_LINE.test(ln) && !HELP_STRIP.test(ln)).join('\n'); } if (outRaw) process.stdout.write(outRaw); if (r.stderr) process.stderr.write(scrub(r.stderr || '')); // create/open 成功尾行发预览卡片 marker(core 解析后剥离;模型面无感) -if (r.status === 0 && !LOCAL && /^(create|open)$/.test(first)) { +if (r.status === 0 && /^(create|open)$/.test(first)) { let file = null; for (const t of argv) { const s = String(t); @@ -194,7 +129,7 @@ if (r.status === 0 && !LOCAL && /^(create|open)$/.test(first)) { // 网关命中活槽位后 POST watch /api/switch 就地重读,页面靠 vendor 自带的 doc-switched 监听自刷。 // fire-and-forget:800ms 封顶,一切失败静默——预览永远不是命令成功的前提。 const CODE = r.status === null ? 1 : r.status; -if (CODE === 0 && !LOCAL && !process.env.OFFICE_JAIL && EDIT_RE.test(first) && argv[1]) { +if (CODE === 0 && !process.env.OFFICE_JAIL && EDIT_RE.test(first) && argv[1]) { let done = false; const finish = () => { if (done) return; done = true; process.exit(CODE); }; try {