From ad19c5d61eb9dd0139e1d284a79cbbdb0d32e10a Mon Sep 17 00:00:00 2001 From: corolin Date: Mon, 23 Nov 2026 13:09:59 +0800 Subject: [PATCH] Prepare Filaxis 0.2.9 with MCP stream output and file tools --- AGENTS.md | 2 +- CHANGELOG.md | 7 ++ README.en.md | 8 +- README.md | 8 +- bin/filaxis.ts | 3 +- docs/skills/SKILL.en.md | 51 +++++------ docs/skills/SKILL.md | 49 +++++----- docs/skills/file-sync.md | 21 ++++- docs/skills/stream-window.md | 1 + package.json | 2 +- src/agent-toolkit.ts | 152 +++++++++++++++++++++++++------ src/file-edit.ts | 36 ++++++-- src/local-driver.ts | 9 ++ src/mcp-server.ts | 99 +++++++++++++++++++-- src/runtime-stack.ts | 22 ++--- src/ssh-pty-driver.ts | 2 +- src/tmux-driver.ts | 2 +- tests/agent-toolkit.test.ts | 57 +++++++++++- tests/file-edit.test.ts | 12 ++- tests/integration-ssh.test.ts | 9 ++ tests/mcp-server.test.ts | 162 +++++++++++++++++++++++++++++++++- 21 files changed, 585 insertions(+), 129 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 91d170f..8ecd3ce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,7 @@ 5. **通道语义**:缺省 `channel:"exec"`(stdout/stderr 分离、**层上下文拼装**——层的 cwd/env/enter 进入管线〔`docker exec`/`ssh` 形态〕在独立通道自动非交互重放,exec 直达层内环境);`channel:"pty"` 继承层内交互状态(su/cd),但 **stderr 混流是终端物理语义**,不是 bug。多跳 PTY 链与交互式二次跳转对 exec 通道**显式拒绝**——这是诚实行为,换 pty 或把途径机收敛为 `-J`。`-J`/`--host` 传 ssh-config **别名**时,别名解析用的是**本运行环境**的 `~/.ssh/config`——沙箱/远端会话里可能没有该条目(连接层报错会带此提示),跨环境请用 `user@host[:port]` 字面量。`jump` 只支持**单跳**(结构化 `SshJumpSpec` 正门/字符串白名单解析——跳板参数会拼进经 shell 执行的 ProxyCommand,白名单外字符直接拒绝);多跳逗号链显式拒绝,多跳正门是层模型 `sshInto` 逐跳派生。 6. **跨流顺序**:双文件落盘后的聚合序是**本地到达序**(近似),不承诺进程真实写入序。 7. **方言适配自动进行**:base64/sha256 按连接探测缓存(OPNsense/Alpine 形态已测)——但你自己的远端脚本原语若依赖 GNU 方言,请同样探测,勿硬编码。 -8. **CAS 校验 ≠ 写入原子性(两轴正交,看 `writeMode` 字段)**:受控编辑/传输缺省 tmp+mv 原子替换(`atomic-replace`);**Docker 单文件 bind mount 挂载点 mv 不可用**(EBUSY/EXDEV)——自动降级保留 inode 写入(`inplace-write`):写入中断可能暴露半截文件,消费方须知。已知挂载环境可显式传 `writeMode:"inplace"` 跳过失败尝试。`mutex`(锁保护)与 `verification`(校验等级)同理都是独立轴——别把四个保证混读成一个「成功」。 +8. **CAS(Compare-and-Swap,比较后写回)**。受控编辑读取 UTF-8 文件及其版本信息,按字面匹配替换片段,然后在写回前比对文件的修改时间、大小和内容指纹。发现文件版本变化时拒绝写回。分别查看 `mutex`(锁保护)与 `writeMode`(写入方式):`atomic-replace` 通过临时文件替换目标,`inplace-write` 保留 inode,中断可能留下部分内容。Docker 单文件 bind mount 可自动降级为原地写入,已知挂载点也可显式传 `writeMode:"inplace"`。大文件回退路径前后核验,并报告 `mutex:"degraded"` 和 `writeMode:"inplace-write"`。文件传输另用 `verification` 报告传输校验等级。 9. **PTY 键入大数据的边界(依赖面声明)**:canonical 行规程的 4096 在 Linux 实测是 **read 分段线而非丢弃线**(无 readline 的 sh 层 + 消费者忙/闲双场景、单行 16K 均完整——缓冲满时 master 写入被流控阻塞退避不丢;回归已钉住,退化即红)。但这**不是跨平台统一保证**(BSD 规程/老内核行为无承诺);传输数据一律经 b64 中继(字母表对行规程/ICRNL/INTR/EOF 结构免疫,控制字符回归锁定)。非 Linux 环境 tmux 层传超大单行前先小载荷探路。 ## 环境规格与漂移 diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d681d2..2185109 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ --- +## 0.2.9 + +- MCP 新增 `list_directory`、`set_active_layer` 和非递归的 `delete_file`。 +- `read_stream` 的 MCP 文本块显示日志帧和相应游标。后台会话与观察窗的选择条件移到工具描述首句。 +- 命令和受控编辑拒绝无效目标参数,避免误用默认层。批量 `push_ssh` 返回前核对连接句柄,报告建连期间被移除或替换的层。 +- 中英文 Skill 将任务选型放在入口,并解释 Compare-and-Swap(CAS)的写前检查、锁保护和写入方式。 + ## 0.2.8 - MCP 和 Agent Toolkit 的 `push_ssh` 可按目标或 SSH 配置别名列表批量建立命名层,逐目标报告新建、复用或连接失败,并返回可用于 `run_batch.layer` 的实际层名。 diff --git a/README.en.md b/README.en.md index 1ba9f26..ef44055 100644 --- a/README.en.md +++ b/README.en.md @@ -46,7 +46,7 @@ if (stop.status === "unknown") { | Long-running sessions | `execSession` returns immediately. Output is recorded in separate `.out` and `.err` files and is available through a recent-output buffer, line watchers, and readiness checks. | | Streaming observation | A separate SSH channel streams live output. It can share the SSH master connection through ControlMaster where available. | | Persistent sessions | The tmux backend can reattach across processes by `terminalId` and restore the working directory. | -| File transfer and editing | `putFile` and `getFile` verify size and, when available, SHA-256 with support for GNU, BSD, and BusyBox tools. `editFile` performs compare-and-swap edits and reports the write mode, lock protection, and verification level. | +| File transfer and editing | `putFile` and `getFile` report the verification level, using size and SHA-256 when available. `editFile` uses compare-and-swap (CAS) to check the file version before writing, and reports the lock protection and write mode. | | Environment discovery | Discover installed tools and GPU capabilities, select suitable layers with `matchLayers({ needs })`, and flag saved results when fingerprints drift. | | Connection management | Reuse connections by topology fingerprint. Filaxis reconnects with backoff and tracks degraded layers. | | SSH host verification | Trust on first use by default, with explicit strict mode and a configurable `known_hosts` file. The SDK accepts private-key paths. | @@ -86,12 +86,12 @@ Or launch it directly with `npx` in your MCP client configuration: } ``` -Exposed MCP tools (15 tools): +Exposed MCP tools (18 tools): - **Execution & batching**: `run_command`, `run_batch` - **Long-running sessions & observation windows**: `spawn_and_observe`, `stop_and_verify`, `observe_stream`, `read_stream`, `close_stream` -- **File operations & transfers**: `read_file`, `edit_file`, `put_file`, `get_file` -- **Layer management**: `push_ssh`, `push_into`, `list_layers`, `remove_layer` +- **Files and directories**: `list_directory`, `read_file`, `edit_file`, `put_file`, `get_file`, `delete_file` +- **Layer management**: `push_ssh`, `push_into`, `list_layers`, `set_active_layer`, `remove_layer` The npm package includes the [English agent skill](./docs/skills/SKILL.en.md), [four playbooks](./docs/skills/), and the [runtime contract](./AGENTS.md). Register the skill according to your agent's conventions. diff --git a/README.md b/README.md index 9ca97db..5166f6a 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ stack.events.on("exit", (e) => console.log("session", e.sessionId, "exit", e.exi | 观察流 | 内置 | 独立 SSH channel 真流式直推(无轮询);ControlMaster 复用;注意力衰减回收 | | 持久会话 | 内置 | tmux 后端 terminalId 跨进程 re-attach + cwd 恢复 | | 文件传输 | 内置 | `putFile/getFile` base64 管道分块 + size/sha256 双校验 + **方言适配**(GNU/BSD/busybox——OPNsense/Alpine 不再必错) | -| 受控编辑 | 内置 | `editFile` CAS 原子写回(写入形态/锁保护/校验等级三轴显式报告,见 AGENTS.md 第 8 条) | +| 受控编辑 | 内置 | `editFile` 用 Compare-and-Swap(CAS)在写回前核对文件版本。结果分别报告锁保护和写入方式,详见 AGENTS.md 第 8 条。 | | 环境规格 | 内置 | 两段式自发现(语言/GPU/关键包)蒸馏落盘;`matchLayers({needs})` 按需选层;指纹漂移标 stale | | 连接治理 | 内置 | 连接拓扑指纹复用(同拓扑零重建);3 次退避自动重连;层状态机与退化哨兵 | | 安全边界 | 内置 | host key 策略显式(tofu 缺省/strict+known_hosts);凭据只传路径永不外泄;渲染永不含密钥内容 | @@ -87,12 +87,12 @@ filaxis mcp-config --format toml # TOML,使用 mcp_servers(Codex) } ``` -暴露的 15 个 MCP 工具速览: +暴露的 18 个 MCP 工具速览: - **命令与批处理**:`run_command`、`run_batch` - **长跑会话与观察窗**:`spawn_and_observe`、`stop_and_verify`、`observe_stream`、`read_stream`、`close_stream` -- **文件读写与传输**:`read_file`、`edit_file`、`put_file`、`get_file` -- **多层连接管理**:`push_ssh`、`push_into`、`list_layers`、`remove_layer` +- **文件与目录**:`list_directory`、`read_file`、`edit_file`、`put_file`、`get_file`、`delete_file` +- **多层连接管理**:`push_ssh`、`push_into`、`list_layers`、`set_active_layer`、`remove_layer` npm 包包含 [Skill 入口与四份子剧本](docs/skills/SKILL.md),以及配套的 [AGENTS.md](AGENTS.md)。需要登记 Skill 时,由 Agent 按自身平台的规则处理这些文件。 diff --git a/bin/filaxis.ts b/bin/filaxis.ts index 5d18ac5..40a6acd 100644 --- a/bin/filaxis.ts +++ b/bin/filaxis.ts @@ -571,7 +571,8 @@ async function main() { } catch (e) { throw new Error(`JSON 载荷解析失败(${o.requestFile ?? "stdin"}): ${(e as Error).message}`); } - if (typeof req.old !== "string" || typeof req.new !== "string") { + if (!req || typeof req.old !== "string" || typeof req.new !== "string" + || (req.all !== undefined && typeof req.all !== "boolean")) { throw new Error('JSON 载荷需含字符串字段 "old" 与 "new"(可选 "all": boolean)'); } old = req.old; diff --git a/docs/skills/SKILL.en.md b/docs/skills/SKILL.en.md index 3eca3eb..484ffb1 100644 --- a/docs/skills/SKILL.en.md +++ b/docs/skills/SKILL.en.md @@ -1,17 +1,10 @@ --- name: filaxis-runtime -version: 0.2.8 +metadata: + version: "0.2.9" description: | - Entry skill guide for the Filaxis remote execution runtime (@syrkos/filaxis) — 30-second execution mode selector, MCP/CLI/SDK recipes, and core execution contracts for reliable SSH, Docker, and multi-hop agent operations. - - Read before starting: - - Any cross-layer or remote command execution, log observation, background session, file edit/transfer, or multi-host troubleshooting task - - Interpreting `unknown` termination outcomes or 3-axis file-write guarantees (`mutex`, `writeMode`, `verification`) - - Diagnosing connection failures (SSH config aliases, jump hosts, or no-ProxyJump bastion traversal) - - Skip when: - - Running simple local one-off commands directly in the host shell - - Working on tasks unrelated to remote execution or Filaxis + Use Filaxis (@syrkos/filaxis) to run commands across layers, batch inspections, manage background jobs, follow logs, or operate on files. + Also use it to diagnose SSH aliases and jump hosts or interpret unknown outcomes and write guarantees. Skip for simple local shell commands and tasks unrelated to Filaxis. --- # Filaxis Agent Skill — Quick Start & Runtime Guide @@ -26,7 +19,21 @@ description: | --- -## 10-Second Start: Copy-Paste CLI Recipes (Do Not Read Source Code First) +## Choose an entry point + +Match the task to an entry point and read the relevant playbook. After execution, check the exit code, readiness marker, or file result. Verify an unknown outcome before deciding whether to retry. + +| Task | MCP tool or reference | +|---|---| +| Wait for one finite command and collect its exit code | `run_command` | +| Batch inspections or apply dependencies across layers | `run_batch`. For bastions or multi-host investigation, read [Cross-host diagnosis](./cross-host-diagnosis.md) | +| Start a background service, wait for readiness, or verify its exit code | `spawn_and_observe` → `stop_and_verify`. Read [Long-running jobs](./longrun-observe.md) | +| Follow logs with a cursor and close the view when finished | `observe_stream` → `read_stream` → `close_stream`. Read [Observation windows](./stream-window.md) | +| List a directory, read, edit, transfer, or delete a file | `list_directory`, `read_file`, `edit_file`, `put_file`, `get_file`, `delete_file`. Read [File operations](./file-sync.md) | +| Switch back to an existing layer as the default | Find its name with `list_layers` and call `set_active_layer`. Pass `layer` for a one-call override | +| Observe a command for a limited interval in the CLI | `filaxis observe` | + +## CLI quick start > Reading package source files upfront wastes hundreds of thousands of tokens. Use these recipes directly: @@ -94,7 +101,7 @@ const ctr = await stack.layerInto("prod", "web", "docker exec -i nginx sh"); const res = await host.driver.exec("uptime", { timeoutMs: 10_000 }); console.log(res.exitCode, res.stdout, res.stderr); -// 3. Controlled CAS edit (pass writeMode: "inplace" for Docker single-file bind mounts) +// 3. Controlled edit with a pre-write version check (writeMode: "inplace" for single-file bind mounts) const ed = await editFile(ctr.driver, "/etc/nginx/nginx.conf", "worker_processes 1;", "worker_processes auto;", { writeMode: "auto", }); @@ -122,22 +129,6 @@ await stack.removeLayer("prod", { destroy: true }); --- -## 30-Second Decision Tree - -``` -Will the command exit on its own? -├─ Yes (one-off: curl / nginx -t / systemctl status) ──→ run_command / exec (exit code is data) -├─ No (tail -f / top / long-running daemon / training) -│ ├─ Quick time-bounded snapshot ───────────────────→ CLI observe (default 8s snapshot) -│ ├─ Wait for ready marker / error pattern & verify exit → spawn_and_observe + stop_and_verify -│ └─ Live non-destructive stream cursor / paging ───→ observe_stream → read_stream → close_stream -└─ Modifying or moving remote files - ├─ Text config / code edits ──────────────────────→ edit_file (CAS + lock + writeMode) - └─ Binary or full-file transfers ─────────────────→ put_file / get_file (or run_batch) -``` - ---- - ## Core Execution Contracts (Never Violate These) | Contract | Rule | @@ -146,7 +137,7 @@ Will the command exit on its own? | **Exit code is data** | Nonzero command exit codes do **not** throw in `exec` / `run_command`. Only execution failures (timeout, abort, dead transport) reject or error. | | **Completion sentinel required** | Missing completion markers (disconnect, remote kill, local abort) produce `outcome: "unknown"` — never fabricate exit code `0` and never blindly replay non-idempotent commands. | | **No never-ending commands in `exec`** | `exec` / `run_command` waits for completion — `tail -f` or `top` will time out. Use `observe_stream` (for streaming logs) or `spawn_and_observe` (for managed background jobs). | -| **Three orthogonal write axes** | Inspect `mutex` (lock protection), `write_mode` (`atomic-replace` vs. `inplace-write` for bind mounts), and `verification` (size / SHA-256) independently. | +| **Controlled edits** | CAS stands for compare-and-swap. Filaxis checks modification time, size, and a content fingerprint before writing and rejects a version conflict. Check `mutex` and `write_mode` separately. For file transfers, check `verification`. | | **PTY combines stderr** | `channel: "pty"` merges stdout and stderr by terminal semantics; default `exec` keeps them separate. | | **SSH aliases are host-local** | `--host` and `-J` / `jump` aliases resolve against the runtime host's `~/.ssh/config`. Use explicit `user@host[:port]` literals when running across containers or sandboxes. | diff --git a/docs/skills/SKILL.md b/docs/skills/SKILL.md index 8dc8106..bb84855 100644 --- a/docs/skills/SKILL.md +++ b/docs/skills/SKILL.md @@ -1,24 +1,31 @@ --- name: filaxis-runtime -version: 0.2.8 +metadata: + version: "0.2.9" description: | - 牵丝 Filaxis 远程执行运行时的技能剧本总入口——选型决策树(exec 还是观察还是会话)+ 核心契约速查 + 四份场景剧本索引。 - - 必读于(借鉴 modern-web-guidance 的触发清单设计): - - 任何跨层/远程执行、观察、会话、文件编辑、多机排查任务开始前 - - 拿到 unknown 终态 / 写入三轴结果需要解读时 - - 连接层失败(别名/跳板/多跳不可直达)需要自救时 - - 不必读: - - 纯本地一次性命令(本机 shell 能直接解决) - - 与本 SDK 无关的任务(数据库/CI 管线/纯前端) + 使用 Filaxis(@syrkos/filaxis)执行跨层命令、批量巡检、管理后台任务、观察日志或操作目标层文件。 + 也用于排查 SSH 别名与跳板、解读 unknown 终态或写入保障。纯本机一次性命令和与 Filaxis 无关的任务可跳过。 --- # Filaxis 技能剧本 · 总入口 > 这份是**引导与选型**:先在这里定打法,再进具体剧本。API 签名见包内版本化文档;语义契约全文见 [AGENTS.md](../../AGENTS.md)。 -## 10 秒上手:复制即用配方(禁止先读源码——盲测实测通读源码花 44 万 Token 零命令) +## 30 秒选型 + +先用下表选执行入口,只读命中的剧本。执行后核对退出码、就绪标记或对应的文件结果。终态未知时先核实,再决定是否重试。 + +| 任务意图 | MCP 工具或参考 | +|---|---| +| 等一条会自行结束的命令并获取退出码 | `run_command` | +| 批量巡检或按依赖跨层执行 | `run_batch`。涉及跳板或多机取证时读 [跨主机排查](./cross-host-diagnosis.md) | +| 启动后台服务、等就绪或核实进程退出码 | `spawn_and_observe` → `stop_and_verify`。读 [长跑任务](./longrun-observe.md) | +| 按游标实时看日志、看完关窗 | `observe_stream` → `read_stream` → `close_stream`。读 [持续观察窗](./stream-window.md) | +| 列目录、读写、传输或删除文件 | `list_directory`、`read_file`、`edit_file`、`put_file`、`get_file`、`delete_file`。读 [文件操作](./file-sync.md) | +| 切回仍注册的默认层 | 用 `list_layers` 找层名,再用 `set_active_layer` 切换。单次指定目标时可直接传 `layer` | +| CLI 限时查看输出 | `filaxis observe`,适用于只取一段观察结果 | + +## CLI 快速上手 ```bash # ① 建层(一次性;之后全部 --layer 复用,免拼连接参数) @@ -86,7 +93,7 @@ const ctr = await stack.layerInto("prod", "web", "docker exec -i nginx sh"); const r = await host.driver.exec("uptime", { timeoutMs: 10_000 }); console.log(r.exitCode, r.stdout, r.stderr); -// ③ 受控编辑(CAS 原子写回;Docker 单文件 bind mount 传 writeMode: "inplace") +// ③ 受控编辑(写回前核对文件版本;Docker 单文件 bind mount 可传 writeMode: "inplace") const ed = await editFile(ctr.driver, "/etc/nginx/nginx.conf", "worker_processes 1;", "worker_processes auto;", { writeMode: "auto", }); @@ -113,20 +120,6 @@ await stack.removeLayer("prod", { destroy: true }); ``` -## 30 秒选型:你面对的是什么? - -``` -命令会自己结束吗? -├─ 会(一次性:curl/nginx -t/systemctl status)→ exec(退出码是数据) -├─ 不会(tail -f/top/常驻服务/训练) -│ ├─ 只想看一段输出 ────────────→ CLI observe(限时快照,缺省 8s) -│ ├─ 值守等关键行/错误模式 ──────→ execSession + watcher → longrun-observe.md -│ └─ 需要持续读取/回看 ─────────→ observe_stream → read_stream → close_stream(stream-window.md) -└─ 要改远端文件 ──────────────────→ editFile 受控编辑 → file-sync.md - (传输 put/get 也在 file-sync.md) -跨主机排查/抓包对照/跳板拓扑 ────────→ cross-host-diagnosis.md -``` - ## 核心契约速查(违者=生产事故) | 契约 | 一句话 | @@ -135,7 +128,7 @@ await stack.removeLayer("prod", { destroy: true }); | **退出码是数据** | exec 非零退出码不抛异常;只有「无法执行」(超时/断链/abort)才 reject | | **完成哨兵是唯一凭证** | 无哨兵(断链/远端 kill)= reject + `outcome:"unknown"`——绝不伪造退出码,绝不自动重放非幂等命令 | | **永不结束的命令不进 exec** | exec 是「等完成」语义——`tail -f`/`top` 必超时;换 observe / 会话+watcher | -| **写入三轴别混读** | `mutex`(锁保护)× `writeMode`(原子/保留 inode)× `verification`(校验等级)——一个「成功」背后三个独立保证,逐个看 | +| **受控编辑** | CAS 全称 Compare-and-Swap(比较后写回)。写前比较文件修改时间、大小和内容指纹,发现冲突就拒绝写回。分别查看 `mutex` 与 `writeMode`。传输校验等级见 `verification` | | **PTY 通道 stderr 混流** | 终端物理语义不是 bug;exec 通道才分离 | | **别名是运行环境的** | `--host`/`-J` 的 ssh-config 别名用**本运行环境**的 `~/.ssh/config`——跨环境用 `user@host[:port]` 字面量 | diff --git a/docs/skills/file-sync.md b/docs/skills/file-sync.md index 6d29d1a..0006edd 100644 --- a/docs/skills/file-sync.md +++ b/docs/skills/file-sync.md @@ -21,6 +21,11 @@ filaxis get --layer host --transport sftp -- /var/tmp/result.bin ./result.bin 两个命令都传单个文件。`put` 的参数顺序是本地源、层内目标,`get` 反过来。查看 JSON 结果的 `verification` 和 `writeMode`。SFTP 失败时命令直接报错,由调用方核实后决定是否改用 exec。含通配符、引号或控制字符的文件名使用 exec。 +## MCP 目录与单文件删除 + +- `list_directory` 接受 `path` 和可选的 `layer`,列出直接子项,包括隐藏项。文本块显示名称与类型,条目元数据在 `structuredContent.entries`。 +- `delete_file` 永久删除一个文件或符号链接本身。目录和递归删除会报错。未明确目标层时使用当前默认层。若返回 `outcome: "unknown"`,先核实目标路径,再决定是否重试。 + ## MCP 上传和下载 调用 `put_file` 上传,下例向 `app` 层写入文件。 @@ -50,10 +55,20 @@ filaxis get --layer host --transport sftp -- /var/tmp/result.bin ./result.bin 独立传输可以并行。使用不同的本地目标路径下载到同一台 MCP 服务机器,或用 `after` 串行写入同一路径。 -## 受控编辑 editFile(一行替代 20 行样板 / 免 sed -i 写坏) +## 受控编辑与 CAS + +CAS 是 **Compare-and-Swap(比较后写回)**。每次编辑先读取目标 UTF-8 文件,再用文件的修改时间、大小和 SHA-256 指纹前 12 个十六进制字符记录版本。Filaxis 按字面匹配 `old`,默认要求唯一命中,`all: true` 可明确要求替换所有匹配。写回前再次比较版本,发现不一致时拒绝写回并报告冲突。 + +例如用 MCP `edit_file` 提交一次替换。版本检查以本次编辑内部读取的文件为基准,调用者提供刚读到的原文片段。 + +```json +{"layer":"app","path":"/app/config.yaml","old":"port: 8080","new":"port: 9090"} +``` -- `editFile(drv, path, oldStr, newStr, { all? })`:**读+戳一次往返**(stat+内容指纹 sha256 前 12 位+base64 读)→ **精确替换**(唯一命中校验——0 命中/多处命中均报错;`all: true` 全替换)→ **远端 CAS 原子写回**(一次往返:stat+内容指纹比对+tmp 写+mv 原子替换——内容指纹封死 stat 秒级粒度的同秒盲区)→ 失败/冲突均报错不盲写。**仅适用 UTF-8 文本**(含非 UTF-8 字节显式拒绝——GBK/二进制静默写回=永久损坏);二进制编辑走 `readBase64` + 自行改写 + `writeFile`;大文件(base64 >90KB——MAX_ARG_STRLEN 单参数 128KB 安全线内留余量)回落 fs 层路径(非原子,结果 `writeMode:"inplace-write"` 显式标注)。 -- 裸 SSH 用 `sed -i` 改远端文件 = 四层引号转义地狱(实测两翻车+写坏 40 行配置)——受控编辑一行写对。 +- `mutex` 报告锁保护。具备 `flock` 时,核验和落位受同一把协作锁保护。`degraded` 表示无锁,核验与写入之间仍有并发窗口。 +- `write_mode`(SDK 为 `writeMode`)报告落位方式。`atomic-replace` 使用临时文件替换目标,`inplace-write` 保留 inode,写入中断可能留下部分内容。 +- 编辑后的 Base64 载荷超过 90,000 字符时,走文件系统回退。回退会在写入前核验并在写后核对内容指纹,结果报告 `degraded` 和 `inplace-write`。回验失败发生在写入之后,应核实目标内容。 +- 二进制文件使用传输工具。传输的 `verification` 描述大小或 SHA-256 校验等级。 ## 陷阱清单 diff --git a/docs/skills/stream-window.md b/docs/skills/stream-window.md index 402da55..903c1d0 100644 --- a/docs/skills/stream-window.md +++ b/docs/skills/stream-window.md @@ -8,6 +8,7 @@ 1. 用 `observe_stream` 开窗并取得 `window_id`。窗口持续接收指定层的 stdout 和 stderr,可在开窗时按流过滤。 2. 用 `read_stream` 回看。缺省返回最近帧。传 `before_seq` 可向前翻页,传 `window_ms` 可回看最近一段时间。 3. 用 `since_seq` 续读,下一次从 `last_delivered_seq` 接着读。可用 `wait_ms` 等新增帧,等待超时后窗口继续接收。返回 `gap` 时从已有落盘日志补读被覆盖的历史。 + 仅读取 MCP 文本块时,使用文本块内的 `last_delivered_seq` 续读,或用 `first_frame_seq` 作为下一次向前翻页的 `before_seq`。达到文本上限时会标记 `text_truncated=true`。单帧超过上限时展示该帧预览并标记 `frame_truncated=true`,完整帧可从同一响应的 `structuredContent` 读取。 4. 用 `close_stream` 关窗。本地窗口等待所属进程组或 Windows Job 退出,SSH 窗口等待本地 SSH 观察进程退出。若停止失败或超时,返回 `outcome: "unknown"`,可用同一个窗口 ID 读取历史或重试关闭。流自然退出后,窗口在回收前仍保留可回看的帧,读取结果中的 `exit_code` 是观察进程的退出码。 ## SDK 剧本 diff --git a/package.json b/package.json index feae155..71033ea 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@syrkos/filaxis", - "version": "0.2.8", + "version": "0.2.9", "description": "牵丝 Filaxis — 面向自动化与 Agent 的远程执行运行时 SDK(Syrkos · 漩核)。千里一线,执行有迹。", "type": "module", "license": "Apache-2.0", diff --git a/src/agent-toolkit.ts b/src/agent-toolkit.ts index 5865a94..e861eb7 100644 --- a/src/agent-toolkit.ts +++ b/src/agent-toolkit.ts @@ -11,12 +11,12 @@ */ import { randomUUID } from "node:crypto"; import { StreamWindowRegistry, type StreamFrame } from "./stream-window.js"; -import type { RuntimeStack } from "./runtime-stack.js"; +import type { LayerHandle, RuntimeStack } from "./runtime-stack.js"; import { editFile } from "./file-edit.js"; import { transferLayerFile, validateFileTransferFields, type FileTransferTransport, type LayerFileTransferResult } from "./layer-file-transfer.js"; import type { TransferResult } from "./file-transfer.js"; import { BATCH_STEP_KINDS, runBatch, type BatchLayerTarget, type BatchStepWithDeps } from "./batch.js"; -import type { RuntimeDriver } from "./driver.js"; +import type { FileEntry, RuntimeDriver } from "./driver.js"; import { SessionOwnership, type StopResult } from "./session-ownership.js"; import { sshArgsFor } from "./ssh-helpers.js"; @@ -81,6 +81,8 @@ export interface AgentToolHandlers { stdout: string; stderr: string; exit_code: number; effective_user?: string; }>; read_file(args: { path: string; layer?: string }): Promise<{ path: string; content: string; size: number; mtime_ms: number }>; + list_directory(args: { path: string; layer?: string }): Promise<{ path: string; entries: FileEntry[] }>; + delete_file(args: { path: string; layer?: string }): Promise<{ path: string; deleted: true }>; put_file(args: AgentFilePutArgs): Promise; get_file(args: AgentFileTransferArgs): Promise; edit_file(args: { path: string; old: string; new: string; all?: boolean; write_mode?: "auto" | "inplace"; layer?: string }): Promise<{ @@ -107,6 +109,7 @@ export interface AgentToolHandlers { list_layers(args: Record): Promise<{ text: string; layers: Array<{ name: string; driver: string; target?: string }>; }>; + set_active_layer(args: { name: string }): Promise<{ active_layer: string }>; remove_layer(args: { name: string; destroy?: boolean }): Promise<{ removed: string }>; // ── 批次组合(第十一季:一次调用描述多原子操作——减少 Planner 轮次)── run_batch(args: { steps: Array>; stop_on_fail?: boolean; max_parallel?: number; layer?: BatchLayerTarget; output?: "text" | "full" }): Promise<{ @@ -148,6 +151,24 @@ const fileTransferProperties = { }; const layerNameSchema = { type: "string", minLength: 1, pattern: "\\S" }; +const layerPathParameters = { + type: "object", + additionalProperties: false, + properties: { + path: { type: "string", minLength: 1, description: "目标层内的绝对路径或相对工作目录的路径" }, + layer: { ...layerNameSchema, description: "目标层名,省略时使用默认层" }, + }, + required: ["path"], +}; + +function layerPathArgs(args: { path: string; layer?: string }) { + const { path, layer, ...extra } = args; + if (Object.keys(extra).length) throw new Error("只接受 path 和 layer"); + if (typeof path !== "string" || !path.length || path.includes("\0")) throw new Error("path 需为不含 NUL 的非空路径"); + if (layer !== undefined && (typeof layer !== "string" || !layer.trim())) throw new Error("layer 需为非空层名"); + return { path, layer }; +} + const sshHostSchema = { type: "string", minLength: 1, pattern: "^\\S+$", description: "目标主机(user@host 或运行环境的 SSH 配置别名)" }; const sshTargetSchema = { type: "object", @@ -258,7 +279,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ write_mode: { type: "string", enum: ["auto", "inplace"], description: "kind=edit/put:inplace 保留目标 inode" }, hunks: { type: "array", - description: "kind=edit:替换对(一次 CAS 原子应用——任一未命中整批拒绝不写)", + description: "kind=edit:同一文件的替换对。全部匹配且写前版本校验通过才写回;任一未命中则本步骤不写", items: { type: "object", properties: { @@ -294,10 +315,11 @@ export const TOOL_DEFS: AgentToolDef[] = [ "退出码如实返回(非零不是异常——是数据,供条件分支);只有无法执行(超时/中断/连接死)才报错。stdout 与 stderr 分离返回。", parameters: { type: "object", + additionalProperties: false, properties: { - command: { type: "string", description: "shell 命令" }, + command: { ...layerNameSchema, description: "shell 命令" }, timeout_ms: { type: "number", description: "超时毫秒(缺省 120000)" }, - layer: { type: "string", description: "目标层名(缺省=默认层——最近 push_ssh/push_into 的层)" }, + layer: { ...layerNameSchema, description: "目标层名,省略时使用当前默认层" }, }, required: ["command"], }, @@ -308,11 +330,11 @@ export const TOOL_DEFS: AgentToolDef[] = [ function: { name: "spawn_and_observe", description: - "启动后台任务或常驻服务,输出落盘到 log_base 对应的 .out/.err 文件。省略 ready_marker 时,启动后返回 session_id 和 log_base。" + + "管理后台任务或服务的进程生命周期。需要等待服务就绪、按错误模式停止或核实退出码时使用本工具。" + + "输出写入 log_base 对应的 .out/.err 文件。省略 ready_marker 时,启动后返回 session_id 和 log_base。" + "提供 ready_marker 时,先回溯近期输出并等待标记,确认就绪后返回;超时或进程提前退出时报告错误。" + - "可用 error_pattern 监测错误并请求停止,后续用 stop_and_verify 核实进程终态与退出码。" + - "若只需持续流式查看实时输出(如 tail -f / 监控日志)并按游标翻页续读,请改用 observe_stream + read_stream。", - parameters: { + "用 stop_and_verify 停止会话并核实终态。持续查看日志可用 observe_stream 开窗。", + parameters: { type: "object", properties: { command: { type: "string", description: "长跑命令" }, @@ -359,19 +381,36 @@ export const TOOL_DEFS: AgentToolDef[] = [ }, }, }, + { + type: "function", + function: { + name: "list_directory", + description: "列出目标层目录的直接子项,含隐藏项、名称和目录标志。可用时返回文件大小和修改时间。目录不存在或读取失败时报错。", + parameters: layerPathParameters, + }, + }, + { + type: "function", + function: { + name: "delete_file", + description: "永久删除目标层的一个文件或符号链接本身。拒绝目录和递归删除。目标不存在时报错;连接中断且终态未知时请先核实,再决定是否重试。", + parameters: layerPathParameters, + }, + }, { type: "function", function: { name: "edit_file", description: - "受控编辑远端文件:精确替换(唯一命中校验,all=true 全替换)+ TOCTOU 乐观锁(他人先写则拒绝)" + - "+ base64 保真写回(零 Shell 转义——绝不 sed -i)。未命中/多处命中/冲突均报错不盲写。" + - "返回 write_mode:atomic-replace=原子替换;inplace-write=保留 inode(bind mount 挂载点 mv 不可用降级)——非原子写入,中断可暴露半截。", + "对目标层的 UTF-8 文本做字面替换。Compare-and-Swap(CAS)在写回前比较文件的修改时间、大小和内容指纹,版本冲突时拒绝写回。" + + "默认要求 old 唯一命中,all=true 时替换所有匹配。返回 mutex 和 write_mode。atomic-replace 表示原子替换," + + "inplace-write 表示保留 inode 原地写入,中断可能留下部分内容。", parameters: { type: "object", + additionalProperties: false, properties: { - path: { type: "string" }, - old: { type: "string", description: "待替换片段(含足够上下文唯一)" }, + path: { type: "string", minLength: 1 }, + old: { type: "string", minLength: 1, description: "待替换片段(含足够上下文唯一)" }, new: { type: "string" }, all: { type: "boolean", description: "多处命中全替换(缺省报错)" }, write_mode: { type: "string", enum: ["auto", "inplace"], description: "inplace=已知 bind mount 挂载环境显式请求保留 inode 写(跳过 mv 失败尝试)" }, @@ -419,9 +458,9 @@ export const TOOL_DEFS: AgentToolDef[] = [ function: { name: "observe_stream", description: - "直接启动一条持续输出命令并打开本地滚动观察窗,立即返回 window_id(不等待命令结束)。" + - "适用于实时盯日志或持续监控输出(如 tail -f、事件流),配合 read_stream 按游标非破坏回看/翻页/续读,完成后用 close_stream 关闭并回收远端流进程。" + - "若需后台起停服务、等待就绪标记并核实进程退出码,请改用 spawn_and_observe + stop_and_verify。", + "实时查看日志或事件流,例如 tail -f。启动观察命令并立即返回滚动窗口的 window_id。" + + "用 read_stream 按游标回看或续读,用 close_stream 关闭窗口并回收观察命令。" + + "启动和管理后台服务的进程生命周期请用 spawn_and_observe。", parameters: { type: "object", properties: { @@ -438,7 +477,8 @@ export const TOOL_DEFS: AgentToolDef[] = [ type: "function", function: { name: "read_stream", - description: "读取本地观察窗。可读最近帧、按 before_seq 向前翻页、按 window_ms 回看或按 since_seq 续读。每次续读用 last_delivered_seq,gap 表示游标区间有丢失。", + description: "读取本地观察窗的日志帧。可读最近帧、按 before_seq 向前翻页、按 window_ms 回看或按 since_seq 续读。" + + "续读用 last_delivered_seq,向前翻页用 first_frame_seq 或本页首帧号。使用当前结果格式里的游标,gap 表示有帧缺失。", parameters: { type: "object", properties: { @@ -518,6 +558,19 @@ export const TOOL_DEFS: AgentToolDef[] = [ parameters: { type: "object", properties: {}, required: [] }, }, }, + { + type: "function", + function: { + name: "set_active_layer", + description: "将一个已注册层设为默认层,影响之后省略 layer 的工具调用。连接和其他层保留,返回 active_layer。可用 list_layers 查看可选层名。", + parameters: { + type: "object", + additionalProperties: false, + properties: { name: { ...layerNameSchema, description: "已注册的层名" } }, + required: ["name"], + }, + }, + }, { type: "function", function: { @@ -568,17 +621,23 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption /** 层寻址(第十季注册表):显式层名 > 注册表默认层(最近 push)> 初始层—— * 未用层族时与旧行为逐字节一致(零破坏),push 后六工具自动落新默认层 */ const resolveDrv = async (layerName?: string): Promise => { - if (layerName) return stack.layer(layerName).driver; + if (layerName !== undefined) { + if (typeof layerName !== "string" || !layerName.trim()) throw new Error("layer 需为非空层名"); + return stack.layer(layerName).driver; + } return stack.active ?? await layer(); }; - const connectSsh = async ({ host, name, connParams }: ReturnType): Promise => { - const result = await stack.addLayer(name, { + const connectSsh = async ({ host, name, connParams }: ReturnType) => { + const { handle, reused, reusedFrom } = await stack.addLayer(name, { driver: "ssh", target: host, config: Object.keys(connParams).length ? { connParams } : undefined, }); return { - layer: result.handle.name, reused: result.reused, reused_from: result.reusedFrom, - note: result.reused ? "落点已由既有层持有——幂等复用(未重复建连)" : "新层已建并成为默认层", + handle, + result: { + layer: handle.name, reused, reused_from: reusedFrom, + note: reused ? "落点已由既有层持有——幂等复用(未重复建连)" : "新层已建并成为默认层", + }, }; }; function pushSsh(args: PushSshTarget & { targets?: never }): Promise; @@ -588,25 +647,36 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption if (typeof args.host !== "string" || !args.host.trim()) { throw new Error("push_ssh 需提供单目标 host 或批量 targets"); } - return connectSsh(sshConnection(args)); + return (await connectSsh(sshConnection(args))).result; } if (Object.keys(args).some((key) => key !== "targets")) throw new Error("push_ssh 的 targets 必须单独提供"); const targets = sshBatchTargets(args.targets); const results: PushSshBatchResult["results"] = []; - const layers = new Set(); + const connected = new Map(); let failures = 0; // Serial registration preserves RuntimeStack's landing reuse and default-layer order. for (const target of targets) { const { host, name } = target; try { - const result = await connectSsh(target); - layers.add(result.layer); + const { handle, result } = await connectSsh(target); + connected.set(results.length, handle); results.push({ host, name, status: "ok", ...result }); } catch (error) { failures++; results.push({ host, name, status: "fail", error: error instanceof Error ? error.message : String(error) }); } } + const layers = new Set(); + for (const [index, handle] of connected) { + if (stack.layers.get(handle.name) === handle) { + layers.add(handle.name); + } else { + const { host, name } = results[index]!; + const error = `层 '${handle.name}' 在批量建连期间已移除或被替换`; + results[index] = { host, name, status: "fail", error }; + failures++; + } + } return { status: failures === 0 ? "ok" : failures === targets.length ? "fail" : "partial", active_layer: stack.activeLayer?.name, @@ -688,10 +758,12 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption }, get layer(): Promise { return layer(); }, // 惰性 getter(失败不缓存+注册命名表——Hydrogen R7 #4) handlers: { - async run_command({ command, timeout_ms, layer: layerName }) { + async run_command({ command, timeout_ms, layer: layerName, ...extra }) { if (Array.isArray(layerName)) { throw new Error("run_command 的 layer 仅支持单个层名;同一命令发往多个层请改用 run_batch 并传 layer 数组"); } + if (Object.keys(extra).length) throw new Error("run_command 含未知参数,目标层字段为 layer"); + if (typeof command !== "string" || !command.trim()) throw new Error("command 需为非空字符串"); const drv = await resolveDrv(layerName); const r = await drv.exec(command, { timeoutMs: timeout_ms }); return { @@ -755,7 +827,24 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption const content = await drv.fs.readFile(path); return { path, content, size: st.size, mtime_ms: st.mtimeMs }; }, - async edit_file({ path, old, new: newStr, all, write_mode: writeMode, layer: layerName }) { + async list_directory(args) { + const { path, layer: layerName } = layerPathArgs(args); + const drv = await resolveDrv(layerName); + return { path, entries: await drv.fs.readdir(path) }; + }, + async delete_file(args) { + const { path, layer: layerName } = layerPathArgs(args); + if (/(?:^|\/)\.{1,2}$|\/$/.test(path)) throw new Error("delete_file 需要单文件路径"); + const drv = await resolveDrv(layerName); + if (drv.descriptor.driver === "local" && process.platform === "win32" + && /(?:^|\\)\.{1,2}$|\\$/.test(path)) { + throw new Error("delete_file 需要单文件路径"); + } + await drv.fs.rm(path, { recursive: false, force: false }); + return { path, deleted: true }; + }, + async edit_file({ path, old, new: newStr, all, write_mode: writeMode, layer: layerName, ...extra }) { + if (Object.keys(extra).length) throw new Error("edit_file 含未知参数,目标层字段为 layer"); const drv = await resolveDrv(layerName); const r = await editFile(drv, path, old, newStr, { all, writeMode }); return { path: r.path, occurrences: r.occurrences, bytes_before: r.bytesBefore, bytes_after: r.bytesAfter, mutex: r.mutex, write_mode: r.writeMode }; @@ -848,6 +937,11 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption await stack.removeLayer(name, { destroy }); return { removed: name }; }, + async set_active_layer({ name, ...extra }) { + if (Object.keys(extra).length) throw new Error("set_active_layer 只接受 name"); + if (typeof name !== "string" || !name.trim()) throw new Error("name 需为非空层名"); + return { active_layer: stack.setActive(name).name }; + }, async run_batch({ steps, stop_on_fail, max_parallel, layer: layerName, output, ...unknownArgs }) { if (!Array.isArray(steps) || !steps.length) throw new Error(`steps 需为非空数组,每步提供 id 和 kind(${BATCH_STEP_KINDS.join("、")})`); const extra = Object.keys(unknownArgs); diff --git a/src/file-edit.ts b/src/file-edit.ts index 41371f3..3895d20 100644 --- a/src/file-edit.ts +++ b/src/file-edit.ts @@ -97,6 +97,19 @@ export const shaCmdOf = (f: string) => const shaCmdOfContent = (content: string) => crypto.createHash("sha256").update(content, "utf-8").digest("hex").slice(0, 12); +function validateEditTarget(path: string, writeMode: EditFileOptions["writeMode"]): void { + if (typeof path !== "string" || !path.length || path.includes("\0")) throw new Error("path 需为不含 NUL 的非空路径"); + if (writeMode !== undefined && writeMode !== "auto" && writeMode !== "inplace") { + throw new Error("write_mode/writeMode 须为 auto 或 inplace"); + } +} + +function validateReplacement(old: string, replacement: string, all: boolean | undefined, label: string): void { + if (typeof old !== "string" || !old.length) throw new Error(`${label} 的 old 需为非空字符串`); + if (typeof replacement !== "string") throw new Error(`${label} 的 new 需为字符串`); + if (all !== undefined && typeof all !== "boolean") throw new Error(`${label} 的 all 需为布尔值`); +} + /** * 受控编辑(真 2 次往返 + 远端 CAS 原子写回): * ① 读+戳+方言探测(1 次往返):`stat 戳; sha 戳; __FXS__; base64 -d 探测; @@ -116,6 +129,9 @@ export async function editFile( newStr: string, opts: EditFileOptions = {}, ): Promise { + const { all, writeMode } = opts; + validateEditTarget(path, writeMode); + validateReplacement(oldStr, newStr, all, "editFile"); const sr = await readStamped(drv, path); const occurrences = sr.content0.split(oldStr).length - 1; if (occurrences === 0) { @@ -123,13 +139,13 @@ export async function editFile( throw new Error(`未命中待替换片段(0 处): ${path}(oldStr 长度 ${oldStr.length},文件 ${sr.content0.length} 字符)。` + `提示:若 old 含引号/多行/缩进——行内 argv 可能被宿主 Shell 剥引号或截断,改用免 Shell 载荷通道(CLI: edit --stdin-json 或 --request-file ;SDK: editFile 直传字符串)后重试`); } - if (occurrences > 1 && !opts.all) { + if (occurrences > 1 && !all) { throw new Error(`多处命中(${occurrences} 处)——精确替换语义拒绝;确认全替换请传 { all: true }: ${path}`); } // 字面替换语义(GPT Astra #5):String.replace 的 replacement 含 $&/$$ 等替换 // 语法会被 V8 解释(实测 old→"$&-new" 写成 "old-new")——回调返回值按字面处理 - const edited = opts.all ? sr.content0.split(oldStr).join(newStr) : sr.content0.replace(oldStr, () => newStr); - const w = await casWrite(drv, path, sr, edited, opts.writeMode === "inplace"); + const edited = all ? sr.content0.split(oldStr).join(newStr) : sr.content0.replace(oldStr, () => newStr); + const w = await casWrite(drv, path, sr, edited, writeMode === "inplace"); return { path, occurrences, @@ -152,11 +168,19 @@ export async function editFileMulti( hunks: Array<{ old: string; new: string; all?: boolean }>, opts: Pick = {}, ): Promise { - if (hunks.length === 0) throw new Error(`editFileMulti 需至少一个 hunk: ${path}`); + const { writeMode } = opts; + validateEditTarget(path, writeMode); + if (!Array.isArray(hunks) || !hunks.length) throw new Error(`editFileMulti 需至少一个 hunk: ${path}`); + const replacements = Array.from(hunks, (hunk, index) => { + if (!hunk || typeof hunk !== "object") throw new Error(`hunk #${index} 需为替换对象`); + const { old, new: replacement, all } = hunk; + validateReplacement(old, replacement, all, `hunk #${index}`); + return { old, new: replacement, all }; + }); const sr = await readStamped(drv, path); let content = sr.content0; const applied: EditMultiHunk[] = []; - for (const [i, h] of hunks.entries()) { + for (const [i, h] of replacements.entries()) { const n = content.split(h.old).length - 1; if (n === 0) { throw new Error(`hunk #${i} 未命中(0 处,整批拒绝未写入): ${path}(oldStr 长度 ${h.old.length},当前内容 ${content.length} 字符——先前 hunk 已应用后的内容)`); @@ -167,7 +191,7 @@ export async function editFileMulti( content = h.all ? content.split(h.old).join(h.new) : content.replace(h.old, () => h.new); // 回调=字面替换($ 语义免疫) applied.push({ old: h.old, new: h.new, occurrences: n }); } - const w = await casWrite(drv, path, sr, content, opts.writeMode === "inplace"); + const w = await casWrite(drv, path, sr, content, writeMode === "inplace"); return { path, occurrences: applied.reduce((s, h) => s + h.occurrences, 0), diff --git a/src/local-driver.ts b/src/local-driver.ts index 3fc1f6e..a7c9311 100644 --- a/src/local-driver.ts +++ b/src/local-driver.ts @@ -393,6 +393,15 @@ class LocalFileSystem implements FileSystemDriver { } async rm(filePath: string, options?: { recursive?: boolean; force?: boolean}): Promise { + if (!options?.recursive && !options?.force) { + // A single unlink cannot remove a directory if the entry changes concurrently. + const target = process.platform === "win32" ? this.resolve(filePath) + : this.baseCwd && !path.isAbsolute(filePath) + ? this.baseCwd + path.sep + filePath + : filePath; + await fs.unlink(target); + return; + } await fs.rm(this.resolve(filePath), options); } diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 94d250b..14a8073 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -25,6 +25,8 @@ const JSONRPC_VERSION = "2.0"; const COMMAND_PREVIEW_BYTES = 8 * 1024; const BATCH_PREVIEW_BYTES = 4 * 1024; const BATCH_TEXT_JSON_BYTES = 8 * 1024; +const STREAM_TEXT_JSON_BYTES = 8 * 1024; +const DIRECTORY_TEXT_JSON_BYTES = 8 * 1024; const BATCH_DETAIL_BYTES = 1024; const FULL_OUTPUT_HINT = ",完整输出见 structuredContent"; @@ -137,7 +139,8 @@ export class McpServer { // 在任何 schema 读取之前必达,是唯一可靠的发现面) instructions: [ "【先看这行】多文件读取/多命令巡检/同命令发往多层/定位排查 → 优先 run_batch(一次调用并行打包,支持传 layer 数组自动扇出,不要逐个工具循环);读工具 schema 时同轮并发读取(逐个读每步一趟 LLM);", - "持续查看日志 → observe_stream 开窗、read_stream 回看或续读、close_stream 关闭;等就绪或错误模式 → spawn_and_observe;", + "管理后台任务或服务(等就绪、按错误模式停止、核实退出码)→ spawn_and_observe + stop_and_verify。", + "实时查看日志或事件流 → observe_stream 开窗、read_stream 按游标读帧、close_stream 回收观察命令。", "edit_file 支持 write_mode:'inplace'(bind mount 保 inode 免重启);", "在 MCP 服务主机与目标层之间传输文件用 put_file 和 get_file。", "契约:退出码是数据(非零不是异常);终态三态 exited/stopped/unknown;unknown 后用 stop_and_verify 核实。", @@ -194,7 +197,8 @@ export class McpServer { sessions: err.sessions, exitCode: err.exitCode, }; - const errorText = textOnlyBatch && err.outcome ? `outcome=${err.outcome}\n${message}` : message; + const errorText = (textOnlyBatch || name === "delete_file") && err.outcome + ? `outcome=${err.outcome}\n${message}` : message; const overflow = name === "run_batch" && jsonStringBytes(errorText) > BATCH_TEXT_JSON_BYTES; this.reply(id, { content: [{ type: "text", text: overflow ? limitBatchText(errorText, textOnlyBatch ? "" : FULL_OUTPUT_HINT) : errorText }], @@ -227,10 +231,25 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea const result = value as Awaited>; return result.text; } + if (name === "set_active_layer") { + const result = value as Awaited>; + return `active_layer=${singleLine(result.active_layer)}`; + } + if (name === "delete_file") { + const result = value as Awaited>; + return `deleted=true | path=${singleLine(result.path)}`; + } + if (name === "list_directory") { + const result = value as Awaited>; + return summarizeDirectory(result); + } if (name === "run_command") { const result = value as Awaited>; return [`exit=${result.exit_code}`, ...outputPreviews(result, COMMAND_PREVIEW_BYTES)].join("\n"); } + if (name === "read_stream") { + return summarizeStreamRead(value as Awaited>); + } if (name === "push_ssh") { const result = value as PushSshResult | PushSshBatchResult; if ("results" in result) { @@ -287,6 +306,73 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea return summarize(value); } +function summarizeDirectory(result: Awaited>): string { + const header = `path=${singleLine(result.path)} | entries=${result.entries.length}`; + const omitted = "\n[目录文本达到上限,完整结果见 structuredContent]"; + const omittedBytes = jsonStringBytes(omitted) - 2; + let remaining = DIRECTORY_TEXT_JSON_BYTES - jsonStringBytes(header); + if (remaining < 0) return limitText(header, omitted, DIRECTORY_TEXT_JSON_BYTES); + const lines = [header]; + for (const [index, entry] of result.entries.entries()) { + const line = `${entry.isDirectory ? "dir" : "file"} ${singleLine(entry.name)}`; + const bytes = jsonStringBytes(`\n${line}`) - 2; + const reserve = index < result.entries.length - 1 ? omittedBytes : 0; + if (bytes + reserve > remaining) { + return remaining >= omittedBytes ? lines.join("\n") + omitted : limitText(header, omitted, DIRECTORY_TEXT_JSON_BYTES); + } + lines.push(line); + remaining -= bytes; + } + return lines.join("\n"); +} + +function summarizeStreamRead(result: Awaited>): string { + const { frames, last_delivered_seq: cursor } = result; + const status = [ + `window=${singleLine(result.window_id)}`, `frames=${frames.length}`, + `oldest_seq=${result.oldest_seq}`, `newest_seq=${result.newest_seq}`, `stale=${result.stale}`, + ]; + if (result.gap) status.push("gap=true"); + if (result.timed_out) status.push("timed_out=true"); + if (result.exit_code !== undefined) status.push(`exit_code=${result.exit_code}`); + if (result.error) status.push(`error=${preview(singleLine(result.error), 256, FULL_OUTPUT_HINT)}`); + + let firstSeq: number | undefined; + let lastSeq = cursor; + const header = (count: number, first?: number, last?: number, partialFrame = false) => [ + ...status, `text_frames=${count}`, + ...(first === undefined ? [] : [`first_frame_seq=${first}`]), + ...(last === undefined ? [] : [`last_delivered_seq=${last}`]), + ...(count < frames.length || partialFrame ? ["text_truncated=true"] : []), + ...(partialFrame ? ["frame_truncated=true"] : []), + ].join(" | "); + const lines: string[] = []; + let lineBytes = 0; + const forward = cursor !== undefined; + // Incremental reads show the first frames; snapshots and backwards pages show the latest. + for (let index = 0; index < frames.length; index++) { + const frame = frames[forward ? index : frames.length - 1 - index]!; + const line = `[${frame.seq} ${frame.stream ?? "output"}] ${singleLine(frame.text)}`; + const bytes = jsonStringBytes(`\n${line}`) - 2; + const first = forward ? firstSeq ?? frame.seq : frame.seq; + const last = forward ? frame.seq : lastSeq ?? frame.seq; + if (jsonStringBytes(header(index + 1, first, last)) + lineBytes + bytes > STREAM_TEXT_JSON_BYTES) { + if (!lines.length) { + const text = `${header(1, frame.seq, frame.seq, true)}\n${line}`; + return limitText(text, "\n[此帧仅显示预览,完整帧见 structuredContent]", STREAM_TEXT_JSON_BYTES); + } + break; + } + lines.push(line); + lineBytes += bytes; + firstSeq = first; + lastSeq = last; + } + if (!forward) lines.reverse(); + // The structured cursor covers the entire page. The text cursor covers the displayed frames. + return [header(lines.length, firstSeq, lastSeq), ...lines].join("\n"); +} + function singleLine(text: string): string { return text.replace(/[\p{Cc}\u2028\u2029]/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`); } @@ -296,12 +382,15 @@ function jsonStringBytes(text: string): number { } function limitBatchText(text: string, hint: string): string { - const suffix = `\n[批次文本达到上限,部分结果已省略${hint}]`; + return limitText(text, `\n[批次文本达到上限,部分结果已省略${hint}]`, BATCH_TEXT_JSON_BYTES); +} + +function limitText(text: string, suffix: string, maxBytes: number): string { let lo = 0; - let hi = Math.min(text.length, BATCH_TEXT_JSON_BYTES); + let hi = Math.min(text.length, maxBytes); while (lo < hi) { const mid = Math.floor((lo + hi + 1) / 2); - if (jsonStringBytes(text.slice(0, mid) + suffix) <= BATCH_TEXT_JSON_BYTES) lo = mid; + if (jsonStringBytes(text.slice(0, mid) + suffix) <= maxBytes) lo = mid; else hi = mid - 1; } const last = text.charCodeAt(lo - 1); diff --git a/src/runtime-stack.ts b/src/runtime-stack.ts index e0c2f19..b746fb0 100644 --- a/src/runtime-stack.ts +++ b/src/runtime-stack.ts @@ -442,17 +442,19 @@ export class RuntimeStack { // 未注册)。自定义 driver 的复用走 connect 缓存键(driverKey 含全量 config—— // 十五轮)自然隔离,不做跨层 identity 合并 const hit = descriptor.driver === "ssh" ? await this.findIdentityHit(descriptor) : undefined; - if (hit) { + if (hit && this.namedLayers.get(hit.handle.name) === hit.handle) { const reused = hit.terminal || await this.verifyLanding(hit.handle, hopHost(layerPathIdentities(descriptor).at(-1) ?? "")); - if (reused) { - this.log.info(`[Filaxis] 层 '${name}' 落点已由 '${hit.handle.name}' 持有——幂等复用(不重复建连)`); - return { handle: hit.handle, reused: true, reusedFrom: hit.handle.name }; + if (this.namedLayers.get(hit.handle.name) === hit.handle) { + if (reused) { + this.log.info(`[Filaxis] 层 '${name}' 落点已由 '${hit.handle.name}' 持有——幂等复用(不重复建连)`); + return { handle: hit.handle, reused: true, reusedFrom: hit.handle.name }; + } + throw new Error( + `层名 '${name}' 的落点 identity 命中既有层 '${hit.handle.name}' 的途经节点,且落点校验不符` + + `(期望 ${hopHost(layerPathIdentities(descriptor).at(-1) ?? "?")},实测 ${hit.handle.actualHostname ?? "?"})` + + `(宁重连不错主机):请检查连接参数后重试`, + ); } - throw new Error( - `层名 '${name}' 的落点 identity 命中既有层 '${hit.handle.name}' 的途经节点,且落点校验不符` + - `(期望 ${hopHost(layerPathIdentities(descriptor).at(-1) ?? "?")},实测 ${hit.handle.actualHostname ?? "?"})` + - `(宁重连不错主机):请检查连接参数后重试`, - ); } const driver = await this.connect(descriptor); const handle: LayerHandle = { name, descriptor: driver.descriptor, driver }; @@ -729,7 +731,7 @@ export class RuntimeStack { for (let i = 0; i < path.length; i++) { const candidate = path[i]!; if (JSON.stringify(RuntimeStack.sshHopContext(candidate)) !== context) continue; - if ((await resolve(candidate, this.log)) === destId) { + if ((await resolve(candidate, this.log)) === destId && this.namedLayers.get(h.name) === h) { return { handle: h, terminal: i === path.length - 1 }; } } diff --git a/src/ssh-pty-driver.ts b/src/ssh-pty-driver.ts index 2a8afa2..90bf966 100644 --- a/src/ssh-pty-driver.ts +++ b/src/ssh-pty-driver.ts @@ -508,7 +508,7 @@ export class SshPtyDriver implements RuntimeDriver { return entries; }, async rm(p, options) { - const r = await fsExec(`rm ${options?.recursive ? "-r " : ""}${options?.force ? "-f " : ""}${q(p)}`); + const r = await fsExec(`rm ${options?.recursive ? "-r " : ""}${options?.force ? "-f " : ""}-- ${q(p)}`); if (r.exitCode !== 0) throw new Error(`rm 失败(exit=${r.exitCode}): ${p}`); }, async mkdir(p, options) { diff --git a/src/tmux-driver.ts b/src/tmux-driver.ts index 78c548e..52cfe6b 100644 --- a/src/tmux-driver.ts +++ b/src/tmux-driver.ts @@ -165,7 +165,7 @@ export class TmuxSessionDriver implements RuntimeDriver { // 退出码入闸(Sol 87 P2-7):rm/mkdir 曾丢 exitCode——对普通文件 mkdir、 // 无 force 删缺席路径都报正常完成。凭证纪律同 readFile/writeFile async rm(p, options) { - const r = await self.exec(`rm ${options?.recursive ? "-r " : ""}${options?.force ? "-f " : ""}${q(p)}`); + const r = await self.exec(`rm ${options?.recursive ? "-r " : ""}${options?.force ? "-f " : ""}-- ${q(p)}`); // force 只影响命令形态(-f 豁免缺席路径——exit 0);非零退出=真实 // 失败(目录未递归删等)照传(Sol 88 P2-1:曾 force 下吞掉一切非零 //——对现存目录的非递归删除谎报完成、目录仍在) diff --git a/tests/agent-toolkit.test.ts b/tests/agent-toolkit.test.ts index 8ac12df..baaa40c 100644 --- a/tests/agent-toolkit.test.ts +++ b/tests/agent-toolkit.test.ts @@ -25,13 +25,66 @@ class MockSshDriver { } describe("createAgentToolkit(反馈 #3)", () => { + test("explicit invalid layer never falls back to the active driver", async () => { + const driver = new MockSshDriver({ driver: "fixture" }); + let executions = 0; + driver.exec = async () => { executions++; return { stdout: "", stderr: "", exitCode: 0 }; }; + const stack = new RuntimeStack(); + await stack.addLayer("fixture", driver as unknown as RuntimeDriver); + const { handlers } = createAgentToolkit(stack); + for (const layer of ["", " ", null, false, 0]) { + await expect(handlers.run_command({ command: "fixture", layer: layer as never })).rejects.toThrow(/非空层名/); + } + const misspelled = { command: "fixture", layer_name: "elsewhere" }; + await expect(handlers.run_command(misspelled)).rejects.toThrow(/目标层字段为 layer/); + await expect(handlers.run_command({ command: "" })).rejects.toThrow(/command 需为非空字符串/); + expect(executions).toBe(0); + expect((await handlers.run_command({ command: "fixture" })).exit_code).toBe(0); + expect(executions).toBe(1); + await stack.removeLayer("fixture", { destroy: true }); + }); + + test("push_ssh batch excludes layers replaced before the response", async () => { + const stack = new RuntimeStack(); + const addLayer = stack.addLayer.bind(stack); + const slowEntered = Promise.withResolvers(); + const release = Promise.withResolvers(); + stack.addLayer = async (name) => { + if (name === "slow") { + slowEntered.resolve(); + await release.promise; + } + return addLayer(name, new MockSshDriver({ driver: "fixture" }) as unknown as RuntimeDriver); + }; + const batch = createAgentToolkit(stack).handlers.push_ssh({ targets: ["first", "slow"] }); + try { + await slowEntered.promise; + await stack.removeLayer("first", { destroy: true }); + await stack.addLayer("first", { driver: "local" }); + release.resolve(); + expect(await batch).toMatchObject({ + status: "partial", + layers: ["slow"], + results: [ + { name: "first", status: "fail", error: expect.stringContaining("已移除或被替换") }, + { name: "slow", status: "ok", layer: "slow" }, + ], + }); + } finally { + release.resolve(); + await batch; + await Promise.all([...stack.layers.keys()].map((name) => stack.removeLayer(name, { destroy: true }))); + } + }); + test("工具定义 + run_command 退出码是数据", async () => { const tk = createAgentToolkit(new RuntimeStack()); expect(tk.tools.map((t) => t.function.name)).toEqual([ "run_batch", // 置顶(第十三季黑盒:Lazy schema 按序读——run_batch 排第 7 被漏读) "run_command", "spawn_and_observe", "stop_and_verify", - "read_file", "edit_file", "put_file", "get_file", "observe_stream", "read_stream", "close_stream", - "push_ssh", "push_into", "list_layers", "remove_layer", // 第十季层族 + "read_file", "list_directory", "delete_file", "edit_file", "put_file", "get_file", + "observe_stream", "read_stream", "close_stream", + "push_ssh", "push_into", "list_layers", "set_active_layer", "remove_layer", ]); const r = await tk.handlers.run_command({ command: "echo tk-out; exit 4" }); expect(r.stdout.trim()).toBe("tk-out"); diff --git a/tests/file-edit.test.ts b/tests/file-edit.test.ts index ce03aaa..c0d5b24 100644 --- a/tests/file-edit.test.ts +++ b/tests/file-edit.test.ts @@ -4,7 +4,7 @@ import { mkdtempSync, writeFileSync, readFileSync, rmSync, mkdirSync, chmodSync, import { tmpdir } from "node:os"; import { join } from "node:path"; import { LocalRuntimeDriver } from "../src/local-driver.js"; -import { editFile, EditConflictError } from "../src/file-edit.js"; +import { editFile, editFileMulti, EditConflictError } from "../src/file-edit.js"; import { createAgentToolkit } from "../src/agent-toolkit.js"; import { RuntimeStack } from "../src/runtime-stack.js"; import type { RuntimeDriver } from "../src/driver.js"; @@ -12,6 +12,16 @@ import type { RuntimeDriver } from "../src/driver.js"; const dir = mkdtempSync(join(tmpdir(), "fx-edit-")); describe("editFile(TOCTOU+精确替换)", () => { + test("invalid edit arguments are rejected before reading or writing", async () => { + const driver = { exec: () => { throw new Error("driver called for invalid input"); } } as unknown as RuntimeDriver; + await expect(editFile(driver, "/fixture", "", "insert", { all: true })).rejects.toThrow(/old 需为非空字符串/); + await expect(editFile(driver, "/fixture", "x", "y", { all: "false" as never })).rejects.toThrow(/all 需为布尔值/); + await expect(editFile(driver, "/fixture", "x", "y", { writeMode: "typo" as never })).rejects.toThrow(/writeMode 须为/); + await expect(editFileMulti(driver, "/fixture", [ + { old: "a", new: "b" }, { old: "", new: "c", all: true }, + ])).rejects.toThrow(/hunk #1 的 old 需为非空字符串/); + }); + test.skipIf(process.platform !== "linux")("符号链接编辑与同目标别名共用 CAS 锁", async () => { const fixture = mkdtempSync(join(tmpdir(), "fx-edit-aliases-")); try { diff --git a/tests/integration-ssh.test.ts b/tests/integration-ssh.test.ts index b02d4b6..0716f6d 100644 --- a/tests/integration-ssh.test.ts +++ b/tests/integration-ssh.test.ts @@ -115,6 +115,15 @@ integration("SSH rejects a broken PTY cwd and distinguishes an empty directory f expect(entries).toHaveLength(34); expect(entries.find((entry) => entry.name === name)).toMatchObject({ isDirectory: false, size: 0 }); expect(entries.find((entry) => entry.name === ".nested")).toMatchObject({ isDirectory: true }); + const scoped = new SshPtyDriver({ driver: "ssh", target: TARGET, cwd: path }); + try { + expect((await scoped.exec("touch ./-literal")).exitCode).toBe(0); + await scoped.fs.rm("-literal"); + expect(await scoped.fs.exists("-literal")).toBe(false); + await expect(scoped.fs.rm(".nested")).rejects.toThrow(/rm 失败/); + } finally { + await scoped.destroy(); + } } finally { await drv.fs.rm(path, { recursive: true, force: true }); await drv.destroy(); diff --git a/tests/mcp-server.test.ts b/tests/mcp-server.test.ts index 0834e38..6f9e015 100644 --- a/tests/mcp-server.test.ts +++ b/tests/mcp-server.test.ts @@ -8,7 +8,7 @@ import { McpServer } from "../src/mcp-server.js"; import { createAgentToolkit, TOOL_DEFS } from "../src/agent-toolkit.js"; import { RuntimeStack } from "../src/runtime-stack.js"; import { LocalRuntimeDriver } from "../src/local-driver.js"; -import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createServer } from "node:net"; @@ -47,6 +47,89 @@ async function waitId(f: { collect: () => Array> }, id: } describe("MCP Server(REQ-0003)", () => { + test("directory listing, default-layer switching, and non-recursive deletion", async () => { + const dir = mkdtempSync(join(tmpdir(), "fx-mcp-directory-")); + const stack = new RuntimeStack(); + const fixture = mcpFixture(stack); + const call = async (id: number, name: string, args: Record) => { + fixture.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }); + return (await waitId(fixture, id)).result; + }; + try { + const previous = join(dir, "previous"); + const current = join(dir, "current"); + mkdirSync(previous); + mkdirSync(current); + mkdirSync(join(previous, "nested")); + writeFileSync(join(previous, "-literal"), "previous"); + writeFileSync(join(current, "-literal"), "current"); + writeFileSync(join(previous, ".hidden"), "hidden"); + if (process.platform !== "win32") symlinkSync("nested", join(previous, "link")); + const previousDriver = new LocalRuntimeDriver({ cwd: previous }); + await stack.addLayer("previous", previousDriver); + await stack.addLayer("current", new LocalRuntimeDriver({ cwd: current })); + + expect(await call(1, "set_active_layer", { name: "unknown" })).toMatchObject({ isError: true }); + expect(stack.activeLayer?.name).toBe("current"); + expect(await call(2, "set_active_layer", { name: "previous" })).toMatchObject({ + structuredContent: { active_layer: "previous" }, content: [{ text: "active_layer=previous" }], + }); + expect(await call(3, "list_directory", { path: "." })).toMatchObject({ + content: [{ text: expect.stringContaining("file .hidden") }], + structuredContent: { entries: expect.arrayContaining([ + expect.objectContaining({ name: "nested", isDirectory: true }), + expect.objectContaining({ name: "-literal", isDirectory: false }), + ]) }, + }); + expect(await call(4, "list_directory", { path: "missing" })).toMatchObject({ isError: true }); + expect(await call(5, "delete_file", { path: "nested", recursive: true })).toMatchObject({ isError: true }); + expect(await call(6, "delete_file", { path: "nested" })).toMatchObject({ isError: true }); + expect(await call(7, "delete_file", { path: "-literal" })).toMatchObject({ + structuredContent: { deleted: true, path: "-literal" }, + }); + expect(await call(8, "delete_file", { path: "-literal" })).toMatchObject({ isError: true }); + if (process.platform !== "win32") { + mkdirSync(join(previous, "other", "deeper"), { recursive: true }); + writeFileSync(join(previous, "other", "target"), "physical"); + writeFileSync(join(previous, "target"), "lexical"); + symlinkSync("other/deeper", join(previous, "alias")); + expect(await call(9, "delete_file", { path: "link/." })).toMatchObject({ isError: true }); + expect(await call(10, "delete_file", { path: "link" })).toMatchObject({ + structuredContent: { deleted: true, path: "link" }, + }); + expect(await call(12, "delete_file", { path: "alias/../target" })).toMatchObject({ isError: false }); + expect(existsSync(join(previous, "other", "target"))).toBe(false); + expect(readFileSync(join(previous, "target"), "utf8")).toBe("lexical"); + } + expect(existsSync(join(previous, "nested"))).toBe(true); + expect(existsSync(join(previous, "-literal"))).toBe(false); + expect(readFileSync(join(current, "-literal"), "utf8")).toBe("current"); + previousDriver.fs.rm = async () => { + throw Object.assign(new Error("connection lost"), { outcome: "unknown" }); + }; + expect(await call(11, "delete_file", { path: ".hidden" })).toMatchObject({ + isError: true, content: [{ text: "outcome=unknown\nconnection lost" }], + structuredContent: { outcome: "unknown" }, + }); + const entries = Array.from({ length: 60 }, (_, i) => ({ name: `entry-${i}-${"雪".repeat(80)}-end`, isDirectory: false })); + previousDriver.fs.readdir = async () => entries; + const listed = await call(13, "list_directory", { path: "." }) as { + content: Array<{ text: string }>; structuredContent: { entries: typeof entries }; + }; + const listingText = listed.content[0]!.text; + expect(listed.structuredContent.entries).toEqual(entries); + expect(Buffer.byteLength(JSON.stringify(listingText))).toBeLessThanOrEqual(8192); + expect(listingText).toContain("完整结果见 structuredContent"); + const fileLines = listingText.split("\n").filter((line) => line.startsWith("file ")); + expect(fileLines.length).toBeGreaterThan(0); + expect(fileLines.every((line) => line.endsWith("-end"))).toBe(true); + } finally { + fixture.close(); + await Promise.all([...stack.layers.keys()].map((name) => stack.removeLayer(name, { destroy: true }))); + rmSync(dir, { recursive: true, force: true }); + } + }); + test("put_file and get_file transfer bytes on the selected layer and report verification", async () => { const dir = mkdtempSync(join(tmpdir(), "fx-mcp-transfer-")); const stack = new RuntimeStack(); @@ -367,6 +450,16 @@ describe("MCP Server(REQ-0003)", () => { // 多行 old(第二处的上下文消歧)+引号+缩进——结构化直达不经宿主 Shell const old2 = '{ "path": "/api/v2", "strip_prefix": false }'; const new2 = '{ "path": "/api/v2", "strip_prefix": true }'; + for (const [index, invalid] of [ + { layer: "" }, { layer_name: "elsewhere" }, { old: "", all: true }, { all: "false" }, { write_mode: "typo" }, + ].entries()) { + const id = index + 10; + f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { + name: "edit_file", arguments: { path: p, old: old2, new: new2, ...invalid }, + } }); + expect((await waitId(f, id)).result).toMatchObject({ isError: true }); + } + expect(readFileSync(p, "utf8")).toBe(content); f.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "edit_file", arguments: { path: p, old: old2, new: new2 } } }); const r = await waitId(f, 1); const res = (r as { result: { isError: boolean; structuredContent: { occurrences: number } } }).result; @@ -451,7 +544,9 @@ test("MCP opens, reads, and closes a continuous window by ID", async () => { const fixture = mcpFixture(); const call = async (id: number, name: string, args: Record) => { fixture.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }); - return (await waitId(fixture, id)).result as { isError: boolean; structuredContent: Record }; + return (await waitId(fixture, id)).result as { + isError: boolean; content: Array<{ text: string }>; structuredContent: Record; + }; }; try { expect((await call(0, "observe_stream", { command: "echo LEGACY", duration_ms: 10 })).isError).toBe(true); @@ -460,6 +555,8 @@ test("MCP opens, reads, and closes a continuous window by ID", async () => { const window_id = opened.structuredContent.window_id; const read = await call(2, "read_stream", { window_id, since_seq: 0, wait_ms: 5000 }); expect(read.structuredContent).toMatchObject({ frames: [{ text: "MCP_WINDOW", stream: "stdout", seq: 1 }] }); + expect(read.content[0]!.text).toContain("[1 stdout] MCP_WINDOW"); + expect(read.content[0]!.text).toContain("last_delivered_seq=1"); const closed = await call(3, "close_stream", { window_id }); expect(closed.structuredContent).toEqual({ window_id, closed: true }); expect((await call(4, "read_stream", { window_id })).isError).toBe(true); @@ -468,6 +565,67 @@ test("MCP opens, reads, and closes a continuous window by ID", async () => { } }, 20_000); +test("read_stream text stays bounded and pages without skipping undisplayed frames", async () => { + const stack = new RuntimeStack(); + const toolkit = createAgentToolkit(stack); + const frames = Array.from({ length: 30 }, (_, index) => ({ + seq: index + 1, ts: 0, stream: index === 1 ? "stderr" as const : "stdout" as const, + text: `line-${index + 1} ` + "雪".repeat(200) + "\u001b[0m", + })); + toolkit.handlers.read_stream = async ({ window_id, since_seq, before_seq }) => { + const page = window_id === "oversized" ? [{ ...frames[0]!, text: "oversized " + "雪".repeat(4000) }, ...frames.slice(1)] : frames; + const selected = page.filter(({ seq }) => seq > (since_seq ?? 0) && seq < (before_seq ?? Infinity)); + return { + window_id, oldest_seq: 1, newest_seq: 30, stale: false, frames: selected, + ...(since_seq === undefined ? {} : { last_delivered_seq: selected.at(-1)?.seq ?? since_seq }), + ...(selected.length ? {} : { timed_out: true }), + }; + }; + const fixture = mcpFixture(stack, toolkit); + const read = async (id: number, args: Record, window_id = "fixture") => { + fixture.write({ jsonrpc: "2.0", id, method: "tools/call", params: { + name: "read_stream", arguments: { window_id, ...args }, + } }); + const result = (await waitId(fixture, id)).result as { + content: Array<{ text: string }>; + structuredContent: Awaited>; + }; + const text = result.content[0]!.text; + expect(Buffer.byteLength(JSON.stringify(text))).toBeLessThanOrEqual(8192); + return { text, structured: result.structuredContent }; + }; + try { + const first = await read(1, { since_seq: 0 }); + expect(first.structured).toEqual({ + window_id: "fixture", oldest_seq: 1, newest_seq: 30, stale: false, frames, last_delivered_seq: 30, + }); + expect(first.text).toContain("text_truncated=true"); + expect(first.text).toContain("[2 stderr] line-2"); + expect(first.text).toContain("\\u001b[0m"); + const cursor = Number(first.text.match(/last_delivered_seq=(\d+)/)?.[1]); + expect(cursor).toBeGreaterThan(2); + expect(cursor).toBeLessThan(30); + expect((await read(2, { since_seq: cursor })).text).toContain(`[${cursor + 1} stdout] line-${cursor + 1} `); + + const backwards = await read(3, { before_seq: 30 }); + const firstSeq = Number(backwards.text.match(/first_frame_seq=(\d+)/)?.[1]); + expect(firstSeq).toBeGreaterThan(1); + expect(backwards.text).toContain("[29 stdout] line-29 "); + expect((await read(4, { before_seq: firstSeq })).text).toContain(`[${firstSeq - 1} stdout] line-${firstSeq - 1} `); + const empty = await read(5, { since_seq: 30 }); + expect(empty.text).toContain("last_delivered_seq=30"); + expect(empty.text).toContain("timed_out=true"); + const oversized = await read(6, { since_seq: 0 }, "oversized"); + expect(oversized.text).toContain("frame_truncated=true"); + expect(oversized.text).toContain("last_delivered_seq=1"); + expect(oversized.text).toContain("[1 stdout] oversized"); + expect(oversized.structured.frames[0]?.text).toHaveLength(4010); + expect((await read(7, { since_seq: 1 }, "oversized")).text).toContain("[2 stderr] line-2"); + } finally { + fixture.close(); + } +}); + describe("MCP layer array fan-out", () => { test("push_ssh validates all batch targets and reports usable layers after partial failure", async () => { const stack = new RuntimeStack();