diff --git a/CHANGELOG.md b/CHANGELOG.md index 923337d..9ca0b1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ --- +## 0.2.11 + +- MCP 工具清单从 18 个合并为 12 个。`read_path` 读取文件或列目录,`manage_path` 创建目录、移动或删除,`transfer_file` 统一上传与下载。层管理、后台会话和观察窗也采用合并后的入口,0.2.10 的旧工具名仍可直接调用。 +- `edit_file` 支持直接创建 UTF-8 文本,默认拒绝覆盖已有文件。CAS 局部替换继续使用 `old` 和 `new`。 +- `observe_stream` 可以开窗时返回首批日志,也可以按窗口 ID 继续读取。MCP 错误文本包含已知的 `outcome` 和会话句柄,方便只读文本的客户端核实结果。 +- tmux 的文件传输按输出窗口分块,超长命令会提示先上传脚本。查询不存在或无权访问的路径会返回对应错误,并保留 tmux 会话。 + +- Windows 上以隐藏控制台方式启动 Filaxis 的 SSH 和 SFTP 子进程,覆盖匿名管道和文件中转。 + ## 0.2.10 - MCP `read_file` 在文本块显示文件正文,超限时标记截断,完整正文保留在结构化结果中。读取请求会拒绝未知字段和无效层名。 diff --git a/README.en.md b/README.en.md index ef44055..5d0d415 100644 --- a/README.en.md +++ b/README.en.md @@ -86,12 +86,12 @@ Or launch it directly with `npx` in your MCP client configuration: } ``` -Exposed MCP tools (18 tools): +Exposed MCP tools (12 tools): - **Execution & batching**: `run_command`, `run_batch` -- **Long-running sessions & observation windows**: `spawn_and_observe`, `stop_and_verify`, `observe_stream`, `read_stream`, `close_stream` -- **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` +- **Long-running sessions & observation windows**: `start_session`, `stop_session`, `observe_stream`, `close_stream` +- **Files and paths**: `read_path`, `edit_file`, `manage_path`, `transfer_file` +- **Layer management**: `connect_layer`, `manage_layers` 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. @@ -104,7 +104,7 @@ filaxis get --host user@host --transport sftp -- /var/tmp/result.bin ./result.bi `put` and `get` move one file at a time. The default exec transport follows the target layer, including entry into a container. Use `--transport sftp` when the SSH server exposes the target filesystem directly, including through a TCP jump host. Results include the verification level and write mode. -In MCP, use `put_file` or `get_file` with `local_path` on the MCP server host and `remote_path` in the target layer. Specify `layer` to address a named layer. For multiple files, use `put` and `get` steps in `run_batch`. The [file transfer playbook](./docs/skills/file-sync.md) includes examples. +In MCP, use `transfer_file` (`direction: "put" | "get"`) with `local_path` on the MCP server host and `remote_path` in the target layer. Specify `layer` to address a named layer. For multiple files, use `put` and `get` steps in `run_batch`. The [file transfer playbook](./docs/skills/file-sync.md) includes examples. ## Tested platforms and connection methods diff --git a/README.md b/README.md index 5166f6a..b7bbac4 100644 --- a/README.md +++ b/README.md @@ -87,12 +87,12 @@ filaxis mcp-config --format toml # TOML,使用 mcp_servers(Codex) } ``` -暴露的 18 个 MCP 工具速览: +暴露的 12 个 MCP 工具速览: - **命令与批处理**:`run_command`、`run_batch` -- **长跑会话与观察窗**:`spawn_and_observe`、`stop_and_verify`、`observe_stream`、`read_stream`、`close_stream` -- **文件与目录**:`list_directory`、`read_file`、`edit_file`、`put_file`、`get_file`、`delete_file` -- **多层连接管理**:`push_ssh`、`push_into`、`list_layers`、`set_active_layer`、`remove_layer` +- **长跑会话与观察窗**:`start_session`、`stop_session`、`observe_stream`、`close_stream` +- **文件与路径管理**:`read_path`、`edit_file`、`manage_path`、`transfer_file` +- **多层连接管理**:`connect_layer`、`manage_layers` npm 包包含 [Skill 入口与四份子剧本](docs/skills/SKILL.md),以及配套的 [AGENTS.md](AGENTS.md)。需要登记 Skill 时,由 Agent 按自身平台的规则处理这些文件。 @@ -105,7 +105,7 @@ filaxis get --host user@host --transport sftp -- /var/tmp/result.bin ./result.bi `put/get` 传输单个文件,支持 `--layer` 和 `--host`。默认用层的 exec 通道,可进入容器。SSH 目标的文件系统可直接访问时,可显式选择 `--transport sftp`,包括经 `-J` 跳板的连接。两条路径都先校验暂存文件再落位,JSON 结果标明校验等级和写入形态。详见 [文件同步剧本](docs/skills/file-sync.md)。 -MCP 对应工具是 `put_file` 和 `get_file`。`local_path` 位于 MCP 服务所在机器,`remote_path` 位于目标层。可用 `layer` 选择命名层。 +MCP 对应工具是 `transfer_file`(传 `direction: "put" | "get"`)。`local_path` 位于 MCP 服务所在机器,`remote_path` 位于目标层。可用 `layer` 选择命名层。 ## 已验证的平台与连接方式 diff --git a/docs/skills/SKILL.en.md b/docs/skills/SKILL.en.md index d02d57b..3166952 100644 --- a/docs/skills/SKILL.en.md +++ b/docs/skills/SKILL.en.md @@ -1,7 +1,7 @@ --- name: filaxis-runtime metadata: - version: "0.2.10" + version: "0.2.11" description: | 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. @@ -27,13 +27,13 @@ Match the task to an entry point and read the relevant playbook. After execution |---|---| | 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 | +| Start a background service, wait for readiness, or verify its exit code | `start_session` → `stop_session`. Read [Long-running jobs](./longrun-observe.md) | +| Follow logs with a cursor and close the view when finished | `observe_stream` (open/read) → `close_stream`. Read [Observation windows](./stream-window.md) | +| Read/list, edit/create, mkdir/move/delete, or transfer files | `read_path`, `edit_file`, `manage_path`, `transfer_file`. Read [File operations](./file-sync.md) | +| List, activate, or remove registered layers | `manage_layers` (`action: "list" \| "activate" \| "remove"`); connect or enter inner layers with `connect_layer` | | Observe a command for a limited interval in the CLI | `filaxis observe` | -For work expected to take over two minutes, such as an OS upgrade or a long build, start a session with `spawn_and_observe`. In one Antigravity run, the host ended an MCP call at about three minutes. A tool's `timeout_ms` cannot extend the host deadline. Follow the [long-running jobs playbook](./longrun-observe.md) to read the logs and verify the outcome. +For work expected to take over two minutes, such as an OS upgrade or a long build, start a session with `start_session`. In one Antigravity run, the host ended an MCP call at about three minutes. A tool's `timeout_ms` cannot extend the host deadline. Follow the [long-running jobs playbook](./longrun-observe.md) to read the logs and verify the outcome. ## CLI quick start @@ -66,16 +66,16 @@ filaxis exec --layer --timeout 8000 -- "(printf 'PING\n'; sleep 1) | nc 1 ## MCP Practical Guidelines -- **Batch inspection and multi-step fixes with `run_batch`**: Combine multiple `read_file`, `run_command`, `edit_file`, `put`, and `get` steps into a single parallel `run_batch` call instead of sequential single-tool loops. -- **Batch SSH connections**: Call `push_ssh` with `{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`. Strings can be SSH config aliases resolved in the runtime environment. Targets are attempted in order and individual connection failures are reported without stopping the batch. Pass the deduplicated `layers` from successful and reused connections directly to `run_batch.layer`. `active_layer` reports the default layer at the end of the call. +- **Batch inspection and multi-step fixes with `run_batch`**: Combine multiple `read`, `exec`, `edit`, `put`, and `get` steps into a single parallel `run_batch` call instead of sequential single-tool loops. +- **Layer connections (`connect_layer`)**: Connect a single SSH host (`host`), a batch (`{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`), or enter an inner container/shell (`enter_cmd`). Strings can be SSH config aliases resolved in the runtime environment. Batch targets are attempted in order and individual failures are reported without stopping the batch. Pass the deduplicated `layers` from successful and reused connections directly to `run_batch.layer`. `active_layer` reports the default layer at the end of the call. - **Layer targeting precedence & multi-layer fan-out**: Both top-level `layer` and per-step `layer` accept either a single layer name or a non-empty array of layer names (top-level sets the batch default; per-step overrides only that step; omitting both uses the active default layer). Multi-layer arrays expand each step into `id@layer` instances that run in parallel up to `max_parallel` (single-element arrays keep the original `id`), and downstream `after` dependencies wait for all expanded instances to succeed (`kind: "get"` rejects multi-layer arrays to avoid overwriting the same `local_path`). `filaxis batch --request-file plan.json` shares the same precedence and array expansion (step `layer` > plan `layer` > `--layer`/`--host` > local). - **Local targeting**: Layer arrays look up registered or saved names. SDK callers can register the local host with `stack.addLayer("local", { driver: "local" })`. The CLI and standalone MCP server leave the local default unnamed. - **Concurrency & ordering (`max_parallel` and `after`)**: Independent steps run in parallel up to `max_parallel`. Use `after: ["step-id"]` to serialize dependent steps (e.g., edit config -> validate -> reload service), even across layers. - **Resource coordination**: `after` references the original step IDs declared in the same batch. Fan-out executes once per layer name, and different names may point to the same environment. Serialize operations that modify the same resource using its environment identity and file path. - **Text vs. structured output**: `run_batch` text previews share 4 KiB across streams and cap at 8 KiB total (prioritizing failed steps and edit guarantees). Clients that only read text blocks can pass `output: "text"`; use the default `output: "full"` to read full `structuredContent`. `run_command` previews up to 8 KiB per stream. -- **Start working right after connecting**: Do not waste turns running `hostname` or `list_layers` after `push_ssh`/`push_into` — the first `run_command`'s exit code and output confirm the layer. -- **Targeted file reading & minimal edits**: Inspect specific line ranges or recent logs (`sed -n '20,40p' ` or `docker logs --tail 30 `). For `edit_file`, copy only the exact target lines with minimal unique context into `old`. -- **Single vs. batch file transfer**: Use `put_file` / `get_file` for individual files (`local_path` is on the MCP server host; `remote_path` is in the target layer; pass `transport: "sftp"` when the SSH server exposes the target filesystem directly). Use `kind: "put"` / `kind: "get"` steps in `run_batch` for multiple files, ordering concurrent writes to the same path with `after`. +- **Start working right after connecting**: Do not waste turns running `hostname` or `manage_layers(action="list")` after `connect_layer` — the first `run_command`'s exit code and output confirm the layer. +- **Targeted file reading & minimal edits**: Inspect specific line ranges or recent logs (`sed -n '20,40p' ` or `docker logs --tail 30 `). For `edit_file`, copy only the exact target lines with minimal unique context into `old` (or pass `content` to create a new UTF-8 file). +- **Single vs. batch file transfer**: Use `transfer_file` (`direction: "put" | "get"`) for individual files (`local_path` is on the MCP server host; `remote_path` is in the target layer; pass `transport: "sftp"` when the SSH server exposes the target filesystem directly). Use `kind: "put"` / `kind: "get"` steps in `run_batch` for multiple files, ordering concurrent writes to the same path with `after`. - **Restricted pipe environments & Windows OpenSSH**: If the host restricts anonymous pipes, set `FILAXIS_SSH_STDIO_MODE=inherit` before starting the CLI/MCP server or creating SSH layers in the SDK (supports direct SSH, single `-J` jump, and non-interactive entry steps; live stream windows and interactive PTY chains require pipes). On Windows, Filaxis restores missing `SystemRoot`, `windir`, `ProgramData`, and `USERNAME` for OpenSSH child processes and logs a single stderr warning when restoring `SystemRoot`. --- @@ -135,10 +135,10 @@ await stack.removeLayer("prod", { destroy: true }); | Contract | Rule | |---|---| -| **Tri-state termination** | `stop_and_verify` / `stopSession` returns `exited` (verified exit code), `stopped` (verified termination), or `unknown` (verification unreachable — **neither success nor failure**). Verify with `verifySession(id)` / `stop_and_verify` instead of assuming cleanup succeeded. | +| **Tri-state termination** | `stop_session` / `stopSession` returns `exited` (verified exit code), `stopped` (verified termination), or `unknown` (verification unreachable — **neither success nor failure**). Verify with `verifySession(id)` / `stop_session` instead of assuming cleanup succeeded. | | **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). | +| **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 `start_session` (for managed background jobs). | | **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. | @@ -159,9 +159,9 @@ Additional detailed scenario playbooks in `docs/skills/`: ## Troubleshooting Checklist -1. **Layer connection failure** — Check whether an SSH config alias is missing in the current container/runtime environment or whether a comma-chained `-J` hop needs `push_ssh` + `push_into` instead. +1. **Layer connection failure** — Check whether an SSH config alias is missing in the current container/runtime environment or whether a comma-chained `-J` hop needs two `connect_layer` calls (`host` then `enter_cmd`) instead. 2. **Missing log output** — Inspect on-disk `.out`/`.err` session logs if hot-window lines were evicted (`evictedCount > 0`), or check `dropped` / `gap` counters on observation streams. -3. **Uncertain stop result** — Call `stop_and_verify` / `verifySession(id)` whenever `status === "unknown"`. +3. **Uncertain stop result** — Call `stop_session` / `verifySession(id)` whenever `status === "unknown"`. 4. **Uncertain file write guarantees** — Check `mutex`, `write_mode`, and `verification` in the structured result; pass `write_mode: "inplace"` upfront for Docker single-file bind mounts. ## Project Policy Tips diff --git a/docs/skills/SKILL.md b/docs/skills/SKILL.md index 0e012b3..9a37076 100644 --- a/docs/skills/SKILL.md +++ b/docs/skills/SKILL.md @@ -1,7 +1,7 @@ --- name: filaxis-runtime metadata: - version: "0.2.10" + version: "0.2.11" description: | 使用 Filaxis(@syrkos/filaxis)执行跨层命令、批量巡检、管理后台任务、观察日志或操作目标层文件。 也用于排查 SSH 别名与跳板、解读 unknown 终态或写入保障。纯本机一次性命令和与 Filaxis 无关的任务可跳过。 @@ -19,13 +19,13 @@ description: | |---|---| | 等一条会自行结束的命令并获取退出码 | `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` | +| 启动后台服务、等就绪或核实进程退出码 | `start_session` → `stop_session`。读 [长跑任务](./longrun-observe.md) | +| 按游标实时看日志、看完关窗 | `observe_stream`(开窗即读+游标续读)→ `close_stream`。读 [持续观察窗](./stream-window.md) | +| 读文件/列目录、编辑/建文本、建目录/移动/删除、传文件 | `read_path`、`edit_file`、`manage_path`、`transfer_file`。读 [文件操作](./file-sync.md) | +| 查询、切换默认层或移除已注册层 | `manage_layers`(`action: "list" \| "activate" \| "remove"`);建连或进内层用 `connect_layer` | | CLI 限时查看输出 | `filaxis observe`,适用于只取一段观察结果 | -预计超过两分钟的任务(如系统升级或长编译)优先用 `spawn_and_observe` 启动。Antigravity 实测曾在约三分钟终止单次 MCP 调用,工具的 `timeout_ms` 无法延长宿主的调用时限。按 [长跑任务剧本](./longrun-observe.md) 查看落盘日志并核实终态。 +预计超过两分钟的任务(如系统升级或长编译)优先用 `start_session` 启动。Antigravity 实测曾在约三分钟终止单次 MCP 调用,工具的 `timeout_ms` 无法延长宿主的调用时限。按 [长跑任务剧本](./longrun-observe.md) 查看落盘日志并核实终态。 ## CLI 快速上手 @@ -54,8 +54,8 @@ filaxis exec --layer <名> --timeout 8000 -- "(printf 'PING ``` **MCP 形态实战指引**(第十二季盲测 B 组教训): -- 多个 SSH 目标可用一次 `push_ssh` 调用,例如 `{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`。字符串可用运行环境 SSH 配置里的别名。按输入顺序建连,单个目标失败后继续尝试。返回的 `layers` 只含建连成功或复用的实际层名,并已去重,非空时可直接传给 `run_batch.layer`。批量结果的 `active_layer` 是调用结束时的默认层。 -- **定位/巡检期用 `run_batch` 打包**——多个 read_file/run_command 一次调用并行 +- 多个 SSH 目标可用一次 `connect_layer` 调用,例如 `{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`;也可单台传 `host` 或传 `enter_cmd` 从既有层进入容器。字符串可用运行环境 SSH 配置里的别名。按输入顺序建连,单个目标失败后继续尝试。返回的 `layers` 只含建连成功或复用的实际层名,并已去重,非空时可直接传给 `run_batch.layer`。批量结果的 `active_layer` 是调用结束时的默认层。 +- **定位/巡检期用 `run_batch` 打包**——多个 `read` / `exec` 一次调用并行 执行(B 组逐个调 18 步 vs CLI 组打包 11 步——这是 MCP 形态省步数的最大杠杆); - `run_batch` 的顶层 `layer` 和步骤 `layer` 均支持传单个层名或层名数组(也可同时传:顶层是批次默认值,步骤的 `layer` 仅覆盖本步;两处都省略时使用调用时的默认层)。传多个层名数组时,步骤按 `id@layer` 展开并在 `max_parallel` 并发池内并行执行,下游 `after` 需等被依赖步骤的所有展开实例均 ok 后才启动(`kind: "get"` 不支持多层数组,防并发覆盖同一 `local_path`);单元素数组保留原 `id`。结果逐步标明命名层。 - CLI 的 `filaxis batch --request-file plan.json` 同样支持这两个字段,并从 `filaxis layer save` 保存的层中解析名称。优先级依次为步骤 `layer`、计划 `layer`、命令行的 `--layer` 或 `--host`,全省略时使用本机。 @@ -64,10 +64,10 @@ filaxis exec --layer <名> --timeout 8000 -- "(printf 'PING - `after` 引用当前批次计划里声明的原始步骤 ID。同一环境可能有多个层名,扇出按层名各执行一次。多个步骤或批次可能同时修改同一资源时,由调用方按实际资源串行化,例如用「环境身份 + 配置路径」作为互斥键。 - `run_batch` 文本逐步展示状态、退出码、编辑的写入方式和锁状态,以及 stdout/stderr 预览。所有输出流共用 4 KiB,整个文本字段序列化后最多 8 KiB,超出时优先显示失败步骤和编辑保障。只看文本块的 MCP 客户端请传 `output: "text"`。需要完整输出时用默认的 `output: "full"`,从 `structuredContent` 取。`run_command` 的文本各流最多预览 8 KiB。 - `output: "text"` 在本机和 SSH 层按预算采集 `exec` / `read` 预览,并继续读取完成哨兵来核实退出码。SSH 文件中转仍在磁盘接收完整输出,回读只取有界的首尾。其他层需要支持限量采集才能在文本模式下执行这些步骤。 -- 建链后立即干活,**不要**逐个 hostname/list_layers 验证——首个 run_command +- 建链后立即干活,**不要**逐个 `hostname` / `manage_layers(action="list")` 验证——首个 `run_command` 的退出码与命令输出就是执行凭证; - 巡检只读目标配置的相关行和最近 20–30 行关键日志,例如在批次的 `exec` 步骤中用 `sed -n '20,40p' ` 或 `docker logs --tail 30 `。批量编辑时,把刚读到的原文连同能唯一定位的上下文直接填入 `old`,在 `new` 只改目标行,无需逐行默写全文。 -- 二进制或整文件传输用 `put_file` / `get_file`。`local_path` 位于 MCP 服务进程所在机器,`remote_path` 位于目标层。传 `layer` 指定目标,`transport: "sftp"` 可选用于文件系统可直达的 SSH 层。完整示例见 [文件同步剧本](./file-sync.md)。 +- 二进制或整文件传输用 `transfer_file`(`direction: "put" | "get"`)。`local_path` 位于 MCP 服务进程所在机器,`remote_path` 位于目标层。传 `layer` 指定目标,`transport: "sftp"` 可选用于文件系统可直达的 SSH 层。完整示例见 [文件同步剧本](./file-sync.md)。 - 批量上传和下载用 `run_batch` 的 `kind: "put"` / `kind: "get"`,字段与单文件工具一致。多个步骤写同一个 `local_path` 或同一目标层文件时,用 `after` 排序,或为每个下载指定不同的本地路径。 - 宿主拦截 SSH 匿名管道时,在建层前设 `FILAXIS_SSH_STDIO_MODE=inherit`。它支持直连、单跳 `-J` 和可非交互重放的进入步骤。逐跳 PTY、交互进入、持久转发和持续观察窗需要可用的匿名管道。若首轮已发出且终态未知,先核实远端状态再决定是否重发。 - Windows 的 OpenSSH 子进程会继承现有配置,并由 Filaxis 补齐缺失的系统和账户变量,例如 `SystemRoot`、`windir`、`ProgramData` 和 `USERNAME`。成功补齐 `SystemRoot` 时,CLI 和 MCP 会在 stderr 告警一次,SDK 通过注入的 logger 记录。SSH 秒退且双流为空时,可检查启动器是否保留了系统环境。 diff --git a/docs/skills/file-sync.md b/docs/skills/file-sync.md index 0ba00e0..82cdfd6 100644 --- a/docs/skills/file-sync.md +++ b/docs/skills/file-sync.md @@ -21,27 +21,27 @@ filaxis get --layer host --transport sftp -- /var/tmp/result.bin ./result.bin 两个命令都传单个文件。`put` 的参数顺序是本地源、层内目标,`get` 反过来。查看 JSON 结果的 `verification` 和 `writeMode`。SFTP 失败时命令直接报错,由调用方核实后决定是否改用 exec。含通配符、引号或控制字符的文件名使用 exec。 -## MCP 目录与单文件删除 +## MCP 路径读取与管理 -- `list_directory` 接受 `path` 和可选的 `layer`,列出直接子项,包括隐藏项。文本块显示名称与类型,条目元数据在 `structuredContent.entries`。 -- `read_file` 的文本块显示文件正文,保留换行与缩进。文本序列化后最多 8 KiB,超限会标记截断,完整正文在 `structuredContent.content`。 -- `delete_file` 永久删除一个文件或符号链接本身。目录和递归删除会报错。未明确目标层时使用当前默认层。若返回 `outcome: "unknown"`,先核实目标路径,再决定是否重试。 +- `read_path` 接受 `path` 和可选的 `layer`,自动区分文件与目录:文件时文本块显示 UTF-8 正文(序列化上限 8 KiB,超限标记截断,完整正文在 `structuredContent.content`);目录时列出直接子项,条目元数据在 `structuredContent.entries`。 +- `manage_path` 统一管理目录与路径生命周期:`action: "mkdir"` 创建目录(默认 `parents: true`);`action: "move"` 移动或重命名(需 `destination`,前置拒绝目标是现存目录及跨设备目录移动);`action: "delete"` 删除路径(默认 `recursive: false` 仅删单文件或符号链接本身并拒绝目录;传 `recursive: true` 可递归删除目录,前置拒绝根目录、`.` / `..`、当前工作目录及上级路径)。前置检查只负责防误操作,不防御同权限并发进程在校验与执行之间的目录调包(TOCTOU),底层原生命令报错原样返回给调用方;若因信号中断返回 `outcome: "unknown"`,先核实目标路径,再决定是否重试。 +- 在 `tmux` 层需要运行超大脚本(超过 `send-keys` 单条 ~15.5 KB 限制)时,单次 `run_command` 会前置报错且不封存窗格;请改用 `run_batch` 先 `kind: "put"` 上传脚本,再通过 `after` 串联 `kind: "exec"` 执行。 ## MCP 上传和下载 -调用 `put_file` 上传,下例向 `app` 层写入文件。 +调用 `transfer_file` 上传或下载单个文件。下例向 `app` 层写入文件(`direction: "put"`)。 ```json -{"layer":"app","local_path":"./config.yaml","remote_path":"/app/config.yaml"} +{"direction":"put","layer":"app","local_path":"./config.yaml","remote_path":"/app/config.yaml"} ``` -调用 `get_file` 下载,下例用 SFTP 把二进制文件写到 MCP 服务所在机器。 +下例用 SFTP 从 `host` 层下载二进制文件到 MCP 服务所在机器(`direction: "get"`)。 ```json -{"layer":"host","remote_path":"/var/tmp/result.bin","local_path":"./result.bin","transport":"sftp"} +{"direction":"get","layer":"host","remote_path":"/var/tmp/result.bin","local_path":"./result.bin","transport":"sftp"} ``` -`local_path` 由 MCP 服务进程解析,相对路径以其工作目录为准。两个工具都可能覆盖目标文件,成功后返回字节数、摘要、校验等级和 `write_mode`。文件内容直接写入目标路径。传输层和校验规则与 CLI 一致。 +`local_path` 由 MCP 服务进程解析,相对路径以其工作目录为准。`transfer_file` 可能覆盖目标文件,成功后返回字节数、摘要、校验等级和 `write_mode`。传输层和校验规则与 CLI 一致。 多个文件可以放进同一次 `run_batch`。下例先从 `source` 层取回文件,再上传到 `target` 层。每步结果的 `transfer` 包含校验信息。 diff --git a/docs/skills/longrun-observe.md b/docs/skills/longrun-observe.md index 24df340..a5f5671 100644 --- a/docs/skills/longrun-observe.md +++ b/docs/skills/longrun-observe.md @@ -16,7 +16,7 @@ ## 剧本 -MCP 长跑任务用 `spawn_and_observe` 启动,保存文本块里的完整 `session_id`、`log_base` 和目标层。持续看日志时,用 `observe_stream` 在同一层跟随 `log_base` 对应的 `.out` 或 `.err`,然后用 `read_stream` 续读。关闭观察窗会回收观察命令。任务自然退出后,用完整 `session_id` 调 `stop_and_verify` 获取可核实的退出码。会话归属缓存过期时,使用原目标层的 `layer`。 +MCP 长跑任务用 `start_session` 启动,保存文本块里的完整 `session_id`、`log_base` 和目标层。持续看日志时,用 `observe_stream` 在同一层传 `command` 跟随 `log_base` 对应的 `.out` 或 `.err`(并可带 `wait_ms` 直接读首屏帧),后续再传同一 `window_id` 调 `observe_stream` 续读,用 `close_stream` 回收观察命令。任务自然退出后,用完整 `session_id` 调 `stop_session` 获取可核实的退出码。会话归属缓存过期时,使用原目标层的 `layer`。 1. **启动即返,不要阻塞在 execSession**:长跑任务是会话不是 exec——`execSession` 返回句柄(`sessionId`/`logBase`/`pid`)后立刻挂 watcher,人再离开。 2. **watcher 三态用法**: diff --git a/docs/skills/stream-window.md b/docs/skills/stream-window.md index 903c1d0..2bd645e 100644 --- a/docs/skills/stream-window.md +++ b/docs/skills/stream-window.md @@ -5,8 +5,8 @@ ## Agent 与 MCP 工具 -1. 用 `observe_stream` 开窗并取得 `window_id`。窗口持续接收指定层的 stdout 和 stderr,可在开窗时按流过滤。 -2. 用 `read_stream` 回看。缺省返回最近帧。传 `before_seq` 可向前翻页,传 `window_ms` 可回看最近一段时间。 +1. 用 `observe_stream` 传 `command` 开窗并取得 `window_id`(可传 `wait_ms` 直接带回首屏帧)。窗口持续接收指定层的 stdout 和 stderr,可在开窗时按流过滤。 +2. 用 `observe_stream` 传 `window_id` 回看或续读。缺省返回最近帧。传 `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` 是观察进程的退出码。 diff --git a/examples/agent-tools.ts b/examples/agent-tools.ts index 39f6375..b474699 100644 --- a/examples/agent-tools.ts +++ b/examples/agent-tools.ts @@ -18,7 +18,7 @@ const tools = { return layer.exec(cmd, { timeoutMs: 30_000 }); }, }, - spawn_and_observe: { + start_session: { description: "启动长跑任务并注册观察(ready 标记 + 错误模式)。返回 sessionId 与首窗口", handler: async (cmd: string, readyMarker: string, errorPattern?: string) => { const layer = await stack.connect({ driver: "local" }); @@ -43,7 +43,7 @@ const tools = { return { sessionId: h.sessionId, tail: await layer.tailSession(h.sessionId, 5) }; }, }, - stop_and_verify: { + stop_session: { description: "停止任务并核实终态(unknown=核实不可达,非成功非失败——需重试或上报)", handler: async (sessionId: string) => { const layer = await stack.connect({ driver: "local" }); @@ -63,12 +63,12 @@ const stack = new RuntimeStack(); const r = await tools.run_command.handler("echo tool-ok; exit 3"); console.log("run_command:", r.stdout.trim(), "exitCode:", r.exitCode, "user:", r.effectiveUser); -const obs = await tools.spawn_and_observe.handler( +const obs = await tools.start_session.handler( "echo READY; for i in 1 2 3; do echo tick-$i; sleep 0.1; done; sleep 20", "READY", "NEVER_MATCH", ); -console.log("spawn_and_observe:", obs.sessionId, "首窗口:", obs.tail.join(",")); +console.log("start_session:", obs.sessionId, "首窗口:", obs.tail.join(",")); -const stop = await tools.stop_and_verify.handler(obs.sessionId); -console.log("stop_and_verify:", stop.status); +const stop = await tools.stop_session.handler(obs.sessionId); +console.log("stop_session:", stop.status); diff --git a/package.json b/package.json index b444e7c..471e535 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@syrkos/filaxis", - "version": "0.2.10", + "version": "0.2.11", "description": "牵丝 Filaxis — 面向自动化与 Agent 的远程执行运行时 SDK(Syrkos · 漩核)。千里一线,执行有迹。", "type": "module", "license": "Apache-2.0", diff --git a/src/agent-toolkit.ts b/src/agent-toolkit.ts index b5173b3..4d509df 100644 --- a/src/agent-toolkit.ts +++ b/src/agent-toolkit.ts @@ -1,15 +1,16 @@ /** - * agent-toolkit.ts — 原生 Agent 工具集(Gemini 试用反馈 #3 + 第十季层族) + * agent-toolkit.ts — 原生 Agent 工具集(12 工具 `verb_noun` 收敛版) * * 一行 `createAgentToolkit(stack)` 生成 LLM 工具面——OpenAI/Anthropic/Vercel AI SDK * 通吃的 {tools, handlers} 双层结构:定义层喂模型,执行层留宿主(桥到任意框架)。 * 语义契约(退出码是数据/终态三态/就绪握手)由内核承载,宿主零胶水。 * - * 第十季层族:执行类工具带可选 layer 参数(缺省=默认层——最近 push 的命名层; - * 未用层族时与旧行为一致,零破坏);push_ssh/push_into/list_layers/remove_layer - * 操作 RuntimeStack 命名层注册表(Paramiko 式句柄寻址——栈/焦点弱化归消费方)。 + * 工具面:run_batch / run_command / start_session / stop_session / + * observe_stream / close_stream / read_path / edit_file / manage_path / + * transfer_file / connect_layer / manage_layers */ import { randomUUID } from "node:crypto"; +import nodePath from "node:path"; import { StreamWindowRegistry, type StreamFrame } from "./stream-window.js"; import type { LayerHandle, RuntimeStack } from "./runtime-stack.js"; import { editFile } from "./file-edit.js"; @@ -47,7 +48,7 @@ function agentTransferResult({ writeMode, ...result }: LayerFileTransferResult): return { ...result, write_mode: writeMode }; } -export interface PushSshTarget { +export interface ConnectSshTarget { host: string; port?: number; user?: string; @@ -56,62 +57,137 @@ export interface PushSshTarget { name?: string; } -export interface PushSshResult { +export interface ConnectSshResult { layer: string; reused: boolean; reused_from?: string; note?: string; } -export interface PushSshBatchArgs { - targets: Array; +export interface ConnectSshBatchArgs { + targets: Array; } -export interface PushSshBatchResult { +export interface ConnectSshBatchResult { status: "ok" | "partial" | "fail"; active_layer?: string; layers: string[]; results: Array<{ host: string; name: string } & ( - ({ status: "ok" } & PushSshResult) | { status: "fail"; error: string } + ({ status: "ok" } & ConnectSshResult) | { status: "fail"; error: string } )>; } +export type ConnectIntoArgs = + | { enter_cmd: string; label?: string; from?: string; name?: string } + | { enter_command: string; label?: string; from?: string; name?: string } + | { enterCommand: string; label?: string; from?: string; name?: string } + | { enterCmd: string; label?: string; from?: string; name?: string }; + +export type PushSshTarget = ConnectSshTarget; +export type PushSshResult = ConnectSshResult; +export type PushSshBatchArgs = ConnectSshBatchArgs; +export type PushSshBatchResult = ConnectSshBatchResult; + +export interface ConnectIntoResult { + layer: string; + target?: string; +} + +export interface ObserveStreamResult { + window_id: string; + name?: string; + oldest_seq: number; + newest_seq: number; + stale: boolean; + frames: StreamFrame[]; + last_delivered_seq?: number; + gap?: boolean; + timed_out?: boolean; + exit_code?: number | null; + error?: string; +} + +export type ReadPathResult = + | { path: string; type: "file"; content: string; size: number; mtime_ms: number } + | { path: string; type: "directory"; entries: FileEntry[] }; + +export type AgentEditFileResult = + | { + mode: "edit"; + path: string; + occurrences: number; + bytes_before: number; + bytes_after: number; + mutex?: "flock" | "degraded"; + write_mode?: "atomic-replace" | "inplace-write"; + } + | { + mode: "write"; + path: string; + created: boolean; + bytes_after: number; + }; + +export type ManagePathResult = + | { action: "mkdir"; path: string; created: true } + | { action: "move"; path: string; destination: string; moved: true } + | { action: "delete"; path: string; deleted: true; recursive: boolean }; + +export type ManageLayersResult = + | { action: "list"; text: string; layers: Array<{ name: string; driver: string; target?: string }> } + | { action: "activate"; active_layer: string } + | { action: "remove"; removed: string }; + export interface AgentToolHandlers { run_command(args: { command: string; timeout_ms?: number; layer?: string }): Promise<{ 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<{ - path: string; occurrences: number; bytes_before: number; bytes_after: number; mutex?: "flock" | "degraded"; write_mode?: "atomic-replace" | "inplace-write"; - }>; - observe_stream(args: { command: string; stream?: "stdout" | "stderr" | "both"; name?: string; layer?: string }): Promise<{ - window_id: string; name?: string; stale: boolean; - }>; - read_stream(args: { window_id: string; limit?: number; since_seq?: number; before_seq?: number; window_ms?: number; wait_ms?: number }): Promise<{ - window_id: string; oldest_seq: number; newest_seq: number; stale: boolean; frames: StreamFrame[]; - last_delivered_seq?: number; gap?: boolean; timed_out?: boolean; exit_code?: number | null; error?: string; - }>; + read_path(args: { path: string; layer?: string }): Promise; + edit_file(args: { path: string; old: string; new: string; all?: boolean; write_mode?: "auto" | "inplace"; layer?: string }): Promise>; + edit_file(args: { path: string; content: string; overwrite?: boolean; create_dirs?: boolean; layer?: string }): Promise>; + manage_path(args: { action: "mkdir"; path: string; parents?: boolean; layer?: string }): Promise>; + manage_path(args: { action: "move"; path: string; destination: string; layer?: string }): Promise>; + manage_path(args: { action: "delete"; path: string; recursive?: boolean; layer?: string }): Promise>; + transfer_file(args: { direction: "put" } & AgentFilePutArgs): Promise; + transfer_file(args: { direction: "get" } & AgentFileTransferArgs): Promise; + observe_stream(args: { + command: string; stream?: "stdout" | "stderr" | "both"; name?: string; layer?: string; limit?: number; wait_ms?: number; + }): Promise; + observe_stream(args: { + window_id: string; limit?: number; since_seq?: number; before_seq?: number; window_ms?: number; wait_ms?: number; + }): Promise; close_stream(args: { window_id: string }): Promise<{ window_id: string; closed: true }>; + start_session(args: { command: string; ready_marker?: string; error_pattern?: string; name?: string; layer?: string }): Promise<{ + session_id: string; log_base: string; note?: string; + }>; + stop_session(args: { session_id: string; layer?: string }): Promise; + // ── 层族(命名层注册表——Paramiko 式句柄寻址)── + connect_layer(args: ConnectSshBatchArgs & Partial | "enter_cmd" | "enter_command" | "enterCommand" | "enterCmd" | "label" | "from", never>>): Promise; + connect_layer(args: ConnectSshTarget & { targets?: never } & Partial>): Promise; + connect_layer(args: ConnectIntoArgs & Partial | "targets", never>>): Promise; + manage_layers(args: { action: "list" }): Promise>; + manage_layers(args: { action: "activate"; name: string }): Promise>; + manage_layers(args: { action: "remove"; name: string; destroy?: boolean }): Promise>; + // ── 兼容 0.2.10 旧工具名直调(不进入 tools/list,仅 handlers/MCP call 适配器)── spawn_and_observe(args: { command: string; ready_marker?: string; error_pattern?: string; name?: string; layer?: string }): Promise<{ session_id: string; log_base: string; note?: string; }>; stop_and_verify(args: { session_id: string; layer?: string }): Promise; - // ── 层族(第十季命名层注册表——Paramiko 式句柄寻址)── - push_ssh(args: PushSshBatchArgs & Partial>): Promise; - push_ssh(args: PushSshTarget & { targets?: never }): Promise; - push_into(args: { enter_cmd: string; label?: string; from?: string; name?: string }): Promise<{ - layer: string; target?: string; - }>; - list_layers(args: Record): Promise<{ + 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; + read_stream(args: { window_id: string; limit?: number; since_seq?: number; before_seq?: number; window_ms?: number; wait_ms?: number }): Promise; + push_ssh(args: ConnectSshBatchArgs & Partial>): Promise; + push_ssh(args: ConnectSshTarget & { targets?: never }): Promise; + push_into(args: ConnectIntoArgs): Promise; + 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 轮次)── + // ── 批次组合(一次调用描述多原子操作——减少 Planner 轮次)── run_batch(args: { steps: Array>; stop_on_fail?: boolean; max_parallel?: number; layer?: BatchLayerTarget; output?: "text" | "full" }): Promise<{ status: "ok" | "fail"; failed_step?: string; steps: Array<{ @@ -151,21 +227,34 @@ const fileTransferProperties = { }; const layerNameSchema = { type: "string", minLength: 1, pattern: "\\S" }; +const nonEmptyPathSchema = { type: "string", minLength: 1, description: "目标层内的绝对路径或相对工作目录的路径" }; const layerPathParameters = { type: "object", additionalProperties: false, properties: { - path: { type: "string", minLength: 1, description: "目标层内的绝对路径或相对工作目录的路径" }, + path: nonEmptyPathSchema, layer: { ...layerNameSchema, description: "目标层名,省略时使用默认层" }, }, required: ["path"], }; +function assertValidPath(path: unknown, label = "path"): asserts path is string { + if (typeof path !== "string" || !path.length || path.includes("\0")) { + throw new Error(`${label} 需为不含 NUL 的非空路径`); + } +} + +function assertOptionalLayerName(layer: unknown): asserts layer is string | undefined { + if (layer !== undefined && (typeof layer !== "string" || !layer.trim())) { + throw new Error("layer 需为非空层名"); + } +} + 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 需为非空层名"); + assertValidPath(path); + assertOptionalLayerName(layer); return { path, layer }; } @@ -189,8 +278,39 @@ const sshTargetsSchema = { description: "按顺序尝试的目标。字符串可直接使用当前运行环境的 SSH 配置别名", items: { anyOf: [sshHostSchema, sshTargetSchema] }, }; +const enterLayerAliases = ["enter_cmd", "enter_command", "enterCommand", "enterCmd"] as const; +const enterLayerCommonProperties = { + label: { type: "string", description: "层显示标签" }, + from: { ...layerNameSchema, description: "源层名(缺省=默认层)" }, + name: { ...layerNameSchema, description: "层名(缺省=label)" }, +}; +const enterCmdSchemaProp = (description: string) => ({ + type: "string", + minLength: 1, + description, +}); +const enterLayerProperties = { + enter_cmd: enterCmdSchemaProp("进入内层环境命令,如 \"docker exec -i web sh\"(等价别名:enter_command / enterCommand / enterCmd)"), + enter_command: enterCmdSchemaProp("enter_cmd 的等价别名:进入内层环境命令"), + enterCommand: enterCmdSchemaProp("enter_cmd 的等价别名:进入内层环境命令"), + enterCmd: enterCmdSchemaProp("enter_cmd 的等价别名:进入内层环境命令"), + ...enterLayerCommonProperties, +}; +const enterLayerVariants = enterLayerAliases.map((key) => ({ + type: "object", + additionalProperties: false, + properties: { + [key]: enterCmdSchemaProp( + key === "enter_cmd" + ? "进入内层环境命令,如 \"docker exec -i web sh\"(等价别名:enter_command / enterCommand / enterCmd)" + : "enter_cmd 的等价别名:进入内层环境命令", + ), + ...enterLayerCommonProperties, + }, + required: [key], +})); -function sshConnection({ host, port, user, key, jump, name }: PushSshTarget) { +function sshConnection({ host, port, user, key, jump, name }: ConnectSshTarget) { const connParams = { ...(port != null ? { port: Number(port) } : {}), ...(user ? { user: String(user) } : {}), @@ -200,8 +320,8 @@ function sshConnection({ host, port, user, key, jump, name }: PushSshTarget) { return { host: String(host), name: name ?? String(host), connParams }; } -function sshBatchTargets(targets: PushSshBatchArgs["targets"]) { - if (!Array.isArray(targets) || !targets.length) throw new Error("push_ssh 的 targets 需为非空数组"); +function sshBatchTargets(targets: ConnectSshBatchArgs["targets"]) { + if (!Array.isArray(targets) || !targets.length) throw new Error("connect_layer 的 targets 需为非空数组"); const names = new Set(); return Array.from(targets, (entry, index) => { const raw = typeof entry === "string" ? { host: entry } : entry; @@ -241,21 +361,53 @@ const batchLayerSchema = (description: string) => ({ description, }); +const observeStreamOpenProperties = { + command: { type: "string", minLength: 1, description: "开窗模式:启动并持续观察流式输出的命令(如 'tail -f /var/log/app.log'),与 window_id 互斥" }, + stream: { type: "string", enum: ["stdout", "stderr", "both"], description: "开窗模式流过滤,缺省 both" }, + name: { type: "string", description: "开窗模式窗口显示名称" }, + layer: { ...layerNameSchema, description: "开窗模式目标层名,缺省使用默认层" }, +}; + +const observeStreamReadProperties = { + window_id: { type: "string", minLength: 1, description: "续读模式:由开窗返回的 window_id,与 command 互斥" }, + since_seq: { type: "integer", minimum: 0, description: "续读模式:读取此序号之后的帧(与 before_seq/window_ms 互斥)" }, + before_seq: { type: "integer", minimum: 0, description: "续读模式:读取此序号之前最近的帧(与 since_seq/window_ms 互斥)" }, + window_ms: { type: "integer", minimum: 0, description: "续读模式:回看最近多少毫秒内的帧(与 since_seq/before_seq 互斥)" }, +}; + +const observeStreamSharedProperties = { + limit: { type: "integer", minimum: 1, maximum: 200, description: "最多返回帧数,缺省 20" }, + wait_ms: { type: "integer", minimum: 0, maximum: 30000, description: "等待新增帧的毫秒数(开窗模式等首屏帧;续读模式仅用于 since_seq)" }, +}; + +const editFileCasProperties = { + path: nonEmptyPathSchema, + old: { type: "string", minLength: 1, description: "CAS 模式:待替换片段(含足够上下文保持唯一)" }, + new: { type: "string", description: "CAS 模式:替换后的新文本" }, + all: { type: "boolean", description: "CAS 模式:多处命中全替换(缺省 false,多处命中报错)" }, + write_mode: { type: "string", enum: ["auto", "inplace"], description: "CAS 模式:inplace=已知 bind mount 挂载环境显式请求保留 inode 写(跳过 mv 失败尝试)" }, + layer: { ...layerNameSchema, description: "目标层名(缺省=默认层)" }, +}; + +const editFileWriteProperties = { + path: nonEmptyPathSchema, + content: { type: "string", description: "写入模式:直接写入或新建的完整 UTF-8 文本(支持空字符串创建空文件)" }, + overwrite: { type: "boolean", description: "写入模式:目标已存在时是否允许覆写(缺省 false——防止误覆盖)" }, + create_dirs: { type: "boolean", description: "写入模式:父目录不存在时是否自动递归创建(缺省 false)" }, + layer: { ...layerNameSchema, description: "目标层名(缺省=默认层)" }, +}; + /** 工具定义单一来源(REQ-0003 MCP tools/list 同源序列化——零漂移) */ export const TOOL_DEFS: AgentToolDef[] = [ - // run_batch 置顶(第十三季黑盒实测:Lazy schema 按序读 6 个基础 - // .json 就动手——run_batch 排第 7 被漏读,排查期连续 6 步串行 read_file - // 单文件 89s/次。排序即发现面:高杠杆批处理工具必须在懒加载首屏) + // run_batch 置顶(第十三季黑盒实测:Lazy schema 按序读前几个 .json 就动手,高杠杆批处理工具必须在首屏) { type: "function", function: { name: "run_batch", description: - "批次组合:一次调用描述多个文件或命令操作(exec/edit/read/put/get),按依赖边(after)拓扑执行——" + - "批次与步骤 layer 均支持层名或层名数组。多个层名按 id@layer 展开,单个层名保留原 id;kind=get 只接受单层。" + - "after 引用计划中声明的步骤 id,等待该步骤在所有目标层成功。" + - "无依赖步骤并行,顺序链靠 after 显式保序;默认任一步失败即停(未启动步骤标 skipped)。返回逐步骤状态与证据(退出码/输出/编辑明细)。" + - "**不做自动回滚**(配置恢复≠运行状态回滚——重载可能已产生外部副作用),失败现场交回调用方决策。", + "编排并执行多步骤文件或命令 DAG(exec/edit/read/put/get),支持按 layer 数组跨多层并行扇出。" + + "单步操作请使用专用工具(run_command、read_path、edit_file、transfer_file);多步骤依赖、批量读取/修改或多层同发请使用本工具。" + + "无 after 依赖的步骤并行,顺序链靠 after 显式保序;默认任一步失败即停(未启动步骤标 skipped),**不做自动回滚**。", parameters: { type: "object", additionalProperties: false, @@ -297,7 +449,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ }, stop_on_fail: { type: "boolean", description: "失败即停(缺省 true)" }, max_parallel: { type: "number", description: "并行度上限(缺省 3)" }, - layer: batchLayerSchema("批次默认目标层名或层名数组(缺省=调用时的默认层;传数组时未覆盖 layer 的步骤自动展开到各层并行执行)"), + layer: batchLayerSchema("批次默认目标层名或层名数组(缺省=默认层;传数组时未覆盖 layer 的步骤自动展开到各层并行执行)"), output: { type: "string", enum: ["text", "full"], description: "MCP 输出模式。text 适合只读文本块的客户端,保留简短预览;full(默认)另在 structuredContent 保留完整输出" }, }, required: ["steps"], @@ -309,15 +461,15 @@ export const TOOL_DEFS: AgentToolDef[] = [ function: { name: "run_command", description: - "执行会自行结束的一次性命令(多条命令或多文件操作请用 run_batch;同一命令发往多个层时可传 layer 数组;" + - "持续盯实时输出且不关心退出码的命令如 tail -f 请改用 observe_stream 直接启动并流式读取;" + - "需后台起停服务、等就绪标记并核实进程退出码的任务请改用 spawn_and_observe)。" + - "退出码如实返回(非零不是异常——是数据,供条件分支);只有无法执行(超时/中断/连接死)才报错。stdout 与 stderr 分离返回。", + "在单层执行会自行结束的一次性命令,物理分离返回 stdout、stderr 与 exit_code。" + + "多命令、多文件或跨多层同发请用 run_batch;持续实时流(如 tail -f)请用 observe_stream;后台常驻服务启停请用 start_session 与 stop_session;" + + "标准文件与目录操作请优先用 read_path、edit_file、manage_path、transfer_file。" + + "非零 exit_code 作为数据正常返回不报错;仅超时、中断或连接异常导致终态未知时报错。", parameters: { type: "object", additionalProperties: false, properties: { - command: { ...layerNameSchema, description: "shell 命令" }, + command: { ...layerNameSchema, description: "会自行结束的 shell 命令" }, timeout_ms: { type: "number", description: "超时毫秒(缺省 120000)" }, layer: { ...layerNameSchema, description: "目标层名,省略时使用当前默认层" }, }, @@ -328,12 +480,12 @@ export const TOOL_DEFS: AgentToolDef[] = [ { type: "function", function: { - name: "spawn_and_observe", + name: "start_session", description: - "管理后台任务或服务的进程生命周期。需要等待服务就绪、按错误模式停止或核实退出码时使用本工具。" + - "输出写入 log_base 对应的 .out/.err 文件。省略 ready_marker 时,启动后返回 session_id 和 log_base。" + - "提供 ready_marker 时,先回溯近期输出并等待标记,确认就绪后返回;超时或进程提前退出时报告错误。" + - "用 stop_and_verify 停止会话并核实终态。持续查看日志可用 observe_stream 开窗。", + "启动后台长跑任务或服务并落盘输出到 log_base(.out/.err),支持就绪握手与错误触发停机。" + + "需要启动后台服务、等待 ready_marker 就绪、按 error_pattern 停机或稍后用 stop_session 核实退出码时使用;" + + "会自行结束的命令用 run_command,临时实时盯日志用 observe_stream。" + + "省略 ready_marker 时立即返回 session_id 与 log_base;提供 ready_marker 时轮询热窗口至就绪后返回,超时或早退时附带终态线索报错。", parameters: { type: "object", properties: { @@ -350,15 +502,16 @@ export const TOOL_DEFS: AgentToolDef[] = [ { type: "function", function: { - name: "stop_and_verify", + name: "stop_session", description: - "停止任务并核实终态。status 三态:exited=拿到退出码;stopped=终止已核实;" + - "unknown=终态证据不足。可用完整 session_id 和原目标层再次核实,或上报结果未知。", + "停止由 start_session 启动的后台会话并核实远端终态。" + + "返回三态 status:exited(已确认退出码)、stopped(终止已核实)或 unknown(终态证据不足,禁止推定已停止)。" + + "返回 unknown 时可持完整 session_id 与原目标 layer 再次调用核实;会话归属未知或已过期时需显式传 layer(初始层用 __initial__)。", parameters: { type: "object", additionalProperties: false, properties: { - session_id: { ...layerNameSchema, description: "spawn_and_observe 返回的完整 session_id" }, + session_id: { ...layerNameSchema, description: "start_session 返回的完整 session_id" }, layer: { ...layerNameSchema, description: "外部会话或归属已过期时指定原目标层,初始层用 __initial__" }, }, required: ["session_id"], @@ -368,151 +521,184 @@ export const TOOL_DEFS: AgentToolDef[] = [ { type: "function", function: { - name: "read_file", - description: - "只读获取目标层中的 UTF-8 文本文件(不修改远端状态),返回 { path, content, size, mtime_ms }。" + - "MCP 文本块显示正文,超限时显示带截断标记的预览。文件不存在、无权限或层不支持元数据时报错。" + - "下载二进制文件用 get_file,多文件读取用 run_batch,受控修改用 edit_file。", - parameters: layerPathParameters, - }, - }, - { - type: "function", - function: { - name: "list_directory", - description: "列出目标层目录的直接子项,含隐藏项、名称和目录标志。可用时返回文件大小和修改时间。目录不存在或读取失败时报错。", - parameters: layerPathParameters, - }, - }, - { - type: "function", - function: { - name: "delete_file", - description: "永久删除目标层的一个文件或符号链接本身。拒绝目录和递归删除。目标不存在时报错;连接中断且终态未知时请先核实,再决定是否重试。", - parameters: layerPathParameters, - }, - }, - { - type: "function", - function: { - name: "edit_file", + name: "observe_stream", description: - "对目标层的 UTF-8 文本做字面替换。Compare-and-Swap(CAS)在写回前比较文件的修改时间、大小和内容指纹,版本冲突时拒绝写回。" + - "默认要求 old 唯一命中,all=true 时替换所有匹配。返回 mutex 和 write_mode。atomic-replace 表示原子替换," + - "inplace-write 表示保留 inode 原地写入,中断可能留下部分内容。", + "启动实时日志/事件流观察窗(传 command,可选 wait_ms 直接带回首屏帧)或按游标续读/回看既有窗口(传 window_id)。" + + "适合 tail -f 等持续流式观察;需要后台服务就绪握手与退出码核实时改用 start_session。观察完毕请调用 close_stream 回收流进程。" + + "续读用 last_delivered_seq 配合 since_seq,向前翻页用 before_seq,时间回看用 window_ms;gap=true 表示中间有帧已被环形覆盖。", parameters: { type: "object", - additionalProperties: false, properties: { - 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 失败尝试)" }, - layer: { type: "string", description: "目标层名(缺省=默认层)" }, + ...observeStreamOpenProperties, + ...observeStreamReadProperties, + ...observeStreamSharedProperties, }, - required: ["path", "old", "new"], + oneOf: [ + { + type: "object", + additionalProperties: false, + properties: { ...observeStreamOpenProperties, ...observeStreamSharedProperties }, + required: ["command"], + }, + { + type: "object", + additionalProperties: false, + properties: { ...observeStreamReadProperties, ...observeStreamSharedProperties }, + required: ["window_id"], + }, + ], }, }, }, { type: "function", function: { - name: "put_file", - description: "从 MCP 服务所在机器上传一个文件到目标层。支持二进制,校验后落位,可能覆盖目标文件。返回校验等级和写入形态。", + name: "close_stream", + description: + "关闭由 observe_stream 打开的本地观察窗,确认终止并回收对应的远端观察流进程与通道资源,返回 { window_id, closed: true }。" + + "流观察完成后应及时调用以防残留进程;若 window_id 不存在或已关闭则报错(不影响其他观察窗)。", parameters: { type: "object", additionalProperties: false, - properties: { - ...fileTransferProperties, - write_mode: { type: "string", enum: ["auto", "inplace"], description: "缺省 auto。inplace 保留目标 inode" }, - }, - required: ["local_path", "remote_path"], + properties: { window_id: { type: "string", minLength: 1, description: "由 observe_stream 返回的观察窗 ID" } }, + required: ["window_id"], }, }, }, { type: "function", function: { - name: "get_file", + name: "read_path", description: - "从目标层下载单个文件到 MCP 服务所在机器(支持二进制)。始终校验大小,目标层支持 SHA-256 时再校验摘要。请用 verification 区分 sha256 与 size。" + - "通过校验后才落位,校验失败不破坏已有本地文件。" + - "成功时会覆盖已存在的 local_path,返回传输通道、字节大小、校验等级 (verification) 与写入形态 (write_mode)。" + - "仅读取远端小文本请用 read_file,批量传输多个文件请使用 run_batch。", - parameters: { - type: "object", - additionalProperties: false, - properties: fileTransferProperties, - required: ["local_path", "remote_path"], - }, + "只读查看目标层中的路径(不修改远端状态):若为文件返回 UTF-8 文本与元数据 { path, type: 'file', content, size, mtime_ms };" + + "若为目录返回直接子项列表 { path, type: 'directory', entries }(含名称、目录标志及可用时的大小/修改时间)。" + + "下载二进制文件用 transfer_file(direction='get'),批量读取多个文件用 run_batch,创建或编辑文本用 edit_file。", + parameters: layerPathParameters, }, }, { type: "function", function: { - name: "observe_stream", + name: "edit_file", description: - "实时查看日志或事件流,例如 tail -f。启动观察命令并立即返回滚动窗口的 window_id。" + - "用 read_stream 按游标回看或续读,用 close_stream 关闭窗口并回收观察命令。" + - "启动和管理后台服务的进程生命周期请用 spawn_and_observe。", + "在目标层做受控 CAS 文本替换(传 old + new)或直接新建/写入完整 UTF-8 文本文件(传 content)。" + + "CAS 模式在写回前校验修改时间、大小与内容指纹(冲突报 EditConflictError),默认要求 old 唯一命中(all=true 全替换),并报告 mutex 与 write_mode;" + + "写入模式默认 overwrite=false 防止误覆盖已有文件,可选 create_dirs=true 自动建父目录。" + + "多文件或同一文件多处并发编辑用 run_batch(kind='edit'),二进制传输用 transfer_file。", parameters: { type: "object", properties: { - command: { type: "string", minLength: 1, description: "由本工具启动并持续观察流式输出的命令(如 'tail -f /var/log/app.log')" }, - stream: { type: "string", enum: ["stdout", "stderr", "both"], description: "流过滤,缺省 both" }, - name: { type: "string", description: "窗口显示名称" }, - layer: { type: "string", description: "目标层名,缺省使用默认层" }, + ...editFileCasProperties, + ...editFileWriteProperties, }, - required: ["command"], + oneOf: [ + { + type: "object", + additionalProperties: false, + properties: editFileCasProperties, + required: ["path", "old", "new"], + }, + { + type: "object", + additionalProperties: false, + properties: editFileWriteProperties, + required: ["path", "content"], + }, + ], }, }, }, { type: "function", function: { - name: "read_stream", - description: "读取本地观察窗的日志帧。可读最近帧、按 before_seq 向前翻页、按 window_ms 回看或按 since_seq 续读。" + - "续读用 last_delivered_seq,向前翻页用 first_frame_seq 或本页首帧号。使用当前结果格式里的游标,gap 表示有帧缺失。", + name: "manage_path", + description: + "管理目标层内的目录与路径生命周期:创建目录(action='mkdir',默认 parents=true)、移动/重命名路径(action='move',需 destination)" + + "或删除路径(action='delete')。" + + "delete 默认 recursive=false 仅删单文件或符号链接本身并拒绝目录;传 recursive=true 可递归删除目录,并前置拒绝根目录、当前工作目录及上级路径。", parameters: { type: "object", properties: { - window_id: { type: "string", minLength: 1 }, - limit: { type: "integer", minimum: 1, maximum: 200, description: "最多返回帧数,缺省 20" }, - since_seq: { type: "integer", minimum: 0, description: "读取此序号之后的帧" }, - before_seq: { type: "integer", minimum: 0, description: "读取此序号之前最近的帧" }, - window_ms: { type: "integer", minimum: 0, description: "回看最近多少毫秒" }, - wait_ms: { type: "integer", minimum: 0, maximum: 30000, description: "续读等待新增帧的毫秒数,仅用于 since_seq" }, + action: { type: "string", enum: ["mkdir", "move", "delete"], description: "路径操作类型" }, + path: nonEmptyPathSchema, + parents: { type: "boolean", description: "action=mkdir:不存在时自动创建上级目录(缺省 true)" }, + destination: { type: "string", minLength: 1, description: "action=move:目标路径" }, + recursive: { type: "boolean", description: "action=delete:递归删除目录(缺省 false——安全起见默认拒绝目录)" }, + layer: { ...layerNameSchema, description: "目标层名,省略时使用默认层" }, }, - required: ["window_id"], + oneOf: [ + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "mkdir" }, + path: nonEmptyPathSchema, + parents: { type: "boolean", description: "不存在时自动创建上级目录(缺省 true)" }, + layer: { ...layerNameSchema, description: "目标层名,省略时使用默认层" }, + }, + required: ["action", "path"], + }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "move" }, + path: nonEmptyPathSchema, + destination: { type: "string", minLength: 1, description: "移动或重命名后的目标路径" }, + layer: { ...layerNameSchema, description: "目标层名,省略时使用默认层" }, + }, + required: ["action", "path", "destination"], + }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "delete" }, + path: nonEmptyPathSchema, + recursive: { type: "boolean", description: "是否递归删除目录(缺省 false)" }, + layer: { ...layerNameSchema, description: "目标层名,省略时使用默认层" }, + }, + required: ["action", "path"], + }, + ], }, }, }, { type: "function", function: { - name: "close_stream", + name: "transfer_file", description: - "关闭由 observe_stream 打开的本地观察窗,确认终止并回收对应的远端观察流进程与通道资源,返回 { window_id, closed: true }。" + - "观察完成后应及时调用以防残留流进程;若 window_id 不存在或已关闭则报错(不影响其他观察窗)。", + "在 MCP 服务所在主机与目标层之间上传(direction='put')或下载(direction='get')单个文件(支持二进制)。" + + "传输始终先校验大小,目标层支持 SHA-256 时再校验摘要(返回 verification 区分 sha256 与 size);校验通过后才落位并覆盖目标文件。" + + "仅查看文本内容用 read_path,新建/修改文本用 edit_file,批量传输多文件用 run_batch(kind='put'|'get')。", parameters: { type: "object", - properties: { window_id: { type: "string", minLength: 1, description: "由 observe_stream 返回的观察窗 ID" } }, - required: ["window_id"], + additionalProperties: false, + properties: { + direction: { type: "string", enum: ["put", "get"], description: "put=本地上传到目标层;get=从目标层下载到本地" }, + ...fileTransferProperties, + write_mode: { type: "string", enum: ["auto", "inplace"], description: "仅 direction=put 有效,缺省 auto。inplace 保留目标 inode" }, + }, + required: ["direction", "local_path", "remote_path"], }, }, }, { type: "function", function: { - name: "push_ssh", + name: "connect_layer", description: - "建立命名 SSH 层。单个目标传 host,批量传 targets(主机、SSH 配置别名或连接对象的数组)。" + - "批量按输入顺序尝试,返回各目标结果。layers 非空时可直接传给 run_batch。新建层成为默认层。" + - "同落点可复用,结果中的 layer 是实际层名。跳板传 jump。", + "建立并激活命名执行层:单台 SSH(传 host,可带 port/user/key/jump/name)、批量 SSH(传 targets 数组,按顺序建连并返回可用于 run_batch 的 layers)," + + "或从既有源层进入内层容器/Shell(传 enter_cmd,如 'docker exec -i web sh',全量继承追加 enter 管线)。" + + "SSH 同落点可幂等复用既有层,新建或复用后成为默认层;查询、切换或移出层请用 manage_layers。", parameters: { type: "object", - properties: { ...sshTargetSchema.properties, targets: sshTargetsSchema }, + properties: { + ...sshTargetSchema.properties, + targets: sshTargetsSchema, + ...enterLayerProperties, + }, oneOf: [ sshTargetSchema, { @@ -521,6 +707,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ properties: { targets: sshTargetsSchema }, required: ["targets"], }, + ...enterLayerVariants, ], }, }, @@ -528,57 +715,46 @@ export const TOOL_DEFS: AgentToolDef[] = [ { type: "function", function: { - name: "push_into", + name: "manage_layers", description: - "从默认层(或 from 指定层)进入内层 shell(docker exec -i sh / kubectl exec 等)——" + - "enter 管线全量继承追加(父层 docker→再 su 不丢)。新层成为默认层。需 ssh 层为源。", - parameters: { - type: "object", - properties: { - enter_cmd: { type: "string", description: "进入命令,如 \"docker exec -i web sh\"(别名 enterCommand/enter_command/enterCmd 等价)" }, - label: { type: "string", description: "层显示标签" }, - from: { type: "string", description: "源层名(缺省=默认层)" }, - name: { type: "string", description: "层名(缺省=label)" }, - }, - required: ["enter_cmd"], - }, - }, - }, - { - type: "function", - function: { - name: "list_layers", - description: - "列出全部命名层(链路/状态/有效用户/默认层标记)。死层/退化层有警示标注(removeLayer 后按原参数重建)。", - 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: { - name: "remove_layer", - description: - "移出命名层(缺省连接保留在指纹缓存——再建同层零成本;destroy=true 才真销毁连接)。", + "查询、切换或移除已注册命名层:action='list' 列出全部命名层及链路/状态/有效用户/默认标记;" + + "action='activate' 将指定 name 设为默认层(保留所有连接);" + + "action='remove' 移出指定层(缺省保留连接在指纹缓存以便零成本重建,传 destroy=true 才真销毁连接)。" + + "新建 SSH 或进入内层环境请用 connect_layer。", parameters: { type: "object", properties: { - name: { type: "string", description: "层名" }, - destroy: { type: "boolean", description: "真销毁连接(缺省 false=保留可复用)" }, + action: { type: "string", enum: ["list", "activate", "remove"], description: "层管理操作" }, + name: { ...layerNameSchema, description: "目标层名(action=activate/remove 时必填)" }, + destroy: { type: "boolean", description: "action=remove:是否真销毁底层连接(缺省 false=保留可复用)" }, }, - required: ["name"], + oneOf: [ + { + type: "object", + additionalProperties: false, + properties: { action: { type: "string", const: "list" } }, + required: ["action"], + }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "activate" }, + name: { ...layerNameSchema, description: "已注册的层名" }, + }, + required: ["action", "name"], + }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "remove" }, + name: { ...layerNameSchema, description: "待移出的层名" }, + destroy: { type: "boolean", description: "真销毁连接(缺省 false=保留可复用)" }, + }, + required: ["action", "name"], + }, + ], }, }, }, @@ -586,8 +762,8 @@ export const TOOL_DEFS: AgentToolDef[] = [ /** 生成 Agent 工具集(定义层 + 执行层;宿主桥接到任意 LLM 框架) */ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOptions = {}): AgentToolkit { - // 初始层(Hydrogen R7 #4):descriptor 形态注册进命名表(list_layers 可见、 - // push_into 无 from 时 activeLayer 有源)+ 失败不缓存(rejected Promise 永久 + // 初始层(Hydrogen R7 #4):descriptor 形态注册进命名表(manage_layers list 可见、 + // connect_layer enter_cmd 无 from 时 activeLayer 有源)+ 失败不缓存(rejected Promise 永久 // 复用=不自愈;每次工具调用重连)。driver 直注形态不注册(外部生命周期) const INITIAL_LAYER_NAME = "__initial__"; let layerPromise: Promise | undefined; @@ -635,18 +811,26 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption }, }; }; - function pushSsh(args: PushSshTarget & { targets?: never }): Promise; - function pushSsh(args: PushSshBatchArgs & Partial>): Promise; - async function pushSsh(args: PushSshTarget | PushSshBatchArgs): Promise { - if (!("targets" in args)) { + const connectSshLayer = async (args: Record) => { + if (args.from !== undefined || args.label !== undefined) { + throw new Error("connect_layer 的 SSH 模式不支持 from 或 label(仅 enter_cmd 模式使用)"); + } + if (args.targets === undefined) { + const unknown = Object.keys(args).filter((k) => !Object.hasOwn(sshTargetSchema.properties, k)); + if (unknown.length) throw new Error(`connect_layer 未知参数:${unknown.join(", ")}`); if (typeof args.host !== "string" || !args.host.trim()) { - throw new Error("push_ssh 需提供单目标 host 或批量 targets"); + throw new Error("connect_layer 需提供 host(单台 SSH)、targets(批量 SSH)或 enter_cmd(进入内层)"); + } + if (args.port !== undefined && (!Number.isInteger(args.port) || (args.port as number) < 1 || (args.port as number) > 65535)) { + throw new Error("port 需为 1 到 65535 的整数"); } - return (await connectSsh(sshConnection(args))).result; + return (await connectSsh(sshConnection(args as unknown as ConnectSshTarget))).result; + } + if (Object.keys(args).some((key) => key !== "targets" && args[key] !== undefined)) { + throw new Error("connect_layer 的 targets 必须单独提供"); } - if (Object.keys(args).some((key) => key !== "targets")) throw new Error("push_ssh 的 targets 必须单独提供"); - const targets = sshBatchTargets(args.targets); - const results: PushSshBatchResult["results"] = []; + const targets = sshBatchTargets(args.targets as ConnectSshBatchArgs["targets"]); + const results: ConnectSshBatchResult["results"] = []; const connected = new Map(); let failures = 0; // Serial registration preserves RuntimeStack's landing reuse and default-layer order. @@ -678,11 +862,46 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption layers: [...layers], results, }; - } + }; + const connectIntoLayer = async (args: Record, presentEnterKeys: readonly string[]): Promise => { + if (presentEnterKeys.length > 1) { + throw new Error(`connect_layer 只能传一个进入命令参数(不要同时传 ${presentEnterKeys.join("、")})`); + } + const sshKeys = ["host", "targets", "port", "user", "key", "jump"]; + const conflicting = sshKeys.filter((k) => args[k] !== undefined); + if (conflicting.length) { + throw new Error(`connect_layer 的内层进入模式(enter_cmd)与 SSH 参数互斥:${conflicting.join(", ")}`); + } + const enterAllowed = new Set([...enterLayerAliases, "label", "from", "name"]); + const unknown = Object.keys(args).filter((k) => !enterAllowed.has(k)); + if (unknown.length) throw new Error(`connect_layer 内层进入模式未知参数:${unknown.join(", ")}`); + const enterKey = presentEnterKeys[0]; + const enterCmd = enterKey && typeof args[enterKey] === "string" && (args[enterKey] as string).trim() + ? (args[enterKey] as string) + : undefined; + if (!enterCmd) { + throw new Error("connect_layer 的 enter_cmd 需为非空命令字符串(别名 enterCommand/enter_command/enterCmd 均可)"); + } + const label = args.label as string | undefined; + const from = args.from as string | undefined; + const name = args.name as string | undefined; + if (label !== undefined && typeof label !== "string") throw new Error("label 需为字符串"); + assertOptionalLayerName(from); + assertOptionalLayerName(name); + const srcName = from ?? stack.activeLayer?.name; + if (!srcName) throw new Error("无源层——先用 connect_layer 建立 SSH 层,或显式传 from"); + const h = await stack.layerInto(srcName, name ?? label ?? enterCmd.slice(0, 30), enterCmd, { label }); + return { layer: h.name, target: h.descriptor.target }; + }; + const connectLayer: AgentToolHandlers["connect_layer"] = (async (args: Record) => { + const presentEnterKeys = enterLayerAliases.filter((k) => args[k] !== undefined); + if (presentEnterKeys.length > 0) return await connectIntoLayer(args, presentEnterKeys); + return await connectSshLayer(args); + }) as unknown as AgentToolHandlers["connect_layer"]; const transferFile = async (operation: "put" | "get", args: AgentFilePutArgs): Promise => { const { local_path, remote_path, layer: layerName, transport, timeout_ms, write_mode, ...unknownFields } = args; const extra = Object.keys(unknownFields); - if (extra.length) throw new Error(`${operation}_file 未知参数:${extra.join(", ")}`); + if (extra.length) throw new Error(`transfer_file 未知参数:${extra.join(", ")}`); if (layerName !== undefined && (typeof layerName !== "string" || !layerName.trim())) throw new Error("layer 需为非空字符串"); const fields = { localPath: local_path, remotePath: remote_path, transport, timeoutMs: timeout_ms, writeMode: write_mode }; validateFileTransferFields(operation, fields); @@ -696,6 +915,28 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption if (!window || window.closed) throw new Error(`观察窗 '${windowId}' 不存在或已关闭`); return window; }; + const formatStreamResult = ( + window_id: string, + result: { + oldestSeq: number; newestSeq: number; stale: boolean; + frames: StreamFrame[]; exitCode?: number | null; error?: string; + lastDeliveredSeq?: number; gap?: boolean; + }, + wait_ms: number, + name?: string, + ): ObserveStreamResult => ({ + window_id, + ...(name ? { name } : {}), + oldest_seq: result.oldestSeq, + newest_seq: result.newestSeq, + stale: result.stale, + frames: result.frames, + ...(result.exitCode !== undefined ? { exit_code: result.exitCode } : {}), + ...(result.error !== undefined ? { error: result.error } : {}), + ...(result.lastDeliveredSeq !== undefined ? { last_delivered_seq: result.lastDeliveredSeq } : {}), + ...(result.gap ? { gap: true } : {}), + ...(wait_ms > 0 && !result.frames.length && !result.gap && !result.stale ? { timed_out: true } : {}), + }); const sessionOwner = new SessionOwnership( opts.sessionResultTtlMs ?? 60_000, opts.sessionCheckIntervalMs ?? 5_000, @@ -744,6 +985,151 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption } throw mk("unknown", `${stillRunningNote ?? "停止结果未知(停止/核实通道均不可确认)"}${causeNote}`); }; + const startSession: AgentToolHandlers["start_session"] = async ({ command, ready_marker, error_pattern, name, layer: layerName }) => { + const drv = await resolveDrv(layerName); + const h = await drv.execSession(command, name ? { name } : undefined); + sessionOwner.track(h.sessionId, drv); // 归属记录(stop_session 按此寻层) + // 启动后异常统一走 postLaunchFail(三十五期 P1 + 三十六期提取共享) + if (error_pattern) { + try { + drv.watchSession(h.sessionId, { pattern: error_pattern, once: false, thenStop: true }); + } catch (err) { + await postLaunchFail(drv, h, "错误监听注册失败", err); + } + } + let note: string | undefined; + if (ready_marker) { + // 就绪握手(回溯热窗口——快输出进程竞态安全)。超时/轮询失败统一走 + // postLaunchFail(三十四期超时诚实三态 + 三十五/三十六期共享收口) + const t0 = Date.now(); + let ticks = 0; + for (;;) { + let lines: string[]; + try { + lines = await drv.tailSession(h.sessionId, 50); + } catch (err) { + await postLaunchFail(drv, h, "ready 轮询失败(tailSession 抛错)", err); + } + if (lines!.some((l) => l.includes(ready_marker))) { note = "ready"; break; } + if (Date.now() - t0 > readyTimeoutMs) { + await postLaunchFail(drv, h, `ready 超时(${readyTimeoutMs}ms 未见 '${ready_marker}')`); + } + // 崩溃快速失败(Hydrogen R3 #7):命令启动即崩(参数/配置错)曾 + // 空轮询整个 readyTimeoutMs 才报超时——每 10 轮(~1s)核实一次 + // 会话状态,已退出即带真实退出码走 postLaunchFail + if (++ticks % 10 === 0) { + const verified = await Promise.resolve() + .then(() => drv.verifySession(h.sessionId)) + .catch(() => undefined); + if (verified?.status === "exited" && Number.isSafeInteger(verified.exitCode)) { + sessionOwner.remember(h.sessionId, { status: "exited", exit_code: verified.exitCode }); + throw Object.assign(new Error( + `进程已退出(exitCode=${verified.exitCode}),未见 ready 标记 '${ready_marker}'`, + ), { outcome: "exited", exitCode: verified.exitCode, sessionId: h.sessionId, logBase: h.logBase }); + } + } + await new Promise((r) => setTimeout(r, 100)); + } + } + return { session_id: h.sessionId, log_base: h.logBase, note }; + }; + const stopSession: AgentToolHandlers["stop_session"] = async ({ session_id, layer: layerName, ...extra }) => { + if (Object.keys(extra).length) throw new Error("stop_session 只接受 session_id 和 layer"); + if (typeof session_id !== "string" || !session_id.trim()) throw new Error("session_id 需为完整的非空会话 ID"); + if (layerName !== undefined && (typeof layerName !== "string" || !layerName.trim())) { + throw new Error("layer 需为非空层名"); + } + // 归属寻层(GPT Astra 二轮 #3 / 三轮 #1 / 四轮 #1):spawn 在远端层的会话回该层停。 + // unknown 时自动接一次 verifySession 核实原语(DeepSeek 评审追问的 unknown 闭环)—— + // stop 的 unknown 是「停止瞬间核实不可达」,verify 是延迟后的独立探测通道。 + // 停止通道抛错也归 unknown 继续 verify(三十七期 #2:旧形态 await + // 直接抛出——后面的 verify 根本不执行,裸抛无 unknown 标记) + const entry = sessionOwner.get(session_id); + if (entry && "result" in entry) return { ...entry.result }; + if (!entry && !layerName) { + return { status: "unknown", note: "会话归属未知或已过期,verify 需要显式指定 layer" }; + } + const drv = entry && "driver" in entry + ? entry.driver + : layerName === INITIAL_LAYER_NAME ? await layer() : stack.layer(layerName!).driver; + let r: { status?: string; exitCode?: number | null }; + try { + r = await drv.stopSession(session_id); + } catch { + r = { status: "unknown", exitCode: null }; // 停止通道失败——归 unknown 走 verify + } + let status: "exited" | "stopped" | "unknown" = r.status === "stopped" ? "stopped" + : r.status !== "unknown" && Number.isSafeInteger(r.exitCode) ? "exited" : "unknown"; + let exitCode = r.exitCode; + let stillRunningNote: string | undefined; + if (status === "unknown") { + try { + const v = await drv.verifySession(session_id); + if (v.status === "exited" && Number.isSafeInteger(v.exitCode)) { status = "exited"; exitCode = v.exitCode; } + else if (v.status === "running") { + stillRunningNote = "进程实测仍在运行(stop 未生效——不可中断态或权限不足)"; + } + } catch { /* verify 不可达——保持 unknown */ } + } + if (status !== "unknown") { + const result: StopResult = status === "exited" + ? { status, exit_code: exitCode } + : { status, note: "终止已核实" }; + sessionOwner.remember(session_id, result); + return result; + } + return { + status: "unknown", + note: stillRunningNote ?? "未取得可核实的终态。重连后,用完整 session_id 和原目标层再次调用 stop_session,或上报结果未知。", + }; + }; + const readStreamWindow = async (args: Record): Promise => { + const { window_id, limit = 20, since_seq, before_seq, window_ms, wait_ms = 0, ...extra } = args as { + window_id: unknown; limit?: unknown; since_seq?: unknown; before_seq?: unknown; window_ms?: unknown; wait_ms?: unknown; + [key: string]: unknown; + }; + if (extra.stream !== undefined || extra.layer !== undefined || extra.name !== undefined || extra.command !== undefined) { + throw new Error("observe_stream 续读模式不支持 command、stream、name 或 layer;请仅传 window_id 及读取游标参数"); + } + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`observe_stream 续读模式未知参数:${unknown.join(", ")}`); + if ([since_seq, before_seq, window_ms].filter((value) => value !== undefined).length > 1) { + throw new Error("since_seq、before_seq 和 window_ms 互斥"); + } + for (const value of [since_seq, before_seq, window_ms, wait_ms]) { + if (value !== undefined && (!Number.isSafeInteger(value) || (value as number) < 0)) { + throw new Error("观察窗的游标和时长需要非负整数"); + } + } + if (!Number.isSafeInteger(limit) || (limit as number) < 1 || (limit as number) > 200) throw new Error("limit 须在 1–200 之间"); + const waitMs = wait_ms as number; + const maxFrames = limit as number; + if (waitMs > 30000 || (waitMs > 0 && since_seq === undefined)) { + throw new Error("wait_ms 仅用于续读,且最大为 30000"); + } + const window = requireWindow(window_id as string); + const deadline = Date.now() + waitMs; + const read = () => since_seq !== undefined ? window.peekSince(since_seq as number, maxFrames) + : before_seq !== undefined ? window.peekBefore(before_seq as number, maxFrames) + : window_ms !== undefined ? window.peekWindow(window_ms as number, maxFrames) + : window.peekLast(maxFrames); + let result = read(); + while (since_seq !== undefined && !result.frames.length && !result.gap && !result.stale && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(50, deadline - Date.now())))); + requireWindow(window_id as string); + result = read(); + } + return formatStreamResult(window_id as string, result, waitMs); + }; + const deleteSingleFile = async (path: string, drv: RuntimeDriver) => { + const isWinLocal = drv.descriptor.driver === "local" && process.platform === "win32"; + const stripped = isWinLocal ? path.replace(/[/\\]+$/, "") : path.replace(/\/+$/, ""); + if (!stripped || /(?:^|\/)\.{1,2}$|\/$/.test(path) + || (isWinLocal && /(?:^|\\)\.{1,2}$|\\$/.test(path))) { + throw new Error("非递归删除需要单文件路径"); + } + await drv.fs.rm(path, { recursive: false, force: false }); + }; return { tools: TOOL_DEFS, @@ -766,182 +1152,297 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption effective_user: r.effectiveUser, }; }, - async spawn_and_observe({ command, ready_marker, error_pattern, name, layer: layerName }) { + start_session: startSession, + async read_path(args) { + const { path, layer: layerName } = layerPathArgs(args); const drv = await resolveDrv(layerName); - const h = await drv.execSession(command, name ? { name } : undefined); - sessionOwner.track(h.sessionId, drv); // 归属记录(stop_and_verify 按此寻层) - // 启动后异常统一走 postLaunchFail(三十五期 P1 + 三十六期提取共享) - if (error_pattern) { - try { - drv.watchSession(h.sessionId, { pattern: error_pattern, once: false, thenStop: true }); - } catch (err) { - await postLaunchFail(drv, h, "错误监听注册失败", err); - } - } - let note: string | undefined; - if (ready_marker) { - // 就绪握手(回溯热窗口——快输出进程竞态安全)。超时/轮询失败统一走 - // postLaunchFail(三十四期超时诚实三态 + 三十五/三十六期共享收口) - const t0 = Date.now(); - let ticks = 0; - for (;;) { - let lines: string[]; + if (!drv.fs.stat) { + if (typeof drv.fs.readdir === "function") { try { - lines = await drv.tailSession(h.sessionId, 50); + return { path, type: "directory", entries: await drv.fs.readdir(path) }; } catch (err) { - await postLaunchFail(drv, h, "ready 轮询失败(tailSession 抛错)", err); + const detail = err instanceof Error ? err.message : String(err); + throw new Error(`read_path 无法读取路径(fs.stat 缺席且列目录失败:${detail}): ${path}`); } - if (lines!.some((l) => l.includes(ready_marker))) { note = "ready"; break; } - if (Date.now() - t0 > readyTimeoutMs) { - await postLaunchFail(drv, h, `ready 超时(${readyTimeoutMs}ms 未见 '${ready_marker}')`); + } + throw new Error("该层不支持 read_path 的元数据(fs.stat 缺席)"); + } + const isPermissionError = (err: unknown): boolean => { + const code = (err as NodeJS.ErrnoException | undefined)?.code; + if (code === "EACCES" || code === "EPERM") return true; + const msg = err instanceof Error ? err.message : String(err); + return /permission denied|operation not permitted|access is denied|eacces|eperm|权限不足/i.test(msg); + }; + const isNotFoundOrNotDirError = (err: unknown): boolean => { + if (isPermissionError(err)) return false; + const code = (err as NodeJS.ErrnoException | undefined)?.code; + if (code === "ENOENT" || code === "ENOTDIR") return true; + if (code) return false; + const msg = err instanceof Error ? err.message : String(err); + return /no such file or directory|not a directory|does not exist|not found|enoent|enotdir/i.test(msg); + }; + const st = await drv.fs.stat(path); + if (!st) { + if (typeof drv.fs.readdir === "function") { + try { + return { path, type: "directory", entries: await drv.fs.readdir(path) }; + } catch (dirErr) { + if (!isNotFoundOrNotDirError(dirErr)) throw dirErr; } - // 崩溃快速失败(Hydrogen R3 #7):命令启动即崩(参数/配置错)曾 - // 空轮询整个 readyTimeoutMs 才报超时——每 10 轮(~1s)核实一次 - // 会话状态,已退出即带真实退出码走 postLaunchFail - if (++ticks % 10 === 0) { - const verified = await Promise.resolve() - .then(() => drv.verifySession(h.sessionId)) - .catch(() => undefined); - if (verified?.status === "exited" && Number.isSafeInteger(verified.exitCode)) { - sessionOwner.remember(h.sessionId, { status: "exited", exit_code: verified.exitCode }); - throw Object.assign(new Error( - `进程已退出(exitCode=${verified.exitCode}),未见 ready 标记 '${ready_marker}'`, - ), { outcome: "exited", exitCode: verified.exitCode, sessionId: h.sessionId, logBase: h.logBase }); - } + } + throw new Error(`路径不存在: ${path}`); + } + if (st.isDirectory === true) { + return { path, type: "directory", entries: await drv.fs.readdir(path) }; + } + if (st.isDirectory === false) { + const content = await drv.fs.readFile(path); + return { path, type: "file", content, size: st.size, mtime_ms: st.mtimeMs }; + } + try { + const content = await drv.fs.readFile(path); + return { path, type: "file", content, size: st.size, mtime_ms: st.mtimeMs }; + } catch (err) { + if (typeof drv.fs.readdir === "function") { + try { + return { path, type: "directory", entries: await drv.fs.readdir(path) }; + } catch (dirErr) { + const errMsg = err instanceof Error ? err.message : String(err); + const fileSaidIsDir = (err as NodeJS.ErrnoException | undefined)?.code === "EISDIR" + || /eisdir|is a directory/i.test(errMsg); + if (fileSaidIsDir || isPermissionError(dirErr)) throw dirErr; } - await new Promise((r) => setTimeout(r, 100)); } + throw err; } - return { session_id: h.sessionId, log_base: h.logBase, note }; - }, - async read_file(args) { - const { path, layer: layerName } = layerPathArgs(args); - const drv = await resolveDrv(layerName); - if (!drv.fs.stat) throw new Error("该层不支持 read_file 的元数据(fs.stat 缺席)"); - const st = await drv.fs.stat(path); - if (!st) throw new Error(`文件不存在: ${path}`); - const content = await drv.fs.readFile(path); - return { path, content, size: st.size, mtime_ms: st.mtimeMs }; }, - 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 需要单文件路径"); + edit_file: (async (args: Record) => { + const hasWrite = args.content !== undefined; + const hasCas = args.old !== undefined || args.new !== undefined; + if (hasWrite && hasCas) { + throw new Error("edit_file 的直接写入模式(content)与 CAS 替换模式(old/new)互斥"); } - 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 (hasWrite) { + const { path, content, overwrite, create_dirs: createDirs, layer: layerName, ...extra } = args; + const unknown = Object.keys(extra); + if (unknown.length) { + throw new Error(`edit_file 写入模式未知参数:${unknown.map((field) => JSON.stringify(field)).join(", ")}`); + } + assertValidPath(path); + assertOptionalLayerName(layerName); + if (typeof content !== "string") throw new Error("edit_file 的 content 需为字符串"); + if (overwrite !== undefined && typeof overwrite !== "boolean") throw new Error("edit_file 的 overwrite 需为布尔值"); + if (createDirs !== undefined && typeof createDirs !== "boolean") throw new Error("edit_file 的 create_dirs 需为布尔值"); + const drv = await resolveDrv(layerName); + if (/(?:^|\/)\.{1,2}$|\/$/.test(path) + || (drv.descriptor.driver === "local" && process.platform === "win32" && /(?:^|\\)\.{1,2}$|\\$/.test(path))) { + throw new Error("edit_file 需要有效的文件路径"); + } + if (createDirs) { + const isWinLocal = drv.descriptor.driver === "local" && process.platform === "win32"; + const parent = isWinLocal ? nodePath.win32.dirname(path) : nodePath.posix.dirname(path); + if (parent && parent !== "." && parent !== "/" && !(isWinLocal && /^[A-Za-z]:[/\\]?$/.test(parent))) { + await drv.fs.mkdir(parent, { recursive: true }); + } + } + if (!overwrite) { + if (typeof drv.fs.createFile !== "function") { + throw new Error("该层不支持独占创建文件(fs.createFile 缺席);如需覆写请显式传 overwrite: true"); + } + try { + await drv.fs.createFile(path, content); + } catch (err) { + const code = (err as { code?: string } | null)?.code; + const msg = err instanceof Error ? err.message : String(err); + if (code === "EEXIST" || msg.includes("EEXIST") || msg.includes("文件已存在")) { + throw new Error(`文件已存在,拒绝覆盖(如需覆写请传 overwrite: true,或改用 old/new 进行 CAS 局部替换): ${path}`); + } + throw err; + } + return { + mode: "write" as const, + path, + created: true, + bytes_after: Buffer.byteLength(content, "utf-8"), + }; + } + const existed = await drv.fs.exists(path); + await drv.fs.writeFile(path, content); + return { + mode: "write" as const, + path, + created: !existed, + bytes_after: Buffer.byteLength(content, "utf-8"), + }; + } + const { path, old, new: newStr, all, write_mode: writeMode, layer: layerName, ...extra } = args as { + path: string; old: string; new: string; all?: boolean; write_mode?: "auto" | "inplace"; layer?: string; + }; const unknown = Object.keys(extra); if (unknown.length) { const hint = unknown.includes("hunks") ? "。单次编辑传 old 和 new,多处替换可用 run_batch 的 edit 步骤" : ""; throw new Error(`edit_file 未知参数:${unknown.map((field) => JSON.stringify(field)).join(", ")}${hint}`); } + if (old === undefined || newStr === undefined) { + throw new Error("edit_file 需传 old 和 new(CAS 替换),或传 content(直接写入/创建)"); + } 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 }; - }, - put_file: (args) => transferFile("put", args), - get_file: (args) => transferFile("get", args), - async observe_stream(args) { - if ("duration_ms" in args) throw new Error("observe_stream 持续开窗,请用 read_stream 的 wait_ms 限制单次等待"); - const { command, stream, name, layer: layerName } = args; - if (observationDisposed) throw new Error("工具集已关闭"); - if (typeof command !== "string" || !command.trim()) throw new Error("command 需要非空字符串"); - if (stream !== undefined && !["stdout", "stderr", "both"].includes(stream)) throw new Error("stream 无效"); - const drv = await resolveDrv(layerName); - if (observationDisposed) throw new Error("工具集已关闭"); - if (!drv.openStreamWindow) throw new Error(`层 '${layerName ?? drv.descriptor.driver}' 不支持持续观察窗`); - const registry = windowRegistry ??= new StreamWindowRegistry(); - const id = randomUUID(); - const window = await drv.openStreamWindow(registry, { name: id, command, stream, retainSequence: false }); - return { window_id: id, ...(name ? { name } : {}), stale: window.stale }; - }, - async read_stream({ window_id, limit = 20, since_seq, before_seq, window_ms, wait_ms = 0 }) { - if ([since_seq, before_seq, window_ms].filter((value) => value !== undefined).length > 1) { - throw new Error("since_seq、before_seq 和 window_ms 互斥"); + return { + mode: "edit" as const, + path: r.path, occurrences: r.occurrences, + bytes_before: r.bytesBefore, bytes_after: r.bytesAfter, + mutex: r.mutex, write_mode: r.writeMode, + }; + }) as AgentToolHandlers["edit_file"], + manage_path: (async (args: Record) => { + const { action, path, layer: layerName, ...rest } = args; + if (action !== "mkdir" && action !== "move" && action !== "delete") { + throw new Error('manage_path 的 action 须为 "mkdir"、"move" 或 "delete"'); + } + assertValidPath(path); + assertOptionalLayerName(layerName); + if (action === "mkdir") { + const { parents, ...extra } = rest; + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`manage_path(mkdir) 未知参数:${unknown.join(", ")}`); + if (parents !== undefined && typeof parents !== "boolean") throw new Error("parents 需为布尔值"); + const drv = await resolveDrv(layerName); + await drv.fs.mkdir(path, { recursive: parents === undefined ? true : Boolean(parents) }); + return { action: "mkdir" as const, path, created: true as const }; } - for (const value of [since_seq, before_seq, window_ms, wait_ms]) { - if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) { - throw new Error("观察窗的游标和时长需要非负整数"); + if (action === "move") { + const { destination, ...extra } = rest; + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`manage_path(move) 未知参数:${unknown.join(", ")}`); + assertValidPath(destination, "destination"); + const drv = await resolveDrv(layerName); + const isWinLocal = drv.descriptor.driver === "local" && process.platform === "win32"; + if (/(?:^|\/)\.{1,2}$|\/$/.test(path) || /(?:^|\/)\.{1,2}$|\/$/.test(destination) + || (isWinLocal && (/(?:^|\\)\.{1,2}$|\\$/.test(path) || /(?:^|\\)\.{1,2}$|\\$/.test(destination)))) { + throw new Error("manage_path(move) 需要精确的文件或目录路径,不支持 . / .. 或尾斜杠"); } + if (!drv.fs.rename) throw new Error("该层不支持路径移动/重命名(fs.rename 缺席)"); + await drv.fs.rename(path, destination); + return { action: "move" as const, path, destination, moved: true as const }; } - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) throw new Error("limit 须在 1–200 之间"); - if (wait_ms > 30000 || (wait_ms > 0 && since_seq === undefined)) { - throw new Error("wait_ms 仅用于续读,且最大为 30000"); + const { recursive, ...extra } = rest; + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`manage_path(delete) 未知参数:${unknown.join(", ")}`); + if (recursive !== undefined && typeof recursive !== "boolean") throw new Error("recursive 需为布尔值"); + const isRecursive = recursive === undefined ? false : Boolean(recursive); + const drv = await resolveDrv(layerName); + const isWinLocal = drv.descriptor.driver === "local" && process.platform === "win32"; + if (!isRecursive) { + await deleteSingleFile(path, drv); + } else { + const stripped = isWinLocal ? path.replace(/[/\\]+$/, "") : path.replace(/\/+$/, ""); + if (!stripped + || /(?:^|\/)\.{1,2}$/.test(stripped) + || (isWinLocal && (/^(?:\.{1,2}|[A-Za-z]:)$/.test(stripped) || /(?:^|\\)\.{1,2}$/.test(stripped)))) { + throw new Error("manage_path(delete) 拒绝删除根目录、工作目录或上级等价路径"); + } + await drv.fs.rm(path, { recursive: true, force: false }); } - const window = requireWindow(window_id); - const deadline = Date.now() + wait_ms; - const read = () => since_seq !== undefined ? window.peekSince(since_seq, limit) - : before_seq !== undefined ? window.peekBefore(before_seq, limit) - : window_ms !== undefined ? window.peekWindow(window_ms, limit) - : window.peekLast(limit); - let result = read(); - while (since_seq !== undefined && !result.frames.length && !result.gap && !result.stale && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(50, deadline - Date.now())))); - requireWindow(window_id); - result = read(); + return { action: "delete" as const, path, deleted: true as const, recursive: isRecursive }; + }) as AgentToolHandlers["manage_path"], + transfer_file: (async (args: Record) => { + const { direction, ...rest } = args; + if (direction !== "put" && direction !== "get") { + throw new Error('transfer_file 的 direction 需为 "put" 或 "get"'); } - return { - window_id, oldest_seq: result.oldestSeq, newest_seq: result.newestSeq, - stale: result.stale, frames: result.frames, - ...(result.exitCode !== undefined ? { exit_code: result.exitCode } : {}), - ...(result.error !== undefined ? { error: result.error } : {}), - ...(result.lastDeliveredSeq !== undefined ? { last_delivered_seq: result.lastDeliveredSeq } : {}), - ...(result.gap ? { gap: true } : {}), - ...(wait_ms > 0 && !result.frames.length && !result.gap && !result.stale ? { timed_out: true } : {}), - }; - }, + if (direction === "get" && rest.write_mode !== undefined) { + throw new Error("transfer_file 在 direction=get 时不支持 write_mode"); + } + const result = await transferFile(direction, rest as unknown as AgentFilePutArgs); + return { direction, ...result }; + }) as unknown as AgentToolHandlers["transfer_file"], + observe_stream: (async (args: Record) => { + if ("duration_ms" in args) throw new Error("observe_stream 持续开窗,请用 wait_ms 限制单次等待"); + const hasCommand = args.command !== undefined; + const hasWindowId = args.window_id !== undefined; + if (hasCommand && hasWindowId) { + throw new Error("observe_stream 不能同时传 command(开窗)和 window_id(续读)"); + } + if (!hasCommand && !hasWindowId) { + throw new Error("observe_stream 需传 command(开窗)或 window_id(续读)"); + } + if (hasCommand) { + const { command, stream, name, layer: layerName, limit = 20, wait_ms = 0, ...extra } = args as { + command: unknown; stream?: unknown; name?: unknown; layer?: unknown; limit?: unknown; wait_ms?: unknown; + [key: string]: unknown; + }; + if (extra.since_seq !== undefined || extra.before_seq !== undefined || extra.window_ms !== undefined) { + throw new Error("observe_stream 开窗模式不支持 since_seq、before_seq 或 window_ms;请先开窗再凭返回的 window_id 续读"); + } + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`observe_stream 开窗模式未知参数:${unknown.join(", ")}`); + if (observationDisposed) throw new Error("工具集已关闭"); + if (typeof command !== "string" || !command.trim()) throw new Error("command 需要非空字符串"); + if (stream !== undefined && stream !== "stdout" && stream !== "stderr" && stream !== "both") throw new Error("stream 无效"); + if (name !== undefined && typeof name !== "string") throw new Error("name 需为字符串"); + assertOptionalLayerName(layerName); + if (!Number.isSafeInteger(limit) || (limit as number) < 1 || (limit as number) > 200) throw new Error("limit 须在 1–200 之间"); + if (!Number.isSafeInteger(wait_ms) || (wait_ms as number) < 0 || (wait_ms as number) > 30000) { + throw new Error("wait_ms 须在 0–30000 之间"); + } + const drv = await resolveDrv(layerName); + if (observationDisposed) throw new Error("工具集已关闭"); + if (!drv.openStreamWindow) throw new Error(`层 '${layerName ?? drv.descriptor.driver}' 不支持持续观察窗`); + const registry = windowRegistry ??= new StreamWindowRegistry(); + const id = randomUUID(); + const window = await drv.openStreamWindow(registry, { + name: id, command, stream: stream as "stdout" | "stderr" | "both" | undefined, retainSequence: false, + }); + const waitMs = wait_ms as number; + const maxFrames = limit as number; + const deadline = Date.now() + waitMs; + let result = window.peekSince(0, maxFrames); + while (!result.frames.length && !result.gap && !result.stale && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(50, deadline - Date.now())))); + requireWindow(id); + result = window.peekSince(0, maxFrames); + } + return formatStreamResult(id, result, waitMs, name as string | undefined); + } + return await readStreamWindow(args); + }) as AgentToolHandlers["observe_stream"], async close_stream({ window_id }) { requireWindow(window_id); await windowRegistry!.stopConfirmed(window_id); return { window_id, closed: true }; }, - // ── 层族(第十季命名层注册表)── - push_ssh: pushSsh, - async push_into(args) { - // 参数别名宽收(第十二季语法糖):enter_cmd / enterCommand / enter_command / enterCmd - // 等价——Agent 手滑完整词不再静默漏建层(同款事故:enterCommand 拼错→裸宿主机层) - const raw = args as Record; - const enterCmd = [raw.enter_cmd, raw.enterCommand, raw.enter_command, raw.enterCmd] - .find((v) => typeof v === "string" && v) as string | undefined; - const label = raw.label as string | undefined; - const from = raw.from as string | undefined; - const name = raw.name as string | undefined; - if (!enterCmd) { - throw new Error("push_into 需提供 enter_cmd(别名 enterCommand/enter_command/enterCmd 均可)"); + // ── 层族(命名层注册表)── + connect_layer: connectLayer, + manage_layers: (async (args: Record) => { + const { action, ...rest } = args; + if (action === "list") { + const unknown = Object.keys(rest); + if (unknown.length) throw new Error(`manage_layers(list) 未知参数:${unknown.join(", ")}`); + return { + action: "list" as const, + text: stack.layerText(), + layers: [...stack.layers.values()].map((h) => ({ + name: h.name, driver: h.descriptor.driver, target: h.descriptor.target, + })), + }; } - const srcName = from ?? stack.activeLayer?.name; - if (!srcName) throw new Error("无源层——先 push_ssh 建层,或显式传 from"); - const h = await stack.layerInto(srcName, name ?? label ?? enterCmd.slice(0, 30), enterCmd, { label }); - return { layer: h.name, target: h.descriptor.target }; - }, - async list_layers(_args) { - void _args; - return { - text: stack.layerText(), - layers: [...stack.layers.values()].map((h) => ({ - name: h.name, driver: h.descriptor.driver, target: h.descriptor.target, - })), - }; - }, - async remove_layer({ name, destroy }) { - 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 }; - }, + if (action === "activate") { + const { name, ...extra } = rest; + if (Object.keys(extra).length) throw new Error("manage_layers(activate) 只接受 action 和 name"); + if (typeof name !== "string" || !name.trim()) throw new Error("name 需为非空层名"); + return { action: "activate" as const, active_layer: stack.setActive(name).name }; + } + if (action === "remove") { + const { name, destroy, ...extra } = rest; + if (Object.keys(extra).length) throw new Error("manage_layers(remove) 只接受 action、name 和 destroy"); + if (typeof name !== "string" || !name.trim()) throw new Error("name 需为非空层名"); + if (destroy !== undefined && typeof destroy !== "boolean") throw new Error("destroy 需为布尔值"); + await stack.removeLayer(name, { destroy: destroy === undefined ? undefined : Boolean(destroy) }); + return { action: "remove" as const, removed: name }; + } + throw new Error('manage_layers 的 action 须为 "list"、"activate" 或 "remove"'); + }) as AgentToolHandlers["manage_layers"], 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); @@ -991,56 +1492,71 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption })), }; }, - async stop_and_verify({ session_id, layer: layerName, ...extra }) { - if (Object.keys(extra).length) throw new Error("stop_and_verify 只接受 session_id 和 layer"); - if (typeof session_id !== "string" || !session_id.trim()) throw new Error("session_id 需为完整的非空会话 ID"); - if (layerName !== undefined && (typeof layerName !== "string" || !layerName.trim())) { - throw new Error("layer 需为非空层名"); - } - // 归属寻层(GPT Astra 二轮 #3 / 三轮 #1 / 四轮 #1):spawn 在远端层的会话回该层停。 - // unknown 时自动接一次 verifySession 核实原语(DeepSeek 评审追问的 unknown 闭环)—— - // stop 的 unknown 是「停止瞬间核实不可达」,verify 是延迟后的独立探测通道。 - // 停止通道抛错也归 unknown 继续 verify(三十七期 #2:旧形态 await - // 直接抛出——后面的 verify 根本不执行,裸抛无 unknown 标记) - const entry = sessionOwner.get(session_id); - if (entry && "result" in entry) return { ...entry.result }; - if (!entry && !layerName) { - return { status: "unknown", note: "会话归属未知或已过期,verify 需要显式指定 layer" }; - } - const drv = entry && "driver" in entry - ? entry.driver - : layerName === INITIAL_LAYER_NAME ? await layer() : stack.layer(layerName!).driver; - let r: { status?: string; exitCode?: number | null }; - try { - r = await drv.stopSession(session_id); - } catch { - r = { status: "unknown", exitCode: null }; // 停止通道失败——归 unknown 走 verify - } - let status: "exited" | "stopped" | "unknown" = r.status === "stopped" ? "stopped" - : r.status !== "unknown" && Number.isSafeInteger(r.exitCode) ? "exited" : "unknown"; - let exitCode = r.exitCode; - let stillRunningNote: string | undefined; - if (status === "unknown") { - try { - const v = await drv.verifySession(session_id); - if (v.status === "exited" && Number.isSafeInteger(v.exitCode)) { status = "exited"; exitCode = v.exitCode; } - else if (v.status === "running") { - stillRunningNote = "进程实测仍在运行(stop 未生效——不可中断态或权限不足)"; - } - } catch { /* verify 不可达——保持 unknown */ } + stop_session: stopSession, + // ── 兼容 0.2.10 旧工具名直调适配器 ── + spawn_and_observe: startSession, + stop_and_verify: stopSession, + async read_file(args) { + const { path, layer: layerName } = layerPathArgs(args); + const drv = await resolveDrv(layerName); + if (!drv.fs.stat) throw new Error("该层不支持 read_file 的元数据(fs.stat 缺席)"); + const st = await drv.fs.stat(path); + if (!st) throw new Error(`文件不存在: ${path}`); + if (st.isDirectory === true) throw new Error(`目标是目录(请使用 read_path 或 list_directory): ${path}`); + const content = await drv.fs.readFile(path); + return { path, content, size: st.size, mtime_ms: st.mtimeMs }; + }, + 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); + const drv = await resolveDrv(layerName); + await deleteSingleFile(path, drv); + return { path, deleted: true as const }; + }, + put_file: (args) => transferFile("put", args), + get_file: (args) => transferFile("get", args), + async read_stream(args) { + const raw = args as Record; + if ("duration_ms" in raw) throw new Error("read_stream 不支持 duration_ms,请使用 wait_ms"); + if (raw.window_id === undefined) requireWindow(""); + return await readStreamWindow(raw); + }, + push_ssh: (async (args: Record) => { + if (enterLayerAliases.some((k) => args[k] !== undefined)) { + throw new Error("push_ssh 仅支持 SSH 目标,进入内层请使用 push_into 或 connect_layer"); } - if (status !== "unknown") { - const result: StopResult = status === "exited" - ? { status, exit_code: exitCode } - : { status, note: "终止已核实" }; - sessionOwner.remember(session_id, result); - return result; + return await connectSshLayer(args); + }) as unknown as AgentToolHandlers["push_ssh"], + async push_into(args) { + const raw = args as Record; + const presentEnterKeys = enterLayerAliases.filter((k) => raw[k] !== undefined); + if (!presentEnterKeys.length) { + throw new Error("push_into 需提供 enter_cmd(别名 enterCommand/enter_command/enterCmd 均可)"); } + return await connectIntoLayer(raw, presentEnterKeys); + }, + async list_layers(_args) { + void _args; return { - status: "unknown", - note: stillRunningNote ?? "未取得可核实的终态。重连后,用完整 session_id 和原目标层再次调用 stop_and_verify,或上报结果未知。", + text: stack.layerText(), + layers: [...stack.layers.values()].map((h) => ({ + name: h.name, driver: h.descriptor.driver, target: h.descriptor.target, + })), }; }, + 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 remove_layer({ name, destroy }) { + await stack.removeLayer(name, { destroy }); + return { removed: name }; + }, }, }; } diff --git a/src/driver.ts b/src/driver.ts index 0e18b1e..e5a8ff9 100644 --- a/src/driver.ts +++ b/src/driver.ts @@ -86,17 +86,21 @@ export interface FileEntry { export interface FileStat { mtimeMs: number; size: number; + isDirectory?: boolean; } export interface FileSystemDriver { readFile(path: string): Promise; /** Read a bounded UTF-8 preview, with a truncation notice when applicable. */ readFilePreview?(path: string, maxOutputBytes: number): Promise; - writeFile(path: string, content: string): Promise; + writeFile(path: string, content: string, options?: { exclusive?: boolean }): Promise; + /** 原子独占创建并写入 UTF-8 文件(目标已存在时抛 EEXIST,绝不覆盖) */ + createFile?(path: string, content: string): Promise; exists(path: string): Promise; readdir(path: string): Promise; rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise; mkdir(path: string, options?: { recursive?: boolean }): Promise; + rename?(from: string, to: string): Promise; /** 可选 stat(mtimeMs/size)——先读后写闸的数据依赖 */ stat?(path: string): Promise; /** diff --git a/src/file-placement.ts b/src/file-placement.ts index a6df813..86954f2 100644 --- a/src/file-placement.ts +++ b/src/file-placement.ts @@ -21,3 +21,82 @@ export function renderPreserveMode(source: string): string { `if [ "$__fx_stage_owner" != "$__fx_owner" ] && ! chown "$__fx_owner" ${source} 2>/dev/null; then echo FX_PERMISSIONS_FAIL; exit 1; fi; ` + `chmod "$__fx_pm" ${source} 2>/dev/null || { echo FX_PERMISSIONS_FAIL; exit 1; }; fi; `; } + +const q = (s: string) => `'${s.replace(/'/g, "'\\''")}'`; + +export function throwRemoteFsCmdError( + op: string, + target: string, + r: { exitCode: number; stdout?: string; stderr?: string }, +): never { + const detail = (r.stderr || r.stdout || "").trim(); + const err = new Error(`${op} 失败(exit=${r.exitCode}): ${target}${detail ? `: ${detail}` : ""}`); + if (r.exitCode >= 129) { + Object.assign(err, { outcome: "unknown" as const }); + } + throw err; +} + +/** Pure POSIX sh accident guardrails for recursive rm (workspace/root/trailing-slash checks, zero Python dependency). */ +export function buildPosixRmGuardCmd(p: string, options?: { force?: boolean }): string { + const stripped = p.replace(/\/+$/, ""); + const trailingSlash = /\/$/.test(p); + const force = Boolean(options?.force); + const fFlag = force ? "1" : "0"; + const tFlag = trailingSlash ? "1" : "0"; + return `( unset CDPATH; __fx_s=${q(stripped)}; ` + + `__fx_cwd=$(pwd -P && printf .) || exit 1; __fx_cwd=\${__fx_cwd%??}; ` + + `__fx_d=$(dirname -- "$__fx_s" && printf .) || exit 1; __fx_d=\${__fx_d%??}; ` + + `__fx_b=$(basename -- "$__fx_s" && printf .) || exit 1; __fx_b=\${__fx_b%??}; ` + + `if [ -z "$__fx_b" ] || [ "$__fx_b" = "." ] || [ "$__fx_b" = ".." ] || [ "$__fx_b" = "/" ]; then ` + + `echo "rm 拒绝危险或无效路径" >&2; exit 1; fi; ` + + `case "$__fx_d" in /*) ;; *) __fx_d="./$__fx_d" ;; esac; ` + + `if ! __fx_pdir=$(cd -P -- "$__fx_d" >/dev/null 2>&1 && pwd -P && printf .); then ` + + `if [ ${fFlag} = 1 ] && [ ! -e "$__fx_s" ] && [ ! -L "$__fx_s" ]; then exit 0; fi; ` + + `echo "rm 路径不存在或父目录不可达" >&2; exit 1; fi; ` + + `__fx_pdir=\${__fx_pdir%??}; ` + + `__fx_t="\${__fx_pdir%/}/$__fx_b"; ` + + `if [ ! -e "$__fx_t" ] && [ ! -L "$__fx_t" ]; then ` + + `if [ ${fFlag} = 1 ]; then exit 0; fi; ` + + `echo "rm 路径不存在" >&2; exit 1; fi; ` + + `if [ ${tFlag} = 1 ] && { [ -L "$__fx_t" ] || [ ! -d "$__fx_t" ]; }; then ` + + `echo "rm 目标不是真实目录(拒绝带尾斜杠的符号链接或文件)" >&2; exit 1; fi; ` + + `if [ -d "$__fx_t" ] && [ ! -L "$__fx_t" ]; then ` + + `__fx_real=$(cd -P -- "$__fx_t" >/dev/null 2>&1 && pwd -P && printf .) || { echo "rm 无法解析目标真实路径" >&2; exit 1; }; ` + + `__fx_real=\${__fx_real%??}; ` + + `if [ ${tFlag} = 1 ] && [ "$__fx_real" != "$__fx_t" ]; then ` + + `echo "rm 目标不是真实目录(拒绝带尾斜杠的符号链接或文件)" >&2; exit 1; fi; ` + + `if [ "$__fx_real" = "/" ] || [ "$__fx_real" = "$__fx_cwd" ]; then ` + + `echo "rm 拒绝删除当前工作目录或上级目录" >&2; exit 1; fi; ` + + `case "$__fx_cwd" in "$__fx_real"/*) echo "rm 拒绝删除当前工作目录或上级目录" >&2; exit 1 ;; esac; ` + + `fi; ` + + `rm -r ${force ? "-f " : ""}-- "$__fx_t" )`; +} + +/** Pure POSIX sh accident guardrails for rename/move (existing-dir/xdev/self-subdir checks, zero Python dependency). */ +export function buildPosixRenameCmd(from: string, to: string): string { + return `( unset CDPATH; __fx_from=${q(from)}; __fx_to=${q(to)}; ` + + `if [ ! -e "$__fx_from" ] && [ ! -L "$__fx_from" ]; then echo "源路径不存在" >&2; exit 1; fi; ` + + `__fx_sd=$(dirname -- "$__fx_from" && printf .) || exit 1; __fx_sd=\${__fx_sd%??}; ` + + `__fx_sb=$(basename -- "$__fx_from" && printf .) || exit 1; __fx_sb=\${__fx_sb%??}; ` + + `case "$__fx_sd" in /*) ;; *) __fx_sd="./$__fx_sd" ;; esac; ` + + `__fx_sdir=$(cd -P -- "$__fx_sd" >/dev/null 2>&1 && pwd -P && printf .) || { echo "源父目录不存在" >&2; exit 1; }; __fx_sdir=\${__fx_sdir%??}; ` + + `__fx_td=$(dirname -- "$__fx_to" && printf .) || exit 1; __fx_td=\${__fx_td%??}; ` + + `__fx_tb=$(basename -- "$__fx_to" && printf .) || exit 1; __fx_tb=\${__fx_tb%??}; ` + + `case "$__fx_td" in /*) ;; *) __fx_td="./$__fx_td" ;; esac; ` + + `__fx_tdir=$(cd -P -- "$__fx_td" >/dev/null 2>&1 && pwd -P && printf .) || { echo "目标父目录不存在" >&2; exit 1; }; __fx_tdir=\${__fx_tdir%??}; ` + + `__fx_src="\${__fx_sdir%/}/$__fx_sb"; __fx_dst="\${__fx_tdir%/}/$__fx_tb"; ` + + `if [ ! -e "$__fx_src" ] && [ ! -L "$__fx_src" ]; then echo "源路径不存在" >&2; exit 1; fi; ` + + `if [ -d "$__fx_dst" ]; then echo "目标是现存目录" >&2; exit 1; fi; ` + + `if [ -d "$__fx_src" ] && [ ! -L "$__fx_src" ]; then ` + + `if [ -e "$__fx_dst" ] || [ -L "$__fx_dst" ]; then echo "目标已存在,拒绝覆盖" >&2; exit 1; fi; ` + + `__fx_sreal=$(cd -P -- "$__fx_src" >/dev/null 2>&1 && pwd -P && printf .) || exit 1; __fx_sreal=\${__fx_sreal%??}; ` + + `if [ "$__fx_tdir" = "$__fx_sreal" ]; then echo "不能将目录移入自身或子目录(EINVAL)" >&2; exit 1; fi; ` + + `case "$__fx_tdir" in "$__fx_sreal"/*) echo "不能将目录移入自身或子目录(EINVAL)" >&2; exit 1 ;; esac; ` + + `__fx_sdev=$(stat -c '%d' "$__fx_src" 2>/dev/null || stat -f '%d' "$__fx_src" 2>/dev/null) || __fx_sdev=; ` + + `__fx_tdev=$(stat -Lc '%d' "$__fx_tdir" 2>/dev/null || stat -Lf '%d' "$__fx_tdir" 2>/dev/null) || __fx_tdev=; ` + + `if [ -z "$__fx_sdev" ] || [ -z "$__fx_tdev" ]; then echo "无法核实文件系统设备号,拒绝目录移动" >&2; exit 1; fi; ` + + `if [ "$__fx_sdev" != "$__fx_tdev" ]; then echo "不支持跨文件系统移动(EXDEV)" >&2; exit 1; fi; ` + + `fi; ` + + `mv -- "$__fx_src" "$__fx_dst" )`; +} diff --git a/src/file-transfer.ts b/src/file-transfer.ts index 5388848..1dfff60 100644 --- a/src/file-transfer.ts +++ b/src/file-transfer.ts @@ -21,21 +21,29 @@ import type { RemoteDialect } from "./dialect.js"; import { renderInplaceWrite, renderPreserveMode } from "./file-placement.js"; import { sshFileStdioRequested, spawnWithFileRedirect } from "./ssh-file-stdio.js"; import { openSshEnvironment } from "./openssh-environment.js"; -import { windowsCreatePrivateStage, windowsPlaceVerifiedPayload } from "./windows-upload-acl.js"; +import { windowsCreatePrivateStage, windowsPlaceExclusivePayload, windowsPlaceVerifiedPayload } from "./windows-upload-acl.js"; import type { ExecOptions } from "./driver.js"; /** Forward exec options when wrapping a driver so payload-bearing calls retain their audit policy. */ -export type TransferExec = (command: string, options?: Pick) => Promise<{ stdout: string; exitCode: number }>; +export type TransferExec = ( + command: string, + options?: Pick, +) => Promise<{ stdout: string; stderr?: string; exitCode: number }>; -/** Decode standard Base64, allowing line wrapping but rejecting malformed output. */ -export function decodeFileRead(output: string, path: string, expectedBytes?: number): string { +/** Decode standard Base64 into raw bytes, allowing line wrapping but rejecting malformed output. */ +export function decodeFileBytes(output: string, path: string, expectedBytes?: number, opLabel = "readFile"): Buffer { const encoded = output.replace(/[ \t\r\n]+/g, ""); const content = Buffer.from(encoded, "base64"); - if (content.toString("base64") !== encoded) throw new Error(`readFile 返回无效 Base64: ${path}`); + if (content.toString("base64") !== encoded) throw new Error(`${opLabel} 返回无效 Base64: ${path}`); if (expectedBytes !== undefined && content.length !== expectedBytes) { - throw new Error(`readFile 长度对账失败(解码 ${content.length}B,源 ${expectedBytes}B): ${path}`); + throw new Error(`${opLabel} 长度对账失败(解码 ${content.length}B,源 ${expectedBytes}B): ${path}`); } - return content.toString("utf-8"); + return content; +} + +/** Decode standard Base64, allowing line wrapping but rejecting malformed output. */ +export function decodeFileRead(output: string, path: string, expectedBytes?: number): string { + return decodeFileBytes(output, path, expectedBytes, "readFile").toString("utf-8"); } /** put 分块大小(base64 字符数——单条命令行安全长度内) */ @@ -84,7 +92,7 @@ export async function putFile( dialect: RemoteDialect, localPath: string, remotePath: string, - opts: { forceInplace?: boolean } = {}, + opts: { chunkB64?: number; forceInplace?: boolean } = {}, ): Promise { return putContent(exec, dialect, await fs.readFile(localPath), remotePath, opts); } @@ -95,6 +103,7 @@ export async function writeInplaceContent( content: Buffer, remotePath: string, chunkB64?: number, + opts: { exclusive?: boolean } = {}, ): Promise { const result = await exec("mktemp -d /tmp/filaxis-write.XXXXXXXXXX"); const stageDir = result.stdout.trim(); @@ -102,7 +111,11 @@ export async function writeInplaceContent( throw new Error(`writeFile 无法创建暂存目录(目标未动): ${remotePath}`); } try { - return await stageAndPlaceContent(exec, dialect, content, remotePath, { chunkB64, forceInplace: true }, `${stageDir}/payload`); + return await stageAndPlaceContent( + exec, dialect, content, remotePath, + { chunkB64, forceInplace: true, exclusive: opts.exclusive }, + `${stageDir}/payload`, + ); } finally { await exec(`rmdir ${q(stageDir)}`).catch(() => undefined); } @@ -126,7 +139,7 @@ export async function putContent( dialect: RemoteDialect, content: Buffer, remotePath: string, - opts: { chunkB64?: number; forceInplace?: boolean } = {}, + opts: { chunkB64?: number; forceInplace?: boolean; exclusive?: boolean } = {}, ): Promise { return stageAndPlaceContent(exec, dialect, content, remotePath, opts, remotePath); } @@ -136,29 +149,33 @@ async function stageAndPlaceContent( dialect: RemoteDialect, content: Buffer, remotePath: string, - opts: { chunkB64?: number; forceInplace?: boolean }, + opts: { chunkB64?: number; forceInplace?: boolean; exclusive?: boolean }, stageBase: string, ): Promise { if (!dialect.base64Decode.length) { throw new Error("远端 base64 原语不可用(方言探测 unknown)——该路径不支持文件传输"); } + if (opts.exclusive) { + const existsChk = await exec(`test -e ${q(remotePath)} || test -L ${q(remotePath)}`); + if (existsChk.exitCode === 0) { + throw Object.assign(new Error(`文件已存在,拒绝覆盖: ${remotePath}`), { code: "EEXIST" as const }); + } + } // 目标目录早拒绝(GPT Astra 八轮 #2):mv 遇现存目录=把临时移进目录 // (basename 保留),落位语义被偷换还报 verified——传输前显式拒绝 const dirChk = await exec(`test -d ${q(remotePath)}`); if (dirChk.exitCode === 0) { throw new Error(`目标是现存目录(拒绝上传):${remotePath}——putFile 落位语义是文件路径`); } + const chunkSize = opts.chunkB64 ?? CHUNK_B64; + if (!Number.isFinite(chunkSize) || chunkSize <= 0) { + throw new Error(`chunkB64 非法(${opts.chunkB64})——须为正数(0/负曾使循环反复发空块永不前进)`); + } const b64 = content.toString("base64"); const { stage, payload: out, windows } = await createUploadStage(exec, stageBase); const tmp = `${stage}/encoded`; const cleanup = () => exec(`rm -f ${q(tmp)} ${q(out)}`).catch(() => undefined); const localSha = createHash("sha256").update(content).digest("hex"); - // 分块尺寸可调(真机实证:tmux server 单命令 ~16-24K 即 "command too long"—— - // 键入通道的调用方须传小 chunk;ssh exec 通道 stdin 传命令不受限,缺省 48K) - const chunkSize = opts.chunkB64 ?? CHUNK_B64; - if (!Number.isFinite(chunkSize) || chunkSize <= 0) { - throw new Error(`chunkB64 非法(${opts.chunkB64})——须为正数(0/负曾使循环反复发空块永不前进)`); - } let level: "sha256" | "size"; try { if (!b64.length) { @@ -189,7 +206,9 @@ async function stageAndPlaceContent( throw e; } try { - const writeMode = await placeVerifiedUpload(exec, out, remotePath, { forceInplace: opts.forceInplace, applyUmask: true, windows }); + const writeMode = await placeVerifiedUpload(exec, out, remotePath, { + forceInplace: opts.forceInplace, applyUmask: true, windows, exclusive: opts.exclusive, + }); return { bytes: content.length, sha256: localSha, verified: true, verification: level, writeMode }; } finally { await exec(`rm -f ${q(tmp)}; rmdir ${q(stage)}`).catch(() => undefined); @@ -197,9 +216,68 @@ async function stageAndPlaceContent( } async function placeVerifiedUpload( - exec: TransferExec, out: string, remotePath: string, { forceInplace = false, applyUmask = false, windows = false } = {}, + exec: TransferExec, out: string, remotePath: string, + { forceInplace = false, applyUmask = false, windows = false, exclusive = false } = {}, ): Promise { const cleanup = () => exec(`rm -f ${q(out)}`).catch(() => undefined); + if (exclusive) { + const exclusiveModeSetup = applyUmask + ? `__fx_mask=$(umask); case "$__fx_mask" in [0-7][0-7][0-7]|0[0-7][0-7][0-7]) ;; ` + + `*) exec 3>&- 2>/dev/null || true; rm -f -- "$__fx_seed" 2>/dev/null || true; echo FX_PERMISSIONS_FAIL; exit 1;; esac; ` + + `__fx_new_mode=$(printf '%03o' "$((0666 & ~(0$__fx_mask)))"); ` + + `chmod "$__fx_new_mode" "$__fx_seed" || { exec 3>&- 2>/dev/null || true; rm -f -- "$__fx_seed" 2>/dev/null || true; echo FX_PERMISSIONS_FAIL; exit 1; }; ` + : ""; + const exclusiveCmd = windows + ? `[ -f ${q(out)} ] || { echo FX_NO_PAYLOAD; exit 1; }; ` + + `__fx_src_win=$(cygpath -aw ${q(out)}) && __fx_tgt_win=$(cygpath -aw ${q(remotePath)}) || exit 1; ` + + `if FILAXIS_UPLOAD_SOURCE="$__fx_src_win" FILAXIS_UPLOAD_TARGET="$__fx_tgt_win" ${windowsPlaceExclusivePayload}; ` + + `then echo FX_MV_OK; else echo FX_WINDOWS_PLACEMENT_UNKNOWN; fi` + : `[ -f ${q(out)} ] || { echo FX_NO_PAYLOAD; exit 1; }; ` + + `if [ -e ${q(remotePath)} ] || [ -L ${q(remotePath)} ]; then echo FX_ALREADY_EXISTS; exit 1; fi; ` + + `__fx_dir=$(dirname -- ${q(remotePath)} && printf .) || exit 1; __fx_dir=\${__fx_dir%??}; ` + + `case "$__fx_dir" in /*) ;; *) __fx_dir="./$__fx_dir" ;; esac; ` + + `__fx_seed=$(mktemp "\${__fx_dir%/}/.filaxis-excl.XXXXXXXXXX" 2>/dev/null) || { echo FX_CREATE_FAIL; exit 1; }; ` + + `exec 3> "$__fx_seed" 2>/dev/null || { rm -f -- "$__fx_seed" 2>/dev/null || true; echo FX_CREATE_FAIL; exit 1; }; ` + + `${exclusiveModeSetup}` + + `if ! ln -T -- "$__fx_seed" ${q(remotePath)} 2>/dev/null; then ` + + `exec 3>&- 2>/dev/null || true; rm -f -- "$__fx_seed" 2>/dev/null || true; ` + + `if [ -e ${q(remotePath)} ] || [ -L ${q(remotePath)} ]; then echo FX_ALREADY_EXISTS; else echo FX_CREATE_FAIL; fi; exit 1; fi; ` + + `rm -f -- "$__fx_seed" 2>/dev/null || true; ` + + `if cat < ${q(out)} >&3 && exec 3>&-; then rm -f ${q(out)} 2>/dev/null || true; echo FX_MV_CAT; ` + + `else exec 3>&- 2>/dev/null || true; echo FX_INPLACE_FAIL; exit 1; fi`; + const res = await exec(`( ${exclusiveCmd} )`); + const resOut = (res.stdout || "").trim(); + if (resOut.includes("FX_ALREADY_EXISTS")) { + await cleanup(); + throw Object.assign(new Error(`文件已存在,拒绝覆盖: ${remotePath}`), { code: "EEXIST" as const }); + } + if (resOut.includes("FX_WINDOWS_PLACEMENT_UNKNOWN")) { + throw Object.assign(new Error(`Windows 上传落位或 ACL 应用结果未知,请核实目标和暂存载荷:${remotePath}(${out})`), { outcome: "unknown" as const }); + } + if (resOut.includes("FX_PERMISSIONS_FAIL")) { + await cleanup(); + throw new Error(`put 落位失败(无法设置文件权限,目标未动): ${remotePath}`); + } + if (resOut.includes("FX_NO_PAYLOAD")) { + await cleanup(); + throw new Error(`put 落位中止(载荷在落位前消失或无法打开,目标未动): ${remotePath}`); + } + if (resOut.includes("FX_CREATE_FAIL")) { + await cleanup(); + throw new Error(`put 落位失败(无法独占创建目标文件,目标未动): ${remotePath}`); + } + if (resOut.includes("FX_INPLACE_FAIL")) { + throw new Error( + `put 落位失败(独占写入失败——请核实目标 ${remotePath};` + + `完整载荷保留在 ${out} 可重试)`, + ); + } + if (res.exitCode !== 0 || (!resOut.includes("FX_MV_OK") && !resOut.includes("FX_MV_CAT"))) { + await cleanup(); + throw new Error(`put 落位异常(目标未动): ${remotePath}(输出 ${resOut.slice(0, 80)})`); + } + return resOut.includes("FX_MV_CAT") ? "inplace-write" : "atomic-replace"; + } // 落位(GPT Astra 七轮 #3 + 八轮 #2 + bind mount 定案 + 十八轮 #2 三态 + 审计 H5): // symlink 追踪(readlink -f 真身——mv 对链接路径会替换链接本身破坏拓扑)+ 属性 // 保持(chmod/chown --reference best-effort);mv 失败自动降级 cat 保留 inode; @@ -297,6 +375,71 @@ async function placeVerifiedUpload( return mvOut.includes("FX_MV_CAT") ? "inplace-write" : "atomic-replace"; } +/** + * 分页读取远端文件字节(供 tmux readFile 与 getFile 共用): + * 小文件单次 Base64 直出;大文件先编码落盘到远端 0600 独占临时文件,再按 8KB Base64 + * 分页读取,避开 tmux 滚动窗口与聚合缓冲截断。 + */ +export async function readPagedFileBytes( + exec: TransferExec, + base64EncodeCmd: string, + remotePath: string, + opts: { maxDirectB64?: number; pageB64?: number; auditLabel?: string; opLabel?: string } = {}, +): Promise { + const maxDirectB64 = opts.maxDirectB64 ?? 12_000; + const pageB64 = Math.max(1, Math.min(8_000, opts.pageB64 ?? 8_000)); + const op = opts.opLabel ?? "readFile"; + const execOpts = opts.auditLabel ? { auditLabel: opts.auditLabel } : undefined; + const st = await exec(`wc -c < ${q(remotePath)} 2>/dev/null`, execOpts); + if (st.exitCode !== 0) { + const detail = (st.stderr || st.stdout || "").trim(); + throw new Error(detail + ? `${op} 失败(wc 退出码 ${st.exitCode}): ${remotePath}: ${detail}` + : `${op} 失败(wc 退出码 ${st.exitCode}): ${remotePath}`); + } + const sizeText = st.stdout.trim(); + const size = Number(sizeText); + if (!/^\d+$/.test(sizeText) || !Number.isSafeInteger(size)) { + throw new Error(`${op} 失败(文件大小无法核实): ${remotePath}`); + } + if (size * 2 <= maxDirectB64) { + const r = await exec(`${base64EncodeCmd} < ${q(remotePath)}`, execOpts); + if (r.exitCode !== 0) { + const detail = (r.stderr || r.stdout || "").trim(); + throw new Error(detail + ? `${op} 失败(base64 退出码 ${r.exitCode}): ${remotePath}: ${detail}` + : `${op} 失败(base64 退出码 ${r.exitCode}): ${remotePath}`); + } + return decodeFileBytes(r.stdout, remotePath, size, op); + } + const tmp = `/tmp/filaxis-read-${randomBytes(8).toString("hex")}.b64`; + try { + const tot = await exec( + `(umask 077; set -C; ${base64EncodeCmd} < ${q(remotePath)} > ${q(tmp)}) && wc -c < ${q(tmp)}`, + execOpts, + ); + const totText = (tot.stdout || "").trim(); + const total = Number(totText); + if (tot.exitCode !== 0 || !/^\d+$/.test(totText) || !Number.isSafeInteger(total)) { + const detail = (tot.stderr || tot.stdout || "").trim(); + throw new Error(detail + ? `${op} 失败(base64 退出码 ${tot.exitCode}): ${remotePath}: ${detail}` + : `${op} 失败(base64 退出码 ${tot.exitCode}): ${remotePath}`); + } + const chunks: string[] = []; + for (let off = 1; off <= total; off += pageB64) { + const pg = await exec(`test -r ${q(tmp)} && tail -c +${off} ${q(tmp)} | head -c ${pageB64}`, execOpts); + if (pg.exitCode !== 0) { + throw new Error(`${op} 分页读失败(页偏移 ${off} 退出码 ${pg.exitCode}): ${remotePath}`); + } + chunks.push(pg.stdout.replace(/[ \t\r\n]+/g, "")); + } + return decodeFileBytes(chunks.join(""), remotePath, size, op); + } finally { + await exec(`rm -f ${q(tmp)}`).catch(() => undefined); + } +} + /** * 下行 get:远端 → 本地。方言 base64 编码回传 → **校验先行** → 本地临时 + * rename 原子落位(GPT Astra 七轮 #2:旧实现先 writeFile 再校验——校验失败 @@ -308,6 +451,7 @@ export async function getFile( dialect: RemoteDialect, remotePath: string, localPath: string, + opts: { chunkB64?: number } = {}, ): Promise { if (!dialect.base64Encode.length) { throw new Error("远端 base64 原语不可用(方言探测 unknown)——该路径不支持文件传输"); @@ -322,9 +466,19 @@ export async function getFile( throw new Error(`本地目标是现存目录(拒绝下载落位):${localPath}`); } const enc = dialect.base64Encode.join(" "); - const r = await exec(`${enc} < ${q(remotePath)}`, { auditLabel: "file download" }); - if (r.exitCode !== 0) throw new Error(`get 编码回传失败(exit=${r.exitCode})`); - const content = Buffer.from(r.stdout.replace(/\s+/g, ""), "base64"); + let content: Buffer; + if (opts.chunkB64 !== undefined) { + content = await readPagedFileBytes(exec, enc, remotePath, { + maxDirectB64: opts.chunkB64, + pageB64: Math.min(8_000, opts.chunkB64), + auditLabel: "file download", + opLabel: "get", + }); + } else { + const r = await exec(`${enc} < ${q(remotePath)}`, { auditLabel: "file download" }); + if (r.exitCode !== 0) throw new Error(`get 编码回传失败(exit=${r.exitCode})`); + content = Buffer.from(r.stdout.replace(/\s+/g, ""), "base64"); + } const localSha = createHash("sha256").update(content).digest("hex"); // 校验先行:不过 → 本地目标零接触(临时都不建) const v = await verify(exec, dialect, remotePath, content.length, localSha); @@ -388,7 +542,9 @@ export type SftpSpawnImpl = (argv: string[], batch: string) => Promise<{ exitCod async function defaultSftpSpawn(argv: string[], batch: string, timeoutMs?: number): Promise<{ exitCode: number | null; stderr: string }> { if (sshFileStdioRequested()) return spawnWithFileRedirect(argv, batch, { executable: "sftp", timeoutMs }); return new Promise((resolve, reject) => { - const p: ChildProcess = defaultSpawn("sftp", argv, { stdio: ["pipe", "ignore", "pipe"], env: openSshEnvironment() }); + const p: ChildProcess = defaultSpawn("sftp", argv, { + stdio: ["pipe", "ignore", "pipe"], windowsHide: true, env: openSshEnvironment(), + }); const timer = timeoutMs ? setTimeout(() => { stderr += `\nsftp 超时(${timeoutMs}ms)`; p.kill("SIGKILL"); diff --git a/src/index.ts b/src/index.ts index c2c15e9..9ff1ca3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,9 +29,12 @@ export { transferLayerFile } from "./layer-file-transfer.js"; export type { FileTransferTransport, LayerFileTransferOptions, LayerFileTransferResult } from "./layer-file-transfer.js"; export * from "./layer-env.js"; export { resolveLocalShell } from "./shell-discovery.js"; -export { createAgentToolkit } from "./agent-toolkit.js"; +export { createAgentToolkit, TOOL_DEFS } from "./agent-toolkit.js"; export type { AgentToolkit, AgentToolDef, AgentToolHandlers, AgentToolkitOptions, + ConnectSshTarget, ConnectSshResult, ConnectSshBatchArgs, ConnectSshBatchResult, + ConnectIntoArgs, ConnectIntoResult, ObserveStreamResult, ReadPathResult, + AgentEditFileResult, ManagePathResult, ManageLayersResult, PushSshTarget, PushSshResult, PushSshBatchArgs, PushSshBatchResult, } from "./agent-toolkit.js"; export { discoverLayer } from "./layer-discovery.js"; diff --git a/src/layer-file-transfer.ts b/src/layer-file-transfer.ts index dd2e505..349a544 100644 --- a/src/layer-file-transfer.ts +++ b/src/layer-file-transfer.ts @@ -45,11 +45,13 @@ export async function transferLayerFile( const auditLabel = operation === "put" ? "file upload" : "file download"; const exec = (command: string) => driver.exec(command, { timeoutMs, auditLabel }); const dialect = await probeDialect(exec); + const isTmux = driver.descriptor.driver === "tmux" || Boolean(driver.descriptor.terminalId) || "terminal" in driver; + const chunkB64 = isTmux ? 12_000 : undefined; const result = operation === "put" ? (sftp ? await sftpPutFile(exec, dialect, localPath, layerPath, sftp) - : await putFile(exec, dialect, localPath, layerPath, { forceInplace })) + : await putFile(exec, dialect, localPath, layerPath, { chunkB64, forceInplace })) : (sftp ? await sftpGetFile(exec, dialect, layerPath, localPath, sftp) - : await getFile(exec, dialect, layerPath, localPath)); + : await getFile(exec, dialect, layerPath, localPath, { chunkB64 })); return { transport, ...result }; } diff --git a/src/local-driver.ts b/src/local-driver.ts index a7c9311..1df76c3 100644 --- a/src/local-driver.ts +++ b/src/local-driver.ts @@ -13,7 +13,8 @@ */ import { spawn } from "node:child_process"; import fs from "node:fs/promises"; -import { createWriteStream } from "node:fs"; +import { createWriteStream, realpath as realpathCallback } from "node:fs"; +import { promisify } from "node:util"; import { ExecCapture, parseCompletionMarker } from "./exec-capture.js"; import path from "node:path"; @@ -330,13 +331,122 @@ export class LocalRuntimeDriver implements RuntimeDriver { } } +const nativeRealpath = typeof realpathCallback?.native === "function" + ? promisify(realpathCallback.native) + : fs.realpath; + +/** Bun 在 Linux 上会对 fs.realpath/realpath.native 词法折叠 "..",POSIX 需逐段按内核语义解析符号链接 */ +async function resolvePosixRealpath(inputPath: string): Promise { + if (!inputPath) { + await fs.lstat(inputPath); + } + let absPath = inputPath; + if (!absPath.startsWith("/")) { + const procCwd = process.cwd(); + const sep = procCwd.endsWith("/") ? "" : "/"; + absPath = `${procCwd}${sep}${absPath}`; + } + let needDir = inputPath.length > 1 && inputPath.endsWith("/"); + const queue = absPath.split("/"); + let current = "/"; + let symlinkCount = 0; + while (queue.length > 0) { + const seg = queue.shift()!; + if (seg === "" || seg === ".") continue; + if (seg === "..") { + current = path.posix.dirname(current); + continue; + } + const next = current === "/" ? `/${seg}` : `${current}/${seg}`; + const st = await fs.lstat(next); + if (st.isSymbolicLink()) { + if (++symlinkCount > 40) { + throw Object.assign( + new Error(`ELOOP: too many levels of symbolic links, realpath '${inputPath}'`), + { code: "ELOOP" as const }, + ); + } + const linkTarget = await fs.readlink(next); + if (linkTarget.length > 1 && linkTarget.endsWith("/") && queue.every((s) => s === "")) { + needDir = true; + } + if (linkTarget.startsWith("/")) current = "/"; + queue.unshift(...linkTarget.split("/")); + continue; + } + if (!st.isDirectory() && (queue.some((s) => s !== "") || needDir)) { + throw Object.assign( + new Error(`ENOTDIR: not a directory, realpath '${inputPath}'`), + { code: "ENOTDIR" as const }, + ); + } + current = next; + } + return current; +} + +async function resolveRealpath(inputPath: string): Promise { + return process.platform === "win32" + ? await nativeRealpath(inputPath) + : await resolvePosixRealpath(inputPath); +} + +function sameOrAncestorPath(candidate: string, targetPath: string, isWin: boolean): boolean { + const normA = isWin ? candidate.toLowerCase() : candidate; + const normB = isWin ? targetPath.toLowerCase() : targetPath; + const trailing = normA.endsWith(path.sep) ? "" : path.sep; + return normA === normB || normB.startsWith(normA + trailing); +} + class LocalFileSystem implements FileSystemDriver { constructor(private readonly baseCwd?: string) {} - /** 相对路径基于 descriptor.cwd 解析(Hydrogen R10 #1:与 ssh 层 execChannel - * 的 cwd 继承对齐——曾直接落 process.cwd=跨后端行为不一致) */ + private rawBaseCwd(): string { + const procCwd = process.cwd(); + if (!this.baseCwd) return procCwd; + if (path.isAbsolute(this.baseCwd)) return this.baseCwd; + const sep = procCwd.endsWith(path.sep) ? "" : path.sep; + return `${procCwd}${sep}${this.baseCwd}`; + } + + /** 相对路径基于原始 descriptor.cwd 拼接,不做词法折叠以对齐 spawn({ cwd }) 的内核解析语义 */ private resolve(filePath: string): string { - return this.baseCwd ? path.resolve(this.baseCwd, filePath) : filePath; + if (!this.baseCwd || path.isAbsolute(filePath)) return filePath; + const base = this.rawBaseCwd(); + const sep = base.endsWith(path.sep) ? "" : path.sep; + return `${base}${sep}${filePath}`; + } + + private async resolveEntryPath(filePath: string, opts?: { ignoreMissingParent?: boolean }): Promise { + let rawPath: string; + if (path.isAbsolute(filePath)) { + rawPath = filePath; + } else { + const base = this.rawBaseCwd(); + let resolvedBase: string; + try { + resolvedBase = await resolveRealpath(base); + } catch (err) { + if (opts?.ignoreMissingParent && (err as NodeJS.ErrnoException)?.code === "ENOENT") { + return null; + } + throw err; + } + const sep = resolvedBase.endsWith(path.sep) ? "" : path.sep; + rawPath = `${resolvedBase}${sep}${filePath}`; + } + const rawParent = path.dirname(rawPath); + const baseName = path.basename(rawPath); + let realParent: string; + try { + realParent = await resolveRealpath(rawParent); + } catch (err) { + if (opts?.ignoreMissingParent && (err as NodeJS.ErrnoException)?.code === "ENOENT") { + return null; + } + throw err; + } + return path.join(realParent, baseName); } async readFile(filePath: string): Promise { @@ -356,8 +466,15 @@ class LocalFileSystem implements FileSystemDriver { return Buffer.from(buf).toString("base64"); } - async writeFile(filePath: string, content: string): Promise { - await fs.writeFile(this.resolve(filePath), content, "utf-8"); + async writeFile(filePath: string, content: string, options?: { exclusive?: boolean }): Promise { + await fs.writeFile(this.resolve(filePath), content, { + encoding: "utf-8", + ...(options?.exclusive ? { flag: "wx" } : {}), + }); + } + + async createFile(filePath: string, content: string): Promise { + await this.writeFile(filePath, content, { exclusive: true }); } async exists(filePath: string): Promise { @@ -369,20 +486,23 @@ class LocalFileSystem implements FileSystemDriver { } } - async stat(filePath: string): Promise<{ mtimeMs: number; size: number } | null> { + async stat(filePath: string): Promise<{ mtimeMs: number; size: number; isDirectory: boolean } | null> { try { const st = await fs.stat(this.resolve(filePath)); - return { mtimeMs: st.mtimeMs, size: st.size }; - } catch { - return null; + return { mtimeMs: st.mtimeMs, size: st.size, isDirectory: st.isDirectory() }; + } catch (err) { + const code = (err as NodeJS.ErrnoException)?.code; + if (code === "ENOENT" || code === "ENOTDIR") return null; + throw err; } } async readdir(dirPath: string): Promise { const resolved = this.resolve(dirPath); const dirents = await fs.readdir(resolved, { withFileTypes: true }); + const sep = resolved.endsWith(path.sep) ? "" : path.sep; return await Promise.all(dirents.map(async (d) => { - const stats = await fs.stat(path.join(resolved, d.name)).catch(() => null); + const stats = await fs.stat(`${resolved}${sep}${d.name}`).catch(() => null); return { name: d.name, isDirectory: d.isDirectory(), @@ -393,19 +513,90 @@ class LocalFileSystem implements FileSystemDriver { } async rm(filePath: string, options?: { recursive?: boolean; force?: boolean}): Promise { + const isWin = process.platform === "win32"; + const stripped = isWin ? filePath.replace(/[/\\]+$/, "") : filePath.replace(/\/+$/, ""); + if (!stripped || (isWin ? /(?:^|[/\\])\.{1,2}$/ : /(?:^|\/)\.{1,2}$/).test(stripped)) { + throw new Error(`rm 拒绝危险或无效路径: ${filePath}`); + } + if (isWin && /^[A-Za-z]:[/\\]*$/.test(filePath)) { + throw new Error(`rm 拒绝删除根目录: ${filePath}`); + } + const hasTrailingSep = isWin ? /[/\\]$/.test(filePath) : /\/$/.test(filePath); + if (!options?.recursive && !options?.force && hasTrailingSep) { + throw new Error(`rm 非递归删除需要单文件路径: ${filePath}`); + } + const baseCwdRaw = this.rawBaseCwd(); + const target = await this.resolveEntryPath(stripped, { ignoreMissingParent: options?.force }); + if (!target) return; + if (hasTrailingSep) { + const lstatSep = await fs.lstat(target).catch(() => null); + if (lstatSep && (lstatSep.isSymbolicLink() || !lstatSep.isDirectory())) { + throw new Error(`rm 目标不是真实目录(拒绝带尾分隔符的符号链接或文件): ${filePath}`); + } + } + if (target === path.parse(target).root) { + throw new Error(`rm 拒绝删除根目录: ${filePath}`); + } + if (options?.recursive) { + const realCwd = await resolveRealpath(baseCwdRaw).catch(() => path.resolve(baseCwdRaw)); + if (sameOrAncestorPath(target, realCwd, isWin)) { + throw new Error(`rm 拒绝删除工作目录或上级目录: ${filePath}`); + } + const lstat = await fs.lstat(target).catch(() => null); + if (lstat && !lstat.isSymbolicLink()) { + const realTarget = await resolveRealpath(target).catch(() => null); + if (realTarget && (realTarget === path.parse(realTarget).root + || sameOrAncestorPath(realTarget, realCwd, isWin))) { + throw new Error(`rm 拒绝删除工作目录或上级目录: ${filePath}`); + } + } + } 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); + await fs.rm(target, options); } async mkdir(dirPath: string, options?: {recursive?: boolean}): Promise { await fs.mkdir(this.resolve(dirPath), options); } + + async rename(from: string, to: string): Promise { + const isWin = process.platform === "win32"; + const hasTrailingOrDot = (p: string) => !p + || (isWin + ? /[/\\]$/.test(p) || /(?:^|[/\\])\.{1,2}$/.test(p) || /^[A-Za-z]:[/\\]*$/.test(p) + : /\/$/.test(p) || /(?:^|\/)\.{1,2}$/.test(p)); + if (hasTrailingOrDot(from) || hasTrailingOrDot(to)) { + throw new Error(`rename 需要精确的文件或目录路径: ${from} -> ${to}`); + } + const resolvedFrom = (await this.resolveEntryPath(from))!; + const resolvedTo = (await this.resolveEntryPath(to))!; + const destStat = await fs.stat(resolvedTo).catch(() => null); + if (destStat?.isDirectory()) { + throw new Error(`rename 失败(目标是现存目录): ${from} -> ${to}`); + } + const srcStat = await fs.lstat(resolvedFrom); + const destParentStat = await fs.stat(path.dirname(resolvedTo)); + if (srcStat.dev !== destParentStat.dev) { + throw Object.assign( + new Error(`rename 失败(不支持跨文件系统移动 EXDEV): ${from} -> ${to}`), + { code: "EXDEV" as const }, + ); + } + if (srcStat.isDirectory()) { + if (sameOrAncestorPath(resolvedFrom, resolvedTo, isWin)) { + throw Object.assign( + new Error(`rename 失败(不能将目录移入自身或子目录 EINVAL): ${from} -> ${to}`), + { code: "EINVAL" as const }, + ); + } + const destLstat = destStat ?? await fs.lstat(resolvedTo).catch(() => null); + if (destLstat) { + throw new Error(`rename 失败(目标已存在): ${from} -> ${to}`); + } + } + await fs.rename(resolvedFrom, resolvedTo); + } } diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 7a9e469..4e11685 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -17,7 +17,19 @@ import * as readline from "node:readline"; import { version } from "../package.json" with { type: "json" }; -import { TOOL_DEFS, type AgentToolHandlers, type AgentToolkit, type PushSshBatchResult, type PushSshResult } from "./agent-toolkit.js"; +import { + TOOL_DEFS, + type AgentEditFileResult, + type AgentToolHandlers, + type AgentToolkit, + type ConnectIntoResult, + type ConnectSshBatchResult, + type ConnectSshResult, + type ManageLayersResult, + type ManagePathResult, + type ObserveStreamResult, + type ReadPathResult, +} from "./agent-toolkit.js"; import { noopLogger, type FilaxisLogger } from "./logger.js"; const MCP_PROTOCOL_VERSION = "2025-06-18"; @@ -140,11 +152,11 @@ export class McpServer { // 在任何 schema 读取之前必达,是唯一可靠的发现面) instructions: [ "【先看这行】多文件读取/多命令巡检/同命令发往多层/定位排查 → 优先 run_batch(一次调用并行打包,支持传 layer 数组自动扇出,不要逐个工具循环);读工具 schema 时同轮并发读取(逐个读每步一趟 LLM);", - "管理后台任务或服务(等就绪、按错误模式停止、核实退出码)→ 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 核实。", + "建立或进入命名层(单台/批量 SSH 或 docker/kubectl 内层)→ connect_layer;查询、切换默认层或移除层 → manage_layers。", + "管理后台任务或服务(等就绪、按错误模式停止、核实退出码)→ start_session + stop_session。", + "实时查看日志或事件流 → observe_stream(传 command 开窗并可 wait_ms 带回首屏帧;传 window_id 按游标续读/回看),close_stream 回收流进程。", + "只读查看文件或目录 → read_path;受控 CAS 编辑或直接新建文本 → edit_file(CAS 模式支持 write_mode:'inplace' 保 inode 免重启);创建目录、移动/重命名或删除(含递归) → manage_path;主机与目标层间传文件 → transfer_file。", + "契约:退出码是数据(非零不是异常);终态三态 exited/stopped/unknown;unknown 后用 stop_session 核实。", ].join("\n"), }); return; @@ -163,15 +175,16 @@ export class McpServer { case "tools/call": { const name = String(params.name ?? ""); const args = (params.arguments ?? {}) as Record; - const handler = (this.tk.handlers as unknown as Record) => Promise>)[name]; - if (!TOOL_DEFS.some((d) => d.function.name === name) || typeof handler !== "function") { + const handlersRecord = this.tk.handlers as unknown as Record; + const handler = Object.hasOwn(handlersRecord, name) ? handlersRecord[name] : undefined; + if (typeof handler !== "function") { this.replyErr(id, -32602, `Unknown tool: ${name}`, { available: TOOL_DEFS.map((d) => d.function.name) }); return; } const textOnlyBatch = name === "run_batch" && args.output === "text"; try { if (typeof args !== "object" || Array.isArray(args)) throw new Error(`${name} 的 arguments 需为对象`); - const r = await handler(args); + const r = await (handler as (a: Record) => Promise)(args); // Some clients only expose content, so include bounded command output there. this.reply(id, { content: [{ type: "text", text: summarizeToolResult(name, r, textOnlyBatch) }], @@ -199,13 +212,27 @@ export class McpServer { exitCode: err.exitCode, }; const evidence: string[] = []; - if (err.outcome && (textOnlyBatch || name === "delete_file" || name === "spawn_and_observe")) { + if (typeof err.outcome === "string" && err.outcome) { evidence.push(`outcome=${singleLine(err.outcome)}`); } - if (name === "spawn_and_observe") { - if (err.sessionId) evidence.push(`session_id=${singleLine(err.sessionId)}`); - if (err.logBase) evidence.push(`log_base=${singleLine(err.logBase)}`); - if (err.exitCode != null) evidence.push(`exit_code=${err.exitCode}`); + if (typeof err.terminalId === "string" && err.terminalId) { + evidence.push(`terminal_id=${singleLine(err.terminalId)}`); + } + if (typeof err.sessionId === "string" && err.sessionId) { + evidence.push(`session_id=${singleLine(err.sessionId)}`); + } + if (typeof err.logBase === "string" && err.logBase) { + evidence.push(`log_base=${singleLine(err.logBase)}`); + } + if (typeof err.exitCode === "number") { + evidence.push(`exit_code=${err.exitCode}`); + } + if (Array.isArray(err.sessions) && err.sessions.length) { + const handles = err.sessions + .filter((s): s is { sessionId: string; logBase: string } => + Boolean(s && typeof s.sessionId === "string" && typeof s.logBase === "string")) + .map((s) => `${singleLine(s.sessionId)} (${singleLine(s.logBase)})`); + if (handles.length) evidence.push(`sessions=${handles.join(", ")}`); } const errorText = [...evidence, message].join("\n"); const overflow = name === "run_batch" && jsonStringBytes(errorText) > BATCH_TEXT_JSON_BYTES; @@ -235,51 +262,77 @@ export class McpServer { } +function summarizeFileContent(content: string): string { + if (!content.length) return "[空文件]"; + if (content.length <= FILE_TEXT_JSON_BYTES && jsonStringBytes(content) <= FILE_TEXT_JSON_BYTES) return content; + return limitText(content, "\n[文件正文已截断,完整正文见 structuredContent.content]", FILE_TEXT_JSON_BYTES); +} + function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolean): string { + if (name === "manage_layers") { + const result = value as ManageLayersResult; + if (result.action === "list") return result.text; + if (result.action === "activate") return `active_layer=${singleLine(result.active_layer)}`; + return `removed=${singleLine(result.removed)}`; + } if (name === "list_layers") { - const result = value as Awaited>; - return result.text; + return (value as Awaited>).text; } if (name === "set_active_layer") { - const result = value as Awaited>; - return `active_layer=${singleLine(result.active_layer)}`; + return `active_layer=${singleLine((value as Awaited>).active_layer)}`; + } + if (name === "manage_path") { + const result = value as ManagePathResult; + if (result.action === "mkdir") return `created=true | path=${singleLine(result.path)}`; + if (result.action === "move") return `moved=true | path=${singleLine(result.path)} -> ${singleLine(result.destination)}`; + return `deleted=true | path=${singleLine(result.path)}${result.recursive ? " | recursive=true" : ""}`; } if (name === "delete_file") { - const result = value as Awaited>; - return `deleted=true | path=${singleLine(result.path)}`; + return `deleted=true | path=${singleLine((value as Awaited>).path)}`; + } + if (name === "read_path") { + const result = value as ReadPathResult; + if (result.type === "directory") return summarizeDirectory(result); + return summarizeFileContent(result.content); } if (name === "read_file") { - const { content } = value as Awaited>; - if (!content.length) return "[空文件]"; - if (content.length <= FILE_TEXT_JSON_BYTES && jsonStringBytes(content) <= FILE_TEXT_JSON_BYTES) return content; - return limitText(content, "\n[文件正文已截断,完整正文见 structuredContent.content]", FILE_TEXT_JSON_BYTES); + return summarizeFileContent((value as Awaited>).content); + } + if (name === "list_directory") { + return summarizeDirectory(value as Awaited>); + } + if (name === "edit_file") { + const result = value as AgentEditFileResult; + if (result.mode === "write") { + return `created=${result.created} | bytes=${result.bytes_after} | path=${singleLine(result.path)}`; + } + const bits = [`replaced=${result.occurrences}`]; + if (result.write_mode) bits.push(`write_mode=${result.write_mode}`); + if (result.mutex) bits.push(`mutex=${result.mutex}`); + return bits.join(" | "); } - if (name === "spawn_and_observe") { - const result = value as Awaited>; + if (name === "start_session" || name === "spawn_and_observe") { + const result = value as Awaited>; const lines = [`session_id=${singleLine(result.session_id)}`, `log_base=${singleLine(result.log_base)}`]; if (result.note) lines.push(`note=${singleLine(result.note)}`); return lines.join("\n"); } - if (name === "stop_and_verify") { - const result = value as Awaited>; + if (name === "stop_session" || name === "stop_and_verify") { + const result = value as Awaited>; const lines = [`status=${result.status}`]; if (result.exit_code != null) lines.push(`exit_code=${result.exit_code}`); if (result.note) lines.push(`note=${singleLine(result.note)}`); return lines.join("\n"); } - 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 === "observe_stream" || name === "read_stream") { + return summarizeStreamRead(value as ObserveStreamResult); } - if (name === "push_ssh") { - const result = value as PushSshResult | PushSshBatchResult; + if (name === "connect_layer" || name === "push_ssh") { + const result = value as ConnectSshResult | ConnectSshBatchResult | ConnectIntoResult; if ("results" in result) { const overview = `status=${result.status}${result.active_layer ? ` | active_layer=${singleLine(result.active_layer)}` : ""}`; const lines = result.results.map((target) => target.status === "ok" @@ -288,6 +341,8 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea const summary = [overview, ...lines].join("\n"); return jsonStringBytes(summary) <= BATCH_TEXT_JSON_BYTES ? summary : limitBatchText(summary, FULL_OUTPUT_HINT); } + if ("reused" in result) return `layer=${singleLine(result.layer)} | reused=${result.reused}`; + return `layer=${singleLine(result.layer)}`; } if (name === "run_batch") { const result = value as Awaited>; @@ -328,13 +383,16 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea return limitBatchText([overview, ...prioritized].join("\n\n"), hint); } if (name === "put_file" || name === "get_file") { - const result = value as Awaited>; - return transferSummary(result); + return transferSummary(value as Awaited>); + } + if (name === "transfer_file") { + const result = value as Awaited>; + return `direction=${result.direction} | ${transferSummary(result)}`; } return summarize(value); } -function summarizeDirectory(result: Awaited>): string { +function summarizeDirectory(result: { path: string; entries: Array<{ name: string; isDirectory: boolean }> }): string { const header = `path=${singleLine(result.path)} | entries=${result.entries.length}`; const omitted = "\n[目录文本达到上限,完整结果见 structuredContent]"; const omittedBytes = jsonStringBytes(omitted) - 2; @@ -354,7 +412,7 @@ function summarizeDirectory(result: Awaited>): string { +function summarizeStreamRead(result: ObserveStreamResult): string { const { frames, last_delivered_seq: cursor } = result; const status = [ `window=${singleLine(result.window_id)}`, `frames=${frames.length}`, @@ -426,7 +484,7 @@ function limitText(text: string, suffix: string, maxBytes: number): string { return text.slice(0, lo) + suffix; } -function transferSummary(result: Awaited>): string { +function transferSummary(result: { bytes: number; transport: string; verification: string; write_mode: string }): string { return `bytes=${result.bytes} | transport=${result.transport} | verification=${result.verification} | write_mode=${result.write_mode}`; } diff --git a/src/runtime-stack.ts b/src/runtime-stack.ts index b746fb0..55d8fe0 100644 --- a/src/runtime-stack.ts +++ b/src/runtime-stack.ts @@ -368,7 +368,7 @@ export class RuntimeStack { // - 派生:pushChild/pushInto(ssh PTY 原语,派生即 init)——父子关系由 // descriptor 继承天然记录(connParams/sshHops/enterPipeline 全量继承) // - 回环检测幂等返回:同落点 identity 命中 → 返回既有层 reused:true(原版 - // push_ssh 判重语义的 Paramiko 化——报错是栈时代的脾气)+ 落点校验 + // SSH 连接判重语义的 Paramiko 化——报错是栈时代的脾气)+ 落点校验 // (hostname 实测 vs 期望,不符=撞了途经节点 → 拒绝,宁重连不错主机) // - snapshot/restore:descriptor 即层身份(tmux 层 terminalId 零成本 // re-attach 现场全保;ssh 层重握手 + enterPipeline 逐条重放=位置确定性恢复) @@ -679,7 +679,7 @@ export class RuntimeStack { /** * descriptor 落点 identity(路径末节点)比对既有层全部路径节点。 - * 判重边界(原版 push_ssh 语义忠实平移):**只在无 enter 管线的纯 ssh 落点层之间**—— + * 判重边界(原版 SSH 建层语义忠实平移):**只在无 enter 管线的纯 ssh 落点层之间**—— * enter 层(容器/内层 shell)的落点是容器而非宿主机,hop identity 管不到(enter 管线 * 不进 layerPathIdentities):同宿主机两个不同容器层会撞 identity + hostname 同为宿主机 * → 误幂等返回错容器。enter 层的身份与复用归 driverKey(含 enters 三列)。 diff --git a/src/ssh-file-stdio.ts b/src/ssh-file-stdio.ts index 7fb34ac..220fbec 100644 --- a/src/ssh-file-stdio.ts +++ b/src/ssh-file-stdio.ts @@ -76,7 +76,9 @@ export async function spawnWithFileRedirect(argv: string[], stdinCmd: string, op await cleanup(); throw Object.assign(new DOMException("exec aborted by AbortSignal(spawn 前检出)", "AbortError"), { outcome: "unknown" }); } - p = spawn(executable, argv, { stdio: [inFd, outFd, errFd], env: openSshEnvironment(process.env, opts.logger) }); + p = spawn(executable, argv, { + stdio: [inFd, outFd, errFd], windowsHide: true, env: openSshEnvironment(process.env, opts.logger), + }); p.once("error", (e: Error) => { spawnErr = e; }); // 本地拒启归账(ENOENT 等)——区别于远端执行结果 } catch (e) { // spawn 同步抛错清场(Sol 81 P2-5):argv 含 NUL 等被 Node 拒启—— diff --git a/src/ssh-helpers.ts b/src/ssh-helpers.ts index e098557..1f079de 100644 --- a/src/ssh-helpers.ts +++ b/src/ssh-helpers.ts @@ -426,7 +426,9 @@ async function lookupSshIdentity(hop: SshHop, logger?: FilaxisLogger): Promise]|\r(?!\n)/g; @@ -76,7 +77,9 @@ class PtyLink { this.fallbackSteps.clear(); this.fallbackSeen = undefined; const spawnAt = Date.now(); - this.proc = spawn("ssh", args, { stdio: ["pipe", "pipe", "pipe"], env: openSshEnvironment(process.env, logger) }); + this.proc = spawn("ssh", args, { + stdio: ["pipe", "pipe", "pipe"], windowsHide: true, env: openSshEnvironment(process.env, logger), + }); // spawn error 监听(Sol 87 P1-4):ssh 不在 PATH 时 ENOENT 是异步 error // 事件——无监听器=uncaughtException 崩**宿主**(调用方 try/catch 收不到 // 拒绝)。归 readyRejecter/pendingExitFailure(建链失败语义,非超时指纹) @@ -465,24 +468,47 @@ export class SshPtyDriver implements RuntimeDriver { }; const statOf = async (p: string) => { const operand = q(cdTargetArg(p)); - const r = await fsExec(`stat -Lc '%s %Y' ${operand} 2>/dev/null || stat -Lf '%z %m' ${operand} 2>/dev/null || true`); - return r.exitCode === 0 ? parseStat(r.stdout) : null; + const r = await fsExec( + `( test -d ${operand} && printf 'd ' || printf 'f '; ` + + `stat -Lc '%s %Y' ${operand} 2>/dev/null || stat -Lf '%z %m' ${operand} 2>/dev/null || LC_ALL=C ls -Lld -- ${operand} >/dev/null )`, + ); + if (r.exitCode !== 0) { + const detail = (r.stderr || r.stdout || "").trim(); + if (/permission denied|operation not permitted/i.test(detail)) { + throw new Error(`stat 权限不足: ${p}: ${detail}`); + } + return null; + } + const m = r.stdout.trim().match(/^([df])\s+([\s\S]+)$/); + if (!m) return null; + const parsed = parseStat(m[2]!); + return parsed ? { ...parsed, isDirectory: m[1] === "d" } : null; + }; + const writeFile: FileSystemDriver["writeFile"] = async (p, content, options) => { + writeDialect ??= probeDialect(fsExec).catch((error) => { + writeDialect = undefined; + throw error; + }); + await writeInplaceContent( + fsExec, await writeDialect, Buffer.from(content, "utf-8"), p, + undefined, { exclusive: options?.exclusive }, + ); }; this.fs = { async readFile(p) { // 远端 b64 直出+本地解码(Hydrogen R4 #2):曾远端 | base64 -d——①BSD 的 // base64 无 -d(-D)②exitCode 不查(文件不存在静默返回空串=契约违背, // runBatch 的 read 步骤误报 ok)③解码输出经 stdout UTF-8 拼接易损坏 - const r = await fsExec(`base64 2>/dev/null < ${q(p)}`); - if (r.exitCode !== 0) throw new Error(`readFile 失败(exit=${r.exitCode}): ${p}`); + const r = await fsExec(`base64 < ${q(p)}`); + if (r.exitCode !== 0) { + const detail = (r.stderr || r.stdout || "").trim(); + throw new Error(detail ? `readFile 失败(exit=${r.exitCode}): ${p}: ${detail}` : `readFile 失败(exit=${r.exitCode}): ${p}`); + } return decodeFileRead(r.stdout, p); }, - async writeFile(p, content) { - writeDialect ??= probeDialect(fsExec).catch((error) => { - writeDialect = undefined; - throw error; - }); - await writeInplaceContent(fsExec, await writeDialect, Buffer.from(content, "utf-8"), p); + writeFile, + async createFile(p, content) { + await writeFile(p, content, { exclusive: true }); }, async exists(p) { const r = await fsExec(`test -e ${q(p)} && echo Y || echo N`); @@ -490,13 +516,21 @@ export class SshPtyDriver implements RuntimeDriver { }, stat: statOf, async readdir(p): Promise { - const r = await fsExec(`cd ${q(cdTargetArg(p))} && [ -r . ] || exit 1; ` + + const target = cdTargetArg(p); + const dotTarget = q(`${target.replace(/\/+$/, "")}/.`); + const r = await fsExec( + `( if ! cd ${q(target)} 2>/dev/null; then LC_ALL=C ls -1 -- ${dotTarget} >/dev/null; exit 1; fi; ` + + `if [ ! -r . ]; then LC_ALL=C ls -1 -- . >/dev/null; exit 1; fi; ` + `for entry in .[!.]* ..?* [!.]*; do ` + `[ -e "./$entry" ] || [ -L "./$entry" ] || continue; ` + `if [ -d "./$entry" ]; then kind=d; else kind=f; fi; ` + `info=$(stat -c '%s %Y' "./$entry" 2>/dev/null || stat -f '%z %m' "./$entry" 2>/dev/null) || info=; ` + - `printf '%s\\0%s\\0%s\\0' "$entry" "$kind" "$info" || exit 1; done`); - if (r.exitCode !== 0) throw new Error(`readdir 失败(exit=${r.exitCode}): ${p}`); + `printf '%s\\0%s\\0%s\\0' "$entry" "$kind" "$info" || exit 1; done )`, + ); + if (r.exitCode !== 0) { + const detail = (r.stderr || r.stdout || "").trim(); + throw new Error(detail ? `readdir 失败(exit=${r.exitCode}): ${p}: ${detail}` : `readdir 失败(exit=${r.exitCode}): ${p}`); + } const frames = r.stdout.split("\0"); if (frames.pop() !== "" || frames.length % 3 !== 0) throw new Error(`readdir 未收到完整目录列表: ${p}`); const entries: FileEntry[] = []; @@ -509,13 +543,33 @@ 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 stripped = p.replace(/\/+$/, ""); + const trailingSlash = /\/$/.test(p); + if (!stripped || /(?:^|\/)\.{1,2}$/.test(stripped) || (!options?.recursive && trailingSlash)) { + throw new Error(`rm 拒绝危险或无效路径: ${p}`); + } + const rmCmd = `rm ${options?.recursive ? "-r " : ""}${options?.force ? "-f " : ""}-- ${q(p)}`; + if (options?.recursive) { + const guarded = buildPosixRmGuardCmd(p, { force: options?.force }); + const r = await fsExec(guarded); + if (r.exitCode !== 0) throwRemoteFsCmdError("rm", p, r); + return; + } + const r = await fsExec(rmCmd); if (r.exitCode !== 0) throw new Error(`rm 失败(exit=${r.exitCode}): ${p}`); }, async mkdir(p, options) { - const r = await fsExec(`mkdir ${options?.recursive ? "-p " : ""}${q(p)}`); + const r = await fsExec(`mkdir ${options?.recursive ? "-p " : ""}-- ${q(p)}`); if (r.exitCode !== 0) throw new Error(`mkdir 失败(exit=${r.exitCode}): ${p}`); }, + async rename(from, to) { + const invalid = (p: string) => !p || /\/$/.test(p) || /(?:^|\/)\.{1,2}$/.test(p); + if (invalid(from) || invalid(to)) { + throw new Error(`rename 需要精确的文件或目录路径: ${from} -> ${to}`); + } + const r = await fsExec(buildPosixRenameCmd(from, to)); + if (r.exitCode !== 0) throwRemoteFsCmdError("rename", `${from} -> ${to}`, r); + }, }; this.sessions = new RemoteSessionManager({ exec: (cmd) => this.exec(cmd), logger: this.log }); this.bindLink(); @@ -827,6 +881,7 @@ export class SshPtyDriver implements RuntimeDriver { const spawnAt = Date.now(); const p = spawn("ssh", argv, { env: openSshEnvironment(process.env, this.log), + windowsHide: true, // 本地 ssh 进程启动目录不用 options.cwd(GPT Astra 十轮 #1):cwd 是 // **远端**语义(stdinCmd 的 cd 前缀)——远端专属目录本地不存在则 // spawn ENOENT,连接尚未建立即崩。本地目录与远端工作目录无关。 diff --git a/src/stream-session-manager.ts b/src/stream-session-manager.ts index d7e92a0..1ae6a42 100644 --- a/src/stream-session-manager.ts +++ b/src/stream-session-manager.ts @@ -47,7 +47,7 @@ export interface StreamStartOptions { onScreen?: (snap: string, frames: number) => void; } -export type SpawnImpl = (cmd: string, argv: string[], opts: { stdio: unknown[]; env?: NodeJS.ProcessEnv }) => ChildProcess; +export type SpawnImpl = (cmd: string, argv: string[], opts: { stdio: unknown[]; env?: NodeJS.ProcessEnv; windowsHide?: boolean }) => ChildProcess; export interface StreamSessionManagerOptions { /** 禁用 ControlMaster(测试/平台受限) */ @@ -104,6 +104,7 @@ export class StreamSessionManager { const child = this.spawnImpl("ssh", argv, { stdio: [opts.stdinScript === undefined ? "ignore" : "pipe", "pipe", "pipe"], env: openSshEnvironment(process.env, this.log), + windowsHide: true, }); // spawn 启动失败前置监听(Sol 87 P2-8):error 事件异步到达——桥到 start // 的 reject(曾仅 finalizeStream→onExit→窗口 stale,open 照常返回零帧窗、 diff --git a/src/terminal/command-executer.ts b/src/terminal/command-executer.ts index 1096606..52286e5 100644 --- a/src/terminal/command-executer.ts +++ b/src/terminal/command-executer.ts @@ -361,10 +361,24 @@ export class CommandExecuter { // The nonce is split from the marker format so the echo isn't evidence. // A leading blank keeps dash-prefixed command names from being parsed as eval options. const safeCommand = `${SAFE_PREFIX} ${body}`; + const safeCmdBytes = Buffer.byteLength(safeCommand, "utf-8"); + if (safeCmdBytes > 15_500) { + throw new Error( + `tmux 单条命令过长(包装后 ${safeCmdBytes} 字节,超出 15500 字节上限);` + + `请改用 transfer_file 上传脚本后执行,或用 run_batch(先 kind="put" 上传脚本,再通过 after 依赖执行 kind="exec")`, + ); + } try { await this.sendKeys(id, safeCommand); } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + if (/command too long/i.test(msg)) { + throw new Error( + `tmux 单条命令过长(${msg});` + + `请改用 transfer_file 上传脚本后执行,或用 run_batch(先 kind="put" 上传脚本,再通过 after 依赖执行 kind="exec")`, + ); + } // **业务命令首次发送失败**(Sol 90 P1-4):sendKeys=写文本+提交回车两段 //——文本(或回车)送达与否不可知=执行结果未知。raw 抛曾直接放行队列, // 下一条已入队命令的文本照进本条前台任务。与哨兵失败(Sol 89 P1-2) @@ -372,7 +386,7 @@ export class CommandExecuter { sessionDead.add(key); sessionSttyOff.delete(key); throw new CommandExecError( - `业务命令发送失败(${e instanceof Error ? e.message : String(e)})——命令文本可能已送达且终态不可确认,会话已封存待重建`, + `业务命令发送失败(${msg})——命令文本可能已送达且终态不可确认,会话已封存待重建`, "", "unknown", ); } diff --git a/src/tmux-driver.ts b/src/tmux-driver.ts index ddadde3..2f443e5 100644 --- a/src/tmux-driver.ts +++ b/src/tmux-driver.ts @@ -21,7 +21,8 @@ import type { } from "./session-types.js"; import { noopLogger, type FilaxisLogger } from "./logger.js"; import { renderSessionCodeGuard, renderSessionGroupState, renderSessionWorker } from "./session-group.js"; -import { decodeFileRead } from "./file-transfer.js"; +import { readPagedFileBytes } from "./file-transfer.js"; +import { buildPosixRenameCmd, buildPosixRmGuardCmd, throwRemoteFsCmdError } from "./file-placement.js"; const q = (s: string) => `'${s.replace(/'/g, "'\\''")}'`; @@ -58,58 +59,19 @@ export class TmuxSessionDriver implements RuntimeDriver { const self = this; this.fs = { async readFile(p) { - // 真机实证(远端 Linux):pane capture 滚动窗口 ~500 行(capture_scrollback - // 缺省),80KB b64 在 220 列 pane 折行 400+ 行——窗口外头部永久丢;且远端 - // 解码形态长行折行混入多余换行。读方向两段式:小文件单次 b64 读回(本地 - // \s+ 归一解码——折行免疫);大文件 b64 落远端临时 + 字节分页读(每页 - // 8K b64 折 ~40 行稳居窗口内,与滚动窗口彻底解耦) - const st = await self.exec(`wc -c < ${q(p)} 2>/dev/null`); - // 凭证纪律(Sol 73 P1-2):编码/wc 命令失败(exit≠0)不作内容凭证 - //——故障注入时 base64 失败曾静默返回空串 - if (st.exitCode !== 0) throw new Error(`readFile 失败(wc 退出码 ${st.exitCode}): ${p}`); - const sizeText = st.stdout.trim(); - const size = Number(sizeText); - if (!/^\d+$/.test(sizeText) || !Number.isSafeInteger(size)) { - throw new Error(`readFile 失败(文件大小无法核实): ${p}`); - } - if (size * 2 <= 12_000) { - const r = await self.exec(`base64 < ${q(p)}`); - if (r.exitCode !== 0) throw new Error(`readFile 失败(base64 退出码 ${r.exitCode}): ${p}`); - return decodeFileRead(r.stdout, p, size); - } - const tmp = `/tmp/filaxis-read-${Math.random().toString(36).slice(2, 10)}.b64`; - // && 连接 + 退出码查(Hydrogen R11 #1):base64 失败(无权限/被删)曾仍 - // 创建空 tmp、wc -c 返 0 exit 0——readFile 静默返回空串而非报错 - const tot = await self.exec(`base64 < ${q(p)} > ${q(tmp)} && wc -c < ${q(tmp)}`); - const total = parseInt((tot.stdout || "").trim(), 10); - // total 异常也走 finally 清理(曾在此 throw 遗留 tmp——throw 挪 try 内) - try { - if (tot.exitCode !== 0 || !Number.isFinite(total)) { - throw new Error(`readFile 失败(base64 退出码 ${tot.exitCode}): ${p}`); - } - let b64 = ""; - for (let off = 1; off <= total; off += 8_000) { - const pg = await self.exec(`tail -c +${off} ${q(tmp)} | head -c 8000`); - // 分页凭证纪律(Sol 74 P1-2):管道尾 rc 只反映 head——中转文件 - // 被删/读取失败曾静默跳页,9KB 源文件返回 5.9KB 还正常完成。 - // 逐页退出码入闸 + 末尾长度对账(解码字节 == wc 实测源大小) - if (pg.exitCode !== 0) { - throw new Error(`readFile 分页读失败(页偏移 ${off} 退出码 ${pg.exitCode}): ${p}`); - } - b64 += pg.stdout.replace(/[ \t\r\n]+/g, ""); - } - return decodeFileRead(b64, p, size); - } finally { - await self.exec(`rm -f ${q(tmp)}`).catch(() => undefined); - } + const buf = await readPagedFileBytes((cmd) => self.exec(cmd), "base64", p); + return buf.toString("utf-8"); }, - async writeFile(p, content) { + async writeFile(p, content, options) { const buf = Buffer.from(content, "utf-8"); const { putContent, writeInplaceContent } = await import("./file-transfer.js"); const exec = (cmd: string) => self.exec(cmd); const dialect = await self.dialect(); - if (buf.length <= 9_000) await writeInplaceContent(exec, dialect, buf, p, 12_000); - else await putContent(exec, dialect, buf, p, { chunkB64: 12_000 }); + if (buf.length <= 9_000) await writeInplaceContent(exec, dialect, buf, p, 12_000, { exclusive: options?.exclusive }); + else await putContent(exec, dialect, buf, p, { chunkB64: 12_000, exclusive: options?.exclusive }); + }, + async createFile(p, content) { + await (self.fs.writeFile)(p, content, { exclusive: true }); }, async exists(p) { const r = await self.exec(`test -e ${q(p)} && echo Y || echo N`); @@ -117,10 +79,20 @@ export class TmuxSessionDriver implements RuntimeDriver { }, async stat(p) { const operand = q(cdTargetArg(p)); - const r = await self.exec(`stat -Lc '%s %Y' ${operand} 2>/dev/null || stat -Lf '%z %m' ${operand} 2>/dev/null || true`); - if (r.exitCode !== 0) return null; - const m = r.stdout.trim().match(/^(\d+)\s+(\d+)$/); - return m ? { size: parseInt(m[1]!, 10), mtimeMs: parseInt(m[2]!, 10) * 1000 } : null; + // 持久会话 shell 内严禁裸 exit(必须包在 ( ... ) 子 shell 中) + const r = await self.exec( + `( test -d ${operand} && printf 'd ' || printf 'f '; ` + + `stat -Lc '%s %Y' ${operand} 2>/dev/null || stat -Lf '%z %m' ${operand} 2>/dev/null || LC_ALL=C ls -Lld -- ${operand} >/dev/null )`, + ); + if (r.exitCode !== 0) { + const detail = (r.stderr || r.stdout || "").trim(); + if (/permission denied|operation not permitted/i.test(detail)) { + throw new Error(`stat 权限不足: ${p}: ${detail}`); + } + return null; + } + const m = r.stdout.trim().match(/^([df])\s+(\d+)\s+(-?\d+)$/); + return m ? { size: parseInt(m[2]!, 10), mtimeMs: parseInt(m[3]!, 10) * 1000, isDirectory: m[1] === "d" } : null; }, async readdir(p): Promise { // 逐名 hex 帧传输(Sol 89 P2-1):PTY 里 ls 的**终端展示形态**对 @@ -132,10 +104,13 @@ export class TmuxSessionDriver implements RuntimeDriver { // 列出来的是别处);**cd 锚定 cdTargetArg**(Sol 90 P2-2:相对路径 // 裸交 cd 被 CDPATH 改写到另一棵树、命中还打印路径进 hex 流触发帧 // 损坏);**glob 用 `.* *` + case 排 . / ..**(Sol 90 P2-1:`.[!.]*` - // 曾把 `..hidden` 这类「第二个字符是点」的合法名静默漏掉);cd 失败 - // 零输出=空列表(旧 ls || true 同语义) + // 曾把 `..hidden` 这类「第二个字符是点」的合法名静默漏掉) + const target = cdTargetArg(p); + const dotTarget = q(`${target.replace(/\/+$/, "")}/.`); const r = await self.exec( - `( unset GLOBIGNORE; set +f; cd ${q(cdTargetArg(p))} 2>/dev/null || exit; ` + + `( unset GLOBIGNORE; set +f; ` + + `if ! cd ${q(target)} 2>/dev/null; then LC_ALL=C ls -1 -- ${dotTarget} >/dev/null; exit 1; fi; ` + + `if [ ! -r . ]; then LC_ALL=C ls -1 -- . >/dev/null; exit 1; fi; ` + `printf 'FX_LIST;'; __fx_n=0; for __fx_e in .[!.]* ..?* [!.]*; do ` + `[ -e "$__fx_e" ] || [ -L "$__fx_e" ] || continue; ` + `__fx_hex=$(printf %s "$__fx_e" | od -An -v -tx1) || exit 1; ` + @@ -146,7 +121,10 @@ export class TmuxSessionDriver implements RuntimeDriver { const end = frames.at(-2)?.match(/^FX_COUNT_(\d+)$/); if (r.exitCode !== 0 || frames[0] !== "FX_LIST" || frames.at(-1) !== "" || !end || Number(end[1]) !== frames.length - 3) { - throw new Error(`readdir 未收到完整目录列表(exit=${r.exitCode}): ${p}`); + const detail = (r.stderr || r.stdout || "").trim(); + throw new Error(detail + ? `readdir 未收到完整目录列表(exit=${r.exitCode}): ${p}: ${detail}` + : `readdir 未收到完整目录列表(exit=${r.exitCode}): ${p}`); } const out: FileEntry[] = []; for (const h of frames.slice(1, -2)) { @@ -165,15 +143,35 @@ 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 stripped = p.replace(/\/+$/, ""); + const trailingSlash = /\/$/.test(p); + if (!stripped || /(?:^|\/)\.{1,2}$/.test(stripped) || (!options?.recursive && trailingSlash)) { + throw new Error(`rm 拒绝危险或无效路径: ${p}`); + } + const rmCmd = `rm ${options?.recursive ? "-r " : ""}${options?.force ? "-f " : ""}-- ${q(p)}`; + if (options?.recursive) { + const guarded = buildPosixRmGuardCmd(p, { force: options?.force }); + const r = await self.exec(guarded); + if (r.exitCode !== 0) throwRemoteFsCmdError("rm", p, r); + return; + } + const r = await self.exec(rmCmd); // force 只影响命令形态(-f 豁免缺席路径——exit 0);非零退出=真实 // 失败(目录未递归删等)照传(Sol 88 P2-1:曾 force 下吞掉一切非零 //——对现存目录的非递归删除谎报完成、目录仍在) - if (r.exitCode !== 0) throw new Error(`rm 失败(exit=${r.exitCode}): ${p}`); + if (r.exitCode !== 0) throwRemoteFsCmdError("rm", p, r); }, async mkdir(p, options) { - const r = await self.exec(`mkdir ${options?.recursive ? "-p " : ""}${q(p)}`); - if (r.exitCode !== 0) throw new Error(`mkdir 失败(exit=${r.exitCode}): ${p}`); + const r = await self.exec(`mkdir ${options?.recursive ? "-p " : ""}-- ${q(p)}`); + if (r.exitCode !== 0) throwRemoteFsCmdError("mkdir", p, r); + }, + async rename(from, to) { + const invalid = (p: string) => !p || /\/$/.test(p) || /(?:^|\/)\.{1,2}$/.test(p); + if (invalid(from) || invalid(to)) { + throw new Error(`rename 需要精确的文件或目录路径: ${from} -> ${to}`); + } + const r = await self.exec(buildPosixRenameCmd(from, to)); + if (r.exitCode !== 0) throwRemoteFsCmdError("rename", `${from} -> ${to}`, r); }, }; } @@ -383,7 +381,7 @@ export class TmuxSessionDriver implements RuntimeDriver { throw new Error("tmux 层不支持 env(send-keys 键入回显会混入输出捕获——终端物理语义);请内联进命令文本或换 ssh/local 层"); } // signal 显式拒绝(Hydrogen R4 #3):runCommand 通道无 abort 挂钩——静默忽略 - // 会让调用方以为可取消。指路 execSession+stop_and_verify(有完整三态收口) + // 会让调用方以为可取消。指路 execSession+stopSession(有完整三态收口) if (options?.signal) { throw new Error("tmux 层 exec 不支持 AbortSignal(runCommand 无中断挂钩);改用 execSession + stopSession(三态收口)"); } diff --git a/src/windows-upload-acl.ts b/src/windows-upload-acl.ts index 3ec9b99..ba15185 100644 --- a/src/windows-upload-acl.ts +++ b/src/windows-upload-acl.ts @@ -54,3 +54,25 @@ if ([IO.File]::Exists($target)) { } } `); + +export const windowsPlaceExclusivePayload = powershell(` +$source = $env:FILAXIS_UPLOAD_SOURCE +$target = $env:FILAXIS_UPLOAD_TARGET +if (Test-Path -LiteralPath $target) { + Write-Output 'FX_ALREADY_EXISTS' + exit 1 +} +try { + [IO.File]::Move($source, $target) +} catch [IO.IOException] { + if (Test-Path -LiteralPath $target) { + Write-Output 'FX_ALREADY_EXISTS' + exit 1 + } + throw +} +& icacls.exe $target /reset | Out-Null +if ($LASTEXITCODE -ne 0) { + throw 'Upload was published but its inherited ACL could not be applied' +} +`); diff --git a/tests/agent-toolkit.test.ts b/tests/agent-toolkit.test.ts index 6e4bcc5..b3a8ba9 100644 --- a/tests/agent-toolkit.test.ts +++ b/tests/agent-toolkit.test.ts @@ -44,7 +44,7 @@ describe("createAgentToolkit(反馈 #3)", () => { await stack.removeLayer("fixture", { destroy: true }); }); - test("push_ssh batch excludes layers replaced before the response", async () => { + test("connect_layer batch excludes layers replaced before the response", async () => { const stack = new RuntimeStack(); const addLayer = stack.addLayer.bind(stack); const slowEntered = Promise.withResolvers(); @@ -56,7 +56,7 @@ describe("createAgentToolkit(反馈 #3)", () => { } return addLayer(name, new MockSshDriver({ driver: "fixture" }) as unknown as RuntimeDriver); }; - const batch = createAgentToolkit(stack).handlers.push_ssh({ targets: ["first", "slow"] }); + const batch = createAgentToolkit(stack).handlers.connect_layer({ targets: ["first", "slow"] }); try { await slowEntered.promise; await stack.removeLayer("first", { destroy: true }); @@ -79,22 +79,24 @@ describe("createAgentToolkit(反馈 #3)", () => { 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", "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 names = tk.tools.map((t) => t.function.name); + expect(names).toEqual([ + "run_batch", // 置顶(高杠杆批处理工具必须在首屏) + "run_command", "start_session", "stop_session", + "observe_stream", "close_stream", + "read_path", "edit_file", "manage_path", "transfer_file", + "connect_layer", "manage_layers", ]); + expect(names.every((n) => /^[a-z]+_[a-z]+$/.test(n))).toBe(true); const r = await tk.handlers.run_command({ command: "echo tk-out; exit 4" }); expect(r.stdout.trim()).toBe("tk-out"); expect(r.exit_code).toBe(4); // 非零不抛——数据 expect(r.effective_user).toBeTruthy(); }, 20_000); - test("spawn_and_observe 就绪握手(回溯竞态安全)+ stop_and_verify 三态", async () => { + test("start_session 就绪握手(回溯竞态安全)+ stop_session 三态", async () => { const tk = createAgentToolkit(new RuntimeStack(), { readyTimeoutMs: 10_000 }); - const h = await tk.handlers.spawn_and_observe({ + const h = await tk.handlers.start_session({ command: "sleep 0.5; echo LISTENING-OK; sleep 30", ready_marker: "LISTENING-OK", error_pattern: "NEVER_MATCH", @@ -102,7 +104,7 @@ describe("createAgentToolkit(反馈 #3)", () => { }); expect(h.session_id).toContain("tk-"); expect(h.note).toBe("ready"); - const s = await tk.handlers.stop_and_verify({ session_id: h.session_id }); + const s = await tk.handlers.stop_session({ session_id: h.session_id }); // local 面三态皆合法(Astra 二轮 #2 后:TERM/KILL 后仍核实不到死亡=unknown 诚实返回, // Windows 下 bash 子进程树收 TERM 偶有不退净——不再伪报 stopped) expect(["exited", "stopped", "unknown"]).toContain(s.status); @@ -110,36 +112,36 @@ describe("createAgentToolkit(反馈 #3)", () => { // GPT Astra #3:旧形态 driver 返回 {exitCode: null}(终止已发、无死亡证明—— // tmux 后端 stop 后 .code 未落盘正是此形态)——必须报 unknown,不得报 stopped - test("stop_and_verify:无 status 且 exitCode null → unknown(无死亡证明不伪 stopped)", async () => { + test("stop_session:无 status 且 exitCode null → unknown(无死亡证明不伪 stopped)", async () => { const fakeOldDriver = { descriptor: { driver: "tmux", target: "mock" }, async stopSession() { return { exitCode: null }; }, // 旧形态:发了 kill,没核实 } as unknown as import("../src/driver.js").RuntimeDriver; const tk = createAgentToolkit(new RuntimeStack(), { driver: fakeOldDriver }); - const r = await tk.handlers.stop_and_verify({ session_id: "s", layer: "__initial__" }); + const r = await tk.handlers.stop_session({ session_id: "s", layer: "__initial__" }); expect(r.status).toBe("unknown"); // 修前:stopped(违宪——终止≠已核实) - expect(r.note).toContain("verify"); // unknown 后自动接 verify(双通道不可达才保持) + expect(r.note).toContain("stop_session"); // unknown 后自动接 verify(双通道不可达才保持) }, 15_000); - test("stop_and_verify validates the handle and needs an exit code before reporting exited", async () => { + test("stop_session validates the handle and needs an exit code before reporting exited", async () => { let stopCalls = 0; const driver = { async stopSession() { stopCalls++; return { status: "exited", exitCode: null }; }, async verifySession() { return { status: "exited", exitCode: null }; }, } as unknown as RuntimeDriver; const { handlers } = createAgentToolkit(new RuntimeStack(), { driver }); - await expect(handlers.stop_and_verify({ session_id: "", layer: "__initial__" })).rejects.toThrow(/完整的非空会话 ID/); - await expect(handlers.stop_and_verify({ session_id: "fixture", layer: "" })).rejects.toThrow(/非空层名/); + await expect(handlers.stop_session({ session_id: "", layer: "__initial__" })).rejects.toThrow(/完整的非空会话 ID/); + await expect(handlers.stop_session({ session_id: "fixture", layer: "" })).rejects.toThrow(/非空层名/); expect(stopCalls).toBe(0); - expect(await handlers.stop_and_verify({ session_id: "fixture", layer: "__initial__" })).toMatchObject({ - status: "unknown", note: expect.stringContaining("再次调用 stop_and_verify"), + expect(await handlers.stop_session({ session_id: "fixture", layer: "__initial__" })).toMatchObject({ + status: "unknown", note: expect.stringContaining("再次调用 stop_session"), }); expect(stopCalls).toBe(1); }); // GPT Astra 二轮 #3:spawn 在远端层的会话曾固定回初始层停(停错层必然失败)—— // 修后按归属层(spawn 时的 driver)停止 - test("stop_and_verify:跨层会话按归属层停止(不落初始层)", async () => { + test("stop_session:跨层会话按归属层停止(不落初始层)", async () => { const stack = new RuntimeStack(); let initStopped: string[] = []; let remoteStopped: string[] = []; @@ -158,9 +160,9 @@ describe("createAgentToolkit(反馈 #3)", () => { // 初始层 = initDrv;命名远端层 = remoteDrv await stack.addLayer("remote", remoteDrv); const tk = createAgentToolkit(stack, { driver: initDrv }); - const h = await tk.handlers.spawn_and_observe({ command: "srv", ready_marker: "READY" }); + const h = await tk.handlers.start_session({ command: "srv", ready_marker: "READY" }); // spawn 落默认层(remote——最近注册)——stop 必须回 remote 停 - const s = await tk.handlers.stop_and_verify({ session_id: h.session_id }); + const s = await tk.handlers.stop_session({ session_id: h.session_id }); expect(s.status).toBe("stopped"); expect(remoteStopped).toContain(h.session_id); // 归属层停了 expect(initStopped).toEqual([]); // 初始层没被误用(修前:停错层报不存在) @@ -168,7 +170,7 @@ describe("createAgentToolkit(反馈 #3)", () => { }, 15_000); // GPT Astra 三轮 #1:unknown 终态**保留归属**(修前停止前就删——重试核实回退初始层停错层) - test("stop_and_verify:unknown 后重试仍找归属层;终态确定才清归属", async () => { + test("stop_session:unknown 后重试仍找归属层;终态确定才清归属", async () => { const stack = new RuntimeStack(); const calls: string[] = []; let stopResult: { status: string; exitCode?: number } = { status: "unknown" }; @@ -187,13 +189,13 @@ describe("createAgentToolkit(反馈 #3)", () => { } as unknown as RuntimeDriver; await stack.addLayer("r2", remoteDrv); const tk = createAgentToolkit(stack, { driver: initDrv }); - await tk.handlers.spawn_and_observe({ command: "c", ready_marker: "R" }); + await tk.handlers.start_session({ command: "c", ready_marker: "R" }); // 第一次:unknown → 归属必须保留 - const r1 = await tk.handlers.stop_and_verify({ session_id: "rs-own" }); + const r1 = await tk.handlers.stop_session({ session_id: "rs-own" }); expect(r1.status).toBe("unknown"); // 重试(网络恢复后再核实):仍走归属层,不落初始层 stopResult = { status: "exited", exitCode: 0 }; - const r2 = await tk.handlers.stop_and_verify({ session_id: "rs-own" }); + const r2 = await tk.handlers.stop_session({ session_id: "rs-own" }); expect(r2).toEqual({ status: "exited", exit_code: 0 }); expect(calls).toEqual(["remote:rs-own", "remote:rs-own"]); // 两次都在归属层(修前第二次落 init) await stack.removeLayer("r2"); @@ -201,7 +203,7 @@ describe("createAgentToolkit(反馈 #3)", () => { // GPT Astra 四轮 #1:旧形态 {exitCode:null}(status undefined)归一为 unknown—— // 归属必须保留(修前 status!=="unknown" 判断把 undefined 当确定终态→删归属→重试落初始层) - test("stop_and_verify:旧形态无死亡证明归一 unknown 且保留归属(重试仍找归属层)", async () => { + test("stop_session:旧形态无死亡证明归一 unknown 且保留归属(重试仍找归属层)", async () => { const stack = new RuntimeStack(); const calls: string[] = []; let stopResult: { exitCode?: number | null; status?: string } = { exitCode: null }; // 旧形态 @@ -220,12 +222,12 @@ describe("createAgentToolkit(反馈 #3)", () => { } as unknown as RuntimeDriver; await stack.addLayer("old", remoteDrv); const tk = createAgentToolkit(stack, { driver: initDrv }); - await tk.handlers.spawn_and_observe({ command: "c", ready_marker: "R" }); - const r1 = await tk.handlers.stop_and_verify({ session_id: "old-s" }); + await tk.handlers.start_session({ command: "c", ready_marker: "R" }); + const r1 = await tk.handlers.stop_session({ session_id: "old-s" }); expect(r1.status).toBe("unknown"); // 归一:无死亡证明 // 重试:仍走归属层 stopResult = { status: "exited", exitCode: 0 }; - const r2 = await tk.handlers.stop_and_verify({ session_id: "old-s" }); + const r2 = await tk.handlers.stop_session({ session_id: "old-s" }); expect(r2.status).toBe("exited"); expect(calls).toEqual(["remote:old-s", "remote:old-s"]); // 修前第二次 init:old-s await stack.removeLayer("old"); @@ -233,47 +235,51 @@ describe("createAgentToolkit(反馈 #3)", () => { }); describe("toolkit 层族(第十季命名层注册表)", () => { - test("push_into/list_layers/remove_layer + layer 参数寻址 + 无层族时零破坏", async () => { + test("connect_layer/manage_layers + layer 参数寻址 + 无层族时零破坏", async () => { const stack = new RuntimeStack(); stack.registerDriver("mockssh", (d) => new MockSshDriver(d) as unknown as RuntimeDriver); const tk = createAgentToolkit(stack, {}); // 零破坏:未用层族——run_command 落初始 local 层(旧行为) const r0 = await tk.handlers.run_command({ command: "echo OLD_PATH" }); expect(r0.stdout).toContain("OLD_PATH"); - // push_into 无源层报错 - await expect(tk.handlers.push_into({ enter_cmd: "docker exec -i web sh" })).rejects.toThrow(/无源层/); - // 注册 mock 层(driver 形态)→ 成默认层 → 六工具自动落它 + // connect_layer(enter_cmd) 无源层报错 + await expect(tk.handlers.connect_layer({ enter_cmd: "docker exec -i web sh" })).rejects.toThrow(/无源层/); + // 注册 mock 层(driver 形态)→ 成默认层 → 工具自动落它 const m = new MockSshDriver({ driver: "mockssh", target: "h1" }); await m.init(); await stack.addLayer("host1", m as unknown as RuntimeDriver); const r1 = await tk.handlers.run_command({ command: "anything" }); expect(r1.stdout).toContain("mock:"); // 落 mock 层而非 local - // push_into 从默认层派生 - const p = await tk.handlers.push_into({ enter_cmd: "docker exec -i web sh", label: "docker:web" }); + // connect_layer(enter_cmd) 从默认层派生 + const p = await tk.handlers.connect_layer({ enter_cmd: "docker exec -i web sh", label: "docker:web" }); expect(p.layer).toBe("docker:web"); expect(enterStepsOf(stack.layer("docker:web").descriptor.config as Record).length).toBe(1); // 参数别名宽收(第十二季):enterCommand 手滑等价——派生自当前默认层 docker:web, // enter 管线全量继承追加(web→db 两步,继承语义) - const p2 = await tk.handlers.push_into({ enterCommand: "docker exec -i db sh" } as never); + const p2 = await tk.handlers.connect_layer({ enterCommand: "docker exec -i db sh" }); expect(p2.layer).toBe("docker exec -i db sh".slice(0, 30)); expect(enterStepsOf(stack.layer("docker exec -i db sh".slice(0, 30)).descriptor.config as Record).length).toBe(2); // layer 显式寻址(跨层) const r2 = await tk.handlers.run_command({ command: "x", layer: "host1" }); expect(r2.stdout).toContain("mock:"); - // list_layers / remove_layer(host1 + docker:web + db 派生层 = 3 层) - const ls = await tk.handlers.list_layers({}); + // manage_layers list / activate / remove(host1 + docker:web + db 派生层 = 3 层) + const ls = await tk.handlers.manage_layers({ action: "list" }); expect(ls.text).toContain("host1"); expect(ls.text).toContain("docker:web"); expect(ls.layers.length).toBe(3); - await tk.handlers.remove_layer({ name: "docker:web" }); - expect((await tk.handlers.list_layers({})).layers.length).toBe(2); - await tk.handlers.remove_layer({ name: "docker exec -i db sh".slice(0, 30) }); + expect(await tk.handlers.manage_layers({ action: "activate", name: "host1" })).toEqual({ + action: "activate", active_layer: "host1", + }); + expect((await tk.handlers.run_command({ command: "x" })).stdout).toContain("mock:"); + await tk.handlers.manage_layers({ action: "remove", name: "docker:web" }); + expect((await tk.handlers.manage_layers({ action: "list" })).layers.length).toBe(2); + await tk.handlers.manage_layers({ action: "remove", name: "docker exec -i db sh".slice(0, 30) }); RuntimeStack.evictDriver({ driver: "mockssh", target: "h1" } as RuntimeDescriptor); }, 20_000); }); // GPT Astra 三十四期 P1:ready 超时谎称「已自动停止」——unknown 须诚实 + 会话线索 + verify -describe("spawn_and_observe ready 超时三态(三十四期)", () => { +describe("start_session ready 超时三态(三十四期)", () => { const mkDrv = (stopStatus: string | Error, verify?: { status: string; exitCode?: number | null }) => ({ descriptor: { driver: "local" }, exec: async () => ({ stdout: "", stderr: "", exitCode: 0 }), @@ -288,7 +294,7 @@ describe("spawn_and_observe ready 超时三态(三十四期)", () => { test("stop unknown + verify unknown → outcome:unknown + 会话线索(不再谎称已停)", async () => { const tk = createAgentToolkit(new RuntimeStack(), { driver: mkDrv("unknown"), readyTimeoutMs: 150 }); let caught: (Error & { outcome?: string; sessionId?: string; logBase?: string }) | undefined; - try { await tk.handlers.spawn_and_observe({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } + try { await tk.handlers.start_session({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } expect(caught?.message).not.toContain("已自动停止"); // 修前:谎称 expect(caught?.message).toContain("可能仍在运行"); // 诚实警告 expect(caught?.outcome).toBe("unknown"); @@ -299,7 +305,7 @@ describe("spawn_and_observe ready 超时三态(三十四期)", () => { test("stop unknown + verify exited → 采纳真实退出码(stopped 语义)", async () => { const tk = createAgentToolkit(new RuntimeStack(), { driver: mkDrv("unknown", { status: "exited", exitCode: 7 }), readyTimeoutMs: 150 }); let caught: (Error & { outcome?: string }) | undefined; - try { await tk.handlers.spawn_and_observe({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } + try { await tk.handlers.start_session({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } expect(caught?.outcome).toBe("stopped"); expect(caught?.message).toContain("exitCode=7"); }, 15_000); @@ -307,7 +313,7 @@ describe("spawn_and_observe ready 超时三态(三十四期)", () => { test("stop stopped → 如实 stopped(无 verify 调用需求)", async () => { const tk = createAgentToolkit(new RuntimeStack(), { driver: mkDrv("stopped"), readyTimeoutMs: 150 }); let caught: (Error & { outcome?: string }) | undefined; - try { await tk.handlers.spawn_and_observe({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } + try { await tk.handlers.start_session({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } expect(caught?.outcome).toBe("stopped"); expect(caught?.message).toContain("停止已核实"); }, 15_000); @@ -315,7 +321,7 @@ describe("spawn_and_observe ready 超时三态(三十四期)", () => { test("stop 通道抛错 → unknown(会话线索保留)", async () => { const tk = createAgentToolkit(new RuntimeStack(), { driver: mkDrv(new Error("channel dead")), readyTimeoutMs: 150 }); let caught: (Error & { outcome?: string }) | undefined; - try { await tk.handlers.spawn_and_observe({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } + try { await tk.handlers.start_session({ command: "x", ready_marker: "READY" }); } catch (e) { caught = e as never; } expect(caught?.outcome).toBe("unknown"); }, 15_000); }); @@ -337,7 +343,7 @@ describe("三十五期", () => { } as unknown as import("../src/driver.js").RuntimeDriver; const tk = createAgentToolkit(new RuntimeStack(), { driver: drv }); let caught: (Error & { outcome?: string; sessionId?: string; logBase?: string }) | undefined; - try { await tk.handlers.spawn_and_observe({ command: "x", ready_marker: "RDY", error_pattern: "ERR" }); } catch (e) { caught = e as never; } + try { await tk.handlers.start_session({ command: "x", ready_marker: "RDY", error_pattern: "ERR" }); } catch (e) { caught = e as never; } expect(caught?.outcome).toBe("stopped"); // stop 核实可靠 expect(caught?.sessionId).toBe("fx-post-boot"); // 修前:裸抛无线索 expect(caught?.message).toContain("watcher backend dead"); // 原因保留 @@ -357,7 +363,7 @@ describe("三十五期", () => { } as unknown as import("../src/driver.js").RuntimeDriver; const tk = createAgentToolkit(new RuntimeStack(), { driver: drv, readyTimeoutMs: 10_000 }); let caught: (Error & { outcome?: string; sessionId?: string }) | undefined; - try { await tk.handlers.spawn_and_observe({ command: "x", ready_marker: "RDY" }); } catch (e) { caught = e as never; } + try { await tk.handlers.start_session({ command: "x", ready_marker: "RDY" }); } catch (e) { caught = e as never; } expect(caught?.outcome).toBe("unknown"); // verify 实测 running expect(caught?.message).toContain("实测仍在运行"); // 诚实警告 expect(caught?.message).toContain("tail channel broke"); // 原因保留 @@ -384,7 +390,7 @@ test("ready 等待期间核实未知时继续等待,且不请求停止", async stopSession: async () => { stops++; return { status: "stopped" }; }, } as unknown as RuntimeDriver; const toolkit = createAgentToolkit(new RuntimeStack(), { driver, readyTimeoutMs: 4000 }); - const result = await toolkit.handlers.spawn_and_observe({ command: "fixture", ready_marker: "READY" }); + const result = await toolkit.handlers.start_session({ command: "fixture", ready_marker: "READY" }); expect(result.note).toBe("ready"); expect(stops).toBe(0); }); @@ -407,10 +413,10 @@ test("natural exit releases Agent routing and caches the verified result for a b sessionResultTtlMs: 150, sessionCheckIntervalMs: 10, }); - await toolkit.handlers.spawn_and_observe({ command: "fixture" }); + await toolkit.handlers.start_session({ command: "fixture" }); finished = true; await Bun.sleep(35); - const stop = toolkit.handlers.stop_and_verify; + const stop = toolkit.handlers.stop_session; expect(await stop({ session_id: "short" })).toEqual({ status: "exited", exit_code: 9 }); expect(explicitStops).toBe(0); await Bun.sleep(170); @@ -432,10 +438,10 @@ test("drivers without a session registry are probed without issuing stop request stopSession: async () => { throw Error("expected cached result"); }, } as unknown as RuntimeDriver; const toolkit = createAgentToolkit(new RuntimeStack(), { driver, sessionCheckIntervalMs: 5 }); - await toolkit.handlers.spawn_and_observe({ command: "fixture" }); + await toolkit.handlers.start_session({ command: "fixture" }); await probed.promise; await Bun.sleep(10); - expect(await toolkit.handlers.stop_and_verify({ session_id: "external" })).toEqual({ status: "exited", exit_code: 4 }); + expect(await toolkit.handlers.stop_session({ session_id: "external" })).toEqual({ status: "exited", exit_code: 4 }); }); test("toolkit rebuilds its configured initial layer after that layer is destroyed", async () => { @@ -452,22 +458,28 @@ test("toolkit rebuilds its configured initial layer after that layer is destroye }); const toolkit = createAgentToolkit(stack, { descriptor: { driver: "fixture" } }); expect((await toolkit.handlers.run_command({ command: "first" })).stdout).toBe("1"); - await toolkit.handlers.remove_layer({ name: "__initial__", destroy: true }); + await toolkit.handlers.manage_layers({ action: "remove", name: "__initial__", destroy: true }); expect((await toolkit.handlers.run_command({ command: "second" })).stdout).toBe("2"); - await toolkit.handlers.remove_layer({ name: "__initial__", destroy: true }); + await toolkit.handlers.manage_layers({ action: "remove", name: "__initial__", destroy: true }); }); -test("observe_stream opens the selected layer and rejects unsupported layers", async () => { +test("observe_stream opens with initial frames, supports incremental reads, and rejects unsupported layers", async () => { const stack = new RuntimeStack(); const local = new (await import("../src/local-driver.js")).LocalRuntimeDriver(); await stack.addLayer("selected", local); const toolkit = createAgentToolkit(stack, { driver: {} as RuntimeDriver }); try { - const { window_id } = await toolkit.handlers.observe_stream({ command: "echo SELECTED", layer: "selected" }); - const result = await toolkit.handlers.read_stream({ window_id, since_seq: 0, wait_ms: 8000 }); - expect(result.frames.map((frame) => frame.text)).toEqual(["SELECTED"]); - await toolkit.handlers.close_stream({ window_id }); - await expect(toolkit.handlers.read_stream({ window_id })).rejects.toThrow(/已关闭/); + const opened = await toolkit.handlers.observe_stream({ command: "echo SELECTED", layer: "selected", wait_ms: 8000 }); + expect(opened.frames.map((frame) => frame.text)).toEqual(["SELECTED"]); + expect(opened.last_delivered_seq).toBe(1); + const followUp = await toolkit.handlers.observe_stream({ window_id: opened.window_id, since_seq: opened.last_delivered_seq }); + expect(followUp.frames).toEqual([]); + await toolkit.handlers.close_stream({ window_id: opened.window_id }); + await expect(toolkit.handlers.observe_stream({ window_id: opened.window_id })).rejects.toThrow(/已关闭/); + await expect(toolkit.handlers.observe_stream({ command: "echo X", window_id: "w" } as never)).rejects.toThrow(/不能同时传/); + await expect(toolkit.handlers.observe_stream({} as never)).rejects.toThrow(/需传 command/); + await expect(toolkit.handlers.observe_stream({ command: "echo X", since_seq: 0 } as never)).rejects.toThrow(/不支持 since_seq/); + await expect(toolkit.handlers.observe_stream({ window_id: opened.window_id, stream: "stdout" } as never)).rejects.toThrow(/不支持.*stream/); await stack.removeLayer("selected"); await stack.addLayer("unsupported", { descriptor: { driver: "mock" }, exec: async () => ({ stdout: "", stderr: "", exitCode: 0 }) } as unknown as RuntimeDriver); await expect(toolkit.handlers.observe_stream({ command: "echo WRONG", layer: "unsupported" })).rejects.toThrow(/不支持持续观察窗/); @@ -475,3 +487,1184 @@ test("observe_stream opens the selected layer and rejects unsupported layers", a toolkit.dispose?.(); } }, 15000); + +describe("12-tool convergence coverage (read_path, edit_file write, manage_path, transfer_file, connect_layer, manage_layers)", () => { + test("read_path falls back cleanly when custom driver stat omits isDirectory", async () => { + const customDrv = { + descriptor: { driver: "custom" }, + fs: { + stat: async () => ({ size: 0, mtimeMs: 100 }), + readFile: async (p: string) => { + if (p === "dir") throw new Error("EISDIR"); + return "file-body"; + }, + readdir: async () => [{ name: "a.txt", isDirectory: false }], + }, + } as unknown as RuntimeDriver; + const tk = createAgentToolkit(new RuntimeStack(), { driver: customDrv }); + expect(await tk.handlers.read_path({ path: "file" })).toEqual({ + path: "file", type: "file", content: "file-body", size: 0, mtime_ms: 100, + }); + expect(await tk.handlers.read_path({ path: "dir" })).toEqual({ + path: "dir", type: "directory", entries: [{ name: "a.txt", isDirectory: false }], + }); + }); + + test("edit_file write mode supports empty files, create_dirs, overwrite guard, and rejects mixed/invalid params", async () => { + const { mkdtempSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const dir = mkdtempSync(join(tmpdir(), "fx-edit-write-")); + const stack = new RuntimeStack(); + const drv = new (await import("../src/local-driver.js")).LocalRuntimeDriver({ cwd: dir }); + await stack.addLayer("w", drv); + const tk = createAgentToolkit(stack); + try { + expect(await tk.handlers.edit_file({ path: "empty.txt", content: "" })).toEqual({ + mode: "write", path: "empty.txt", created: true, bytes_after: 0, + }); + expect(readFileSync(join(dir, "empty.txt"), "utf8")).toBe(""); + await expect(tk.handlers.edit_file({ path: "sub/a.txt", content: "v1" })).rejects.toThrow(); + expect(await tk.handlers.edit_file({ path: "sub/a.txt", content: "v1", create_dirs: true })).toEqual({ + mode: "write", path: "sub/a.txt", created: true, bytes_after: 2, + }); + await expect(tk.handlers.edit_file({ path: "sub/a.txt", content: "v2" })).rejects.toThrow(/拒绝覆盖/); + expect(await tk.handlers.edit_file({ path: "sub/a.txt", content: "v2", overwrite: true })).toEqual({ + mode: "write", path: "sub/a.txt", created: false, bytes_after: 2, + }); + expect(readFileSync(join(dir, "sub/a.txt"), "utf8")).toBe("v2"); + await expect(tk.handlers.edit_file({ path: "sub/a.txt", content: "x", old: "v2", new: "v3" } as never)).rejects.toThrow(/互斥/); + await expect(tk.handlers.edit_file({ path: "sub/a.txt", content: "x", write_mode: "auto" } as never)).rejects.toThrow(/未知参数/); + await expect(tk.handlers.edit_file({ path: "sub/a.txt" } as never)).rejects.toThrow(/需传 old 和 new/); + } finally { + await stack.removeLayer("w", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("manage_path handles mkdir, move, and safe/recursive delete", async () => { + const { mkdtempSync, writeFileSync, existsSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const dir = mkdtempSync(join(tmpdir(), "fx-manage-path-")); + const stack = new RuntimeStack(); + const drv = new (await import("../src/local-driver.js")).LocalRuntimeDriver({ cwd: dir }); + await stack.addLayer("fs", drv); + const tk = createAgentToolkit(stack); + try { + await expect(tk.handlers.manage_path({ action: "mkdir", path: "a/b/c", parents: false })).rejects.toThrow(); + expect(await tk.handlers.manage_path({ action: "mkdir", path: "a/b/c" })).toEqual({ + action: "mkdir", path: "a/b/c", created: true, + }); + writeFileSync(join(dir, "a/b/c/file.txt"), "hello"); + expect(await tk.handlers.manage_path({ action: "move", path: "a/b/c/file.txt", destination: "a/moved.txt" })).toEqual({ + action: "move", path: "a/b/c/file.txt", destination: "a/moved.txt", moved: true, + }); + expect(existsSync(join(dir, "a/b/c/file.txt"))).toBe(false); + expect(readFileSync(join(dir, "a/moved.txt"), "utf8")).toBe("hello"); + + await expect(tk.handlers.manage_path({ action: "delete", path: "a" })).rejects.toThrow(); + const dangerousPaths = process.platform === "win32" + ? ["/", "\\", ".", "..", "C:\\", "a/..", "a/."] + : ["/", ".", "..", "a/..", "a/."]; + for (const dangerous of dangerousPaths) { + await expect(tk.handlers.manage_path({ action: "delete", path: dangerous, recursive: true })).rejects.toThrow(/拒绝删除/); + } + expect(await tk.handlers.manage_path({ action: "delete", path: "a", recursive: true })).toEqual({ + action: "delete", path: "a", deleted: true, recursive: true, + }); + expect(existsSync(join(dir, "a"))).toBe(false); + + await expect(tk.handlers.manage_path({ action: "mkdir", path: "x", recursive: true } as never)).rejects.toThrow(/未知参数/); + await expect(tk.handlers.manage_path({ action: "move", path: "x", destination: "y", parents: true } as never)).rejects.toThrow(/未知参数/); + await expect(tk.handlers.manage_path({ action: "nope", path: "x" } as never)).rejects.toThrow(/action 须为/); + } finally { + await stack.removeLayer("fs", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("transfer_file, connect_layer, and manage_layers validate mode-specific arguments", async () => { + const tk = createAgentToolkit(new RuntimeStack()); + await expect(tk.handlers.transfer_file({ direction: "sync", local_path: "a", remote_path: "b" } as never)).rejects.toThrow(/direction/); + await expect(tk.handlers.transfer_file({ direction: "get", local_path: "a", remote_path: "b", write_mode: "inplace" } as never)).rejects.toThrow(/不支持 write_mode/); + await expect(tk.handlers.connect_layer({ enter_cmd: "sh", host: "web" } as never)).rejects.toThrow(/互斥/); + await expect(tk.handlers.connect_layer({ host: "web", from: "base" } as never)).rejects.toThrow(/不支持 from 或 label/); + await expect(tk.handlers.connect_layer({} as never)).rejects.toThrow(/需提供 host/); + await expect(tk.handlers.manage_layers({ action: "list", name: "x" } as never)).rejects.toThrow(/未知参数/); + await expect(tk.handlers.manage_layers({ action: "activate", name: "x", destroy: true } as never)).rejects.toThrow(/只接受 action 和 name/); + await expect(tk.handlers.manage_layers({ action: "unknown" } as never)).rejects.toThrow(/action 须为/); + }); +}); + +describe("audit regression fixes (P1/P2/P3)", () => { + test("[P1] recursive delete rejects equivalent parent/cwd paths and preserves workspace files", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, existsSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { basename, join } = await import("node:path"); + const dir = mkdtempSync(join(tmpdir(), "fx-rm-guard-")); + const stack = new RuntimeStack(); + const drv = new (await import("../src/local-driver.js")).LocalRuntimeDriver({ cwd: dir }); + await stack.addLayer("fs", drv); + const tk = createAgentToolkit(stack); + try { + mkdirSync(join(dir, "subdir", "deep"), { recursive: true }); + writeFileSync(join(dir, "keep.txt"), "keep"); + writeFileSync(join(dir, "subdir", "nested.txt"), "nested"); + const cwdSelfRel = `../${basename(dir)}`; + for (const p of ["subdir/..//", "subdir/..\\", "subdir/deep/../..//", "./", ".///", cwdSelfRel, dir]) { + await expect(tk.handlers.manage_path({ action: "delete", path: p, recursive: true })).rejects.toThrow(); + await expect(drv.fs.rm(p, { recursive: true, force: false })).rejects.toThrow(); + } + expect(existsSync(dir)).toBe(true); + expect(readFileSync(join(dir, "keep.txt"), "utf8")).toBe("keep"); + expect(readFileSync(join(dir, "subdir", "nested.txt"), "utf8")).toBe("nested"); + } finally { + await stack.removeLayer("fs", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("[P1] concurrent edit_file default writes are atomic and never overwrite each other", async () => { + const { mkdtempSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const dir = mkdtempSync(join(tmpdir(), "fx-excl-write-")); + const stack = new RuntimeStack(); + const drv = new (await import("../src/local-driver.js")).LocalRuntimeDriver({ cwd: dir }); + await stack.addLayer("w", drv); + const tk = createAgentToolkit(stack); + try { + const results = await Promise.allSettled([ + tk.handlers.edit_file({ path: "race.txt", content: "first-writer" }), + tk.handlers.edit_file({ path: "race.txt", content: "second-writer" }), + ]); + const fulfilled = results.filter((r): r is PromiseFulfilledResult<{ mode: "write"; path: string; created: boolean; bytes_after: number }> => r.status === "fulfilled"); + const rejected = results.filter((r): r is PromiseRejectedResult => r.status === "rejected"); + expect(fulfilled).toHaveLength(1); + expect(fulfilled[0]!.value.created).toBe(true); + expect(rejected).toHaveLength(1); + expect(String(rejected[0]!.reason)).toContain("拒绝覆盖"); + const expected = fulfilled[0]!.value.bytes_after === 12 ? "first-writer" : "second-writer"; + expect(readFileSync(join(dir, "race.txt"), "utf8")).toBe(expected); + } finally { + await stack.removeLayer("w", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("[P1] move/rename rejects existing destination directories on local and SSH/tmux commands", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-rename-guard-")); + const stack = new RuntimeStack(); + const local = new LocalRuntimeDriver({ cwd: dir }); + await stack.addLayer("localfs", local); + const tk = createAgentToolkit(stack); + try { + mkdirSync(join(dir, "destDir")); + writeFileSync(join(dir, "src.txt"), "from-src"); + writeFileSync(join(dir, "destDir", "src.txt"), "existing-inside-dir"); + + // Local driver via manage_path + await expect(tk.handlers.manage_path({ action: "move", path: "src.txt", destination: "destDir" })).rejects.toThrow(/目录/); + expect(readFileSync(join(dir, "src.txt"), "utf8")).toBe("from-src"); + expect(readFileSync(join(dir, "destDir", "src.txt"), "utf8")).toBe("existing-inside-dir"); + + // SSH driver exact shell command executed in real POSIX shell (cwd = dir) + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = (cmd: string) => local.exec(cmd); + await expect(ssh.fs.rename!("src.txt", "destDir")).rejects.toThrow(); + expect(readFileSync(join(dir, "src.txt"), "utf8")).toBe("from-src"); + expect(readFileSync(join(dir, "destDir", "src.txt"), "utf8")).toBe("existing-inside-dir"); + + // Tmux driver exact shell command executed in real POSIX shell (cwd = dir) + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = (cmd: string) => local.exec(cmd); + await expect(tmux.fs.rename!("src.txt", "destDir")).rejects.toThrow(); + expect(readFileSync(join(dir, "src.txt"), "utf8")).toBe("from-src"); + expect(readFileSync(join(dir, "destDir", "src.txt"), "utf8")).toBe("existing-inside-dir"); + + // Exclusive write via SSH fs.writeFile refuses concurrent/existing overwrite + await ssh.fs.writeFile("excl.txt", "first", { exclusive: true }); + await expect(ssh.fs.writeFile("excl.txt", "second", { exclusive: true })).rejects.toThrow(); + expect(readFileSync(join(dir, "excl.txt"), "utf8")).toBe("first"); + + // Valid rename to non-existent file still works via SSH driver command + await ssh.fs.rename!("src.txt", "renamed.txt"); + expect(readFileSync(join(dir, "renamed.txt"), "utf8")).toBe("from-src"); + + // SSH recursive rm guard inside real POSIX shell + const sub = join(dir, "sub"); + mkdirSync(sub); + writeFileSync(join(dir, "keep.txt"), "keep"); + const { basename } = await import("node:path"); + await expect(ssh.fs.rm(`../${basename(dir)}`, { recursive: true })).rejects.toThrow(); + await expect(ssh.fs.rm("sub/..//", { recursive: true })).rejects.toThrow(); + expect(readFileSync(join(dir, "keep.txt"), "utf8")).toBe("keep"); + } finally { + await stack.removeLayer("localfs", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("[P2] read_path lists directories on custom drivers without fs.stat", async () => { + const noStatDriver = { + descriptor: { driver: "nostat" }, + fs: { + readdir: async () => [{ name: "only.txt", isDirectory: false }], + }, + } as unknown as RuntimeDriver; + const tk = createAgentToolkit(new RuntimeStack(), { driver: noStatDriver }); + expect(await tk.handlers.read_path({ path: "/data" })).toEqual({ + path: "/data", + type: "directory", + entries: [{ name: "only.txt", isDirectory: false }], + }); + const brokenDriver = { + descriptor: { driver: "nostat-err" }, + fs: { + readdir: async () => { throw new Error("permission denied"); }, + }, + } as unknown as RuntimeDriver; + const tk2 = createAgentToolkit(new RuntimeStack(), { driver: brokenDriver }); + await expect(tk2.handlers.read_path({ path: "/secret" })).rejects.toThrow(/fs\.stat 缺席.*permission denied/); + }); + + test("[P3] connect_layer schema oneOf accepts all advertised enter_cmd aliases", async () => { + const { TOOL_DEFS } = await import("../src/agent-toolkit.js"); + const connectDef = TOOL_DEFS.find((d) => d.function.name === "connect_layer")!; + const oneOf = connectDef.function.parameters.oneOf as Array<{ + additionalProperties?: boolean; + properties: Record; + required: string[]; + }>; + for (const alias of ["enter_cmd", "enter_command", "enterCommand", "enterCmd"]) { + const matching = oneOf.filter((branch) => + branch.required.includes(alias) + && branch.additionalProperties === false + && Object.hasOwn(branch.properties, alias), + ); + expect(matching).toHaveLength(1); + } + + const stack = new RuntimeStack(); + const drv = new MockSshDriver({ driver: "mockssh", target: "h1" }); + await drv.init(); + await stack.addLayer("base", drv as unknown as RuntimeDriver); + const tk = createAgentToolkit(stack); + try { + const r1 = await tk.handlers.connect_layer({ enter_command: "docker exec -i c1 sh", name: "c1" }); + expect(r1.layer).toBe("c1"); + const r2 = await tk.handlers.connect_layer({ enterCmd: "docker exec -i c2 sh", from: "base", name: "c2" }); + expect(r2.layer).toBe("c2"); + await expect(tk.handlers.connect_layer({ enter_cmd: "a", enterCommand: "b" } as never)).rejects.toThrow(/只能传一个/); + } finally { + await Promise.all([...stack.layers.keys()].map((n) => stack.removeLayer(n, { destroy: true }))); + } + }); + + test("[P1] exclusive upload refuses directory created after pre-check and reports partial write separately from EEXIST", async () => { + const { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-excl-posix-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + const stagesCreated: string[] = []; + const basePosixExec = (transform?: (cmd: string) => string) => async (cmd: string) => { + const actual = transform ? transform(cmd) : cmd; + const r = await local.exec(`uname() { echo Linux; }; ${actual}`); + const m = r.stdout.trim().match(/^\/tmp\/filaxis-write\.[A-Za-z0-9]{10}$/); + if (m) stagesCreated.push(m[0]!); + return r; + }; + try { + // 1. Target becomes a directory right after pre-check: must fail with EEXIST and not link inside dir. + const sshDirRace = new SshPtyDriver({ driver: "ssh", target: "mock" }); + let injectedDir = false; + (sshDirRace as unknown as { execChannel: (cmd: string) => Promise }).execChannel = basePosixExec((cmd) => { + if (cmd.includes("exec 3>") && !injectedDir) { + injectedDir = true; + return cmd.replace("FX_ALREADY_EXISTS; exit 1; fi;", "FX_ALREADY_EXISTS; exit 1; fi; mkdir -p 'race-dir.txt';"); + } + return cmd; + }); + await expect(sshDirRace.fs.createFile!("race-dir.txt", "should-not-enter-dir")).rejects.toMatchObject({ + code: "EEXIST", + }); + expect(injectedDir).toBe(true); + expect(readdirSync(join(dir, "race-dir.txt"))).toEqual([]); + + // 2. Write fails/interrupts after set -C creates target: must NOT report EEXIST and must preserve staged payload. + const sshWriteFail = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (sshWriteFail as unknown as { execChannel: (cmd: string) => Promise }).execChannel = basePosixExec((cmd) => + cmd.includes("exec 3>") ? `cat() { printf 'half'; return 1; }; ${cmd}` : cmd, + ); + let caught: unknown; + try { + await sshWriteFail.fs.createFile!("partial.txt", "complete-payload"); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(Error); + const errObj = caught as NodeJS.ErrnoException; + expect(errObj.code).not.toBe("EEXIST"); + expect(errObj.message).toContain("独占写入失败"); + expect(errObj.message).not.toContain("文件已存在"); + expect(readFileSync(join(dir, "partial.txt"), "utf8")).toBe("half"); + const payloadMatch = errObj.message.match(/完整载荷保留在 (\S+)/); + expect(payloadMatch).toBeTruthy(); + const verifyPayload = await local.exec(`test -f '${payloadMatch![1]!.replace(/'/g, "'\\''")}' && cat '${payloadMatch![1]!.replace(/'/g, "'\\''")}'`); + expect(verifyPayload.exitCode).toBe(0); + expect(verifyPayload.stdout).toBe("complete-payload"); + + // 3. On POSIX platforms with mkfifo (Linux/WSL/macOS), FIFO created after pre-check is atomically rejected without writing to the pipe reader. + if (process.platform !== "win32") { + const sshFifoRace = new SshPtyDriver({ driver: "ssh", target: "mock" }); + let injectedFifo = false; + (sshFifoRace as unknown as { execChannel: (cmd: string) => Promise }).execChannel = basePosixExec((cmd) => { + if (cmd.includes("ln -T --") && !injectedFifo) { + injectedFifo = true; + return cmd.replace( + "FX_ALREADY_EXISTS; exit 1; fi;", + "FX_ALREADY_EXISTS; exit 1; fi; mkfifo 'race-fifo' && { cat 'race-fifo' > 'fifo-captured.txt' /dev/null & printf '%s' \"$!\" > 'fifo-reader.pid'; }; sleep 0.05;", + ); + } + return cmd; + }); + await expect(sshFifoRace.fs.createFile!("race-fifo", "never-sent-to-fifo")).rejects.toMatchObject({ + code: "EEXIST", + }); + expect(injectedFifo).toBe(true); + const fifoOut = await local.exec( + "test -p 'race-fifo' && echo FIFO_OK; " + + ": > 'race-fifo' 2>/dev/null || true; " + + "kill \"$(cat 'fifo-reader.pid' 2>/dev/null)\" 2>/dev/null || true; " + + "cat 'fifo-captured.txt' 2>/dev/null || true", + ); + expect(fifoOut.stdout).toContain("FIFO_OK"); + expect(fifoOut.stdout).not.toContain("never-sent-to-fifo"); + } + } finally { + for (const s of stagesCreated) { + await local.exec(`rm -rf '${s}'`).catch(() => undefined); + } + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("[P1] edit_file default write requires explicit fs.createFile and rejects 2-arg writeFile drivers", async () => { + const files = new Map(); + let writeCalls = 0; + const legacyCustomDriver = { + descriptor: { driver: "custom-2arg" }, + fs: { + exists: async (p: string) => files.has(p), + writeFile: async (p: string, c: string) => { + writeCalls++; + files.set(p, c); + }, + }, + } as unknown as RuntimeDriver; + const tk = createAgentToolkit(new RuntimeStack(), { driver: legacyCustomDriver }); + await expect(tk.handlers.edit_file({ path: "doc.txt", content: "first" })).rejects.toThrow(/fs\.createFile 缺席/); + expect(writeCalls).toBe(0); + expect(await tk.handlers.edit_file({ path: "doc.txt", content: "forced", overwrite: true })).toEqual({ + mode: "write", path: "doc.txt", created: true, bytes_after: 6, + }); + expect(files.get("doc.txt")).toBe("forced"); + + const atomicDriver = { + descriptor: { driver: "custom-excl" }, + fs: { + exists: async (p: string) => files.has(p), + writeFile: async (p: string, c: string) => { files.set(p, c); }, + createFile: async (p: string, c: string) => { + if (files.has(p)) throw Object.assign(new Error(`文件已存在: ${p}`), { code: "EEXIST" }); + files.set(p, c); + }, + }, + } as unknown as RuntimeDriver; + const tkAtomic = createAgentToolkit(new RuntimeStack(), { driver: atomicDriver }); + expect(await tkAtomic.handlers.edit_file({ path: "fresh.txt", content: "created" })).toEqual({ + mode: "write", path: "fresh.txt", created: true, bytes_after: 7, + }); + await expect(tkAtomic.handlers.edit_file({ path: "fresh.txt", content: "second" })).rejects.toThrow(/拒绝覆盖/); + expect(files.get("fresh.txt")).toBe("created"); + }); + + test("[P2] read_path lists directories when fs.stat is defined but returns null (missing remote stat)", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-nostat-ssh-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = (cmd: string) => + local.exec(`stat() { return 127; }; ${cmd}`); + const stack = new RuntimeStack(); + await stack.addLayer("nostatssh", ssh); + const tk = createAgentToolkit(stack); + try { + mkdirSync(join(dir, "sub")); + writeFileSync(join(dir, "hello.txt"), "hi"); + expect(await ssh.fs.stat!(".")).toBeNull(); + const res = await tk.handlers.read_path({ path: "." }); + expect(res.type).toBe("directory"); + if (res.type === "directory") { + expect(res.entries.map((e) => e.name).sort()).toEqual(["hello.txt", "sub"]); + } + await expect(tk.handlers.read_path({ path: "missing-dir" })).rejects.toThrow(/路径不存在/); + } finally { + await stack.removeLayer("nostatssh", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("[P1] local recursive rm resolves symlink/../ paths via filesystem semantics and keeps workspace data", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const root = mkdtempSync(join(tmpdir(), "fx-local-symlink-rm-")); + const ws = join(root, "ws"); + const outside = join(root, "outside"); + const outsideSub = join(outside, "sub"); + const outsideData = join(outside, "data"); + const wsData = join(ws, "data"); + mkdirSync(wsData, { recursive: true }); + mkdirSync(outsideSub, { recursive: true }); + mkdirSync(outsideData, { recursive: true }); + writeFileSync(join(wsData, "keep.txt"), "ws-intact"); + writeFileSync(join(outsideData, "victim.txt"), "outside-data"); + symlinkSync(outsideSub, join(ws, "link"), process.platform === "win32" ? "junction" : "dir"); + const wsDeep = join(ws, "deep"); + mkdirSync(wsDeep, { recursive: true }); + symlinkSync(root, join(ws, "to-root"), process.platform === "win32" ? "junction" : "dir"); + + const local = new LocalRuntimeDriver({ cwd: ws }); + try { + await local.fs.rm("link/../data", { recursive: true, force: false }); + if (process.platform === "win32") { + // Win32 RtlDosPathNameToNtPathName collapses ".." before junctions in the OS itself. + expect(existsSync(wsData)).toBe(false); + expect(readFileSync(join(outsideData, "victim.txt"), "utf8")).toBe("outside-data"); + mkdirSync(wsData, { recursive: true }); + writeFileSync(join(wsData, "keep.txt"), "ws-intact"); + } else { + // POSIX VFS resolves symlinks left-to-right before applying "..". + expect(existsSync(outsideData)).toBe(false); + expect(readFileSync(join(wsData, "keep.txt"), "utf8")).toBe("ws-intact"); + } + + // Symlink path resolving back to workspace root must be refused. + await expect(local.fs.rm("to-root/ws", { recursive: true, force: false })).rejects.toThrow(/拒绝删除工作目录/); + await expect(local.fs.rm("deep/../to-root/ws", { recursive: true, force: false })).rejects.toThrow(/拒绝删除工作目录/); + if (process.platform !== "win32") { + const subAB = join(ws, "a", "b"); + mkdirSync(subAB, { recursive: true }); + symlinkSync(subAB, join(ws, "link-to-sub"), "dir"); + // Lexically folds to dirname(root)/ws, but OS resolves through ws/a/b/../../../ws === ws. + await expect(local.fs.rm("link-to-sub/../../../ws", { recursive: true, force: false })).rejects.toThrow(/拒绝删除工作目录/); + } + expect(readFileSync(join(wsData, "keep.txt"), "utf8")).toBe("ws-intact"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("[P1] SSH and tmux recursive rm guard ignores inherited CDPATH and protects workspace", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const root = mkdtempSync(join(tmpdir(), "fx-rm-cdpath-")); + const decoyBase = join(root, "decoy-cdpath"); + const decoyTarget = join(decoyBase, "subdir"); + const work = join(root, "work"); + const workSub = join(work, "subdir"); + mkdirSync(decoyTarget, { recursive: true }); + mkdirSync(workSub, { recursive: true }); + writeFileSync(join(work, "keep.txt"), "must-survive"); + const local = new LocalRuntimeDriver({ cwd: work }); + const cdpathExec = (cmd: string) => local.exec(`CDPATH="../decoy-cdpath"; export CDPATH; ${cmd}`); + try { + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = cdpathExec; + await expect(ssh.fs.rm("subdir/../../work", { recursive: true })).rejects.toThrow(); + expect(readFileSync(join(work, "keep.txt"), "utf8")).toBe("must-survive"); + + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = cdpathExec; + await expect(tmux.fs.rm("subdir/../../work", { recursive: true })).rejects.toThrow(); + expect(readFileSync(join(work, "keep.txt"), "utf8")).toBe("must-survive"); + + // Legitimate subdirectory delete operates in cwd, never in CDPATH decoy. + await ssh.fs.rm("subdir", { recursive: true }); + expect(existsSync(workSub)).toBe(false); + expect(existsSync(decoyTarget)).toBe(true); + expect(readFileSync(join(work, "keep.txt"), "utf8")).toBe("must-survive"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, 20_000); + + test("[P1] local rename preserves symlink/../ resolution semantics for source and destination", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const root = mkdtempSync(join(tmpdir(), "fx-local-symlink-mv-")); + const ws = join(root, "ws"); + const outside = join(root, "outside"); + const outsideSub = join(outside, "sub"); + const outsideData = join(outside, "data"); + const wsData = join(ws, "data"); + mkdirSync(wsData, { recursive: true }); + mkdirSync(outsideSub, { recursive: true }); + mkdirSync(outsideData, { recursive: true }); + writeFileSync(join(wsData, "source.txt"), "ws-source"); + writeFileSync(join(outsideData, "source.txt"), "outside-source"); + symlinkSync(outsideSub, join(ws, "link"), process.platform === "win32" ? "junction" : "dir"); + symlinkSync(outsideData, join(ws, "to-outside-data"), process.platform === "win32" ? "junction" : "dir"); + + const local = new LocalRuntimeDriver({ cwd: ws }); + try { + // Symlink without post-symlink ".." behaves uniformly across OSes. + await local.fs.rename!("to-outside-data/source.txt", "to-outside-data/moved.txt"); + expect(readFileSync(join(outsideData, "moved.txt"), "utf8")).toBe("outside-source"); + expect(readFileSync(join(wsData, "source.txt"), "utf8")).toBe("ws-source"); + + // Symlink followed by ".." follows OS filesystem semantics (POSIX dereferences link first; Win32 folds before junction). + await local.fs.rename!("link/../data/moved.txt", "link/../data/moved2.txt").catch(async () => { + await local.fs.rename!("link/../data/source.txt", "link/../data/moved2.txt"); + }); + if (process.platform === "win32") { + expect(readFileSync(join(wsData, "moved2.txt"), "utf8")).toBe("ws-source"); + expect(existsSync(join(wsData, "source.txt"))).toBe(false); + expect(readFileSync(join(outsideData, "moved.txt"), "utf8")).toBe("outside-source"); + } else { + expect(readFileSync(join(outsideData, "moved2.txt"), "utf8")).toBe("outside-source"); + expect(existsSync(join(outsideData, "moved.txt"))).toBe(false); + expect(readFileSync(join(wsData, "source.txt"), "utf8")).toBe("ws-source"); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("[P1] SSH and tmux recursive rm guard rejects parent or cwd names ending with newlines", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const root = mkdtempSync(join(tmpdir(), "fx-rm-newline-")); + try { + if (process.platform !== "win32") { + const parentNl = join(root, "parent\n"); + const work = join(parentNl, "work"); + mkdirSync(join(work, "sub"), { recursive: true }); + writeFileSync(join(work, "keep.txt"), "keep-newline-parent"); + const localWork = new LocalRuntimeDriver({ cwd: work }); + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = (cmd: string) => localWork.exec(cmd); + await expect(ssh.fs.rm("../parent\n", { recursive: true })).rejects.toThrow(); + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = (cmd: string) => localWork.exec(cmd); + await expect(tmux.fs.rm("sub/../../parent\n", { recursive: true })).rejects.toThrow(); + expect(readFileSync(join(work, "keep.txt"), "utf8")).toBe("keep-newline-parent"); + } else { + const { basename } = await import("node:path"); + const work = join(root, "work"); + mkdirSync(work, { recursive: true }); + writeFileSync(join(work, "keep.txt"), "win-intact"); + const localWork = new LocalRuntimeDriver({ cwd: work }); + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = (cmd: string) => localWork.exec(cmd); + await expect(ssh.fs.rm(`../${basename(work)}`, { recursive: true })).rejects.toThrow(/当前工作目录或上级目录/); + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = (cmd: string) => localWork.exec(cmd); + await expect(tmux.fs.rm(`../${basename(work)}`, { recursive: true })).rejects.toThrow(/rm 失败/); + expect(readFileSync(join(work, "keep.txt"), "utf8")).toBe("win-intact"); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, 20_000); + + test("[P2] SSH and tmux directory rename succeeds even if another process immediately recreates source path", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-mv-recreate-src-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + const recreateAfterMv = (cmd: string) => local.exec( + `mv() { ` + + `command mv "$@"; __rc=$?; ` + + `if [ "$__rc" -eq 0 ]; then mkdir -p 'srcDir' && printf 'recreated' > 'srcDir/fresh.txt'; fi; ` + + `return "$__rc"; ` + + `}; ${cmd}`, + ); + try { + mkdirSync(join(dir, "srcDir")); + writeFileSync(join(dir, "srcDir", "orig.txt"), "moved-payload"); + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = recreateAfterMv; + await ssh.fs.rename!("srcDir", "destDir1"); + expect(readFileSync(join(dir, "destDir1", "orig.txt"), "utf8")).toBe("moved-payload"); + expect(readFileSync(join(dir, "srcDir", "fresh.txt"), "utf8")).toBe("recreated"); + + rmSync(join(dir, "srcDir"), { recursive: true, force: true }); + mkdirSync(join(dir, "srcDir")); + writeFileSync(join(dir, "srcDir", "orig.txt"), "tmux-payload"); + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = recreateAfterMv; + await tmux.fs.rename!("srcDir", "destDir2"); + expect(readFileSync(join(dir, "destDir2", "orig.txt"), "utf8")).toBe("tmux-payload"); + expect(readFileSync(join(dir, "srcDir", "fresh.txt"), "utf8")).toBe("recreated"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("[P1] trailing backslash on POSIX is preserved as literal filename char and trailing slash rejects regular files", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-trail-sep-")); + const stack = new RuntimeStack(); + const drv = new LocalRuntimeDriver({ cwd: dir }); + await stack.addLayer("sep", drv); + const tk = createAgentToolkit(stack); + try { + writeFileSync(join(dir, "regular.txt"), "keep-regular"); + await expect(drv.fs.rm("regular.txt/", { recursive: true })).rejects.toThrow(/不是.*目录/); + await expect(drv.fs.rm("regular.txt/", { recursive: true, force: true })).rejects.toThrow(/不是.*目录/); + expect(readFileSync(join(dir, "regular.txt"), "utf8")).toBe("keep-regular"); + + if (process.platform !== "win32") { + mkdirSync(join(dir, "plain"), { recursive: true }); + writeFileSync(join(dir, "plain", "keep.txt"), "keep-plain"); + mkdirSync(join(dir, "plain\\"), { recursive: true }); + writeFileSync(join(dir, "plain\\", "victim.txt"), "backslash-dir"); + await tk.handlers.manage_path({ action: "delete", path: "plain\\", recursive: true }); + expect(existsSync(join(dir, "plain\\"))).toBe(false); + expect(readFileSync(join(dir, "plain", "keep.txt"), "utf8")).toBe("keep-plain"); + + writeFileSync(join(dir, "file\\"), "bs-file"); + await tk.handlers.manage_path({ action: "delete", path: "file\\", recursive: false }); + expect(existsSync(join(dir, "file\\"))).toBe(false); + } + } finally { + await stack.removeLayer("sep", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("[P1][P2] local, SSH, and tmux rename refuse cross-filesystem moves upfront without clobbering external dirs", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, statSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-xdev-mv-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + let mvCalled = 0; + const xdevExec = async (cmd: string) => { + const wrapped = `python3() { return 127; }; stat() { ` + + `case "$*" in ` + + `*"-c %d"*"srcDir"*|*"-c '%d'"*"srcDir"*|*"srcDir"*) ` + + `if [ "$1" = "-c" ] && [ "$2" = "%d" ]; then echo 1001; return 0; fi ;; ` + + `esac; ` + + `if [ "$1" = "-Lc" ] && [ "$2" = "%d" ]; then echo 2002; return 0; fi; ` + + `command stat "$@"; ` + + `}; mv() { echo "MV_SHOULD_NOT_RUN" >&2; return 99; }; ${cmd}`; + const r = await local.exec(wrapped); + if (r.stderr.includes("MV_SHOULD_NOT_RUN")) mvCalled++; + return r; + }; + try { + mkdirSync(join(dir, "srcDir")); + writeFileSync(join(dir, "srcDir", "item.txt"), "stay-intact"); + + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = xdevExec; + await expect(ssh.fs.rename!("srcDir", "destXdev")).rejects.toThrow(/EXDEV/); + + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = xdevExec; + await expect(tmux.fs.rename!("srcDir", "destXdev")).rejects.toThrow(/rename 失败/); + + expect(mvCalled).toBe(0); + expect(existsSync(join(dir, "destXdev"))).toBe(false); + expect(readFileSync(join(dir, "srcDir", "item.txt"), "utf8")).toBe("stay-intact"); + + if (process.platform === "linux" && existsSync("/dev/shm")) { + const tmpDev = statSync(tmpdir()).dev; + const shmDev = statSync("/dev/shm").dev; + if (tmpDev !== shmDev) { + const shmDest = join("/dev/shm", `fx-xdev-${Date.now()}-${Math.random().toString(16).slice(2)}`); + const shmNew = `${shmDest}-new`; + mkdirSync(shmDest); + try { + await expect(local.fs.rename!("srcDir", shmDest)).rejects.toThrow(/EXDEV|现存目录/); + await expect(local.fs.rename!("srcDir", shmNew)).rejects.toThrow(/EXDEV/); + const sshReal = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (sshReal as unknown as { execChannel: (cmd: string) => Promise }).execChannel = (cmd: string) => local.exec(cmd); + await expect(sshReal.fs.rename!("srcDir", shmNew)).rejects.toThrow(/EXDEV/); + const tmuxReal = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmuxReal.exec = (cmd: string) => local.exec(cmd); + await expect(tmuxReal.fs.rename!("srcDir", shmNew)).rejects.toThrow(/rename 失败/); + expect(existsSync(shmDest)).toBe(true); + expect(existsSync(shmNew)).toBe(false); + expect(readFileSync(join(dir, "srcDir", "item.txt"), "utf8")).toBe("stay-intact"); + } finally { + rmSync(shmDest, { recursive: true, force: true }); + rmSync(shmNew, { recursive: true, force: true }); + } + } + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("[P2] default local driver without cwd refuses recursive rm on process.cwd() and its parents via absolute path", async () => { + const { dirname } = await import("node:path"); + const { existsSync } = await import("node:fs"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const defaultLocal = new LocalRuntimeDriver(); + const tk = createAgentToolkit(new RuntimeStack(), { driver: defaultLocal }); + const selfCwd = process.cwd(); + const parentCwd = dirname(selfCwd); + await expect(defaultLocal.fs.rm(selfCwd, { recursive: true })).rejects.toThrow(/拒绝删除工作目录或上级目录/); + await expect(defaultLocal.fs.rm(parentCwd, { recursive: true })).rejects.toThrow(/拒绝删除工作目录或上级目录/); + await expect(tk.handlers.manage_path({ action: "delete", path: selfCwd, recursive: true })).rejects.toThrow(/拒绝删除工作目录或上级目录/); + expect(existsSync(selfCwd)).toBe(true); + }); + + test("[P1] local exec and fs tools operate in the same OS-resolved cwd when configured cwd has symlink/..", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync, rmSync, realpathSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join, sep } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const root = mkdtempSync(join(tmpdir(), "fx-cwd-sym-")); + const ws = join(root, "ws"); + const outside = join(root, "outside"); + const outsideSub = join(outside, "sub"); + const outsideData = join(outside, "data"); + const wsData = join(ws, "data"); + mkdirSync(join(wsData, "target"), { recursive: true }); + mkdirSync(outsideSub, { recursive: true }); + mkdirSync(join(outsideData, "target"), { recursive: true }); + writeFileSync(join(wsData, "marker.txt"), "ws-marker"); + writeFileSync(join(wsData, "target", "f.txt"), "ws-target"); + writeFileSync(join(outsideData, "marker.txt"), "outside-marker"); + writeFileSync(join(outsideData, "target", "f.txt"), "outside-target"); + symlinkSync(outsideSub, join(ws, "link"), process.platform === "win32" ? "junction" : "dir"); + + const configuredCwd = `${ws}${sep}link${sep}..${sep}data`; + const local = new LocalRuntimeDriver({ cwd: configuredCwd }); + try { + const cmdMarker = (await local.exec("cat marker.txt")).stdout.trim(); + const fsMarker = (await local.fs.readFile("marker.txt")).trim(); + // File tool and exec command must observe the exact same marker and target directory. + expect(fsMarker).toBe(cmdMarker); + + await local.fs.rm("target", { recursive: true }); + const expectedRemoved = process.platform === "win32" ? wsData : outsideData; + const expectedPreserved = process.platform === "win32" ? outsideData : wsData; + expect(existsSync(join(expectedRemoved, "target"))).toBe(false); + if (process.platform !== "win32") { + const cmdPwd = realpathSync((await local.exec("pwd -P")).stdout.trim()); + expect(cmdPwd).toBe(realpathSync(expectedRemoved)); + } + expect(readFileSync(join(expectedPreserved, "target", "f.txt"), "utf8")).toBe( + process.platform === "win32" ? "outside-target" : "ws-target", + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("[P2] SSH and tmux rename refuse execution when remote stat cannot verify device IDs", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-mv-nostat-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + let mvRan = 0; + const noStatExec = async (cmd: string) => { + const r = await local.exec(`python3() { return 127; }; stat() { return 127; }; mv() { echo "MV_RAN" >&2; return 99; }; ${cmd}`); + if (r.stderr.includes("MV_RAN")) mvRan++; + return r; + }; + try { + mkdirSync(join(dir, "srcDir")); + writeFileSync(join(dir, "srcDir", "a.txt"), "keep-me"); + + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = noStatExec; + await expect(ssh.fs.rename!("srcDir", "destDir")).rejects.toThrow(/无法核实文件系统设备号|缺少禁止跨设备复制/); + + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = noStatExec; + await expect(tmux.fs.rename!("srcDir", "destDir")).rejects.toThrow(/rename 失败/); + + expect(mvRan).toBe(0); + expect(existsSync(join(dir, "destDir"))).toBe(false); + expect(readFileSync(join(dir, "srcDir", "a.txt"), "utf8")).toBe("keep-me"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("[P2] local directory rename uses native node:fs without requiring mv on PATH", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-mv-nopath-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + const origPath = process.env.PATH; + try { + mkdirSync(join(dir, "srcDir")); + writeFileSync(join(dir, "srcDir", "file.txt"), "native-ok"); + process.env.PATH = ""; + await local.fs.rename!("srcDir", "dstDir"); + expect(existsSync(join(dir, "srcDir"))).toBe(false); + expect(readFileSync(join(dir, "dstDir", "file.txt"), "utf8")).toBe("native-ok"); + } finally { + process.env.PATH = origPath; + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("[P2] recursive rm consistently refuses trailing slash on directory symlinks across local, SSH, and tmux", async () => { + const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, lstatSync, symlinkSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + const dir = mkdtempSync(join(tmpdir(), "fx-rm-symlink-slash-")); + const realDir = join(dir, "realdir"); + const linkPath = join(dir, "link"); + mkdirSync(realDir, { recursive: true }); + writeFileSync(join(realDir, "keep.txt"), "target-intact"); + symlinkSync(realDir, linkPath, process.platform === "win32" ? "junction" : "dir"); + + const local = new LocalRuntimeDriver({ cwd: dir }); + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (cmd: string) => Promise }).execChannel = (cmd: string) => local.exec(cmd); + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = (cmd: string) => local.exec(cmd); + try { + await expect(local.fs.rm("link/", { recursive: true, force: false })).rejects.toThrow(/不是真实目录/); + await expect(local.fs.rm("link/", { recursive: true, force: true })).rejects.toThrow(/不是真实目录/); + if (process.platform !== "win32") { + await expect(ssh.fs.rm("link/", { recursive: true, force: false })).rejects.toThrow(/rm 失败/); + await expect(ssh.fs.rm("link/", { recursive: true, force: true })).rejects.toThrow(/rm 失败/); + await expect(tmux.fs.rm("link/", { recursive: true, force: false })).rejects.toThrow(/rm 失败/); + await expect(tmux.fs.rm("link/", { recursive: true, force: true })).rejects.toThrow(/rm 失败/); + } + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(join(realDir, "keep.txt"), "utf8")).toBe("target-intact"); + + // Without trailing slash, recursive rm removes the symlink entry itself and preserves target contents. + await local.fs.rm("link", { recursive: true, force: false }); + expect(() => lstatSync(linkPath)).toThrow(); + expect(readFileSync(join(realDir, "keep.txt"), "utf8")).toBe("target-intact"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("local, SSH, and tmux rm/rename succeed without Python and surface raw shell errors directly", async () => { + const { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + + const dir = mkdtempSync(join(tmpdir(), "fx-zero-python-")); + const local = new LocalRuntimeDriver({ cwd: dir }); + const origPath = process.env.PATH; + try { + // 1. Local recursive rm and directory rename require zero external binaries (even PATH=""). + mkdirSync(join(dir, "localVictim", "sub"), { recursive: true }); + writeFileSync(join(dir, "localVictim", "sub", "a.txt"), "bye"); + mkdirSync(join(dir, "localSrc")); + writeFileSync(join(dir, "localSrc", "b.txt"), "moved-local"); + process.env.PATH = ""; + try { + await local.fs.rm("localVictim", { recursive: true }); + await local.fs.rename!("localSrc", "localDst"); + } finally { + process.env.PATH = origPath; + } + expect(existsSync(join(dir, "localVictim"))).toBe(false); + expect(readFileSync(join(dir, "localDst", "b.txt"), "utf8")).toBe("moved-local"); + + // 2. SSH and tmux rm/rename succeed cleanly when python3/python/perl are completely absent. + const noPyExec = (cmd: string) => local.exec( + `python3() { return 127; }; python() { return 127; }; perl() { return 127; }; ${cmd}`, + ); + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: (c: string) => Promise }).execChannel = noPyExec; + const tmux = new TmuxSessionDriver({ driver: "tmux", target: "mock" }); + tmux.exec = noPyExec; + + mkdirSync(join(dir, "sshVictim", "nested"), { recursive: true }); + writeFileSync(join(dir, "sshVictim", "nested", "x.txt"), "gone"); + await ssh.fs.rm("sshVictim", { recursive: true }); + expect(existsSync(join(dir, "sshVictim"))).toBe(false); + + mkdirSync(join(dir, "tmuxSrc")); + writeFileSync(join(dir, "tmuxSrc", "y.txt"), "moved-tmux"); + await tmux.fs.rename!("tmuxSrc", "tmuxDst"); + expect(existsSync(join(dir, "tmuxSrc"))).toBe(false); + expect(readFileSync(join(dir, "tmuxDst", "y.txt"), "utf8")).toBe("moved-tmux"); + await tmux.fs.rm("tmuxDst", { recursive: true }); + expect(existsSync(join(dir, "tmuxDst"))).toBe(false); + + // 3. Raw shell errors from rm/mv are surfaced directly; exit >= 129 sets outcome="unknown". + mkdirSync(join(dir, "errDir")); + (ssh as unknown as { execChannel: (c: string) => Promise }).execChannel = (cmd: string) => + local.exec(`rm() { echo "custom-shell-eperm" >&2; return 1; }; ${cmd}`); + await expect(ssh.fs.rm("errDir", { recursive: true })).rejects.toThrow(/custom-shell-eperm/); + + (ssh as unknown as { execChannel: (c: string) => Promise }).execChannel = (cmd: string) => + local.exec(`rm() { return 143; }; ${cmd}`); + await expect(ssh.fs.rm("errDir", { recursive: true })).rejects.toMatchObject({ outcome: "unknown" }); + } finally { + process.env.PATH = origPath; + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("real tmux session executes rm/rename, rejects >15.5KB commands without sealing, and runs large scripts via run_batch(put -> after -> exec)", async () => { + if (process.platform === "win32") return; + const { TmuxInvoker } = await import("../src/terminal/tmux-invoker.js"); + if (!(await TmuxInvoker.isAvailable())) return; + const { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { TerminalManager } = await import("../src/terminal-manager.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + + const dir = mkdtempSync(join(tmpdir(), "fx-real-tmux-slim-")); + const ws = join(dir, "ws"); + const tmDir = join(dir, "tm"); + mkdirSync(join(ws, "victim"), { recursive: true }); + mkdirSync(tmDir, { recursive: true }); + writeFileSync(join(ws, "victim", "a.txt"), "remove-me"); + writeFileSync(join(ws, "keep.txt"), "stay-intact"); + + const tm = new TerminalManager({ terminalDir: tmDir, config: { poll_interval_ms: 80, spawn_poll_ms: 50 } }); + const drv = new TmuxSessionDriver({ driver: "tmux", cwd: ws, config: { launchCmd: "bash" } }, { terminalManager: tm }); + await drv.init(); + const stack = new RuntimeStack(); + await stack.addLayer("tm", drv); + const tk = createAgentToolkit(stack); + try { + // 1. Recursive delete & rename in real tmux + await drv.fs.rm("victim", { recursive: true }); + expect(existsSync(join(ws, "victim"))).toBe(false); + expect(readFileSync(join(ws, "keep.txt"), "utf8")).toBe("stay-intact"); + + // 2. Oversized >15.5KB command throws actionable guidance BEFORE sendKeys and leaves pane unsealed + const hugeCmd = `echo ${"A".repeat(17_000)}`; + let longErr: (Error & { outcome?: string }) | undefined; + try { + await drv.exec(hugeCmd); + } catch (e) { + longErr = e as Error & { outcome?: string }; + } + expect(longErr?.message).toMatch(/run_batch.*put.*after.*exec|transfer_file/); + expect(longErr?.outcome).toBeUndefined(); + + const alive = await drv.exec("echo pane-unsealed"); + expect(alive.exitCode).toBe(0); + expect(alive.stdout.trim()).toBe("pane-unsealed"); + + // 3. run_batch(kind="put" -> after -> kind="exec") uploads and runs a >20KB script cleanly on real tmux + const localScript = join(dir, "big-job.sh"); + const padComment = "# " + "X".repeat(24_000) + "\n"; + writeFileSync(localScript, `#!/bin/sh\n${padComment}printf 'BATCH_SCRIPT_OK\\n'\n`); + const batchRes = await tk.handlers.run_batch({ + layer: "tm", + steps: [ + { id: "upload", kind: "put", local_path: localScript, remote_path: "uploaded-job.sh" }, + { id: "run", kind: "exec", command: "sh ./uploaded-job.sh && rm -f ./uploaded-job.sh", after: ["upload"] }, + ], + }); + expect(batchRes.status).toBe("ok"); + expect(batchRes.steps).toHaveLength(2); + const runStep = batchRes.steps.find((s) => s.id === "run"); + expect(runStep?.stdout).toContain("BATCH_SCRIPT_OK"); + expect(existsSync(join(ws, "uploaded-job.sh"))).toBe(false); + // 4. [P2] 128 KiB binary upload + download roundtrip on real tmux without scrollback truncation + const localBinSrc = join(dir, "src-128k.bin"); + const localBinDst = join(dir, "dst-128k.bin"); + const binPayload = Buffer.alloc(128 * 1024); + for (let i = 0; i < binPayload.length; i++) binPayload[i] = (i * 73 + 19) & 0xff; + writeFileSync(localBinSrc, binPayload); + + const putRes = await tk.handlers.transfer_file({ + direction: "put", layer: "tm", local_path: localBinSrc, remote_path: "remote-128k.bin", + }); + expect(putRes.verified).toBe(true); + expect(putRes.bytes).toBe(128 * 1024); + + const getRes = await tk.handlers.transfer_file({ + direction: "get", layer: "tm", remote_path: "remote-128k.bin", local_path: localBinDst, + }); + expect(getRes.verified).toBe(true); + expect(getRes.bytes).toBe(128 * 1024); + expect(Buffer.compare(readFileSync(localBinDst), binPayload)).toBe(0); + + // 5. [P1] read_path on a non-existent path reports not-found without exiting the persistent tmux shell + await expect(tk.handlers.read_path({ layer: "tm", path: "definitely-missing-path" })).rejects.toThrow(/路径不存在/); + const afterMissing = await tk.handlers.run_command({ layer: "tm", command: "printf 'STILL_ALIVE_OK\\n'" }); + expect(afterMissing.exit_code).toBe(0); + expect(afterMissing.stdout).toContain("STILL_ALIVE_OK"); + } finally { + await stack.removeLayer("tm", { destroy: true }); + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); + + test("[P2] read_path preserves EACCES/permission-denied errors instead of reporting path not found", async () => { + const fsPromises = await import("node:fs/promises"); + const { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const { SshPtyDriver } = await import("../src/ssh-pty-driver.js"); + const { TmuxSessionDriver } = await import("../src/tmux-driver.js"); + + const dir = mkdtempSync(join(tmpdir(), "fx-perm-read-")); + try { + // 1. Cross-platform: LocalRuntimeDriver.fs.stat rethrows EACCES/EPERM (only ENOENT/ENOTDIR -> null) + const local = new LocalRuntimeDriver({ cwd: dir }); + const origStat = fsPromises.default.stat; + const secretDir = join(dir, "secret-dir"); + mkdirSync(secretDir); + fsPromises.default.stat = (async (p: Parameters[0], opts?: Parameters[1]) => { + if (String(p).includes("secret-dir")) { + throw Object.assign(new Error(`EACCES: permission denied, stat '${String(p)}'`), { code: "EACCES" }); + } + return origStat(p, opts); + }) as typeof origStat; + try { + const tkLocal = createAgentToolkit(new RuntimeStack(), { driver: local }); + await expect(tkLocal.handlers.read_path({ path: "secret-dir" })).rejects.toThrow(/EACCES|permission denied/i); + await expect(tkLocal.handlers.read_path({ path: "truly-missing" })).rejects.toThrow(/路径不存在/); + } finally { + fsPromises.default.stat = origStat; + } + + // 2. Cross-platform: when stat returns null (e.g. missing remote stat), readdir EACCES is preserved + const nullStatPermDrv = { + descriptor: { driver: "custom-perm" }, + fs: { + stat: async () => null, + readdir: async (p: string) => { + if (p === "denied") { + throw Object.assign(new Error("EACCES: permission denied, scandir 'denied'"), { code: "EACCES" }); + } + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }); + }, + readFile: async () => "", + writeFile: async () => {}, + exists: async () => false, + rm: async () => {}, + mkdir: async () => {}, + }, + } as unknown as RuntimeDriver; + const tkNullStat = createAgentToolkit(new RuntimeStack(), { driver: nullStatPermDrv }); + await expect(tkNullStat.handlers.read_path({ path: "denied" })).rejects.toThrow(/EACCES|permission denied/i); + await expect(tkNullStat.handlers.read_path({ path: "missing" })).rejects.toThrow(/路径不存在/); + + // 3. POSIX real filesystem permission checks across local, SSH, and tmux + if (process.platform !== "win32") { + const isRoot = typeof process.geteuid === "function" && process.geteuid() === 0; + const setpriv = isRoot ? Bun.which("setpriv") : null; + if (!isRoot || setpriv) { + const pDir = join(dir, "posix-perm"); + mkdirSync(join(pDir, "d000"), { recursive: true }); + mkdirSync(join(pDir, "d111"), { recursive: true }); + mkdirSync(join(pDir, "p000", "sub"), { recursive: true }); + writeFileSync(join(pDir, "d111", "inside.txt"), "hidden"); + chmodSync(dir, 0o755); + chmodSync(pDir, 0o755); + chmodSync(join(pDir, "d000"), 0o000); + chmodSync(join(pDir, "d111"), 0o111); + chmodSync(join(pDir, "p000"), 0o000); + try { + if (!isRoot) { + const tkRealLocal = createAgentToolkit(new RuntimeStack(), { driver: new LocalRuntimeDriver({ cwd: pDir }) }); + await expect(tkRealLocal.handlers.read_path({ path: "d000" })).rejects.toThrow(/EACCES|permission denied/i); + await expect(tkRealLocal.handlers.read_path({ path: "d111" })).rejects.toThrow(/EACCES|permission denied/i); + await expect(tkRealLocal.handlers.read_path({ path: "p000/sub" })).rejects.toThrow(/EACCES|permission denied/i); + } + const runAsUnpriv = async (cmd: string) => { + const argv = isRoot + ? [setpriv!, "--reuid=65534", "--regid=65534", "--clear-groups", "sh", "-c", `cd ${JSON.stringify(pDir)} && eval "$1"`, "_", cmd] + : ["sh", "-c", `cd ${JSON.stringify(pDir)} && eval "$1"`, "_", cmd]; + const proc = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { stdout, stderr, exitCode }; + }; + const ssh = new SshPtyDriver({ driver: "ssh", target: "mock" }); + (ssh as unknown as { execChannel: typeof runAsUnpriv }).execChannel = runAsUnpriv; + const tmux = new TmuxSessionDriver({ driver: "tmux" }); + tmux.exec = async (cmd) => { + const r = await runAsUnpriv(cmd); + return { stdout: r.stdout + r.stderr, stderr: "", exitCode: r.exitCode }; + }; + for (const drv of [ssh, tmux]) { + const tkRemote = createAgentToolkit(new RuntimeStack(), { driver: drv }); + await expect(tkRemote.handlers.read_path({ path: "d000" })).rejects.toThrow(/permission denied|权限不足/i); + await expect(tkRemote.handlers.read_path({ path: "d111" })).rejects.toThrow(/permission denied|权限不足/i); + await expect(tkRemote.handlers.read_path({ path: "p000/sub" })).rejects.toThrow(/permission denied|权限不足/i); + await expect(tkRemote.handlers.read_path({ path: "missing-sub" })).rejects.toThrow(/路径不存在/); + } + } finally { + chmodSync(join(pDir, "d000"), 0o700); + chmodSync(join(pDir, "d111"), 0o700); + chmodSync(join(pDir, "p000"), 0o700); + } + } + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 30_000); +}); diff --git a/tests/file-edit.test.ts b/tests/file-edit.test.ts index c0d5b24..1c1a88b 100644 --- a/tests/file-edit.test.ts +++ b/tests/file-edit.test.ts @@ -312,44 +312,62 @@ describe("editFile(TOCTOU+精确替换)", () => { }, 30_000); }); -describe("toolkit 新工具(read_file/edit_file/observe_stream)", () => { - test("read_file + edit_file 真跑", async () => { +describe("toolkit 新工具(read_path/edit_file/observe_stream)", () => { + test("read_path + edit_file(CAS + 直接写入)真跑", async () => { const d2 = mkdtempSync(join(tmpdir(), "fx-tk-")); const p = join(d2, "conf.env"); writeFileSync(p, "TOKEN=FX_8829\n"); const tk = createAgentToolkit(new RuntimeStack(), {}); - const rf = await tk.handlers.read_file({ path: p }); + const rf = await tk.handlers.read_path({ path: p }); + expect(rf.type).toBe("file"); + if (rf.type !== "file") throw new Error("expected file"); expect(rf.content).toContain("FX_8829"); expect(rf.size).toBeGreaterThan(0); + const dirRead = await tk.handlers.read_path({ path: d2 }); + expect(dirRead.type).toBe("directory"); + if (dirRead.type !== "directory") throw new Error("expected directory"); + expect(dirRead.entries.some((e) => e.name === "conf.env" && !e.isDirectory)).toBe(true); const ef = await tk.handlers.edit_file({ path: p, old: "FX_8829", new: "FX_9999" }); + expect(ef.mode).toBe("edit"); expect(ef.occurrences).toBe(1); expect(ef.mutex === "flock" || ef.mutex === "degraded").toBe(true); // 保护等级透传到 Agent 工具面(Astra 五轮 P2) - expect((await tk.handlers.read_file({ path: p })).content).toContain("FX_9999"); + const rfAfter = await tk.handlers.read_path({ path: p }); + expect(rfAfter.type === "file" && rfAfter.content).toContain("FX_9999"); + + // 直接创建/写入文本(默认拒绝覆写,overwrite=true 才覆写,create_dirs=true 自动建父目录) + const createdPath = join(d2, "nested", "new.txt"); + const wf = await tk.handlers.edit_file({ path: createdPath, content: "HELLO_NEW\n", create_dirs: true }); + expect(wf).toEqual({ mode: "write", path: createdPath, created: true, bytes_after: 10 }); + await expect(tk.handlers.edit_file({ path: createdPath, content: "OVERWRITE" })).rejects.toThrow(/拒绝覆盖/); + const ow = await tk.handlers.edit_file({ path: createdPath, content: "OVERWRITTEN", overwrite: true }); + expect(ow).toEqual({ mode: "write", path: createdPath, created: false, bytes_after: 11 }); rmSync(d2, { recursive: true, force: true }); }, 20_000); - test("observe_stream 持续接收,按流过滤、回看和游标续读", async () => { + test("observe_stream 开窗首读、按流过滤、回看和游标续读", async () => { const tk = createAgentToolkit(new RuntimeStack(), {}); const dir = mkdtempSync(join(tmpdir(), "fx-window-test-")); const gate = join(dir, "gate"); const path = (await import("../src/ssh-helpers.js")).shellQuote(gate.replace(/\\/g, "/")); try { - const { window_id } = await tk.handlers.observe_stream({ + const first = await tk.handlers.observe_stream({ command: `echo IGNORE; printf 'E1\\nE2\\nE3\\n' >&2; while [ ! -f ${path} ]; do sleep 0.1; done; echo E4 >&2`, stream: "stderr", + limit: 1, + wait_ms: 8000, }); - const first = await tk.handlers.read_stream({ window_id, since_seq: 0, wait_ms: 8000, limit: 1 }); + const window_id = first.window_id; expect(first.frames.map(({ text, stream }) => [text, stream])).toEqual([["E1", "stderr"]]); - const rest = await tk.handlers.read_stream({ window_id, since_seq: first.last_delivered_seq, wait_ms: 8000 }); + const rest = await tk.handlers.observe_stream({ window_id, since_seq: first.last_delivered_seq, wait_ms: 8000 }); expect(rest.frames.map((frame) => frame.text)).toEqual(["E2", "E3"]); - const backward = await tk.handlers.read_stream({ window_id, before_seq: rest.newest_seq, limit: 2 }); + const backward = await tk.handlers.observe_stream({ window_id, before_seq: rest.newest_seq, limit: 2 }); expect(backward.frames.map((frame) => frame.text)).toEqual(["E1", "E2"]); - const timeout = await tk.handlers.read_stream({ window_id, since_seq: rest.newest_seq, wait_ms: 20 }); + const timeout = await tk.handlers.observe_stream({ window_id, since_seq: rest.newest_seq, wait_ms: 20 }); expect(timeout.timed_out).toBe(true); writeFileSync(gate, ""); - const late = await tk.handlers.read_stream({ window_id, since_seq: rest.newest_seq, wait_ms: 8000 }); + const late = await tk.handlers.observe_stream({ window_id, since_seq: rest.newest_seq, wait_ms: 8000 }); expect(late.frames.map((frame) => frame.text)).toEqual(["E4"]); - const history = await tk.handlers.read_stream({ window_id, window_ms: 30000 }); + const history = await tk.handlers.observe_stream({ window_id, window_ms: 30000 }); expect(history.frames.map((frame) => frame.text)).toEqual(["E1", "E2", "E3", "E4"]); expect(await tk.handlers.close_stream({ window_id })).toEqual({ window_id, closed: true }); } finally { diff --git a/tests/file-transfer.test.ts b/tests/file-transfer.test.ts index a64c5de..6d96c05 100644 --- a/tests/file-transfer.test.ts +++ b/tests/file-transfer.test.ts @@ -856,3 +856,89 @@ describe("Sol 73:长名漏网入口", () => { return { files, exec }; } }); + +describe("[P2] tmux 大文件分块下载(避开输出滚动窗口截断)", () => { + const hasSh = Boolean(Bun.which("sh")); + test.skipIf(!hasSh)("128 KiB 二进制文件经受限输出窗口的 tmux 层下载完整通过", async () => { + const shPath = Bun.which("sh")!; + const dir = mkdtempSync(join(tmpdir(), "fx-tmux-get128k-")); + const fwd = (p: string) => p.replace(/\\/g, "/"); + try { + const payload = Buffer.alloc(128 * 1024); + for (let i = 0; i < payload.length; i++) payload[i] = (i * 37 + 13) & 0xff; + const remoteFile = join(dir, "remote-128k.bin"); + const localOut = join(dir, "local-128k.bin"); + writeFileSync(remoteFile, payload); + + let maxStdoutSeen = 0; + const cappedTmuxDriver = { + descriptor: { driver: "tmux" as const }, + async exec(cmd: string) { + const p = Bun.spawn([shPath, "-c", cmd], { stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(p.stdout).text(), + new Response(p.stderr).text(), + p.exited, + ]); + maxStdoutSeen = Math.max(maxStdoutSeen, stdout.length); + // 模拟 tmux 滚动缓冲上限(超过 32KB 的单次输出头部被截掉) + const bounded = stdout.length > 32_000 ? stdout.slice(-32_000) : stdout; + return { stdout: bounded, stderr, exitCode }; + }, + } as never; + + const res = await transferLayerFile(cappedTmuxDriver, "get", { + remotePath: fwd(remoteFile), + localPath: localOut, + }); + expect(res.verified).toBe(true); + expect(res.bytes).toBe(128 * 1024); + expect(maxStdoutSeen).toBeLessThanOrEqual(9_000); + expect(Buffer.compare(readFileSync(localOut), payload)).toBe(0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 25_000); + + test("[P2] 下载暂存编码命令抛错时仍进入 finally 清理远端临时文件", async () => { + const dir = mkdtempSync(join(tmpdir(), "fx-tmux-get-clean-")); + try { + const localOut = join(dir, "local-never-written.bin"); + let stagedTmp = ""; + let cleanedTmp = ""; + const exec: TransferExec = async (cmd) => { + if (cmd.startsWith("wc -c < ")) return { stdout: "131072\n", exitCode: 0 }; + const mStage = cmd.match(/> '(\/tmp\/filaxis-read-[0-9a-f]+\.b64)'/); + if (mStage) { + stagedTmp = mStage[1]!; + throw Object.assign(new Error("模拟编码完成后通道中断"), { outcome: "unknown" as const }); + } + const mClean = cmd.match(/^rm -f '(\/tmp\/filaxis-read-[0-9a-f]+\.b64)'$/); + if (mClean) { + cleanedTmp = mClean[1]!; + return { stdout: "", exitCode: 0 }; + } + return { stdout: "", exitCode: 0 }; + }; + const dialect = { + family: "gnu", + base64Encode: ["base64", "-w", "0"], + base64Decode: ["base64", "-d"], + sha256: ["sha256sum"], + } as never; + let caught: (Error & { outcome?: string }) | undefined; + try { + await getFile(exec, dialect, "/remote/big.bin", localOut, { chunkB64: 12_000 }); + } catch (err) { + caught = err as Error & { outcome?: string }; + } + expect(caught?.message).toContain("模拟编码完成后通道中断"); + expect(caught?.outcome).toBe("unknown"); + expect(stagedTmp).toMatch(/^\/tmp\/filaxis-read-[0-9a-f]+\.b64$/); + expect(cleanedTmp).toBe(stagedTmp); + expect(() => readFileSync(localOut)).toThrow(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/integration-ssh.test.ts b/tests/integration-ssh.test.ts index 09cfe81..36ac27e 100644 --- a/tests/integration-ssh.test.ts +++ b/tests/integration-ssh.test.ts @@ -328,7 +328,7 @@ describe("SSH 真机集成(AC-02/04/15 远端面)", () => { let cursor = 0; const frames: Array<{ text: string; stream?: string }> = []; while (frames.length < 3) { - const page = await toolkit.handlers.read_stream({ window_id, since_seq: cursor, wait_ms: 5000 }); + const page = await toolkit.handlers.observe_stream({ window_id, since_seq: cursor, wait_ms: 5000 }); if (!page.frames.length) break; frames.push(...page.frames); cursor = page.last_delivered_seq!; @@ -337,14 +337,14 @@ describe("SSH 真机集成(AC-02/04/15 远端面)", () => { expect(frames).toContainEqual(expect.objectContaining({ text: "/tmp", stream: "stdout" })); expect(frames).toContainEqual(expect.objectContaining({ text: "REMOTE_ERR", stream: "stderr" })); expect(frames.at(-1)?.text).toBe("REMOTE_LATE"); - const history = await toolkit.handlers.read_stream({ window_id, before_seq: cursor }); + const history = await toolkit.handlers.observe_stream({ window_id, before_seq: cursor }); expect(history.frames.map(({ text }) => text).sort()).toEqual(["/tmp", "REMOTE_ERR"]); - const done = await toolkit.handlers.read_stream({ window_id, since_seq: cursor, wait_ms: 5000 }); + const done = await toolkit.handlers.observe_stream({ window_id, since_seq: cursor, wait_ms: 5000 }); expect(done).toMatchObject({ stale: true, exit_code: 0 }); await toolkit.handlers.close_stream({ window_id }); const failed = await toolkit.handlers.observe_stream({ command: "printf '\\342\\202'; exit 37", layer: "remote-window" }); - const terminal = await toolkit.handlers.read_stream({ window_id: failed.window_id, since_seq: 0, wait_ms: 5000 }); + const terminal = await toolkit.handlers.observe_stream({ window_id: failed.window_id, since_seq: 0, wait_ms: 5000 }); expect(terminal).toMatchObject({ stale: true, exit_code: 37, frames: [{ text: "�", stream: "stdout" }] }); await toolkit.handlers.close_stream({ window_id: failed.window_id }); } finally { @@ -699,7 +699,7 @@ describe("第十一季:批量组合(CI 真机)", () => { const toolkit = createAgentToolkit(stack); try { await stack.addLayer("controller", { driver: "local" }); - const connections = await toolkit.handlers.push_ssh({ targets: [ + const connections = await toolkit.handlers.connect_layer({ targets: [ { host: TARGET, name: "remote" }, { host: TARGET, name: "duplicate-landing" }, ] }); expect(connections).toMatchObject({ diff --git a/tests/mcp-server.test.ts b/tests/mcp-server.test.ts index 392b94b..065b3bd 100644 --- a/tests/mcp-server.test.ts +++ b/tests/mcp-server.test.ts @@ -47,7 +47,7 @@ async function waitId(f: { collect: () => Array> }, id: } describe("MCP Server(REQ-0003)", () => { - test("directory listing, default-layer switching, and non-recursive deletion", async () => { + test("path reading, default-layer switching, and path management (mkdir/move/delete)", async () => { const dir = mkdtempSync(join(tmpdir(), "fx-mcp-directory-")); const stack = new RuntimeStack(); const fixture = mcpFixture(stack); @@ -69,54 +69,79 @@ describe("MCP Server(REQ-0003)", () => { 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(await call(1, "manage_layers", { action: "activate", 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(2, "manage_layers", { action: "activate", name: "previous" })).toMatchObject({ + structuredContent: { action: "activate", active_layer: "previous" }, content: [{ text: "active_layer=previous" }], }); - expect(await call(3, "list_directory", { path: "." })).toMatchObject({ + expect(await call(3, "read_path", { path: "." })).toMatchObject({ content: [{ text: expect.stringContaining("file .hidden") }], - structuredContent: { entries: expect.arrayContaining([ - expect.objectContaining({ name: "nested", isDirectory: true }), - expect.objectContaining({ name: "-literal", isDirectory: false }), - ]) }, + structuredContent: { + type: "directory", + 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(4, "read_path", { path: "missing" })).toMatchObject({ isError: true }); + expect(await call(5, "manage_path", { action: "delete", path: "nested" })).toMatchObject({ isError: true }); + expect(await call(6, "manage_path", { action: "delete", path: "/", recursive: true })).toMatchObject({ isError: true }); + expect(await call(7, "manage_path", { action: "delete", path: "-literal" })).toMatchObject({ + structuredContent: { action: "delete", deleted: true, path: "-literal", recursive: false }, }); - expect(await call(8, "delete_file", { path: "-literal" })).toMatchObject({ isError: true }); + expect(await call(8, "manage_path", { action: "delete", 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(9, "manage_path", { action: "delete", path: "link/." })).toMatchObject({ isError: true }); + expect(await call(10, "manage_path", { action: "delete", path: "link" })).toMatchObject({ + structuredContent: { action: "delete", deleted: true, path: "link", recursive: false }, }); - expect(await call(12, "delete_file", { path: "alias/../target" })).toMatchObject({ isError: false }); + expect(await call(12, "manage_path", { action: "delete", 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"); + + // mkdir + edit_file(write) + move + recursive delete + expect(await call(14, "manage_path", { action: "mkdir", path: "created/sub" })).toMatchObject({ + isError: false, content: [{ text: "created=true | path=created/sub" }], + structuredContent: { action: "mkdir", path: "created/sub", created: true }, + }); + expect(await call(15, "edit_file", { path: "created/sub/note.txt", content: "hello" })).toMatchObject({ + isError: false, content: [{ text: "created=true | bytes=5 | path=created/sub/note.txt" }], + structuredContent: { mode: "write", path: "created/sub/note.txt", created: true, bytes_after: 5 }, + }); + expect(await call(16, "manage_path", { action: "move", path: "created/sub/note.txt", destination: "created/moved.txt" })).toMatchObject({ + isError: false, content: [{ text: "moved=true | path=created/sub/note.txt -> created/moved.txt" }], + structuredContent: { action: "move", path: "created/sub/note.txt", destination: "created/moved.txt", moved: true }, + }); + expect(readFileSync(join(previous, "created", "moved.txt"), "utf8")).toBe("hello"); + expect(await call(17, "manage_path", { action: "delete", path: "created", recursive: true })).toMatchObject({ + isError: false, content: [{ text: "deleted=true | path=created | recursive=true" }], + structuredContent: { action: "delete", path: "created", deleted: true, recursive: true }, + }); + expect(existsSync(join(previous, "created"))).toBe(false); + previousDriver.fs.rm = async () => { throw Object.assign(new Error("connection lost"), { outcome: "unknown" }); }; - expect(await call(11, "delete_file", { path: ".hidden" })).toMatchObject({ + expect(await call(11, "manage_path", { action: "delete", 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 listed = await call(13, "read_path", { path: "." }) as { + content: Array<{ text: string }>; structuredContent: { type: "directory"; entries: typeof entries }; }; const listingText = listed.content[0]!.text; + expect(listed.structuredContent.type).toBe("directory"); expect(listed.structuredContent.entries).toEqual(entries); expect(Buffer.byteLength(JSON.stringify(listingText))).toBeLessThanOrEqual(8192); expect(listingText).toContain("完整结果见 structuredContent"); @@ -130,7 +155,7 @@ describe("MCP Server(REQ-0003)", () => { } }); - test("put_file and get_file transfer bytes on the selected layer and report verification", async () => { + test("transfer_file puts and gets bytes on the selected layer and report verification", async () => { const dir = mkdtempSync(join(tmpdir(), "fx-mcp-transfer-")); const stack = new RuntimeStack(); const f = mcpFixture(stack); @@ -146,13 +171,13 @@ describe("MCP Server(REQ-0003)", () => { return (await waitId(f, id, 20_000)).result; }; const paths = { layer: "fixture", remote_path: "layer file.bin" }; - expect(await call(1, "put_file", { ...paths, path: input })).toMatchObject({ isError: true }); + expect(await call(1, "transfer_file", { direction: "put", ...paths, path: input })).toMatchObject({ isError: true }); expect(existsSync(join(dir, paths.remote_path))).toBe(false); - for (const [id, name, local_path] of [[2, "put_file", input], [3, "get_file", output]] as const) { - expect(await call(id, name, { ...paths, local_path })).toMatchObject({ + for (const [id, direction, local_path] of [[2, "put", input], [3, "get", output]] as const) { + expect(await call(id, "transfer_file", { direction, ...paths, local_path })).toMatchObject({ isError: false, content: [{ text: expect.stringContaining("verification=sha256") }], - structuredContent: { bytes: payload.length, transport: "exec", verification: "sha256", write_mode: "atomic-replace" }, + structuredContent: { direction, bytes: payload.length, transport: "exec", verification: "sha256", write_mode: "atomic-replace" }, }); } expect(readFileSync(output)).toEqual(payload); @@ -167,9 +192,11 @@ describe("MCP Server(REQ-0003)", () => { const f = mcpFixture(); try { f.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "run_batch", arguments: { commands: [] } } }); - f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "read_stream", arguments: { session: "demo" } } }); + f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "observe_stream", arguments: { window_id: "" } } }); + f.write({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "observe_stream", arguments: { session: "demo" } } }); expect((await waitId(f, 1)).result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("steps 需为非空数组") }] }); expect((await waitId(f, 2)).result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("window_id 需为非空字符串") }] }); + expect((await waitId(f, 3)).result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("observe_stream 需传 command") }] }); } finally { f.close(); } }); @@ -246,13 +273,13 @@ describe("MCP Server(REQ-0003)", () => { expect(calls).toHaveLength(2); } finally { f.close(); } }); - test("list_layers exposes the empty and populated layer lists in MCP text", async () => { + test("manage_layers(list) exposes the empty and populated layer lists in MCP text", async () => { const stack = new RuntimeStack(); const f = mcpFixture(stack); async function listLayers(id: number) { - f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "list_layers" } }); + f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "manage_layers", arguments: { action: "list" } } }); const response = await waitId(f, id); - return response.result as { content: Array<{ type: string; text: string }>; structuredContent: { layers: Array<{ name: string }> } }; + return response.result as { content: Array<{ type: string; text: string }>; structuredContent: { action: string; layers: Array<{ name: string }> } }; } try { const empty = await listLayers(1); @@ -340,7 +367,7 @@ describe("MCP Server(REQ-0003)", () => { } finally { fixture.close(); } }); - test("read_file displays exact text and marks an oversized preview without changing the structured body", async () => { + test("read_path displays exact text and marks an oversized preview without changing the structured body", async () => { const dir = mkdtempSync(join(tmpdir(), "fx-mcp-read-body-")); const stack = new RuntimeStack(); const fixture = mcpFixture(stack); @@ -348,11 +375,11 @@ describe("MCP Server(REQ-0003)", () => { const boundary = "x".repeat(8190); const large = 'File start\n' + '雪🧵\n"\\'.repeat(1200) + '\nFile end'; const read = async (id: number, args: Record) => { - fixture.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "read_file", arguments: args } }); + fixture.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "read_path", arguments: args } }); return (await waitId(fixture, id)).result as { isError: boolean; content: Array<{ text: string }>; - structuredContent?: { path: string; content: string; size: number; mtime_ms: number }; + structuredContent?: { path: string; type: string; content: string; size: number; mtime_ms: number }; }; }; try { @@ -364,7 +391,7 @@ describe("MCP Server(REQ-0003)", () => { expect(exact.isError).toBe(false); expect(exact.content[0]?.text).toBe(small); expect(exact.structuredContent).toMatchObject({ - path: "small.sources", content: small, size: Buffer.byteLength(small), + path: "small.sources", type: "file", content: small, size: Buffer.byteLength(small), }); expect((await read(2, { path: "boundary" })).content[0]?.text).toBe(boundary); const clipped = await read(3, { path: "large" }); @@ -433,7 +460,7 @@ describe("MCP Server(REQ-0003)", () => { } finally { f.close(); } }, 15_000); - test.skipIf(process.platform !== "win32")("push_ssh reaches the jump port through native Windows OpenSSH", async () => { + test.skipIf(process.platform !== "win32")("connect_layer reaches the jump port through native Windows OpenSSH", async () => { let connections = 0; const proxy = createServer((socket) => { connections++; socket.destroy(); }); await new Promise((resolve, reject) => { @@ -447,7 +474,7 @@ describe("MCP Server(REQ-0003)", () => { const jumps = [`localhost:${address.port}`, `probe@127.0.0.1:${address.port}`]; for (const [index, jump] of jumps.entries()) { const id = index + 1; - f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "push_ssh", arguments: { host: "127.0.0.1", jump } } }); + f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "connect_layer", arguments: { host: "127.0.0.1", jump } } }); const response = await waitId(f, id); // Reaching the listener proves the native client parsed the jump address. expect(response.result).toMatchObject({ isError: true }); @@ -479,14 +506,20 @@ describe("MCP Server(REQ-0003)", () => { f.write({ jsonrpc: "2.0", id: 1, method: "tools/list" }); const r = await waitId(f, 1); const tools = (r as { result: { tools: Array<{ name: string; description: string; inputSchema: unknown }> } }).result.tools; + expect(tools.length).toBe(12); expect(tools.length).toBe(TOOL_DEFS.length); expect(tools.map((t) => t.name)).toEqual(TOOL_DEFS.map((d) => d.function.name)); // 同序同名 + expect(tools.every((t) => /^[a-z]+_[a-z]+$/.test(t.name))).toBe(true); // schema 同源断言:inputSchema 即 function.parameters(漂移即红) for (let i = 0; i < tools.length; i++) { expect(tools[i]!.inputSchema).toEqual(TOOL_DEFS[i]!.function.parameters); } - // 核心六工具在场 - for (const n of ["run_command", "read_file", "edit_file", "put_file", "get_file", "observe_stream", "spawn_and_observe", "stop_and_verify"]) { + // 全量 12 工具在场 + for (const n of [ + "run_batch", "run_command", "start_session", "stop_session", + "observe_stream", "close_stream", "read_path", "edit_file", + "manage_path", "transfer_file", "connect_layer", "manage_layers", + ]) { expect(tools.map((t) => t.name)).toContain(n); } f.close(); @@ -561,15 +594,15 @@ describe("MCP Server(REQ-0003)", () => { f.close(); }); - test("AC-04 会话链跨调用:spawn→stop 按返回 session_id 串起", async () => { + test("AC-04 会话链跨调用:start_session→stop_session 按返回 session_id 串起", async () => { const f = mcpFixture(); - f.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "spawn_and_observe", arguments: { command: "echo READY; sleep 10", ready_marker: "READY", ready_timeout_ms: 6000 } } }); + f.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "start_session", arguments: { command: "echo READY; sleep 10", ready_marker: "READY", ready_timeout_ms: 6000 } } }); const spawnR = await waitId(f, 1, 20_000); const spawnRes = spawnR as { result: { structuredContent: { session_id: string; note?: string } } }; const sid = spawnRes.result.structuredContent.session_id; expect(sid).toBeTruthy(); expect(spawnRes.result.structuredContent.note).toBe("ready"); - f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "stop_and_verify", arguments: { session_id: sid } } }); + f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "stop_session", arguments: { session_id: sid } } }); const stopR = await waitId(f, 2, 20_000); const stopRes = stopR as { result: { structuredContent: { status: string } } }; expect(["stopped", "exited", "unknown"]).toContain(stopRes.result.structuredContent.status); // 三态可辨 @@ -588,7 +621,7 @@ describe("MCP Server(REQ-0003)", () => { }; }; try { - const launched = await call(1, "spawn_and_observe", { + const launched = await call(1, "start_session", { command: "echo READY; sleep 1; exit 7", ready_marker: "READY", name: "long-session-name", }); expect(launched.isError).toBe(false); @@ -604,9 +637,9 @@ describe("MCP Server(REQ-0003)", () => { terminal = await driver.verifySession(sessionId); } expect(terminal).toEqual({ status: "exited", exitCode: 7 }); - const shortened = await call(2, "stop_and_verify", { session_id: sessionId.slice(0, 24) }); + const shortened = await call(2, "stop_session", { session_id: sessionId.slice(0, 24) }); expect(shortened.content[0]!.text).toContain("status=unknown\nnote=会话归属未知或已过期"); - const result = await call(3, "stop_and_verify", { session_id: sessionId }); + const result = await call(3, "stop_session", { session_id: sessionId }); expect(result.structuredContent).toEqual({ status: "exited", exit_code: 7 }); expect(result.content[0]!.text).toBe("status=exited\nexit_code=7"); } finally { @@ -628,7 +661,7 @@ describe("MCP Server(REQ-0003)", () => { const fixture = mcpFixture(stack, createAgentToolkit(stack, { driver, readyTimeoutMs: 5 })); try { fixture.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { - name: "spawn_and_observe", arguments: { command: "fixture", ready_marker: "READY" }, + name: "start_session", arguments: { command: "fixture", ready_marker: "READY" }, } }); const { result } = await waitId(fixture, 1) as { result: { isError: boolean; content: Array<{ text: string }>; structuredContent: Record; @@ -640,7 +673,7 @@ describe("MCP Server(REQ-0003)", () => { }); }); -test("remove_layer returns all unresolved session handles via MCP", async () => { +test("manage_layers(remove) returns all unresolved session handles via MCP", async () => { const stack = new RuntimeStack(); const sessions = [{ sessionId: "fixture", logBase: "/tmp/fixture" }]; const driver = { @@ -652,16 +685,119 @@ test("remove_layer returns all unresolved session handles via MCP", async () => const fixture = mcpFixture(stack); try { fixture.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { - name: "remove_layer", arguments: { name: "owned", destroy: true }, + name: "manage_layers", arguments: { action: "remove", name: "owned", destroy: true }, } }); expect(await waitId(fixture, 1)).toMatchObject({ - result: { isError: true, structuredContent: { outcome: "unknown", sessions } }, + result: { + isError: true, + content: [{ text: "outcome=unknown\nsessions=fixture (/tmp/fixture)\ncleanup unknown" }], + structuredContent: { outcome: "unknown", sessions }, + }, }); } finally { fixture.close(); } }); +test("MCP error text surfaces outcome=unknown and state handles for run_command, transfer_file, edit_file, and manage_layers", async () => { + const dir = mkdtempSync(join(tmpdir(), "fx-mcp-unknown-text-")); + const stack = new RuntimeStack(); + const localSrc = join(dir, "upload.bin"); + const localDst = join(dir, "download.bin"); + writeFileSync(localSrc, "payload-data"); + + const drv = { + descriptor: { driver: "ssh", target: "mock-host" }, + async exec(cmd: string) { + if (cmd === "printf filaxis | base64 -w 0") return { stdout: "ZmlsYXhpcw==\n", stderr: "", exitCode: 0 }; + if (cmd === "printf ZmlsYXhpcw== | base64 -d") return { stdout: "filaxis", stderr: "", exitCode: 0 }; + if (cmd === "printf filaxis | sha256sum") return { stdout: `${"0".repeat(64)} -\n`, stderr: "", exitCode: 0 }; + if (cmd.startsWith("test -d ")) return { stdout: "", stderr: "", exitCode: 1 }; + if (cmd.startsWith("(umask 077; case ")) return { stdout: "", stderr: "", exitCode: 0 }; + if (cmd.startsWith("rm -f ") || cmd.startsWith("rmdir ")) return { stdout: "", stderr: "", exitCode: 0 }; + if (cmd.includes("printf %s ")) { + throw Object.assign(new Error("upload link lost"), { outcome: "unknown" as const }); + } + if (cmd.startsWith("base64 -w 0 < ")) { + throw Object.assign(new Error("download link lost"), { outcome: "unknown" as const }); + } + throw Object.assign(new Error("command timed out without sentinel"), { outcome: "unknown" as const }); + }, + async destroy() { + throw Object.assign(new Error("tmux destroy timed out"), { outcome: "unknown" as const, terminalId: "term-x" }); + }, + fs: { + readFile: async () => "before", + writeFile: async () => { throw Object.assign(new Error("write link lost"), { outcome: "unknown" as const }); }, + createFile: async () => { throw Object.assign(new Error("create link lost"), { outcome: "unknown" as const }); }, + exists: async () => true, + readdir: async () => [], + rm: async () => {}, + mkdir: async () => {}, + stat: async () => ({ mtimeMs: 100, size: 6, isDirectory: false }), + }, + } as unknown as import("../src/driver.js").RuntimeDriver; + + await stack.addLayer("mock", drv); + const f = mcpFixture(stack); + const call = async (id: number, name: string, args: Record) => { + f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }); + return (await waitId(f, id, 15_000)).result as { + isError: boolean; + content: Array<{ type: string; text: string }>; + structuredContent?: Record; + }; + }; + + try { + const cmdRes = await call(1, "run_command", { layer: "mock", command: "touch /tmp/flag" }); + expect(cmdRes.isError).toBe(true); + expect(cmdRes.structuredContent).toMatchObject({ outcome: "unknown", error: "command timed out without sentinel" }); + expect(cmdRes.content[0]!.text).toBe("outcome=unknown\ncommand timed out without sentinel"); + + const putRes = await call(2, "transfer_file", { + layer: "mock", direction: "put", local_path: localSrc, remote_path: "/remote/up.bin", + }); + expect(putRes.isError).toBe(true); + expect(putRes.structuredContent).toMatchObject({ outcome: "unknown", error: "upload link lost" }); + expect(putRes.content[0]!.text).toBe("outcome=unknown\nupload link lost"); + + const getRes = await call(3, "transfer_file", { + layer: "mock", direction: "get", remote_path: "/remote/down.bin", local_path: localDst, + }); + expect(getRes.isError).toBe(true); + expect(getRes.structuredContent).toMatchObject({ outcome: "unknown", error: "download link lost" }); + expect(getRes.content[0]!.text).toBe("outcome=unknown\ndownload link lost"); + + const legacyPut = await call(4, "put_file", { + layer: "mock", local_path: localSrc, remote_path: "/remote/legacy-up.bin", + }); + expect(legacyPut.isError).toBe(true); + expect(legacyPut.content[0]!.text).toBe("outcome=unknown\nupload link lost"); + + const legacyGet = await call(5, "get_file", { + layer: "mock", remote_path: "/remote/legacy-down.bin", local_path: localDst, + }); + expect(legacyGet.isError).toBe(true); + expect(legacyGet.content[0]!.text).toBe("outcome=unknown\ndownload link lost"); + + const editRes = await call(6, "edit_file", { + layer: "mock", path: "/remote/note.txt", content: "updated", overwrite: true, + }); + expect(editRes.isError).toBe(true); + expect(editRes.structuredContent).toMatchObject({ outcome: "unknown", error: "write link lost" }); + expect(editRes.content[0]!.text).toBe("outcome=unknown\nwrite link lost"); + + const rmLayerRes = await call(7, "manage_layers", { action: "remove", name: "mock", destroy: true }); + expect(rmLayerRes.isError).toBe(true); + expect(rmLayerRes.structuredContent).toMatchObject({ outcome: "unknown", terminalId: "term-x" }); + expect(rmLayerRes.content[0]!.text).toBe("outcome=unknown\nterminal_id=term-x\ntmux destroy timed out"); + } finally { + f.close(); + rmSync(dir, { recursive: true, force: true }); + } +}); + test("MCP opens, reads, and closes a continuous window by ID", async () => { const fixture = mcpFixture(); const call = async (id: number, name: string, args: Record) => { @@ -675,26 +811,28 @@ test("MCP opens, reads, and closes a continuous window by ID", async () => { const opened = await call(1, "observe_stream", { command: "echo MCP_WINDOW" }); expect(opened.isError).toBe(false); const window_id = opened.structuredContent.window_id; - const read = await call(2, "read_stream", { window_id, since_seq: 0, wait_ms: 5000 }); + const read = await call(2, "observe_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); + expect((await call(4, "observe_stream", { window_id })).isError).toBe(true); } finally { fixture.close(); } }, 20_000); -test("read_stream text stays bounded and pages without skipping undisplayed frames", async () => { +test("observe_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 }) => { + toolkit.handlers.observe_stream = (async ({ window_id, since_seq, before_seq }: { + window_id: string; since_seq?: number; before_seq?: number; + }) => { 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 { @@ -702,15 +840,15 @@ test("read_stream text stays bounded and pages without skipping undisplayed fram ...(since_seq === undefined ? {} : { last_delivered_seq: selected.at(-1)?.seq ?? since_seq }), ...(selected.length ? {} : { timed_out: true }), }; - }; + }) as typeof toolkit.handlers.observe_stream; 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 }, + name: "observe_stream", arguments: { window_id, ...args }, } }); const result = (await waitId(fixture, id)).result as { content: Array<{ text: string }>; - structuredContent: Awaited>; + structuredContent: Awaited>; }; const text = result.content[0]!.text; expect(Buffer.byteLength(JSON.stringify(text))).toBeLessThanOrEqual(8192); @@ -749,7 +887,7 @@ test("read_stream text stays bounded and pages without skipping undisplayed fram }); describe("MCP layer array fan-out", () => { - test("push_ssh validates all batch targets and reports usable layers after partial failure", async () => { + test("connect_layer validates all batch targets and reports usable layers after partial failure", async () => { const stack = new RuntimeStack(); const addLayer = stack.addLayer.bind(stack); const attempted: Array<{ name: string; descriptor: Parameters[1] }> = []; @@ -777,10 +915,10 @@ describe("MCP layer array fan-out", () => { { hosts: ["web"] }, ]; for (const [index, args] of invalid.entries()) { - expect(await call(index, "push_ssh", args)).toMatchObject({ isError: true }); + expect(await call(index, "connect_layer", args)).toMatchObject({ isError: true }); } expect(attempted).toHaveLength(0); - expect(await call(10, "push_ssh", { targets: [ + expect(await call(10, "connect_layer", { targets: [ "web", "unreachable", { host: "db", name: "database", port: 2222, user: "deploy", jump: "bastion" }, "same-host", ] })).toMatchObject({ isError: false, @@ -801,10 +939,11 @@ describe("MCP layer array fan-out", () => { name: "database", descriptor: { driver: "ssh", target: "db", config: { connParams: { port: 2222, user: "deploy", jump: "bastion" } } }, }); - expect(await call(11, "push_ssh", { targets: ["unreachable"] })).toMatchObject({ + expect(await call(11, "connect_layer", { targets: ["unreachable"] })).toMatchObject({ structuredContent: { status: "fail", layers: [], active_layer: "database" }, }); - expect(await call(12, "push_ssh", { host: "single" })).toMatchObject({ + expect(await call(12, "connect_layer", { host: "single" })).toMatchObject({ + content: [{ text: "layer=single | reused=false" }], structuredContent: { layer: "single", reused: false }, }); } finally { @@ -905,4 +1044,95 @@ describe("MCP layer array fan-out", () => { expect(res.content[0]!.text).toContain("run_batch"); } finally { f.close(); } }); + + test("[P2] legacy 0.2.10 MCP tool names remain callable with original response shapes while hidden from tools/list", async () => { + const dir = mkdtempSync(join(tmpdir(), "fx-mcp-legacy-")); + const stack = new RuntimeStack(); + const local = new LocalRuntimeDriver({ cwd: dir }); + writeFileSync(join(dir, "hello.txt"), "legacy-content"); + writeFileSync(join(dir, "rm-me.txt"), "bye"); + writeFileSync(join(dir, "upload-src.bin"), "BIN123"); + await stack.addLayer("main", local); + const f = mcpFixture(stack); + const call = async (id: number, name: string, args: Record = {}) => { + f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }); + return (await waitId(f, id, 20_000)).result as { + isError: boolean; content: Array<{ text: string }>; structuredContent?: Record; + }; + }; + try { + f.write({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + const listedTools = ((await waitId(f, 1)).result as { tools: Array<{ name: string }> }).tools.map((t) => t.name); + expect(listedTools).toHaveLength(12); + expect(listedTools).not.toContain("read_file"); + + // read_file / list_directory / delete_file + const rf = await call(2, "read_file", { path: "hello.txt" }); + expect(rf.isError).toBe(false); + expect(rf.structuredContent).toMatchObject({ path: "hello.txt", content: "legacy-content" }); + expect(rf.structuredContent).not.toHaveProperty("type"); + expect((await call(3, "read_file", { path: "." })).isError).toBe(true); + + const ld = await call(4, "list_directory", { path: "." }); + expect(ld.isError).toBe(false); + expect(ld.structuredContent).not.toHaveProperty("type"); + expect(ld.structuredContent!.entries).toEqual(expect.arrayContaining([expect.objectContaining({ name: "hello.txt" })])); + + expect((await call(5, "delete_file", { path: "rm-me.txt", recursive: true })).isError).toBe(true); + const df = await call(6, "delete_file", { path: "rm-me.txt" }); + expect(df.structuredContent).toEqual({ path: "rm-me.txt", deleted: true }); + expect(df.content[0]!.text).toBe("deleted=true | path=rm-me.txt"); + + // put_file / get_file + const pf = await call(7, "put_file", { local_path: join(dir, "upload-src.bin"), remote_path: "uploaded.bin" }); + expect(pf.isError).toBe(false); + expect(pf.structuredContent).toMatchObject({ bytes: 6, verification: "sha256", transport: "exec" }); + expect(pf.structuredContent).not.toHaveProperty("direction"); + const gf = await call(8, "get_file", { remote_path: "uploaded.bin", local_path: join(dir, "downloaded.bin") }); + expect(gf.isError).toBe(false); + expect(gf.structuredContent).not.toHaveProperty("direction"); + + // observe_stream -> read_stream -> close_stream + const obs = await call(9, "observe_stream", { command: "echo LEGACY_FRAME" }); + const wid = obs.structuredContent!.window_id as string; + const rs = await call(10, "read_stream", { window_id: wid, since_seq: 0, wait_ms: 5000 }); + expect(rs.structuredContent).toMatchObject({ frames: [{ text: "LEGACY_FRAME", seq: 1 }] }); + expect(rs.content[0]!.text).toContain("[1 stdout] LEGACY_FRAME"); + expect((await call(11, "close_stream", { window_id: wid })).isError).toBe(false); + + // spawn_and_observe -> stop_and_verify + const sp = await call(12, "spawn_and_observe", { command: "echo READY; sleep 5", ready_marker: "READY" }); + const sid = sp.structuredContent!.session_id as string; + const sv = await call(13, "stop_and_verify", { session_id: sid }); + expect(["stopped", "exited", "unknown"]).toContain(sv.structuredContent!.status as string); + + // list_layers / set_active_layer / remove_layer + push_ssh / push_into + await stack.addLayer("alt", { + descriptor: { driver: "ssh", target: "alt-host" }, + exec: async () => ({ stdout: "", stderr: "", exitCode: 0 }), + init: async () => undefined, + destroy: async () => undefined, + pushInto: async (cmd: string) => ({ + descriptor: { driver: "ssh", target: "alt-host", config: { enterPipeline: [{ cmd }] } }, + init: async () => undefined, + destroy: async () => undefined, + exec: async () => ({ stdout: "", stderr: "", exitCode: 0 }), + }), + } as unknown as import("../src/driver.js").RuntimeDriver); + const ll = await call(14, "list_layers"); + expect(ll.structuredContent).not.toHaveProperty("action"); + expect(ll.content[0]!.text).toContain("alt"); + const sal = await call(15, "set_active_layer", { name: "alt" }); + expect(sal.structuredContent).toEqual({ active_layer: "alt" }); + const pi = await call(16, "push_into", { enter_cmd: "docker exec -i web sh", name: "web-ctr" }); + expect(pi.structuredContent).toMatchObject({ layer: "web-ctr" }); + const rl = await call(17, "remove_layer", { name: "web-ctr" }); + expect(rl.structuredContent).toEqual({ removed: "web-ctr" }); + expect((await call(18, "push_ssh", { targets: [] })).isError).toBe(true); + } finally { + f.close(); + await Promise.all([...stack.layers.keys()].map((name) => stack.removeLayer(name, { destroy: true }))); + rmSync(dir, { recursive: true, force: true }); + } + }, 30_000); }); diff --git a/tests/runtime-stack.test.ts b/tests/runtime-stack.test.ts index bbd64af..4b50482 100644 --- a/tests/runtime-stack.test.ts +++ b/tests/runtime-stack.test.ts @@ -834,7 +834,7 @@ describe("三十七期", () => { // 宿主未崩(测试还在跑即证明) }); - test("#2 stop_and_verify 停止通道抛错 → unknown + verify 继续(不裸抛)", async () => { + test("#2 stop_session 停止通道抛错 → unknown + verify 继续(不裸抛)", async () => { let verifyCalled = false; const drv = { descriptor: { driver: "local" }, @@ -847,7 +847,7 @@ describe("三十七期", () => { verifySession: async () => { verifyCalled = true; return { status: "exited", exitCode: 3 }; }, } as unknown as import("../src/driver.js").RuntimeDriver; const tk = createAgentToolkit(new RuntimeStack(), { driver: drv }); - const r = await tk.handlers.stop_and_verify({ session_id: "s34", layer: "__initial__" }); + const r = await tk.handlers.stop_session({ session_id: "s34", layer: "__initial__" }); expect(verifyCalled).toBe(true); // 修前:stop 抛错后 verify 根本不执行 expect(r.status).toBe("exited"); // verify 采纳真实退出码 expect((r as { exit_code?: number }).exit_code).toBe(3);