From a0caa05f62d7424b057aa8c36a5b9df1c602c978 Mon Sep 17 00:00:00 2001 From: corolin Date: Wed, 25 Nov 2026 16:44:09 +0800 Subject: [PATCH 1/2] Prepare Filaxis 0.2.12 with shared daemon and SSH forwarding --- CHANGELOG.md | 8 + bin/filaxis-mcp.ts | 63 +- bin/filaxis.ts | 821 +++++++++++++++++-- docs/skills/SKILL.en.md | 4 +- docs/skills/SKILL.md | 6 +- package.json | 2 +- src/agent-toolkit.ts | 160 +++- src/daemon-client.ts | 235 ++++++ src/daemon-files.ts | 185 +++++ src/daemon-server.ts | 1053 ++++++++++++++++++++++++ src/driver.ts | 6 + src/index.ts | 7 + src/local-driver.ts | 1 + src/local-session-manager.ts | 7 +- src/mcp-proxy.ts | 490 ++++++++++++ src/mcp-server.ts | 162 ++-- src/runtime-stack.ts | 218 ++++- src/shell-discovery.ts | 4 +- src/ssh-forward.ts | 1035 ++++++++++++++++++++++++ src/ssh-helpers.ts | 74 +- src/ssh-pty-driver.ts | 61 ++ src/stream-window.ts | 24 +- src/terminal/command-executer.ts | 2 +- src/terminal/pane-output-observer.ts | 1 + src/terminal/tmux-invoker.ts | 2 +- tests/agent-toolkit.test.ts | 4 +- tests/batch.test.ts | 4 +- tests/cli-help.test.ts | 52 +- tests/daemon.test.ts | 1100 ++++++++++++++++++++++++++ tests/file-edit.test.ts | 30 +- tests/file-transfer.test.ts | 6 +- tests/integration-ssh.test.ts | 19 +- tests/mcp-config.test.ts | 4 +- tests/mcp-proxy.test.ts | 698 ++++++++++++++++ tests/ssh-forward.test.ts | 799 +++++++++++++++++++ tests/ssh-transport.test.ts | 57 +- tests/terminal.test.ts | 30 +- 37 files changed, 7166 insertions(+), 268 deletions(-) create mode 100644 src/daemon-client.ts create mode 100644 src/daemon-files.ts create mode 100644 src/daemon-server.ts create mode 100644 src/mcp-proxy.ts create mode 100644 src/ssh-forward.ts create mode 100644 tests/daemon.test.ts create mode 100644 tests/mcp-proxy.test.ts create mode 100644 tests/ssh-forward.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ca0b1d..d425a70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,14 @@ --- +## 0.2.12 + +- 新增可显式启动的本机 Daemon。符合条件的 CLI 和 MCP 调用可共享命名层、转发与观察窗。MCP 代理断线后重连,已发出但终态未知的调用会按 `outcome: "unknown"` 返回。 +- CLI 新增 `forward add/list/remove` 和 `stream open/peek/list/close`。MCP 的 `manage_layers` 新增动态转发操作,支持 SSH 本地转发、远端转发和 SOCKS。可非交互进入的内层环境支持本地 TCP 转发。 +- SSH 转发等到实际就绪才返回成功。关闭时核实进程退出,结果未知时保留转发 ID。移除层名后仍可按 ID 操作活跃转发。 +- CLI 在调用方目录解析本地文件和相对 SSH 凭据路径。OpenSSH 路径中的空格会保留,逐跳 SSH 的主目录由执行该跳的环境解析。 +- Daemon 保留 RPC 错误详情并明确拒绝超过 16 MiB 的请求。CLI 会在执行前报告缺失或冲突的参数,观察流按指定分流分页并显示断流原因。 + ## 0.2.11 - MCP 工具清单从 18 个合并为 12 个。`read_path` 读取文件或列目录,`manage_path` 创建目录、移动或删除,`transfer_file` 统一上传与下载。层管理、后台会话和观察窗也采用合并后的入口,0.2.10 的旧工具名仍可直接调用。 diff --git a/bin/filaxis-mcp.ts b/bin/filaxis-mcp.ts index 0b683cc..9e5a104 100644 --- a/bin/filaxis-mcp.ts +++ b/bin/filaxis-mcp.ts @@ -11,18 +11,30 @@ * filaxis-mcp --enter "ssh remote-vm" --host user@bastion # 多跳 */ import { McpServer } from "../src/mcp-server.js"; +import { McpStdioProxy } from "../src/mcp-proxy.js"; +import { probeDaemon } from "../src/daemon-client.js"; import { RuntimeStack } from "../src/runtime-stack.js"; import { createAgentToolkit } from "../src/agent-toolkit.js"; import type { RuntimeDescriptor } from "../src/driver.js"; import { noopLogger } from "../src/logger.js"; // argv 解析(零依赖手写——与 bin/filaxis.ts 同哲学;子集:--host/--port/--user/ -// --key/-J/--enter/--hop/--layer/--docker) +// --key/-J/--enter/--hop/--layer/--docker/--no-daemon/--daemon-dir) const argv = process.argv.slice(2); const o: { host?: string; port?: number; user?: string; key?: string; jump?: string; hop: string[]; enter: string[]; layer?: string; docker?: string; + noDaemon?: boolean; daemonDir?: string; } = { hop: [], enter: [] }; +function optionValue(index: number): string { + const value = argv[index + 1]; + if (!value || value.startsWith("-")) { + console.error(`filaxis-mcp: ${argv[index]} 需要参数值`); + process.exit(2); + } + return value; +} + for (let i = 0; i < argv.length; i++) { const a = argv[i]!; switch (a) { @@ -32,15 +44,31 @@ for (let i = 0; i < argv.length; i++) { o.host = v; break; } - case "--port": o.port = parseInt(argv[++i]!, 10); break; - case "--user": o.user = argv[++i]; break; - case "--key": o.key = argv[++i]; break; - case "-J": case "--jump": o.jump = argv[++i]; break; - case "--hop": o.hop.push(argv[++i]!); break; - case "--enter": o.enter.push(argv[++i]!); break; - case "--layer": o.layer = argv[++i]; break; - case "--docker": o.docker = argv[++i]; break; - default: console.error(`filaxis-mcp: 未知参数 ${a}(支持 --host/--port/--user/--key/-J/--hop/--enter/--docker)`); + case "--port": { + const raw = argv[++i]; + const p = raw === undefined ? NaN : Number(raw); + if (!raw || !/^\d+$/.test(raw) || !Number.isInteger(p) || p < 1 || p > 65535) { + console.error(`filaxis-mcp: --port 需要 1-65535 整数(收到: ${raw ?? "(缺失)"})`); + process.exit(2); + } + o.port = p; + break; + } + case "--user": o.user = optionValue(i); i++; break; + case "--key": o.key = optionValue(i); i++; break; + case "-J": case "--jump": o.jump = optionValue(i); i++; break; + case "--hop": o.hop.push(optionValue(i)); i++; break; + case "--enter": o.enter.push(optionValue(i)); i++; break; + case "--layer": o.layer = optionValue(i); i++; break; + case "--docker": o.docker = optionValue(i); i++; break; + case "--no-daemon": o.noDaemon = true; break; + case "--daemon-dir": { + const v = argv[++i]; + if (!v || v.startsWith("-")) { console.error("filaxis-mcp: --daemon-dir 需要目录路径"); process.exit(2); } + o.daemonDir = v; + break; + } + default: console.error(`filaxis-mcp: 未知参数 ${a}(支持 --host/--port/--user/--key/-J/--hop/--enter/--docker/--no-daemon/--daemon-dir)`); process.exit(2); } } @@ -50,14 +78,23 @@ async function main(): Promise { // Keep diagnostics separate from MCP JSON-RPC stdout. const stderr = (message: string) => console.error(`[mcp] ${message}`); const logger = { ...noopLogger, warn: stderr, error: stderr }; - const stack = new RuntimeStack({ logger }); - let opts: Parameters[1]; + const hasSshPathOpts = Boolean(o.port !== undefined || o.user || o.key || o.jump || o.hop.length || o.enter.length || o.docker); if (o.layer) { throw new Error("filaxis-mcp 暂不支持 --layer 快照寻址(FEAT-04 后续)——用 --host/--enter"); } - if (!o.host && argv.length > 0) { + if (!o.host && hasSshPathOpts) { throw new Error("SSH 路径参数需要 --host"); } + const useDaemonAllowed = !o.noDaemon && process.env.FILAXIS_NO_DAEMON !== "1" && !o.host && !hasSshPathOpts; + if (useDaemonAllowed) { + const activeDaemon = await probeDaemon(o.daemonDir); + if (activeDaemon) { + new McpStdioProxy({ daemonDir: o.daemonDir, logger }).start(); + return; + } + } + const stack = new RuntimeStack({ logger }); + let opts: Parameters[1]; if (o.host) { const config: Record = {}; const conn: Record = {}; diff --git a/bin/filaxis.ts b/bin/filaxis.ts index 40a6acd..6bedf2e 100644 --- a/bin/filaxis.ts +++ b/bin/filaxis.ts @@ -16,16 +16,23 @@ * --known-hosts)+ sshHops 逐跳链(--hop 可重复)+ enterPipeline(--enter 可重复 * + --docker 糖)。每跳独立密钥等极端拓扑走 SDK descriptor 全量描述。 */ -import { RuntimeStack, LocalRuntimeDriver, SshPtyDriver, editFile, discoverLayer, layerDisplayName, runBatch, type BatchPlan } from "../src/index.js"; +import { + RuntimeStack, LocalRuntimeDriver, SshPtyDriver, editFile, discoverLayer, layerDisplayName, runBatch, type BatchPlan, type BatchReport, + DaemonServer, DaemonClient, probeDaemon, spawnDaemonBackground, parseAddrToUrl, urlRequestHost, urlRequestPort, + defaultDaemonDir, readDaemonLock, readDaemonConnection, cleanupDaemonFiles, isPidAlive, + normalizeForwardSpec, type CloseForwardResult, type OpenForwardSpec, type ForwardInfo, type CliTargetSpec, +} from "../src/index.js"; import type { RuntimeDriver, RuntimeDescriptor } from "../src/driver.js"; -import { readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync, readdirSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync } from "node:fs"; import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; -import { dirname, extname, join } from "node:path"; +import { dirname, extname, isAbsolute, join, resolve as resolvePath } from "node:path"; import { fileURLToPath } from "node:url"; import { withLocalWriteLock } from "./local-write-lock.js"; import { transferLayerFile } from "../src/layer-file-transfer.js"; import { noopLogger } from "../src/logger.js"; +import type { SshConnParams } from "../src/ssh-helpers.js"; +import { version as pkgVersion } from "../package.json" with { type: "json" }; const args = process.argv.slice(2); const cmd = args[0]; @@ -45,19 +52,28 @@ function dockerArg(argv: string[], i: number): string { return v; } -function numArg(argv: string[], i: number, opts: { positive?: boolean } = {}): number { +function numArg(argv: string[], i: number, opts: { positive?: boolean; nonNegative?: boolean } = {}): number { const raw = argv[i + 1]; - const n = raw === undefined ? NaN : parseInt(raw, 10); - if (!Number.isFinite(n) || (opts.positive && (n <= 0))) { - throw new Error(`参数 ${argv[i]} 需要一个${opts.positive ? "正" : ""}数字(收到: ${raw ?? "(缺失)"})`); + const n = raw !== undefined && /^[+-]?\d+$/.test(raw) ? Number(raw) : NaN; + if (!Number.isSafeInteger(n) || (opts.positive && n <= 0) || (opts.nonNegative && n < 0)) { + const desc = opts.positive ? "正" : opts.nonNegative ? "非负" : ""; + throw new Error(`参数 ${argv[i]} 需要一个${desc}数字(收到: ${raw ?? "(缺失)"})`); } return n; } +function strArg(argv: string[], i: number): string { + const v = argv[i + 1]; + if (!v || /^-(?:-|[A-Za-z])/.test(v)) { + throw new Error(`参数 ${argv[i]} 需要参数值`); + } + return v; +} + const batchValueOptions = new Set([ "--host", "--user", "--port", "--key", "-J", "--jump", "--hop", "--enter", "--docker", "--docker-shell", "--docker-runtime", "--forward", "--host-key", "--known-hosts", - "--layer", "--request-file", + "--layer", "--request-file", "--daemon-dir", ]); function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "default"): { @@ -71,16 +87,23 @@ function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "defau transport?: "exec" | "sftp"; stdinJson?: boolean; requestFile?: string; pty?: boolean; help?: boolean; stdinScript?: boolean; scriptFile?: string; // exec 免 Shell 通道(盲测 #4) + noDaemon?: boolean; daemonDir?: string; json?: boolean; + addr?: string; foreground?: boolean; force?: boolean; + dynLocal: string[]; dynRemote: string[]; dynDynamic: string[]; + id?: string; after?: number; before?: number; limit?: number; wait?: number; name?: string; positional: string[]; } { - const o: ReturnType = { positional: [], hop: [], enter: [], forward: [] }; + const o: ReturnType = { + positional: [], hop: [], enter: [], forward: [], + dynLocal: [], dynRemote: [], dynDynamic: [], + }; let noMoreOpts = false; // `--` 后全 positional(Astra 二十五期 #2:业务命令里的 --layer 等字面量曾被吞成选项——错层/丢参数) for (let i = 0; i < argv.length; i++) { const a = argv[i]!; if (noMoreOpts) { o.positional.push(a); continue; } if (a === "--") { noMoreOpts = true; continue; } // 命令分隔符:终止选项解析 if (a === "--help" || a === "-h") return { ...o, help: true }; - if (mode === "batch" && a.startsWith("-") && a !== "--stdin-json") { + if (mode === "batch" && a.startsWith("-") && a !== "--stdin-json" && a !== "--no-daemon") { if (!batchValueOptions.has(a)) throw new Error(`batch 不支持 ${a}`); const value = argv[i + 1]; if (!value || value.startsWith("-")) throw new Error(`batch 的 ${a} 需要参数值`); @@ -88,32 +111,40 @@ function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "defau switch (a) { case "--host": { const v = argv[++i]; - if (!v) throw new Error("--host 需要目标(user@host 形态)"); + if (!v || v.startsWith("-")) throw new Error("--host 需要目标(user@host 形态)"); o.host = v; break; } - case "--user": o.user = argv[++i]; break; + case "--user": o.user = strArg(argv, i); i++; break; case "--port": o.port = numArg(argv, i); i++; break; - case "--key": o.key = argv[++i]; break; - case "-J": case "--jump": o.jump = argv[++i]; break; - case "--hop": o.hop.push(argv[++i]!); break; - case "--enter": o.enter.push(argv[++i]!); break; + case "--key": o.key = strArg(argv, i); i++; break; + case "-J": case "--jump": o.jump = strArg(argv, i); i++; break; + case "--hop": o.hop.push(strArg(argv, i)); i++; break; + case "--enter": o.enter.push(strArg(argv, i)); i++; break; case "--pty": o.pty = true; break; case "--docker": o.docker = dockerArg(argv, i); i++; break; case "--docker-shell": o.dockerShell = dockerArg(argv, i); i++; break; case "--docker-runtime": o.dockerRuntime = dockerArg(argv, i); i++; break; - case "--forward": o.forward.push(argv[++i]!); break; - case "--host-key": o.hostKey = argv[++i]; break; - case "--known-hosts": o.knownHosts = argv[++i]; break; + case "--forward": o.forward.push(strArg(argv, i)); i++; break; + case "--host-key": o.hostKey = strArg(argv, i); i++; break; + case "--known-hosts": o.knownHosts = strArg(argv, i); i++; break; case "--layer": { const v = argv[++i]; - if (!v) throw new Error(`--layer 需要层名(收到缺失——曾静默落本机执行)`); // Sol 57 P1-1 + if (!v || v.startsWith("-")) throw new Error("--layer 需要层名"); o.layer = v; break; } case "--timeout": o.timeout = numArg(argv, i, { positive: true }); i++; break; // 正数(Hydrogen R9 #4:0/负数曾静默禁用或立即杀) case "--duration": o.duration = numArg(argv, i, { positive: true }); i++; break; - case "--stream": o.stream = argv[++i]; break; + case "--stream": { + const stream = strArg(argv, i); + if (stream !== "stdout" && stream !== "stderr" && stream !== "both") { + throw new Error("--stream 仅接受 stdout、stderr 或 both"); + } + o.stream = stream; + i++; + break; + } case "--all": o.all = true; break; case "--write-mode": { const v = argv[++i]; @@ -129,13 +160,38 @@ function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "defau } case "--stdin-json": o.stdinJson = true; break; case "--stdin-script": o.stdinScript = true; break; // exec 免 Shell:命令从 stdin 读(盲测 #4) - case "--script-file": o.scriptFile = argv[++i]; break; // exec 免 Shell:命令从文件读 - case "--request-file": o.requestFile = argv[++i]; break; + case "--script-file": o.scriptFile = strArg(argv, i); i++; break; + case "--request-file": o.requestFile = strArg(argv, i); i++; break; + case "--no-daemon": o.noDaemon = true; break; + case "--daemon-dir": o.daemonDir = strArg(argv, i); i++; break; + case "--json": o.json = true; break; + case "--addr": o.addr = strArg(argv, i); i++; break; + case "--foreground": o.foreground = true; break; + case "--force": o.force = true; break; + case "-L": o.dynLocal.push(strArg(argv, i)); i++; break; + case "-R": o.dynRemote.push(strArg(argv, i)); i++; break; + case "-D": { + const next = argv[i + 1]; + if (next === undefined || (next.startsWith("-") && !/^-\d/.test(next))) { + o.dynDynamic.push("0"); + } else { + o.dynDynamic.push(next); + i++; + } + break; + } + case "--id": o.id = strArg(argv, i); i++; break; + case "--after": o.after = numArg(argv, i, { nonNegative: true }); i++; break; + case "--before": o.before = numArg(argv, i, { nonNegative: true }); i++; break; + case "--limit": o.limit = numArg(argv, i, { positive: true }); i++; break; + case "--wait": o.wait = numArg(argv, i, { nonNegative: true }); i++; break; + case "--name": o.name = strArg(argv, i); i++; break; default: if (mode !== "default" && a.startsWith("-")) throw new Error(`未知参数 ${a}。以 - 开头的路径请放在 -- 之后`); o.positional.push(a); } } + if (o.stdinScript && o.scriptFile) throw new Error("--stdin-script 与 --script-file 二选一"); return o; } @@ -295,20 +351,16 @@ function savedLayerDriver(name: string, layers: Record, needPtyLink = false): Promise { + validateCliTargetOptions(opts); // PTY link 按需建(审计 M1):exec 通道独立 ssh 进程、观察流独立 spawn——都不依赖 // PTY link,且不 init 能保留 execChannel 的「多跳不可直达」诚实拒绝语义(统一 // init 会把假跳板名的错误提前成建链失败,改变错误落点);--pty 走 link.execMarker // 必须先建链(修前恒抛「未就绪」)。 const drv: RuntimeDriver = (() => { if (opts.layer) { - if (opts.host) throw new Error("--layer 与 --host 互斥(层路径已持久化——改路径请 filaxis layer save 覆盖)"); return savedLayerDriver(opts.layer); } if (opts.host) return new SshPtyDriver(buildSshDescriptor(opts), { logger: sshLogger }); - // local 层无路径概念——路径参数在场而 --host 缺席 = 防呆报错(静默忽略=错机器风险) - if (opts.jump || opts.hop.length || opts.enter.length || opts.docker || opts.forward.length || opts.hostKey || opts.knownHosts) { - throw new Error("路径描述参数(--jump/--hop/--enter/--docker/--forward/--host-key/--known-hosts)需要 --host(local 层无路径概念)"); - } return new LocalRuntimeDriver(); })(); if (needPtyLink && drv instanceof SshPtyDriver) await drv.init(); @@ -340,7 +392,196 @@ async function readStdinAll(): Promise { return text; } -async function runCliBatch(o: ReturnType): Promise { +/** 拆分冒号同时保留方括号内 IPv6(如 [::1]:8080:[::1]:80) */ +function splitColonsRespectingBrackets(raw: string): string[] { + const parts: string[] = []; + let cur = ""; + let inBracket = false; + for (const ch of raw) { + if (ch === "[") { + inBracket = true; + cur += ch; + } else if (ch === "]") { + inBracket = false; + cur += ch; + } else if (ch === ":" && !inBracket) { + parts.push(cur); + cur = ""; + } else { + cur += ch; + } + } + if (inBracket) throw new Error(`端口转发规格括号未闭合: ${raw}`); + parts.push(cur); + return parts; +} + +function parseStrictPort(raw: string, allowZero: boolean, spec: string): number { + if (allowZero && raw === "") return 0; + if (!/^\d+$/.test(raw)) throw new Error(`端口必须是数字 (${raw}): ${spec}`); + const port = Number(raw); + const min = allowZero ? 0 : 1; + if (!Number.isInteger(port) || port < min || port > 65535) { + throw new Error(`端口超出范围 ${min}-65535 (${raw}): ${spec}`); + } + return port; +} + +function parseDynamicForwardCliSpec(kind: "L" | "R" | "D", raw: string, id?: string, timeoutMs?: number): OpenForwardSpec { + const parts = splitColonsRespectingBrackets(raw); + let spec: OpenForwardSpec; + if (kind === "D") { + if (parts.length === 1) { + spec = { kind, bindPort: parseStrictPort(parts[0]!, true, raw) }; + } else if (parts.length === 2) { + spec = { kind, bindAddr: parts[0]!, bindPort: parseStrictPort(parts[1]!, true, raw) }; + } else { + throw new Error(`-D 规格格式应为 [bindAddr:]bindPort,收到: ${raw}`); + } + } else { + if (parts.length === 2) { + spec = { + kind, + bindPort: 0, + targetHost: parts[0]!, + targetPort: parseStrictPort(parts[1]!, false, raw), + }; + } else if (parts.length === 3) { + spec = { + kind, + bindPort: parseStrictPort(parts[0]!, true, raw), + targetHost: parts[1]!, + targetPort: parseStrictPort(parts[2]!, false, raw), + }; + } else if (parts.length === 4) { + spec = { + kind, + bindAddr: parts[0]!, + bindPort: parseStrictPort(parts[1]!, true, raw), + targetHost: parts[2]!, + targetPort: parseStrictPort(parts[3]!, false, raw), + }; + } else { + throw new Error(`-${kind} 规格格式应为 [[bindAddr:]bindPort:]targetHost:targetPort,收到: ${raw}`); + } + } + if (id !== undefined) spec.id = id; + if (timeoutMs !== undefined) spec.timeoutMs = timeoutMs; + normalizeForwardSpec(spec); + return spec; +} + +function validateCliTargetOptions(opts: ReturnType): void { + if (opts.layer && opts.host) throw new Error("--layer 与 --host 互斥(层路径已持久化——改路径请 filaxis layer save 覆盖)"); + if (!opts.host && (opts.user !== undefined || opts.port !== undefined || opts.key !== undefined || + opts.jump || opts.hop.length || opts.enter.length || opts.docker || opts.dockerRuntime || + opts.dockerShell || opts.forward.length || opts.hostKey || opts.knownHosts)) { + throw new Error("SSH 连接参数需要 --host(已保存层请修改快照)"); + } +} + +function resolveDaemonSshPaths(descriptor: RuntimeDescriptor): RuntimeDescriptor { + if (descriptor?.driver !== "ssh") return descriptor; + const config = descriptor.config; + const conn = config?.connParams as SshConnParams | undefined; + if (!conn || typeof conn !== "object") return descriptor; + + const fromCaller = (file: string | undefined): string | undefined => { + if (typeof file !== "string" || !file || file === "none" || isAbsolute(file) || /^(?:~|%|\$\{)/.test(file)) return file; + return resolvePath(file); + }; + const jump = conn.jump; + return { + ...descriptor, + config: { + ...config, + connParams: { + ...conn, + keyFile: fromCaller(conn.keyFile), + knownHostsFile: fromCaller(conn.knownHostsFile), + ...(jump && typeof jump === "object" + ? { jump: { ...jump, keyFile: fromCaller(jump.keyFile) } } + : {}), + }, + }, + }; +} + +function buildCliTargetSpec(opts: ReturnType, allowSavedLayerLookup = true): CliTargetSpec { + validateCliTargetOptions(opts); + if (opts.layer) { + if (allowSavedLayerLookup) { + const layers = loadLayerStore(); + if (Object.hasOwn(layers, opts.layer)) { + return { layer: opts.layer, descriptor: resolveDaemonSshPaths(layers[opts.layer]!) }; + } + } + return { layer: opts.layer }; + } + if (opts.host) { + return { descriptor: resolveDaemonSshPaths(buildSshDescriptor(opts)) }; + } + return { descriptor: { driver: "local" }, cwd: process.cwd() }; +} + +async function tryDaemon(opts: ReturnType): Promise { + if (opts.noDaemon || process.env.FILAXIS_NO_DAEMON === "1") return null; + return probeDaemon(opts.daemonDir); +} + +async function requireDaemon(opts: ReturnType): Promise { + if (opts.noDaemon) { + throw new Error("该命令依赖常驻 Daemon,不支持 --no-daemon"); + } + const client = await probeDaemon(opts.daemonDir); + if (!client) { + throw new Error("未检测到活跃的 Filaxis Daemon,请先运行 filaxis daemon start"); + } + return client; +} + +function printBatchReport(r: BatchReport): void { + for (const s of r.steps) { + const head = `[${s.status}] ${s.id} (${s.kind}${s.durationMs != null ? ` ${s.durationMs}ms` : ""})${s.layer === undefined ? "" : ` layer=${s.layer}`}`; + if (s.status === "skipped") { + console.log(`${head} — ${s.skippedBecause}`); + continue; + } + if (s.kind === "exec") { + console.log(`${head} exit=${s.exitCode}${s.effectiveUser ? ` user=${s.effectiveUser}` : ""}${s.error ? ` ✗ ${s.error}` : ""}`); + if (s.stdout) process.stdout.write(s.stdout.endsWith("\n") ? s.stdout : s.stdout + "\n"); + if (s.stderr) process.stderr.write(s.stderr.endsWith("\n") ? s.stderr : s.stderr + "\n"); + } else if (s.kind === "edit" && s.edits) { + console.log(`${head} ${s.edits.path} 替换 ${s.edits.occurrences} 处,${s.edits.bytesBefore}B → ${s.edits.bytesAfter}B${s.edits.mutex === "degraded" ? "(无锁降级)" : ""}`); + } else if (s.transfer) { + const { bytes, transport, verification, writeMode } = s.transfer; + console.log(`${head} ${bytes} 字节 | transport=${transport} | verification=${verification} | writeMode=${writeMode}`); + } else { + console.log(`${head} ${((s.stdout ?? "").length)} 字符`); + } + if (s.error && s.kind !== "exec") console.error(` ✗ ${s.error}`); + } + console.log(`batch ${r.status}${r.failedStep ? `(失败于 ${r.failedStep})` : ""}`); + process.exitCode = r.status === "ok" ? 0 : 1; +} + +function printObserveStopStatus( + stopStatus: "exited" | "stopped" | "unknown", + verifyStatus: string | undefined, + verifyError: string | undefined, + sessionId: string, + logBase: string, +): void { + if (stopStatus !== "unknown") return; + if (verifyStatus === "unknown" || verifyStatus === "running") process.exitCode = 1; + if (verifyStatus === "running") { + console.error(`[filaxis] 停止结果未知且核实显示**任务仍在运行**——会话 ${sessionId} 日志 ${logBase},勿盲目重试`); + } else if (verifyStatus === "unknown") { + console.error(`[filaxis] 停止与核实均为未知(${verifyError ? `核实失败: ${verifyError}` : "通道异常或会话失联"})——会话 ${sessionId} 日志 ${logBase},任务可能仍在运行:核实终态后再重试`); + } +} + +async function runCliBatch(o: ReturnType, daemon: DaemonClient | null): Promise { // 批次组合(第十一季):计划 JSON 经 --request-file / --stdin-json 直达 //(免 Shell 通道哲学——多行命令/hunk 绝不进 argv) if (o.positional.length) throw new Error(`batch 不接受位置参数:${o.positional.join(" ")}`); @@ -363,6 +604,27 @@ async function runCliBatch(o: ReturnType): Promise { if (o.layer && plan && typeof plan === "object" && !Array.isArray(plan) && plan.layer === undefined) { plan = { ...plan, layer: o.layer }; } + if (daemon) { + const savedLayers = Object.fromEntries( + Object.entries(loadLayerStore()).map(([name, descriptor]) => [name, resolveDaemonSshPaths(descriptor)]), + ); + const target = !o.layer ? buildCliTargetSpec(o) : undefined; + const resolvedPlan: BatchPlan = (plan && typeof plan === "object" && !Array.isArray(plan) && Array.isArray(plan.steps)) + ? { + ...plan, + steps: plan.steps.map((step) => { + if (step && typeof step === "object" && (step.kind === "put" || step.kind === "get") + && typeof step.localPath === "string" && step.localPath.length > 0 && !step.localPath.includes("\0")) { + return { ...step, localPath: resolvePath(step.localPath) }; + } + return step; + }), + } + : plan; + const r = await daemon.rpc("batch", { target, plan: resolvedPlan, savedLayers, clientCwd: process.cwd() }); + printBatchReport(r); + return; + } const drivers = new Map(); let saved: Record | undefined; try { @@ -373,31 +635,320 @@ async function runCliBatch(o: ReturnType): Promise { drivers.set(name, driver); return driver; }, plan); - for (const s of r.steps) { - const head = `[${s.status}] ${s.id} (${s.kind}${s.durationMs != null ? ` ${s.durationMs}ms` : ""})${s.layer === undefined ? "" : ` layer=${s.layer}`}`; - if (s.status === "skipped") { - console.log(`${head} — ${s.skippedBecause}`); - continue; - } - if (s.kind === "exec") { - console.log(`${head} exit=${s.exitCode}${s.effectiveUser ? ` user=${s.effectiveUser}` : ""}${s.error ? ` ✗ ${s.error}` : ""}`); - if (s.stdout) process.stdout.write(s.stdout.endsWith("\n") ? s.stdout : s.stdout + "\n"); - if (s.stderr) process.stderr.write(s.stderr.endsWith("\n") ? s.stderr : s.stderr + "\n"); - } else if (s.kind === "edit" && s.edits) { - console.log(`${head} ${s.edits.path} 替换 ${s.edits.occurrences} 处,${s.edits.bytesBefore}B → ${s.edits.bytesAfter}B${s.edits.mutex === "degraded" ? "(无锁降级)" : ""}`); - } else if (s.transfer) { - const { bytes, transport, verification, writeMode } = s.transfer; - console.log(`${head} ${bytes} 字节 | transport=${transport} | verification=${verification} | writeMode=${writeMode}`); + printBatchReport(r); + } finally { + await Promise.all([...drivers.values()].map(destroyDriver)); + } +} + +async function waitForPidExit(pid: number, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (!isPidAlive(pid)) return true; + await new Promise((r) => setTimeout(r, 50)); + } + return !isPidAlive(pid); +} + +async function forceStopPid(pid: number, dir: string): Promise { + try { process.kill(pid, "SIGTERM"); } catch { /* ignore */ } + if (await waitForPidExit(pid, 2_000)) { + cleanupDaemonFiles(dir, pid); + return true; + } + try { process.kill(pid, "SIGKILL"); } catch { /* ignore */ } + if (await waitForPidExit(pid, 2_000)) { + cleanupDaemonFiles(dir, pid); + return true; + } + return false; +} + +async function handleDaemonCmd(sub: string | undefined, o: ReturnType): Promise { + if ((sub === "start" || sub === "status" || sub === "stop") && o.positional.length) { + throw new Error(`daemon ${sub} 不接受位置参数: ${o.positional.join(" ")}`); + } + const dir = o.daemonDir ?? defaultDaemonDir(); + if (sub === "start") { + let host = "127.0.0.1"; + let port = 0; + if (o.addr) { + const url = parseAddrToUrl(o.addr); + host = urlRequestHost(url); + port = urlRequestPort(url); + } + if (o.foreground) { + const srv = new DaemonServer({ daemonDir: dir, host, port, version: pkgVersion, logger: sshLogger }); + const addr = await srv.start(); + if (o.json) { + console.log(JSON.stringify({ running: true, pid: process.pid, addr, daemonDir: dir })); } else { - console.log(`${head} ${((s.stdout ?? "").length)} 字符`); + console.log(`Filaxis Daemon 已启动 (foreground): pid=${process.pid} addr=${addr}`); } - if (s.error && s.kind !== "exec") console.error(` ✗ ${s.error}`); + let closing = false; + const onSignal = () => { + if (closing) return; + closing = true; + void srv.stop(); + }; + process.on("SIGINT", onSignal); + process.on("SIGTERM", onSignal); + await srv.waitForStop(); + process.removeListener("SIGINT", onSignal); + process.removeListener("SIGTERM", onSignal); + return; } - console.log(`batch ${r.status}${r.failedStep ? `(失败于 ${r.failedStep})` : ""}`); - process.exitCode = r.status === "ok" ? 0 : 1; - } finally { - await Promise.all([...drivers.values()].map(destroyDriver)); + const cliEntryPath = fileURLToPath(import.meta.url); + const info = await spawnDaemonBackground({ cliEntryPath, daemonDir: dir, addr: o.addr }); + if (o.json) { + console.log(JSON.stringify({ running: true, ...info, daemonDir: dir }, null, 2)); + } else { + console.log(`Filaxis Daemon 已启动: pid=${info.pid} addr=${info.addr} dir=${dir}`); + } + return; + } + if (sub === "status") { + const client = await probeDaemon(dir); + if (!client) { + if (o.json) console.log(JSON.stringify({ running: false, daemonDir: dir })); + else console.log(`Filaxis Daemon 未运行 (${dir})`); + process.exitCode = 1; + return; + } + const info = await client.status(); + if (o.json) { + console.log(JSON.stringify({ running: true, ...info, daemonDir: dir }, null, 2)); + } else { + console.log(`Filaxis Daemon 运行中: pid=${info.pid} addr=${info.addr} uptime=${Math.round(info.uptimeMs / 1000)}s`); + console.log(` layers=${info.layers.length} forwards=${info.forwards.length} streams=${info.streams.length}`); + } + return; + } + if (sub === "stop") { + const client = await probeDaemon(dir); + if (client) { + let pid: number | undefined; + try { pid = (await client.status(1500)).pid; } catch { pid = readDaemonLock(dir)?.pid; } + await client.shutdown(); + const deadline = Date.now() + 5000; + while (Date.now() < deadline) { + const stillConn = readDaemonConnection(dir); + const alive = pid ? isPidAlive(pid) : false; + if (!stillConn && !alive) break; + await new Promise((r) => setTimeout(r, 50)); + } + if (pid && isPidAlive(pid)) { + if (!o.force) { + process.exitCode = 1; + if (o.json) console.log(JSON.stringify({ stopped: false, status: "unknown", pid })); + else console.error(`[filaxis] Daemon 停机核实超时:进程仍存活 (pid=${pid}),终态未知(加 --force 可强制终止)`); + return; + } + const killed = await forceStopPid(pid, dir); + if (!killed) { + process.exitCode = 1; + if (o.json) console.log(JSON.stringify({ stopped: false, status: "unknown", forced: true, pid })); + else console.error(`[filaxis] 强制终止 Daemon 后仍未确认退出 (pid=${pid}),终态未知`); + return; + } + if (o.json) console.log(JSON.stringify({ stopped: true, forced: true, pid })); + else console.log(`已强制停止 Filaxis Daemon (pid=${pid})`); + return; + } + if (o.json) console.log(JSON.stringify({ stopped: true, ...(pid ? { pid } : {}) })); + else console.log(`Filaxis Daemon 已停止${pid ? ` (pid=${pid})` : ""}`); + return; + } + const lock = readDaemonLock(dir); + if (lock && isPidAlive(lock.pid)) { + if (!o.force) { + throw new Error(`Daemon 控制面无响应但进程仍存活 (pid=${lock.pid})——加 --force 强制终止`); + } + const killed = await forceStopPid(lock.pid, dir); + if (!killed) { + process.exitCode = 1; + if (o.json) console.log(JSON.stringify({ stopped: false, status: "unknown", forced: true, pid: lock.pid })); + else console.error(`[filaxis] 强制终止 Daemon 后仍未确认退出 (pid=${lock.pid}),终态未知`); + return; + } + if (o.json) console.log(JSON.stringify({ stopped: true, forced: true, pid: lock.pid })); + else console.log(`已强制停止 Filaxis Daemon (pid=${lock.pid})`); + return; + } + if (lock) { + cleanupDaemonFiles(dir); + if (o.json) console.log(JSON.stringify({ stopped: true, staleCleaned: true })); + else console.log("未检测到活跃 Daemon(已清理陈旧锁文件)"); + return; + } + if (o.json) console.log(JSON.stringify({ stopped: false, running: false })); + else console.log("Filaxis Daemon 未运行"); + process.exitCode = 1; + return; } + throw new Error("用法: filaxis daemon start [--addr host:port] [--foreground] [--daemon-dir dir] | status | stop [--force]"); +} + +async function handleForwardCmd(sub: string | undefined, o: ReturnType): Promise { + if (sub === "list" && o.positional.length) throw new Error("forward list 不接受位置参数"); + if ((sub === "remove" || sub === "rm") && (o.positional.length !== 1 || !o.positional[0])) { + throw new Error("forward remove 需要且只接受一个 forward_id"); + } + const client = await requireDaemon(o); + if (sub === "add") { + if (o.positional.length) { + throw new Error(`forward add 不接受位置参数: ${o.positional.join(" ")}`); + } + const specs: Array<{ kind: "L" | "R" | "D"; raw: string }> = [ + ...o.dynLocal.map((raw) => ({ kind: "L" as const, raw })), + ...o.dynRemote.map((raw) => ({ kind: "R" as const, raw })), + ...o.dynDynamic.map((raw) => ({ kind: "D" as const, raw })), + ]; + if (specs.length !== 1) { + throw new Error("用法: filaxis forward add (--layer NAME | --host HOST) (-L SPEC | -R SPEC | -D SPEC) [--id ID]"); + } + const spec = parseDynamicForwardCliSpec(specs[0]!.kind, specs[0]!.raw, o.id, o.timeout); + const target = buildCliTargetSpec(o); + const info = await client.rpc("forward.add", { target, spec }); + if (info.status !== "active") { + if (o.json) console.log(JSON.stringify(info, null, 2)); + else console.error(`forward add: id=${info.forwardId} status=${info.status}${info.lastError ? ` (${info.lastError})` : ""}`); + process.exitCode = 1; + return; + } + if (o.json) { + console.log(JSON.stringify(info, null, 2)); + } else { + const targetDesc = info.kind === "dynamic" ? "SOCKS5" : `${info.targetHost}:${info.targetPort}`; + console.log(`forward added: id=${info.forwardId} layer=${info.layer ?? "?"} ${info.kind} ${info.bindAddr}:${info.bindPort} -> ${targetDesc} (${info.transportMode})`); + } + return; + } + if (sub === "list") { + const res = await client.rpc<{ forwards: ForwardInfo[] }>("forward.list", { ...(o.layer ? { layer: o.layer } : {}) }); + if (o.json) { + console.log(JSON.stringify(res.forwards, null, 2)); + return; + } + if (res.forwards.length === 0) { + console.log("(无活跃动态端口转发)"); + return; + } + for (const f of res.forwards) { + const dst = f.kind === "dynamic" ? "SOCKS5" : `${f.targetHost}:${f.targetPort}`; + console.log(` ${f.forwardId} | layer=${f.layer ?? "?"} | ${f.kind} ${f.bindAddr}:${f.bindPort} -> ${dst} | ${f.transportMode} | ${f.status}`); + } + return; + } + if (sub === "remove" || sub === "rm") { + const res = await client.rpc("forward.remove", { + forwardId: o.positional[0]!, + ...(o.layer ? { layer: o.layer } : {}), + }); + if (o.json) { + console.log(JSON.stringify(res, null, 2)); + } else { + console.log(`forward remove: id=${res.forwardId} status=${res.status}${res.detail ? ` (${res.detail})` : ""}`); + } + if (res.status === "unknown") process.exitCode = 1; + return; + } + throw new Error("用法: filaxis forward add ... | list [--layer NAME] | remove "); +} + +type StreamRpcResult = { + window_id: string; + name?: string; + layer?: string; + oldest_seq: number; + newest_seq: number; + stale: boolean; + frames: Array<{ seq: number; ts: number; text: string; stream?: string }>; + last_delivered_seq?: number; + gap?: boolean; + exit_code?: number | null; + error?: string; +}; + +function printStreamRpcResult(res: StreamRpcResult): void { + const header = [ + `window=${res.window_id}`, + ...(res.layer ? [`layer=${res.layer}`] : []), + `oldest=${res.oldest_seq}`, + `newest=${res.newest_seq}`, + `stale=${res.stale}`, + ...(res.last_delivered_seq !== undefined ? [`cursor=${res.last_delivered_seq}`] : []), + ...(res.gap ? ["gap=true"] : []), + ...(res.exit_code !== undefined ? [`exit=${res.exit_code}`] : []), + ].join(" | "); + console.log(header); + for (const f of res.frames) { + console.log(`[${f.seq} ${f.stream ?? "output"}] ${f.text}`); + } + if (res.error) console.error(`[filaxis] ${res.error}`); +} + +async function handleStreamCmd(sub: string | undefined, o: ReturnType): Promise { + if (sub === "list" && o.positional.length) throw new Error("stream list 不接受位置参数"); + if ((sub === "peek" || sub === "close") && (o.positional.length !== 1 || !o.positional[0])) { + throw new Error(`stream ${sub} 需要且只接受一个 window_id`); + } + const client = await requireDaemon(o); + if (sub === "open") { + let command = o.positional.join(" "); + const sanitizeScript = (t: string): string => + (t.charCodeAt(0) === 0xfeff ? t.slice(1) : t).replace(/\r\n/g, "\n"); + if (o.stdinScript) command = sanitizeScript(await readStdinAll()); + else if (o.scriptFile) command = sanitizeScript(readFileSync(o.scriptFile, "utf-8")); + if (!command.trim()) throw new Error("用法: filaxis stream open [--layer NAME | --host HOST] [--stream stdout|stderr|both] [--wait MS] [--limit N] -- "); + const target = buildCliTargetSpec(o); + const res = await client.rpc("stream.open", { + target, + command, + ...(o.stream ? { stream: o.stream } : {}), + ...(o.name ? { name: o.name } : {}), + ...(o.limit !== undefined ? { limit: o.limit } : {}), + ...(o.wait !== undefined ? { waitMs: o.wait } : {}), + }); + if (o.json) console.log(JSON.stringify(res, null, 2)); + else printStreamRpcResult(res); + return; + } + if (sub === "peek") { + const res = await client.rpc("stream.peek", { + windowId: o.positional[0]!, + ...(o.after !== undefined ? { afterSeq: o.after } : {}), + ...(o.before !== undefined ? { beforeSeq: o.before } : {}), + ...(o.limit !== undefined ? { limit: o.limit } : {}), + ...(o.wait !== undefined ? { waitMs: o.wait } : {}), + ...(o.stream ? { stream: o.stream } : {}), + }); + if (o.json) console.log(JSON.stringify(res, null, 2)); + else printStreamRpcResult(res); + return; + } + if (sub === "close") { + const res = await client.rpc<{ window_id: string; closed: boolean }>("stream.close", { windowId: o.positional[0]! }); + if (o.json) console.log(JSON.stringify(res, null, 2)); + else console.log(`stream closed: ${res.window_id}`); + return; + } + if (sub === "list") { + const res = await client.rpc<{ streams: Array<{ window_id: string; name?: string; layer: string; command: string; oldest_seq: number; newest_seq: number; stale: boolean }> }>("stream.list"); + if (o.json) { + console.log(JSON.stringify(res.streams, null, 2)); + return; + } + if (res.streams.length === 0) { + console.log("(无活跃观察窗)"); + return; + } + for (const w of res.streams) { + console.log(` ${w.window_id} | layer=${w.layer} | seq=${w.oldest_seq}..${w.newest_seq} | stale=${w.stale} | ${w.command}`); + } + return; + } + throw new Error("用法: filaxis stream open ... | peek | close | list"); } const generalHelp = `filaxis CLI — 千里一线,执行有迹 @@ -418,7 +969,13 @@ const generalHelp = `filaxis CLI — 千里一线,执行有迹 --stdin-json # 计划及每步可用 layer 选择已保存层 filaxis layer save --host ... [-J/--hop/--enter/--docker/...] # 层路径持久化 list | rm # 层清单/移除 - (全子命令 --layer 用已存层一行直达;与 --host 互斥) + filaxis daemon start [--addr host:port] [--foreground] # 显式启停常驻 Daemon + status | stop [--force] # 查看状态/优雅停机 + filaxis forward add (--layer NAME|--host ...) (-L|-R|-D SPEC) # 动态端口转发(需 Daemon) + list [--layer NAME] | remove + filaxis stream open [--layer NAME|--host ...] -- # 跨命令持续观察窗(需 Daemon) + peek [--after SEQ|--before SEQ] | close | list + (全子命令 --layer 用已存层一行直达;与 --host 互斥;检测到活跃 Daemon 时自动复用,--no-daemon 绕过) 路径描述(需 --host;对齐内核三件套 connParams/sshHops/enterPipeline): -J, --jump 跳板(-J:途径机不占层,ssh 自身代理) @@ -447,6 +1004,19 @@ async function main() { ["layer save", "filaxis layer save --host HOST [--port N] [--key FILE] [-J JUMP] [--hop HOST] [--enter CMD] [--docker CTR] [--forward SPEC] [--host-key tofu|strict] [--known-hosts FILE]"], ["layer list", "filaxis layer list"], ["layer rm", "filaxis layer rm "], + ["daemon", "filaxis daemon start [--addr host:port] [--foreground] [--daemon-dir dir] [--json] | status [--json] | stop [--force] [--json]"], + ["daemon start", "filaxis daemon start [--addr host:port] [--foreground] [--daemon-dir dir] [--json]"], + ["daemon status", "filaxis daemon status [--daemon-dir dir] [--json]"], + ["daemon stop", "filaxis daemon stop [--force] [--daemon-dir dir] [--json]"], + ["forward", "filaxis forward add (--layer NAME | --host HOST) (-L SPEC | -R SPEC | -D SPEC) [--id ID] [--json] | list [--layer NAME] [--json] | remove [--layer NAME] [--json]"], + ["forward add", "filaxis forward add (--layer NAME | --host HOST) (-L [[bind:]port:]host:port | -R [[bind:]port:]host:port | -D [[bind:]port]) [--id ID] [--json]"], + ["forward list", "filaxis forward list [--layer NAME] [--daemon-dir dir] [--json]"], + ["forward remove", "filaxis forward remove [--layer NAME] [--daemon-dir dir] [--json]"], + ["stream", "filaxis stream open (--layer NAME | --host HOST) [--stream stdout|stderr|both] [--limit N] [--wait MS] [--json] -- | peek [--after SEQ|--before SEQ] [--limit N] [--wait MS] [--json] | close | list"], + ["stream open", "filaxis stream open [--layer NAME | --host HOST] [--stream stdout|stderr|both] [--limit N] [--wait MS] [--name NAME] [--json] -- "], + ["stream peek", "filaxis stream peek [--after SEQ | --before SEQ] [--limit N] [--wait MS] [--stream stdout|stderr|both] [--json]"], + ["stream close", "filaxis stream close [--json]"], + ["stream list", "filaxis stream list [--json]"], ]); if (!cmd || (args.length === 1 && helpFlag(cmd))) { console.log(generalHelp); @@ -481,6 +1051,20 @@ async function main() { handleLayerCmd(sub, o); return; } + if (cmd === "daemon" || cmd === "forward" || cmd === "stream") { + const sub = args[1]; + const o = parseOpts(args.slice(2)); + if (helpFlag(sub) || o.help || !sub) { + const specific = sub ? commandHelp.get(`${cmd} ${sub}`) : undefined; + console.log(`用法: ${specific ?? commandHelp.get(cmd)}`); + if (!sub) process.exitCode = 1; + return; + } + if (cmd === "daemon") await handleDaemonCmd(sub, o); + else if (cmd === "forward") await handleForwardCmd(sub, o); + else await handleStreamCmd(sub, o); + return; + } const transfer = cmd === "put" || cmd === "get" ? cmd : undefined; const o = parseOpts(args.slice(1), cmd === "batch" ? "batch" : transfer ? "strict" : "default"); const help = commandHelp.get(cmd); @@ -488,10 +1072,6 @@ async function main() { console.log(`用法: ${help}`); return; } - if (cmd === "batch") { - await runCliBatch(o); - return; - } if (transfer) { if (o.pty) throw new Error(`${transfer} 需要非交互 exec 通道完成文件校验`); if (transfer === "get" && o.writeMode !== undefined) throw new Error("--write-mode 仅用于 put"); @@ -499,6 +1079,15 @@ async function main() { throw new Error(transferUsage(transfer)); } } + const daemon = await tryDaemon(o); + if (cmd === "batch") { + await runCliBatch(o, daemon); + return; + } + if (daemon) { + await runViaDaemon(cmd, o, daemon); + return; + } const drv = await driverFor(o, o.pty === true); // --pty 需先建 PTY link(审计 M1) try { switch (cmd) { @@ -627,12 +1216,7 @@ async function main() { let vStatus = "unknown"; let vErr = ""; try { vStatus = (await drv.verifySession(h.sessionId)).status; } catch (e) { vErr = (e as Error).message; } - if (vStatus === "unknown" || vStatus === "running") process.exitCode = 1; - if (vStatus === "running") { - console.error(`[filaxis] 停止结果未知且核实显示**任务仍在运行**——会话 ${h.sessionId} 日志 ${h.logBase},勿盲目重试`); - } else if (vStatus === "unknown") { - console.error(`[filaxis] 停止与核实均为未知(${vErr ? `核实失败: ${vErr}` : "通道异常或会话失联"})——会话 ${h.sessionId} 日志 ${h.logBase},任务可能仍在运行:核实终态后再重试`); - } + printObserveStopStatus(stopR.status, vStatus, vErr, h.sessionId, h.logBase); } break; } @@ -650,7 +1234,120 @@ async function main() { } } +async function runViaDaemon(cmd: string, o: ReturnType, daemon: DaemonClient): Promise { + switch (cmd) { + case "put": + case "get": { + const target = buildCliTargetSpec(o); + const [source, destination] = o.positional as [string, string]; + const result = await daemon.rpc("transfer", { + target, + direction: cmd, + localPath: resolvePath(cmd === "put" ? source : destination), + remotePath: cmd === "put" ? destination : source, + transport: o.transport, + timeoutMs: o.timeout, + writeMode: o.writeMode, + }); + console.log(JSON.stringify(result)); + break; + } + case "exec": { + const target = buildCliTargetSpec(o); + let execCmd = o.positional.join(" "); + const sanitizeScript = (t: string): string => + (t.charCodeAt(0) === 0xfeff ? t.slice(1) : t).replace(/\r\n/g, "\n"); + if (o.stdinScript) execCmd = sanitizeScript(await readStdinAll()); + else if (o.scriptFile) execCmd = sanitizeScript(readFileSync(o.scriptFile, "utf-8")); + const r = await daemon.rpc<{ stdout: string; stderr: string; exitCode: number; effectiveUser?: string }>("exec", { + target, + command: execCmd, + timeoutMs: o.timeout ?? 120_000, + pty: o.pty === true, + }); + process.stdout.write(r.stdout); + if (r.stderr) process.stderr.write(r.stderr); + console.error(`\n[exit=${r.exitCode} user=${r.effectiveUser ?? "?"}]`); + process.exitCode = r.exitCode; + break; + } + case "cat": { + const [p] = o.positional; + if (!p || p === "--help" || p === "-h") { + console.log("用法: filaxis cat [--host ...] [--layer <名>] \n输出远端/本地文件内容(UTF-8 文本;二进制走 SDK readBase64)"); + break; + } + const target = buildCliTargetSpec(o); + const r = await daemon.rpc<{ content: string }>("cat", { target, path: p }); + process.stdout.write(r.content); + break; + } + case "edit": { + const [p, oldArg, newArg] = o.positional; + let old = oldArg; + let newStr = newArg; + let all = o.all; + if (o.stdinJson || o.requestFile) { + if (o.stdinJson && o.requestFile) throw new Error("--stdin-json 与 --request-file 二选一"); + if (oldArg !== undefined || newArg !== undefined) { + throw new Error("--stdin-json/--request-file 与位置参数 互斥(JSON 载荷已携带)"); + } + const payload = o.requestFile ? readFileSync(o.requestFile, "utf-8") : await readStdinAll(); + let req: { old?: unknown; new?: unknown; all?: unknown }; + try { req = JSON.parse(payload) as typeof req; } + catch (e) { throw new Error(`JSON 载荷解析失败(${o.requestFile ?? "stdin"}): ${(e as Error).message}`); } + if (!req || typeof req.old !== "string" || typeof req.new !== "string" + || (req.all !== undefined && typeof req.all !== "boolean")) { + throw new Error('JSON 载荷需含字符串字段 "old" 与 "new"(可选 "all": boolean)'); + } + old = req.old; + newStr = req.new; + if (typeof req.all === "boolean") all = req.all; + } + if (!p || old === undefined || newStr === undefined) { + throw new Error("用法: filaxis edit [--host ...] [--all] [--write-mode auto|inplace] 或 (--stdin-json | --request-file )\n提示:old/new 含引号/多行时优先 --request-file(免 Shell 通道,宿主引号规则零影响)"); + } + const target = buildCliTargetSpec(o); + const r = await daemon.rpc<{ path: string; occurrences: number; bytesBefore: number; bytesAfter: number; mutex?: string }>("edit", { + target, path: p, old, new: newStr, all, writeMode: o.writeMode, + }); + console.log(`edited: ${r.path} 替换 ${r.occurrences} 处,${r.bytesBefore}B → ${r.bytesAfter}B${r.mutex === "degraded" ? "(无锁降级)" : ""}`); + break; + } + case "observe": { + const target = buildCliTargetSpec(o); + const r = await daemon.rpc<{ + lines: Array<{ stream: string; text: string }>; + stopStatus: "exited" | "stopped" | "unknown"; + verifyStatus?: string; + verifyError?: string; + sessionId: string; + logBase: string; + }>("observe", { + target, + command: o.positional.join(" "), + stream: o.stream, + duration: o.duration ?? 8000, + }); + for (const l of r.lines) console.log(`[${l.stream}] ${l.text}`); + printObserveStopStatus(r.stopStatus, r.verifyStatus, r.verifyError, r.sessionId, r.logBase); + break; + } + case "probe": { + const target = buildCliTargetSpec(o); + const r = await daemon.rpc<{ key: string; spec: unknown; note?: string }>("probe", { target }); + console.log(JSON.stringify({ key: r.key, spec: r.spec, note: r.note }, null, 2)); + break; + } + default: + console.error(generalHelp); + process.exitCode = 1; + } +} + void main().catch((err) => { - console.error(`[filaxis] ${(err as Error).message}`); + const { message, outcome, forwardId } = err as Error & { outcome?: string; forwardId?: string }; + const detail = outcome === "unknown" && !message.includes("outcome=unknown") ? " (outcome=unknown)" : ""; + console.error(`[filaxis] ${message}${detail}${forwardId ? ` forward_id=${forwardId}` : ""}`); process.exit(1); }); diff --git a/docs/skills/SKILL.en.md b/docs/skills/SKILL.en.md index 3166952..79107ad 100644 --- a/docs/skills/SKILL.en.md +++ b/docs/skills/SKILL.en.md @@ -1,7 +1,7 @@ --- name: filaxis-runtime metadata: - version: "0.2.11" + version: "0.2.12" 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. @@ -62,6 +62,8 @@ filaxis edit --layer --request-file edit.json filaxis exec --layer --timeout 8000 -- "(printf 'PING\n'; sleep 1) | nc 127.0.0.1 6379" ``` +Run `filaxis daemon start` to share layers, forwards, and observation windows between the CLI and MCP launchers without an explicit SSH target. Use `filaxis daemon status` to inspect the daemon, `filaxis daemon stop` to stop it, or `--no-daemon` for an individual call. Manage continuous observation with `filaxis stream open/peek/close`. Manage forwarding with `filaxis forward add/list/remove` or the MCP `manage_layers` actions `forward_add`, `forward_list`, and `forward_remove`. Use the returned window or forward ID to inspect and close it. + --- ## MCP Practical Guidelines diff --git a/docs/skills/SKILL.md b/docs/skills/SKILL.md index 9a37076..fa139bd 100644 --- a/docs/skills/SKILL.md +++ b/docs/skills/SKILL.md @@ -1,7 +1,7 @@ --- name: filaxis-runtime metadata: - version: "0.2.11" + version: "0.2.12" description: | 使用 Filaxis(@syrkos/filaxis)执行跨层命令、批量巡检、管理后台任务、观察日志或操作目标层文件。 也用于排查 SSH 别名与跳板、解读 unknown 终态或写入保障。纯本机一次性命令和与 Filaxis 无关的任务可跳过。 @@ -72,7 +72,9 @@ filaxis exec --layer <名> --timeout 8000 -- "(printf 'PING - 宿主拦截 SSH 匿名管道时,在建层前设 `FILAXIS_SSH_STDIO_MODE=inherit`。它支持直连、单跳 `-J` 和可非交互重放的进入步骤。逐跳 PTY、交互进入、持久转发和持续观察窗需要可用的匿名管道。若首轮已发出且终态未知,先核实远端状态再决定是否重发。 - Windows 的 OpenSSH 子进程会继承现有配置,并由 Filaxis 补齐缺失的系统和账户变量,例如 `SystemRoot`、`windir`、`ProgramData` 和 `USERNAME`。成功补齐 `SystemRoot` 时,CLI 和 MCP 会在 stderr 告警一次,SDK 通过注入的 logger 记录。SSH 秒退且双流为空时,可检查启动器是否保留了系统环境。 -**Agent 形态升级路径**:CLI 每条命令独立进程(连接不复用)。高频操作或脚本编排时换 SDK / `createAgentToolkit` 常驻形态——连接/PTY 复用 + 结构化参数(`editFile` 直接传字符串免临时 JSON 文件 + `runBatch` 直接传数组免 plan 文件),步数与 Token 双降(盲测实证阶段二 non_cache 省 17.7%)。 +用 `filaxis daemon start` 启动本机守护进程后,CLI 与未指定 SSH 启动目标的 MCP 服务可共享层、转发和观察窗。用 `filaxis daemon status` 查看状态,`filaxis daemon stop` 停止,或给单次命令传 `--no-daemon`。持续观察用 `filaxis stream open/peek/close`,转发用 `filaxis forward add/list/remove`,或在 MCP `manage_layers` 中使用 `forward_add`、`forward_list`、`forward_remove`。按返回的窗口 ID 或转发 ID 查询和关闭。 + +SDK 的 `createAgentToolkit` 也可在宿主进程内复用连接和 PTY,并接受结构化参数。 ### SDK 最小配方(Bun / Node 编码接入) diff --git a/package.json b/package.json index 471e535..6bedcf6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@syrkos/filaxis", - "version": "0.2.11", + "version": "0.2.12", "description": "牵丝 Filaxis — 面向自动化与 Agent 的远程执行运行时 SDK(Syrkos · 漩核)。千里一线,执行有迹。", "type": "module", "license": "Apache-2.0", diff --git a/src/agent-toolkit.ts b/src/agent-toolkit.ts index 4d509df..95d68f8 100644 --- a/src/agent-toolkit.ts +++ b/src/agent-toolkit.ts @@ -18,8 +18,10 @@ import { transferLayerFile, validateFileTransferFields, type FileTransferTranspo import type { TransferResult } from "./file-transfer.js"; import { BATCH_STEP_KINDS, runBatch, type BatchLayerTarget, type BatchStepWithDeps } from "./batch.js"; import type { FileEntry, RuntimeDriver } from "./driver.js"; -import { SessionOwnership, type StopResult } from "./session-ownership.js"; +import type { SessionOwnership as _SessionOwnership, StopResult } from "./session-ownership.js"; +import { SessionOwnership } from "./session-ownership.js"; import { sshArgsFor } from "./ssh-helpers.js"; +import type { ForwardInfo, OpenForwardSpec } from "./ssh-forward.js"; export interface AgentToolDef { type: "function"; @@ -136,7 +138,10 @@ export type ManagePathResult = export type ManageLayersResult = | { action: "list"; text: string; layers: Array<{ name: string; driver: string; target?: string }> } | { action: "activate"; active_layer: string } - | { action: "remove"; removed: string }; + | { action: "remove"; removed: string } + | { action: "forward_add"; forward: ForwardInfo } + | { action: "forward_list"; forwards: ForwardInfo[] } + | { action: "forward_remove"; forward_id: string; status: "stopped" | "already_closed" | "unknown"; detail?: string }; export interface AgentToolHandlers { run_command(args: { command: string; timeout_ms?: number; layer?: string }): Promise<{ @@ -168,6 +173,19 @@ export interface AgentToolHandlers { manage_layers(args: { action: "list" }): Promise>; manage_layers(args: { action: "activate"; name: string }): Promise>; manage_layers(args: { action: "remove"; name: string; destroy?: boolean }): Promise>; + manage_layers(args: { + action: "forward_add"; + kind: "local" | "remote" | "dynamic" | "L" | "R" | "D"; + bind_port?: number; + bind_addr?: string; + target_host?: string; + target_port?: number; + forward_id?: string; + timeout_ms?: number; + layer?: string; + }): Promise>; + manage_layers(args: { action: "forward_list"; layer?: string }): Promise>; + manage_layers(args: { action: "forward_remove"; forward_id: string; layer?: string }): 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; @@ -210,6 +228,8 @@ export interface AgentToolkitOptions { /** 层描述符(缺省 local);也可直接传已连接的 driver */ descriptor?: { driver: string; target?: string; config?: Record }; driver?: RuntimeDriver; + /** 外部共享观察窗注册表(Daemon/Proxy 共享现场时注入;省略则每工具集自建自销) */ + windowRegistry?: StreamWindowRegistry; /** 就绪握手与 watcher 轮询的超时上限 */ readyTimeoutMs?: number; /** Retain confirmed results after releasing their driver reference. */ @@ -717,16 +737,30 @@ export const TOOL_DEFS: AgentToolDef[] = [ function: { name: "manage_layers", description: - "查询、切换或移除已注册命名层:action='list' 列出全部命名层及链路/状态/有效用户/默认标记;" + + "查询、切换、移除已注册命名层或管理动态端口转发:action='list' 列出全部命名层及链路/状态/有效用户/默认标记;" + "action='activate' 将指定 name 设为默认层(保留所有连接);" + - "action='remove' 移出指定层(缺省保留连接在指纹缓存以便零成本重建,传 destroy=true 才真销毁连接)。" + + "action='remove' 移出指定层(缺省保留连接在指纹缓存以便零成本重建,传 destroy=true 才真销毁连接);" + + "action='forward_add' 在目标或默认 SSH 层动态开启 -L/-R/-D 端口转发(bind_port 不填或传 0 自动分配空闲端口);" + + "action='forward_list' 查询动态端口转发列表;action='forward_remove' 关闭指定 forward_id。" + "新建 SSH 或进入内层环境请用 connect_layer。", parameters: { type: "object", properties: { - action: { type: "string", enum: ["list", "activate", "remove"], description: "层管理操作" }, + action: { + type: "string", + enum: ["list", "activate", "remove", "forward_add", "forward_list", "forward_remove"], + description: "层与动态转发管理操作", + }, name: { ...layerNameSchema, description: "目标层名(action=activate/remove 时必填)" }, destroy: { type: "boolean", description: "action=remove:是否真销毁底层连接(缺省 false=保留可复用)" }, + layer: { ...layerNameSchema, description: "action=forward_*:目标层名(缺省=默认层;forward_list 缺省=全部层)" }, + kind: { type: "string", enum: ["local", "remote", "dynamic", "L", "R", "D"], description: "action=forward_add:转发类型" }, + bind_addr: { type: "string", minLength: 1, description: "action=forward_add:绑定地址,缺省 127.0.0.1" }, + bind_port: { type: "integer", minimum: 0, maximum: 65535, description: "action=forward_add:绑定端口(省略或传 0=自动分配随机空闲端口)" }, + target_host: { type: "string", minLength: 1, description: "action=forward_add(local/remote 必填):目标主机" }, + target_port: { type: "integer", minimum: 1, maximum: 65535, description: "action=forward_add(local/remote 必填):目标端口" }, + forward_id: { type: "string", minLength: 1, description: "action=forward_add 可选自定义 ID;action=forward_remove 必填转发 ID" }, + timeout_ms: { type: "integer", minimum: 1, maximum: 2147483647, description: "action=forward_add:建链超时毫秒数,缺省 15000" }, }, oneOf: [ { @@ -754,6 +788,41 @@ export const TOOL_DEFS: AgentToolDef[] = [ }, required: ["action", "name"], }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "forward_add" }, + kind: { type: "string", enum: ["local", "remote", "dynamic", "L", "R", "D"] }, + bind_port: { type: "integer", minimum: 0, maximum: 65535 }, + bind_addr: { type: "string", minLength: 1 }, + target_host: { type: "string", minLength: 1 }, + target_port: { type: "integer", minimum: 1, maximum: 65535 }, + forward_id: { type: "string", minLength: 1 }, + timeout_ms: { type: "integer", minimum: 1, maximum: 2147483647 }, + layer: { ...layerNameSchema }, + }, + required: ["action", "kind"], + }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "forward_list" }, + layer: { ...layerNameSchema }, + }, + required: ["action"], + }, + { + type: "object", + additionalProperties: false, + properties: { + action: { type: "string", const: "forward_remove" }, + forward_id: { type: "string", minLength: 1 }, + layer: { ...layerNameSchema }, + }, + required: ["action", "forward_id"], + }, ], }, }, @@ -762,6 +831,10 @@ export const TOOL_DEFS: AgentToolDef[] = [ /** 生成 Agent 工具集(定义层 + 执行层;宿主桥接到任意 LLM 框架) */ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOptions = {}): AgentToolkit { + const unregisteredDriver = () => { + const driver = opts.driver; + return driver && !stack.hasForwardDriver(driver) ? driver : undefined; + }; // 初始层(Hydrogen R7 #4):descriptor 形态注册进命名表(manage_layers list 可见、 // connect_layer enter_cmd 无 from 时 activeLayer 有源)+ 失败不缓存(rejected Promise 永久 // 复用=不自愈;每次工具调用重连)。driver 直注形态不注册(外部生命周期) @@ -907,7 +980,7 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption validateFileTransferFields(operation, fields); return agentTransferResult(await transferLayerFile(await resolveDrv(layerName), operation, fields)); }; - let windowRegistry: StreamWindowRegistry | undefined; + let windowRegistry: StreamWindowRegistry | undefined = opts.windowRegistry; let observationDisposed = false; const requireWindow = (windowId: string) => { if (typeof windowId !== "string" || !windowId.trim()) throw new Error("window_id 需为非空字符串,请使用 observe_stream 返回的 window_id"); @@ -1135,7 +1208,7 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption tools: TOOL_DEFS, dispose() { observationDisposed = true; - windowRegistry?.dispose(); + if (!opts.windowRegistry) windowRegistry?.dispose(); }, get layer(): Promise { return layer(); }, // 惰性 getter(失败不缓存+注册命名表——Hydrogen R7 #4) handlers: { @@ -1441,7 +1514,78 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption 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"'); + if (action === "forward_add") { + const { + layer: layerName, kind, bind_addr, bind_port, target_host, target_port, forward_id, timeout_ms, + ...extra + } = rest; + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`manage_layers(forward_add) 未知参数:${unknown.join(", ")}`); + assertOptionalLayerName(layerName); + if (bind_addr !== undefined && typeof bind_addr !== "string") throw new Error("bind_addr 需为字符串"); + if (target_host !== undefined && typeof target_host !== "string") throw new Error("target_host 需为字符串"); + if (forward_id !== undefined && (typeof forward_id !== "string" || !forward_id.trim())) { + throw new Error("forward_id 需为非空字符串"); + } + const spec: OpenForwardSpec = { + kind: kind as OpenForwardSpec["kind"], + ...(bind_port !== undefined ? { bindPort: bind_port as number } : {}), + ...(typeof bind_addr === "string" ? { bindAddr: bind_addr } : {}), + ...(typeof target_host === "string" ? { targetHost: target_host } : {}), + ...(target_port !== undefined ? { targetPort: target_port as number } : {}), + ...(typeof forward_id === "string" ? { id: forward_id } : {}), + ...(timeout_ms !== undefined ? { timeoutMs: timeout_ms as number } : {}), + }; + const selectedLayer = layerName ?? stack.activeLayer?.name; + if (selectedLayer !== undefined) { + if (spec.id && unregisteredDriver()?.listForwards?.().some((f) => f.forwardId === spec.id)) { + throw new Error(`转发 ID '${spec.id}' 已存在于注入驱动`); + } + return { action: "forward_add" as const, forward: await stack.openForward(spec, selectedLayer) }; + } + const drv = await layer(); + if (stack.layers.get(INITIAL_LAYER_NAME)?.driver === drv) { + return { action: "forward_add" as const, forward: await stack.openForward(spec, INITIAL_LAYER_NAME) }; + } + if (typeof drv.openForward !== "function") { + throw new Error(`层 '${drv.descriptor.driver}' 不支持动态端口转发`); + } + if (spec.id && stack.listForwards().some((f) => f.forwardId === spec.id)) { + throw new Error(`转发 ID '${spec.id}' 已存在于已注册层`); + } + return { action: "forward_add" as const, forward: await drv.openForward(spec) }; + } + if (action === "forward_list") { + const { layer: layerName, ...extra } = rest; + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`manage_layers(forward_list) 未知参数:${unknown.join(", ")}`); + assertOptionalLayerName(layerName); + const registered = stack.listForwards(layerName); + const external = layerName === undefined ? unregisteredDriver()?.listForwards?.() ?? [] : []; + return { action: "forward_list" as const, forwards: [...registered, ...external] }; + } + if (action === "forward_remove") { + const { forward_id, layer: layerName, ...extra } = rest; + const unknown = Object.keys(extra); + if (unknown.length) throw new Error(`manage_layers(forward_remove) 未知参数:${unknown.join(", ")}`); + assertOptionalLayerName(layerName); + if (typeof forward_id !== "string" || !forward_id.trim()) throw new Error("forward_id 需为非空字符串"); + const external = layerName === undefined ? unregisteredDriver() : undefined; + const registered = external && stack.listForwards().some((f) => f.forwardId === forward_id); + if (registered && external?.listForwards?.().some((f) => f.forwardId === forward_id)) { + throw new Error(`转发 ID '${forward_id}' 同时存在于命名层和注入驱动,请明确指定命名层`); + } + const res = !registered && typeof external?.closeForward === "function" + ? await external.closeForward(forward_id) + : await stack.closeForward(forward_id, layerName); + return { + action: "forward_remove" as const, + forward_id: res.forwardId, + status: res.status, + ...(res.detail ? { detail: res.detail } : {}), + }; + } + throw new Error('manage_layers 的 action 须为 "list"、"activate"、"remove"、"forward_add"、"forward_list" 或 "forward_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("、")})`); diff --git a/src/daemon-client.ts b/src/daemon-client.ts new file mode 100644 index 0000000..ec6ceef --- /dev/null +++ b/src/daemon-client.ts @@ -0,0 +1,235 @@ +/** + * daemon-client.ts — Filaxis 常驻守护进程 HTTP 客户端与显式后台拉起器 + * + * 零第三方依赖:仅使用 node:http / node:child_process。 + * 重要不变量:probeDaemon 仅探测已存在的 Daemon,绝不隐式拉起后台进程; + * 仅 filaxis daemon start 显式调用 spawnDaemonBackground。 + */ +import { spawn } from "node:child_process"; +import * as http from "node:http"; +import { defaultDaemonDir, isPidAlive, readDaemonConnection } from "./daemon-files.js"; +import type { DaemonStatusInfo } from "./daemon-server.js"; + +export function urlRequestHost(url: URL): string { + const h = url.hostname; + return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h; +} + +export function urlRequestPort(url: URL): number { + if (url.port !== "") return Number(url.port); + return url.protocol === "https:" ? 443 : 80; +} + +export function parseAddrToUrl(addr: string): URL { + const trimmed = addr.trim(); + const normalized = /^https?:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`; + const url = new URL(normalized); + const authority = normalized.replace(/^https?:\/\//i, "").split(/[/?#]/, 1)[0] ?? ""; + const hasExplicitPort = /:\d+$/.test(authority); + if (!url.hostname || (!url.port && !hasExplicitPort)) { + throw new Error(`非法 Daemon 监听地址(需要 host:port 形态): ${addr}`); + } + return url; +} + +export interface DaemonClientOptions { + addr: string; + token: string; +} + +function tagTransportUnknown(err: unknown): unknown { + if (err && typeof err === "object" && "outcome" in err && (err as { outcome?: unknown }).outcome !== undefined) { + return err; + } + if (err && typeof err === "object") { + const code = (err as { code?: unknown }).code; + if (code === "ECONNREFUSED") return err; + const tagged = err as Error & { outcome?: unknown }; + if (tagged.outcome === undefined) tagged.outcome = "unknown"; + return tagged; + } + return Object.assign(new Error(String(err)), { outcome: "unknown" }); +} + +export class DaemonClient { + readonly addr: string; + private readonly token: string; + private readonly baseUrl: URL; + + constructor(opts: DaemonClientOptions) { + this.addr = opts.addr; + this.token = opts.token; + this.baseUrl = parseAddrToUrl(opts.addr); + } + + async health(timeoutMs = 1500): Promise { + try { + const res = await this.rawRequest("GET", "/health", undefined, timeoutMs, false); + return res.statusCode === 200 && Boolean((res.json as { ok?: unknown } | undefined)?.ok === true); + } catch { + return false; + } + } + + async status(timeoutMs = 3000): Promise { + return this.unwrap(await this.rawRequest("GET", "/status", undefined, timeoutMs, true)); + } + + async shutdown(timeoutMs = 5000): Promise<{ ok: true }> { + const response = await this.rawRequest("POST", "/shutdown", {}, timeoutMs, true); + return this.unwrap<{ ok: true }>(response); + } + + async rpc(method: string, params: Record = {}, timeoutMs?: number): Promise { + const response = await this.rawRequest("POST", "/rpc", { method, params }, timeoutMs, true); + return this.unwrap(response); + } + + private unwrap(res: { statusCode: number; raw: string; json?: unknown }): T { + if (res.statusCode === 401) { + throw new Error("Daemon 鉴权失败 (HTTP 401):Bearer token 不匹配或已失效"); + } + const parsed = res.json as Record | undefined; + if (parsed && parsed.ok === true) { + return parsed.result as T; + } + if (parsed && parsed.ok === false) { + const err = new Error(String(parsed.error ?? "Daemon RPC 调用失败")) as Error & { + outcome?: unknown; + sessionId?: unknown; + logBase?: unknown; + exitCode?: unknown; + terminalId?: unknown; + forwardId?: string; + code?: string | number; + statusCode?: number; + partialOutput?: string; + }; + if (res.statusCode >= 400) err.statusCode = res.statusCode; + if (typeof parsed.name === "string") err.name = parsed.name; + if (typeof parsed.code === "string" || typeof parsed.code === "number") err.code = parsed.code; + if (typeof parsed.partialOutput === "string") err.partialOutput = parsed.partialOutput; + if (parsed.outcome !== undefined) err.outcome = parsed.outcome; + if (parsed.sessionId !== undefined) err.sessionId = parsed.sessionId; + if (parsed.logBase !== undefined) err.logBase = parsed.logBase; + if (parsed.exitCode !== undefined) err.exitCode = parsed.exitCode; + if (parsed.terminalId !== undefined) err.terminalId = parsed.terminalId; + if (typeof parsed.forwardId === "string") err.forwardId = parsed.forwardId; + throw err; + } + throw new Error(`Daemon HTTP ${res.statusCode}: ${res.raw.slice(0, 200)}`); + } + + private rawRequest( + method: "GET" | "POST", + reqPath: string, + body: unknown, + timeoutMs: number | undefined, + withAuth: boolean, + ): Promise<{ statusCode: number; raw: string; json?: unknown }> { + return new Promise((resolve, reject) => { + const payload = body !== undefined ? Buffer.from(JSON.stringify(body), "utf-8") : undefined; + const headers: Record = {}; + if (withAuth) headers.Authorization = `Bearer ${this.token}`; + if (payload) { + headers["Content-Type"] = "application/json; charset=utf-8"; + headers["Content-Length"] = String(payload.byteLength); + } + + const req = http.request({ + protocol: this.baseUrl.protocol, + hostname: urlRequestHost(this.baseUrl), + port: urlRequestPort(this.baseUrl), + path: reqPath, + method, + headers, + agent: false, + }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (d: Buffer) => chunks.push(d)); + res.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf-8"); + let json: unknown; + try { json = JSON.parse(raw); } catch { /* non-json */ } + resolve({ statusCode: res.statusCode ?? 0, raw, json }); + }); + res.on("error", onTransportError); + }); + + if (timeoutMs !== undefined && timeoutMs > 0) { + req.setTimeout(timeoutMs, () => { + req.destroy(new Error(`Daemon 请求超时 (${timeoutMs}ms): ${method} ${reqPath}`)); + }); + } + req.on("error", onTransportError); + if (payload) req.write(payload); + req.end(); + + function onTransportError(err: Error): void { + reject(method === "POST" ? tagTransportUnknown(err) : err); + } + }); + } +} + +/** 仅探测已存在的活跃 Daemon;无文件、PID 已死或连通失败均返回 null(绝不自动拉起) */ +export async function probeDaemon(daemonDir = defaultDaemonDir(), timeoutMs = 800): Promise { + const conn = readDaemonConnection(daemonDir); + if (!conn) return null; + if (conn.lock?.pid && !isPidAlive(conn.lock.pid)) return null; + try { + const client = new DaemonClient({ addr: conn.addr, token: conn.token }); + await client.status(timeoutMs); + return client; + } catch { + return null; + } +} + +export interface SpawnDaemonOptions { + cliEntryPath: string; + daemonDir?: string; + addr?: string; + readyTimeoutMs?: number; +} + +/** 仅由 `filaxis daemon start` 显式调用:后台独立拉起 Daemon 并等待控制面就绪 */ +export async function spawnDaemonBackground(opts: SpawnDaemonOptions): Promise { + const daemonDir = opts.daemonDir ?? defaultDaemonDir(); + const readyTimeoutMs = opts.readyTimeoutMs ?? 10_000; + const existing = await probeDaemon(daemonDir); + if (existing) { + const { pid, addr } = await existing.status(); + throw new Error(`Filaxis Daemon 已在运行 (pid=${pid}, addr=${addr})`); + } + const argv = [opts.cliEntryPath, "daemon", "start", "--foreground", "--daemon-dir", daemonDir]; + if (opts.addr) argv.push("--addr", opts.addr); + + const child = spawn(process.execPath, argv, { + detached: true, + stdio: "ignore", + windowsHide: true, + env: { ...process.env, FILAXIS_DAEMON_DIR: daemonDir }, + }); + + let earlyExit: string | undefined; + child.once("error", (err) => { + earlyExit = `Daemon 进程启动失败: ${err.message}`; + }); + child.once("exit", (code, signal) => { + earlyExit = `Daemon 进程提前退出 (code=${code ?? "null"} signal=${signal ?? "none"})`; + }); + child.unref(); + + const deadline = Date.now() + readyTimeoutMs; + while (Date.now() < deadline) { + if (earlyExit) throw new Error(earlyExit); + const client = await probeDaemon(daemonDir, 500); + if (client) { + const status = await client.status(1500).catch(() => undefined); + if (status && status.pid === child.pid) return status; + } + await new Promise((r) => setTimeout(r, 80)); + } + throw new Error(`等待 Filaxis Daemon 就绪超时 (${readyTimeoutMs}ms)`); +} diff --git a/src/daemon-files.ts b/src/daemon-files.ts new file mode 100644 index 0000000..b384f21 --- /dev/null +++ b/src/daemon-files.ts @@ -0,0 +1,185 @@ +/** + * daemon-files.ts — Filaxis 常驻守护进程本地状态文件、PID 单实例锁与 Bearer Token 工具 + * + * 零第三方依赖,仅使用 node:crypto / node:fs / node:os / node:path(Bun + Node LTS、Windows + Linux 同构)。 + */ +import * as crypto from "node:crypto"; +import { + chmodSync, + mkdirSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +export interface DaemonPaths { + dir: string; + lockFile: string; + addrFile: string; + tokenFile: string; +} + +export interface DaemonLockRecord { + pid: number; + startedAt: number; + version: string; +} + +export interface DaemonConnectionInfo { + addr: string; + token: string; + lock?: DaemonLockRecord; +} + +export function defaultDaemonDir(): string { + return process.env.FILAXIS_DAEMON_DIR || join(homedir(), ".filaxis", "daemon"); +} + +export function assertLoopbackHost(host: string): string { + const normalized = host.trim().replace(/^\[|\]$/g, "").toLowerCase(); + if (normalized === "127.0.0.1" || normalized === "::1" || normalized === "localhost") { + return host.trim().replace(/^\[|\]$/g, ""); + } + throw new Error(`Filaxis Daemon 仅允许绑定本地回环地址(127.0.0.1 / ::1 / localhost),拒绝监听: ${host}`); +} + +export function daemonPaths(dir = defaultDaemonDir()): DaemonPaths { + return { + dir, + lockFile: join(dir, "daemon.lock"), + addrFile: join(dir, "daemon.addr"), + tokenFile: join(dir, "daemon.token"), + }; +} + +export function isPidAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === "ESRCH") return false; + if (code === "EPERM") return true; + return false; + } +} + +export function readDaemonLock(dir = defaultDaemonDir()): DaemonLockRecord | null { + const { lockFile } = daemonPaths(dir); + try { + const raw = readFileSync(lockFile, "utf-8"); + const parsed = JSON.parse(raw) as Partial; + if (!parsed || typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid)) return null; + return { + pid: parsed.pid, + startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0, + version: typeof parsed.version === "string" ? parsed.version : "", + }; + } catch { + return null; + } +} + +export function acquireDaemonLock(dir: string, version: string): DaemonLockRecord { + const { lockFile } = daemonPaths(dir); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const record: DaemonLockRecord = { + pid: process.pid, + startedAt: Date.now(), + version, + }; + const payload = JSON.stringify(record); + + const tryExclusiveCreate = (): boolean => { + try { + writeFileSync(lockFile, payload, { flag: "wx", mode: 0o600 }); + if (process.platform !== "win32") { + try { chmodSync(lockFile, 0o600); } catch { /* ignore */ } + } + return true; + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "EEXIST") return false; + throw err; + } + }; + + if (tryExclusiveCreate()) return record; + + const existing = readDaemonLock(dir); + if (existing && isPidAlive(existing.pid)) { + throw new Error(`Filaxis Daemon 已在运行 (pid=${existing.pid})`); + } + try { + unlinkSync(lockFile); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; + } + if (!tryExclusiveCreate()) { + const racer = readDaemonLock(dir); + throw new Error( + racer && isPidAlive(racer.pid) + ? `Filaxis Daemon 已在运行 (pid=${racer.pid})` + : `Filaxis Daemon 启动锁并发冲突: ${lockFile}`, + ); + } + return record; +} + +export function writePrivateFileAtomic(filePath: string, content: string): void { + mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 }); + const tmp = `${filePath}.${crypto.randomBytes(4).toString("hex")}.tmp`; + try { + writeFileSync(tmp, content, { flag: "wx", mode: 0o600 }); + if (process.platform !== "win32") { + try { chmodSync(tmp, 0o600); } catch { /* ignore */ } + } + renameSync(tmp, filePath); + if (process.platform !== "win32") { + try { chmodSync(filePath, 0o600); } catch { /* ignore */ } + } + } finally { + try { unlinkSync(tmp); } catch { /* rename 后临时文件已消失 */ } + } +} + +export function generateDaemonToken(): string { + return crypto.randomBytes(32).toString("hex"); +} + +export function verifyBearerToken(authHeader: string | undefined, expectedToken: string): boolean { + if (!authHeader || !expectedToken) return false; + const match = authHeader.trim().match(/^Bearer\s+(\S+)$/i); + if (!match) return false; + const providedBuf = Buffer.from(match[1]!, "utf-8"); + const expectedBuf = Buffer.from(expectedToken, "utf-8"); + if (providedBuf.byteLength !== expectedBuf.byteLength) return false; + return crypto.timingSafeEqual(providedBuf, expectedBuf); +} + +export function readDaemonConnection(dir = defaultDaemonDir()): DaemonConnectionInfo | null { + const { addrFile, tokenFile } = daemonPaths(dir); + try { + const addr = readFileSync(addrFile, "utf-8").trim(); + const token = readFileSync(tokenFile, "utf-8").trim(); + if (!addr || !token) return null; + const lock = readDaemonLock(dir) ?? undefined; + return { addr, token, ...(lock ? { lock } : {}) }; + } catch { + return null; + } +} + +export function cleanupDaemonFiles(dir = defaultDaemonDir(), expectedPid?: number): void { + const { lockFile, addrFile, tokenFile } = daemonPaths(dir); + if (expectedPid !== undefined) { + const current = readDaemonLock(dir); + if (current && current.pid !== expectedPid) return; + } + for (const file of [addrFile, tokenFile, lockFile]) { + try { unlinkSync(file); } catch { /* ignore */ } + } +} diff --git a/src/daemon-server.ts b/src/daemon-server.ts new file mode 100644 index 0000000..9017076 --- /dev/null +++ b/src/daemon-server.ts @@ -0,0 +1,1053 @@ +/** + * daemon-server.ts — Filaxis 显式常驻守护进程 HTTP 控制面与共享工作现场 + * + * 设计要点(REQ-0005): + * - 零第三方依赖:仅基于 node:http / node:crypto / node:path 等标准库; + * - 仅监听本地回环(缺省 127.0.0.1),除 GET /health 外全端点强制 Bearer Token 常量时间鉴权(401); + * - 惰性层解析:SSH 非交互 exec/stream/forward 不强迫预建 PTY link(保持 OPNsense 与多跳诚实拒绝语义), + * 仅在 --pty 调用时按需初始化 PTY link; + * - 内部持有统一 RuntimeStack 与 StreamWindowRegistry,供 CLI 与后续 MCP Proxy 共享现场。 + */ +import * as crypto from "node:crypto"; +import * as http from "node:http"; +import * as path from "node:path"; +import { RuntimeStack, type LayerHandle } from "./runtime-stack.js"; +import type { RuntimeDescriptor, RuntimeDriver } from "./driver.js"; +import { LocalRuntimeDriver } from "./local-driver.js"; +import { SshPtyDriver } from "./ssh-pty-driver.js"; +import { StreamWindowRegistry, type StreamFrame } from "./stream-window.js"; +import { editFile } from "./file-edit.js"; +import { transferLayerFile, type FileTransferTransport } from "./layer-file-transfer.js"; +import { discoverLayer } from "./layer-discovery.js"; +import { runBatch, type BatchPlan } from "./batch.js"; +import type { OpenForwardSpec, ForwardInfo } from "./ssh-forward.js"; +import { createAgentToolkit, type AgentToolkit } from "./agent-toolkit.js"; +import { McpProtocolHandler } from "./mcp-server.js"; +import { noopLogger, type FilaxisLogger } from "./logger.js"; +import { + acquireDaemonLock, + assertLoopbackHost, + cleanupDaemonFiles, + daemonPaths, + defaultDaemonDir, + generateDaemonToken, + verifyBearerToken, + writePrivateFileAtomic, +} from "./daemon-files.js"; + +export interface CliTargetSpec { + layer?: string; + descriptor?: RuntimeDescriptor; + cwd?: string; +} + +export interface DaemonLayerSummary { + name: string; + driver: string; + target?: string; + active: boolean; +} + +export interface DaemonStreamSummary { + window_id: string; + name?: string; + layer: string; + command: string; + oldest_seq: number; + newest_seq: number; + stale: boolean; + closed: boolean; +} + +export interface DaemonStatusInfo { + pid: number; + startedAt: number; + uptimeMs: number; + version: string; + addr: string; + layers: DaemonLayerSummary[]; + forwards: ForwardInfo[]; + streams: DaemonStreamSummary[]; +} + +export interface DaemonServerOptions { + daemonDir?: string; + host?: string; + port?: number; + version?: string; + logger?: FilaxisLogger; + stack?: RuntimeStack; + windowRegistry?: StreamWindowRegistry; + toolkit?: AgentToolkit; + sseKeepaliveMs?: number; + writeFiles?: boolean; +} + +const MAX_RPC_BODY_BYTES = 16 * 1024 * 1024; +const DEFAULT_SSE_KEEPALIVE_MS = 15_000; + +interface McpSseClient { + id: string; + res: http.ServerResponse; + sendEvent: (event: string, data: string) => void; + close: () => void; +} + +class HttpStatusError extends Error { + constructor(readonly statusCode: number, message: string) { + super(message); + } +} + +export class DaemonServer { + readonly stack: RuntimeStack; + readonly windowRegistry: StreamWindowRegistry; + readonly toolkit: AgentToolkit; + readonly token: string; + readonly daemonDir: string; + readonly version: string; + + private readonly host: string; + private readonly port: number; + private readonly log: FilaxisLogger; + private readonly writeFiles: boolean; + private readonly sseKeepaliveMs: number; + private readonly mcpHandler: McpProtocolHandler; + private readonly mcpSseClients = new Map(); + private readonly startedAt = Date.now(); + private readonly ptyInitialized = new WeakSet(); + private readonly ptyInitInflight = new WeakMap>(); + private readonly resolvingLayers = new Map }>(); + private readonly ephemeralLayers = new Map(); + private readonly streamMeta = new Map(); + private implicitLocal?: LayerHandle; + + private server?: http.Server; + private listenAddr?: string; + private starting?: Promise; + private stopping?: Promise; + private stopped = false; + private stopWaiters: Array<() => void> = []; + + constructor(opts: DaemonServerOptions = {}) { + this.daemonDir = opts.daemonDir ?? defaultDaemonDir(); + this.host = assertLoopbackHost(opts.host ?? "127.0.0.1"); + this.port = opts.port ?? 0; + this.version = opts.version ?? "0.0.0"; + this.log = opts.logger ?? noopLogger; + this.stack = opts.stack ?? new RuntimeStack({ logger: this.log }); + this.windowRegistry = opts.windowRegistry ?? new StreamWindowRegistry({ logger: this.log }); + this.toolkit = opts.toolkit ?? createAgentToolkit(this.stack, { windowRegistry: this.windowRegistry }); + this.mcpHandler = new McpProtocolHandler({ toolkit: this.toolkit, serverVersion: this.version }); + this.sseKeepaliveMs = opts.sseKeepaliveMs ?? DEFAULT_SSE_KEEPALIVE_MS; + this.writeFiles = opts.writeFiles !== false; + this.token = generateDaemonToken(); + } + + get addr(): string { + if (!this.listenAddr) throw new Error("DaemonServer 尚未启动"); + return this.listenAddr; + } + + async start(): Promise { + if (this.stopping) throw new Error("DaemonServer 已停止或正在停止,请创建新实例"); + if (this.listenAddr) return this.listenAddr; + this.starting ??= this.startListening().finally(() => { this.starting = undefined; }); + return this.starting; + } + + private async startListening(): Promise { + if (this.writeFiles) { + acquireDaemonLock(this.daemonDir, this.version); + } + + const srv = http.createServer((req, res) => { + void this.handleHttp(req, res); + }); + this.server = srv; + + try { + await new Promise((resolve, reject) => { + const onError = (err: Error) => { + srv.removeListener("listening", onListening); + reject(err); + }; + const onListening = () => { + srv.removeListener("error", onError); + resolve(); + }; + srv.once("error", onError); + srv.once("listening", onListening); + srv.listen(this.port, this.host); + }); + + const address = srv.address(); + if (!address || typeof address === "string") { + throw new Error("无法获取 Daemon HTTP 监听端口"); + } + const hostPart = address.address.includes(":") ? `[${address.address}]` : address.address; + this.listenAddr = `http://${hostPart}:${address.port}`; + + if (this.writeFiles) { + const paths = daemonPaths(this.daemonDir); + writePrivateFileAtomic(paths.tokenFile, this.token); + writePrivateFileAtomic(paths.addrFile, this.listenAddr); + } + return this.listenAddr; + } catch (err) { + try { srv.close(); } catch { /* ignore */ } + this.server = undefined; + this.listenAddr = undefined; + if (this.writeFiles) { + cleanupDaemonFiles(this.daemonDir, process.pid); + } + throw err; + } + } + + private pruneStreamMeta(): void { + for (const id of [...this.streamMeta.keys()]) { + if (!this.windowRegistry.get(id)) { + this.streamMeta.delete(id); + } + } + } + + waitForStop(): Promise { + if (this.stopped) return Promise.resolve(); + return new Promise((resolve) => { + this.stopWaiters.push(resolve); + }); + } + + status(): DaemonStatusInfo { + this.pruneStreamMeta(); + const activeName = this.stack.activeLayer?.name; + const layers: DaemonLayerSummary[] = [...this.stack.layers.values()].map((h) => ({ + name: h.name, + driver: h.descriptor.driver, + ...(h.descriptor.target !== undefined ? { target: h.descriptor.target } : {}), + active: h.name === activeName, + })); + const streams: DaemonStreamSummary[] = []; + for (const w of this.windowRegistry.list()) { + const win = this.windowRegistry.get(w.name); + const meta = this.streamMeta.get(w.name); + streams.push({ + window_id: w.name, + ...(meta?.displayName ? { name: meta.displayName } : {}), + layer: meta?.layer ?? w.layer, + command: w.command, + oldest_seq: win?.oldestSeq ?? 0, + newest_seq: win?.newestSeq ?? 0, + stale: w.stale, + closed: win?.closed ?? false, + }); + } + return { + pid: process.pid, + startedAt: this.startedAt, + uptimeMs: Math.max(0, Date.now() - this.startedAt), + version: this.version, + addr: this.listenAddr ?? "", + layers, + forwards: this.stack.listForwards(), + streams, + }; + } + + async stop(): Promise { + if (this.stopping) return this.stopping; + this.stopping = (async () => { + await this.starting?.catch(() => undefined); + for (const client of [...this.mcpSseClients.values()]) { + client.close(); + } + this.mcpSseClients.clear(); + const srv = this.server; + this.server = undefined; + if (srv) { + await new Promise((resolve) => { + srv.close(() => resolve()); + (srv as { closeAllConnections?: () => void }).closeAllConnections?.(); + }); + } + const activeWindows = this.windowRegistry.list().map((w) => w.name); + await Promise.all(activeWindows.map((id) => this.windowRegistry.stopConfirmed(id).catch(() => undefined))); + this.toolkit.dispose?.(); + this.windowRegistry.dispose(); + this.streamMeta.clear(); + await this.stack.destroyDetachedForwardDrivers(); + for (const name of [...this.stack.layers.keys()]) { + await this.stack.removeLayer(name, { destroy: true }).catch(() => undefined); + } + this.ephemeralLayers.clear(); + await this.implicitLocal?.driver.destroy().catch(() => undefined); + this.implicitLocal = undefined; + this.listenAddr = undefined; + if (this.writeFiles) { + cleanupDaemonFiles(this.daemonDir, process.pid); + } + this.stopped = true; + for (const resolve of this.stopWaiters) resolve(); + this.stopWaiters = []; + })(); + return this.stopping; + } + + private async handleHttp(req: http.IncomingMessage, res: http.ServerResponse): Promise { + const parsedUrl = new URL(req.url ?? "/", "http://127.0.0.1"); + const reqPath = parsedUrl.pathname; + if (req.method === "GET" && reqPath === "/health") { + this.sendJson(res, 200, { ok: true }); + return; + } + + if (!verifyBearerToken(req.headers.authorization, this.token)) { + this.sendJson(res, 401, { ok: false, error: "Unauthorized" }); + return; + } + + if (req.method === "GET" && reqPath === "/status") { + this.sendJson(res, 200, { ok: true, result: this.status() }); + return; + } + + if (req.method === "GET" && reqPath === "/mcp/sse") { + this.handleMcpSse(req, res); + return; + } + + if (req.method === "POST" && reqPath === "/mcp/message") { + await this.handleMcpMessage(req, res, parsedUrl.searchParams.get("sessionId")); + return; + } + + if (req.method === "POST" && reqPath === "/shutdown") { + this.sendJson(res, 200, { ok: true, result: { ok: true } }); + setTimeout(() => { void this.stop(); }, 20).unref?.(); + return; + } + + if (req.method === "POST" && reqPath === "/rpc") { + let payload: { method?: unknown; params?: unknown }; + try { + payload = await readJsonBody(req); + } catch (err) { + const status = err instanceof HttpStatusError ? err.statusCode : 400; + this.sendJson(res, status, { ok: false, error: err instanceof Error ? err.message : String(err) }); + return; + } + const method = typeof payload.method === "string" ? payload.method : ""; + const params = (payload.params && typeof payload.params === "object" && !Array.isArray(payload.params)) + ? payload.params as Record + : {}; + if (!method) { + this.sendJson(res, 400, { ok: false, error: "RPC 请求缺少 method 字段" }); + return; + } + try { + const result = await this.dispatchRpc(method, params); + this.sendJson(res, 200, { ok: true, result }); + } catch (err) { + this.sendJson(res, 200, serializeRpcError(err)); + } + return; + } + + this.sendJson(res, 404, { ok: false, error: `Not Found: ${req.method ?? "UNKNOWN"} ${reqPath}` }); + } + + private handleMcpSse(req: http.IncomingMessage, res: http.ServerResponse): void { + const sessionId = crypto.randomUUID(); + res.writeHead(200, { + "Content-Type": "text/event-stream; charset=utf-8", + "Cache-Control": "no-cache, no-transform", + "Connection": "keep-alive", + }); + res.flushHeaders?.(); + + let closed = false; + const sendEvent = (event: string, data: string) => { + if (closed || res.writableEnded || res.destroyed) return; + const lines = data.split(/\r?\n/).map((line) => `data: ${line}`).join("\n"); + res.write(`event: ${event}\n${lines}\n\n`); + }; + + const keepalive = this.sseKeepaliveMs > 0 + ? setInterval(() => { + if (!closed && !res.writableEnded && !res.destroyed) { + res.write(": keepalive\n\n"); + } + }, this.sseKeepaliveMs) + : null; + keepalive?.unref?.(); + + const cleanup = () => { + if (closed) return; + closed = true; + if (keepalive) clearInterval(keepalive); + this.mcpSseClients.delete(sessionId); + }; + + const client: McpSseClient = { + id: sessionId, + res, + sendEvent, + close: () => { + cleanup(); + if (!res.writableEnded) { + try { res.end(); } catch { /* ignore */ } + } + if (!res.destroyed) { + try { res.destroy(); } catch { /* ignore */ } + } + }, + }; + + this.mcpSseClients.set(sessionId, client); + req.on("close", cleanup); + res.on("close", cleanup); + res.on("error", cleanup); + + sendEvent("endpoint", `/mcp/message?sessionId=${encodeURIComponent(sessionId)}`); + } + + private async handleMcpMessage( + req: http.IncomingMessage, + res: http.ServerResponse, + sessionId: string | null, + ): Promise { + let body: unknown; + try { + body = await readRawJsonBody(req); + } catch (err) { + const status = err instanceof HttpStatusError ? err.statusCode : 400; + this.sendJson(res, status, { ok: false, error: err instanceof Error ? err.message : String(err) }); + return; + } + + if (sessionId !== null) { + const client = this.mcpSseClients.get(sessionId); + if (!client) { + this.sendJson(res, 404, { ok: false, error: `SSE session not found: ${sessionId}` }); + return; + } + this.sendJson(res, 202, { ok: true }); + void this.mcpHandler.handleMessage(body).then((resp) => { + if (resp) { + client.sendEvent("message", JSON.stringify(resp)); + } + }); + return; + } + + const resp = await this.mcpHandler.handleMessage(body); + if (resp) { + this.sendJson(res, 200, resp); + } else { + this.sendJson(res, 202, { ok: true }); + } + } + + private sendJson(res: http.ServerResponse, status: number, body: unknown): void { + if (res.writableEnded) return; + const json = JSON.stringify(body); + res.writeHead(status, { + "Content-Type": "application/json; charset=utf-8", + "Content-Length": Buffer.byteLength(json, "utf-8"), + }); + res.end(json); + } + + private instantiateDriver(descriptor: RuntimeDescriptor): RuntimeDriver | null { + if (descriptor.driver === "local") { + const cfg = (descriptor.config ?? {}) as Record; + const drv = new LocalRuntimeDriver({ + ...(descriptor.cwd ? { cwd: descriptor.cwd } : {}), + ...(typeof cfg.shell === "string" ? { shell: cfg.shell } : {}), + logger: this.log, + }); + drv.descriptor = { ...descriptor }; + return drv; + } + if (descriptor.driver === "ssh") { + return new SshPtyDriver(descriptor, { logger: this.log }); + } + return null; + } + + private hasActiveStreamsForLayer(layerName: string): boolean { + this.pruneStreamMeta(); + for (const w of this.windowRegistry.list()) { + const win = this.windowRegistry.get(w.name); + if (!win || win.closed) continue; + const meta = this.streamMeta.get(w.name); + if (meta?.implicitLocal) continue; + const ownerLayer = meta?.layer ?? w.layer; + if (ownerLayer === layerName) return true; + } + return false; + } + + private resolveClientLocalPath(filePath: string, clientCwd?: string): string { + if (clientCwd && filePath && !filePath.includes("\0") && !path.isAbsolute(filePath)) { + return path.resolve(clientCwd, filePath); + } + return filePath; + } + + private resolveBatchPlanLocalPaths(plan: BatchPlan, clientCwd?: string): BatchPlan { + if (!clientCwd || !plan || typeof plan !== "object" || Array.isArray(plan) || !Array.isArray(plan.steps)) { + return plan; + } + return { + ...plan, + steps: plan.steps.map((step) => { + if (step && typeof step === "object" && (step.kind === "put" || step.kind === "get") + && typeof step.localPath === "string") { + return { ...step, localPath: this.resolveClientLocalPath(step.localPath, clientCwd) }; + } + return step; + }), + }; + } + + private async registerLazyLayer(name: string, descriptor: RuntimeDescriptor, opts: { activate?: boolean } = {}): Promise { + const direct = this.instantiateDriver(descriptor); + if (direct) { + const res = await this.stack.addLayer(name, direct, { activate: opts.activate }); + return res.handle; + } + const res = await this.stack.addLayer(name, descriptor, { activate: opts.activate }); + return res.handle; + } + + private async ensureLayerOnce( + dedupKey: string, + descriptorKey: string, + create: () => Promise, + ): Promise { + const inflight = this.resolvingLayers.get(dedupKey); + if (inflight) { + if (inflight.key !== descriptorKey) { + throw new Error( + `层 '${dedupKey.replace(/^named:/, "")}' 正在并发注册或更新为另一份配置,拒绝合并不同描述符的并发请求`, + ); + } + return inflight.promise; + } + const task = create().finally(() => { + if (this.resolvingLayers.get(dedupKey)?.promise === task) { + this.resolvingLayers.delete(dedupKey); + } + }); + this.resolvingLayers.set(dedupKey, { key: descriptorKey, promise: task }); + return task; + } + + private getImplicitLocalHandle(): LayerHandle { + if (!this.implicitLocal) { + const drv = new LocalRuntimeDriver({ logger: this.log }); + this.implicitLocal = { name: "local", descriptor: drv.descriptor, driver: drv }; + } + return this.implicitLocal; + } + + private getEphemeralLayer(key: string): LayerHandle | undefined { + const name = this.ephemeralLayers.get(key); + const handle = name === undefined ? undefined : this.stack.layers.get(name); + if (handle && RuntimeStack.driverKey(handle.descriptor) === key) return handle; + this.ephemeralLayers.delete(key); + return undefined; + } + + private async resolveTarget(target?: CliTargetSpec, opts: { needPty?: boolean } = {}): Promise { + let handle: LayerHandle; + + if (!target || (!target.layer && (!target.descriptor || (target.descriptor.driver === "local" && !target.descriptor.cwd && !target.descriptor.config)))) { + handle = this.getImplicitLocalHandle(); + } else if (target.layer) { + if (target.descriptor) { + const layerName = target.layer; + const descriptor = target.descriptor; + const desiredKey = RuntimeStack.driverKey(descriptor); + const fastExisting = this.stack.layers.has(layerName) ? this.stack.layer(layerName) : undefined; + if (fastExisting && RuntimeStack.driverKey(fastExisting.descriptor) === desiredKey) { + handle = fastExisting; + } else { + handle = await this.ensureLayerOnce(`named:${layerName}`, desiredKey, async () => { + if (this.stack.layers.has(layerName)) { + const existing = this.stack.layer(layerName); + if (RuntimeStack.driverKey(existing.descriptor) === desiredKey) { + return existing; + } + const hasActiveForwards = this.stack.hasLiveForwards(layerName); + const hasActiveStreams = this.hasActiveStreamsForLayer(layerName); + if (hasActiveForwards || hasActiveStreams) { + throw new Error( + `层 '${layerName}' 已在 Daemon 注册且配置与新描述符不一致,当前仍有${hasActiveForwards ? "正在建立或未确认关闭的动态端口转发" : "活跃观察窗"},拒绝静默覆盖——请先清理该层资源或移除旧层后重试`, + ); + } + const wasActive = this.stack.activeLayer?.name === layerName; + await this.stack.removeLayer(layerName, { destroy: false }); + return this.registerLazyLayer(layerName, descriptor, { activate: wasActive }); + } + return this.registerLazyLayer(layerName, descriptor, { activate: false }); + }); + } + } else if (this.stack.layers.has(target.layer)) { + handle = this.stack.layer(target.layer); + } else { + throw new Error(`层 '${target.layer}' 未在 Daemon 注册(可先 filaxis layer save ${target.layer} --host ...)`); + } + } else { + const descriptor = target.descriptor!; + const key = RuntimeStack.driverKey(descriptor); + const existing = this.getEphemeralLayer(key); + if (existing) { + handle = existing; + } else { + handle = await this.ensureLayerOnce(`ephemeral:${key}`, key, async () => { + const again = this.getEphemeralLayer(key); + if (again) return again; + const shortHash = crypto.createHash("sha256").update(key).digest("hex").slice(0, 6); + const base = (descriptor.target ?? descriptor.driver).replace(/[^A-Za-z0-9._@-]/g, "_").slice(0, 24) || "layer"; + let candidate = `${base}#${shortHash}`; + if (this.stack.layers.has(candidate)) { + candidate = `${candidate}-${crypto.randomBytes(2).toString("hex")}`; + } + const created = await this.registerLazyLayer(candidate, descriptor, { activate: false }); + this.ephemeralLayers.set(key, created.name); + return created; + }); + } + } + + if (opts.needPty && handle.driver instanceof SshPtyDriver && !this.ptyInitialized.has(handle.driver)) { + const sshDrv = handle.driver; + let initTask = this.ptyInitInflight.get(sshDrv); + if (!initTask) { + initTask = sshDrv.init().then(() => { + this.ptyInitialized.add(sshDrv); + }).finally(() => { + if (this.ptyInitInflight.get(sshDrv) === initTask) { + this.ptyInitInflight.delete(sshDrv); + } + }); + this.ptyInitInflight.set(sshDrv, initTask); + } + await initTask; + } + return handle; + } + + private resolveLayerFilePath(drv: RuntimeDriver, filePath: string, clientCwd?: string): string { + if (drv.descriptor.driver === "local" && clientCwd && !path.isAbsolute(filePath)) { + return path.resolve(clientCwd, filePath); + } + return filePath; + } + + private async dispatchRpc(method: string, params: Record): Promise { + switch (method) { + case "status": + return this.status(); + + case "exec": { + const target = params.target as CliTargetSpec | undefined; + const command = String(params.command ?? ""); + const timeoutMs = typeof params.timeoutMs === "number" ? params.timeoutMs : 120_000; + const pty = params.pty === true; + const h = await this.resolveTarget(target, { needPty: pty }); + const isLocal = h.descriptor.driver === "local"; + const r = await h.driver.exec(command, { + timeoutMs, + channel: pty ? "pty" : undefined, + ...(isLocal && target?.cwd ? { cwd: target.cwd } : {}), + }); + return { + stdout: r.stdout, + stderr: r.stderr, + exitCode: r.exitCode, + ...(r.effectiveUser !== undefined ? { effectiveUser: r.effectiveUser } : {}), + }; + } + + case "cat": { + const target = params.target as CliTargetSpec | undefined; + const rawPath = String(params.path ?? ""); + if (!rawPath) throw new Error("cat 缺少 path 参数"); + const h = await this.resolveTarget(target); + const resolved = this.resolveLayerFilePath(h.driver, rawPath, target?.cwd); + return { content: await h.driver.fs.readFile(resolved) }; + } + + case "edit": { + const target = params.target as CliTargetSpec | undefined; + const rawPath = String(params.path ?? ""); + const old = params.old; + const newStr = params.new; + if (!rawPath || typeof old !== "string" || typeof newStr !== "string") { + throw new Error("edit 需要 path、old 与 new 字符串参数"); + } + const h = await this.resolveTarget(target); + const resolved = this.resolveLayerFilePath(h.driver, rawPath, target?.cwd); + return editFile(h.driver, resolved, old, newStr, { + all: params.all === true, + writeMode: params.writeMode as "auto" | "inplace" | undefined, + }); + } + + case "transfer": { + const target = params.target as CliTargetSpec | undefined; + const direction = params.direction === "get" ? "get" : params.direction === "put" ? "put" : undefined; + if (!direction) throw new Error("transfer 需要 direction=put|get"); + const h = await this.resolveTarget(target); + const clientCwd = typeof params.clientCwd === "string" && params.clientCwd ? params.clientCwd : target?.cwd; + const remotePath = this.resolveLayerFilePath(h.driver, String(params.remotePath ?? ""), target?.cwd); + return transferLayerFile(h.driver, direction, { + localPath: this.resolveClientLocalPath(String(params.localPath ?? ""), clientCwd), + remotePath, + transport: params.transport as FileTransferTransport | undefined, + timeoutMs: typeof params.timeoutMs === "number" ? params.timeoutMs : undefined, + writeMode: params.writeMode as "auto" | "inplace" | undefined, + }); + } + + case "observe": { + const target = params.target as CliTargetSpec | undefined; + const command = String(params.command ?? ""); + const streamArg = typeof params.stream === "string" ? params.stream : undefined; + const duration = typeof params.duration === "number" ? params.duration : 8000; + const h = await this.resolveTarget(target); + const isLocal = h.descriptor.driver === "local"; + const session = await h.driver.execSession(command, { + name: "cli-observe", + ...(isLocal && target?.cwd ? { cwd: target.cwd } : {}), + }); + await new Promise((r) => setTimeout(r, duration)); + const streams: Array<"stdout" | "stderr"> = streamArg === "stderr" + ? ["stderr"] + : streamArg === "stdout" + ? ["stdout"] + : ["stdout", "stderr"]; + const lines: Array<{ stream: string; text: string }> = []; + try { + for (const st of streams) { + const log = await h.driver.readSessionLog(session.sessionId, { lines: 500, stream: st }); + for (const text of (log ?? "").split("\n")) { + if (text !== "") lines.push({ stream: st, text }); + } + } + } catch (e) { + await h.driver.stopSession(session.sessionId).catch(() => undefined); + const err = new Error( + `观察输出读取失败(${(e as Error).message})——已尝试停止。` + + `会话线索 session_id=${session.sessionId} log_base=${session.logBase}(任务可能仍在运行,核实后再重试)`, + ) as Error & { outcome: string; sessionId: string; logBase: string }; + err.outcome = "unknown"; + err.sessionId = session.sessionId; + err.logBase = session.logBase; + throw err; + } + const filtered = (streamArg && streamArg !== "both") + ? lines.filter((l) => l.stream === streamArg) + : lines; + const stopR = await h.driver.stopSession(session.sessionId).catch(() => ({ status: "unknown" as const })); + let verifyStatus: string | undefined; + let verifyError: string | undefined; + if (stopR.status === "unknown") { + verifyStatus = "unknown"; + try { + verifyStatus = (await h.driver.verifySession(session.sessionId)).status; + } catch (e) { + verifyError = (e as Error).message; + } + } + return { + lines: filtered, + stopStatus: stopR.status, + ...(verifyStatus !== undefined ? { verifyStatus } : {}), + ...(verifyError !== undefined ? { verifyError } : {}), + sessionId: session.sessionId, + logBase: session.logBase, + }; + } + + case "probe": { + const target = params.target as CliTargetSpec | undefined; + const h = await this.resolveTarget(target); + const r = await discoverLayer(h.driver, { skipStage2: false }); + return { key: r.key, spec: r.spec, note: r.probeNote }; + } + + case "batch": { + const target = params.target as CliTargetSpec | undefined; + const plan = params.plan as BatchPlan; + const savedLayers = (params.savedLayers ?? {}) as Record; + const clientCwd = typeof params.clientCwd === "string" && params.clientCwd ? params.clientCwd : target?.cwd; + const resolvedPlan = this.resolveBatchPlanLocalPaths(plan, clientCwd); + let scopedLocal: LocalRuntimeDriver | undefined; + try { + return await runBatch(async (layerName) => { + if (layerName === undefined) { + if ((!target || (!target.layer && (!target.descriptor || target.descriptor.driver === "local"))) && target?.cwd) { + scopedLocal ??= new LocalRuntimeDriver({ cwd: target.cwd, logger: this.log }); + return scopedLocal; + } + return (await this.resolveTarget(target)).driver; + } + if (Object.hasOwn(savedLayers, layerName)) { + return (await this.resolveTarget({ layer: layerName, descriptor: savedLayers[layerName]! })).driver; + } + if (this.stack.layers.has(layerName)) { + return this.stack.layer(layerName).driver; + } + throw new Error(`层 '${layerName}' 未保存(filaxis layer list 查看;filaxis layer save ${layerName} --host ... 创建)`); + }, resolvedPlan); + } finally { + await scopedLocal?.destroy().catch(() => undefined); + } + } + + case "forward.add": { + const target = params.target as CliTargetSpec | undefined; + const spec = params.spec as OpenForwardSpec; + if (!spec || typeof spec !== "object") throw new Error("forward.add 需要 spec 参数"); + const h = await this.resolveTarget(target); + if (typeof h.driver.openForward !== "function") { + throw new Error(`层 '${h.name}' (${h.descriptor.driver}) 不支持动态端口转发`); + } + if (this.stack.layers.get(h.name) !== h) { + throw new Error(`层 '${h.name}' 已变更,请重新指定目标层`); + } + return this.stack.openForward(spec, h.name); + } + + case "forward.list": { + const layer = typeof params.layer === "string" ? params.layer : undefined; + return { forwards: this.stack.listForwards(layer) }; + } + + case "forward.remove": { + const forwardId = typeof params.forwardId === "string" ? params.forwardId : ""; + if (!forwardId) throw new Error("forward.remove 需要 forwardId"); + const layer = typeof params.layer === "string" ? params.layer : undefined; + return this.stack.closeForward(forwardId, layer); + } + + case "stream.open": { + const target = params.target as CliTargetSpec | undefined; + const command = typeof params.command === "string" ? params.command : ""; + if (!command.trim()) throw new Error("stream.open 需要非空 command"); + const stream = params.stream as "stdout" | "stderr" | "both" | undefined; + if (stream !== undefined && stream !== "stdout" && stream !== "stderr" && stream !== "both") { + throw new Error(`stream 无效: ${String(stream)}(支持 stdout|stderr|both)`); + } + const displayName = typeof params.name === "string" && params.name.trim() ? params.name.trim() : undefined; + const limit = typeof params.limit === "number" ? params.limit : 20; + const waitMs = typeof params.waitMs === "number" ? params.waitMs : 0; + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) throw new Error("limit 须在 1–200 之间"); + if (!Number.isSafeInteger(waitMs) || waitMs < 0 || waitMs > 30_000) throw new Error("waitMs 须在 0–30000 之间"); + + this.pruneStreamMeta(); + const h = await this.resolveTarget(target); + const openDriver = (h.descriptor.driver === "local" && target?.cwd) + ? new LocalRuntimeDriver({ cwd: target.cwd, logger: this.log }) + : h.driver; + if (typeof openDriver.openStreamWindow !== "function") { + throw new Error(`层 '${h.name}' (${h.descriptor.driver}) 不支持持续观察窗`); + } + const id = crypto.randomUUID(); + const win = await openDriver.openStreamWindow(this.windowRegistry, { + name: id, + command, + stream, + retainSequence: false, + }); + this.streamMeta.set(id, { displayName, layer: h.name, implicitLocal: h === this.implicitLocal }); + + const deadline = Date.now() + waitMs; + let res = win.peekSince(0, limit); + while (!res.frames.length && !res.gap && !res.stale && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, Math.max(0, Math.min(50, deadline - Date.now())))); + const cur = this.windowRegistry.get(id); + if (!cur || cur.closed) throw new Error(`观察窗 '${id}' 在等待首屏期间已关闭`); + res = cur.peekSince(0, limit); + } + return formatDaemonStreamResult(id, res, h.name, displayName); + } + + case "stream.peek": { + const windowId = typeof params.windowId === "string" ? params.windowId : ""; + if (!windowId.trim()) throw new Error("stream.peek 需要非空 windowId"); + const afterSeq = params.afterSeq as number | undefined; + const beforeSeq = params.beforeSeq as number | undefined; + const limit = typeof params.limit === "number" ? params.limit : 20; + const waitMs = typeof params.waitMs === "number" ? params.waitMs : 0; + const streamFilter = params.stream as "stdout" | "stderr" | "both" | undefined; + if (afterSeq !== undefined && beforeSeq !== undefined) { + throw new Error("afterSeq 与 beforeSeq 互斥"); + } + for (const v of [afterSeq, beforeSeq]) { + if (v !== undefined && (!Number.isSafeInteger(v) || v < 0)) { + throw new Error("afterSeq / beforeSeq 须为非负整数"); + } + } + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) throw new Error("limit 须在 1–200 之间"); + if (!Number.isSafeInteger(waitMs) || waitMs < 0 || waitMs > 30_000) throw new Error("waitMs 须在 0–30000 之间"); + if (waitMs > 0 && afterSeq === undefined) throw new Error("waitMs 仅可用于 --after 增量续读"); + if (streamFilter !== undefined && streamFilter !== "stdout" && streamFilter !== "stderr" && streamFilter !== "both") { + throw new Error(`stream 无效: ${String(streamFilter)}`); + } + const selectedStream = streamFilter === "both" ? undefined : streamFilter; + + const requireActiveWin = () => { + const w = this.windowRegistry.get(windowId); + if (!w || w.closed) throw new Error(`观察窗 '${windowId}' 不存在或已关闭`); + return w; + }; + const readOnce = () => { + const w = requireActiveWin(); + return afterSeq !== undefined + ? w.peekSince(afterSeq, limit, undefined, selectedStream) + : beforeSeq !== undefined + ? w.peekBefore(beforeSeq, limit, selectedStream) + : w.peekLast(limit, selectedStream); + }; + + const deadline = Date.now() + waitMs; + let res = readOnce(); + while (afterSeq !== undefined && !res.frames.length && !res.gap && !res.stale && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, Math.max(0, Math.min(50, deadline - Date.now())))); + res = readOnce(); + } + + const meta = this.streamMeta.get(windowId); + return formatDaemonStreamResult(windowId, res, meta?.layer, meta?.displayName); + } + + case "stream.close": { + const windowId = typeof params.windowId === "string" ? params.windowId : ""; + if (!windowId.trim()) throw new Error("stream.close 需要非空 windowId"); + const w = this.windowRegistry.get(windowId); + if (!w || w.closed) throw new Error(`观察窗 '${windowId}' 不存在或已关闭`); + await this.windowRegistry.stopConfirmed(windowId); + this.streamMeta.delete(windowId); + return { window_id: windowId, closed: true }; + } + + case "stream.list": + return { streams: this.status().streams }; + + case "layer.list": + return { + layers: this.status().layers, + text: this.stack.layerText(), + }; + + case "layer.remove": { + const name = typeof params.name === "string" ? params.name : ""; + if (!name) throw new Error("layer.remove 需要 name"); + await this.stack.removeLayer(name, { destroy: params.destroy === true }); + for (const [key, mappedName] of [...this.ephemeralLayers.entries()]) { + if (mappedName === name) this.ephemeralLayers.delete(key); + } + return { removed: name }; + } + + default: + throw new Error(`未知 Daemon RPC 方法: ${method}`); + } + } +} + +function formatDaemonStreamResult( + windowId: string, + res: { + oldestSeq: number; + newestSeq: number; + stale: boolean; + frames: StreamFrame[]; + exitCode?: number | null; + error?: string; + lastDeliveredSeq?: number; + gap?: boolean; + }, + layer?: string, + name?: string, +) { + return { + window_id: windowId, + ...(name ? { name } : {}), + ...(layer ? { layer } : {}), + oldest_seq: res.oldestSeq, + newest_seq: res.newestSeq, + stale: res.stale, + frames: res.frames, + ...(res.lastDeliveredSeq !== undefined ? { last_delivered_seq: res.lastDeliveredSeq } : {}), + ...(res.gap ? { gap: true } : {}), + ...(res.exitCode !== undefined ? { exit_code: res.exitCode } : {}), + ...(res.error !== undefined ? { error: res.error } : {}), + }; +} + +function serializeRpcError(err: unknown): Record { + const obj = (err !== null && typeof err === "object" ? err : {}) as { + outcome?: unknown; + sessionId?: unknown; + logBase?: unknown; + exitCode?: unknown; + terminalId?: unknown; + forwardId?: unknown; + code?: unknown; + partialOutput?: unknown; + }; + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...(err instanceof Error ? { name: err.name } : {}), + ...(typeof obj.code === "string" || typeof obj.code === "number" ? { code: obj.code } : {}), + ...(typeof obj.partialOutput === "string" ? { partialOutput: obj.partialOutput } : {}), + ...(obj.outcome !== undefined ? { outcome: obj.outcome } : {}), + ...(obj.sessionId !== undefined ? { sessionId: obj.sessionId } : {}), + ...(obj.logBase !== undefined ? { logBase: obj.logBase } : {}), + ...(obj.exitCode !== undefined ? { exitCode: obj.exitCode } : {}), + ...(obj.terminalId !== undefined ? { terminalId: obj.terminalId } : {}), + ...(typeof obj.forwardId === "string" ? { forwardId: obj.forwardId } : {}), + }; +} + +async function readRawJsonBody(req: http.IncomingMessage): Promise { + const chunks: Buffer[] = []; + let total = 0; + for await (const chunk of req) { + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + total += buf.byteLength; + if (total > MAX_RPC_BODY_BYTES) { + // Finish reading without retaining the body so the client receives HTTP 413. + chunks.length = 0; + continue; + } + chunks.push(buf); + } + if (total > MAX_RPC_BODY_BYTES) { + throw new HttpStatusError(413, `请求体超过限制 (${MAX_RPC_BODY_BYTES} 字节)`); + } + const raw = Buffer.concat(chunks).toString("utf-8").trim(); + if (!raw) throw new HttpStatusError(400, "空 JSON 请求体"); + try { + return JSON.parse(raw); + } catch (e) { + throw new HttpStatusError(400, `JSON 解析失败: ${(e as Error).message}`); + } +} + +async function readJsonBody(req: http.IncomingMessage): Promise<{ method?: unknown; params?: unknown }> { + const parsed = await readRawJsonBody(req); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new HttpStatusError(400, "RPC 请求体必须是 JSON 对象"); + } + return parsed as { method?: unknown; params?: unknown }; +} diff --git a/src/driver.ts b/src/driver.ts index e5a8ff9..d2537db 100644 --- a/src/driver.ts +++ b/src/driver.ts @@ -119,6 +119,7 @@ import type { } from "./session-types.js"; import type { ObservationWindowOptions, StreamWindow, StreamWindowRegistry } from "./stream-window.js"; +import type { OpenForwardSpec, ForwardInfo, CloseForwardResult } from "./ssh-forward.js"; export interface RuntimeDriver { /** The non-interactive exec channel supports maxOutputBytes without collecting full output. */ @@ -158,6 +159,11 @@ export interface RuntimeDriver { // 强隔离文件系统 fs: FileSystemDriver; + // 动态端口转发(-L / -R / -D,REQ-0005) + openForward?(spec: OpenForwardSpec): Promise; + closeForward?(forwardId: string): Promise; + listForwards?(): ForwardInfo[]; + // 初始化与销毁 init(): Promise; destroy(): Promise; diff --git a/src/index.ts b/src/index.ts index 9ff1ca3..8a7b877 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,13 @@ export * from "./factory.js"; export * from "./runtime-stack.js"; export * from "./dialect.js"; export * from "./ssh-helpers.js"; +export * from "./ssh-forward.js"; +export * from "./daemon-files.js"; +export * from "./daemon-server.js"; +export * from "./daemon-client.js"; +export { McpServer, McpProtocolHandler } from "./mcp-server.js"; +export type { McpServerOptions, McpProtocolHandlerOptions } from "./mcp-server.js"; +export * from "./mcp-proxy.js"; export * from "./remote-session-manager.js"; export * from "./ssh-pty-driver.js"; export * from "./tmux-driver.js"; diff --git a/src/local-driver.ts b/src/local-driver.ts index 1df76c3..7a4ffef 100644 --- a/src/local-driver.ts +++ b/src/local-driver.ts @@ -174,6 +174,7 @@ export class LocalRuntimeDriver implements RuntimeDriver { env, cwd, stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, }); // stdin 管道错误必须监听(GPT Astra 九轮 P1):shell 提前退出(流式解析 // 撞语法错即死)时继续写管道抛 write EOF——无 error 监听器则 uncaught diff --git a/src/local-session-manager.ts b/src/local-session-manager.ts index fb80ed9..7de00bb 100644 --- a/src/local-session-manager.ts +++ b/src/local-session-manager.ts @@ -82,7 +82,7 @@ export interface LocalSessionManagerOptions { /** 执行 shell(缺省 "bash";Windows 需 Git Bash/WSL 提供 bash——平台差异显式声明,不静默切换) */ shell?: string; /** spawn 注入(缺省 node:child_process.spawn)——消费方沙箱包装/测试 mock 注入点 */ - spawnImpl?: (cmd: string, argv: string[], opts: { env: NodeJS.ProcessEnv; cwd?: string; stdio: unknown[] }) => ChildProcess; + spawnImpl?: (cmd: string, argv: string[], opts: { env: NodeJS.ProcessEnv; cwd?: string; stdio: unknown[]; windowsHide?: boolean }) => ChildProcess; /** 可注入日志(缺省 noop——SDK 不替调用方往 stdout 喷日志) */ logger?: FilaxisLogger; } @@ -153,6 +153,7 @@ export class LocalSessionManager { proc = entry.supervisor?.child ?? this.spawnImpl!(this.shell, ["-c", command], { env, cwd, stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, ...(process.platform !== "win32" ? { detached: true } : {}), }); } catch (e) { @@ -449,7 +450,7 @@ export class LocalSessionManager { // error 监听兜底(二十五期模式散点):fire-and-forget spawn 无监听, // ENOENT 时异步 error = uncaughtException 崩宿主(taskkill 系统自带, // 防御性一行) - spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore" }).on("error", () => undefined); + spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore", windowsHide: true }).on("error", () => undefined); } else { try { process.kill(-pid, "SIGTERM"); } catch { try { entry.proc.kill("SIGTERM"); } catch { /* gone */ } } } @@ -458,7 +459,7 @@ export class LocalSessionManager { // 高并发下 PID 快速复用时误杀同号新进程 if (!entry.running) return; if (process.platform === "win32") { - spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore" }).on("error", () => undefined); + spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore", windowsHide: true }).on("error", () => undefined); } else { try { process.kill(-pid, "SIGKILL"); } catch { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } } } diff --git a/src/mcp-proxy.ts b/src/mcp-proxy.ts new file mode 100644 index 0000000..bc0df14 --- /dev/null +++ b/src/mcp-proxy.ts @@ -0,0 +1,490 @@ +/** + * mcp-proxy.ts — filaxis-mcp stdio ↔ Daemon HTTP/SSE 保活代理 + * + * 设计要点(REQ-0005 Phase 3): + * - 零第三方依赖:仅使用 node:http / node:readline / node:string_decoder; + * - 单 stdin 读循环:重连时绝不重复创建 readline 监听器; + * - Watchdog + 退避重连 + Token 轮换重读:每次建连前重读 daemon.addr 与 daemon.token; + * - 语义不变量(AC-07 零自动重放):一旦 SSE 断连,在途已 POST 的请求立即回传 + * JSON-RPC error (outcome="unknown") 并清空 inFlight,绝不自动重放非幂等调用。 + */ +import * as http from "node:http"; +import * as readline from "node:readline"; +import { StringDecoder } from "node:string_decoder"; +import { defaultDaemonDir, readDaemonConnection } from "./daemon-files.js"; +import { parseAddrToUrl, urlRequestHost, urlRequestPort } from "./daemon-client.js"; +import { noopLogger, type FilaxisLogger } from "./logger.js"; + +export interface McpStdioProxyOptions { + daemonDir?: string; + stdin?: NodeJS.ReadableStream; + stdout?: NodeJS.WritableStream; + logger?: FilaxisLogger; + watchdogIdleMs?: number; + initialReconnectDelayMs?: number; + maxReconnectDelayMs?: number; + maxInFlight?: number; +} + +interface PendingMessage { + raw: string; + id?: number | string; + method?: string; +} + +interface ActiveSseSession { + addr: string; + token: string; + baseUrl: URL; + postPath?: string; + activeNotifPosts: number; + abort: (err?: Error) => void; +} + +interface InFlightRequest { + id: number | string; + method: string; +} + +const DEFAULT_WATCHDOG_IDLE_MS = 45_000; +const DEFAULT_INITIAL_RECONNECT_MS = 200; +const DEFAULT_MAX_RECONNECT_MS = 5_000; +const DEFAULT_MAX_IN_FLIGHT = 128; +const MAX_PENDING_QUEUE = 1024; +const POST_TIMEOUT_MS = 10_000; + +function idKey(id: number | string): string { + return `${typeof id}:${String(id)}`; +} + +export class McpStdioProxy { + private readonly daemonDir: string; + private readonly input: NodeJS.ReadableStream; + private readonly out: NodeJS.WritableStream; + private readonly log: FilaxisLogger; + private readonly watchdogIdleMs: number; + private readonly initialReconnectDelayMs: number; + private readonly maxReconnectDelayMs: number; + private readonly maxInFlight: number; + + private rl?: readline.Interface; + private started = false; + private closed = false; + private activeSession: ActiveSseSession | null = null; + private sleepTimer: ReturnType | null = null; + private wakeSleep: (() => void) | null = null; + private reconnectDelayMs: number; + + private readonly pendingQueue: PendingMessage[] = []; + private readonly inFlight = new Map(); + + constructor(opts: McpStdioProxyOptions = {}) { + this.daemonDir = opts.daemonDir ?? defaultDaemonDir(); + this.input = opts.stdin ?? process.stdin; + this.out = opts.stdout ?? process.stdout; + this.log = opts.logger ?? noopLogger; + this.watchdogIdleMs = opts.watchdogIdleMs ?? DEFAULT_WATCHDOG_IDLE_MS; + this.initialReconnectDelayMs = opts.initialReconnectDelayMs ?? DEFAULT_INITIAL_RECONNECT_MS; + this.maxReconnectDelayMs = opts.maxReconnectDelayMs ?? DEFAULT_MAX_RECONNECT_MS; + this.maxInFlight = opts.maxInFlight ?? DEFAULT_MAX_IN_FLIGHT; + this.reconnectDelayMs = this.initialReconnectDelayMs; + } + + start(): void { + if (this.started) return; + this.started = true; + this.rl = readline.createInterface({ input: this.input, terminal: false }); + this.rl.on("line", (line) => this.onLine(line)); + this.rl.on("close", () => { + this.log.info("[mcp-proxy] stdin 关闭——仅退出代理,Daemon 现场继续保留"); + this.close(); + }); + void this.connectLoop(); + } + + close(): void { + if (this.closed) return; + this.closed = true; + if (this.sleepTimer) { + clearTimeout(this.sleepTimer); + this.sleepTimer = null; + } + this.wakeSleep?.(); + this.wakeSleep = null; + this.activeSession?.abort(); + this.activeSession = null; + this.rl?.close(); + } + + private writeStdout(msg: Record | string): void { + if (this.closed) return; + const line = typeof msg === "string" ? msg : JSON.stringify(msg); + this.out.write(line.endsWith("\n") ? line : `${line}\n`); + } + + private onLine(line: string): void { + const trimmed = line.trim(); + if (!trimmed) return; + let parsed: unknown; + try { + parsed = JSON.parse(trimmed); + } catch { + const idMatch = trimmed.match(/"id"\s*:\s*(\d+|"[^"]*")/); + let id: number | string | null = null; + if (idMatch) { + try { id = JSON.parse(idMatch[1]!) as number | string; } catch { id = null; } + } + this.writeStdout({ + jsonrpc: "2.0", + id, + error: { code: -32700, message: "Parse error: invalid JSON" }, + }); + return; + } + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + this.writeStdout({ + jsonrpc: "2.0", + id: null, + error: { code: -32600, message: `Invalid Request: expected object, got ${parsed === null ? "null" : typeof parsed}` }, + }); + return; + } + const obj = parsed as Record; + const rawId = obj.id; + const hasId = (typeof rawId === "number" || typeof rawId === "string"); + if (this.pendingQueue.length >= MAX_PENDING_QUEUE) { + if (hasId) { + this.writeStdout({ + jsonrpc: "2.0", + id: rawId, + error: { + code: -32000, + message: `MCP 代理待发队列已满 (${MAX_PENDING_QUEUE}),拒绝接收新请求(outcome=unknown)`, + data: { outcome: "unknown", reason: "queue_overflow" }, + }, + }); + } + return; + } + this.pendingQueue.push({ + raw: trimmed, + ...(hasId ? { id: rawId } : {}), + ...(typeof obj.method === "string" ? { method: obj.method } : {}), + }); + this.pumpQueue(); + } + + private failOneInFlight(entry: InFlightRequest | undefined, message: string, data: { outcome?: "unknown"; statusCode?: number }): void { + if (!entry) return; + const key = idKey(entry.id); + if (this.inFlight.get(key) !== entry) return; + this.inFlight.delete(key); + this.writeStdout({ + jsonrpc: "2.0", + id: entry.id, + error: { + code: -32000, + message, + data: { method: entry.method, ...data }, + }, + }); + } + + private failInFlight(reason: string): void { + if (this.inFlight.size === 0) return; + const entries = [...this.inFlight.values()]; + this.inFlight.clear(); + for (const entry of entries) { + this.writeStdout({ + jsonrpc: "2.0", + id: entry.id, + error: { + code: -32000, + message: `${reason}——远端执行状态未知(outcome=unknown),内核不会自动重放该请求,请核实远端状态后由调用方决定是否重试`, + data: { outcome: "unknown", method: entry.method }, + }, + }); + } + } + + private pumpQueue(): void { + const session = this.activeSession; + if (this.closed || !session || !session.postPath) return; + + while (this.pendingQueue.length > 0 && (this.inFlight.size + session.activeNotifPosts) < this.maxInFlight) { + const item = this.pendingQueue.shift()!; + this.dispatchPost(session, item); + } + } + + private dispatchPost(session: ActiveSseSession, item: PendingMessage): void { + const entry = item.id === undefined ? undefined : { id: item.id, method: item.method ?? "unknown" }; + if (entry) { + this.inFlight.set(idKey(entry.id), entry); + } else { + session.activeNotifPosts++; + } + + let postDone = false; + const releaseNotif = () => { + if (postDone) return; + postDone = true; + if (!entry) { + session.activeNotifPosts--; + } + }; + + const payload = Buffer.from(item.raw, "utf-8"); + const req = http.request({ + protocol: session.baseUrl.protocol, + hostname: urlRequestHost(session.baseUrl), + port: urlRequestPort(session.baseUrl), + path: session.postPath, + method: "POST", + headers: { + "Content-Type": "application/json; charset=utf-8", + "Content-Length": String(payload.byteLength), + Authorization: `Bearer ${session.token}`, + }, + agent: false, + }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (d: Buffer) => chunks.push(d)); + res.on("end", () => { + releaseNotif(); + const code = res.statusCode ?? 0; + if (code < 200 || code >= 300) { + const detail = Buffer.concat(chunks).toString("utf-8").slice(0, 200); + const rejectedBeforeExecution = code === 413; + this.failOneInFlight( + entry, + `Daemon POST 失败 (HTTP ${code}): ${detail || "request rejected"}${rejectedBeforeExecution ? "" : "(outcome=unknown,不自动重放)"}`, + rejectedBeforeExecution ? { statusCode: code } : { statusCode: code, outcome: "unknown" }, + ); + if (code === 401 || code === 404) { + if (this.activeSession === session) session.abort(); + } + } + this.pumpQueue(); + }); + res.on("error", (err) => { + releaseNotif(); + this.failOneInFlight( + entry, + `Daemon POST 响应读取失败(${err.message})——远端执行状态未知(outcome=unknown),不自动重放`, + { outcome: "unknown" }, + ); + if (this.activeSession === session) session.abort(); + this.pumpQueue(); + }); + }); + + req.setTimeout(POST_TIMEOUT_MS, () => { + req.destroy(new Error(`Daemon POST 超时 (${POST_TIMEOUT_MS}ms)`)); + }); + + req.on("error", (err) => { + releaseNotif(); + this.failOneInFlight( + entry, + `Daemon POST 连接失败(${err.message})——远端执行状态未知(outcome=unknown),不自动重放`, + { outcome: "unknown" }, + ); + if (this.activeSession === session) session.abort(); + this.pumpQueue(); + }); + + req.write(payload); + req.end(); + } + + private async connectLoop(): Promise { + while (!this.closed) { + const conn = readDaemonConnection(this.daemonDir); + if (!conn) { + await this.waitReconnect(); + continue; + } + try { + await this.runSseSession(conn.addr, conn.token); + } catch (err) { + if (!this.closed) { + this.log.warn(`[mcp-proxy] SSE 会话断开: ${err instanceof Error ? err.message : String(err)}`); + } + } + if (!this.closed) { + this.failInFlight("Daemon SSE 连接中断"); + await this.waitReconnect(); + } + } + } + + private waitReconnect(): Promise { + if (this.closed) return Promise.resolve(); + const delay = this.reconnectDelayMs; + this.reconnectDelayMs = Math.min(this.maxReconnectDelayMs, Math.max(50, delay * 2)); + return new Promise((resolve) => { + this.wakeSleep = resolve; + this.sleepTimer = setTimeout(() => { + this.sleepTimer = null; + this.wakeSleep = null; + resolve(); + }, delay); + this.sleepTimer.unref?.(); + }); + } + + private runSseSession(addr: string, token: string): Promise { + const baseUrl = parseAddrToUrl(addr); + return new Promise((resolve, reject) => { + let settled = false; + let watchdog: ReturnType | null = null; + let reqRef: http.ClientRequest | null = null; + let resRef: http.IncomingMessage | null = null; + + const session: ActiveSseSession = { + addr, + token, + baseUrl, + activeNotifPosts: 0, + abort: (err) => { + finish(err ?? new Error("SSE 连接已关闭")); + if (resRef && !resRef.destroyed) { + try { resRef.destroy(); } catch { /* ignore */ } + } + if (reqRef && !reqRef.destroyed) { + try { reqRef.destroy(); } catch { /* ignore */ } + } + }, + }; + + const finish = (err?: Error) => { + if (settled) return; + settled = true; + if (watchdog) { clearInterval(watchdog); watchdog = null; } + if (this.activeSession === session) this.activeSession = null; + if (err) reject(err); + else resolve(); + }; + + const req = http.request({ + protocol: baseUrl.protocol, + hostname: urlRequestHost(baseUrl), + port: urlRequestPort(baseUrl), + path: "/mcp/sse", + method: "GET", + headers: { + Accept: "text/event-stream", + "Cache-Control": "no-cache", + Authorization: `Bearer ${token}`, + }, + agent: false, + }, (res) => { + resRef = res; + if (res.statusCode !== 200) { + res.resume(); + finish(new Error(`SSE 握手失败: HTTP ${res.statusCode ?? 0}`)); + return; + } + + this.activeSession = session; + let lastSeenAt = Date.now(); + const checkInterval = Math.max(15, Math.min(1000, Math.floor(this.watchdogIdleMs / 3))); + watchdog = setInterval(() => { + if (Date.now() - lastSeenAt > this.watchdogIdleMs) { + const idleErr = new Error(`SSE 数据饥饿超时 (${this.watchdogIdleMs}ms)`); + session.abort(idleErr); + } + }, checkInterval); + watchdog.unref?.(); + + const dec = new StringDecoder("utf-8"); + let buf = ""; + let evName = ""; + const dataLines: string[] = []; + + const flushEvent = () => { + if (settled) return; + if (!dataLines.length) { + evName = ""; + return; + } + const event = evName; + const payload = dataLines.join("\n"); + evName = ""; + dataLines.length = 0; + + if (event === "endpoint") { + session.postPath = payload.trim(); + this.reconnectDelayMs = this.initialReconnectDelayMs; + this.pumpQueue(); + return; + } + if (event === "message" || event === "") { + try { + const msg = JSON.parse(payload) as { id?: unknown }; + if (msg && (typeof msg.id === "number" || typeof msg.id === "string")) { + this.inFlight.delete(idKey(msg.id)); + } + } catch { /* 原样透传 */ } + this.writeStdout(payload); + this.pumpQueue(); + } + }; + + const processLines = (final: boolean) => { + for (;;) { + const nl = buf.indexOf("\n"); + if (nl === -1) break; + const line = buf.slice(0, nl).replace(/\r$/, ""); + buf = buf.slice(nl + 1); + if (line === "") { + flushEvent(); + } else if (line.startsWith(":")) { + // SSE comment/keepalive + } else if (line.startsWith("event:")) { + evName = line.slice("event:".length).trim(); + } else if (line.startsWith("data:")) { + let val = line.slice("data:".length); + if (val.startsWith(" ")) val = val.slice(1); + dataLines.push(val); + } + } + if (final && buf.length > 0) { + const line = buf.replace(/\r$/, ""); + buf = ""; + if (line.startsWith("data:")) { + let val = line.slice("data:".length); + if (val.startsWith(" ")) val = val.slice(1); + dataLines.push(val); + } + flushEvent(); + } + }; + + res.on("data", (chunk: Buffer) => { + lastSeenAt = Date.now(); + buf += dec.write(chunk); + processLines(false); + }); + res.on("end", () => { + buf += dec.end(); + processLines(true); + finish(new Error("SSE 流意外结束")); + }); + res.on("close", () => { + finish(new Error("SSE 连接已关闭")); + }); + res.on("error", (err) => { + finish(err instanceof Error ? err : new Error(String(err))); + }); + }); + + reqRef = req; + req.on("error", (err) => { + finish(err instanceof Error ? err : new Error(String(err))); + }); + req.end(); + }); + } +} diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 4e11685..d8c21bd 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -68,49 +68,38 @@ export interface McpServerOptions { stdin?: NodeJS.ReadableStream; } -export class McpServer { +export interface McpProtocolHandlerOptions { + toolkit: AgentToolkit; + serverName?: string; + serverVersion?: string; +} + +function makeReply(id: number | string | null, result: Record): Record { + return { jsonrpc: JSONRPC_VERSION, id, result }; +} + +function makeReplyErr(id: number | string | null, code: number, message: string, data?: unknown): Record { + return { jsonrpc: JSONRPC_VERSION, id, error: { code, message, ...(data !== undefined ? { data } : {}) } }; +} + +/** 传输无关的 MCP JSON-RPC 2.0 协议分发器(供 stdio McpServer 与 DaemonServer HTTP/SSE 共用) */ +export class McpProtocolHandler { private readonly tk: AgentToolkit; private readonly name: string; private readonly version: string; - private readonly log: FilaxisLogger; - private readonly out: NodeJS.WritableStream; - private initialized = false; - private rl?: readline.Interface; - constructor(opts: McpServerOptions) { + constructor(opts: McpProtocolHandlerOptions) { this.tk = opts.toolkit; this.name = opts.serverName ?? "@syrkos/filaxis"; this.version = opts.serverVersion ?? version; - this.log = opts.logger ?? noopLogger; - this.out = opts.stdout ?? process.stdout; - const input = opts.stdin ?? process.stdin; - this.rl = readline.createInterface({ input, terminal: false }); - this.rl.on("line", (line) => this.onLine(line)); - this.rl.on("close", () => { - // 连接断开=客户端退出:进程内 toolkit 状态(会话句柄)交还内核 TTL 回收 - this.tk.dispose?.(); - this.log.info("[mcp] stdin 关闭——server 退出"); - }); } - private write(msg: Record): void { - this.out.write(JSON.stringify(msg) + "\n"); - } - - private reply(id: number | string | null, result: Record): void { - this.write({ jsonrpc: JSONRPC_VERSION, id, result }); - } - - private replyErr(id: number | string | null, code: number, message: string, data?: unknown): void { - this.write({ jsonrpc: JSONRPC_VERSION, id, error: { code, message, ...(data !== undefined ? { data } : {}) } }); - } - - private onLine(line: string): void { + async handleRawLine(line: string): Promise | null> { const trimmed = line.trim(); - if (trimmed === "") return; - let msg: JsonRpcRequest | JsonRpcNotification; + if (trimmed === "") return null; + let msg: unknown; try { - msg = JSON.parse(trimmed) as JsonRpcRequest; + msg = JSON.parse(trimmed); } catch { // 解析失败:若可提取 id 则按规范回 Parse error(-32700) const idMatch = trimmed.match(/"id"\s*:\s*(\d+|"[^"]*")/); @@ -120,30 +109,34 @@ export class McpServer { if (idMatch) { try { id = JSON.parse(idMatch[1]!) as number | string; } catch { id = null; } } - this.replyErr(id, -32700, "Parse error: invalid JSON"); - return; + return makeReplyErr(id, -32700, "Parse error: invalid JSON"); } + return this.handleMessage(msg); + } + + async handleMessage(msg: unknown): Promise | null> { if (msg === null || typeof msg !== "object") { // JSON null/标量防御(Sol 五十四期 P1-4):null 是合法 JSON——解析成功 // 后 `"id" in null` 抛 TypeError 逃出监听器崩进程 - this.replyErr(null, -32600, `Invalid Request: expected object, got ${msg === null ? "null" : typeof msg}`); - return; + return makeReplyErr(null, -32600, `Invalid Request: expected object, got ${msg === null ? "null" : typeof msg}`); + } + const obj = msg as Record; + if (!("id" in obj) || obj.id === undefined || obj.id === null) return null; // 通知(notifications/initialized 等)——无响应 + const req = obj as unknown as JsonRpcRequest; + const id = (req.id ?? 0) as number | string; + try { + return await this.dispatch(req, id); + } catch (e) { + return makeReplyErr(id, -32603, `Internal error: ${e instanceof Error ? e.message : String(e)}`); } - if (!("id" in msg) || msg.id === undefined || msg.id === null) return; // 通知(notifications/initialized 等)——无响应 - const req = msg as JsonRpcRequest; // id 已非空(上方守卫) - this.dispatch(req).catch((e) => { - this.replyErr(req.id!, -32603, `Internal error: ${e instanceof Error ? e.message : String(e)}`); - }); } - private async dispatch(req: JsonRpcRequest): Promise { + private async dispatch(req: JsonRpcRequest, id: number | string): Promise> { const { method } = req; - const id = (req.id ?? 0) as number | string; // 守卫后非空(通知已 return) const params = req.params ?? {}; switch (method) { case "initialize": - this.initialized = true; - this.reply(id, { + return makeReply(id, { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: { tools: { listChanged: false } }, serverInfo: { name: this.name, version: this.version }, @@ -152,25 +145,23 @@ export class McpServer { // 在任何 schema 读取之前必达,是唯一可靠的发现面) instructions: [ "【先看这行】多文件读取/多命令巡检/同命令发往多层/定位排查 → 优先 run_batch(一次调用并行打包,支持传 layer 数组自动扇出,不要逐个工具循环);读工具 schema 时同轮并发读取(逐个读每步一趟 LLM);", - "建立或进入命名层(单台/批量 SSH 或 docker/kubectl 内层)→ connect_layer;查询、切换默认层或移除层 → manage_layers。", + "建立或进入命名层(单台/批量 SSH 或 docker/kubectl 内层)→ connect_layer;查询、切换默认层、移除层或管理动态端口转发(-L/-R/-D) → 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; case "tools/list": { // 单一来源直序列化(AC-02 零漂移):OpenAI function 形态 → MCP // tools[].{name,description,inputSchema} 投影——字段名映射非复制 - this.reply(id, { + return makeReply(id, { tools: TOOL_DEFS.map((d) => ({ name: d.function.name, description: d.function.description, inputSchema: d.function.parameters, })), }); - return; } case "tools/call": { const name = String(params.name ?? ""); @@ -178,15 +169,14 @@ export class McpServer { 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; + return makeReplyErr(id, -32602, `Unknown tool: ${name}`, { available: TOOL_DEFS.map((d) => d.function.name) }); } 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 as (a: Record) => Promise)(args); // Some clients only expose content, so include bounded command output there. - this.reply(id, { + return makeReply(id, { content: [{ type: "text", text: summarizeToolResult(name, r, textOnlyBatch) }], ...(textOnlyBatch ? {} : { structuredContent: r }), isError: false, @@ -197,6 +187,7 @@ export class McpServer { const err = (e !== null && typeof e === "object" ? e : {}) as { outcome?: string; terminalId?: string; + forwardId?: string; sessionId?: string; logBase?: string; sessions?: Array<{ sessionId: string; logBase: string }>; @@ -206,6 +197,7 @@ export class McpServer { const details = { outcome: err.outcome, terminalId: err.terminalId, + forwardId: err.forwardId, sessionId: err.sessionId, logBase: err.logBase, sessions: err.sessions, @@ -218,6 +210,9 @@ export class McpServer { if (typeof err.terminalId === "string" && err.terminalId) { evidence.push(`terminal_id=${singleLine(err.terminalId)}`); } + if (typeof err.forwardId === "string" && err.forwardId) { + evidence.push(`forward_id=${singleLine(err.forwardId)}`); + } if (typeof err.sessionId === "string" && err.sessionId) { evidence.push(`session_id=${singleLine(err.sessionId)}`); } @@ -236,7 +231,7 @@ export class McpServer { } const errorText = [...evidence, message].join("\n"); const overflow = name === "run_batch" && jsonStringBytes(errorText) > BATCH_TEXT_JSON_BYTES; - this.reply(id, { + return makeReply(id, { content: [{ type: "text", text: overflow ? limitBatchText(errorText, textOnlyBatch ? "" : FULL_OUTPUT_HINT) : errorText }], isError: true, ...(!textOnlyBatch && (overflow || Object.values(details).some((value) => value !== undefined)) @@ -244,22 +239,53 @@ export class McpServer { : {}), }); } - return; } case "ping": - this.reply(id, {}); - return; + return makeReply(id, {}); default: - this.replyErr(id, -32601, `Method not found: ${method}`); + return makeReplyErr(id, -32601, `Method not found: ${method}`); } } +} + +export class McpServer { + private readonly tk: AgentToolkit; + private readonly log: FilaxisLogger; + private readonly out: NodeJS.WritableStream; + private readonly protocol: McpProtocolHandler; + private rl?: readline.Interface; + + constructor(opts: McpServerOptions) { + this.tk = opts.toolkit; + this.log = opts.logger ?? noopLogger; + this.out = opts.stdout ?? process.stdout; + this.protocol = new McpProtocolHandler({ + toolkit: opts.toolkit, + serverName: opts.serverName, + serverVersion: opts.serverVersion, + }); + const input = opts.stdin ?? process.stdin; + this.rl = readline.createInterface({ input, terminal: false }); + this.rl.on("line", (line) => { + void this.protocol.handleRawLine(line).then((resp) => { + if (resp) this.write(resp); + }); + }); + this.rl.on("close", () => { + // 连接断开=客户端退出:进程内 toolkit 状态(会话句柄)交还内核 TTL 回收 + this.tk.dispose?.(); + this.log.info("[mcp] stdin 关闭——server 退出"); + }); + } + + private write(msg: Record): void { + this.out.write(JSON.stringify(msg) + "\n"); + } /** 测试/优雅收尾:关闭输入监听 */ close(): void { this.rl?.close(); } - - } function summarizeFileContent(content: string): string { @@ -273,7 +299,23 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea 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 (result.action === "remove") return `removed=${singleLine(result.removed)}`; + if (result.action === "forward_add") { + const f = result.forward; + const dst = f.kind === "dynamic" ? "SOCKS5" : `${singleLine(f.targetHost ?? "")}:${f.targetPort}`; + return `forward=${singleLine(f.forwardId)} | layer=${singleLine(f.layer ?? "?")} | ${f.kind} ${singleLine(f.bindAddr)}:${f.bindPort} -> ${dst}`; + } + if (result.action === "forward_list") { + if (!result.forwards.length) return "forwards=0"; + return [ + `forwards=${result.forwards.length}`, + ...result.forwards.map((f) => { + const dst = f.kind === "dynamic" ? "SOCKS5" : `${singleLine(f.targetHost ?? "")}:${f.targetPort}`; + return `${singleLine(f.forwardId)} | layer=${singleLine(f.layer ?? "?")} | ${f.kind} ${singleLine(f.bindAddr)}:${f.bindPort} -> ${dst} | ${f.status}`; + }), + ].join("\n"); + } + return `forward_id=${singleLine(result.forward_id)} | status=${result.status}${result.detail ? ` | ${singleLine(result.detail)}` : ""}`; } if (name === "list_layers") { return (value as Awaited>).text; diff --git a/src/runtime-stack.ts b/src/runtime-stack.ts index 55d8fe0..237ed07 100644 --- a/src/runtime-stack.ts +++ b/src/runtime-stack.ts @@ -19,9 +19,13 @@ import { hopHost, type SshHop, type SshConnParams, } from "./ssh-helpers.js"; import type { SessionEvent } from "./session-types.js"; +import type { OpenForwardSpec, ForwardInfo, CloseForwardResult } from "./ssh-forward.js"; import { noopLogger, type FilaxisLogger } from "./logger.js"; -export type FilaxisEvents = SessionEvent | { type: "layerState"; layer: string; state: string }; +export type FilaxisEvents = + | SessionEvent + | { type: "layerState"; layer: string; state: string } + | { type: "forwardExit"; layer?: string; forward: ForwardInfo }; export interface StackFeatures { /** ControlMaster 多路复用可用(非 Windows + ssh 二进制存在) */ @@ -72,6 +76,9 @@ export class RuntimeStack { * 两个 stack 各注册同名 driver 的不同实现不再串用连接(B 拿到 A 的实例) */ private cacheNs: string; private featuresCache: StackFeatures | null = null; + private readonly pendingForwardIds = new Map(); + private readonly pendingForwards = new WeakMap(); + private readonly detachedForwardDrivers = new Set(); constructor(opts: RuntimeStackOptions = {}) { this.factory = opts.factory ?? new RuntimeFactory(); @@ -93,7 +100,33 @@ export class RuntimeStack { * this(每 stack 一份、引用稳定)——重复 connect 时 Set.add 幂等去重); * evictDriver 清空登记并恢复原回调 */ private sessionForward?: (e: SessionEvent) => void; + private readonly forwardEventCbs = new WeakMap void>(); + + private bridgeForwardEvents(drv: RuntimeDriver): void { + const fc = (drv as { forwardControl?: { subs?: Set<(info: ForwardInfo) => void> } }).forwardControl; + if (!fc?.subs) return; + let cb = this.forwardEventCbs.get(drv); + if (!cb) { + cb = (info: ForwardInfo) => { + let layerName = info.layer; + if (!layerName) { + for (const h of this.namedLayers.values()) { + if (h.driver === drv) { layerName = h.name; break; } + } + } + this.events.emit({ + type: "forwardExit", + ...(layerName ? { layer: layerName } : {}), + forward: layerName ? { ...info, layer: layerName } : info, + }); + }; + this.forwardEventCbs.set(drv, cb); + } + fc.subs.add(cb); + } + private bridgeSessionEvents(drv: RuntimeDriver): void { + this.bridgeForwardEvents(drv); const sm = (drv as { sessions?: { onEvent?: (e: SessionEvent) => void; @@ -350,6 +383,8 @@ export class RuntimeStack { sm.__fxSubs.clear(); if (sm.__fxOrig) sm.onEvent = sm.__fxOrig; } + const fc = (drv as { forwardControl?: { subs?: Set } }).forwardControl; + fc?.subs?.clear(); } /** 开放注册(透传 factory;AC-09 第三方 Transport 同权)。注册即退出共享缓存 @@ -417,6 +452,7 @@ export class RuntimeStack { async addLayer( name: string, descriptorOrDriver: RuntimeDescriptor | RuntimeDriver, + opts?: { activate?: boolean }, ): Promise<{ handle: LayerHandle; reused: boolean; reusedFrom?: string }> { this.assertNotDupName(name); if (this.isDriver(descriptorOrDriver)) { @@ -424,16 +460,20 @@ export class RuntimeStack { const handle: LayerHandle = { name, descriptor: driver.descriptor, driver }; this.trackDriver(handle); this.namedLayers.set(name, handle); - this.activeName = name; + if (opts?.activate !== false) this.activeName = name; return { handle, reused: false }; } const descriptor = descriptorOrDriver; // 名称预留(二十七期 #2):统一经 withNameReservation(二十八期 #1 起 // layerInto/sshInto 同款——所有异步建层入口共用的并发同名防线) - return this.withNameReservation(name, () => this.addLayerInner(name, descriptor)); + return this.withNameReservation(name, () => this.addLayerInner(name, descriptor, opts)); } - private async addLayerInner(name: string, descriptor: RuntimeDescriptor): Promise<{ handle: LayerHandle; reused: boolean; reusedFrom?: string }> { + private async addLayerInner( + name: string, + descriptor: RuntimeDescriptor, + opts?: { activate?: boolean }, + ): Promise<{ handle: LayerHandle; reused: boolean; reusedFrom?: string }> { // 回环检测幂等(descriptor 形态):新落点 identity ∈ 既有层路径 identity 集。 // 末节点命中=同落点构造性成立(canonical identity 相同)→ 直接复用; // 途经节点命中(identity 撞了某层的中间跳)→ hostname 落点校验把关(宁重连不错主机)。 @@ -460,7 +500,7 @@ export class RuntimeStack { const handle: LayerHandle = { name, descriptor: driver.descriptor, driver }; this.trackDriver(handle); // 登记计数(Sol 70 #1 复归:claim 无释放出口曾堵死最后一层) this.namedLayers.set(name, handle); - this.activeName = name; + if (opts?.activate !== false) this.activeName = name; return { handle, reused: false }; } @@ -545,9 +585,129 @@ export class RuntimeStack { return h; } + private resolveForwardLayer(layerName?: string): LayerHandle { + if (layerName !== undefined) return this.requireLayer(layerName); + if (!this.activeName) { + throw new Error(`未指定层名且当前无默认层(既有:${[...this.namedLayers.keys()].join(", ") || "空"})——请先 addLayer 或显式指定层名`); + } + return this.requireLayer(this.activeName); + } + + /** 在指定或默认层打开动态端口转发(-L / -R / -D,REQ-0005) */ + async openForward(spec: OpenForwardSpec, layerName?: string): Promise { + const h = this.resolveForwardLayer(layerName); + if (typeof h.driver.openForward !== "function") { + throw new Error(`层 '${h.name}' (${h.descriptor.driver}) 不支持动态端口转发`); + } + if (spec.id) { + const pendingLayer = this.pendingForwardIds.get(spec.id); + if (pendingLayer !== undefined) { + throw new Error(`转发 ID '${spec.id}' 正在层 '${pendingLayer}' 中建立,拒绝并发重复创建`); + } + for (const other of this.forwardDrivers()) { + if (other.driver === h.driver) continue; + if (other.driver.listForwards?.().some((f) => f.forwardId === spec.id + && (other.layer !== undefined || f.status === "active" || f.status === "unknown"))) { + throw new Error(other.layer + ? `转发 ID '${spec.id}' 已在层 '${other.layer}' 中存在` + : `转发 ID '${spec.id}' 已存在于已移出层的驱动`); + } + } + this.pendingForwardIds.set(spec.id, h.name); + } + this.pendingForwards.set(h.driver, (this.pendingForwards.get(h.driver) ?? 0) + 1); + try { + this.bridgeForwardEvents(h.driver); + const info = await h.driver.openForward(spec); + return { ...info, layer: h.name }; + } finally { + const remaining = this.pendingForwards.get(h.driver)! - 1; + if (remaining === 0) this.pendingForwards.delete(h.driver); + else this.pendingForwards.set(h.driver, remaining); + if (spec.id && this.pendingForwardIds.get(spec.id) === h.name) { + this.pendingForwardIds.delete(spec.id); + } + } + } + + /** Whether replacing this layer could make a pending or live forward unreachable. */ + hasLiveForwards(layerName: string): boolean { + return this.driverHasLiveForwards(this.requireLayer(layerName).driver); + } + + private driverHasLiveForwards(driver: RuntimeDriver): boolean { + return this.pendingForwards.has(driver) + || (driver.listForwards?.().some((f) => f.status === "active" || f.status === "unknown") ?? false); + } + + hasForwardDriver(driver: RuntimeDriver): boolean { + return [...this.namedLayers.values()].some((layer) => layer.driver === driver) + || (this.detachedForwardDrivers.has(driver) && this.driverHasLiveForwards(driver)); + } + + private *forwardDrivers(): Iterable<{ driver: RuntimeDriver; layer?: string }> { + const seen = new Set(); + for (const { driver, name } of this.namedLayers.values()) { + if (seen.has(driver)) continue; + seen.add(driver); + yield { driver, layer: name }; + } + for (const driver of this.detachedForwardDrivers) { + if (seen.has(driver) || !this.driverHasLiveForwards(driver)) { + this.detachedForwardDrivers.delete(driver); + } else { + yield { driver }; + } + } + } + + /** 关闭指定或跨层检索到的动态端口转发,遵循 stopped / already_closed / unknown 三态 */ + async closeForward(forwardId: string, layerName?: string): Promise { + if (layerName !== undefined) { + const h = this.requireLayer(layerName); + if (typeof h.driver.closeForward !== "function") { + throw new Error(`层 '${h.name}' (${h.descriptor.driver}) 不支持动态端口转发`); + } + return h.driver.closeForward(forwardId); + } + for (const { driver, layer } of this.forwardDrivers()) { + if (typeof driver.closeForward === "function") { + if (driver.listForwards?.().some((f) => f.forwardId === forwardId + && (layer !== undefined || f.status === "active" || f.status === "unknown"))) { + return driver.closeForward(forwardId); + } + } + } + throw new Error(`转发 '${forwardId}' 不存在`); + } + + /** 查询指定层或所有已注册层的动态端口转发列表 */ + listForwards(layerName?: string): ForwardInfo[] { + if (layerName !== undefined) { + const h = this.requireLayer(layerName); + return (h.driver.listForwards?.() ?? []).map((f) => ({ ...f, layer: h.name })); + } + const out: ForwardInfo[] = []; + for (const { driver, layer } of this.forwardDrivers()) { + for (const f of driver.listForwards?.() ?? []) { + if (layer !== undefined) { + out.push({ ...f, layer: f.layer ?? layer }); + } else if (f.status === "active" || f.status === "unknown") { + const { layer: _formerLayer, ...forward } = f; + out.push(forward); + } + } + } + return out; + } + /** 移出注册表(缺省连接保留在指纹缓存可复用;destroy=true 才真销毁) */ async removeLayer(name: string, opts: { destroy?: boolean } = {}): Promise { const h = this.requireLayer(name); + if (this.driverHasLiveForwards(h.driver) && ![...this.namedLayers.values()] + .some((other) => other.name !== name && other.driver === h.driver)) { + this.detachedForwardDrivers.add(h.driver); + } this.namedLayers.delete(name); // 默认层回落在异步销毁**之前**(Sol 68 P1):destroy 暂停期间缺省命令 //(未显式指定层的 run_command)曾落到初始 driver——销毁完才切到存活层 @@ -565,26 +725,34 @@ export class RuntimeStack { if (refs === 0) RuntimeStack.driverRefs.delete(h.driver); else RuntimeStack.driverRefs.set(h.driver, refs); if (opts.destroy && refs === 0) { - // 缓存同步逐出(Sol 71 #2 → Sol 73 #3 homeKey):按本 driver 实际 - // 挂载键实例核对清——按描述符算键曾因 init 补写 terminalId 键不匹配 - // (旧缓存残留、重连拿回已销毁实例);定时器只复核+销毁本代(不逐出) - RuntimeStack.evictDriverHome(h.driver, true); - let disposal = RuntimeStack.destroyScheduled.get(h.driver); - if (!disposal) { - disposal = new Promise((resolve) => setTimeout(resolve, 0)).then(async () => { - if ((RuntimeStack.driverRefs.get(h.driver) ?? 0) > 0) return; - RuntimeStack.destroyingDrivers.add(h.driver); - try { - await h.driver.destroy(); - } finally { - RuntimeStack.unbridgeSessionEvents(h.driver); - RuntimeStack.destroyingDrivers.delete(h.driver); - } - }).finally(() => RuntimeStack.destroyScheduled.delete(h.driver)); - RuntimeStack.destroyScheduled.set(h.driver, disposal); - } - await disposal; + await this.destroyUnreferencedDriver(h.driver); + } + } + + async destroyDetachedForwardDrivers(): Promise { + const detached = [...this.detachedForwardDrivers].filter((driver) => + (RuntimeStack.driverRefs.get(driver) ?? 0) === 0 && this.driverHasLiveForwards(driver)); + await Promise.allSettled(detached.map((driver) => this.destroyUnreferencedDriver(driver))); + } + + private destroyUnreferencedDriver(driver: RuntimeDriver): Promise { + // 缓存同步逐出,销毁前复核当前引用,避免误销毁已重新挂载的连接。 + RuntimeStack.evictDriverHome(driver, true); + let disposal = RuntimeStack.destroyScheduled.get(driver); + if (!disposal) { + disposal = new Promise((resolve) => setTimeout(resolve, 0)).then(async () => { + if ((RuntimeStack.driverRefs.get(driver) ?? 0) > 0) return; + RuntimeStack.destroyingDrivers.add(driver); + try { + await driver.destroy(); + } finally { + RuntimeStack.unbridgeSessionEvents(driver); + RuntimeStack.destroyingDrivers.delete(driver); + } + }).finally(() => RuntimeStack.destroyScheduled.delete(driver)); + RuntimeStack.destroyScheduled.set(driver, disposal); } + return disposal; } /** 层清单纯文本(零 ANSI/零表格——npm 零依赖红线;彩色表格留消费方) */ @@ -770,7 +938,7 @@ export class RuntimeStack { const has = (bin: string) => new Promise((resolve) => { const probe = process.platform === "win32" - ? spawn("where", [bin], { stdio: "ignore" }) + ? spawn("where", [bin], { stdio: "ignore", windowsHide: true }) : spawn("which", [bin], { stdio: "ignore" }); probe.on("close", (code) => resolve(code === 0)); probe.on("error", () => resolve(false)); diff --git a/src/shell-discovery.ts b/src/shell-discovery.ts index 8004573..2a94a5b 100644 --- a/src/shell-discovery.ts +++ b/src/shell-discovery.ts @@ -10,7 +10,7 @@ * 4. 回退 "bash" + 诊断提示(用户可能真有 WSL 发行版) */ import { existsSync } from "node:fs"; -import { execSync } from "node:child_process"; +import { execFileSync } from "node:child_process"; const GIT_BASH_CANDIDATES = [ "C:\\Program Files\\Git\\bin\\bash.exe", @@ -21,7 +21,7 @@ const GIT_BASH_CANDIDATES = [ /** PATH 上 bash 的解析结果(无则 undefined) */ function bashOnPath(): string | undefined { try { - return execSync("where bash", { stdio: ["ignore", "pipe", "ignore"] }) + return execFileSync("where", ["bash"], { stdio: ["ignore", "pipe", "ignore"], windowsHide: true }) .toString().split("\n").map((l) => l.trim()).filter(Boolean)[0]; } catch { return undefined; diff --git a/src/ssh-forward.ts b/src/ssh-forward.ts new file mode 100644 index 0000000..9d80e13 --- /dev/null +++ b/src/ssh-forward.ts @@ -0,0 +1,1035 @@ +/** + * ssh-forward.ts — SSH 动态端口转发内核(-L / -R / -D 双路径自动适配) + * + * 两条路径统一收敛到相同的 OpenForwardSpec / ForwardInfo / CloseForwardResult 契约: + * - Path A(Mux):非 Windows 且存在可用 ControlMaster 控制套接字时, + * 经 `ssh -S -O forward / -O cancel` 复用已有主连接,零额外握手开销。 + * - Path B(Subprocess):Windows(无 ControlMaster)、禁用 mux 或主连接未建 mux 时, + * 自动降级为受托管的 `ssh -N -o ExitOnForwardFailure=yes` 子进程,并纳入层生命周期回收。 + * + * 语义不变量(REQ-0005 / AGENTS.md): + * - closeForward 遵循「终止即请求、死亡须核实」,严格返回 stopped / already_closed / unknown; + * - bindPort: 0 时必须回传实测绑定端口,解析失败一律报错,绝不返回 0 假装成功; + * - 托管子进程意外退出诚实标记为 exited 并触发事件,绝不静默假装健康。 + */ +import * as crypto from "node:crypto"; +import { spawn, type ChildProcess } from "node:child_process"; +import * as net from "node:net"; +import { StringDecoder } from "node:string_decoder"; +import { autonomousSshOpts, muxFlagsFor, renderEnterBridgeCommand, shellQuote, type EnterStep, type SshConnParams } from "./ssh-helpers.js"; +import { openSshEnvironment } from "./openssh-environment.js"; +import { noopLogger, type FilaxisLogger } from "./logger.js"; + +export type DynamicForwardKind = "local" | "remote" | "dynamic"; +export type ForwardTransportMode = "mux" | "subprocess" | "stdio-bridge"; +export type ForwardStatus = "active" | "exited" | "stopped" | "unknown"; + +export interface OpenForwardSpec { + kind: DynamicForwardKind | "L" | "R" | "D"; + bindAddr?: string; + bindPort?: number; + targetHost?: string; + targetPort?: number; + id?: string; + timeoutMs?: number; +} + +export interface ForwardInfo { + forwardId: string; + layer?: string; + kind: DynamicForwardKind; + bindAddr: string; + bindPort: number; + targetHost?: string; + targetPort?: number; + transportMode: ForwardTransportMode; + status: ForwardStatus; + createdAt: number; + pid?: number; + exitCode?: number | null; + lastError?: string; +} + +export interface CloseForwardResult { + status: "stopped" | "already_closed" | "unknown"; + forwardId: string; + detail?: string; +} + +export interface NormalizedForwardSpec { + kind: DynamicForwardKind; + flag: "-L" | "-R" | "-D"; + bindAddr: string; + bindPort: number; + targetHost?: string; + targetPort?: number; + forwardId: string; + timeoutMs: number; +} + +export interface ExecSshResult { + exitCode: number | null; + stdout: string; + stderr: string; + timedOut?: boolean; +} + +export interface ForwardDeps { + execSsh?: (argv: string[], timeoutMs: number) => Promise; + spawnSsh?: (argv: string[]) => ChildProcess; + spawnBridge?: (argv: string[]) => ChildProcess; + allocateLocalPort?: (bindAddr: string) => Promise; + muxControlPath?: () => string | undefined; + stopGraceMs?: number; + killWaitMs?: number; +} + +export interface SshForwardManagerOptions { + /** 用于启动独立转发或控制命令的 ssh 目标参数(不含静态 forwards 以避免端口冲突) */ + destArgs: string[]; + /** 用于计算 mux ControlPath 的完整参数(含静态连接特征,缺省同 destArgs) */ + muxDestArgs?: string[]; + connParams?: SshConnParams; + layerName?: string; + /** 若层含 enterPipeline(如 --docker/--enter),本地转发自动经穿层 stdio TCP 桥穿透到内层 127.0.0.1 */ + enterSteps?: EnterStep[]; + execInLayer?: (command: string, opts?: { timeoutMs?: number }) => Promise<{ stdout: string; stderr: string; exitCode: number }>; + logger?: FilaxisLogger; + onForwardExit?: (info: ForwardInfo) => void; + _deps?: ForwardDeps; +} + +const HOST_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const IPV6_RE = /^[0-9A-Fa-f:]+$/; +const FORWARD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const DEFAULT_FORWARD_TIMEOUT_MS = 15_000; +const DEFAULT_MUX_CMD_TIMEOUT_MS = 5_000; +const DEFAULT_STOP_GRACE_MS = 3_000; +const DEFAULT_KILL_WAIT_MS = 2_000; +const MAX_DIAG_BYTES = 4096; + +type BridgeTool = "socat" | "python3" | "python" | "node" | "nc"; + +const PYTHON_STDIO_TCP_BRIDGE = [ + "import os,select,socket,sys", + "s=socket.create_connection((sys.argv[1],int(sys.argv[2])))", + "rf=[0,s]", + "eof_in=False", + "while rf:", + " r,_,_=select.select(rf,[],[])", + " if 0 in r:", + " d=os.read(0,16384)", + " if not d:", + " eof_in=True;rf.remove(0)", + " try:s.shutdown(socket.SHUT_WR)", + " except OSError:pass", + " else:s.sendall(d)", + " if s in r:", + " d=s.recv(16384)", + " if not d:break", + " v=memoryview(d)", + " while v:", + " n=os.write(1,v);v=v[n:]", + "s.close()", +].join("\n"); + +const NODE_STDIO_TCP_BRIDGE = [ + "const net=require('node:net');", + "const s=net.createConnection({host:process.argv[1],port:Number(process.argv[2])});", + "const bye=()=>process.exit(0);", + "s.on('error',()=>process.exit(1));", + "process.stdin.on('error',()=>s.destroy());", + "process.stdout.on('error',()=>s.destroy());", + "process.stdin.pipe(s);", + "s.pipe(process.stdout);", + "s.on('close',bye);", +].join(""); + +export function buildInnerTcpBridgeCmd(tool: BridgeTool, targetHost: string, targetPort: number): string { + if (tool === "socat") { + const dest = targetHost.includes(":") ? `TCP6:[${targetHost}]:${targetPort}` : `TCP:${targetHost}:${targetPort}`; + return `exec socat - ${shellQuote(dest)}`; + } + if (tool === "python3" || tool === "python") { + return `exec ${tool} -u -c ${shellQuote(PYTHON_STDIO_TCP_BRIDGE)} ${shellQuote(targetHost)} ${String(targetPort)}`; + } + if (tool === "node") { + return `exec node -e ${shellQuote(NODE_STDIO_TCP_BRIDGE)} ${shellQuote(targetHost)} ${String(targetPort)}`; + } + return `exec nc ${shellQuote(targetHost)} ${String(targetPort)}`; +} + +function unwrapBrackets(host: string): string { + const trimmed = host.trim(); + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + return trimmed.slice(1, -1); + } + return trimmed; +} + +function assertSafeHost(label: string, raw: string, allowWildcard = false): string { + const host = unwrapBrackets(raw); + if (!host) throw new Error(`动态端口转发 ${label} 不能为空`); + if (allowWildcard && host === "*") return host; + const ok = host.includes(":") ? IPV6_RE.test(host) : HOST_RE.test(host); + if (!ok) { + throw new Error(`非法动态端口转发 ${label}(禁止前导 '-'、空白或 shell 元字符): ${JSON.stringify(raw.slice(0, 60))}`); + } + return host; +} + +function assertPort(label: string, port: unknown, allowZero: boolean): number { + if (typeof port !== "number" || !Number.isInteger(port)) { + throw new Error(`动态端口转发 ${label} 必须为整数: ${String(port)}`); + } + const min = allowZero ? 0 : 1; + if (port < min || port > 65535) { + throw new Error(`动态端口转发 ${label} 超出范围(${min}-65535): ${port}`); + } + return port; +} + +function formatBindOrTargetAddr(addr: string): string { + if (addr === "*") return "*"; + return addr.includes(":") ? `[${addr}]` : addr; +} + +function bindHostFor(bindAddr: string): string { + return bindAddr === "*" ? "0.0.0.0" : bindAddr; +} + +function appendDiag(prev: string, chunk: string): string { + const next = prev + chunk; + return next.length > MAX_DIAG_BYTES ? next.slice(-MAX_DIAG_BYTES) : next; +} + +/** 归一化并严格校验动态端口转发规格 */ +export function normalizeForwardSpec(spec: OpenForwardSpec): NormalizedForwardSpec { + let kind: DynamicForwardKind; + let flag: "-L" | "-R" | "-D"; + if (spec.kind === "local" || spec.kind === "L") { + kind = "local"; + flag = "-L"; + } else if (spec.kind === "remote" || spec.kind === "R") { + kind = "remote"; + flag = "-R"; + } else if (spec.kind === "dynamic" || spec.kind === "D") { + kind = "dynamic"; + flag = "-D"; + } else { + throw new Error(`不支持的动态端口转发类型: ${String((spec as { kind?: unknown }).kind)}(支持 local/L, remote/R, dynamic/D)`); + } + + const bindAddr = spec.bindAddr === undefined || spec.bindAddr === "" + ? "127.0.0.1" + : assertSafeHost("bindAddr", spec.bindAddr, true); + const bindPort = spec.bindPort === undefined ? 0 : assertPort("bindPort", spec.bindPort, true); + + let targetHost: string | undefined; + let targetPort: number | undefined; + if (kind === "local" || kind === "remote") { + if (typeof spec.targetHost !== "string" || !spec.targetHost.trim()) { + throw new Error(`${kind} 模式必须提供 targetHost`); + } + targetHost = assertSafeHost("targetHost", spec.targetHost, false); + targetPort = assertPort("targetPort", spec.targetPort, false); + } + + let forwardId: string; + if (spec.id !== undefined) { + if (typeof spec.id !== "string" || !FORWARD_ID_RE.test(spec.id)) { + throw new Error(`非法转发 ID(仅支持字母数字及 ._-): ${JSON.stringify(spec.id)}`); + } + forwardId = spec.id; + } else { + forwardId = `fwd-${crypto.randomBytes(6).toString("hex")}`; + } + + const timeoutMs = spec.timeoutMs ?? DEFAULT_FORWARD_TIMEOUT_MS; + if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) { + throw new Error(`非法 timeoutMs: ${String(spec.timeoutMs)}`); + } + + return { kind, flag, bindAddr, bindPort, targetHost, targetPort, forwardId, timeoutMs }; +} + +/** 渲染为 OpenSSH `-L` / `-R` / `-D` 参数值(IPv6 自动加方括号) */ +export function renderDynamicForwardSpec(norm: NormalizedForwardSpec, effectivePort = norm.bindPort): string { + const bind = formatBindOrTargetAddr(norm.bindAddr); + if (norm.kind === "dynamic") { + return `${bind}:${effectivePort}`; + } + const target = formatBindOrTargetAddr(norm.targetHost!); + return `${bind}:${effectivePort}:${target}:${norm.targetPort!}`; +} + +export function parseMuxAllocatedPort(stdout: string, stderr: string): number | undefined { + for (const text of [stdout, stderr]) { + const alloc = text.match(/Allocated port (\d+)/i); + if (alloc) { + const p = Number(alloc[1]); + if (Number.isInteger(p) && p >= 1 && p <= 65535) return p; + } + const bare = text.match(/^\s*(\d{1,5})\s*$/m); + if (bare) { + const p = Number(bare[1]); + if (Number.isInteger(p) && p >= 1 && p <= 65535) return p; + } + } + return undefined; +} + +export function parseSubprocessRemotePort(line: string): number | undefined { + const m = line.match(/Allocated port (\d+)(?:\s+for remote forward)?/i); + if (!m) return undefined; + const p = Number(m[1]); + return Number.isInteger(p) && p >= 1 && p <= 65535 ? p : undefined; +} + +async function defaultAllocateLocalPort(bindAddr: string): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.unref(); + srv.once("error", (err) => reject(new Error(`分配本地空闲端口失败 (${bindAddr}): ${err.message}`))); + srv.listen(0, bindHostFor(bindAddr), () => { + const addr = srv.address(); + const port = addr && typeof addr === "object" ? addr.port : 0; + srv.close((closeErr) => { + if (closeErr) reject(closeErr); + else if (port < 1 || port > 65535) reject(new Error("系统返回无效的临时端口号")); + else resolve(port); + }); + }); + }); +} + +function defaultExecSsh(argv: string[], timeoutMs: number, logger: FilaxisLogger): Promise { + return new Promise((resolve, reject) => { + const child = spawn("ssh", argv, { + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + env: openSshEnvironment(process.env, logger), + }); + const outDec = new StringDecoder("utf-8"); + const errDec = new StringDecoder("utf-8"); + let stdout = ""; + let stderr = ""; + let settled = false; + let timedOut = false; + + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGTERM"); + setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + }, 500).unref(); + }, timeoutMs); + + child.stdout?.on("data", (d: Buffer) => { stdout += outDec.write(d); }); + child.stderr?.on("data", (d: Buffer) => { stderr += errDec.write(d); }); + child.once("error", (err) => { + if (settled) return; + settled = true; + clearTimeout(timer); + reject(new Error(`启动 ssh 控制命令失败: ${err.message}`)); + }); + child.once("close", (code) => { + if (settled) return; + settled = true; + clearTimeout(timer); + stdout += outDec.end(); + stderr += errDec.end(); + resolve({ exitCode: code, stdout, stderr, timedOut }); + }); + }); +} + +interface BridgeConnection { + socket: net.Socket; + child: ChildProcess; + stopping?: Promise; +} + +interface PendingForwardChild { + child: ChildProcess; + cancelStartup?: () => void; + cancelled?: boolean; + stopping?: Promise; + unconfirmed?: ForwardInfo; +} + +interface ManagedForwardEntry { + info: ForwardInfo; + norm: NormalizedForwardSpec; + effectiveSpec: string; + muxSocket?: string; + child?: ChildProcess; + bridgeServer?: net.Server; + bridgeConns?: Set; + closing: boolean; + inFlightClose?: Promise; +} + +/** 单条 SSH 层的动态端口转发管理器(Mux 优先 + Subprocess 自动降级 + enterPipeline stdio TCP 桥) */ +export class SshForwardManager { + private readonly entries = new Map(); + private readonly pendingIds = new Set(); + private readonly pendingChildren = new Map(); + private closedAll = false; + private cachedBridgeTool?: BridgeTool; + private readonly destArgs: string[]; + private readonly muxDestArgs: string[]; + private readonly connParams?: SshConnParams; + private readonly layerName?: string; + private readonly enterSteps: EnterStep[]; + private readonly execInLayer?: SshForwardManagerOptions["execInLayer"]; + private readonly log: FilaxisLogger; + private readonly onForwardExit?: (info: ForwardInfo) => void; + private readonly deps: Required; + + constructor(opts: SshForwardManagerOptions) { + this.destArgs = opts.destArgs; + this.muxDestArgs = opts.muxDestArgs ?? opts.destArgs; + this.connParams = opts.connParams; + this.layerName = opts.layerName; + this.enterSteps = opts.enterSteps ? [...opts.enterSteps] : []; + this.execInLayer = opts.execInLayer; + this.log = opts.logger ?? noopLogger; + this.onForwardExit = opts.onForwardExit; + + const sshOpts = autonomousSshOpts(this.connParams); + const defaultMuxControlPath = () => { + const flags = muxFlagsFor(this.muxDestArgs, { sshOptions: sshOpts }); + const cp = flags.find((f) => f.startsWith("ControlPath=")); + return cp ? cp.slice("ControlPath=".length) : undefined; + }; + + this.deps = { + execSsh: opts._deps?.execSsh ?? ((argv, ms) => defaultExecSsh(argv, ms, this.log)), + spawnSsh: opts._deps?.spawnSsh ?? ((argv) => spawn("ssh", argv, { + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + env: openSshEnvironment(process.env, this.log), + })), + spawnBridge: opts._deps?.spawnBridge ?? ((argv) => spawn("ssh", argv, { + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, + env: openSshEnvironment(process.env, this.log), + })), + allocateLocalPort: opts._deps?.allocateLocalPort ?? defaultAllocateLocalPort, + muxControlPath: opts._deps?.muxControlPath ?? defaultMuxControlPath, + stopGraceMs: opts._deps?.stopGraceMs ?? DEFAULT_STOP_GRACE_MS, + killWaitMs: opts._deps?.killWaitMs ?? DEFAULT_KILL_WAIT_MS, + }; + } + + private async activeMuxSocket(): Promise { + const sock = this.deps.muxControlPath(); + if (!sock) return undefined; + try { + const check = await this.deps.execSsh(["-S", sock, "-O", "check", ...this.destArgs], 3_000); + return !check.timedOut && check.exitCode === 0 ? sock : undefined; + } catch { + return undefined; + } + } + + async openForward(spec: OpenForwardSpec): Promise { + if (this.closedAll) { + throw new Error("转发管理器已关闭,无法新建动态端口转发"); + } + const norm = normalizeForwardSpec(spec); + if (this.entries.has(norm.forwardId) || this.pendingIds.has(norm.forwardId) || this.pendingChildren.has(norm.forwardId)) { + throw new Error(`转发 ID '${norm.forwardId}' 已存在或正在建立`); + } + this.pendingIds.add(norm.forwardId); + try { + if (this.enterSteps.length > 0) { + return await this.openViaStdioBridge(norm); + } + const muxSock = await this.activeMuxSocket(); + if (this.closedAll) { + throw new Error("转发管理器已关闭,无法新建动态端口转发"); + } + if (muxSock) { + return await this.openViaMux(norm, muxSock); + } + return await this.openViaSubprocess(norm); + } finally { + this.pendingIds.delete(norm.forwardId); + } + } + + private async openViaMux(norm: NormalizedForwardSpec, sock: string): Promise { + let requestPort = norm.bindPort; + if (norm.bindPort === 0 && norm.kind !== "remote") { + // OpenSSH `-O forward` 仅对 `-R ...:0:...` 回传动态端口;本地端口由本机分配以保精确 `-O cancel` + requestPort = await this.deps.allocateLocalPort(norm.bindAddr); + } + const reqSpec = renderDynamicForwardSpec(norm, requestPort); + const res = await this.deps.execSsh( + ["-S", sock, "-O", "forward", norm.flag, reqSpec, ...this.destArgs], + norm.timeoutMs, + ); + if (res.timedOut) { + const err = new Error(`Mux 动态端口转发超时 (${norm.timeoutMs}ms): ${norm.flag} ${reqSpec}`) as Error & { outcome: "unknown" }; + err.outcome = "unknown"; + throw err; + } + if (res.exitCode !== 0) { + const detail = (res.stderr || res.stdout).trim(); + throw new Error(`Mux 动态端口转发失败 (exit=${res.exitCode}): ${detail || reqSpec}`); + } + + let effectivePort = requestPort; + if (effectivePort === 0) { + const parsed = parseMuxAllocatedPort(res.stdout, res.stderr); + if (!parsed) { + throw new Error( + `Mux 动态端口转发未能解析远端分配端口(禁止返回 port=0): stdout=${JSON.stringify(res.stdout.trim())} stderr=${JSON.stringify(res.stderr.trim())}`, + ); + } + effectivePort = parsed; + } + + const effectiveSpec = renderDynamicForwardSpec(norm, effectivePort); + if (this.closedAll) { + await this.deps.execSsh( + ["-S", sock, "-O", "cancel", norm.flag, effectiveSpec, ...this.destArgs], + DEFAULT_MUX_CMD_TIMEOUT_MS, + ).catch(() => undefined); + throw new Error("转发管理器已关闭,已尝试取消在途转发"); + } + const info: ForwardInfo = { + forwardId: norm.forwardId, + ...(this.layerName ? { layer: this.layerName } : {}), + kind: norm.kind, + bindAddr: norm.bindAddr, + bindPort: effectivePort, + ...(norm.targetHost !== undefined ? { targetHost: norm.targetHost } : {}), + ...(norm.targetPort !== undefined ? { targetPort: norm.targetPort } : {}), + transportMode: "mux", + status: "active", + createdAt: Date.now(), + }; + this.entries.set(norm.forwardId, { + info, + norm, + effectiveSpec, + muxSocket: sock, + closing: false, + }); + return { ...info }; + } + + private async openViaSubprocess(norm: NormalizedForwardSpec): Promise { + let effectivePort = norm.bindPort; + if (norm.bindPort === 0 && norm.kind !== "remote") { + effectivePort = await this.deps.allocateLocalPort(norm.bindAddr); + } + if (this.closedAll) throw new Error("转发管理器已关闭"); + const effectiveSpec = renderDynamicForwardSpec(norm, effectivePort); + const argv = [ + "-N", "-T", "-v", + "-o", "ExitOnForwardFailure=yes", + "-o", "ClearAllForwardings=no", + "-o", "ControlPath=none", + ...autonomousSshOpts(this.connParams), + norm.flag, effectiveSpec, + ...this.destArgs, + ]; + const child = this.deps.spawnSsh(argv); + const id = norm.forwardId; + const pending: PendingForwardChild = { child }; + this.pendingChildren.set(id, pending); + child.once("close", () => { + if (this.pendingChildren.get(id) === pending) this.pendingChildren.delete(id); + }); + + let entry!: ManagedForwardEntry; + let ready = false; + let diagTail = ""; + let exitedAfterReady: { code: number | null } | undefined; + + try { + await new Promise((resolve, reject) => { + let settled = false; + const errDec = new StringDecoder("utf-8"); + let pendingLine = ""; + + const cleanupStartup = () => { + clearTimeout(timeoutTimer); + }; + + const failStartup = (message: string) => { + if (settled) return; + settled = true; + cleanupStartup(); + reject(new Error(message)); + }; + + const succeedStartup = () => { + if (settled) return; + settled = true; + ready = true; + cleanupStartup(); + resolve(); + }; + + const handleStderrLine = (line: string) => { + if (ready) return; + if (norm.kind === "remote" && effectivePort === 0) { + const allocated = parseSubprocessRemotePort(line); + if (allocated) { + effectivePort = allocated; + succeedStartup(); + } + return; + } + if (norm.kind === "remote") { + const confirmed = /^debug1: remote forward success for: listen (?:.*:)?(\d+), connect /i.exec(line); + if (confirmed && Number(confirmed[1]) === effectivePort) { + succeedStartup(); + } + return; + } + // OpenSSH reaches the client loop after checking local binds with ExitOnForwardFailure. + if (/^debug1: Entering interactive session\./.test(line)) { + succeedStartup(); + } + }; + + // stdout 持续排空,避免子进程缓冲区写满阻塞 + child.stdout?.on("data", () => undefined); + child.stderr?.on("data", (chunk: Buffer | string) => { + const text = typeof chunk === "string" ? chunk : errDec.write(chunk); + diagTail = appendDiag(diagTail, text); + if (ready) return; + pendingLine += text; + const lines = pendingLine.split(/\r?\n/); + pendingLine = lines.pop() ?? ""; + for (const line of lines) { + handleStderrLine(line); + if (ready) break; + } + }); + + child.once("error", (err) => { + if (!ready) { + failStartup(`本地 ssh 转发进程启动失败: ${err.message}`); + } + }); + + child.once("exit", (code) => { + if (pendingLine && !ready) { + handleStderrLine(pendingLine); + pendingLine = ""; + } + if (!ready) { + failStartup( + `动态端口转发建链失败 (ssh -N exit=${code ?? "signal"}): ${diagTail.trim() || effectiveSpec}`, + ); + return; + } + if (entry) { + if (!entry.closing) { + entry.info.status = "exited"; + entry.info.exitCode = code; + entry.info.lastError = diagTail.trim() || (code !== 0 ? `ssh -N 意外退出 (code=${code})` : "ssh -N 意外退出"); + try { this.onForwardExit?.({ ...entry.info }); } catch { /* 回调异常不外溢 */ } + } + } else { + exitedAfterReady = { code }; + } + }); + + const timeoutTimer = setTimeout(() => { + failStartup(`动态端口转发启动超时 (${norm.timeoutMs}ms): ${norm.flag} ${effectiveSpec}${diagTail.trim() ? `\n${diagTail.trim()}` : ""}`); + }, norm.timeoutMs); + pending.cancelStartup = () => failStartup("转发建立已取消(管理器已关闭或收到关闭请求)"); + if (this.closedAll) pending.cancelStartup(); + }); + if (pending.cancelled || this.closedAll) throw new Error("转发建立已取消"); + } catch (error) { + const result = await this.stopPendingForward(id, pending); + if (result.status === "unknown") { + pending.unconfirmed = { + forwardId: id, kind: norm.kind, bindAddr: norm.bindAddr, bindPort: effectivePort, + targetHost: norm.targetHost, targetPort: norm.targetPort, + transportMode: "subprocess", status: "unknown", createdAt: Date.now(), + pid: child.pid, lastError: result.detail, + }; + throw Object.assign(error instanceof Error ? error : new Error(String(error)), { + outcome: "unknown", forwardId: id, + }); + } + throw error; + } + this.pendingChildren.delete(id); + + const finalSpec = renderDynamicForwardSpec(norm, effectivePort); + const info: ForwardInfo = { + forwardId: norm.forwardId, + ...(this.layerName ? { layer: this.layerName } : {}), + kind: norm.kind, + bindAddr: norm.bindAddr, + bindPort: effectivePort, + ...(norm.targetHost !== undefined ? { targetHost: norm.targetHost } : {}), + ...(norm.targetPort !== undefined ? { targetPort: norm.targetPort } : {}), + transportMode: "subprocess", + status: "active", + createdAt: Date.now(), + ...(child.pid !== undefined ? { pid: child.pid } : {}), + }; + entry = { + info, + norm, + effectiveSpec: finalSpec, + child, + closing: false, + }; + this.entries.set(norm.forwardId, entry); + if (exitedAfterReady) { + entry.info.status = "exited"; + entry.info.exitCode = exitedAfterReady.code; + entry.info.lastError = diagTail.trim() || (exitedAfterReady.code !== 0 ? `ssh -N 意外退出 (code=${exitedAfterReady.code})` : "ssh -N 意外退出"); + try { this.onForwardExit?.({ ...entry.info }); } catch { /* 回调异常不外溢 */ } + throw Object.assign(new Error( + `动态端口转发建立后立即退出 (ssh -N exit=${exitedAfterReady.code ?? "signal"}): ${entry.info.lastError}`, + ), { forwardId: norm.forwardId, exitCode: exitedAfterReady.code }); + } + return { ...info }; + } + + private async probeBridgeTool(timeoutMs: number): Promise { + if (this.cachedBridgeTool) return this.cachedBridgeTool; + if (!this.execInLayer) { + throw new Error("带 enterPipeline(如 --docker/--enter)的层缺少执行通道,无法探测内层 TCP 桥原语(socat/python3/python/node/nc)"); + } + const probeCmd = "for t in socat python3 python node nc; do command -v \"$t\" >/dev/null 2>&1 && { printf '%s\\n' \"$t\"; exit 0; }; done; exit 127"; + const r = await this.execInLayer(probeCmd, { timeoutMs: Math.min(timeoutMs, 10_000) }); + const found = r.stdout.trim().split(/\r?\n/)[0]?.trim(); + if (r.exitCode !== 0 || (found !== "socat" && found !== "python3" && found !== "python" && found !== "node" && found !== "nc")) { + throw new Error( + `目标内层容器/环境未检测到可用的 TCP 桥接工具(需要 socat / python3 / python / node / nc 之一,probe exit=${r.exitCode}${r.stderr.trim() ? `: ${r.stderr.trim()}` : ""})`, + ); + } + this.cachedBridgeTool = found; + return found; + } + + private async openViaStdioBridge(norm: NormalizedForwardSpec): Promise { + if (norm.kind !== "local") { + throw new Error( + `带 enterPipeline(如 --docker/--enter)的内层环境目前仅支持 -L 本地到内层的 TCP 穿透转发,不支持 -R/-D(防止静默落到外层宿主机)`, + ); + } + const tool = await this.probeBridgeTool(norm.timeoutMs); + const innerCmd = buildInnerTcpBridgeCmd(tool, norm.targetHost!, norm.targetPort!); + const rendered = renderEnterBridgeCommand(this.enterSteps, innerCmd); + if (rendered.kind === "unreachable") { + throw new Error(`无法建立穿层动态转发(${rendered.reason}[进入步骤:${rendered.step}])`); + } + + const sshOpts = autonomousSshOpts(this.connParams); + const bridgeArgv = [ + "-T", "-o", "ClearAllForwardings=yes", + ...sshOpts, + ...muxFlagsFor(this.muxDestArgs, { sshOptions: sshOpts }), + ...this.destArgs, + "--", + rendered.command, + ]; + + const server = net.createServer(); + const bridgeConns = new Set(); + + await new Promise((resolve, reject) => { + const onErr = (err: Error) => { + server.removeListener("listening", onListening); + reject(new Error(`穿层转发本地监听失败 (${norm.bindAddr}:${norm.bindPort}): ${err.message}`)); + }; + const onListening = () => { + server.removeListener("error", onErr); + resolve(); + }; + server.once("error", onErr); + server.once("listening", onListening); + server.listen(norm.bindPort, bindHostFor(norm.bindAddr)); + }); + + const bound = server.address(); + const effectivePort = bound && typeof bound === "object" ? bound.port : 0; + if (!effectivePort || effectivePort < 1 || effectivePort > 65535) { + await new Promise((r) => server.close(() => r())); + throw new Error("穿层动态转发未能获取本地监听端口"); + } + if (this.closedAll) { + await new Promise((r) => server.close(() => r())); + throw new Error("转发管理器已关闭,已回收穿层转发监听"); + } + + const effectiveSpec = renderDynamicForwardSpec(norm, effectivePort); + const info: ForwardInfo = { + forwardId: norm.forwardId, + ...(this.layerName ? { layer: this.layerName } : {}), + kind: norm.kind, + bindAddr: norm.bindAddr, + bindPort: effectivePort, + targetHost: norm.targetHost, + targetPort: norm.targetPort, + transportMode: "stdio-bridge", + status: "active", + createdAt: Date.now(), + }; + const entry: ManagedForwardEntry = { + info, + norm, + effectiveSpec, + bridgeServer: server, + bridgeConns, + closing: false, + }; + this.entries.set(norm.forwardId, entry); + + server.on("connection", (socket) => { + if (entry.closing || this.closedAll) { + socket.destroy(); + return; + } + let child: ChildProcess; + try { + child = this.deps.spawnBridge(bridgeArgv); + } catch { + socket.destroy(); + return; + } + const conn: BridgeConnection = { socket, child }; + bridgeConns.add(conn); + + let teardownStarted = false; + const teardownConn = () => { + if (!socket.destroyed) socket.destroy(); + if (!entry.closing && !teardownStarted && bridgeConns.has(conn)) { + teardownStarted = true; + void this.stopBridgeChild(entry, conn); + } + }; + + socket.on("error", teardownConn); + socket.once("close", teardownConn); + child.once("error", teardownConn); + child.once("close", () => { + bridgeConns.delete(conn); + teardownConn(); + }); + child.stdin?.on("error", teardownConn); + child.stdout?.on("error", teardownConn); + child.stderr?.on("data", () => undefined); + child.stderr?.on("error", () => undefined); + + if (child.stdin) socket.pipe(child.stdin); + if (child.stdout) child.stdout.pipe(socket); + }); + + server.on("error", (err) => { + if (entry.closing) return; + entry.info.status = "exited"; + entry.info.lastError = `穿层本地监听异常: ${err.message}`; + for (const c of [...bridgeConns]) { + try { c.socket.destroy(); } catch { /* ignore */ } + if (c.child.exitCode === null && c.child.signalCode === null) { + try { c.child.kill("SIGTERM"); } catch { /* ignore */ } + } + } + try { this.onForwardExit?.({ ...entry.info }); } catch { /* ignore */ } + }); + + return { ...info }; + } + + async closeForward(forwardId: string): Promise { + const pending = this.pendingChildren.get(forwardId); + if (pending) return this.stopPendingForward(forwardId, pending); + const entry = this.entries.get(forwardId); + if (!entry) { + throw new Error(`转发 '${forwardId}' 不存在`); + } + if (entry.info.status === "stopped" || entry.info.status === "exited") { + return { status: "already_closed", forwardId }; + } + if (entry.inFlightClose) { + return entry.inFlightClose; + } + const task = entry.info.transportMode === "mux" + ? this.closeViaMux(entry) + : entry.info.transportMode === "stdio-bridge" + ? this.closeViaStdioBridge(entry) + : this.closeViaSubprocess(entry); + entry.inFlightClose = task.finally(() => { entry.inFlightClose = undefined; }); + return entry.inFlightClose; + } + + private stopPendingForward(forwardId: string, pending: PendingForwardChild): Promise { + if (pending.stopping) return pending.stopping; + pending.cancelled = true; + pending.cancelStartup?.(); + const child = pending.child; + const stopped = child.pid === undefined ? Promise.resolve({ exited: true }) : this.terminateChildVerified(child); + pending.stopping = stopped.then(({ exited }): CloseForwardResult => { + if (!exited) { + return { status: "unknown", forwardId, detail: "建立中的 ssh -N 进程未确认退出" }; + } + if (this.pendingChildren.get(forwardId) === pending) this.pendingChildren.delete(forwardId); + return { status: "stopped", forwardId }; + }).finally(() => { pending.stopping = undefined; }); + return pending.stopping; + } + + private async terminateChildVerified(child: ChildProcess): Promise<{ exited: boolean; code: number | null }> { + if (child.exitCode !== null || child.signalCode !== null) { + return { exited: true, code: child.exitCode }; + } + return new Promise<{ exited: boolean; code: number | null }>((resolve) => { + let settled = false; + let killTimer: ReturnType | null = null; + let giveUpTimer: ReturnType | null = null; + + const finish = (ok: boolean, code: number | null) => { + if (settled) return; + settled = true; + if (killTimer) clearTimeout(killTimer); + if (giveUpTimer) clearTimeout(giveUpTimer); + child.removeListener("exit", onExit); + child.removeListener("close", onExit); + resolve({ exited: ok, code }); + }; + const onExit = (code: number | null) => finish(true, code); + child.once("exit", onExit); + child.once("close", onExit); + + try { + child.kill("SIGTERM"); + } catch { + // 如果进程已结束则等待退出回调或直接查状态 + } + if (settled) return; + + killTimer = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) { + try { child.kill("SIGKILL"); } catch { /* ignore */ } + } + if (settled) return; + giveUpTimer = setTimeout(() => { + finish(child.exitCode !== null || child.signalCode !== null, child.exitCode); + }, this.deps.killWaitMs); + }, this.deps.stopGraceMs); + }); + } + + private stopBridgeChild(entry: ManagedForwardEntry, conn: BridgeConnection): Promise { + conn.stopping ??= this.terminateChildVerified(conn.child).then(({ exited }) => { + if (exited) entry.bridgeConns?.delete(conn); + return exited; + }).finally(() => { conn.stopping = undefined; }); + return conn.stopping; + } + + private async closeViaStdioBridge(entry: ManagedForwardEntry): Promise { + const { forwardId } = entry.info; + entry.closing = true; + + const srv = entry.bridgeServer; + const serverClosed = new Promise((resolve) => { + if (!srv) return resolve(); + try { srv.close(() => resolve()); } catch { resolve(); } + }); + + const conns = [...(entry.bridgeConns ?? [])]; + for (const c of conns) { + try { c.socket.destroy(); } catch { /* ignore */ } + } + const [results] = await Promise.all([ + Promise.all(conns.map((c) => this.stopBridgeChild(entry, c))), + serverClosed, + ]); + if (results.every(Boolean)) { + entry.info.status = "stopped"; + return { status: "stopped", forwardId }; + } + entry.closing = false; + entry.info.status = "unknown"; + entry.info.lastError = "部分穿层桥接子进程在 SIGTERM/SIGKILL 窗口内未确认退出"; + return { status: "unknown", forwardId, detail: entry.info.lastError }; + } + + private async closeViaMux(entry: ManagedForwardEntry): Promise { + const { forwardId } = entry.info; + try { + const res = await this.deps.execSsh( + ["-S", entry.muxSocket!, "-O", "cancel", entry.norm.flag, entry.effectiveSpec, ...this.destArgs], + DEFAULT_MUX_CMD_TIMEOUT_MS, + ); + if (!res.timedOut && res.exitCode === 0) { + entry.info.status = "stopped"; + return { status: "stopped", forwardId }; + } + const detail = (res.stderr || res.stdout).trim(); + const forwardAbsent = /^(?:mux_client_forward: )?(?:forwarding request failed: )?(?:port not forwarded|forward(?:ing)? not (?:found|active)|no such forward(?:ing)?)[.!]?$/im.test(detail); + if (!res.timedOut && forwardAbsent) { + entry.info.status = "stopped"; + return { status: "already_closed", forwardId, ...(detail ? { detail } : {}) }; + } + entry.info.status = "unknown"; + entry.info.lastError = detail || (res.timedOut ? "mux -O cancel 超时" : `mux -O cancel 退出码=${res.exitCode}`); + return { status: "unknown", forwardId, detail: entry.info.lastError }; + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + entry.info.status = "unknown"; + entry.info.lastError = detail; + return { status: "unknown", forwardId, detail }; + } + } + + private async closeViaSubprocess(entry: ManagedForwardEntry): Promise { + const { forwardId } = entry.info; + const child = entry.child; + if (!child || child.exitCode !== null || child.signalCode !== null) { + entry.info.status = "exited"; + return { status: "already_closed", forwardId }; + } + + entry.closing = true; + const exited = await this.terminateChildVerified(child); + if (exited.exited) { + entry.info.status = "stopped"; + entry.info.exitCode = exited.code; + return { status: "stopped", forwardId }; + } + entry.closing = false; + entry.info.status = "unknown"; + entry.info.lastError = "托管 ssh -N 进程在 SIGTERM/SIGKILL 窗口内未确认退出"; + return { status: "unknown", forwardId, detail: entry.info.lastError }; + } + + listForwards(): ForwardInfo[] { + const forwards = [...this.entries.values()].map((e) => ({ ...e.info })); + for (const { unconfirmed } of this.pendingChildren.values()) { + if (unconfirmed) forwards.push({ ...unconfirmed }); + } + return forwards; + } + + hasForward(forwardId: string): boolean { + return this.entries.has(forwardId) || this.pendingChildren.has(forwardId); + } + + async closeAll(): Promise { + this.closedAll = true; + const targets = new Set(this.pendingChildren.keys()); + for (const entry of this.entries.values()) { + if (entry.info.status === "active" || entry.info.status === "unknown") targets.add(entry.info.forwardId); + } + return Promise.all([...targets].map((id) => this.closeForward(id))); + } +} diff --git a/src/ssh-helpers.ts b/src/ssh-helpers.ts index 1f079de..7fc81cc 100644 --- a/src/ssh-helpers.ts +++ b/src/ssh-helpers.ts @@ -164,7 +164,13 @@ function quoteWindowsProxyArg(value: string): string { return `"${escaped}"`; } -function renderSshArgs(hop: SshHop, windowsProxy: boolean): string[] { +function knownHostsOption(file: string, windows: boolean): string { + const path = windows ? file.replaceAll("\\", "/") : file; + const quoted = /[\s"'\\#]/.test(path) ? '"' + path.replace(/["\\]/g, "\\$&") + '"' : path; + return `UserKnownHostsFile=${quoted}`; +} + +function renderSshArgs(hop: SshHop, windowsProxy: boolean, remote = false): string[] { if (!isHopObj(hop) || !hop.conn) { assertBareHost(hopHost(hop)); return [hopHost(hop)]; @@ -183,18 +189,16 @@ function renderSshArgs(hop: SshHop, windowsProxy: boolean): string[] { const policy = hop.conn.hostKeyPolicy === "strict" ? "yes" : "accept-new"; let hk = `-o StrictHostKeyChecking=${policy} `; if (hop.conn.knownHostsFile) { - const file = expandHomePath(hop.conn.knownHostsFile); - // -o is parsed again as an ssh_config option, including its path quoting. - const fileArg = windowsProxy && /\s/.test(file) ? `"${file.replaceAll("\\", "/")}"` : file; - const option = windowsProxy ? proxyQuote(`UserKnownHostsFile=${fileArg}`) : `UserKnownHostsFile=${proxyQuote(file)}`; - hk += `-o ${option} `; + const file = remote ? hop.conn.knownHostsFile : expandHomePath(hop.conn.knownHostsFile); + hk += `-o ${proxyQuote(knownHostsOption(file, windowsProxy))} `; } - const keyOpt = js.keyFile ? `-i ${proxyQuote(js.keyFile)} ` : ""; + const jumpKey = remote && typeof jump === "object" ? jump.keyFile : js.keyFile; + const keyOpt = jumpKey ? `-i ${proxyQuote(jumpKey)} ` : ""; const portOpt = js.port ? `-p ${js.port} ` : ""; const target = proxyQuote(js.user ? `${js.user}@${js.host}` : js.host); args.push("-o", `ProxyCommand=ssh ${hk}${keyOpt}${portOpt}-W %h:%p ${target}`); } - if (keyFile) args.push("-i", expandHomePath(keyFile)); + if (keyFile) args.push("-i", remote ? keyFile : expandHomePath(keyFile)); if (port) args.push("-p", String(port)); for (const f of forwards ?? []) { args.push(f.kind === "L" ? "-L" : f.kind === "R" ? "-R" : "-D", renderForwardArg(f)); @@ -208,11 +212,12 @@ function renderSshArgs(hop: SshHop, windowsProxy: boolean): string[] { /** PTY 内单行发送所需的引用形式。**单引号包裹**(GPT Astra 十二轮 #1:双引号 * 内 $()/反引号照常展开——且会让内层 ProxyCommand 的单引号防护失效,结构化 * jump.keyFile 的命令替换实测经此通道执行);白名单裸串零引用开销。 */ +function quoteSshShellArg(arg: string): string { + return /^[A-Za-z0-9_@:./%=-]+$/.test(arg) ? arg : shellQuote(arg); +} + export function sshArgsQuoted(hop: SshHop): string { - // This command is sent to a remote POSIX shell, independent of the local host. - return renderSshArgs(hop, false) - .map((a) => (/^[A-Za-z0-9_@:./%=-]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`)) - .join(" "); + return renderSshArgs(hop, false, true).map(quoteSshShellArg).join(" "); } /** `~` 展开——spawn 参数数组不经过 shell,tilde 不会被展开(生产实证:公钥认证被拒 exit 255) */ @@ -329,6 +334,10 @@ export function assertNoLikelyTypoKeys(config: Record | undefin * 渲染只含密钥/known_hosts **路径**,永不包含其内容(AC-12 无泄漏红线)。 */ export function autonomousSshOpts(conn?: SshConnParams): string[] { + return renderAutonomousSshOpts(conn, false); +} + +function renderAutonomousSshOpts(conn: SshConnParams | undefined, remote: boolean): string[] { // LogLevel=ERROR(第十二季 B 组实测):跳板 UserKnownHostsFile 变更产生的 // "Warning: Permanently added" 每次 run_command 重复灌 stderr——压到 ERROR 级 const opts = ["-o", "LogLevel=ERROR", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=3"]; @@ -340,7 +349,8 @@ export function autonomousSshOpts(conn?: SshConnParams): string[] { // 独立信任锚(Hydrogen R6 #2):knownHostsFile 与策略正交——tofu 模式下曾静默 // 忽略(指纹仍写宿主 ~/.ssh/known_hosts,隔离意图失效) if (conn?.knownHostsFile) { - opts.push("-o", `UserKnownHostsFile=${expandHomePath(conn.knownHostsFile)}`); + const file = remote ? conn.knownHostsFile : expandHomePath(conn.knownHostsFile); + opts.push("-o", knownHostsOption(file, !remote && process.platform === "win32")); } return opts; } @@ -389,7 +399,7 @@ export function rootSshSpawnArgs(destArgs: string[], conn?: SshConnParams): stri /** PTY 内 hop 登录命令(选项语义与 root 对齐) */ export function hopSshCommand(hop: SshHop): string { const conn = typeof hop === "object" ? hop.conn : undefined; - return `ssh ${autonomousSshOpts(conn).join(" ")} ${sshArgsQuoted(hop)}`; + return `ssh ${renderAutonomousSshOpts(conn, true).map(quoteSshShellArg).join(" ")} ${sshArgsQuoted(hop)}`; } /** 「等待输入」感知特征:ssh 停在交互提示(密码/口令/yes-no)——检测到即失败交还原文 */ @@ -610,3 +620,39 @@ export function renderExecChannel( } return { kind: "ok", remoteArgs, stdinCmd: payload }; } + +export type EnterBridgeCommandRender = + | { kind: "ok"; command: string } + | { kind: "unreachable"; reason: string; step: string }; + +/** + * 渲染穿层(enterPipeline)二进制安全的远端桥接命令: + * 逐层以 argv `-c` 包裹(绝不经 `sh -s` 消费 stdin),保证第 0 字节起即为干净双向 stdio 字节流。 + */ +export function renderEnterBridgeCommand(steps: EnterStep[], innerCommand: string): EnterBridgeCommandRender { + let current = innerCommand; + for (let i = steps.length - 1; i >= 0; i--) { + const raw = steps[i]!.cmd; + const trimmed = raw.trim(); + let tokens: string[]; + if (/^ssh(\s|$)/.test(trimmed)) { + const stripped = trimmed.replace(/(^|\s)-+(tt|t)\b/g, "$1").replace(/\s+/g, " ").trim(); + const parsed = tokenizeArgv(stripped); + if (!parsed.includes("-T")) parsed.splice(1, 0, "-T"); + tokens = [...parsed, "sh", "-c", current]; + } else { + const cleaned = trimmed.replace(/(^|\s)-(it|ti)\b/g, "$1-i").replace(/(^|\s)-t\b/g, "$1-i").trim(); + const m = SHELL_TAIL_RE.exec(cleaned); + if (!m) { + return { + kind: "unreachable", + reason: "进入命令无法非交互透传 stdio 桥接(既非「… bash/sh」结尾、也非「ssh <目标>」形态)", + step: raw, + }; + } + tokens = [...tokenizeArgv(cleaned), "-c", current]; + } + current = tokens.map(shellQuote).join(" "); + } + return { kind: "ok", command: current }; +} diff --git a/src/ssh-pty-driver.ts b/src/ssh-pty-driver.ts index f98920c..4f495b8 100644 --- a/src/ssh-pty-driver.ts +++ b/src/ssh-pty-driver.ts @@ -33,6 +33,7 @@ import { sshArgsFor, renderExecChannel, shellQuote, muxFlagsFor, assertNoLikelyTypoKeys, envPrefixOf, ENV_NAME_RE, type SshConnParams, type SshHop, ENTER_ALIAS_KEYS, } from "./ssh-helpers.js"; import { RemoteSessionManager } from "./remote-session-manager.js"; +import { SshForwardManager, type ForwardDeps, type OpenForwardSpec, type ForwardInfo, type CloseForwardResult } from "./ssh-forward.js"; import { probeDialect, type RemoteDialect } from "./dialect.js"; import { decodeFileRead, writeInplaceContent } from "./file-transfer.js"; import { buildPosixRenameCmd, buildPosixRmGuardCmd, throwRemoteFsCmdError } from "./file-placement.js"; @@ -423,6 +424,8 @@ export function resolveLayerState( export interface SshPtyDriverOptions { logger?: FilaxisLogger; + /** @internal 测试注入转发依赖 */ + _forwardDeps?: ForwardDeps; } /** SSH Transport driver:每层一条独立多跳 PTY + 双通道 exec + 远端会话/文件 */ @@ -447,6 +450,12 @@ export class SshPtyDriver implements RuntimeDriver { /** 在途重连定时器(Sol 88 P1-10):exit() 显式清——到期复查之外的双保险 */ private reconnectTimer: ReturnType | null = null; private readonly log: FilaxisLogger; + private readonly forwardDeps?: ForwardDeps; + private forwardManager?: SshForwardManager; + /** @internal 转发意外退出订阅集(供 RuntimeStack 桥接) */ + readonly forwardControl = { + subs: new Set<(info: ForwardInfo) => void>(), + }; private static readonly MAX_RECONNECT = 3; private static readonly RECONNECT_DELAYS_MS = [2_000, 5_000, 10_000]; @@ -459,6 +468,7 @@ export class SshPtyDriver implements RuntimeDriver { assertNoLikelyTypoKeys(descriptor.config as Record | undefined, "ssh 层配置"); this.descriptor = descriptor; this.log = opts.logger ?? noopLogger; + this.forwardDeps = opts._forwardDeps; const self = this; const fsExec = async (cmd: string) => self.execChannel(cmd, undefined); let writeDialect: Promise | undefined; @@ -745,6 +755,7 @@ export class SshPtyDriver implements RuntimeDriver { this.layerState = "dead"; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // 排程中的重连不再到期拉新进程(Sol 88 P1-10) this.link.kill(); + await this.forwardManager?.closeAll().catch(() => undefined); } async destroy(): Promise { await this.exit(); } @@ -1021,6 +1032,56 @@ export class SshPtyDriver implements RuntimeDriver { return this.sessions.verify(sessionId); } listSessions() { return this.sessions.list(); } + + // ── 动态端口转发(-L / -R / -D,REQ-0005)── + private ensureForwardManager(): SshForwardManager { + if (!this.forwardManager) { + const target = this.descriptor.target ?? ""; + const connParams = this.descriptor.config?.connParams as SshConnParams | undefined; + const rootHop: SshHop = connParams ? { host: target, conn: connParams } : target; + const tunnelHop: SshHop = connParams + ? { host: target, conn: { ...connParams, forwards: undefined } } + : target; + this.forwardManager = new SshForwardManager({ + destArgs: sshArgsFor(tunnelHop), + muxDestArgs: sshArgsFor(rootHop), + connParams, + enterSteps: enterStepsOf(this.descriptor.config as Record | undefined), + execInLayer: (cmd, execOpts) => this.exec(cmd, execOpts), + logger: this.log, + onForwardExit: (info) => { + for (const fn of this.forwardControl.subs) { + try { fn(info); } catch { /* 订阅方异常不外溢 */ } + } + }, + _deps: this.forwardDeps, + }); + } + return this.forwardManager; + } + + async openForward(spec: OpenForwardSpec): Promise { + if (this.useFileStdio) throw fileStdioUnsupported("动态端口转发"); + if (!this.alive || this.layerShellGone || this.reconnecting) { + throw new Error("SSH 层当前不可用,无法打开动态端口转发"); + } + const hops = this.descriptor.config?.sshHops; + if (Array.isArray(hops) && hops.length > 0) { + throw new Error("动态端口转发需要可直连或经 -J 跳板的 SSH 层,逐跳 PTY 登录链不可用"); + } + return this.ensureForwardManager().openForward(spec); + } + + async closeForward(forwardId: string): Promise { + if (!this.forwardManager) { + throw new Error(`转发 '${forwardId}' 不存在`); + } + return this.forwardManager.closeForward(forwardId); + } + + listForwards(): ForwardInfo[] { + return this.forwardManager ? this.forwardManager.listForwards() : []; + } } /** shell 单引号安全引用 */ diff --git a/src/stream-window.ts b/src/stream-window.ts index 8c02941..ea490af 100644 --- a/src/stream-window.ts +++ b/src/stream-window.ts @@ -143,19 +143,25 @@ export class StreamWindow { } /** 最近 n 帧 */ - peekLast(n = 20): PeekResult { + peekLast(n = 20, stream?: StreamFrame["stream"]): PeekResult { // n=0=显式请求零帧(Sol 五十二期 #3:Math.max(0,n) 后 slice(-0) 曾返回 // 全部帧)——0/负数返回空(与「无缓冲」一致) if (n <= 0) return this.snapshot([]); - return this.snapshot(this.frames.slice(-n)); + const frames = stream === undefined ? this.frames : this.frames.filter((f) => f.stream === stream); + return this.snapshot(frames.slice(-n)); } /** Return the most recent retained frames strictly before the cursor. */ - peekBefore(beforeSeq: number, n = 20): PeekResult { + peekBefore(beforeSeq: number, n = 20, stream?: StreamFrame["stream"]): PeekResult { if (n <= 0) return this.snapshot([]); - const result = this.snapshot(this.frames.filter((frame) => frame.seq < beforeSeq).slice(-n)); + const frames = this.frames + .filter((frame) => frame.seq < beforeSeq && (stream === undefined || frame.stream === stream)) + .slice(-n); + const result = this.snapshot(frames); const through = Math.min(beforeSeq - 1, this.allocated); - if (through > 0 && (!this.frames.length || this.oldestSeq > Math.max(1, through - n + 1))) result.gap = true; + const missingHistory = stream === undefined ? this.oldestSeq > Math.max(1, through - n + 1) + : frames.length < n && this.oldestSeq > 1; + if (through > 0 && (!this.frames.length || missingHistory)) result.gap = true; return result; } @@ -170,8 +176,10 @@ export class StreamWindow { * 增量断点续读:返回 > sinceSeq 的帧(上限 n 兜底)。 * 带 consumerId 时推进该消费者游标;中间覆盖(oldestSeq > sinceSeq+1)置 gap。 */ - peekSince(sinceSeq: number, n = 50, consumerId?: string): PeekResult { - const frames = this.frames.filter((f) => f.seq > sinceSeq).slice(0, Math.max(0, n)); + peekSince(sinceSeq: number, n = 50, consumerId?: string, stream?: StreamFrame["stream"]): PeekResult { + const frames = this.frames + .filter((f) => f.seq > sinceSeq && (stream === undefined || f.stream === stream)) + .slice(0, Math.max(0, n)); const result = this.snapshot(frames); result.lastDeliveredSeq = frames.length ? frames[frames.length - 1]!.seq : sinceSeq; // 空洞双形态(五十期 #1 补):①环形覆盖(oldestSeq > since+1)②游标超前 @@ -493,7 +501,7 @@ export class StreamWindowRegistry { const shell = opts.shell ?? this.shell; const supervised = this.spawnImpl ? undefined : startLocalObservation(shell, opts.command, opts.cwd); const child = supervised ? supervised.child : this.spawnImpl!(shell, ["-c", opts.command], { - cwd: opts.cwd, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", + cwd: opts.cwd, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, }); const push = (stream: "stdout" | "stderr", line: string) => { if (!opts.stream || opts.stream === "both" || opts.stream === stream) win.push(line, stream); diff --git a/src/terminal/command-executer.ts b/src/terminal/command-executer.ts index 52286e5..c288852 100644 --- a/src/terminal/command-executer.ts +++ b/src/terminal/command-executer.ts @@ -152,7 +152,7 @@ async function resolveExecutionPane(id: string): Promise { if (state.stdout.trim() !== `${panePid}\t1\t1`) { throw new CommandExecError(`tmux 窗格 '${target}' 无法确认由 Filaxis 独占且处于待命状态,请新建会话`); } - const { stdout: groups } = await execFileAsync("ps", ["-o", "pgid=,tpgid=", "-p", panePid]); + const { stdout: groups } = await execFileAsync("ps", ["-o", "pgid=,tpgid=", "-p", panePid], { windowsHide: true }); const [group, foreground] = groups.trim().split(/\s+/); if (!group || !/^[1-9]\d*$/.test(group) || group !== foreground) { throw new CommandExecError(`tmux 窗格 '${target}' 的前台正在被占用或无法核实,拒绝发送`); diff --git a/src/terminal/pane-output-observer.ts b/src/terminal/pane-output-observer.ts index 9d3d69c..553c94b 100644 --- a/src/terminal/pane-output-observer.ts +++ b/src/terminal/pane-output-observer.ts @@ -16,6 +16,7 @@ export async function observePaneOutput( ): Promise { const client = spawn("tmux", ["-C", "attach-session", "-Er", "-t", session], { stdio: ["pipe", "pipe", "ignore"], + windowsHide: true, }); // Latin-1 preserves byte values even when tmux splits a UTF-8 character across events. const lines = createInterface({ input: client.stdout.setEncoding("latin1"), crlfDelay: Infinity }); diff --git a/src/terminal/tmux-invoker.ts b/src/terminal/tmux-invoker.ts index 662775a..324123b 100644 --- a/src/terminal/tmux-invoker.ts +++ b/src/terminal/tmux-invoker.ts @@ -17,7 +17,7 @@ export class TmuxInvoker { let stdout = ""; let stderr = ""; let settled = false; - const p = spawn("tmux", args, { stdio: ["ignore", "pipe", "pipe"] }); + const p = spawn("tmux", args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); // StringDecoder 双流(Hydrogen R5 #4):跨块多字节 UTF-8 撕裂防护 const oDec = new StringDecoder("utf-8"); const eDec = new StringDecoder("utf-8"); diff --git a/tests/agent-toolkit.test.ts b/tests/agent-toolkit.test.ts index b3a8ba9..6782323 100644 --- a/tests/agent-toolkit.test.ts +++ b/tests/agent-toolkit.test.ts @@ -375,7 +375,7 @@ describe("三十五期", () => { describe("CLI observe 冒烟(正常路径)", () => { test("observe 端到端:启动→挂流→tail 输出报告", async () => { const { execSync } = await import("node:child_process"); - const r = execSync('bun bin/filaxis.ts observe --duration 800 -- "echo SELF_AUDIT_OK"', { encoding: "utf-8", timeout: 15_000 }); + const r = execSync('bun bin/filaxis.ts observe --duration 800 -- "echo SELF_AUDIT_OK"', { encoding: "utf-8", timeout: 15_000, windowsHide: true }); expect(r).toContain("SELF_AUDIT_OK"); }, 20_000); }); @@ -1634,7 +1634,7 @@ describe("audit regression fixes (P1/P2/P3)", () => { 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 proc = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe", windowsHide: true }); const [stdout, stderr, exitCode] = await Promise.all([ new Response(proc.stdout).text(), new Response(proc.stderr).text(), diff --git a/tests/batch.test.ts b/tests/batch.test.ts index 4305948..39a1ad6 100644 --- a/tests/batch.test.ts +++ b/tests/batch.test.ts @@ -185,7 +185,7 @@ describe("toolkit run_batch + CLI batch 冒烟", () => { { id: "r", kind: "read", path: p, after: ["e"] }, ], })); - const out = execSync(`bun bin/filaxis.ts batch --request-file "${plan}"`, { encoding: "utf-8" }); + const out = execSync(`bun bin/filaxis.ts batch --request-file "${plan}"`, { encoding: "utf-8", windowsHide: true }); expect(out).toContain("[ok] w (exec"); expect(out).toContain("替换 1 处"); expect(out).toContain("[ok] r (read"); @@ -200,7 +200,7 @@ describe("toolkit run_batch + CLI batch 冒烟", () => { })); let errOut = ""; try { - execSync(`bun bin/filaxis.ts batch --request-file "${plan2}"`, { encoding: "utf-8", stdio: "pipe" }); + execSync(`bun bin/filaxis.ts batch --request-file "${plan2}"`, { encoding: "utf-8", stdio: "pipe", windowsHide: true }); } catch (e) { errOut = String((e as { stdout?: string }).stdout ?? ""); } diff --git a/tests/cli-help.test.ts b/tests/cli-help.test.ts index 1f5e91f..ec9c6ab 100644 --- a/tests/cli-help.test.ts +++ b/tests/cli-help.test.ts @@ -12,8 +12,11 @@ test.each([ ["filaxis put", ["put", "--help"]], ["filaxis get", ["get", "--help"]], ["filaxis mcp-config", ["mcp-config", "--help"]], + ["filaxis daemon", ["daemon", "--help"]], + ["filaxis forward", ["forward", "--help"]], + ["filaxis stream", ["stream", "--help"]], ])("CLI help includes %s and exits successfully (%j)", (usage, args) => { - const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", ...args], { stderr: "pipe" }); + const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", ...args], { stderr: "pipe", windowsHide: true }); expect(result.exitCode).toBe(0); expect(result.stdout.toString()).toContain(usage); expect(result.stderr.toString()).toBe(""); @@ -27,14 +30,57 @@ test.each([ ["unsupported channel", ["--pty"], "batch 不支持 --pty"], ])("CLI batch rejects %s before running the plan", (_case, args, error) => { const input = JSON.stringify({ steps: [{ id: "probe", kind: "exec", command: "printf SHOULD_NOT_RUN" }] }); - const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "batch", ...args, "--stdin-json"], { stdin: Buffer.from(input), stderr: "pipe" }); + const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "batch", ...args, "--stdin-json"], { stdin: Buffer.from(input), stderr: "pipe", windowsHide: true }); expect(result.exitCode).toBe(1); expect(result.stdout.toString()).toBe(""); expect(result.stderr.toString()).toContain(error); }); +test.each([ + [["daemon", "stop", "unexpected"], "daemon stop 不接受位置参数"], + [["forward", "remove", "first", "second"], "forward remove 需要且只接受一个 forward_id"], + [["forward", "list", "unexpected"], "forward list 不接受位置参数"], + [["stream", "close", "first", "second"], "stream close 需要且只接受一个 window_id"], + [["stream", "peek", "first", "second"], "stream peek 需要且只接受一个 window_id"], + [["stream", "list", "unexpected"], "stream list 不接受位置参数"], +])("CLI rejects unused Daemon command arguments (%j)", (args, error) => { + const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", ...args], { stderr: "pipe", windowsHide: true }); + expect(result.exitCode).toBe(1); + expect(result.stdout.toString()).toBe(""); + expect(result.stderr.toString()).toContain(error); +}); + +test.each([ + [["exec", "--no-daemon", "--script-file"], "--script-file 需要参数值"], + [["exec", "--script-file", "--no-daemon", "--", "printf SHOULD_NOT_RUN"], "--script-file 需要参数值"], + [["exec", "--stdin-script", "--script-file", "fixture.sh"], "--stdin-script 与 --script-file 二选一"], + [["exec", "--timeout", "500ms", "--", "printf SHOULD_NOT_RUN"], "--timeout 需要一个正数字"], + [["exec", "--no-daemon", "--port", "2222", "--", "printf SHOULD_NOT_RUN"], "SSH 连接参数需要 --host"], + [["exec", "--layer", "fixture", "--key", "identity", "--", "printf SHOULD_NOT_RUN"], "SSH 连接参数需要 --host"], + [["observe", "--stream", "out", "--", "printf SHOULD_NOT_RUN"], "--stream 仅接受 stdout"], +])("CLI rejects ambiguous execution parameters (%j)", (args, error) => { + const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", ...args], { stderr: "pipe", windowsHide: true }); + expect(result.exitCode).toBe(1); + expect(result.stdout.toString()).toBe(""); + expect(result.stderr.toString()).toContain(error); +}); + +test.each([ + [["--layer"], "--layer 需要参数值"], + [["--layer", "--no-daemon"], "--layer 需要参数值"], + [["--host", "fixture.invalid", "--key", "--no-daemon"], "--key 需要参数值"], +])("MCP launcher rejects missing option values before defaulting to a target (%j)", (args, error) => { + const result = Bun.spawnSync([process.execPath, "bin/filaxis-mcp.ts", ...args], { + stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), + stderr: "pipe", windowsHide: true, + }); + expect(result.exitCode).toBe(2); + expect(result.stdout.toString()).toBe(""); + expect(result.stderr.toString()).toContain(error); +}); + test("CLI treats --help after -- as command data", () => { - const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "exec", "--", "printf '%s' --help"], { stderr: "pipe" }); + const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "exec", "--", "printf '%s' --help"], { stderr: "pipe", windowsHide: true }); expect(result.exitCode).toBe(0); expect(result.stdout.toString()).toBe("--help"); }); diff --git a/tests/daemon.test.ts b/tests/daemon.test.ts new file mode 100644 index 0000000..eaadd2b --- /dev/null +++ b/tests/daemon.test.ts @@ -0,0 +1,1100 @@ +/** + * daemon.test.ts — 显式常驻 Daemon、鉴权文件锁、RPC 共享现场与 CLI 端到端测试(REQ-0005 Phase 2) + */ +import { describe, expect, test } from "bun:test"; +import { EventEmitter } from "node:events"; +import { spawn, type ChildProcess } from "node:child_process"; +import * as http from "node:http"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve as resolvePath } from "node:path"; +import { PassThrough } from "node:stream"; +import { + acquireDaemonLock, + cleanupDaemonFiles, + DaemonClient, + DaemonServer, + daemonPaths, + generateDaemonToken, + LocalRuntimeDriver, + parseAddrToUrl, + probeDaemon, + readDaemonConnection, + SshPtyDriver, + spawnDaemonBackground, + StreamWindowRegistry, + urlRequestPort, + verifyBearerToken, + writePrivateFileAtomic, +} from "../src/index.js"; + +class MockChild extends EventEmitter { + stdout = new PassThrough(); + stderr = new PassThrough(); + pid = 51515; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + signals: NodeJS.Signals[] = []; + + kill(signal: NodeJS.Signals = "SIGTERM"): boolean { + this.signals.push(signal); + if (signal === "SIGTERM") { + this.exitCode = 0; + this.signalCode = "SIGTERM"; + this.emit("exit", 0, "SIGTERM"); + this.emit("close", 0, "SIGTERM"); + } + return true; + } +} + +function makeTempDir(prefix: string): string { + return mkdtempSync(join(tmpdir(), prefix)); +} + +function runCli(args: string[], daemonDir: string) { + return Bun.spawnSync([process.execPath, "bin/filaxis.ts", ...args], { + stdout: "pipe", + stderr: "pipe", + windowsHide: true, + env: { ...process.env, FILAXIS_DAEMON_DIR: daemonDir }, + }); +} + +function runCliAsync(args: string[], daemonDir: string, options: { cwd?: string; layers?: string } = {}) { + return new Promise<{ exitCode: number | null; stdout: string; stderr: string }>((resolve, reject) => { + const child = spawn(process.execPath, [resolvePath("bin/filaxis.ts"), ...args], { + stdio: ["ignore", "pipe", "pipe"], windowsHide: true, + cwd: options.cwd, + env: { + ...process.env, + FILAXIS_DAEMON_DIR: daemonDir, + ...(options.layers ? { FILAXIS_LAYERS: options.layers } : {}), + }, + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk: string) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { stderr += chunk; }); + child.once("error", reject); + child.once("close", (exitCode) => resolve({ exitCode, stdout, stderr })); + }); +} + +describe("daemon-files lock & token", () => { + test("enforces single-instance PID lock and reclaims stale dead-PID lock", () => { + const dir = makeTempDir("fx-daemon-lock-"); + try { + const rec = acquireDaemonLock(dir, "0.2.11"); + expect(rec.pid).toBe(process.pid); + expect(() => acquireDaemonLock(dir, "0.2.11")).toThrow(/已在运行/); + + const { lockFile } = daemonPaths(dir); + writeFileSync(lockFile, JSON.stringify({ pid: 999_999_99, startedAt: 1, version: "0.0.0" })); + const reclaimed = acquireDaemonLock(dir, "0.2.11"); + expect(reclaimed.pid).toBe(process.pid); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("generates 32-byte hex token and verifies Bearer case-insensitively", () => { + const dir = makeTempDir("fx-daemon-tok-"); + try { + const token = generateDaemonToken(); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(verifyBearerToken(`Bearer ${token}`, token)).toBe(true); + expect(verifyBearerToken(`bearer ${token}`, token)).toBe(true); + expect(verifyBearerToken(`Bearer ${"0".repeat(64)}`, token)).toBe(false); + expect(verifyBearerToken(undefined, token)).toBe(false); + expect(verifyBearerToken(`Basic ${token}`, token)).toBe(false); + + const { tokenFile } = daemonPaths(dir); + writePrivateFileAtomic(tokenFile, token); + expect(readFileSync(tokenFile, "utf-8")).toBe(token); + if (process.platform !== "win32") { + expect(statSync(tokenFile).mode & 0o777).toBe(0o600); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("DaemonServer & DaemonClient RPC", () => { + test("passes client-relative SSH files to the daemon for explicit hosts and saved layers", async () => { + const dir = makeTempDir("fx-daemon-ssh-paths-"); + const cwd = join(dir, "client"); + const layers = join(dir, "layers.json"); + mkdirSync(cwd); + writeFileSync(layers, JSON.stringify({ + fixture: { + driver: "ssh", target: "fixture.invalid", + config: { + connParams: { keyFile: "~/fixture-key", knownHostsFile: "hosts", jump: { host: "jump.invalid", keyFile: "jump-key" } }, + sshHops: [{ host: "inner.invalid", conn: { keyFile: "inner-key" } }], + }, + }, + })); + const plan = join(dir, "plan.json"); + writeFileSync(plan, JSON.stringify({ layer: "fixture", steps: [{ id: "fixture", kind: "exec", command: "fixture" }] })); + const requests: unknown[] = []; + const stub = http.createServer(async (req, res) => { + let result: Record = {}; + if (req.method === "POST") { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk); + const request = JSON.parse(Buffer.concat(chunks).toString("utf8")); + requests.push(request); + result = request.method === "batch" + ? { status: "ok", steps: [] } + : { stdout: "", stderr: "", exitCode: 0 }; + } + res.end(JSON.stringify({ ok: true, result })); + }); + try { + await new Promise((resolve) => stub.listen(0, "127.0.0.1", resolve)); + const { addrFile, tokenFile } = daemonPaths(dir); + writePrivateFileAtomic(addrFile, `127.0.0.1:${(stub.address() as { port: number }).port}`); + writePrivateFileAtomic(tokenFile, "fixture"); + const opts = { cwd, layers }; + const direct = await runCliAsync([ + "exec", "--host", "fixture.invalid", "--key", "key", "--known-hosts", "hosts", "--", "fixture", + ], dir, opts); + expect(direct.exitCode).toBe(0); + expect((await runCliAsync(["exec", "--layer", "fixture", "--", "fixture"], dir, opts)).exitCode).toBe(0); + expect((await runCliAsync(["batch", "--request-file", plan], dir, opts)).exitCode).toBe(0); + + const savedConfig = { + connParams: { + keyFile: "~/fixture-key", + knownHostsFile: join(cwd, "hosts"), + jump: { host: "jump.invalid", keyFile: join(cwd, "jump-key") }, + }, + sshHops: [{ host: "inner.invalid", conn: { keyFile: "inner-key" } }], + }; + expect(requests).toMatchObject([ + { method: "exec", params: { target: { descriptor: { config: { connParams: { + keyFile: join(cwd, "key"), knownHostsFile: join(cwd, "hosts"), + } } } } } }, + { method: "exec", params: { target: { layer: "fixture", descriptor: { config: savedConfig } } } }, + { method: "batch", params: { savedLayers: { fixture: { config: savedConfig } } } }, + ]); + } finally { + await new Promise((resolve) => stub.close(() => resolve())); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("returns an explicit HTTP 413 for an oversized RPC body and stays available", async () => { + const srv = new DaemonServer({ writeFiles: false }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + const rejection = client.rpc("cat", { path: "x".repeat(17 * 1024 * 1024) }, 5_000); + await expect(rejection).rejects.toMatchObject({ statusCode: 413, message: expect.stringContaining("请求体超过限制") }); + await expect(rejection).rejects.not.toHaveProperty("outcome"); + expect(await client.health()).toBe(true); + } finally { + await srv.stop(); + } + }); + + test("shares a pending listen and does not reopen a stopped server instance", async () => { + const srv = new DaemonServer({ writeFiles: false }); + const starting = srv.start(); + const secondStart = srv.start(); + const stopping = srv.stop(); + const [addr, secondAddr] = await Promise.all([starting, secondStart, stopping]); + expect(secondAddr).toBe(addr); + await expect(srv.start()).rejects.toThrow(/已停止或正在停止/); + const client = new DaemonClient({ addr, token: srv.token }); + expect(await client.health()).toBe(false); + }); + + test("background launch rejects an already-running daemon instead of returning its PID as a new launch", async () => { + const dir = makeTempDir("fx-daemon-existing-start-"); + const srv = new DaemonServer({ daemonDir: dir }); + try { + const addr = await srv.start(); + await expect(spawnDaemonBackground({ + daemonDir: dir, + cliEntryPath: resolvePath("bin/filaxis.ts"), + })).rejects.toThrow(/Daemon 已在运行/); + expect((await new DaemonClient({ addr, token: srv.token }).status()).pid).toBe(process.pid); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("enforces Bearer auth (401) on protected endpoints while allowing /health", async () => { + const dir = makeTempDir("fx-daemon-auth-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + const unauth = await fetch(`${addr}/status`); + expect(unauth.status).toBe(401); + + const wrongRpc = await fetch(`${addr}/rpc`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: "Bearer wrong" }, + body: JSON.stringify({ method: "status" }), + }); + expect(wrongRpc.status).toBe(401); + + const health = await fetch(`${addr}/health`); + expect(health.status).toBe(200); + expect(await health.json()).toEqual({ ok: true }); + + const client = await probeDaemon(dir); + expect(client).not.toBeNull(); + const status = await client!.status(); + expect(status.pid).toBe(process.pid); + expect(status.addr).toBe(addr); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("executes exec/cat/edit and cross-call stream open/peek/list/close", async () => { + const dir = makeTempDir("fx-daemon-rpc-"); + const work = makeTempDir("fx-daemon-work-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + + const targetFile = join(work, "sample.txt"); + writeFileSync(targetFile, "hello old world\n", "utf-8"); + + const catRes = await client.rpc<{ content: string }>("cat", { path: "sample.txt", target: { cwd: work } }); + expect(catRes.content).toBe("hello old world\n"); + + const editRes = await client.rpc<{ occurrences: number }>("edit", { + path: targetFile, + old: "old", + new: "new", + }); + expect(editRes.occurrences).toBe(1); + expect(readFileSync(targetFile, "utf-8")).toBe("hello new world\n"); + + const execRes = await client.rpc<{ stdout: string; exitCode: number }>("exec", { + command: "printf 'daemon-exec-ok'", + }); + expect(execRes.exitCode).toBe(0); + expect(execRes.stdout).toBe("daemon-exec-ok"); + + const opened = await client.rpc<{ + window_id: string; + frames: Array<{ seq: number; text: string }>; + last_delivered_seq?: number; + }>("stream.open", { + command: "printf 'line1\\n'; sleep 0.2; printf 'line2\\n'", + waitMs: 2000, + limit: 20, + }); + expect(opened.window_id).toBeTruthy(); + + const listRes = await client.rpc<{ streams: Array<{ window_id: string }> }>("stream.list"); + expect(listRes.streams.some((s) => s.window_id === opened.window_id)).toBe(true); + + let cursor = opened.last_delivered_seq ?? 0; + const collected = opened.frames.map((f) => f.text); + const deadline = Date.now() + 4000; + while (collected.length < 2 && Date.now() < deadline) { + const peek = await client.rpc<{ + frames: Array<{ seq: number; text: string }>; + last_delivered_seq?: number; + }>("stream.peek", { windowId: opened.window_id, afterSeq: cursor, waitMs: 500 }); + for (const f of peek.frames) collected.push(f.text); + cursor = peek.last_delivered_seq ?? cursor; + } + expect(collected).toEqual(["line1", "line2"]); + + const closed = await client.rpc<{ closed: boolean }>("stream.close", { windowId: opened.window_id }); + expect(closed.closed).toBe(true); + await expect(client.rpc("stream.peek", { windowId: opened.window_id })).rejects.toThrow(/不存在或已关闭/); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + rmSync(work, { recursive: true, force: true }); + } + }, 15_000); + + test("paginates and waits on the selected stream and retains the stale stream error", async () => { + const observer = new MockChild(); + const spawnFixture = (() => observer) as unknown as typeof spawn; + const registry = new StreamWindowRegistry({ shell: "fixture", spawnImpl: spawnFixture }); + const srv = new DaemonServer({ writeFiles: false, windowRegistry: registry }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + const win = await registry.open({ name: "mixed", command: "fixture" }); + win.push("out-1", "stdout"); + win.push("err-2", "stderr"); + win.push("out-3", "stdout"); + const peek = (cursors: Record = {}) => client.rpc("stream.peek", { + windowId: win.name, limit: 1, stream: "stderr", ...cursors, + }, 8_000); + const frames = [{ seq: 2, text: "err-2", stream: "stderr" }]; + await expect(peek()).resolves.toMatchObject({ frames }); + await expect(peek({ beforeSeq: 4 })).resolves.toMatchObject({ frames }); + await expect(peek({ afterSeq: 0 })).resolves.toMatchObject({ frames, last_delivered_seq: 2 }); + let readStarted!: () => void; + const firstRead = new Promise((resolve) => { readStarted = resolve; }); + const peekSince = win.peekSince.bind(win); + win.peekSince = (...args) => { + const result = peekSince(...args); + readStarted(); + return result; + }; + const waiting = peek({ afterSeq: 2, waitMs: 5_000 }); + await Promise.race([firstRead, waiting]); + win.push("err-4", "stderr"); + await expect(waiting).resolves.toMatchObject({ + frames: [{ seq: 4, text: "err-4", stream: "stderr" }], last_delivered_seq: 4, + }); + + observer.kill("SIGTERM"); + win.markStale(null, "fixture connection closed"); + await expect(peek()).resolves.toMatchObject({ + stale: true, error: "fixture connection closed", frames: [{ seq: 4, text: "err-4" }], + }); + } finally { + if (observer.exitCode === null) observer.kill("SIGTERM"); + await srv.stop(); + } + }, 15_000); + + test("forward remove exits unsuccessfully when the forward could not be confirmed closed", async () => { + const dir = makeTempDir("fx-daemon-forward-unknown-"); + const srv = new DaemonServer({ daemonDir: dir }); + try { + await srv.start(); + const driver = new SshPtyDriver({ driver: "ssh", target: "fixture.invalid" }); + driver.closeForward = async (forwardId) => ({ forwardId, status: "unknown", detail: "fixture unverified" }); + await srv.stack.addLayer("fixture", driver); + const removed = await runCliAsync(["forward", "remove", "fwd-id", "--layer", "fixture", "--json"], dir); + expect(removed.exitCode).toBe(1); + expect(JSON.parse(removed.stdout)).toEqual({ forwardId: "fwd-id", status: "unknown", detail: "fixture unverified" }); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("manages forward.add / forward.list / forward.remove via Daemon RPC and cleans up on stop", async () => { + const srv = new DaemonServer({ writeFiles: false, version: "test" }); + let childRef!: MockChild; + try { + const addr = await srv.start(); + const sshDriver = new SshPtyDriver({ driver: "ssh", target: "ops@example.com" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + childRef = new MockChild(); + setTimeout(() => { + childRef.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 18080.\ndebug1: Entering interactive session.\n"); + }, 5); + return childRef as unknown as ChildProcess; + }, + }, + }); + await srv.stack.addLayer("prod", sshDriver); + + const client = new DaemonClient({ addr, token: srv.token }); + const added = await client.rpc<{ forwardId: string; bindPort: number; layer: string }>("forward.add", { + target: { layer: "prod" }, + spec: { id: "db-fwd", kind: "L", bindPort: 18080, targetHost: "127.0.0.1", targetPort: 5432 }, + }); + expect(added.forwardId).toBe("db-fwd"); + expect(added.layer).toBe("prod"); + expect(added.bindPort).toBe(18080); + + const list = await client.rpc<{ forwards: Array<{ forwardId: string }> }>("forward.list", { layer: "prod" }); + expect(list.forwards.map((f) => f.forwardId)).toEqual(["db-fwd"]); + + const removed = await client.rpc<{ status: string }>("forward.remove", { forwardId: "db-fwd", layer: "prod" }); + expect(removed.status).toBe("stopped"); + expect(childRef.signals).toContain("SIGTERM"); + + await client.rpc("forward.add", { + target: { layer: "prod" }, + spec: { id: "detached", kind: "L", bindPort: 18080, targetHost: "127.0.0.1", targetPort: 5432 }, + }); + await client.rpc("layer.remove", { name: "prod" }); + expect(srv.stack.layers.has("prod")).toBe(false); + const detached = await client.rpc<{ forwards: Array<{ forwardId: string; layer?: string }> }>("forward.list"); + expect(detached.forwards.map((f) => f.forwardId)).toEqual(["detached"]); + expect(detached.forwards[0]).not.toHaveProperty("layer"); + expect(childRef.signals).toEqual([]); + await srv.stop(); + expect(childRef.signals).toContain("SIGTERM"); + } finally { + await srv.stop(); + } + }, 15_000); + + test("stops a forward still being established on an unnamed driver during shutdown", async () => { + const srv = new DaemonServer({ writeFiles: false }); + let started!: () => void; + const childStarted = new Promise((resolve) => { started = resolve; }); + const child = new MockChild(); + const driver = new SshPtyDriver({ driver: "ssh", target: "fixture.invalid" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { started(); return child as unknown as ChildProcess; }, + }, + }); + try { + await srv.start(); + await srv.stack.addLayer("pending", driver); + const opening = srv.stack.openForward({ + id: "pending", kind: "L", bindPort: 18101, targetHost: "127.0.0.1", targetPort: 8080, + }); + void opening.catch(() => undefined); + await childStarted; + await srv.stack.removeLayer("pending"); + await srv.stop(); + expect(child.signals).toContain("SIGTERM"); + await expect(opening).rejects.toThrow(); + } finally { + await srv.stop(); + await driver.destroy(); + } + }, 15_000); +}); + +describe("CLI daemon / forward / stream E2E", () => { + test("never spawns daemon implicitly and errors cleanly on forward/stream without daemon", () => { + const dir = makeTempDir("fx-cli-nod-"); + try { + const execRes = runCli(["exec", "--", "printf 'single-shot'"], dir); + expect(execRes.exitCode).toBe(0); + expect(execRes.stdout.toString()).toBe("single-shot"); + const { lockFile, addrFile, tokenFile } = daemonPaths(dir); + expect(existsSync(lockFile)).toBe(false); + expect(existsSync(addrFile)).toBe(false); + expect(existsSync(tokenFile)).toBe(false); + + const fwdRes = runCli(["forward", "list"], dir); + expect(fwdRes.exitCode).toBe(1); + expect(fwdRes.stderr.toString()).toContain("filaxis daemon start"); + + const streamRes = runCli(["stream", "peek", "win-1"], dir); + expect(streamRes.exitCode).toBe(1); + expect(streamRes.stderr.toString()).toContain("filaxis daemon start"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 20_000); + + test("supports explicit daemon start -> status -> exec/no-daemon -> stream -> stop", () => { + const dir = makeTempDir("fx-cli-e2e-"); + mkdirSync(dir, { recursive: true }); + try { + const startRes = runCli(["daemon", "start", "--json"], dir); + expect(startRes.exitCode).toBe(0); + const startJson = JSON.parse(startRes.stdout.toString()) as { running: boolean; pid: number; addr: string }; + expect(startJson.running).toBe(true); + expect(startJson.pid).toBeGreaterThan(0); + + const statusRes = runCli(["daemon", "status", "--json"], dir); + expect(statusRes.exitCode).toBe(0); + const statusJson = JSON.parse(statusRes.stdout.toString()) as { running: boolean; pid: number }; + expect(statusJson.running).toBe(true); + expect(statusJson.pid).toBe(startJson.pid); + + const execViaDaemon = runCli(["exec", "--", "printf 'via-daemon'"], dir); + expect(execViaDaemon.exitCode).toBe(0); + expect(execViaDaemon.stdout.toString()).toBe("via-daemon"); + + const execBypass = runCli(["exec", "--no-daemon", "--", "printf 'bypass-daemon'"], dir); + expect(execBypass.exitCode).toBe(0); + expect(execBypass.stdout.toString()).toBe("bypass-daemon"); + + const openRes = runCli(["stream", "open", "--wait", "2000", "--json", "--", "printf 's1\\ns2\\n'"], dir); + expect(openRes.exitCode).toBe(0); + const openJson = JSON.parse(openRes.stdout.toString()) as { + window_id: string; + frames: Array<{ seq: number; text: string }>; + last_delivered_seq?: number; + }; + expect(openJson.window_id).toBeTruthy(); + + const peekRes = runCli(["stream", "peek", openJson.window_id, "--after", "0", "--wait", "2000", "--json"], dir); + expect(peekRes.exitCode).toBe(0); + const peekJson = JSON.parse(peekRes.stdout.toString()) as { frames: Array<{ text: string }> }; + expect(peekJson.frames.map((f) => f.text)).toEqual(["s1", "s2"]); + + const closeRes = runCli(["stream", "close", openJson.window_id, "--json"], dir); + expect(closeRes.exitCode).toBe(0); + + const stopRes = runCli(["daemon", "stop", "--json"], dir); + expect(stopRes.exitCode).toBe(0); + const stopJson = JSON.parse(stopRes.stdout.toString()) as { stopped: boolean }; + expect(stopJson.stopped).toBe(true); + + expect(readDaemonConnection(dir)).toBeNull(); + const afterStop = runCli(["daemon", "status", "--json"], dir); + expect(afterStop.exitCode).toBe(1); + } finally { + try { + const conn = readDaemonConnection(dir); + if (conn?.lock?.pid) { + try { process.kill(conn.lock.pid, "SIGTERM"); } catch { /* ignore */ } + } + cleanupDaemonFiles(dir); + } catch { /* ignore */ } + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); + + test("enforces loopback bind, deduplicates concurrent first local exec, and honors target.cwd in batch/stream", async () => { + const dir = makeTempDir("fx-daemon-hardening-"); + const work = makeTempDir("fx-daemon-cwd-"); + expect(() => new DaemonServer({ daemonDir: dir, host: "0.0.0.0" })).toThrow(/仅允许绑定本地回环/); + + writeFileSync(join(work, "cwd-marker.txt"), "hello-cwd", "utf-8"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + + // Concurrent first requests to local layer must not collide in RuntimeStack.addLayer + const [e1, e2] = await Promise.all([ + client.rpc<{ stdout: string; exitCode: number }>("exec", { command: "printf 'c1'" }), + client.rpc<{ stdout: string; exitCode: number }>("exec", { command: "printf 'c2'" }), + ]); + expect(e1.stdout).toBe("c1"); + expect(e2.stdout).toBe("c2"); + + // batch honors client target.cwd for relative paths + const batchRes = await client.rpc<{ status: string; steps: Array<{ stdout?: string }> }>("batch", { + target: { descriptor: { driver: "local" }, cwd: work }, + plan: { steps: [{ id: "r1", kind: "read", path: "cwd-marker.txt" }] }, + }); + expect(batchRes.status).toBe("ok"); + expect(batchRes.steps[0]?.stdout).toBe("hello-cwd"); + + // stream.open honors client target.cwd + const stRes = await client.rpc<{ window_id: string; frames: Array<{ text: string }> }>("stream.open", { + target: { descriptor: { driver: "local" }, cwd: work }, + command: "cat cwd-marker.txt", + waitMs: 2000, + }); + expect(stRes.frames.map((f) => f.text)).toContain("hello-cwd"); + await client.rpc("stream.close", { windowId: stRes.window_id }); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + rmSync(work, { recursive: true, force: true }); + } + }, 15_000); + + test("CLI forward add accepts omitted bindPort (-L host:port, -D with no port) and rejects invalid specs", async () => { + const dir = makeTempDir("fx-cli-fwd-omit-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + await srv.start(); + const sshDriver = new SshPtyDriver({ driver: "ssh", target: "ops@example.com" }, { + _forwardDeps: { + muxControlPath: () => undefined, + allocateLocalPort: async () => 54321, + spawnSsh: () => { + const child = new MockChild(); + setTimeout(() => { + child.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 54321.\ndebug1: Entering interactive session.\n"); + }, 5); + return child as unknown as ChildProcess; + }, + }, + }); + await srv.stack.addLayer("prod", sshDriver); + + const okL = await runCliAsync(["forward", "add", "--layer", "prod", "-L", "127.0.0.1:5432", "--json"], dir); + expect(okL.exitCode).toBe(0); + const infoL = JSON.parse(okL.stdout) as { kind: string; bindPort: number; targetHost: string; targetPort: number }; + expect(infoL).toMatchObject({ kind: "local", bindPort: 54321, targetHost: "127.0.0.1", targetPort: 5432 }); + + const okD = await runCliAsync(["forward", "add", "--layer", "prod", "-D", "--json"], dir); + expect(okD.exitCode).toBe(0); + const infoD = JSON.parse(okD.stdout) as { kind: string; bindPort: number }; + expect(infoD).toMatchObject({ kind: "dynamic", bindPort: 54321 }); + + const badD = await runCliAsync(["forward", "add", "--layer", "prod", "-D", "-1"], dir); + expect(badD.exitCode).toBe(1); + expect(badD.stderr).toContain("端口"); + + const badAuto = await runCliAsync(["forward", "add", "--layer", "prod", "-L", "auto:127.0.0.1:5432"], dir); + expect(badAuto.exitCode).toBe(1); + expect(badAuto.stderr).toContain("端口必须是数字"); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 30_000); + + test("resolves relative batch localPath against CLI caller cwd rather than daemon cwd for put and get", async () => { + const daemonDir = makeTempDir("fx-daemon-batch-dir-"); + const daemonCwd = makeTempDir("fx-daemon-cwd-b-"); + const callerCwd = makeTempDir("fx-caller-cwd-b-"); + const remoteDir = makeTempDir("fx-remote-cwd-b-"); + writeFileSync(join(daemonCwd, "input.txt"), "FROM_DAEMON_CWD", "utf-8"); + writeFileSync(join(callerCwd, "input.txt"), "FROM_CALLER_CWD", "utf-8"); + + const cliEntry = resolvePath("bin/filaxis.ts"); + const fgChild = spawn(process.execPath, [cliEntry, "daemon", "start", "--foreground", "--daemon-dir", daemonDir], { + cwd: daemonCwd, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + env: { ...process.env, FILAXIS_DAEMON_DIR: daemonDir }, + }); + try { + let client: DaemonClient | null = null; + const deadline = Date.now() + 10_000; + while (Date.now() < deadline && !client) { + client = await probeDaemon(daemonDir, 300); + if (!client) await new Promise((r) => setTimeout(r, 80)); + } + expect(client).not.toBeNull(); + + const remoteTarget = join(remoteDir, "uploaded.txt").replace(/\\/g, "/"); + const planFile = join(callerCwd, "plan.json"); + writeFileSync(planFile, JSON.stringify({ + steps: [ + { id: "up", kind: "put", localPath: "input.txt", remotePath: remoteTarget }, + { id: "down", kind: "get", localPath: "downloaded.txt", remotePath: remoteTarget, after: ["up"] }, + ], + }), "utf-8"); + + const batchRes = await new Promise<{ exitCode: number | null; stdout: string; stderr: string }>((resolve, reject) => { + const c = spawn(process.execPath, [cliEntry, "batch", "--daemon-dir", daemonDir, "--request-file", "plan.json"], { + cwd: callerCwd, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + env: { ...process.env, FILAXIS_DAEMON_DIR: daemonDir }, + }); + let stdout = ""; + let stderr = ""; + c.stdout.on("data", (d: Buffer) => { stdout += d.toString("utf-8"); }); + c.stderr.on("data", (d: Buffer) => { stderr += d.toString("utf-8"); }); + c.once("error", reject); + c.once("close", (exitCode) => resolve({ exitCode, stdout, stderr })); + }); + expect(batchRes.exitCode).toBe(0); + expect(readFileSync(join(remoteDir, "uploaded.txt"), "utf-8")).toBe("FROM_CALLER_CWD"); + expect(readFileSync(join(callerCwd, "downloaded.txt"), "utf-8")).toBe("FROM_CALLER_CWD"); + expect(existsSync(join(daemonCwd, "downloaded.txt"))).toBe(false); + } finally { + try { fgChild.kill("SIGTERM"); } catch { /* ignore */ } + await new Promise((r) => setTimeout(r, 150)); + cleanupDaemonFiles(daemonDir); + rmSync(daemonDir, { recursive: true, force: true }); + rmSync(daemonCwd, { recursive: true, force: true }); + rmSync(callerCwd, { recursive: true, force: true }); + rmSync(remoteDir, { recursive: true, force: true }); + } + }, 30_000); + + test("updates cached named layer when saved descriptor changes and rejects conflict with active forward", async () => { + const dir = makeTempDir("fx-daemon-layer-upd-"); + const dirA = makeTempDir("fx-layer-a-"); + const dirB = makeTempDir("fx-layer-b-"); + writeFileSync(join(dirA, "marker.txt"), "from-A", "utf-8"); + writeFileSync(join(dirB, "marker.txt"), "from-B", "utf-8"); + + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + + // 1) Initial named layer points to dirA + const c1 = await client.rpc<{ content: string }>("cat", { + target: { layer: "app", descriptor: { driver: "local", cwd: dirA } }, + path: "marker.txt", + }); + expect(c1.content).toBe("from-A"); + + // 2) Updated descriptor points to dirB -> Daemon replaces stale layer handle + const c2 = await client.rpc<{ content: string }>("cat", { + target: { layer: "app", descriptor: { driver: "local", cwd: dirB } }, + path: "marker.txt", + }); + expect(c2.content).toBe("from-B"); + + // 3) batch savedLayers also honors updated descriptor for an already-cached layer + const b1 = await client.rpc<{ status: string; steps: Array<{ stdout?: string }> }>("batch", { + savedLayers: { app: { driver: "local", cwd: dirA } }, + plan: { steps: [{ id: "r", kind: "read", layer: "app", path: "marker.txt" }] }, + }); + expect(b1.status).toBe("ok"); + expect(b1.steps[0]?.stdout).toBe("from-A"); + + // 4) Pending and confirmed forwards both keep their layer addressable. + let childStarted!: (child: MockChild) => void; + const started = new Promise((resolve) => { childStarted = resolve; }); + const sshOld = new SshPtyDriver({ driver: "ssh", target: "ops@old.example" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const c = new MockChild(); + childStarted(c); + return c as unknown as ChildProcess; + }, + }, + }); + await srv.stack.addLayer("tun-layer", sshOld); + const opening = client.rpc<{ forwardId: string }>("forward.add", { + target: { layer: "tun-layer" }, + spec: { kind: "L", bindPort: 18111, targetHost: "db", targetPort: 5432 }, + }); + void opening.catch(() => undefined); + const child = await started; + const replaceLayer = () => client.rpc("cat", { + target: { layer: "tun-layer", descriptor: { driver: "local", cwd: dirA } }, + path: "marker.txt", + }); + try { + await expect(replaceLayer()).rejects.toThrow(/拒绝静默覆盖/); + } finally { + child.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 18111.\ndebug1: Entering interactive session.\n"); + } + const { forwardId } = await opening; + await expect(replaceLayer()).rejects.toThrow(/拒绝静默覆盖/); + + await expect(client.rpc("forward.remove", { forwardId })).resolves.toMatchObject({ status: "stopped" }); + await expect(replaceLayer()).resolves.toEqual({ content: "from-A" }); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + rmSync(dirA, { recursive: true, force: true }); + rmSync(dirB, { recursive: true, force: true }); + } + }, 15_000); + + test("supports IPv6 loopback [::1] for DaemonServer and DaemonClient", async () => { + const dir = makeTempDir("fx-daemon-ipv6-"); + const srv = new DaemonServer({ daemonDir: dir, host: "::1", version: "ipv6" }); + try { + try { + await srv.start(); + } catch (e) { + const code = (e as NodeJS.ErrnoException).code; + if (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT") return; + throw e; + } + expect(srv.addr).toContain("[::1]:"); + const client = new DaemonClient({ addr: srv.addr, token: srv.token }); + expect(await client.health()).toBe(true); + expect((await client.status()).version).toBe("ipv6"); + const r = await client.rpc<{ stdout: string; exitCode: number }>("exec", { command: "printf 'v6-ok'" }); + expect(r.exitCode).toBe(0); + expect(r.stdout).toBe("v6-ok"); + } finally { + await srv.stop().catch(() => undefined); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("[P1] rejects concurrent same-name layer requests with conflicting descriptors", async () => { + const dir = makeTempDir("fx-daemon-conc-conflict-"); + const dirA = makeTempDir("fx-conc-a-"); + const dirB = makeTempDir("fx-conc-b-"); + writeFileSync(join(dirA, "marker.txt"), "from-A", "utf-8"); + writeFileSync(join(dirB, "marker.txt"), "from-B", "utf-8"); + + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + let releaseGate!: () => void; + const firstEntered = new Promise((r) => { + const origAddLayer = srv.stack.addLayer.bind(srv.stack); + const gate = new Promise((res) => { releaseGate = res; }); + srv.stack.addLayer = async (name, desc, opts) => { + if (name === "race-app") { + r(); + await gate; + } + return origAddLayer(name, desc, opts); + }; + }); + + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + + const p1 = client.rpc<{ content: string }>("cat", { + target: { layer: "race-app", descriptor: { driver: "local", cwd: dirA } }, + path: "marker.txt", + }); + await firstEntered; + + const p2 = client.rpc<{ content: string }>("cat", { + target: { layer: "race-app", descriptor: { driver: "local", cwd: dirB } }, + path: "marker.txt", + }); + await expect(p2).rejects.toThrow(/并发注册|拒绝合并/); + + releaseGate(); + expect((await p1).content).toBe("from-A"); + } finally { + releaseGate?.(); + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + rmSync(dirA, { recursive: true, force: true }); + rmSync(dirB, { recursive: true, force: true }); + } + }, 15_000); + + test("[P1] explicit CLI targets preserve existing MCP default layer and leave empty activeLayer unset", async () => { + const dir = makeTempDir("fx-daemon-active-preserve-"); + const dirA = makeTempDir("fx-active-a-"); + const dirB = makeTempDir("fx-active-b-"); + writeFileSync(join(dirA, "who.txt"), "MCP_DEFAULT_A", "utf-8"); + writeFileSync(join(dirB, "who.txt"), "CLI_EXPLICIT_B", "utf-8"); + + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + + // 1) Even when activeLayer starts undefined, explicit ephemeral CLI target does not hijack it + const eph1 = await client.rpc<{ content: string }>("cat", { + target: { descriptor: { driver: "local", cwd: dirB } }, + path: "who.txt", + }); + expect(eph1.content).toBe("CLI_EXPLICIT_B"); + expect(srv.stack.activeLayer).toBeUndefined(); + + // 2) MCP establishes default layer "mcp-default" + await srv.stack.addLayer("mcp-default", { driver: "local", cwd: dirA }); + expect(srv.stack.activeLayer?.name).toBe("mcp-default"); + + // 3) Explicit CLI named and ephemeral calls must NOT switch activeLayer away from "mcp-default" + const cliNamed = await client.rpc<{ content: string }>("cat", { + target: { layer: "cli-other", descriptor: { driver: "local", cwd: dirB } }, + path: "who.txt", + }); + expect(cliNamed.content).toBe("CLI_EXPLICIT_B"); + expect(srv.stack.activeLayer?.name).toBe("mcp-default"); + + const mcpRead = await srv.toolkit.handlers.read_path({ path: "who.txt" }); + expect(mcpRead).toMatchObject({ type: "file", content: "MCP_DEFAULT_A" }); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + rmSync(dirA, { recursive: true, force: true }); + rmSync(dirB, { recursive: true, force: true }); + } + }, 15_000); + + test("[P2] probeDaemon returns null on invalid daemon.addr and CLI falls back to single-shot execution", async () => { + const dir = makeTempDir("fx-daemon-bad-addr-"); + try { + acquireDaemonLock(dir, "0.2.11"); + const paths = daemonPaths(dir); + writePrivateFileAtomic(paths.addrFile, "not-a-valid-addr"); + writePrivateFileAtomic(paths.tokenFile, generateDaemonToken()); + + expect(await probeDaemon(dir)).toBeNull(); + const res = runCli(["exec", "--", "printf 'standalone-fallback-ok'"], dir); + expect(res.exitCode).toBe(0); + expect(res.stdout.toString()).toBe("standalone-fallback-ok"); + } finally { + cleanupDaemonFiles(dir); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("[P1] implicit local CLI commands never hijack a user-registered SSH layer named 'local'", async () => { + const dir = makeTempDir("fx-daemon-local-clash-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + const fakeSsh = { + descriptor: { driver: "ssh", target: "ops@ssh-named-local" }, + fs: { + readFile: async () => "SSH_LOCAL_FS", + writeFile: async () => undefined, + stat: async () => ({ size: 0, mtimeMs: 0, isFile: true, isDirectory: false }), + readdir: async () => [], + mkdir: async () => undefined, + rename: async () => undefined, + rm: async () => undefined, + }, + exec: async () => ({ stdout: "FROM_SSH_NAMED_LOCAL", stderr: "", exitCode: 0 }), + execSession: async () => { throw new Error("unused"); }, + tailSession: async () => [], + readSessionLog: async () => "", + watchSession: () => ({ cancel: () => undefined }), + stopSession: async () => ({ status: "stopped" as const }), + verifySession: async () => ({ status: "exited" as const, exitCode: 0 }), + listSessions: () => [], + getCwd: async () => "/", + getEnv: async () => undefined, + init: async () => undefined, + destroy: async () => undefined, + }; + await srv.stack.addLayer("local", fakeSsh as never); + + const client = new DaemonClient({ addr, token: srv.token }); + // Implicit local (no target, or descriptor.driver === "local" without target.layer) executes locally, NOT on SSH "local" + const r1 = await client.rpc<{ stdout: string; exitCode: number }>("exec", { command: "printf 'REAL_LOCAL_1'" }); + expect(r1.exitCode).toBe(0); + expect(r1.stdout).toBe("REAL_LOCAL_1"); + + const r2 = await client.rpc<{ stdout: string; exitCode: number }>("exec", { + target: { descriptor: { driver: "local" } }, + command: "printf 'REAL_LOCAL_2'", + }); + expect(r2.exitCode).toBe(0); + expect(r2.stdout).toBe("REAL_LOCAL_2"); + + // Explicit target: { layer: "local" } intentionally targets the registered layer named "local" + const r3 = await client.rpc<{ stdout: string; exitCode: number }>("exec", { + target: { layer: "local" }, + command: "printf 'IGNORED'", + }); + expect(r3.stdout).toBe("FROM_SSH_NAMED_LOCAL"); + await expect(client.rpc("forward.add", { + spec: { kind: "D", bindPort: 0 }, + })).rejects.toMatchObject({ message: "层 'local' (local) 不支持动态端口转发" }); + + const stream = await client.rpc<{ window_id: string }>("stream.open", { + command: "printf 'implicit-local-log\\n'", + waitMs: 2_000, + }); + try { + await expect(client.rpc("exec", { + target: { layer: "local", descriptor: { driver: "local" } }, + command: "printf 'NEW_NAMED_LOCAL'", + })).resolves.toMatchObject({ stdout: "NEW_NAMED_LOCAL", exitCode: 0 }); + } finally { + await client.rpc("stream.close", { windowId: stream.window_id }); + } + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 30_000); + + test("[P2] RPC mid-flight socket drop preserves error and tags outcome='unknown'", async () => { + const dir = makeTempDir("fx-daemon-rpc-drop-"); + const stub = http.createServer((req, res) => { + if (req.method === "GET" && req.url === "/status") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ ok: true, result: {} })); + return; + } + req.on("data", () => undefined); + req.on("end", () => { + req.socket.destroy(); + }); + }); + await new Promise((resolve) => stub.listen(0, "127.0.0.1", () => resolve())); + const port = (stub.address() as { port: number }).port; + try { + const client = new DaemonClient({ addr: `127.0.0.1:${port}`, token: "tok" }); + let caught: (Error & { outcome?: unknown; code?: unknown }) | undefined; + try { + await client.rpc("exec", { command: "echo may-have-ran" }); + } catch (e) { + caught = e as Error & { outcome?: unknown; code?: unknown }; + } + expect(caught).toBeInstanceOf(Error); + expect(caught?.outcome).toBe("unknown"); + + const paths = daemonPaths(dir); + writePrivateFileAtomic(paths.addrFile, `127.0.0.1:${port}`); + writePrivateFileAtomic(paths.tokenFile, "tok"); + const cli = Bun.spawn([process.execPath, "bin/filaxis.ts", "exec", "--", "printf should-not-replay"], { + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + windowsHide: true, + env: { ...process.env, FILAXIS_DAEMON_DIR: dir }, + }); + const [exitCode, stdout, stderr] = await Promise.all([ + cli.exited, new Response(cli.stdout).text(), new Response(cli.stderr).text(), + ]); + expect(exitCode).toBe(1); + expect(stdout).toBe(""); + expect(stderr).toContain("outcome=unknown"); + } finally { + await new Promise((resolve) => stub.close(() => resolve())); + rmSync(dir, { recursive: true, force: true }); + } + }, 10_000); + + test("preserves confirmed RPC errors without marking their outcome unknown", async () => { + const srv = new DaemonServer({ writeFiles: false }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + const rejection = client.rpc("cat", {}); + await expect(rejection).rejects.toThrow("cat 缺少 path 参数"); + await expect(rejection).rejects.not.toHaveProperty("outcome"); + + const unauthorized = new DaemonClient({ addr, token: "wrong-token" }); + const rejectedAuth = unauthorized.rpc("exec", {}); + await expect(rejectedAuth).rejects.toThrow("HTTP 401"); + await expect(rejectedAuth).rejects.not.toHaveProperty("outcome"); + + const driver = new LocalRuntimeDriver(); + const failure = Object.assign(new Error("fixture command interrupted"), { + name: "AbortError", code: "ABORT_ERR", outcome: "unknown", partialOutput: "fixture output", + }); + driver.exec = async () => { throw failure; }; + await srv.stack.addLayer("fixture", driver); + await expect(client.rpc("exec", { + target: { layer: "fixture" }, command: "fixture", + })).rejects.toMatchObject({ + name: failure.name, code: failure.code, outcome: failure.outcome, partialOutput: failure.partialOutput, + }); + } finally { + await srv.stop(); + } + }); + + test("explicit descriptors keep selecting their target after a shared layer name is replaced", async () => { + const dir = makeTempDir("fx-daemon-ephemeral-replace-"); + const first = join(dir, "first"); + const second = join(dir, "second"); + mkdirSync(first); + mkdirSync(second); + writeFileSync(join(first, "marker.txt"), "first"); + writeFileSync(join(second, "marker.txt"), "second"); + const srv = new DaemonServer({ writeFiles: false }); + try { + const addr = await srv.start(); + const client = new DaemonClient({ addr, token: srv.token }); + const target = { descriptor: { driver: "local", cwd: first } }; + const read = (targetSpec: Record) => client.rpc<{ content: string }>( + "cat", { target: targetSpec, path: "marker.txt" }, + ); + expect((await read(target)).content).toBe("first"); + const [layer] = (await client.status()).layers; + if (!layer) throw new Error("Expected the descriptor to register a layer"); + const { name } = layer; + expect((await read({ layer: name, descriptor: { driver: "local", cwd: second } })).content).toBe("second"); + expect((await read(target)).content).toBe("first"); + expect((await read({ layer: name })).content).toBe("second"); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("[P2] parseAddrToUrl & urlRequestPort accept explicit default HTTP port :80 and :443 while rejecting portless hosts", () => { + expect(urlRequestPort(parseAddrToUrl("127.0.0.1:80"))).toBe(80); + expect(urlRequestPort(parseAddrToUrl("http://127.0.0.1:80"))).toBe(80); + expect(urlRequestPort(parseAddrToUrl("[::1]:80"))).toBe(80); + expect(urlRequestPort(parseAddrToUrl("https://127.0.0.1:443"))).toBe(443); + expect(urlRequestPort(parseAddrToUrl("127.0.0.1:8080"))).toBe(8080); + + expect(() => parseAddrToUrl("127.0.0.1")).toThrow(/非法 Daemon 监听地址/); + expect(() => parseAddrToUrl("http://127.0.0.1")).toThrow(/非法 Daemon 监听地址/); + expect(() => parseAddrToUrl("[::1]")).toThrow(/非法 Daemon 监听地址/); + }); +}); diff --git a/tests/file-edit.test.ts b/tests/file-edit.test.ts index 1c1a88b..597a29f 100644 --- a/tests/file-edit.test.ts +++ b/tests/file-edit.test.ts @@ -389,10 +389,11 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { const generation = "00000000-0000-4000-8000-000000000001"; const run = () => Bun.spawnSync([process.execPath, "bin/filaxis.ts", "layer", "save", "probe", "--host", "web-01"], { env: { ...process.env, FILAXIS_LAYERS: store }, + windowsHide: true, }); try { mkdirSync(lock); - const dead = spawn(process.execPath, ["-e", "process.exit(0)"], { stdio: "ignore" }); + const dead = spawn(process.execPath, ["-e", "process.exit(0)"], { stdio: "ignore", windowsHide: true }); await once(dead, "exit"); expect(dead.pid).toBeDefined(); writeFileSync(join(lock, `${dead.pid}-${generation}`), ""); @@ -412,15 +413,15 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { const p = join(d3, "x.env"); writeFileSync(p, "K=1\n"); const fwd = p.replace(/\\/g, "/"); - const out1 = execSync('bun bin/filaxis.ts exec -- "echo CLI_OK" 2>&1', { encoding: "utf-8", cwd: process.cwd() }); + const out1 = execSync('bun bin/filaxis.ts exec -- "echo CLI_OK" 2>&1', { encoding: "utf-8", cwd: process.cwd(), windowsHide: true }); expect(out1).toContain("CLI_OK"); expect(out1).toContain("exit=0"); - const out2 = execSync(`bun bin/filaxis.ts cat "${fwd}"`, { encoding: "utf-8" }); + const out2 = execSync(`bun bin/filaxis.ts cat "${fwd}"`, { encoding: "utf-8", windowsHide: true }); expect(out2).toContain("K=1"); - const out3 = execSync(`bun bin/filaxis.ts edit "${fwd}" "K=1" "K=2"`, { encoding: "utf-8" }); + const out3 = execSync(`bun bin/filaxis.ts edit "${fwd}" "K=1" "K=2"`, { encoding: "utf-8", windowsHide: true }); expect(out3).toContain("1 处"); expect(readFileSync(p, "utf-8")).toBe("K=2\n"); - const out4 = execSync('bun bin/filaxis.ts observe --stream stderr --duration 2000 -- "echo EO; echo EE 1>&2; sleep 2" 2>&1', { encoding: "utf-8" }); + const out4 = execSync('bun bin/filaxis.ts observe --stream stderr --duration 2000 -- "echo EO; echo EE 1>&2; sleep 2" 2>&1', { encoding: "utf-8", windowsHide: true }); expect(out4).toContain("[stderr] EE"); expect(out4).not.toContain("[stdout] EO"); rmSync(d3, { recursive: true, force: true }); @@ -440,7 +441,7 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { old: '"timeout_ms": 3500,\n "strip_prefix": false', new: '"timeout_ms": 3500,\n "strip_prefix": true', })); - const out1 = execSync(`bun bin/filaxis.ts edit "${fwd(p)}" --request-file "${fwd(req)}"`, { encoding: "utf-8" }); + const out1 = execSync(`bun bin/filaxis.ts edit "${fwd(p)}" --request-file "${fwd(req)}"`, { encoding: "utf-8", windowsHide: true }); expect(out1).toContain("1 处"); expect(readFileSync(p, "utf-8")).toContain('"strip_prefix": true'); // stdin 管道通道(execSync input 直喂 stdin) @@ -448,6 +449,7 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { const out2 = execSync(`bun bin/filaxis.ts edit "${fwd(p)}" --stdin-json`, { input: JSON.stringify({ old: "K=1", new: "K=2" }), encoding: "utf-8", + windowsHide: true, }); expect(out2).toContain("1 处"); expect(readFileSync(p, "utf-8")).toBe("K=2\n"); @@ -460,7 +462,7 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { const { execSync } = await import("node:child_process"); let errText = ""; try { - execSync('bun bin/filaxis.ts exec --docker web -- "echo X"', { encoding: "utf-8", stdio: "pipe" }); + execSync('bun bin/filaxis.ts exec --docker web -- "echo X"', { encoding: "utf-8", stdio: "pipe", windowsHide: true }); } catch (e) { errText = String((e as { stderr?: string }).stderr ?? (e as Error).message); } @@ -475,30 +477,30 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { const env = { ...process.env, FILAXIS_LAYERS: store }; const out1 = execSync( 'bun bin/filaxis.ts layer save nginx --host web-01 -J jump-host --docker lab-nginx-b3', - { encoding: "utf-8", env }, + { encoding: "utf-8", env, windowsHide: true }, ); expect(out1).toContain("nginx"); expect(out1).toContain("--layer nginx"); // 覆盖保存幂等 - execSync('bun bin/filaxis.ts layer save nginx --host web-01', { encoding: "utf-8", env }); - const out2 = execSync("bun bin/filaxis.ts layer list", { encoding: "utf-8", env }); + execSync('bun bin/filaxis.ts layer save nginx --host web-01', { encoding: "utf-8", env, windowsHide: true }); + const out2 = execSync("bun bin/filaxis.ts layer list", { encoding: "utf-8", env, windowsHide: true }); expect(out2).toContain("nginx"); expect(out2).toContain("web-01"); // --layer 与 --host 互斥 let err1 = ""; try { - execSync('bun bin/filaxis.ts exec --layer nginx --host x -- "echo 1"', { encoding: "utf-8", env, stdio: "pipe" }); + execSync('bun bin/filaxis.ts exec --layer nginx --host x -- "echo 1"', { encoding: "utf-8", env, stdio: "pipe", windowsHide: true }); } catch (e) { err1 = String((e as { stderr?: string }).stderr ?? e); } expect(err1).toContain("互斥"); // 未保存层报错 let err2 = ""; try { - execSync('bun bin/filaxis.ts exec --layer ghost -- "echo 1"', { encoding: "utf-8", env, stdio: "pipe" }); + execSync('bun bin/filaxis.ts exec --layer ghost -- "echo 1"', { encoding: "utf-8", env, stdio: "pipe", windowsHide: true }); } catch (e) { err2 = String((e as { stderr?: string }).stderr ?? e); } expect(err2).toContain("未保存"); // rm 后清单空 - execSync("bun bin/filaxis.ts layer rm nginx", { encoding: "utf-8", env }); - const out3 = execSync("bun bin/filaxis.ts layer list", { encoding: "utf-8", env }); + execSync("bun bin/filaxis.ts layer rm nginx", { encoding: "utf-8", env, windowsHide: true }); + const out3 = execSync("bun bin/filaxis.ts layer list", { encoding: "utf-8", env, windowsHide: true }); expect(out3).toContain("无已保存层"); rmSync(d6, { recursive: true, force: true }); }, 60_000); diff --git a/tests/file-transfer.test.ts b/tests/file-transfer.test.ts index 6d96c05..d9f30ac 100644 --- a/tests/file-transfer.test.ts +++ b/tests/file-transfer.test.ts @@ -347,7 +347,7 @@ describe("putFile(真实 shell 回归)", () => { const target = "file with spaces.bin"; const info = (path: string, operation: string) => execFileSync("powershell.exe", [ "-NoProfile", "-NonInteractive", "-Command", operation, - ], { encoding: "utf8", env: { ...process.env, FX_TEST_ACL_PATH: path } }).trim(); + ], { encoding: "utf8", windowsHide: true, env: { ...process.env, FX_TEST_ACL_PATH: path } }).trim(); const snapshot = "([IO.File]::GetAccessControl($env:FX_TEST_ACL_PATH)).GetSecurityDescriptorSddlForm('Access')"; const staged: string[] = []; const exec: TransferExec = async (command) => { @@ -424,7 +424,7 @@ describe("putFile(真实 shell 回归)", () => { const realExec: TransferExec = async (command) => { // sh -s stdin 传命令(与 execChannel 同形态)——sh -c 走 argv,Windows // 32767 字符上限装不下 48K chunk(uv_spawn ENAMETOOLONG,本测试实测踩出) - const p = Bun.spawn(["sh", "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn(["sh", "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(command); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -874,7 +874,7 @@ describe("[P2] tmux 大文件分块下载(避开输出滚动窗口截断)", const cappedTmuxDriver = { descriptor: { driver: "tmux" as const }, async exec(cmd: string) { - const p = Bun.spawn([shPath, "-c", cmd], { stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-c", cmd], { stdout: "pipe", stderr: "pipe", windowsHide: true }); const [stdout, stderr, exitCode] = await Promise.all([ new Response(p.stdout).text(), new Response(p.stderr).text(), diff --git a/tests/integration-ssh.test.ts b/tests/integration-ssh.test.ts index 36ac27e..2c4c524 100644 --- a/tests/integration-ssh.test.ts +++ b/tests/integration-ssh.test.ts @@ -478,7 +478,7 @@ describe("SSH 真机集成(AC-02/04/15 远端面)", () => { ...(transport === "sftp" ? { FILAXIS_SSH_STDIO_MODE: "inherit" } : {}), }; const cli = (command: "put" | "get", from: string, to: string) => JSON.parse(execFileSync( - process.execPath, ["bin/filaxis.ts", command, ...options, "--", from, to], { encoding: "utf8", env }, + process.execPath, ["bin/filaxis.ts", command, ...options, "--", from, to], { encoding: "utf8", env, windowsHide: true }, )); expect(cli("put", input, `${name} file.bin`)).toMatchObject({ transport, bytes: payload.length, verification: "sha256", writeMode: "atomic-replace" }); expect(cli("get", `${name} file.bin`, output)).toMatchObject({ transport, bytes: payload.length, verification: "sha256" }); @@ -613,7 +613,7 @@ describe("第四季:PTY 残影串台回归(CI 真机)", () => { // ── 第九季:CLI 路径描述透传(--enter 重放 / --docker 糖全链路 / --hop 拒绝)── describe("第九季:CLI 路径描述(CI 真机)", () => { integration("--enter sh:exec 通道进入管线重放(stdin 管道零嵌套引用)", async () => { - const out = execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--host", TARGET, "--enter", "sh", "--", "echo ENTER_OK"], { encoding: "utf-8" }); + const out = execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--host", TARGET, "--enter", "sh", "--", "echo ENTER_OK"], { encoding: "utf-8", windowsHide: true }); expect(out).toContain("ENTER_OK"); }, 60_000); @@ -625,14 +625,15 @@ describe("第九季:CLI 路径描述(CI 真机)", () => { if (started.exitCode !== 0) throw new Error(started.stderr); const args = ["bin/filaxis.ts"]; const layer = ["--host", TARGET, "--docker", container]; - const out = execFileSync(process.execPath, [...args, "exec", ...layer, "--", "echo DOCKER_OK; cat /etc/alpine-release"], { encoding: "utf-8" }); + const out = execFileSync(process.execPath, [...args, "exec", ...layer, "--", "echo DOCKER_OK; cat /etc/alpine-release"], { encoding: "utf-8", windowsHide: true }); expect(out).toContain("DOCKER_OK"); expect(out).toMatch(/\d+\.\d+\.\d+/); const path = "/tmp/fx-cli-edit.json"; - execFileSync(process.execPath, [...args, "exec", ...layer, "--", `printf '{"k": 1}' > ${path}`]); + execFileSync(process.execPath, [...args, "exec", ...layer, "--", `printf '{"k": 1}' > ${path}`], { windowsHide: true }); const edited = execFileSync(process.execPath, [...args, "edit", ...layer, path, "--stdin-json"], { input: JSON.stringify({ old: "1", new: "2" }), encoding: "utf-8", + windowsHide: true, }); expect(edited).toContain("1 处"); } finally { @@ -644,7 +645,7 @@ describe("第九季:CLI 路径描述(CI 真机)", () => { integration("--hop 链 exec 通道拒绝(不可直达语义自守——指引收敛 -J 或 pty 通道)", async () => { let errText = ""; try { - execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--host", TARGET, "--hop", "user@bastion:2222", "--", "echo X"], { encoding: "utf-8", stdio: "pipe" }); + execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--host", TARGET, "--hop", "user@bastion:2222", "--", "echo X"], { encoding: "utf-8", stdio: "pipe", windowsHide: true }); } catch (e) { errText = String((e as { stderr?: string }).stderr ?? (e as Error).message); } @@ -771,7 +772,7 @@ describe("第十一季:CLI 层快照(CI 真机)", () => { writeFileSync(planPath, JSON.stringify(plan)); return execFileSync(process.execPath, [ "bin/filaxis.ts", "batch", "--layer", layer, "--request-file", planPath, - ], { encoding: "utf8", env }); + ], { encoding: "utf8", env, windowsHide: true }); }; try { writeFileSync(layers, JSON.stringify({ @@ -797,11 +798,11 @@ describe("第十一季:CLI 层快照(CI 真机)", () => { const d = mkdtempSync(j(tmpdir(), "fx-cli-layer-")); const env = { ...process.env, FILAXIS_LAYERS: j(d, "layers.json") }; try { - execFileSync(process.execPath, ["bin/filaxis.ts", "layer", "save", "lo", "--host", TARGET], { encoding: "utf-8", env }); + execFileSync(process.execPath, ["bin/filaxis.ts", "layer", "save", "lo", "--host", TARGET], { encoding: "utf-8", env, windowsHide: true }); // 第一条:建 master(一次握手);第二条:CM 复用毫秒级 - const o1 = execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--layer", "lo", "--", "echo L1_OK"], { encoding: "utf-8", env }); + const o1 = execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--layer", "lo", "--", "echo L1_OK"], { encoding: "utf-8", env, windowsHide: true }); expect(o1).toContain("L1_OK"); - const o2 = execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--layer", "lo", "--", "echo L2_OK"], { encoding: "utf-8", env }); + const o2 = execFileSync(process.execPath, ["bin/filaxis.ts", "exec", "--layer", "lo", "--", "echo L2_OK"], { encoding: "utf-8", env, windowsHide: true }); expect(o2).toContain("L2_OK"); } finally { rmSync(d, { recursive: true, force: true }); diff --git a/tests/mcp-config.test.ts b/tests/mcp-config.test.ts index f6dc794..efc4f7f 100644 --- a/tests/mcp-config.test.ts +++ b/tests/mcp-config.test.ts @@ -17,12 +17,12 @@ test("mcp-config emits one selected format without writing to the home or projec const original = '{"mcpServers":{"existing":{}}}'; writeFileSync(config, original); const env = { ...process.env, HOME: home, USERPROFILE: home }; - const runtime = Bun.spawnSync([process.execPath, "-e", 'console.log(require("node:os").homedir())'], { cwd: project, env }); + const runtime = Bun.spawnSync([process.execPath, "-e", 'console.log(require("node:os").homedir())'], { cwd: project, env, windowsHide: true }); expect(runtime.stdout.toString().trim()).toBe(home); const server = { command: process.execPath, args: [join(dirname(cli), "filaxis-mcp.ts")] }; function run(...args: string[]) { - return Bun.spawnSync([process.execPath, cli, "mcp-config", ...args], { cwd: project, env }); + return Bun.spawnSync([process.execPath, cli, "mcp-config", ...args], { cwd: project, env, windowsHide: true }); } const json = run(); diff --git a/tests/mcp-proxy.test.ts b/tests/mcp-proxy.test.ts new file mode 100644 index 0000000..f6a2c76 --- /dev/null +++ b/tests/mcp-proxy.test.ts @@ -0,0 +1,698 @@ +/** + * mcp-proxy.test.ts — Phase 3 测试:manage_layers 动态转发、MCP SSE 共享控制面、 + * Proxy 重连保活、Watchdog/Token 轮换、零自动重放与零隐式拉起(REQ-0005) + */ +import { describe, expect, test } from "bun:test"; +import { spawn, type ChildProcess } from "node:child_process"; +import { EventEmitter } from "node:events"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import * as http from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import { + createAgentToolkit, + DaemonClient, + DaemonServer, + daemonPaths, + LocalRuntimeDriver, + McpServer, + McpStdioProxy, + RuntimeStack, + SshPtyDriver, + TOOL_DEFS, + writePrivateFileAtomic, +} from "../src/index.js"; + +class MockChild extends EventEmitter { + stdout = new PassThrough(); + stderr = new PassThrough(); + pid = 61616; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + signals: NodeJS.Signals[] = []; + + kill(signal: NodeJS.Signals = "SIGTERM"): boolean { + this.signals.push(signal); + if (signal === "SIGTERM") { + this.exitCode = 0; + this.signalCode = "SIGTERM"; + this.emit("exit", 0, "SIGTERM"); + this.emit("close", 0, "SIGTERM"); + } + return true; + } +} + +function makeTempDir(prefix: string): string { + return mkdtempSync(join(tmpdir(), prefix)); +} + +function attachProxyFixture(opts: ConstructorParameters[0]) { + const stdin = new PassThrough(); + const stdout = new PassThrough(); + const proxy = new McpStdioProxy({ ...opts, stdin, stdout }); + const responses: Array> = []; + let acc = ""; + stdout.on("data", (chunk: Buffer) => { + acc += chunk.toString("utf-8"); + let nl: number; + while ((nl = acc.indexOf("\n")) !== -1) { + const line = acc.slice(0, nl).trim(); + acc = acc.slice(nl + 1); + if (line) responses.push(JSON.parse(line) as Record); + } + }); + proxy.start(); + return { + proxy, + send: (msg: Record) => { stdin.write(JSON.stringify(msg) + "\n"); }, + closeStdin: () => { stdin.end(); }, + responses, + }; +} + +async function waitForResponse( + responses: Array>, + id: number | string, + timeoutMs = 10_000, +): Promise> { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const hit = responses.find((r) => r.id === id); + if (hit) return hit; + await new Promise((r) => setTimeout(r, 25)); + } + throw new Error(`waitForResponse(${String(id)}) timeout`); +} + +describe("manage_layers dynamic forwarding & 12-tool surface", () => { + test("lists and closes injected-driver forwards after registering or activating a named layer", async () => { + const stack = new RuntimeStack(); + const makeDriver = (name: string, port: number) => new SshPtyDriver({ driver: "ssh", target: name }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const child = new MockChild(); + setTimeout(() => child.stderr.write(`debug1: Local forwarding listening on 127.0.0.1 port ${port}.\ndebug1: Entering interactive session.\n`), 5); + return child as unknown as ChildProcess; + }, + }, + }); + const injected = makeDriver("injected.invalid", 18121); + const named = makeDriver("named.invalid", 18122); + const toolkit = createAgentToolkit(stack, { driver: injected }); + const { manage_layers } = toolkit.handlers; + const spec = { action: "forward_add", kind: "L", target_host: "localhost", target_port: 80 } as const; + try { + const opened = await manage_layers({ ...spec, bind_port: 18121, forward_id: "injected" }); + await stack.addLayer("named", named, { activate: false }); + await manage_layers({ ...spec, layer: "named", bind_port: 18122, forward_id: "named" }); + expect((await manage_layers({ action: "forward_list" })).forwards.map((f) => f.forwardId).sort()) + .toEqual(["injected", "named"]); + + stack.setActive("named"); + expect((await manage_layers({ action: "forward_list" })).forwards.map((f) => f.forwardId).sort()) + .toEqual(["injected", "named"]); + expect((await manage_layers({ action: "forward_list", layer: "named" })).forwards.map((f) => f.forwardId)) + .toEqual(["named"]); + await expect(manage_layers({ ...spec, bind_port: 18123, forward_id: "injected" })) + .rejects.toThrow(/已存在于注入驱动/); + await expect(manage_layers({ action: "forward_remove", forward_id: opened.forward.forwardId })) + .resolves.toMatchObject({ status: "stopped" }); + expect(named.listForwards()).toMatchObject([{ forwardId: "named", status: "active" }]); + + await stack.addLayer("injected-alias", injected, { activate: false }); + await manage_layers({ ...spec, layer: "injected-alias", bind_port: 18121, forward_id: "unregistered" }); + await stack.removeLayer("injected-alias"); + const remaining = await manage_layers({ action: "forward_list" }); + expect(remaining.forwards.map((f) => f.forwardId).sort()).toEqual(["named", "unregistered"]); + await expect(manage_layers({ action: "forward_remove", forward_id: "unregistered" })) + .resolves.toMatchObject({ status: "stopped" }); + } finally { + toolkit.dispose?.(); + await Promise.all([injected.destroy(), named.destroy()]); + } + }, 15_000); + + test("keeps TOOL_DEFS at 12 tools and handles forward_add/forward_list/forward_remove via McpServer", async () => { + expect(TOOL_DEFS).toHaveLength(12); + const manageTool = TOOL_DEFS.find((t) => t.function.name === "manage_layers")!; + const oneOf = (manageTool.function.parameters as { oneOf?: Array<{ properties?: { action?: { const?: string } }; required?: string[] }> }).oneOf ?? []; + const fwdAddSchema = oneOf.find((v) => v.properties?.action?.const === "forward_add"); + expect(fwdAddSchema?.required).toEqual(["action", "kind"]); + const stack = new RuntimeStack(); + const local = new LocalRuntimeDriver(); + await stack.addLayer("local", local); + + let childRef!: MockChild; + const sshDriver = new SshPtyDriver({ driver: "ssh", target: "ops@tunnel.test" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + childRef = new MockChild(); + setTimeout(() => { + childRef.stderr.write("debug1: Allocated port 45123 for remote forward to localhost:3000\n"); + }, 5); + return childRef as unknown as ChildProcess; + }, + }, + }); + await stack.addLayer("ssh-main", sshDriver); + + const stdin = new PassThrough(); + const stdout = new PassThrough(); + new McpServer({ toolkit: createAgentToolkit(stack), stdin, stdout }); + const responses: Array> = []; + let acc = ""; + stdout.on("data", (d: Buffer) => { + acc += d.toString("utf-8"); + let nl: number; + while ((nl = acc.indexOf("\n")) !== -1) { + responses.push(JSON.parse(acc.slice(0, nl)) as Record); + acc = acc.slice(nl + 1); + } + }); + + const call = async (id: number, args: Record) => { + stdin.write(JSON.stringify({ + jsonrpc: "2.0", + id, + method: "tools/call", + params: { name: "manage_layers", arguments: args }, + }) + "\n"); + return (await waitForResponse(responses, id)).result as { + isError: boolean; + content: Array<{ text: string }>; + structuredContent?: Record; + }; + }; + + try { + const badLocal = await call(1, { + action: "forward_add", + layer: "local", + kind: "L", + bind_port: 8080, + target_host: "db", + target_port: 5432, + }); + expect(badLocal.isError).toBe(true); + expect(badLocal.content[0]!.text).toContain("不支持动态端口转发"); + + const badParam = await call(2, { action: "forward_list", extra_bad: 1 }); + expect(badParam.isError).toBe(true); + + const added = await call(3, { + action: "forward_add", + layer: "ssh-main", + kind: "remote", + target_host: "localhost", + target_port: 3000, + forward_id: "mcp-r1", + }); + expect(added.isError).toBe(false); + expect(added.structuredContent).toMatchObject({ + action: "forward_add", + forward: { + forwardId: "mcp-r1", + layer: "ssh-main", + kind: "remote", + bindPort: 45123, + status: "active", + }, + }); + + const listed = await call(4, { action: "forward_list" }); + expect(listed.isError).toBe(false); + expect((listed.structuredContent as { forwards: Array<{ forwardId: string }> }).forwards.map((f) => f.forwardId)) + .toEqual(["mcp-r1"]); + + const removed = await call(5, { action: "forward_remove", forward_id: "mcp-r1" }); + expect(removed.isError).toBe(false); + expect(removed.structuredContent).toEqual({ + action: "forward_remove", + forward_id: "mcp-r1", + status: "stopped", + }); + expect(childRef.signals).toContain("SIGTERM"); + } finally { + stdin.end(); + await stack.removeLayer("ssh-main", { destroy: true }).catch(() => undefined); + await stack.removeLayer("local", { destroy: true }).catch(() => undefined); + } + }); +}); + +describe("DaemonServer MCP HTTP/SSE & McpStdioProxy", () => { + test("enforces Bearer auth (401) on /mcp/sse and /mcp/message", async () => { + const dir = makeTempDir("fx-mcp-auth-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + const addr = await srv.start(); + expect((await fetch(`${addr}/mcp/sse`)).status).toBe(401); + expect((await fetch(`${addr}/mcp/message`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: "Bearer wrong" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }), + })).status).toBe(401); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("survives MCP proxy client restart and shares streams + forwards with CLI DaemonClient", async () => { + const dir = makeTempDir("fx-mcp-share-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + let childRef!: MockChild; + try { + const addr = await srv.start(); + const sshDriver = new SshPtyDriver({ driver: "ssh", target: "ops@share.test" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + childRef = new MockChild(); + setTimeout(() => { + childRef.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 19090.\ndebug1: Entering interactive session.\n"); + }, 5); + return childRef as unknown as ChildProcess; + }, + }, + }); + await srv.stack.addLayer("shared-ssh", sshDriver); + await srv.stack.addLayer("local", new LocalRuntimeDriver()); + + // Proxy #1 opens a stream window and reads initial frame, then disconnects stdin + const p1 = attachProxyFixture({ daemonDir: dir }); + p1.send({ jsonrpc: "2.0", id: 1, method: "initialize" }); + await waitForResponse(p1.responses, 1); + + p1.send({ + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: "observe_stream", + arguments: { + command: "printf 'frame-one\\n'; sleep 1.5; printf 'frame-two\\n'", + wait_ms: 3000, + }, + }, + }); + const openResp = await waitForResponse(p1.responses, 2); + const openSc = (openResp.result as { structuredContent: { window_id: string; frames: Array<{ text: string }> } }).structuredContent; + expect(openSc.frames.map((f) => f.text)).toContain("frame-one"); + const windowId = openSc.window_id; + + // Close Proxy #1 stdin; Daemon现场 must survive + p1.closeStdin(); + await new Promise((r) => setTimeout(r, 80)); + + // CLI DaemonClient sees the MCP-opened stream window and adds a forward + const cli = new DaemonClient({ addr, token: srv.token }); + const peekedByCli = await cli.rpc<{ window_id: string; frames: Array<{ text: string }> }>("stream.peek", { + windowId, + limit: 10, + }); + expect(peekedByCli.frames.map((f) => f.text)).toContain("frame-one"); + + await cli.rpc("forward.add", { + target: { layer: "shared-ssh" }, + spec: { id: "cli-fwd", kind: "L", bindPort: 19090, targetHost: "127.0.0.1", targetPort: 80 }, + }); + + // Proxy #2 reconnects and sees the same stream window + CLI-created forward, then closes both + const p2 = attachProxyFixture({ daemonDir: dir }); + p2.send({ + jsonrpc: "2.0", + id: 10, + method: "tools/call", + params: { name: "manage_layers", arguments: { action: "forward_list" } }, + }); + const fwdListResp = await waitForResponse(p2.responses, 10); + expect((fwdListResp.result as { structuredContent: { forwards: Array<{ forwardId: string }> } }).structuredContent.forwards.map((f) => f.forwardId)) + .toEqual(["cli-fwd"]); + + p2.send({ + jsonrpc: "2.0", + id: 11, + method: "tools/call", + params: { name: "manage_layers", arguments: { action: "forward_remove", forward_id: "cli-fwd" } }, + }); + const fwdRmResp = await waitForResponse(p2.responses, 11); + expect((fwdRmResp.result as { structuredContent: { status: string } }).structuredContent.status).toBe("stopped"); + expect(childRef.signals).toContain("SIGTERM"); + + p2.send({ + jsonrpc: "2.0", + id: 12, + method: "tools/call", + params: { name: "close_stream", arguments: { window_id: windowId } }, + }); + const closeResp = await waitForResponse(p2.responses, 12); + expect((closeResp.result as { structuredContent: { closed: boolean } }).structuredContent.closed).toBe(true); + p2.closeStdin(); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("watchdog triggers reconnect and re-reads rotated token/addr after daemon restart", async () => { + const dir = makeTempDir("fx-mcp-watchdog-"); + let srv1: DaemonServer | undefined = new DaemonServer({ + daemonDir: dir, + version: "v1", + sseKeepaliveMs: 60_000, + }); + let srv2: DaemonServer | undefined; + try { + await srv1.start(); + const token1 = srv1.token; + const addr1 = srv1.addr; + + const fx = attachProxyFixture({ + daemonDir: dir, + watchdogIdleMs: 300, + initialReconnectDelayMs: 30, + maxReconnectDelayMs: 80, + }); + fx.send({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + const r1 = await waitForResponse(fx.responses, 1); + expect((r1.result as { tools: unknown[] }).tools).toHaveLength(12); + + // Wait past watchdogIdleMs so proxy destroys hung SSE and reconnects + await new Promise((r) => setTimeout(r, 420)); + fx.send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); + const r2 = await waitForResponse(fx.responses, 2); + expect((r2.result as { tools: unknown[] }).tools).toHaveLength(12); + + // Stop srv1 and start srv2 on the same daemonDir (new port + rotated token) + await srv1.stop(); + srv1 = undefined; + srv2 = new DaemonServer({ daemonDir: dir, version: "v2", sseKeepaliveMs: 50 }); + await srv2.stack.addLayer("local", new LocalRuntimeDriver()); + await srv2.start(); + expect(srv2.token).not.toBe(token1); + expect(srv2.addr).not.toBe(addr1); + await new Promise((r) => setTimeout(r, 250)); + + fx.send({ + jsonrpc: "2.0", + id: 3, + method: "tools/call", + params: { name: "run_command", arguments: { command: "printf 'rotated-ok'" } }, + }); + const r3 = await waitForResponse(fx.responses, 3, 10_000); + expect((r3.result as { structuredContent: { stdout: string; exit_code: number } }).structuredContent).toMatchObject({ + stdout: "rotated-ok", + exit_code: 0, + }); + fx.closeStdin(); + } finally { + await srv1?.stop().catch(() => undefined); + await srv2?.stop().catch(() => undefined); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("never auto-replays in-flight tools/call on SSE disconnect (returns outcome=unknown)", async () => { + const dir = makeTempDir("fx-mcp-noreplay-"); + let execCount = 0; + let startedResolve!: () => void; + const execStarted = new Promise((r) => { startedResolve = r; }); + + const makeMockToolkit = () => { + const stack = new RuntimeStack(); + const tk = createAgentToolkit(stack, { + driver: { + descriptor: { driver: "local", target: "mock" }, + exec: async (cmd: string) => { + execCount++; + startedResolve(); + if (cmd === "hang-non-idempotent") { + await new Promise((r) => setTimeout(r, 5_000)); + } + return { stdout: "ok", stderr: "", exitCode: 0 }; + }, + execSession: async () => { throw new Error("unused"); }, + tailSession: async () => [], + readSessionLog: async () => "", + watchSession: () => ({ cancel: () => undefined }), + stopSession: async () => ({ status: "stopped" as const }), + verifySession: async () => ({ status: "exited" as const, exitCode: 0 }), + listSessions: () => [], + getCwd: async () => "/", + getEnv: async () => undefined, + fs: new LocalRuntimeDriver().fs, + init: async () => undefined, + destroy: async () => undefined, + }, + }); + return tk; + }; + + let srv1: DaemonServer | undefined = new DaemonServer({ daemonDir: dir, toolkit: makeMockToolkit() }); + let srv2: DaemonServer | undefined; + try { + await srv1.start(); + const fx = attachProxyFixture({ + daemonDir: dir, + initialReconnectDelayMs: 30, + maxReconnectDelayMs: 80, + }); + + fx.send({ + jsonrpc: "2.0", + id: 99, + method: "tools/call", + params: { name: "run_command", arguments: { command: "hang-non-idempotent" } }, + }); + await execStarted; + expect(execCount).toBe(1); + + // Sever Daemon #1 mid-execution and bring up Daemon #2 on same daemonDir + await srv1.stop(); + srv1 = undefined; + + const errResp = await waitForResponse(fx.responses, 99); + expect(errResp.error).toMatchObject({ + code: -32000, + data: { outcome: "unknown", method: "tools/call" }, + }); + + srv2 = new DaemonServer({ daemonDir: dir, toolkit: makeMockToolkit() }); + await srv2.start(); + await new Promise((r) => setTimeout(r, 150)); + + // Subsequent new request works, and the severed call was NEVER replayed + fx.send({ + jsonrpc: "2.0", + id: 100, + method: "tools/call", + params: { name: "run_command", arguments: { command: "after-reconnect" } }, + }); + const okResp = await waitForResponse(fx.responses, 100); + expect((okResp.result as { isError: boolean }).isError).toBe(false); + expect(execCount).toBe(2); // 1 (severed) + 1 (new request) — strictly 0 replays! + fx.closeStdin(); + } finally { + await srv1?.stop().catch(() => undefined); + await srv2?.stop().catch(() => undefined); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("disconnected SSE sessions cannot fail reused IDs or consume the new session's POST slots", async () => { + const dir = makeTempDir("fx-mcp-old-post-"); + const streams: http.ServerResponse[] = []; + let onOldPost!: (res: http.ServerResponse) => void; + let onOldNotification!: (res: http.ServerResponse) => void; + let onNewPost!: () => void; + const oldPost = new Promise((resolve) => { onOldPost = resolve; }); + const oldNotification = new Promise((resolve) => { onOldNotification = resolve; }); + const newPost = new Promise((resolve) => { onNewPost = resolve; }); + let firstSessionRequests = 0; + let secondSessionRequests = 0; + const stub = http.createServer((req, res) => { + if (req.url === "/mcp/sse") { + streams.push(res); + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.write(`event: endpoint\ndata: /post/${streams.length}\n\n`); + return; + } + req.resume(); + req.on("end", () => { + if (req.url === "/post/1") { + if (firstSessionRequests++ === 0) onOldPost(res); + else onOldNotification(res); + } else { + res.writeHead(202).end(); + if (++secondSessionRequests === 2) onNewPost(); + } + }); + }); + let fx: ReturnType | undefined; + try { + await new Promise((resolve) => stub.listen(0, "127.0.0.1", resolve)); + const port = (stub.address() as { port: number }).port; + const { addrFile, tokenFile } = daemonPaths(dir); + writePrivateFileAtomic(addrFile, `127.0.0.1:${port}`); + writePrivateFileAtomic(tokenFile, "fixture"); + fx = attachProxyFixture({ daemonDir: dir, initialReconnectDelayMs: 30, maxInFlight: 2 }); + const request = { jsonrpc: "2.0", id: 7, method: "tools/list" }; + fx.send(request); + const delayed = await oldPost; + fx.send({ jsonrpc: "2.0", method: "notifications/initialized" }); + const delayedNotification = await oldNotification; + streams[0]!.end(); + expect((await waitForResponse(fx.responses, 7)).error).toMatchObject({ data: { outcome: "unknown" } }); + fx.responses.length = 0; + + fx.send(request); + fx.send({ ...request, id: 8 }); + await newPost; + delayedNotification.writeHead(202).end(); + await new Promise((resolve) => delayed.writeHead(500).end("old request failure", resolve)); + await new Promise((resolve) => setTimeout(resolve, 100)); + streams[1]!.write('event: message\ndata: {"jsonrpc":"2.0","id":7,"result":{"tools":[]}}\n\n'); + streams[1]!.write('event: message\ndata: {"jsonrpc":"2.0","id":8,"result":{"tools":[]}}\n\n'); + expect(await waitForResponse(fx.responses, 7)).toEqual({ jsonrpc: "2.0", id: 7, result: { tools: [] } }); + expect(await waitForResponse(fx.responses, 8)).toEqual({ jsonrpc: "2.0", id: 8, result: { tools: [] } }); + } finally { + fx?.proxy.close(); + stub.closeAllConnections(); + await new Promise((resolve) => stub.close(() => resolve())); + rmSync(dir, { recursive: true, force: true }); + } + }, 8_000); + + test("filaxis-mcp process stays standalone and never spawns daemon implicitly when daemonDir is empty", async () => { + const dir = makeTempDir("fx-mcp-bin-nod-"); + const child = spawn(process.execPath, ["bin/filaxis-mcp.ts", "--daemon-dir", dir], { + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, + }); + const responses: Array> = []; + let acc = ""; + child.stdout.on("data", (d: Buffer) => { + acc += d.toString("utf-8"); + let nl: number; + while ((nl = acc.indexOf("\n")) !== -1) { + const line = acc.slice(0, nl).trim(); + acc = acc.slice(nl + 1); + if (line) responses.push(JSON.parse(line) as Record); + } + }); + + try { + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" }) + "\n"); + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }) + "\n"); + + const r2 = await waitForResponse(responses, 2, 10_000); + expect((r2.result as { tools: unknown[] }).tools).toHaveLength(12); + + child.stdin.end(); + const exitCode = await new Promise((resolve) => { + if (child.exitCode !== null) resolve(child.exitCode); + else child.once("close", (code) => resolve(code)); + }); + expect(exitCode).toBe(0); + + const { lockFile, addrFile, tokenFile } = daemonPaths(dir); + expect(existsSync(lockFile)).toBe(false); + expect(existsSync(addrFile)).toBe(false); + expect(existsSync(tokenFile)).toBe(false); + } finally { + if (child.exitCode === null) child.kill("SIGTERM"); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("fails in-flight request immediately with outcome=unknown when POST target rejects/errors", async () => { + const dir = makeTempDir("fx-mcp-posterr-"); + const srv = new DaemonServer({ daemonDir: dir, version: "test" }); + try { + await srv.start(); + const fx = attachProxyFixture({ + daemonDir: dir, + initialReconnectDelayMs: 50, + maxReconnectDelayMs: 100, + }); + fx.send({ jsonrpc: "2.0", id: 1, method: "initialize" }); + await waitForResponse(fx.responses, 1); + + // Corrupt daemon.token? Or stop server right as POST happens? Even simpler: + // Send an oversized or malformed POST? Wait: proxy reads from daemon.addr; + // if Daemon returns 401/404 or closes socket during POST, proxy emits -32000 outcome=unknown. + // Stop server and immediately send request before SSE close propagates, or test 404 via closing SSE clients. + const stopping = srv.stop(); + fx.send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); + await stopping; + const resp = await waitForResponse(fx.responses, 2, 5_000); + expect(resp.error).toMatchObject({ + code: -32000, + data: { outcome: "unknown" }, + }); + fx.closeStdin(); + } finally { + await srv.stop().catch(() => undefined); + rmSync(dir, { recursive: true, force: true }); + } + }, 10_000); + + test("reports oversized MCP requests as rejected and keeps the session usable", async () => { + const dir = makeTempDir("fx-mcp-post-oversize-"); + const srv = new DaemonServer({ daemonDir: dir }); + let fx: ReturnType | undefined; + try { + await srv.start(); + fx = attachProxyFixture({ daemonDir: dir }); + fx.send({ + jsonrpc: "2.0", id: 1, method: "tools/call", + params: { name: "run_command", arguments: { command: "x".repeat(17 * 1024 * 1024) } }, + }); + const { error } = await waitForResponse(fx.responses, 1); + expect(error).toMatchObject({ + message: expect.stringContaining("请求体超过限制"), + data: { method: "tools/call", statusCode: 413 }, + }); + expect((error as { data: Record }).data).not.toHaveProperty("outcome"); + fx.send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); + expect((await waitForResponse(fx.responses, 2)).result).toBeDefined(); + } finally { + fx?.proxy.close(); + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + + test("connects MCP HTTP/SSE proxy over IPv6 loopback [::1]", async () => { + const dir = makeTempDir("fx-mcp-ipv6-"); + const srv = new DaemonServer({ daemonDir: dir, host: "::1", version: "ipv6" }); + try { + try { + await srv.start(); + } catch (e) { + const code = (e as NodeJS.ErrnoException).code; + if (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT") return; + throw e; + } + expect(srv.addr).toContain("[::1]:"); + + const fx = attachProxyFixture({ daemonDir: dir }); + fx.send({ jsonrpc: "2.0", id: 1, method: "initialize" }); + const initResp = await waitForResponse(fx.responses, 1); + expect((initResp.result as { serverInfo: { version: string } }).serverInfo.version).toBe("ipv6"); + + fx.send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); + const listResp = await waitForResponse(fx.responses, 2); + expect((listResp.result as { tools: unknown[] }).tools).toHaveLength(12); + fx.closeStdin(); + } finally { + await srv.stop().catch(() => undefined); + rmSync(dir, { recursive: true, force: true }); + } + }, 10_000); +}); diff --git a/tests/ssh-forward.test.ts b/tests/ssh-forward.test.ts new file mode 100644 index 0000000..995ef9e --- /dev/null +++ b/tests/ssh-forward.test.ts @@ -0,0 +1,799 @@ +/** + * ssh-forward.test.ts — 动态端口转发双路径内核与栈接线测试(REQ-0005 Phase 1) + */ +import { describe, expect, test } from "bun:test"; +import { spawn, type ChildProcess } from "node:child_process"; +import { EventEmitter } from "node:events"; +import * as net from "node:net"; +import { PassThrough } from "node:stream"; +import { + SshForwardManager, + normalizeForwardSpec, + renderDynamicForwardSpec, + parseMuxAllocatedPort, + parseSubprocessRemotePort, + buildInnerTcpBridgeCmd, + type ForwardInfo, +} from "../src/ssh-forward.js"; +import { renderEnterBridgeCommand, sshArgsFor } from "../src/ssh-helpers.js"; +import { SshPtyDriver } from "../src/ssh-pty-driver.js"; +import { LocalRuntimeDriver } from "../src/local-driver.js"; +import { RuntimeStack } from "../src/runtime-stack.js"; + +class MockChild extends EventEmitter { + stdout = new PassThrough(); + stderr = new PassThrough(); + pid = 42424; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + signals: NodeJS.Signals[] = []; + + constructor(private readonly onKill?: (sig: NodeJS.Signals, self: MockChild) => void) { + super(); + } + + kill(signal: NodeJS.Signals = "SIGTERM"): boolean { + this.signals.push(signal); + this.onKill?.(signal, this); + return true; + } + + finish(code: number | null, signal: NodeJS.Signals | null = null): void { + this.exitCode = code; + this.signalCode = signal; + this.emit("exit", code, signal); + this.emit("close", code, signal); + } +} + +describe("ssh-forward spec normalization & rendering", () => { + test("supports local/remote/dynamic, short aliases, default bindAddr, and IPv6 bracketing", () => { + const l = normalizeForwardSpec({ kind: "L", bindPort: 8080, targetHost: "db.internal", targetPort: 5432 }); + expect(l.kind).toBe("local"); + expect(l.flag).toBe("-L"); + expect(l.bindAddr).toBe("127.0.0.1"); + expect(renderDynamicForwardSpec(l)).toBe("127.0.0.1:8080:db.internal:5432"); + + const r = normalizeForwardSpec({ kind: "remote", bindAddr: "*", bindPort: 9000, targetHost: "::1", targetPort: 3000 }); + expect(r.flag).toBe("-R"); + expect(renderDynamicForwardSpec(r)).toBe("*:9000:[::1]:3000"); + + const d = normalizeForwardSpec({ kind: "D", bindAddr: "[::1]", bindPort: 1080 }); + expect(d.kind).toBe("dynamic"); + expect(d.bindAddr).toBe("::1"); + expect(renderDynamicForwardSpec(d)).toBe("[::1]:1080"); + + const omittedL = normalizeForwardSpec({ kind: "L", targetHost: "db.internal", targetPort: 5432 }); + expect(omittedL.bindPort).toBe(0); + const omittedR = normalizeForwardSpec({ kind: "R", targetHost: "127.0.0.1", targetPort: 3000 }); + expect(omittedR.bindPort).toBe(0); + const omittedD = normalizeForwardSpec({ kind: "D" }); + expect(omittedD.bindPort).toBe(0); + }); + + test("rejects invalid hosts, ports, ids, and injection payloads", () => { + expect(() => normalizeForwardSpec({ kind: "invalid" as never, bindPort: 80 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "D", bindPort: "auto" as never })).toThrow(/必须为整数/); + expect(() => normalizeForwardSpec({ kind: "L", bindAddr: "-evil", bindPort: 80, targetHost: "h", targetPort: 80 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "L", bindAddr: "127.0.0.1;id", bindPort: 80, targetHost: "h", targetPort: 80 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "L", bindPort: -1, targetHost: "h", targetPort: 80 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "L", bindPort: 70000, targetHost: "h", targetPort: 80 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "L", bindPort: 80, targetHost: "-h", targetPort: 80 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "R", bindPort: 80, targetHost: "h", targetPort: 0 })).toThrow(); + expect(() => normalizeForwardSpec({ kind: "D", bindPort: 1080, id: "bad id!" })).toThrow(); + }); + + test("parses allocated ports from mux and subprocess outputs", () => { + expect(parseMuxAllocatedPort("43210\n", "")).toBe(43210); + expect(parseMuxAllocatedPort("", "Allocated port 51234 for remote forward.\n")).toBe(51234); + expect(parseMuxAllocatedPort("0\n", "")).toBeUndefined(); + expect(parseSubprocessRemotePort("debug1: Allocated port 49152 for remote forward to localhost:3000")).toBe(49152); + }); +}); + +describe("SshForwardManager Path A (Mux -O forward / -O cancel)", () => { + test("uses mux when control socket check succeeds, handles remote port 0, and closes with exact port", async () => { + const calls: string[][] = []; + const mgr = new SshForwardManager({ + destArgs: ["ops@example.com"], + layerName: "prod", + _deps: { + muxControlPath: () => "/tmp/cm-prod", + execSsh: async (argv) => { + calls.push(argv); + if (argv.includes("check")) return { exitCode: 0, stdout: "Master running\n", stderr: "" }; + if (argv.includes("forward")) return { exitCode: 0, stdout: "43210\n", stderr: "" }; + if (argv.includes("cancel")) return { exitCode: 0, stdout: "", stderr: "" }; + return { exitCode: 1, stdout: "", stderr: "unexpected" }; + }, + }, + }); + + const info = await mgr.openForward({ + id: "r-dyn", + kind: "remote", + targetHost: "127.0.0.1", + targetPort: 3000, + }); + expect(info.transportMode).toBe("mux"); + expect(info.bindPort).toBe(43210); + expect(info.status).toBe("active"); + expect(calls[1]).toEqual(["-S", "/tmp/cm-prod", "-O", "forward", "-R", "127.0.0.1:0:127.0.0.1:3000", "ops@example.com"]); + + const closed = await mgr.closeForward("r-dyn"); + expect(closed).toEqual({ status: "stopped", forwardId: "r-dyn" }); + expect(calls[2]).toEqual(["-S", "/tmp/cm-prod", "-O", "cancel", "-R", "127.0.0.1:43210:127.0.0.1:3000", "ops@example.com"]); + + const again = await mgr.closeForward("r-dyn"); + expect(again).toEqual({ status: "already_closed", forwardId: "r-dyn" }); + }); + + test("rejects mux remote bindPort=0 when allocated port cannot be parsed", async () => { + const mgr = new SshForwardManager({ + destArgs: ["ops@example.com"], + _deps: { + muxControlPath: () => "/tmp/cm-prod", + execSsh: async (argv) => argv.includes("check") + ? { exitCode: 0, stdout: "", stderr: "" } + : { exitCode: 0, stdout: "ok", stderr: "" }, + }, + }); + + await expect(mgr.openForward({ kind: "R", bindPort: 0, targetHost: "localhost", targetPort: 80 })).rejects.toThrow(/未能解析/); + }); + + test("reports already_closed and unknown honestly on mux -O cancel", async () => { + let cancelMode: "not_found" | "broken" | "missing_socket" = "not_found"; + const mgr = new SshForwardManager({ + destArgs: ["ops@example.com"], + _deps: { + muxControlPath: () => "/tmp/cm-prod", + execSsh: async (argv) => { + if (argv.includes("check") || argv.includes("forward")) return { exitCode: 0, stdout: "", stderr: "" }; + if (cancelMode === "not_found") return { exitCode: 255, stdout: "", stderr: "mux_client_forward: forward not found" }; + if (cancelMode === "missing_socket") { + return { exitCode: 255, stdout: "", stderr: "Control socket connect(/tmp/cm-prod): No such file or directory" }; + } + return { exitCode: 255, stdout: "", stderr: "Control socket connect(/tmp/cm-prod): Connection refused" }; + }, + }, + }); + + const f1 = await mgr.openForward({ kind: "D", bindPort: 1080 }); + expect(await mgr.closeForward(f1.forwardId)).toEqual({ + status: "already_closed", + forwardId: f1.forwardId, + detail: "mux_client_forward: forward not found", + }); + + cancelMode = "broken"; + const f2 = await mgr.openForward({ kind: "D", bindPort: 1081 }); + const res2 = await mgr.closeForward(f2.forwardId); + expect(res2.status).toBe("unknown"); + expect(res2.detail).toContain("Connection refused"); + expect(mgr.listForwards().find((f) => f.forwardId === f2.forwardId)?.status).toBe("unknown"); + + cancelMode = "missing_socket"; + const res3 = await mgr.closeForward(f2.forwardId); + expect(res3.status).toBe("unknown"); + expect(res3.detail).toContain("No such file or directory"); + expect(mgr.listForwards().find((f) => f.forwardId === f2.forwardId)?.status).toBe("unknown"); + }); +}); + +describe("SshForwardManager Path B (Subprocess ssh -N fallback)", () => { + test("reports a confirmed SSH exit before returning a newly opened forward", async () => { + const manager = new SshForwardManager({ destArgs: ["fixture.invalid"], _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const child = new MockChild(); + setTimeout(() => { + child.stderr.write("debug1: Entering interactive session.\n"); + child.finish(255); + }, 5); + return child as unknown as ChildProcess; + }, + } }); + await expect(manager.openForward({ id: "exited-during-start", kind: "D", bindPort: 18081 })) + .rejects.toMatchObject({ forwardId: "exited-during-start", exitCode: 255 }); + expect(manager.listForwards()).toMatchObject([{ forwardId: "exited-during-start", status: "exited" }]); + }); + + test.each([true, false])("closeAll verifies a starting child that ignores SIGTERM (SIGKILL works: %s)", async (killWorks) => { + let finishOnKill = killWorks; + let onSpawn!: () => void; + const spawned = new Promise((resolve) => { onSpawn = resolve; }); + const child = new MockChild((signal, self) => { + if (signal === "SIGKILL" && finishOnKill) self.finish(0, signal); + }); + const mgr = new SshForwardManager({ destArgs: ["fixture.invalid"], _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { onSpawn(); return child as unknown as ChildProcess; }, + stopGraceMs: 15, killWaitMs: 20, + } }); + const opening = mgr.openForward({ id: "pending-close", kind: "L", bindPort: 18103, targetHost: "localhost", targetPort: 80 }); + void opening.catch(() => undefined); + try { + await spawned; + const result = await mgr.closeAll(); + expect(child.signals).toEqual(["SIGTERM", "SIGKILL"]); + expect(result).toMatchObject([{ forwardId: "pending-close", status: killWorks ? "stopped" : "unknown" }]); + if (killWorks) { + await expect(opening).rejects.toThrow(/已取消/); + } else { + await expect(opening).rejects.toMatchObject({ outcome: "unknown", forwardId: "pending-close" }); + expect(mgr.listForwards()).toMatchObject([{ forwardId: "pending-close", status: "unknown" }]); + finishOnKill = true; + await expect(mgr.closeForward("pending-close")).resolves.toMatchObject({ status: "stopped" }); + expect(mgr.listForwards()).toEqual([]); + } + } finally { + if (child.exitCode === null) child.finish(0); + await opening.catch(() => undefined); + } + }); + + test("falls back to subprocess when mux check fails, allocates local port=0, and strips static forwards", async () => { + const spawnedArgvs: string[][] = []; + const connParams = { + user: "ops", + port: 2222, + hostKeyPolicy: "strict" as const, + forwards: [{ kind: "L" as const, port: 9999, target: "localhost:99" }], + }; + const mgr = new SshForwardManager({ + destArgs: sshArgsFor({ host: "host.test", conn: { ...connParams, forwards: undefined } }), + muxDestArgs: sshArgsFor({ host: "host.test", conn: connParams }), + connParams, + _deps: { + muxControlPath: () => "/tmp/cm-missing", + execSsh: async () => ({ exitCode: 255, stdout: "", stderr: "not running" }), + spawnSsh: (argv) => { + spawnedArgvs.push(argv); + const child = new MockChild((sig, self) => { + if (sig === "SIGTERM") self.finish(0, "SIGTERM"); + }); + setTimeout(() => { + child.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 12345.\ndebug1: Entering interactive session.\r\n"); + }, 5); + return child as unknown as ChildProcess; + }, + }, + }); + + const info = await mgr.openForward({ kind: "L", bindPort: 0, targetHost: "db", targetPort: 5432 }); + expect(info.transportMode).toBe("subprocess"); + expect(info.bindPort).toBeGreaterThan(0); + expect(info.bindPort).toBeLessThanOrEqual(65535); + expect(spawnedArgvs[0]).toContain("-N"); + expect(spawnedArgvs[0]).toContain("ExitOnForwardFailure=yes"); + expect(spawnedArgvs[0]).toContain("StrictHostKeyChecking=yes"); + expect(spawnedArgvs[0]).not.toContain("9999:localhost:99"); + + expect(await mgr.closeForward(info.forwardId)).toEqual({ status: "stopped", forwardId: info.forwardId }); + }); + + test("opens remote port=0 via subprocess stderr Allocated port and handles unexpected exit", async () => { + let childRef!: MockChild; + const exits: ForwardInfo[] = []; + const mgr = new SshForwardManager({ + destArgs: ["ops@example.com"], + onForwardExit: (info) => exits.push(info), + _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { + childRef = new MockChild(); + setTimeout(() => { + childRef.stderr.write("debug1: Allocated port 55123 for remote forward to localhost:8000\n"); + }, 5); + return childRef as unknown as ChildProcess; + }, + }, + }); + + const info = await mgr.openForward({ kind: "remote", bindPort: 0, targetHost: "localhost", targetPort: 8000 }); + expect(info.bindPort).toBe(55123); + + childRef.finish(255); + expect(exits.length).toBe(1); + expect(exits[0]?.status).toBe("exited"); + expect(exits[0]?.exitCode).toBe(255); + expect(await mgr.closeForward(info.forwardId)).toEqual({ status: "already_closed", forwardId: info.forwardId }); + }); + + test("does not interpret an occupied port or a bind attempt as successful forwarding", async () => { + const occupied = net.createServer((socket) => socket.destroy()); + await new Promise((resolve) => occupied.listen(0, "127.0.0.1", resolve)); + const port = (occupied.address() as net.AddressInfo).port; + try { + const manager = new SshForwardManager({ destArgs: ["fixture.invalid"], _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const child = new MockChild((_signal, self) => self.finish(0)); + setTimeout(() => child.stderr.write(`debug1: Local forwarding listening on 127.0.0.1 port ${port}.\n`), 5); + return child as unknown as ChildProcess; + }, + } }); + await expect(manager.openForward({ kind: "D", bindPort: port, timeoutMs: 150 })).rejects.toThrow(/启动超时/); + expect(manager.listForwards()).toEqual([]); + } finally { + await new Promise((resolve) => occupied.close(() => resolve())); + } + }); + + test("waits for remote forwarding confirmation after entering the client loop", async () => { + const mgrFail = new SshForwardManager({ + destArgs: ["ops@example.com"], + _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const c = new MockChild(); + setTimeout(() => { + c.stderr.write("debug1: Entering interactive session.\nError: remote port forwarding failed for listen port 8080\n"); + c.finish(255); + }, 5); + return c as unknown as ChildProcess; + }, + }, + }); + await expect(mgrFail.openForward({ kind: "R", bindPort: 8080, targetHost: "localhost", targetPort: 80 })) + .rejects.toThrow(/remote port forwarding failed/); + + const manager = new SshForwardManager({ destArgs: ["fixture.invalid"], _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const child = new MockChild((_signal, self) => self.finish(0)); + setTimeout(() => child.stderr.write( + "debug1: Entering interactive session.\ndebug1: remote forward success for: listen 127.0.0.1:8081, connect localhost:80\n", + ), 5); + return child as unknown as ChildProcess; + }, + } }); + await expect(manager.openForward({ kind: "R", bindPort: 8081, targetHost: "localhost", targetPort: 80 })) + .resolves.toMatchObject({ status: "active", bindPort: 8081 }); + await manager.closeAll(); + }); + + test("escalates SIGTERM to SIGKILL and reports unknown when child refuses to exit", async () => { + let childKillRef!: MockChild; + const mgrKill = new SshForwardManager({ + destArgs: ["ops@example.com"], + _deps: { + muxControlPath: () => undefined, + stopGraceMs: 15, + killWaitMs: 50, + spawnSsh: () => { + childKillRef = new MockChild((sig, self) => { + if (sig === "SIGKILL") self.finish(null, "SIGKILL"); + }); + setTimeout(() => childKillRef.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 7001.\ndebug1: Entering interactive session.\n"), 5); + return childKillRef as unknown as ChildProcess; + }, + }, + }); + const f1 = await mgrKill.openForward({ kind: "L", bindPort: 7001, targetHost: "db", targetPort: 5432 }); + expect(await mgrKill.closeForward(f1.forwardId)).toEqual({ status: "stopped", forwardId: f1.forwardId }); + expect(childKillRef.signals).toEqual(["SIGTERM", "SIGKILL"]); + + const mgrStuck = new SshForwardManager({ + destArgs: ["ops@example.com"], + _deps: { + muxControlPath: () => undefined, + stopGraceMs: 15, + killWaitMs: 20, + spawnSsh: () => { + const c = new MockChild(); + setTimeout(() => c.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 7002.\ndebug1: Entering interactive session.\n"), 5); + return c as unknown as ChildProcess; + }, + }, + }); + const f2 = await mgrStuck.openForward({ kind: "L", bindPort: 7002, targetHost: "db", targetPort: 5432 }); + const stuckClose = await mgrStuck.closeForward(f2.forwardId); + expect(stuckClose.status).toBe("unknown"); + expect(mgrStuck.listForwards()[0]?.status).toBe("unknown"); + }); +}); + +describe("RuntimeStack & SshPtyDriver forward integration and boundaries", () => { + test("rejects dynamic forwards on local layer, inherit file-stdio mode, and multi-hop PTY chains", async () => { + const stack = new RuntimeStack(); + await stack.addLayer("local", new LocalRuntimeDriver()); + await expect(stack.openForward({ kind: "L", bindPort: 8080, targetHost: "db", targetPort: 5432 }, "local")) + .rejects.toThrow(/不支持动态端口转发/); + expect(stack.listForwards("local")).toEqual([]); + + const hopDriver = new SshPtyDriver({ + driver: "ssh", + target: "bastion", + config: { sshHops: ["inner"] }, + }); + await expect(hopDriver.openForward({ kind: "L", bindPort: 8080, targetHost: "db", targetPort: 5432 })) + .rejects.toThrow(/逐跳 PTY 登录链不可用/); + + const prevMode = process.env.FILAXIS_SSH_STDIO_MODE; + process.env.FILAXIS_SSH_STDIO_MODE = "inherit"; + try { + const inheritDriver = new SshPtyDriver({ driver: "ssh", target: "host" }); + await expect(inheritDriver.openForward({ kind: "L", bindPort: 8080, targetHost: "db", targetPort: 5432 })) + .rejects.toThrow(/FILAXIS_SSH_STDIO_MODE=inherit/); + } finally { + if (prevMode === undefined) delete process.env.FILAXIS_SSH_STDIO_MODE; + else process.env.FILAXIS_SSH_STDIO_MODE = prevMode; + } + }); + + test("wires forward events, cross-layer list/close, and destroys active forwards on layer removal", async () => { + let spawnedChild!: MockChild; + const sshDriver = new SshPtyDriver({ driver: "ssh", target: "ops@app" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + spawnedChild = new MockChild((sig, self) => { + if (sig === "SIGTERM") self.finish(0, "SIGTERM"); + }); + setTimeout(() => { + spawnedChild.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 8081.\ndebug1: Entering interactive session.\n"); + }, 5); + return spawnedChild as unknown as ChildProcess; + }, + }, + }); + + const stack = new RuntimeStack(); + await stack.addLayer("app", sshDriver); + const events: Array<{ type: string; layer?: string; forward?: ForwardInfo }> = []; + stack.events.on("forwardExit", (e) => events.push(e as { type: string; layer?: string; forward?: ForwardInfo })); + + const f1 = await stack.openForward({ id: "web-8081", kind: "L", bindPort: 8081, targetHost: "127.0.0.1", targetPort: 80 }); + expect(f1.layer).toBe("app"); + expect(stack.listForwards().map((f) => f.forwardId)).toEqual(["web-8081"]); + await expect(stack.closeForward("missing-id")).rejects.toThrow(/不存在/); + + await stack.removeLayer("app", { destroy: true }); + expect(spawnedChild.signals).toContain("SIGTERM"); + expect(sshDriver.listForwards()[0]?.status).toBe("stopped"); + expect(events).toEqual([]); + }); + + test("a forward can still be closed by ID after its last layer name is removed and reused", async () => { + const driver = new SshPtyDriver({ driver: "ssh", target: "fixture.invalid" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const child = new MockChild((signal, self) => { if (signal === "SIGTERM") self.finish(0, signal); }); + setTimeout(() => child.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 18082.\ndebug1: Entering interactive session.\n"), 5); + return child as unknown as ChildProcess; + }, + }, + }); + const stack = new RuntimeStack(); + try { + await stack.addLayer("fixture", driver); + const spec = { id: "detached", kind: "L", bindPort: 18082, targetHost: "localhost", targetPort: 80 } as const; + const { forwardId } = await stack.openForward(spec, "fixture"); + await stack.removeLayer("fixture"); + await stack.addLayer("fixture", new LocalRuntimeDriver()); + expect(stack.listForwards("fixture")).toEqual([]); + expect(stack.listForwards()).toMatchObject([{ forwardId, status: "active" }]); + expect(stack.listForwards()[0]).not.toHaveProperty("layer"); + await expect(stack.closeForward(forwardId)).resolves.toMatchObject({ status: "stopped" }); + expect(stack.listForwards()).toEqual([]); + } finally { + await driver.destroy(); + } + }); + + test("emits forwardExit event on RuntimeStack when managed tunnel exits unexpectedly", async () => { + let spawnedChild!: MockChild; + const sshDriver = new SshPtyDriver({ driver: "ssh", target: "ops@app" }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + spawnedChild = new MockChild(); + setTimeout(() => { + spawnedChild.stderr.write("debug1: Local forwarding listening on 127.0.0.1 port 8082.\ndebug1: Entering interactive session.\n"); + }, 5); + return spawnedChild as unknown as ChildProcess; + }, + }, + }); + + const stack = new RuntimeStack(); + await stack.addLayer("app", sshDriver); + const events: Array<{ type: string; layer?: string; forward: ForwardInfo }> = []; + stack.events.on("forwardExit", (e) => { + if (e.type === "forwardExit") events.push(e); + }); + + await stack.openForward({ id: "tunnel-drop", kind: "L", bindPort: 8082, targetHost: "127.0.0.1", targetPort: 80 }); + spawnedChild.finish(1); + + expect(events.length).toBe(1); + expect(events[0]?.layer).toBe("app"); + expect(events[0]?.forward.forwardId).toBe("tunnel-drop"); + expect(events[0]?.forward.status).toBe("exited"); + }); + + test("rejects concurrent duplicate forwardId, reaps pending child on closeAll, tags mux timeout unknown, and rejects cross-layer duplicate id", async () => { + // 1) Concurrent duplicate forwardId & closeAll reaping pending subprocess + let pendingChild!: MockChild; + const slowMgr = new SshForwardManager({ + destArgs: ["ops@slow"], + _deps: { + muxControlPath: () => undefined, + spawnSsh: () => { + pendingChild = new MockChild((sig, self) => { + if (sig === "SIGTERM") self.finish(0, "SIGTERM"); + }); + return pendingChild as unknown as ChildProcess; + }, + }, + }); + const p1 = slowMgr.openForward({ id: "dup-id", kind: "L", bindPort: 17001, targetHost: "db", targetPort: 5432 }); + const p2 = slowMgr.openForward({ id: "dup-id", kind: "L", bindPort: 17002, targetHost: "db", targetPort: 5432 }); + await expect(p2).rejects.toThrow(/已存在或正在建立/); + await slowMgr.closeAll(); + await expect(p1).rejects.toThrow(/已关闭|建链失败/); + expect(pendingChild.signals).toContain("SIGTERM"); + + // 2) Mux timeout carries outcome: "unknown" + const timeoutMgr = new SshForwardManager({ + destArgs: ["ops@mux"], + _deps: { + muxControlPath: () => "/tmp/cm-mux", + execSsh: async (argv) => argv.includes("check") + ? { exitCode: 0, stdout: "ok", stderr: "" } + : { exitCode: null, stdout: "", stderr: "", timedOut: true }, + }, + }); + let muxErr: (Error & { outcome?: string }) | undefined; + try { + await timeoutMgr.openForward({ kind: "L", bindPort: 17003, targetHost: "db", targetPort: 5432 }); + } catch (e) { + muxErr = e as Error & { outcome?: string }; + } + expect(muxErr?.outcome).toBe("unknown"); + + // 3) Cross-layer duplicate forwardId rejection in RuntimeStack + const mkDrv = (target: string, port: number) => new SshPtyDriver({ driver: "ssh", target }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const c = new MockChild((sig, self) => { + if (sig === "SIGTERM") self.finish(0, "SIGTERM"); + }); + setTimeout(() => c.stderr.write(`debug1: Local forwarding listening on 127.0.0.1 port ${port}.\ndebug1: Entering interactive session.\n`), 5); + return c as unknown as ChildProcess; + }, + }, + }); + const stack = new RuntimeStack(); + await stack.addLayer("a", mkDrv("ops@a", 17010)); + await stack.addLayer("b", mkDrv("ops@b", 17011)); + await stack.openForward({ id: "shared-name", kind: "L", bindPort: 17010, targetHost: "db", targetPort: 5432 }, "a"); + await expect( + stack.openForward({ id: "shared-name", kind: "L", bindPort: 17011, targetHost: "db", targetPort: 5432 }, "b"), + ).rejects.toThrow(/已在层 'a' 中存在/); + await stack.removeLayer("a", { destroy: true }); + await stack.removeLayer("b", { destroy: true }); + }); + + test("tags forwardExit events with the emitting driver layer rather than the first bridged driver", async () => { + const children: MockChild[] = []; + const mkDrv = (target: string, port: number) => new SshPtyDriver({ driver: "ssh", target }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const c = new MockChild(); + children.push(c); + setTimeout(() => c.stderr.write(`debug1: Local forwarding listening on 127.0.0.1 port ${port}.\ndebug1: Entering interactive session.\n`), 5); + return c as unknown as ChildProcess; + }, + }, + }); + const stack = new RuntimeStack(); + const events: Array<{ type: string; layer?: string; forward?: { forwardId: string; layer?: string; status: string } }> = []; + stack.events.on("forwardExit", (e) => events.push(e as never)); + + await stack.addLayer("layer-a", mkDrv("ops@a", 17020)); + await stack.addLayer("layer-b", mkDrv("ops@b", 17021)); + + await stack.openForward({ id: "fwd-b", kind: "L", bindPort: 17021, targetHost: "db", targetPort: 5432 }, "layer-b"); + expect(children).toHaveLength(1); + children[0]!.finish(255, null); + + expect(events).toHaveLength(1); + expect(events[0]!.layer).toBe("layer-b"); + expect(events[0]!.forward).toMatchObject({ forwardId: "fwd-b", layer: "layer-b", status: "exited" }); + + await stack.removeLayer("layer-a", { destroy: true }); + await stack.removeLayer("layer-b", { destroy: true }); + }); +}); + +describe("enterPipeline layer-penetrating dynamic forwarding (stdio-bridge)", () => { + test("renders binary-safe multi-layer argv bridge commands and rejects interactive steps", () => { + const inner = buildInnerTcpBridgeCmd("python3", "127.0.0.1", 6379); + const single = renderEnterBridgeCommand([{ cmd: "docker exec -it web bash" }], inner); + expect(single.kind).toBe("ok"); + if (single.kind === "ok") { + expect(single.command).toContain("'docker' 'exec' '-i' 'web' 'bash' '-c'"); + expect(single.command).not.toContain("-it"); + } + + const nested = renderEnterBridgeCommand([ + { cmd: "ssh -t vm-b" }, + { cmd: "docker exec -it app-ctr sh" }, + ], buildInnerTcpBridgeCmd("socat", "127.0.0.1", 8080)); + expect(nested.kind).toBe("ok"); + if (nested.kind === "ok") { + expect(nested.command).toContain("'ssh' '-T' 'vm-b' 'sh' '-c'"); + expect(nested.command).toContain("socat"); + } + + const bad = renderEnterBridgeCommand([{ cmd: "su - app" }], inner); + expect(bad.kind).toBe("unreachable"); + }); + + test("guards enterPipeline layers against -R/-D host leaks, missing tools, and interactive steps", async () => { + const makeDrv = (enterCmd: string, probeOut = "socat", probeCode = 0) => new SshPtyDriver({ + driver: "ssh", + target: "ops@host", + config: { enterPipeline: [{ cmd: enterCmd }] }, + }); + + const d1 = makeDrv("docker exec -it web bash"); + d1.exec = async () => ({ stdout: "", stderr: "", exitCode: 0 }); + await expect(d1.openForward({ kind: "R", bindPort: 0, targetHost: "127.0.0.1", targetPort: 80 })).rejects.toThrow(/仅支持 -L/); + await expect(d1.openForward({ kind: "D", bindPort: 0 })).rejects.toThrow(/仅支持 -L/); + + d1.exec = async () => ({ stdout: "", stderr: "", exitCode: 127 }); + await expect(d1.openForward({ kind: "L", bindPort: 0, targetHost: "127.0.0.1", targetPort: 80 })).rejects.toThrow(/socat/); + + const dBad = makeDrv("su - root"); + dBad.exec = async () => ({ stdout: "socat\n", stderr: "", exitCode: 0 }); + await expect(dBad.openForward({ kind: "L", bindPort: 0, targetHost: "127.0.0.1", targetPort: 80 })).rejects.toThrow(/无法建立穿层动态转发/); + }); + + test("forwards TCP traffic through stdio-bridge into target loopback port and cleans up on close", async () => { + // Simulate a 3rd-layer container loopback TCP service on an ephemeral local port + const echoServer = net.createServer((sock) => { + sock.on("data", (chunk: Buffer | string) => { + const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk; + sock.write(Buffer.concat([Buffer.from("ctr:"), buf])); + }); + }); + await new Promise((resolve) => echoServer.listen(0, "127.0.0.1", () => resolve())); + const containerPort = (echoServer.address() as net.AddressInfo).port; + + let capturedArgv: string[] = []; + const drv = new SshPtyDriver({ + driver: "ssh", + target: "ops@host", + config: { enterPipeline: [{ cmd: "docker exec -it web bash" }] }, + }, { + _forwardDeps: { + spawnBridge: (argv) => { + capturedArgv = argv; + // Verify rendered remote command ends with node inner TCP bridge script, then execute the inner node bridge directly against containerPort + const remoteCmd = argv[argv.length - 1] ?? ""; + expect(remoteCmd).toContain("docker"); + expect(remoteCmd).toContain("-i"); + expect(remoteCmd).toContain("node"); + return spawn(process.execPath, [ + "-e", + "const net=require('node:net');const s=net.createConnection({host:'127.0.0.1',port:Number(process.argv[1])});s.on('error',()=>process.exit(1));process.stdin.on('error',()=>s.destroy());process.stdout.on('error',()=>s.destroy());process.stdin.pipe(s);s.pipe(process.stdout);s.on('close',()=>process.exit(0));", + String(containerPort), + ], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + }, + }, + }); + drv.exec = async () => ({ stdout: "node\n", stderr: "", exitCode: 0 }); + + let client: net.Socket | undefined; + try { + const info = await drv.openForward({ + id: "ctr-db", + kind: "L", + targetHost: "127.0.0.1", + targetPort: containerPort, + }); + expect(info.transportMode).toBe("stdio-bridge"); + expect(info.bindPort).toBeGreaterThan(0); + + const reply = await new Promise((resolve, reject) => { + const c = net.createConnection({ host: "127.0.0.1", port: info.bindPort }); + client = c; + c.once("error", reject); + c.once("data", (d) => { + const text = d.toString("utf-8"); + resolve(text); + }); + c.write("hello-layer3"); + }); + expect(reply).toBe("ctr:hello-layer3"); + expect(capturedArgv).toContain("ops@host"); + + const closed = await Promise.race([ + drv.closeForward("ctr-db"), + new Promise((_, reject) => setTimeout(() => reject(new Error("close waited for the client to disconnect")), 2_000).unref()), + ]); + expect(closed.status).toBe("stopped"); + } finally { + client?.destroy(); + await drv.destroy().catch(() => undefined); + await new Promise((r) => echoServer.close(() => r())); + } + }, 15_000); + + test("keeps a disconnected bridge child addressable until its exit is verified", async () => { + let spawned!: () => void; + let killAttempted!: () => void; + const childStarted = new Promise((resolve) => { spawned = resolve; }); + const kill = new Promise((resolve) => { killAttempted = resolve; }); + const child = new MockChild((signal) => { + if (signal === "SIGKILL") killAttempted(); + }); + const drv = new SshPtyDriver({ + driver: "ssh", target: "fixture.invalid", + config: { enterPipeline: [{ cmd: "docker exec -i fixture sh" }] }, + }, { + _forwardDeps: { + spawnBridge: () => { spawned(); return child as unknown as ChildProcess; }, + stopGraceMs: 15, + killWaitMs: 20, + }, + }); + drv.exec = async () => ({ stdout: "node\n", stderr: "", exitCode: 0 }); + let client: net.Socket | undefined; + try { + const info = await drv.openForward({ id: "disconnect", kind: "L", targetHost: "127.0.0.1", targetPort: 8080 }); + client = net.createConnection({ host: "127.0.0.1", port: info.bindPort }); + await childStarted; + client.destroy(); + await kill; + await expect(drv.closeForward("disconnect")).resolves.toMatchObject({ status: "unknown" }); + child.finish(0, "SIGKILL"); + await expect(drv.closeForward("disconnect")).resolves.toMatchObject({ status: "stopped" }); + } finally { + client?.destroy(); + if (child.exitCode === null) child.finish(0); + await drv.destroy(); + } + }, 15_000); + + test("[P1] blocks cross-layer concurrent duplicate forwardId before async open settles", async () => { + const mkSlowDrv = (target: string, port: number) => new SshPtyDriver({ driver: "ssh", target }, { + _forwardDeps: { + muxControlPath: () => undefined, + spawnSsh: () => { + const c = new MockChild((sig, self) => { + if (sig === "SIGTERM") self.finish(0, "SIGTERM"); + }); + setTimeout(() => c.stderr.write(`debug1: Local forwarding listening on 127.0.0.1 port ${port}.\ndebug1: Entering interactive session.\n`), 50); + return c as unknown as ChildProcess; + }, + }, + }); + const stack = new RuntimeStack(); + await stack.addLayer("a", mkSlowDrv("ops@a", 17110)); + await stack.addLayer("b", mkSlowDrv("ops@b", 17111)); + + try { + const pA = stack.openForward({ id: "race-id", kind: "L", bindPort: 17110, targetHost: "db", targetPort: 5432 }, "a"); + const pB = stack.openForward({ id: "race-id", kind: "L", bindPort: 17111, targetHost: "db", targetPort: 5432 }, "b"); + + await expect(pB).rejects.toThrow(/正在层 'a' 中建立/); + const infoA = await pA; + expect(infoA).toMatchObject({ forwardId: "race-id", layer: "a", status: "active" }); + + const closed = await stack.closeForward("race-id"); + expect(closed.status).toBe("stopped"); + expect(stack.listForwards().filter((f) => f.status === "active")).toHaveLength(0); + } finally { + await stack.removeLayer("a", { destroy: true }); + await stack.removeLayer("b", { destroy: true }); + } + }); +}); diff --git a/tests/ssh-transport.test.ts b/tests/ssh-transport.test.ts index 36e0855..55f72d0 100644 --- a/tests/ssh-transport.test.ts +++ b/tests/ssh-transport.test.ts @@ -7,7 +7,7 @@ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSy import { tmpdir } from "node:os"; import { join } from "node:path"; import { - sshArgsFor, hopLabel, enterStepsOf, renderExecChannel, envPrefixOf, parseJumpSpec, + sshArgsFor, hopSshCommand, hopLabel, enterStepsOf, renderExecChannel, envPrefixOf, parseJumpSpec, } from "../src/ssh-helpers.js"; import { __testBrokenStdioExit, __testFileRedirect, resolveLayerState, SshPtyDriver } from "../src/ssh-pty-driver.js"; import { RemoteSessionManager } from "../src/remote-session-manager.js"; @@ -24,7 +24,7 @@ test.skipIf(process.platform !== "linux")("SSH writeFile 解码器写出一部 let fail = true; Object.assign(driver, { async execChannel(command: string) { - const result = Bun.spawnSync(["sh", "-c", (fail ? failDecode : "") + command]); + const result = Bun.spawnSync(["sh", "-c", (fail ? failDecode : "") + command], { windowsHide: true }); return { stdout: result.stdout.toString(), stderr: result.stderr.toString(), exitCode: result.exitCode }; }, }); @@ -135,7 +135,7 @@ describe("ssh-helpers", () => { }); // 产物作为命令行交给真实 sh 解析(模拟 PTY 发送):set -- 拿 argv——命令替换 // 若被展开会创建文件且 argv 不再字面 - const p = Bun.spawn([shPath, "-c", `set -- ${line}; printf '%s' "$@"`], { stdout: "pipe" }); + const p = Bun.spawn([shPath, "-c", `set -- ${line}; printf '%s' "$@"`], { stdout: "pipe", windowsHide: true }); const out = await new Response(p.stdout).text(); expect(await p.exited).toBe(0); expect(out).toContain("$(touch FXS_QUOTED_PWN)"); // 字面到达(未展开) @@ -202,7 +202,7 @@ describe("ssh-helpers", () => { const sh = Bun.which("sh"); if (!sh) return; // CI Linux / Git Bash 均有 sh const runSh = async (stdinCmd: string) => { - const p = Bun.spawn([sh, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([sh, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(stdinCmd); await p.stdin.end(); const [out, err, code] = await Promise.all([ @@ -310,7 +310,7 @@ describe("ssh-helpers", () => { expect(r.kind).toBe("ok"); if (r.kind !== "ok") return; // 首层 argv 形态 [sh, -s, sh, -s] 等价于本地:sh -s 吃 stdinCmd(含内层 heredoc) - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(r.stdinCmd); await p.stdin.end(); const [out, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -340,7 +340,7 @@ describe("ssh-helpers", () => { const sh = Bun.which("sh") && Bun.which("printenv"); if (!sh) return; // CI Linux / Git Bash const runSh = async (stdinCmd: string) => { - const p = Bun.spawn(["sh", "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn(["sh", "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(stdinCmd); await p.stdin.end(); // Bun FileSink:错误以 reject 形式从 end() 抛出(可捕获,无 uncaught 路径) const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -514,7 +514,7 @@ describe("RemoteSessionManager(mock 远端)", () => { const script = `cat() { :; }; awk() { printf '%s\\n' "$FX_TEST_STAMP"; }; ` + `pkill() { :; }; kill() { printf '%s\\n' "$1"; }; sleep() { :; }; ${cmd}`; const r = Bun.spawnSync([shell, "-s"], { - stdin: Buffer.from(script), env: { ...process.env, FX_TEST_STAMP: stamp }, + stdin: Buffer.from(script), env: { ...process.env, FX_TEST_STAMP: stamp }, windowsHide: true, }); const signal = r.stdout.toString().trim().replace(/^-/, ""); if (signal) signals.push(signal); @@ -664,7 +664,7 @@ describe("RemoteSessionManager(mock 远端)", () => { const logDir = join(dirG, "occupied"); // 普通文件(非目录) writeFileSync(logDir, "not a dir\n"); const realExec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -684,7 +684,7 @@ describe("RemoteSessionManager(mock 远端)", () => { const dirX = mkdtempSync(join(tmpdir(), "fx-exit-")); const logDir = dirX.replace(/\\/g, "/"); const realExec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -713,7 +713,7 @@ describe("RemoteSessionManager(mock 远端)", () => { const dirT = mkdtempSync(join(tmpdir(), "fx-tl-")); const logDir = dirT.replace(/\\/g, "/"); const realExec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn(["sh", "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn(["sh", "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -740,6 +740,29 @@ describe("RemoteSessionManager(mock 远端)", () => { import { autonomousSshOpts } from "../src/ssh-helpers.js"; describe("host key 策略可配(AC-12)", () => { + test("renders a known_hosts path with spaces as one OpenSSH config value", () => { + const path = process.platform === "win32" ? "C:\\SSH data\\known_hosts" : "/fixture/SSH data/known_hosts"; + const expected = process.platform === "win32" ? "C:/SSH data/known_hosts" : path; + expect(autonomousSshOpts({ knownHostsFile: path })).toContain(`UserKnownHostsFile="${expected}"`); + }); + + test("PTY hop keeps file arguments intact and lets remote OpenSSH resolve its own home", () => { + const command = hopSshCommand({ + host: "fixture.invalid", + conn: { + knownHostsFile: "~/SSH data/known_hosts", + keyFile: "~/SSH data/id_fixture", + jump: { host: "jump.invalid", keyFile: "~/SSH data/id_jump" }, + }, + }); + const argv = Bun.spawnSync([resolveLocalShell(), "-c", `ssh() { printf '%s\\n' "$@"; }; ${command}`], { windowsHide: true }); + expect(argv.exitCode).toBe(0); + const args = argv.stdout.toString().trimEnd().split(/\r?\n/); + expect(args).toContain('UserKnownHostsFile="~/SSH data/known_hosts"'); + expect(args).toContain("~/SSH data/id_fixture"); + expect(args.find((arg) => arg.startsWith("ProxyCommand="))).toContain("-i '~/SSH data/id_jump'"); + }, 15_000); + test("tofu 缺省=accept-new;strict=yes+known_hosts 路径展开", () => { const tofu = autonomousSshOpts(); expect(tofu).toContain("StrictHostKeyChecking=accept-new"); @@ -800,7 +823,7 @@ describe("二十二期(真实 sh)", () => { const mkReal = (logDir: string, pollMs = 200) => { const shPath = Bun.which("sh")!; const exec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -841,7 +864,7 @@ describe("二十二期(真实 sh)", () => { const binSh = (logDir + "/bin").replace(/^([A-Za-z]):/, (_m, dr: string) => "/" + dr.toLowerCase()); const shPath = Bun.which("sh")!; const exec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(`export PATH=${binSh}:$PATH; ${cmd}`); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -863,7 +886,7 @@ describe("终态尾行冲刷(二十三期)", () => { const logDir = d.replace(/\\/g, "/"); const shPath = Bun.which("sh")!; const exec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -892,7 +915,7 @@ describe("reapIdle 事件单发(自审)", () => { const logDir = d.replace(/\\/g, "/"); const shPath = Bun.which("sh")!; const exec = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -1202,7 +1225,7 @@ describe("Sol 71:readLog lines 字节保真", () => { const remote = fakeRemote(); const shPath = Bun.which("sh")!; const realSh = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -1241,7 +1264,7 @@ describe("Sol 72:lines 临时副本落 TMPDIR", () => { let sawCmd = ""; const realSh = async (cmd: string): Promise<{ stdout: string; exitCode: number }> => { const p = Bun.spawn([shell, "--posix", "-s"], { - stdin: "pipe", stdout: "pipe", stderr: "pipe", + stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true, env: { ...process.env, TMPDIR: scratch.replaceAll("\\", "/") }, }); p.stdin.write(cmd); @@ -1278,7 +1301,7 @@ describe("Sol 73:TMPDIR 失效回落", () => { const remote = fakeRemote(); const shPath = Bun.which("sh")!; const realSh = async (cmd: string, env?: Record): Promise<{ stdout: string; exitCode: number }> => { - const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", env: { ...process.env, ...env } }); + const p = Bun.spawn([shPath, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true, env: { ...process.env, ...env } }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); diff --git a/tests/terminal.test.ts b/tests/terminal.test.ts index 637c34f..ac2ea9e 100644 --- a/tests/terminal.test.ts +++ b/tests/terminal.test.ts @@ -522,7 +522,7 @@ test.each([ const script = `cat() { case "$1" in *.pid) printf 4242;; *.st) printf '%s' "$FX_TEST_STAMP";; esac; }; ` + `awk() { printf 11111; }; kill() { printf '%s\\n' "$1"; }; ${command}`; const run = Bun.spawnSync([shell, "--posix", "-s"], { - stdin: Buffer.from(script), env: { ...process.env, FX_TEST_STAMP: stamp }, + stdin: Buffer.from(script), env: { ...process.env, FX_TEST_STAMP: stamp }, windowsHide: true, }); const signal = run.stdout.toString().trim().replace(/^-/, ""); if (signal) signals.push(signal); @@ -921,7 +921,7 @@ describe("tmux execSession 启动握手(孪生对齐审计)", () => { // 真 Bash 执行整条握手链(Astra 同款复现手法):注入目标零创建(主断言—— // 链是否在慢 bash 环境跑完 3s 握手窗是环境变量〔Gemini 环境实测 exit 1〕, // 与注入封死无关——exitCode 弱断言仅排崩溃级) - const r = Bun.spawnSync(["bash", "-c", seen], { timeout: 15_000 }); + const r = Bun.spawnSync(["bash", "-c", seen], { timeout: 15_000, windowsHide: true }); expect(r.exitCode).not.toBeLessThan(0); expect(existsSync(probe)).toBe(false); // 修前:$(touch) 每次求值都执行 }, 15_000); @@ -1017,7 +1017,7 @@ describe("Sol 74:tmux 会话语义", () => { spawnSession: async () => "fx74", runCommand: async (_id: string, cmd: string, _t?: number) => { hooks.onPage?.(cmd); - const p = Bun.spawn([shPath(), "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([shPath(), "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -1039,7 +1039,7 @@ describe("Sol 74:tmux 会话语义", () => { const tok = `/tmp/fx-grp-tok-${Math.random().toString(36).slice(2, 8)}`; const g = Bun.spawnSync([sh, "-c", `setsid sh -c 'echo \$\$ > ${tok}; sleep 5 >/dev/null 2>&1 /dev/null 2>&1 /dev/null"]); + "sleep 0.4; cat " + tok + " 2>/dev/null"], { windowsHide: true }); const pgid = g.stdout.toString().trim(); if (!/^\d+$/.test(pgid)) return; // 无 setsid——环境不适用(CI Linux 矩阵覆盖) mkdirSync("/tmp/filaxis-sessions", { recursive: true }); @@ -1052,7 +1052,7 @@ describe("Sol 74:tmux 会话语义", () => { expect((await drv.verifySession(sid)).status).toBe("running"); // 修前:组长死组活被报 DEAD→unknown const st = await drv.stopSession(sid); // 组杀收口(TERM 组 → 核实窗 → 最多 KILL) } finally { - Bun.spawnSync([sh, "-c", `rm -f ${base}.pid ${base}.pgid ${base}.st ${base}.code ${tok}; kill -TERM -- -${pgid} 2>/dev/null; true`]); + Bun.spawnSync([sh, "-c", `rm -f ${base}.pid ${base}.pgid ${base}.st ${base}.code ${tok}; kill -TERM -- -${pgid} 2>/dev/null; true`], { windowsHide: true }); } }, 20_000); @@ -1068,7 +1068,7 @@ describe("Sol 74:tmux 会话语义", () => { const m = cmd.match(/tail -c \+\d+ (\S+)/); if (!m) return; if (!myTmp) { myTmp = m[1]!; return; } // 首页:捕获中转名 - if (!hit) { hit = true; Bun.spawnSync([shPath(), "-c", `rm -f ${myTmp}`]); } // 次页前删它 + if (!hit) { hit = true; Bun.spawnSync([shPath(), "-c", `rm -f ${myTmp}`], { windowsHide: true }); } // 次页前删它 } }); await expect(drv.fs.readFile(src)).rejects.toThrow(/分页读失败|长度对账|无效 Base64/); // 修前:~5922B 正常完成 }, 20_000); @@ -1154,7 +1154,7 @@ describe("Sol 75:持久 shell 语义/组长身份", () => { test.skipIf(!Bun.which("sh"))("P2-3 组长活但 .st 不符 → unknown(复用组拦截;修前组存活直信 running)", async () => { const sh = Bun.which("sh")!; // 自有活组长:exec setsid sleep——pid==pgid 且活着(stdio 全重定向防拖挂) - const g = Bun.spawnSync([sh, "-c", "setsid sh -c 'exec sleep 5 >/dev/null 2>&1 /dev/null 2>&1 /dev/null 2>&1 /dev/null 2>&1 { const stubTerminal = { spawnSession: async () => "fx75", runCommand: async (_id: string, cmd: string, _t?: number) => { - const p = Bun.spawn([sh, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([sh, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -1181,7 +1181,7 @@ describe("Sol 75:持久 shell 语义/组长身份", () => { ); expect((await drv.verifySession(sid)).status).toBe("unknown"); // 修前:running(组存活直信) } finally { - Bun.spawnSync([sh, "-c", `rm -f ${base}.pid ${base}.pgid ${base}.st; kill -TERM ${pid} 2>/dev/null; true`]); + Bun.spawnSync([sh, "-c", `rm -f ${base}.pid ${base}.pgid ${base}.st; kill -TERM ${pid} 2>/dev/null; true`], { windowsHide: true }); } }, 20_000); }); @@ -1197,7 +1197,7 @@ describe("Sol 76:组长死放行组信号/registry 列表甄别", () => { const tok2 = `/tmp/fx-grp-tok-${Math.random().toString(36).slice(2, 8)}`; const g = Bun.spawnSync([sh, "-c", `setsid sh -c 'echo \$\$ > ${tok2}; sleep 8 >/dev/null 2>&1 /dev/null 2>&1 /dev/null"]); + "sleep 0.4; cat " + tok2 + " 2>/dev/null"], { windowsHide: true }); const pgid = g.stdout.toString().trim(); if (!/^\d+$/.test(pgid)) return; mkdirSync("/tmp/filaxis-sessions", { recursive: true }); @@ -1209,7 +1209,7 @@ describe("Sol 76:组长死放行组信号/registry 列表甄别", () => { const stubTerminal = { spawnSession: async () => "fx76", runCommand: async (_id: string, cmd: string, _t?: number) => { - const p = Bun.spawn([sh, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn([sh, "-s"], { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); p.stdin.write(cmd); await p.stdin.end(); const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); @@ -1227,11 +1227,11 @@ describe("Sol 76:组长死放行组信号/registry 列表甄别", () => { const st = await drv.stopSession(sid); // 修前:unknown(.st 卡死不放行)+孙进程照跑 expect(["stopped", "unknown"]).toContain(st.status); // 组信号已放行——孙进程应死(组探不到了) - const probe = Bun.spawnSync([sh, "-c", `/bin/kill -0 -- -${pgid} 2>/dev/null && echo ALIVE || echo DEAD`]); + const probe = Bun.spawnSync([sh, "-c", `/bin/kill -0 -- -${pgid} 2>/dev/null && echo ALIVE || echo DEAD`], { windowsHide: true }); expect(probe.stdout.toString().trim()).toBe("DEAD"); void t0; } finally { - Bun.spawnSync([sh, "-c", `rm -f ${base}.pid ${base}.pgid ${base}.st ${base}.code ${tok2}; /bin/kill -KILL -- -${pgid} 2>/dev/null; true`]); + Bun.spawnSync([sh, "-c", `rm -f ${base}.pid ${base}.pgid ${base}.st ${base}.code ${tok2}; /bin/kill -KILL -- -${pgid} 2>/dev/null; true`], { windowsHide: true }); } }, 30_000); @@ -2163,7 +2163,7 @@ describe("Sol 90:首发失败封存/跨进程锁/readdir 补全", () => { `import { CommandExecuter } from ${JSON.stringify(source)}; ` + `try { await new CommandExecuter({resolvePane: async id => ({target:id, lockPath:CommandExecuter.__testSessLockPath(id), assertIdle: async () => {}, setInput: async () => {}})}).execute("S90F", "true", { timeoutMs: 20 }); process.exitCode = 1; } ` + `catch (e) { console.log(e.message); }`, - ], { stdout: "pipe", stderr: "inherit" }); + ], { stdout: "pipe", stderr: "inherit", windowsHide: true }); expect(await new Response(child.stdout).text()).toContain("已封存"); expect(await child.exited).toBe(0); } finally { @@ -2181,7 +2181,7 @@ describe("Sol 90:首发失败封存/跨进程锁/readdir 补全", () => { writeFileSync(lockPath, ""); const child = Bun.spawn([process.execPath, "-e", 'setTimeout(() => require("node:fs").rmSync(process.argv[1]), 1500);', "--", lockPath, - ], { stdout: "ignore", stderr: "ignore" }); + ], { stdout: "ignore", stderr: "ignore", windowsHide: true }); const realInvoke = TmuxInvoker.invoke.bind(TmuxInvoker); const realTry = TmuxInvoker.tryInvoke.bind(TmuxInvoker); let marker = ""; From 5ab6251cbfffa8f3dbf93dcb204f306650975c1c Mon Sep 17 00:00:00 2001 From: corolin Date: Wed, 25 Nov 2026 16:49:33 +0800 Subject: [PATCH 2/2] Harden release error serialization and runtime identifiers --- src/daemon-server.ts | 2 +- src/file-transfer.ts | 5 +---- src/terminal/session-launcher.ts | 3 ++- tests/daemon.test.ts | 5 +++++ 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/daemon-server.ts b/src/daemon-server.ts index 9017076..eba055b 100644 --- a/src/daemon-server.ts +++ b/src/daemon-server.ts @@ -1006,7 +1006,7 @@ function serializeRpcError(err: unknown): Record { }; return { ok: false, - error: err instanceof Error ? err.message : String(err), + error: err instanceof Error ? err.message : "Daemon RPC 执行失败", ...(err instanceof Error ? { name: err.name } : {}), ...(typeof obj.code === "string" || typeof obj.code === "number" ? { code: obj.code } : {}), ...(typeof obj.partialOutput === "string" ? { partialOutput: obj.partialOutput } : {}), diff --git a/src/file-transfer.ts b/src/file-transfer.ts index 1dfff60..adc0827 100644 --- a/src/file-transfer.ts +++ b/src/file-transfer.ts @@ -592,10 +592,7 @@ function withSuffix(p: string, suffix: string): string { const name = slash >= 0 ? p.slice(slash + 1) : p; const suffixBytes = Buffer.byteLength(suffix, "utf-8"); if (Buffer.byteLength(name, "utf-8") + suffixBytes <= 255) return p + suffix; - const crypto = globalThis.crypto; - const h = crypto && "randomUUID" in crypto - ? crypto.randomUUID().slice(0, 8) - : Math.random().toString(16).slice(2, 10); + const h = randomBytes(4).toString("hex"); const keep = Math.max(1, 255 - suffixBytes - 9); let cut = name.slice(0, keep); while (Buffer.byteLength(cut, "utf-8") > keep && cut.length > 0) cut = cut.slice(0, -1); diff --git a/src/terminal/session-launcher.ts b/src/terminal/session-launcher.ts index 65ef6c8..0666822 100644 --- a/src/terminal/session-launcher.ts +++ b/src/terminal/session-launcher.ts @@ -6,6 +6,7 @@ * 未知 driver 且无 launchCmd → 抛 /Unknown driver/;会话立即死亡 → 清 profile 抛带 hint 错。 * FR-9 第一道防线:launchCmd 前置 env_hardening_prefix 关交互 Prompt。 */ +import { randomBytes } from "node:crypto"; import { SessionRegistry, type TerminalProfile } from "./session-registry.js"; import { FILAXIS_PANE_OPTION, TmuxInvoker } from "./tmux-invoker.js"; import { DEFAULT_TERMINAL_CONFIG, type TerminalConfig } from "./types.js"; @@ -38,7 +39,7 @@ export class SessionLauncher { config?: Record, customId?: string, ): Promise { - const id = customId || ("term_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 6)); + const id = customId || `term_${Date.now().toString(36)}_${randomBytes(6).toString("hex")}`; const launchCmd = this.resolveLaunchCmd(driver, target, config); // customId 复用:会话仍存活直接返回(profile 按当前入参刷新) diff --git a/tests/daemon.test.ts b/tests/daemon.test.ts index eaadd2b..ef49a3f 100644 --- a/tests/daemon.test.ts +++ b/tests/daemon.test.ts @@ -1052,6 +1052,11 @@ describe("CLI daemon / forward / stream E2E", () => { })).rejects.toMatchObject({ name: failure.name, code: failure.code, outcome: failure.outcome, partialOutput: failure.partialOutput, }); + + driver.exec = async () => { throw { toString: () => "internal error details" }; }; + await expect(client.rpc("exec", { + target: { layer: "fixture" }, command: "fixture", + })).rejects.toMatchObject({ message: "Daemon RPC 执行失败" }); } finally { await srv.stop(); }