diff --git a/CHANGELOG.md b/CHANGELOG.md index d425a70..f10b853 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,19 @@ --- +## 0.2.13 + +- **[DeepSeek]** 非交互 SSH 及其跳板代理启用 `BatchMode`,PTY 登录链保持可交互。认证失败依据原始 SSH 输出和本地配置报告。缺少完成哨兵时保留未知终态,由调用方决定是否再次连接。 +- **[DeepSeek]** 一次性 PTY 命令(`filaxis exec --no-daemon --pty`)不再在输出结果后多等约 8 秒才退出。 +- **[DeepSeek]** `batch` 的 exec 步骤可用 `commandFile` 引用脚本文件,替代 `command`(MCP 字段名为 `command_file`)。层名支持 `*` 与 `?` 通配,按已存或已注册的层名展开,没有任何匹配时整批拒绝。CLI 新增 `--max-parallel` 与 `--no-stop-on-fail`,覆盖计划里的对应字段。 +- **[DeepSeek]** `filaxis forward list` 缺省只列仍在用的转发,`--all` 列出全部(MCP 为 `forward_list` 的 `include_closed`)。CLI JSON 与 MCP 的转发记录改用 snake_case 字段,`forwardId` 保留为兼容别名。 +- **[DeepSeek]** `filaxis exec --json` 输出单行结构化结果;文本模式的完成标记在正文排空后输出,`2>&1` 合流时位于末尾。 +- **[自挖]** 一次性模式(`--no-daemon`)按层文件里的 `driver` 加载已存层,不再把任何条目都当作 SSH 目标。 +- **[自挖]** 修复穿层转发(`-L` 经 enterPipeline 进入内层)在 `ssh <目标>` 形态的进入步骤上全部静默失效:转发建立成功,但任何连接立刻被关闭且无报错。原因是给嵌套 ssh 的命令少包一层引号,内层桥接命令在目标机上没有被执行。docker / bash 结尾形态不受影响。 +- **[自挖]** 独立 MCP 和 Daemon 的 MCP 入口都支持按名加载 CLI 保存的层,`run_batch` 也可以按通配匹配。带 `--layer NAME` 启动的 MCP 服务以指定层为默认目标,直接运行。SDK 可用 `createAgentToolkit` 的 `savedLayers` 和导出的 `loadLayerStore` 接入同一份层表。 +- **[自挖]** 穿层执行保留 SSH 参数里的引号内容。桥接子进程启动失败或无输出即异常退出时,最近错误会显示在 CLI 和 MCP 的转发列表里。 +- **[自挖]** `batch` 会明确拒绝未知顶层字段、格式错误的层目标和重复目标。脚本文件参数仅适用于 exec 步骤。 + ## 0.2.12 - 新增可显式启动的本机 Daemon。符合条件的 CLI 和 MCP 调用可共享命名层、转发与观察窗。MCP 代理断线后重连,已发出但终态未知的调用会按 `outcome: "unknown"` 返回。 diff --git a/bin/filaxis-mcp.ts b/bin/filaxis-mcp.ts index 9e5a104..693a349 100644 --- a/bin/filaxis-mcp.ts +++ b/bin/filaxis-mcp.ts @@ -9,6 +9,8 @@ * filaxis-mcp # local 层 * filaxis-mcp --host root@192.0.2.10 --port 2222 # ssh 层 * filaxis-mcp --enter "ssh remote-vm" --host user@bastion # 多跳 + * filaxis-mcp --layer web-01 # 已存层(filaxis layer save) + * # 不论用哪种方式绑定,run_command 的 layer 参数与 run_batch 的层通配都认已存层 */ import { McpServer } from "../src/mcp-server.js"; import { McpStdioProxy } from "../src/mcp-proxy.js"; @@ -17,6 +19,7 @@ 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"; +import { loadLayerStore } from "../src/layer-store.js"; // argv 解析(零依赖手写——与 bin/filaxis.ts 同哲学;子集:--host/--port/--user/ // --key/-J/--enter/--hop/--layer/--docker/--no-daemon/--daemon-dir) @@ -79,13 +82,19 @@ async function main(): Promise { const stderr = (message: string) => console.error(`[mcp] ${message}`); const logger = { ...noopLogger, warn: stderr, error: stderr }; const hasSshPathOpts = Boolean(o.port !== undefined || o.user || o.key || o.jump || o.hop.length || o.enter.length || o.docker); + let savedDescriptor: RuntimeDescriptor | undefined; + // --layer 与 --host 族互斥(快照寻址 = 整个连接参数都在快照里) if (o.layer) { - throw new Error("filaxis-mcp 暂不支持 --layer 快照寻址(FEAT-04 后续)——用 --host/--enter"); + if (o.host || hasSshPathOpts) throw new Error("filaxis-mcp: --layer 与 --host 族互斥"); + savedDescriptor = loadLayerStore()[o.layer]; + if (!savedDescriptor) { + throw new Error(`filaxis-mcp: 层 '${o.layer}' 未保存(filaxis layer list 查看;filaxis layer save ${o.layer} --host ... 创建)`); + } } if (!o.host && hasSshPathOpts) { throw new Error("SSH 路径参数需要 --host"); } - const useDaemonAllowed = !o.noDaemon && process.env.FILAXIS_NO_DAEMON !== "1" && !o.host && !hasSshPathOpts; + const useDaemonAllowed = !o.noDaemon && process.env.FILAXIS_NO_DAEMON !== "1" && !o.layer && !o.host && !hasSshPathOpts; if (useDaemonAllowed) { const activeDaemon = await probeDaemon(o.daemonDir); if (activeDaemon) { @@ -112,9 +121,11 @@ async function main(): Promise { const desc: RuntimeDescriptor = { driver: "ssh", target: o.host, ...(Object.keys(config).length ? { config } : {}) }; opts = { descriptor: desc }; } else { - opts = {}; // local 缺省 + opts = { descriptor: savedDescriptor }; } - const tk = createAgentToolkit(stack, opts); + // 已存层表注入:run_command 等工具按层名寻址、run_batch 的层通配都认 filaxis layer + // save 保存的层(与 CLI 一致)。按需读取,进程存活期间新保存的层也认。 + const tk = createAgentToolkit(stack, { ...opts, savedLayers: loadLayerStore }); new McpServer({ toolkit: tk, logger, diff --git a/bin/filaxis.ts b/bin/filaxis.ts index 6bedf2e..8908355 100644 --- a/bin/filaxis.ts +++ b/bin/filaxis.ts @@ -21,16 +21,17 @@ import { DaemonServer, DaemonClient, probeDaemon, spawnDaemonBackground, parseAddrToUrl, urlRequestHost, urlRequestPort, defaultDaemonDir, readDaemonLock, readDaemonConnection, cleanupDaemonFiles, isPidAlive, normalizeForwardSpec, type CloseForwardResult, type OpenForwardSpec, type ForwardInfo, type CliTargetSpec, + forwardInfoToPublic, closeForwardResultToPublic, isForwardActive, expandBatchLayerWildcards, } from "../src/index.js"; import type { RuntimeDriver, RuntimeDescriptor } from "../src/driver.js"; import { readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync } from "node:fs"; import { randomUUID } from "node:crypto"; -import { homedir } from "node:os"; 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 { layerStorePath, loadLayerStore } from "../src/layer-store.js"; import type { SshConnParams } from "../src/ssh-helpers.js"; import { version as pkgVersion } from "../package.json" with { type: "json" }; @@ -73,8 +74,10 @@ function strArg(argv: string[], i: number): string { 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", "--daemon-dir", + "--layer", "--request-file", "--daemon-dir", "--max-parallel", ]); +/** batch 模式下的无值开关(其余 `-` 开头的一律拒绝:batch 不接受位置参数) */ +const batchFlagOptions = new Set(["--stdin-json", "--no-daemon", "--no-stop-on-fail"]); function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "default"): { host?: string; user?: string; port?: number; key?: string; @@ -83,6 +86,8 @@ function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "defau forward: string[]; hostKey?: string; knownHosts?: string; layer?: string; timeout?: number; duration?: number; stream?: string; all?: boolean; + /** batch 开关(DSH 评估 2026-11-26 #6):覆盖计划里的 maxParallel / stopOnFail */ + maxParallel?: number; noStopOnFail?: boolean; writeMode?: "auto" | "inplace"; transport?: "exec" | "sftp"; stdinJson?: boolean; requestFile?: string; pty?: boolean; help?: boolean; @@ -103,7 +108,7 @@ function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "defau 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" && a !== "--no-daemon") { + if (mode === "batch" && a.startsWith("-") && !batchFlagOptions.has(a)) { if (!batchValueOptions.has(a)) throw new Error(`batch 不支持 ${a}`); const value = argv[i + 1]; if (!value || value.startsWith("-")) throw new Error(`batch 的 ${a} 需要参数值`); @@ -135,6 +140,8 @@ function parseOpts(argv: string[], mode: "default" | "strict" | "batch" = "defau break; } case "--timeout": o.timeout = numArg(argv, i, { positive: true }); i++; break; // 正数(Hydrogen R9 #4:0/负数曾静默禁用或立即杀) + case "--max-parallel": o.maxParallel = numArg(argv, i, { positive: true }); i++; break; + case "--no-stop-on-fail": o.noStopOnFail = true; break; case "--duration": o.duration = numArg(argv, i, { positive: true }); i++; break; case "--stream": { const stream = strArg(argv, i); @@ -276,19 +283,7 @@ function buildSshDescriptor(opts: ReturnType): RuntimeDescript } // ── 层快照存储(CLI 跨调用共享——A 方案;FILAXIS_LAYERS 可覆盖路径) ── -function layerStorePath(): string { - return process.env.FILAXIS_LAYERS ?? (homedir() + "/.filaxis/layers.json"); -} -function loadLayerStore(): Record { - try { - const parsed = JSON.parse(readFileSync(layerStorePath(), "utf-8")); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("层快照必须是对象"); - return Object.assign(Object.create(null), parsed); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return Object.create(null); - throw error; - } -} +// 读取在 src/layer-store.ts(MCP 入口与 Daemon 同源——三路对层名与层通配的解析一致) function updateLayerStore(update: (store: Record) => T): T { const path = layerStorePath(); mkdirSync(dirname(path), { recursive: true }); @@ -345,9 +340,21 @@ function handleLayerCmd(sub: string | undefined, rest: ReturnType console.error(`[filaxis] ${message}`) }; -function savedLayerDriver(name: string, layers: Record = loadLayerStore()): SshPtyDriver { +function savedLayerDriver(name: string, layers: Record = loadLayerStore()): RuntimeDriver { if (!Object.hasOwn(layers, name)) throw new Error(`层 '${name}' 未保存(filaxis layer list 查看;filaxis layer save ${name} --host ... 创建)`); - return new SshPtyDriver(layers[name]!, { logger: sshLogger }); + const descriptor = layers[name]!; + // 按 descriptor 的 driver 分派,与 Daemon 路径的 resolveTarget 一致。已存层按约定由 + // `layer save --host` 产生(SSH),但层文件可被手改:这里曾无条件包成 SshPtyDriver + //——非 SSH 条目(driver:"local")会变成对空主机名的 ssh 连接(落到 localhost 的 sshd) + if (descriptor.driver === "ssh") return new SshPtyDriver(descriptor, { logger: sshLogger }); + if (descriptor.driver === "local") { + const shell = descriptor.config?.shell; + return new LocalRuntimeDriver({ + cwd: descriptor.cwd, + shell: typeof shell === "string" ? shell : undefined, + }); + } + throw new Error(`层 '${name}' 的 driver '${descriptor.driver}' 在一次性模式(--no-daemon)下不可用——去掉 --no-daemon 经 Daemon 执行`); } async function driverFor(opts: ReturnType, needPtyLink = false): Promise { @@ -540,6 +547,28 @@ async function requireDaemon(opts: ReturnType): Promise&1` 合流后它就落在 + * 正文中间。先等 stdout 排空再写标记(合流后标记恒在末尾)。--json 结构化输出, + * 调用方不必再从正文里认标记行。 + * 只设 exitCode、不 process.exit(Gemini #8——曾跳过外层 finally 的 drv.destroy())。 + */ +async function printExecResult(r: { stdout: string; stderr: string; exitCode: number; effectiveUser?: string }, json: boolean): Promise { + if (json) { + console.log(JSON.stringify({ exitCode: r.exitCode, effectiveUser: r.effectiveUser ?? null, stdout: r.stdout, stderr: r.stderr })); + } else { + if (r.stdout) { + await new Promise((done, reject) => { + process.stdout.write(r.stdout, (error) => error ? reject(error) : done()); + }); + } + if (r.stderr) process.stderr.write(r.stderr); + console.error(`\n[exit=${r.exitCode} user=${r.effectiveUser ?? "?"}]`); + } + process.exitCode = r.exitCode; +} + 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}`}`; @@ -601,12 +630,23 @@ async function runCliBatch(o: ReturnType, daemon: DaemonClient } catch (e) { throw new Error(`batch 计划 JSON 解析失败: ${(e as Error).message}`); } + let saved: Record | undefined; if (o.layer && plan && typeof plan === "object" && !Array.isArray(plan) && plan.layer === undefined) { plan = { ...plan, layer: o.layer }; } + // 命令行开关覆盖计划字段(DSH 评估 2026-11-26 #6):显式写在命令行上的意图优先。 + // --no-stop-on-fail 把缺省的失败即停关掉——巡检要「一台挂了其余照看」;改配置→验证 + // →重载这类链保持缺省(前一步失败不该继续) + if (plan && typeof plan === "object" && !Array.isArray(plan)) { + if (o.maxParallel !== undefined) plan = { ...plan, maxParallel: o.maxParallel }; + if (o.noStopOnFail) plan = { ...plan, stopOnFail: false }; + // 层通配("q-*")按已存层名展开——只在此入口做:内核的层解析只认具体名。 + // 无匹配即拒绝(把 "q-*" 原样交下去会被当成一个不存在的层名) + plan = expandBatchLayerWildcards(plan, () => Object.keys(saved ??= loadLayerStore()), "已存层"); + } if (daemon) { const savedLayers = Object.fromEntries( - Object.entries(loadLayerStore()).map(([name, descriptor]) => [name, resolveDaemonSshPaths(descriptor)]), + Object.entries(saved ??= 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)) @@ -626,7 +666,6 @@ async function runCliBatch(o: ReturnType, daemon: DaemonClient return; } const drivers = new Map(); - let saved: Record | undefined; try { const r = await runBatch(async (name) => { const existing = drivers.get(name); @@ -811,13 +850,13 @@ async function handleForwardCmd(sub: string | undefined, o: ReturnType("forward.add", { target, spec }); if (info.status !== "active") { - if (o.json) console.log(JSON.stringify(info, null, 2)); + if (o.json) console.log(JSON.stringify(forwardInfoToPublic(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)); + console.log(JSON.stringify(forwardInfoToPublic(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})`); @@ -825,18 +864,32 @@ async function handleForwardCmd(sub: string | undefined, o: ReturnType("forward.list", { ...(o.layer ? { layer: o.layer } : {}) }); + // 默认只报仍在用的转发(DSH 评估 2026-11-26 #5a):remove 之后条目以 stopped + // 留在表里做幂等判定——曾照样列出,与「无活跃转发」的空表文案自相矛盾。 + // --all 连同已停止/已退出的一并列出(--json 同受 --all 控制) + const all = o.all === true; + const res = await client.rpc<{ forwards: ForwardInfo[] }>("forward.list", { + ...(o.layer ? { layer: o.layer } : {}), + includeClosed: all, + }); + // 本地再滤一次:对上不认 includeClosed 的旧 daemon,行为不变 + const shown = all ? res.forwards : res.forwards.filter(isForwardActive); if (o.json) { - console.log(JSON.stringify(res.forwards, null, 2)); + console.log(JSON.stringify(shown.map(forwardInfoToPublic), null, 2)); return; } - if (res.forwards.length === 0) { - console.log("(无活跃动态端口转发)"); + if (shown.length === 0) { + console.log(all ? "(无动态端口转发)" : "(无活跃动态端口转发)"); return; } - for (const f of res.forwards) { + for (const f of shown) { 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}`); + if (f.lastError) { + // 最近一次异常的尾行(完整内容在 --json 的 last_error)——穿层转发连接即断时死因在这里 + const lines = f.lastError.trim().split(/\r?\n/); + console.log(` ↳ ${lines[0]!.trim()}${lines.length > 1 ? ` …${lines[lines.length - 1]!.trim()}` : ""}`.slice(0, 240)); + } } return; } @@ -846,7 +899,7 @@ async function handleForwardCmd(sub: string | undefined, o: ReturnType + [--timeout MS] [--pty] [--json] -- # --enter 支持 "ssh <目标>"(自动非交互重放)与 "<...> bash" 结尾形态; # 交互式进入(su - 类)用 --pty(stderr 与 stdout 混流=终端物理行为) + # --json 输出单行 {exitCode, effectiveUser, stdout, stderr}(脚本取值用,不必认标记行) filaxis cat [--host ...] ${transferUsage("put")} ${transferUsage("get")} @@ -965,20 +1019,27 @@ const generalHelp = `filaxis CLI — 千里一线,执行有迹 --stdin-json | --request-file # 免 Shell 通道(JSON {old,new,all}——多行/引号保真) filaxis observe [--host ...] [--stream stderr|stdout|both] [--duration MS] -- filaxis probe [--host ...] # 两段式环境探测 - filaxis batch [--layer ...|--host ...] --request-file # 批次组合(DAG 依赖+fail-fast+逐步骤证据) + filaxis batch [--layer ...|--host ...] --request-file # 批次组合(DAG 依赖+逐步骤证据) --stdin-json # 计划及每步可用 layer 选择已保存层 + [--max-parallel N] [--no-stop-on-fail] # 覆盖计划里的 maxParallel / stopOnFail + # 缺省失败即停:某步失败后未启动的步骤标 skipped(改配置→验证→重载这类链要这个) + # 巡检要「一台挂了其余照看」→ --no-stop-on-fail + # exec 步骤可写 "commandFile": 引用脚本文件(零转义、可复用)替代 "command" + # layer 支持通配("q-*" 按已存层名展开) filaxis layer save --host ... [-J/--hop/--enter/--docker/...] # 层路径持久化 list | rm # 层清单/移除 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 + list [--layer NAME] [--all] | remove + # list 默认只报仍在用的转发;--all 连已停止/已退出的一并列出 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 自身代理) + -J, --jump 跳板(-J:途径机不占层,ssh 自身代理)。跳板的用户名与密钥取自 + ssh 配置/ssh-agent——--key 只给目标主机;字面 IP 跳板需在 ssh config 配好 --hop 逐跳登录链(可重复=链序;每跳独立端口/用户,密钥共享 --key) --enter 进入内层 shell(可重复=管线序,如 "docker exec -i web bash") --docker 糖 = --enter "docker exec -i sh"(--docker-shell bash / --docker-runtime podman 可换) @@ -992,14 +1053,18 @@ async function main() { const helpFlag = (value: string | undefined) => value === "--help" || value === "-h"; const commandHelp = new Map([ ["mcp-config", "filaxis mcp-config [--format json|toml]"], - ["exec", "filaxis exec [--layer NAME | --host HOST] [--timeout MS] [--pty] -- \nfilaxis exec [目标选项] --stdin-script | --script-file FILE"], + ["exec", "filaxis exec [--layer NAME | --host HOST] [--timeout MS] [--pty] [--json] -- \nfilaxis exec [目标选项] --stdin-script | --script-file FILE\n--json 输出单行 {exitCode, effectiveUser, stdout, stderr}(脚本取值用,不必从正文里认 [exit=N user=…] 标记行)"], ["cat", "filaxis cat [--layer NAME | --host HOST] -- "], ["put", transferUsage("put")], ["get", transferUsage("get")], ["edit", "filaxis edit [--layer NAME | --host HOST] [--all] [--write-mode auto|inplace]\nfilaxis edit [目标选项] --stdin-json | --request-file FILE"], ["observe", "filaxis observe [--layer NAME | --host HOST] [--stream stderr|stdout|both] [--duration MS] -- "], ["probe", "filaxis probe [--layer NAME | --host HOST]"], - ["batch", "filaxis batch [--layer NAME | --host HOST] --request-file FILE | --stdin-json\n目标优先级:步骤 layer → 计划 layer → --layer 或 --host。命名层来自 filaxis layer save。"], + ["batch", "filaxis batch [--layer NAME|--layer 通配 | --host HOST] --request-file FILE | --stdin-json\n" + + " [--max-parallel N] [--no-stop-on-fail]\n" + + "目标优先级:步骤 layer → 计划 layer → --layer 或 --host。命名层来自 filaxis layer save;名字可写通配(如 \"q-*\"),按已存层名展开。\n" + + "--max-parallel / --no-stop-on-fail 覆盖计划里的 maxParallel / stopOnFail。缺省失败即停(未启动步骤标 skipped);巡检要「一台挂了其余照看」用 --no-stop-on-fail。\n" + + "exec 步骤可用 \"commandFile\" 引用脚本文件,替代 \"command\"(命令原样进文件,零转义、可复用)。"], ["layer", "filaxis layer save --host HOST | list | rm "], ["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"], @@ -1008,9 +1073,9 @@ async function main() { ["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", "filaxis forward add (--layer NAME | --host HOST) (-L SPEC | -R SPEC | -D SPEC) [--id ID] [--json] | list [--layer NAME] [--all] [--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 list", "filaxis forward list [--layer NAME] [--all] [--daemon-dir dir] [--json]\n默认只报仍在用的转发(已停止/已退出的条目用 --all 查看)。--json 字段为 snake_case(forward_id、bind_addr…),forwardId 保留为兼容别名。"], ["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] -- "], @@ -1120,10 +1185,7 @@ async function main() { timeoutMs: o.timeout ?? 120_000, channel: o.pty ? "pty" : undefined, }); - 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; // 不 process.exit(Gemini #8——曾跳过外层 finally 的 drv.destroy()) + await printExecResult(r, o.json === true); break; } case "cat": { @@ -1265,10 +1327,7 @@ async function runViaDaemon(cmd: string, o: ReturnType, daemon 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; + await printExecResult(r, o.json === true); break; } case "cat": { diff --git a/docs/skills/SKILL.en.md b/docs/skills/SKILL.en.md index 79107ad..1415ee1 100644 --- a/docs/skills/SKILL.en.md +++ b/docs/skills/SKILL.en.md @@ -1,7 +1,7 @@ --- name: filaxis-runtime metadata: - version: "0.2.12" + version: "0.2.13" 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. @@ -26,7 +26,7 @@ Match the task to an entry point and read the relevant playbook. After execution | Task | MCP tool or reference | |---|---| | Wait for one finite command and collect its exit code | `run_command` | -| Batch inspections or apply dependencies across layers | `run_batch`. For bastions or multi-host investigation, read [Cross-host diagnosis](./cross-host-diagnosis.md) | +| Batch inspections or apply dependencies across layers | `run_batch` (pass `stop_on_fail: false` for inspections, or one failure skips the rest). For bastions or multi-host investigation, read [Cross-host diagnosis](./cross-host-diagnosis.md) | | Start a background service, wait for readiness, or verify its exit code | `start_session` → `stop_session`. Read [Long-running jobs](./longrun-observe.md) | | Follow logs with a cursor and close the view when finished | `observe_stream` (open/read) → `close_stream`. Read [Observation windows](./stream-window.md) | | Read/list, edit/create, mkdir/move/delete, or transfer files | `read_path`, `edit_file`, `manage_path`, `transfer_file`. Read [File operations](./file-sync.md) | @@ -60,17 +60,24 @@ filaxis edit --layer --request-file edit.json # 5. Commands that may hang (nc/ping/tail) — always pass --timeout (CLI default is 120s) filaxis exec --layer --timeout 8000 -- "(printf 'PING\n'; sleep 1) | nc 127.0.0.1 6379" + +# 6. Batches (plan JSON without escaping; add --no-stop-on-fail for inspections; layer names may use wildcards) +filaxis batch --layer "q-*" --no-stop-on-fail --request-file plan.json +filaxis exec --layer --json -- "" # single-line JSON {exitCode, effectiveUser, stdout, stderr} ``` -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. +Run `filaxis daemon start` to share layers, forwards, and observation windows between the CLI and MCP launchers started without `--host` or `--layer`. 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. The forward list reports only forwards still in use. Pass `filaxis forward list --all` or `forward_list` with `include_closed: true` to include stopped entries. Forward records use snake_case fields (`forward_id`, `bind_addr`, `bind_port`, …). --- ## MCP Practical Guidelines - **Batch inspection and multi-step fixes with `run_batch`**: Combine multiple `read`, `exec`, `edit`, `put`, and `get` steps into a single parallel `run_batch` call instead of sequential single-tool loops. +- **Turn off fail-fast for inspections**: by default the first failing step stops the batch and steps that have not started (including expanded instances on other layers) are marked `skipped` — one host fails and the rest are never checked. Pass `stop_on_fail: false` for read-only batches such as inspections and multi-host evidence collection (CLI: `filaxis batch … --no-stop-on-fail`). Read the per-step status lines first, then drill into the failed layers. Keep the default for chains such as edit config → validate → reload: a failed step should not be followed by the next one. +- **Less escaping**: an `exec` step can reference a script file with `command_file` instead of `command` — the script goes in as-is, so quotes and newlines need no JSON escaping, and the same script can be reused across steps (the two are mutually exclusive; an unreadable or empty file rejects the whole batch). Relative paths resolve against the server process working directory, so prefer absolute paths when running through the Daemon. - **Layer connections (`connect_layer`)**: Connect a single SSH host (`host`), a batch (`{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`), or enter an inner container/shell (`enter_cmd`). Strings can be SSH config aliases resolved in the runtime environment. Batch targets are attempted in order and individual failures are reported without stopping the batch. Pass the deduplicated `layers` from successful and reused connections directly to `run_batch.layer`. `active_layer` reports the default layer at the end of the call. -- **Layer targeting precedence & multi-layer fan-out**: Both top-level `layer` and per-step `layer` accept either a single layer name or a non-empty array of layer names (top-level sets the batch default; per-step overrides only that step; omitting both uses the active default layer). Multi-layer arrays expand each step into `id@layer` instances that run in parallel up to `max_parallel` (single-element arrays keep the original `id`), and downstream `after` dependencies wait for all expanded instances to succeed (`kind: "get"` rejects multi-layer arrays to avoid overwriting the same `local_path`). `filaxis batch --request-file plan.json` shares the same precedence and array expansion (step `layer` > plan `layer` > `--layer`/`--host` > local). +- **Layer targeting precedence & multi-layer fan-out**: Both top-level `layer` and per-step `layer` accept either a single layer name or a non-empty array of layer names (top-level sets the batch default; per-step overrides only that step; omitting both uses the active default layer). Multi-layer arrays expand each step into `id@layer` instances that run in parallel up to `max_parallel` (single-element arrays keep the original `id`), and downstream `after` dependencies wait for all expanded instances to succeed (`kind: "get"` rejects multi-layer arrays to avoid overwriting the same `local_path`). `filaxis batch --request-file plan.json` shares the same precedence and array expansion (step `layer` > plan `layer` > `--layer`/`--host` > local). Plan files use camelCase fields (`command` or `commandFile`, `maxParallel`, `stopOnFail`); the `--max-parallel N` and `--no-stop-on-fail` switches override the matching plan fields. +- **Layer wildcards**: a layer name may contain `*` (any character sequence) or `?` (one character), e.g. `"q-*"`, and expands against registered or saved layer names instead of listing them one by one (MCP, the SDK and the CLI share one saved-layer store: layers written by `filaxis layer save` need no `connect_layer` first and are loaded on demand when addressed by name or matched by a wildcard; `filaxis-mcp --layer NAME` binds a saved layer directly). A pattern with no match rejects the whole batch; it never falls back to the default layer. - **Local targeting**: Layer arrays look up registered or saved names. SDK callers can register the local host with `stack.addLayer("local", { driver: "local" })`. The CLI and standalone MCP server leave the local default unnamed. - **Concurrency & ordering (`max_parallel` and `after`)**: Independent steps run in parallel up to `max_parallel`. Use `after: ["step-id"]` to serialize dependent steps (e.g., edit config -> validate -> reload service), even across layers. - **Resource coordination**: `after` references the original step IDs declared in the same batch. Fan-out executes once per layer name, and different names may point to the same environment. Serialize operations that modify the same resource using its environment identity and file path. diff --git a/docs/skills/SKILL.md b/docs/skills/SKILL.md index fa139bd..2a3f15e 100644 --- a/docs/skills/SKILL.md +++ b/docs/skills/SKILL.md @@ -1,7 +1,7 @@ --- name: filaxis-runtime metadata: - version: "0.2.12" + version: "0.2.13" description: | 使用 Filaxis(@syrkos/filaxis)执行跨层命令、批量巡检、管理后台任务、观察日志或操作目标层文件。 也用于排查 SSH 别名与跳板、解读 unknown 终态或写入保障。纯本机一次性命令和与 Filaxis 无关的任务可跳过。 @@ -18,7 +18,7 @@ description: | | 任务意图 | MCP 工具或参考 | |---|---| | 等一条会自行结束的命令并获取退出码 | `run_command` | -| 批量巡检或按依赖跨层执行 | `run_batch`。涉及跳板或多机取证时读 [跨主机排查](./cross-host-diagnosis.md) | +| 批量巡检或按依赖跨层执行 | `run_batch`(巡检传 `stop_on_fail: false`,否则一台失败其余被跳过)。涉及跳板或多机取证时读 [跨主机排查](./cross-host-diagnosis.md) | | 启动后台服务、等就绪或核实进程退出码 | `start_session` → `stop_session`。读 [长跑任务](./longrun-observe.md) | | 按游标实时看日志、看完关窗 | `observe_stream`(开窗即读+游标续读)→ `close_stream`。读 [持续观察窗](./stream-window.md) | | 读文件/列目录、编辑/建文本、建目录/移动/删除、传文件 | `read_path`、`edit_file`、`manage_path`、`transfer_file`。读 [文件操作](./file-sync.md) | @@ -51,14 +51,21 @@ filaxis edit --layer <名> --request-file edit.json # ⑤ 挂起类命令(nc/ping/tail -f)必带 --timeout——CLI 缺省 120s filaxis exec --layer <名> --timeout 8000 -- "(printf 'PING '; sleep 1) | nc 127.0.0.1 6379" + +# ⑥ 批次(计划 JSON 免转义;巡检加 --no-stop-on-fail;层名可写通配,按已存层名展开) +filaxis batch --layer "q-*" --no-stop-on-fail --request-file plan.json +filaxis exec --layer <名> --json -- "" # 单行 JSON {exitCode, effectiveUser, stdout, stderr} ``` **MCP 形态实战指引**(第十二季盲测 B 组教训): - 多个 SSH 目标可用一次 `connect_layer` 调用,例如 `{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`;也可单台传 `host` 或传 `enter_cmd` 从既有层进入容器。字符串可用运行环境 SSH 配置里的别名。按输入顺序建连,单个目标失败后继续尝试。返回的 `layers` 只含建连成功或复用的实际层名,并已去重,非空时可直接传给 `run_batch.layer`。批量结果的 `active_layer` 是调用结束时的默认层。 - **定位/巡检期用 `run_batch` 打包**——多个 `read` / `exec` 一次调用并行 执行(B 组逐个调 18 步 vs CLI 组打包 11 步——这是 MCP 形态省步数的最大杠杆); +- **巡检要显式关掉失败即停**:`run_batch` 缺省任一步失败即停,尚未启动的步骤(含其它层的展开实例)标 `skipped`——一台失败,其余都不看。批量巡检、多机取证这类只读批次传 `stop_on_fail: false`(CLI:`filaxis batch … --no-stop-on-fail`)。第一遍只看各步状态行,再对失败的层单独钻取。改配置→验证→重载这类链保持缺省:前一步失败不应继续。 +- **少写转义**:`exec` 步骤可用 `command_file` 引用脚本文件,替代 `command`——命令原样进文件,JSON 里的引号和换行不必再转义,同一脚本可被多个步骤复用(二者互斥;读不出或内容为空则整批拒绝)。相对路径相对服务进程的工作目录,经 Daemon 执行时建议给绝对路径。 - `run_batch` 的顶层 `layer` 和步骤 `layer` 均支持传单个层名或层名数组(也可同时传:顶层是批次默认值,步骤的 `layer` 仅覆盖本步;两处都省略时使用调用时的默认层)。传多个层名数组时,步骤按 `id@layer` 展开并在 `max_parallel` 并发池内并行执行,下游 `after` 需等被依赖步骤的所有展开实例均 ok 后才启动(`kind: "get"` 不支持多层数组,防并发覆盖同一 `local_path`);单元素数组保留原 `id`。结果逐步标明命名层。 -- CLI 的 `filaxis batch --request-file plan.json` 同样支持这两个字段,并从 `filaxis layer save` 保存的层中解析名称。优先级依次为步骤 `layer`、计划 `layer`、命令行的 `--layer` 或 `--host`,全省略时使用本机。 +- CLI 的 `filaxis batch --request-file plan.json` 同样支持这两个字段,并从 `filaxis layer save` 保存的层中解析名称。优先级依次为步骤 `layer`、计划 `layer`、命令行的 `--layer` 或 `--host`,全省略时使用本机。计划文件里的字段是驼峰写法(`command` 或 `commandFile`、`maxParallel`、`stopOnFail`);命令行开关 `--max-parallel N` 与 `--no-stop-on-fail` 覆盖计划里的对应字段。 +- 层名可写通配:`*` 匹配任意字符序列,`?` 匹配单个字符(如 `"q-*"`),按已注册或已保存的层名展开(MCP、SDK 与 CLI 认同一份已存层表:`filaxis layer save` 保存的层不必先 `connect_layer`,按名寻址或被通配命中时自动加载;`filaxis-mcp --layer NAME` 可直接绑定已存层),免去逐个罗列。没有任何匹配时整批拒绝,不会改用默认层。 - 层名数组只查已注册或保存的层。SDK 可用 `stack.addLayer("local", { driver: "local" })` 把本机加入命名层;CLI 和独立 MCP 服务的本机默认目标不会自动注册为 `local`。 - `max_parallel` 是整个批次的并发上限。无依赖的步骤可以并行,包括同层的独立巡检。需要先改配置、再验证、最后重载时,用 `after` 引用前置步骤的 `id`。依赖可以跨层,前置步骤成功后才会启动后续步骤。 - `after` 引用当前批次计划里声明的原始步骤 ID。同一环境可能有多个层名,扇出按层名各执行一次。多个步骤或批次可能同时修改同一资源时,由调用方按实际资源串行化,例如用「环境身份 + 配置路径」作为互斥键。 @@ -72,7 +79,7 @@ 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 秒退且双流为空时,可检查启动器是否保留了系统环境。 -用 `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 查询和关闭。 +用 `filaxis daemon start` 启动本机守护进程后,CLI 与未显式指定 `--host` 或 `--layer` 的 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 查询和关闭。转发列表缺省只报仍在用的转发,已停止的条目用 `filaxis forward list --all` 或 `forward_list` 的 `include_closed: true` 查看。转发记录字段为 snake_case(`forward_id`、`bind_addr`、`bind_port`…)。 SDK 的 `createAgentToolkit` 也可在宿主进程内复用连接和 PTY,并接受结构化参数。 diff --git a/package.json b/package.json index 0be3c5c..050bd7b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@syrkos/filaxis", - "version": "0.2.12", + "version": "0.2.13", "description": "牵丝 Filaxis — 面向自动化与 Agent 的远程执行运行时 SDK(Syrkos · 漩核)。千里一线,执行有迹。", "type": "module", "license": "Apache-2.0", diff --git a/src/agent-toolkit.ts b/src/agent-toolkit.ts index 95d68f8..4295817 100644 --- a/src/agent-toolkit.ts +++ b/src/agent-toolkit.ts @@ -16,12 +16,12 @@ import type { LayerHandle, RuntimeStack } from "./runtime-stack.js"; import { editFile } from "./file-edit.js"; import { transferLayerFile, validateFileTransferFields, type FileTransferTransport, type LayerFileTransferResult } from "./layer-file-transfer.js"; import type { TransferResult } from "./file-transfer.js"; -import { BATCH_STEP_KINDS, runBatch, type BatchLayerTarget, type BatchStepWithDeps } from "./batch.js"; -import type { FileEntry, RuntimeDriver } from "./driver.js"; +import { BATCH_STEP_KINDS, expandBatchLayerWildcards, runBatch, type BatchLayerTarget, type BatchStepWithDeps } from "./batch.js"; +import type { FileEntry, RuntimeDescriptor, RuntimeDriver } from "./driver.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"; +import { forwardInfoToPublic, isForwardActive, type ForwardInfo, type OpenForwardSpec, type PublicForwardInfo } from "./ssh-forward.js"; export interface AgentToolDef { type: "function"; @@ -139,8 +139,10 @@ 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: "forward_add"; forward: ForwardInfo } - | { action: "forward_list"; forwards: ForwardInfo[] } + // 转发记录对外为 snake_case 投影(forward_id、bind_addr…;forwardId 为兼容别名)—— + // 与本工具的参数命名和 observe_stream 的 window_id 同一风格 + | { action: "forward_add"; forward: PublicForwardInfo } + | { action: "forward_list"; forwards: PublicForwardInfo[] } | { action: "forward_remove"; forward_id: string; status: "stopped" | "already_closed" | "unknown"; detail?: string }; export interface AgentToolHandlers { @@ -184,7 +186,7 @@ export interface AgentToolHandlers { timeout_ms?: number; layer?: string; }): Promise>; - manage_layers(args: { action: "forward_list"; layer?: string }): Promise>; + manage_layers(args: { action: "forward_list"; layer?: string; include_closed?: boolean }): 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<{ @@ -236,6 +238,10 @@ export interface AgentToolkitOptions { sessionResultTtlMs?: number; /** Interval for checking tracked sessions and expiring results. */ sessionCheckIntervalMs?: number; + /** 已存层表(`filaxis layer save` 的产物)的读取函数,按需调用、不缓存——入口注入 + * (filaxis-mcp 与 Daemon 传 loadLayerStore)。工具集自身不读用户目录:未注入时 + * 行为与从前一致。未注册的层名或层通配命中这里的条目时按需注册(不抢默认层)。 */ + savedLayers?: () => Record; } const fileTransferProperties = { @@ -427,7 +433,8 @@ export const TOOL_DEFS: AgentToolDef[] = [ description: "编排并执行多步骤文件或命令 DAG(exec/edit/read/put/get),支持按 layer 数组跨多层并行扇出。" + "单步操作请使用专用工具(run_command、read_path、edit_file、transfer_file);多步骤依赖、批量读取/修改或多层同发请使用本工具。" + - "无 after 依赖的步骤并行,顺序链靠 after 显式保序;默认任一步失败即停(未启动步骤标 skipped),**不做自动回滚**。", + "无 after 依赖的步骤并行,顺序链靠 after 显式保序;默认任一步失败即停(未启动步骤标 skipped),**不做自动回滚**。" + + "巡检/批量只读请传 stop_on_fail:false——缺省的失败即停会让其余步骤被跳过(一台失败,其余都不看)。", parameters: { type: "object", additionalProperties: false, @@ -443,8 +450,12 @@ export const TOOL_DEFS: AgentToolDef[] = [ ...fileTransferProperties, id: { type: "string", description: "步骤唯一 id(after 引用用)" }, kind: { type: "string", enum: BATCH_STEP_KINDS }, - layer: batchLayerSchema("覆盖批次默认层。多个层名按 id@layer 展开,单元素数组保留原 id;kind=get 只接受单层"), - command: { type: "string", description: "kind=exec:shell 命令" }, + layer: batchLayerSchema("覆盖批次默认层。多个层名按 id@layer 展开,单元素数组保留原 id;kind=get 只接受单层。可写通配(如 \"q-*\"),按本会话已注册的层名与已存层表(filaxis layer save 的产物)展开,命中未注册的已存层时自动加载"), + command: { type: "string", description: "kind=exec:shell 命令(或改用 command_file 引用脚本文件)" }, + command_file: { + type: "string", minLength: 1, + description: "kind=exec:脚本文件路径,替代 command(二者互斥)。命令原样进文件——免 JSON 转义、同一脚本可复用;读不出或为空则整批拒绝。相对路径相对服务进程工作目录,经 Daemon 执行时建议给绝对路径", + }, expect_exit: { type: "array", items: { type: "number" }, description: "kind=exec:预期退出码集合(缺省 [0])" }, timeout_ms: { type: "number", description: "kind=exec:超时毫秒" }, path: { type: "string", description: "kind=edit/read:文件路径" }, @@ -467,9 +478,9 @@ export const TOOL_DEFS: AgentToolDef[] = [ required: ["id", "kind"], }, }, - stop_on_fail: { type: "boolean", description: "失败即停(缺省 true)" }, + stop_on_fail: { type: "boolean", description: "失败即停(缺省 true:某步失败后未启动的步骤标 skipped)。巡检/批量只读请传 false——一台失败其余照看" }, max_parallel: { type: "number", description: "并行度上限(缺省 3)" }, - layer: batchLayerSchema("批次默认目标层名或层名数组(缺省=默认层;传数组时未覆盖 layer 的步骤自动展开到各层并行执行)"), + layer: batchLayerSchema("批次默认目标层名或层名数组(缺省=默认层;传数组时未覆盖 layer 的步骤自动展开到各层并行执行)。可写通配(如 \"q-*\"),按本会话已注册的层名与已存层表(filaxis layer save 的产物)展开,命中未注册的已存层时自动加载"), output: { type: "string", enum: ["text", "full"], description: "MCP 输出模式。text 适合只读文本块的客户端,保留简短预览;full(默认)另在 structuredContent 保留完整输出" }, }, required: ["steps"], @@ -741,7 +752,8 @@ export const TOOL_DEFS: AgentToolDef[] = [ "action='activate' 将指定 name 设为默认层(保留所有连接);" + "action='remove' 移出指定层(缺省保留连接在指纹缓存以便零成本重建,传 destroy=true 才真销毁连接);" + "action='forward_add' 在目标或默认 SSH 层动态开启 -L/-R/-D 端口转发(bind_port 不填或传 0 自动分配空闲端口);" + - "action='forward_list' 查询动态端口转发列表;action='forward_remove' 关闭指定 forward_id。" + + "action='forward_list' 查询动态端口转发列表(缺省只报仍在用的转发,include_closed=true 连已停止/已退出的一并返回);" + + "action='forward_remove' 关闭指定 forward_id。转发记录字段为 snake_case(forward_id、bind_addr、bind_port、target_host、target_port、transport_mode、status…;forwardId 仅为兼容别名)。" + "新建 SSH 或进入内层环境请用 connect_layer。", parameters: { type: "object", @@ -761,6 +773,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ 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" }, + include_closed: { type: "boolean", description: "action=forward_list:true 连已停止/已退出的转发一并返回(缺省 false=只报仍在用的)" }, }, oneOf: [ { @@ -810,6 +823,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ properties: { action: { type: "string", const: "forward_list" }, layer: { ...layerNameSchema }, + include_closed: { type: "boolean" }, }, required: ["action"], }, @@ -864,10 +878,45 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption const readyTimeoutMs = opts.readyTimeoutMs ?? 15_000; /** 层寻址(第十季注册表):显式层名 > 注册表默认层(最近 push)> 初始层—— * 未用层族时与旧行为逐字节一致(零破坏),push 后六工具自动落新默认层 */ + // 已存层:未注册的层名命中入口注入的层表时按需注册。同名并发只建一次(名字预留 + // 会把第二次 addLayer 判成重名);加载后与 connect_layer 注册的层无差别。 + // activate:false——被顺带加载的层不抢默认层。 + const loadingSaved = new Map>(); + const savedDescriptor = (name: string): RuntimeDescriptor | undefined => { + if (!opts.savedLayers) return undefined; + const store = opts.savedLayers(); + const entry = Object.hasOwn(store, name) ? store[name] : undefined; + return entry && typeof entry === "object" ? entry : undefined; + }; + const loadSaved = (name: string): Promise => { + const inflight = loadingSaved.get(name); + if (inflight) return inflight; + const p = (async () => { + const descriptor = savedDescriptor(name); + if (!descriptor) throw new Error(`层 '${name}' 未注册,也不在已存层表里`); + try { + const driver = await stack.connect(descriptor); + return (await stack.addLayer(name, driver, { activate: false })).handle.driver; + } catch (e) { + throw new Error(`已存层 '${name}' 加载失败: ${e instanceof Error ? e.message : String(e)}`); + } + })().finally(() => loadingSaved.delete(name)); + loadingSaved.set(name, p); + return p; + }; + /** 层名解析范围:已注册的在前,其后是已存层表里尚未注册的 */ + const knownLayerNames = (): string[] => { + const names = [...stack.layers.keys()]; + if (opts.savedLayers) { + for (const name of Object.keys(opts.savedLayers())) if (!names.includes(name)) names.push(name); + } + return names; + }; const resolveDrv = async (layerName?: string): Promise => { if (layerName !== undefined) { if (typeof layerName !== "string" || !layerName.trim()) throw new Error("layer 需为非空层名"); - return stack.layer(layerName).driver; + if (stack.layers.has(layerName)) return stack.layer(layerName).driver; + return loadSaved(layerName); } return stack.active ?? await layer(); }; @@ -961,6 +1010,7 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption if (label !== undefined && typeof label !== "string") throw new Error("label 需为字符串"); assertOptionalLayerName(from); assertOptionalLayerName(name); + if (from !== undefined) await resolveDrv(from); const srcName = from ?? stack.activeLayer?.name; if (!srcName) throw new Error("无源层——先用 connect_layer 建立 SSH 层,或显式传 from"); const h = await stack.layerInto(srcName, name ?? label ?? enterCmd.slice(0, 30), enterCmd, { label }); @@ -1504,6 +1554,7 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption const { name, ...extra } = rest; if (Object.keys(extra).length) throw new Error("manage_layers(activate) 只接受 action 和 name"); if (typeof name !== "string" || !name.trim()) throw new Error("name 需为非空层名"); + await resolveDrv(name); return { action: "activate" as const, active_layer: stack.setActive(name).name }; } if (action === "remove") { @@ -1538,14 +1589,15 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption }; const selectedLayer = layerName ?? stack.activeLayer?.name; if (selectedLayer !== undefined) { + await resolveDrv(selectedLayer); 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) }; + return { action: "forward_add" as const, forward: forwardInfoToPublic(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) }; + return { action: "forward_add" as const, forward: forwardInfoToPublic(await stack.openForward(spec, INITIAL_LAYER_NAME)) }; } if (typeof drv.openForward !== "function") { throw new Error(`层 '${drv.descriptor.driver}' 不支持动态端口转发`); @@ -1553,16 +1605,20 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption 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) }; + return { action: "forward_add" as const, forward: forwardInfoToPublic(await drv.openForward(spec)) }; } if (action === "forward_list") { - const { layer: layerName, ...extra } = rest; + const { layer: layerName, include_closed, ...extra } = rest; const unknown = Object.keys(extra); if (unknown.length) throw new Error(`manage_layers(forward_list) 未知参数:${unknown.join(", ")}`); + if (include_closed !== undefined && typeof include_closed !== "boolean") throw new Error("include_closed 需为布尔值"); assertOptionalLayerName(layerName); const registered = stack.listForwards(layerName); const external = layerName === undefined ? unregisteredDriver()?.listForwards?.() ?? [] : []; - return { action: "forward_list" as const, forwards: [...registered, ...external] }; + const all = [...registered, ...external]; + // 缺省只报仍在用的转发:已停止/已退出的条目是幂等判定的墓碑,不是在用的转发 + const shown = include_closed === true ? all : all.filter(isForwardActive); + return { action: "forward_list" as const, forwards: shown.map(forwardInfoToPublic) }; } if (action === "forward_remove") { const { forward_id, layer: layerName, ...extra } = rest; @@ -1592,15 +1648,16 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption const extra = Object.keys(unknownArgs); if (extra.length) throw new Error(`run_batch 未知参数:${extra.join(", ")}(支持 steps、layer、stop_on_fail、max_parallel、output)`); if (output !== undefined && output !== "text" && output !== "full") throw new Error('output 需为 "text" 或 "full"'); - const r = await runBatch(resolveDrv, { + const plan = expandBatchLayerWildcards({ steps: steps.map((raw, stepIdx): BatchStepWithDeps => { if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`steps[${stepIdx}] 需为对象`); // 仅转换字段名,实际类型由 runBatch 在执行前统一校验。 - const { id, kind, layer, after, command, path, hunks, expect_exit, timeout_ms, write_mode, local_path, remote_path, transport, ...unknownFields } = raw; + const { id, kind, layer, after, command, command_file, path, hunks, expect_exit, timeout_ms, write_mode, local_path, remote_path, transport, ...unknownFields } = raw; const extra = Object.keys(unknownFields); if (extra.length) throw new Error(`steps[${stepIdx}] 含未知字段:${extra.join(", ")}(目标层字段为 layer)`); return { id, kind, layer, after, command, path, hunks, transport, + commandFile: command_file, expectExit: expect_exit, timeoutMs: timeout_ms, writeMode: write_mode, localPath: local_path, remotePath: remote_path, } as BatchStepWithDeps; @@ -1608,7 +1665,8 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption layer: layerName === undefined ? stack.activeLayer?.name : layerName, stopOnFail: stop_on_fail, maxParallel: max_parallel, - }, output === "text" ? { previewBudgetBytes: 4096 } : {}); + }, knownLayerNames, opts.savedLayers ? "已注册层或已存层" : "已注册层"); + const r = await runBatch(resolveDrv, plan, output === "text" ? { previewBudgetBytes: 4096 } : {}); return { status: r.status, failed_step: r.failedStep, diff --git a/src/batch.ts b/src/batch.ts index 1632a51..edc48b5 100644 --- a/src/batch.ts +++ b/src/batch.ts @@ -17,15 +17,23 @@ * 非预期退出码 = fail,但退出码/输出原样进报告 */ import type { RuntimeDriver } from "./driver.js"; +import { readFileSync } from "node:fs"; import { editFileMulti, type EditMultiHunk } from "./file-edit.js"; import { transferLayerFile, validateFileTransferFields, type FileTransferTransport, type LayerFileTransferResult } from "./layer-file-transfer.js"; import { shellQuote } from "./ssh-helpers.js"; -/** exec 步骤(命令 + 预期退出码集合——非零预期显式声明) */ +/** exec 步骤(命令 + 预期退出码集合——非零预期显式声明)。 + * 命令来源二选一:`command` 内联,或 `commandFile` 引用脚本文件(DSH 评估 + * 2026-11-26 #6)——命令原样进文件,JSON 字符串里的引号/换行转义全部省掉, + * 且同一脚本可被多个步骤/批次复用。commandFile 在计划校验阶段读取并内联: + * 读不出或为空即整批拒绝(零副作用),不会跑到一半才发现。 */ export interface BatchExecStep { id: string; kind: "exec"; - command: string; + command?: string; + /** 脚本文件路径(与 command 互斥)。相对路径按当前进程工作目录解析——经 Daemon + * 执行时由调用方传入的工作目录解析(CLI 已接;MCP 直连请给绝对路径) */ + commandFile?: string; timeoutMs?: number; /** 预期退出码集合(缺省 [0];如健康检查预期 [0] 或显式 [3]) */ expectExit?: number[]; @@ -144,6 +152,16 @@ export async function runBatch( options: { previewBudgetBytes?: number } = {}, ): Promise { // ── 计划校验(零副作用阶段)── + // 未知顶层键拒绝(DSH 真机巡检踩中:`layers` 与 `layer` 一字之差被静默忽略, + // 计划落回默认层在调用方本机执行——「想扫集群、结果扫了自己」的副作用事故。 + // 拼错的字段名必须当场报错,不能当不存在。) + if (plan && typeof plan === "object" && !Array.isArray(plan)) { + const known = new Set(["steps", "layer", "stopOnFail", "maxParallel"]); + const unknown = Object.keys(plan).filter((k) => !known.has(k)); + if (unknown.length > 0) { + throw new Error(`批次计划非法:未知顶层字段 '${unknown.join("、")}'(合法: ${[...known].join("、")}——注意层字段名是 layer,可传数组扇出)`); + } + } if (!Array.isArray(plan?.steps) || plan.steps.length === 0) { // 空计划拒绝(冷路径摸排批 4:SDK 直调曾静默 ok——CLI 有守卫而内核没有, // 绕过 CLI 的消费方拿到「成功执行了零个步骤」的假成功) @@ -160,11 +178,14 @@ export async function runBatch( if (!BATCH_STEP_KINDS.includes(step.kind)) { throw new Error(`批次计划非法:未知 kind '${step.kind}'(合法: ${BATCH_STEP_KINDS.join("、")})`); } - const targetLayers = validateStep(step) ?? planLayers ?? [undefined]; + // commandFile 在此读取并内联(零副作用阶段,且先于 validateStep——后者要求 + // command 已在场);不改写调用方传入的计划对象 + const source = step.kind === "exec" ? { ...step, command: resolveExecCommand(step) } : step; + const targetLayers = validateStep(source) ?? planLayers ?? [undefined]; if (step.kind === "get" && targetLayers.length > 1) { throw new Error(`批次计划非法:步骤 '${step.id}' 的 kind='get' 不支持多个目标层(并发下载会覆盖同一 local_path),请拆分为独立步骤`); } - const { after: dependencies, ...operation } = step; + const { after: dependencies, ...operation } = source; if (operation.kind === "exec" && operation.expectExit) operation.expectExit = [...operation.expectExit]; if (operation.kind === "edit") operation.hunks = operation.hunks.map((hunk) => ({ ...hunk })); const steps = targetLayers.map((layer) => { @@ -325,6 +346,105 @@ function nonEmptyString(value: unknown): value is string { return typeof value === "string" && value.trim().length > 0; } +/** exec 步骤的命令来源(DSH 评估 2026-11-26 #6):command 与 commandFile 二选一。 + * commandFile 就地读取并内联为 command——计划非法时零副作用。内容归一同 + * exec --script-file(剥 BOM、CRLF→LF:Windows 侧编辑器写出的脚本到 bash 里 \r 会 + * 被当成命令名的一部分)。相对路径按当前进程工作目录解析。 */ +function resolveExecCommand(step: BatchExecStep): string { + // 显式类型注解:never 返回的辅助函数只有这样声明,其后的控制流收窄才生效 + const invalid: (detail: string) => never = (detail): never => { + throw new Error(`批次计划非法:步骤 '${step.id}' ${detail}`); + }; + const hasCommand = step.command !== undefined; + const hasFile = step.commandFile !== undefined; + if (hasCommand && hasFile) invalid("的 command 与 commandFile 互斥(只能给一个)"); + if (hasFile) { + const file = step.commandFile; + if (typeof file !== "string" || !nonEmptyString(file)) invalid("的 commandFile 需为非空字符串路径"); + let raw: string; + try { + raw = readFileSync(file, { encoding: "utf-8" }); + } catch (error) { + return invalid(`的 commandFile 读取失败(${file}):${(error as Error).message}`); + } + const command = (raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw).replace(/\r\n/g, "\n"); + if (!command.trim()) invalid(`的 commandFile 内容为空(${file})`); + return command; + } + if (!hasCommand) invalid("是 exec 步骤但缺 command(内联命令,或改用 commandFile 引用脚本文件)"); + return step.command as string; +} + +/** 层名是否含通配(`*` 任意字符序列、`?` 单个字符;DSH 评估 2026-11-26 #6) */ +export function hasLayerWildcard(name: string): boolean { + return /[*?]/.test(name); +} + +function wildcardToRegExp(pattern: string): RegExp { + return new RegExp(`^${pattern.split(/([*?])/).map((part) => (part === "*" ? ".*" : part === "?" ? "." : part.replace(/[.+^${}()|[\]\\]/g, "\\$&"))).join("")}$`); +} + +/** + * 按已知层名展开一个层目标(层名或含通配的模式)。精确等于已知层名的优先按字面 + * 取(层名本身含 * ? 也不会被当模式)。无匹配返回空数组——由调用方决定报错口径。 + */ +export function expandLayerPattern(target: string, known: readonly string[]): string[] { + if (known.includes(target)) return [target]; + if (!hasLayerWildcard(target)) return [target]; + const re = wildcardToRegExp(target); + return known.filter((name) => re.test(name)); +} + +/** + * 计划里的层通配展开(CLI 与 MCP 入口共用;内核的层解析函数只认具体名,所以通配 + * 必须在入口按「已知层名全集」展开)。规则: + * - 顶层 layer 与每个步骤的 layer(单个名或数组)里的模式都展开;展开结果保持已知 + * 层名的原有顺序;数组内去重。 + * - **无匹配即整批拒绝**(零副作用):把 "q-*" 原样当层名交下去,轻则报「层未保存」, + * 重则被当成默认层目标——静默换执行面。 + * - 不含通配的计划原样返回(同一对象引用)。 + */ +export function expandBatchLayerWildcards( + plan: BatchPlan, + known: readonly string[] | (() => readonly string[]), + knownLabel = "已存层", +): BatchPlan { + if (!Array.isArray(plan.steps)) return plan; + let names: readonly string[] | undefined; + const expandOne = (target: string | string[] | undefined, where: string): string | string[] | undefined => { + const targets = typeof target === "string" ? [target] : target; + if (!Array.isArray(targets) || ![...targets].every(nonEmptyString) || !targets.some(hasLayerWildcard)) return target; + validateLayerTarget(target, where); + const available = names ??= typeof known === "function" ? known() : known; + const expandName = (name: string): string[] => { + const hit = expandLayerPattern(name, available); + if (hit.length === 0) { + const scope = available.length === 0 + ? `(当前没有任何${knownLabel})` + : `(现有:${available.slice(0, 12).join("、")}${available.length > 12 ? ` 等 ${available.length} 个` : ""})`; + throw new Error(`批次计划非法:${where} 的层通配 '${name}' 未匹配任何${knownLabel}${scope}`); + } + return hit; + }; + if (typeof target === "string") { + const hit = expandName(target); + return hit.length === 1 ? hit[0]! : hit; + } + const out = [...new Set(targets.flatMap(expandName))]; + return out.length === targets.length && out.every((name, i) => name === targets[i]) ? target : out; + }; + const layer = expandOne(plan.layer, "计划 layer"); + let touched = layer !== plan.layer; + const steps = plan.steps.map((step) => { + if (!step || typeof step !== "object" || step.layer === undefined) return step; + const hit = expandOne(step.layer, `步骤 '${step.id}' 的 layer`); + if (step.layer === hit) return step; + touched = true; + return { ...step, layer: hit }; + }); + return touched ? { ...plan, layer, steps } : plan; +} + function validateLayerTarget(value: unknown, label: string): string[] | undefined { if (value === undefined) return undefined; if (typeof value === "string") { @@ -357,6 +477,9 @@ function validateStep(step: BatchStepWithDeps): string[] | undefined { throw new Error(`批次计划非法:步骤 '${step.id}' 的 ${field} ${expected}`); }; const stepLayers = validateLayerTarget(step.layer, `步骤 '${step.id}' 的 layer`); + if (step.kind !== "exec" && "commandFile" in step && step.commandFile !== undefined) { + invalid("commandFile", "只支持 kind='exec'"); + } if (step.after !== undefined && (!Array.isArray(step.after) || ![...step.after].every(nonEmptyString))) { invalid("after", "需为步骤 id 数组"); } @@ -389,7 +512,10 @@ async function runStep(drv: RuntimeDriver, s: ResolvedBatchStep, previewBytes?: const base = { id: s.id, kind: s.kind, startedAt }; try { if (s.kind === "exec") { - const r = await drv.exec(s.command, { timeoutMs: s.timeoutMs, maxOutputBytes: previewBytes }); + // command 在校验阶段已由 resolveExecCommand 保证在场(commandFile 已内联) + const command = s.command; + if (command === undefined) throw new Error(`步骤 '${s.id}' 缺少 command(内部错误:commandFile 未解析)`); + const r = await drv.exec(command, { timeoutMs: s.timeoutMs, maxOutputBytes: previewBytes }); const expect = s.expectExit ?? [0]; const ok = expect.includes(r.exitCode); return { diff --git a/src/daemon-server.ts b/src/daemon-server.ts index a7fd142..bd2cda1 100644 --- a/src/daemon-server.ts +++ b/src/daemon-server.ts @@ -20,10 +20,11 @@ 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 { isForwardActive, type OpenForwardSpec, type 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 { loadLayerStore } from "./layer-store.js"; import { acquireDaemonLock, assertLoopbackHost, @@ -137,7 +138,7 @@ export class DaemonServer { 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.toolkit = opts.toolkit ?? createAgentToolkit(this.stack, { windowRegistry: this.windowRegistry, savedLayers: loadLayerStore }); this.mcpHandler = new McpProtocolHandler({ toolkit: this.toolkit, serverVersion: this.version }); this.sseKeepaliveMs = opts.sseKeepaliveMs ?? DEFAULT_SSE_KEEPALIVE_MS; this.writeFiles = opts.writeFiles !== false; @@ -514,6 +515,11 @@ export class DaemonServer { && typeof step.localPath === "string") { return { ...step, localPath: this.resolveClientLocalPath(step.localPath, clientCwd) }; } + // commandFile(exec 步骤引用的脚本文件,DSH 评估 2026-11-26 #6)同款按调用方 + // 工作目录解析——Daemon 进程自己的工作目录与 CLI 调用方无关 + if (step && typeof step === "object" && step.kind === "exec" && typeof step.commandFile === "string" && step.commandFile.trim()) { + return { ...step, commandFile: this.resolveClientLocalPath(step.commandFile, clientCwd) }; + } return step; }), }; @@ -833,7 +839,11 @@ export class DaemonServer { case "forward.list": { const layer = typeof params.layer === "string" ? params.layer : undefined; - return { forwards: this.stack.listForwards(layer) }; + // includeClosed(DSH 评估 2026-11-26 #5a):缺省 true 保持协议兼容;调用方 + // 显式传 false 时只报仍在用的转发(stopped/exited 是墓碑,见 isForwardActive) + const includeClosed = params.includeClosed !== false; + const forwards = this.stack.listForwards(layer); + return { forwards: includeClosed ? forwards : forwards.filter(isForwardActive) }; } case "forward.remove": { diff --git a/src/index.ts b/src/index.ts index 8a7b877..62ad264 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export * from "./local-driver.js"; export * from "./events.js"; export * from "./factory.js"; export * from "./runtime-stack.js"; +export * from "./layer-store.js"; export * from "./dialect.js"; export * from "./ssh-helpers.js"; export * from "./ssh-forward.js"; @@ -51,7 +52,7 @@ export { Vt100Screen } from "./vt100-screen.js"; export type { Vt100ScreenOptions } from "./vt100-screen.js"; export { editFile, editFileMulti, EditConflictError } from "./file-edit.js"; export type { EditFileOptions, EditFileResult, EditFileMultiResult, EditMultiHunk } from "./file-edit.js"; -export { runBatch } from "./batch.js"; +export { runBatch, expandBatchLayerWildcards, expandLayerPattern, hasLayerWildcard } from "./batch.js"; export type { BatchPlan, BatchLayerTarget, BatchStep, BatchStepWithDeps, BatchExecStep, BatchEditStep, BatchReadStep, BatchPutStep, BatchGetStep, BatchReport, BatchStepReport, BatchStepStatus, diff --git a/src/layer-store.ts b/src/layer-store.ts new file mode 100644 index 0000000..c0a0512 --- /dev/null +++ b/src/layer-store.ts @@ -0,0 +1,28 @@ +/** + * layer-store.ts — 已存层表(`~/.filaxis/layers.json`,`FILAXIS_LAYERS` 覆盖路径) + * + * `filaxis layer save` 写入的层描述符。CLI、MCP 入口与 Daemon 都从这里取同一份, + * 三条入口对层名与层通配的解析才一致。只读;写入锁与原子落位在 CLI 侧 + * (`updateLayerStore`)。库代码与工具集自身不读用户目录——由入口把读取函数 + * 注入工具集(`createAgentToolkit` 的 `savedLayers`)。 + */ +import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import type { RuntimeDescriptor } from "./driver.js"; + +export function layerStorePath(): string { + return process.env.FILAXIS_LAYERS ?? join(homedir(), ".filaxis", "layers.json"); +} + +/** 文件不存在视为空表;存在但读不出、或形态不对则抛错(坏档不静默当空) */ +export function loadLayerStore(): Record { + try { + const parsed = JSON.parse(readFileSync(layerStorePath(), "utf-8")); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("层快照必须是对象"); + return Object.assign(Object.create(null), parsed); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return Object.create(null); + throw error; + } +} diff --git a/src/mcp-server.ts b/src/mcp-server.ts index d8c21bd..304d003 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -302,16 +302,17 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea 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}`; + const dst = f.kind === "dynamic" ? "SOCKS5" : `${singleLine(f.target_host ?? "")}:${f.target_port}`; + return `forward=${singleLine(f.forward_id)} | layer=${singleLine(f.layer ?? "?")} | ${f.kind} ${singleLine(f.bind_addr)}:${f.bind_port} -> ${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}`; + const dst = f.kind === "dynamic" ? "SOCKS5" : `${singleLine(f.target_host ?? "")}:${f.target_port}`; + const error = f.last_error ? ` | ${singleLine(f.last_error).slice(0, 240)}` : ""; + return `${singleLine(f.forward_id)} | layer=${singleLine(f.layer ?? "?")} | ${f.kind} ${singleLine(f.bind_addr)}:${f.bind_port} -> ${dst} | ${f.status}${error}`; }), ].join("\n"); } diff --git a/src/ssh-forward.ts b/src/ssh-forward.ts index 9d80e13..af8d267 100644 --- a/src/ssh-forward.ts +++ b/src/ssh-forward.ts @@ -56,6 +56,73 @@ export interface CloseForwardResult { detail?: string; } +/** 转发是否仍承载流量(DSH 评估 2026-11-26 #5a)。已停止/已退出的条目只是墓碑—— + * 留在表里是给 closeForward 做幂等判定(already_closed)的,列表类查询默认不该再 + * 把它们当作在用的转发报出来。status=unknown 是「终止未确认」,不能当已停隐藏。 */ +export function isForwardActive(info: Pick): boolean { + return info.status !== "stopped" && info.status !== "exited"; +} + +/** + * 对外转发记录(CLI --json 与 MCP 结果;DSH 评估 2026-11-26 #5b):snake_case—— + * 与工具参数(forward_id、bind_addr…)和流观察窗的 window_id 同一命名风格。 + * SDK 类型 ForwardInfo 保持驼峰不动。 + */ +export interface PublicForwardInfo { + forward_id: string; + /** 兼容别名(将移除)——请读 forward_id */ + forwardId: string; + layer?: string; + kind: DynamicForwardKind; + bind_addr: string; + bind_port: number; + target_host?: string; + target_port?: number; + transport_mode: ForwardTransportMode; + status: ForwardStatus; + created_at: number; + pid?: number; + exit_code?: number | null; + last_error?: string; +} + +export interface PublicCloseForwardResult { + forward_id: string; + /** 兼容别名(将移除)——请读 forward_id */ + forwardId: string; + status: CloseForwardResult["status"]; + detail?: string; +} + +export function forwardInfoToPublic(info: ForwardInfo): PublicForwardInfo { + return { + forward_id: info.forwardId, + forwardId: info.forwardId, + ...(info.layer !== undefined ? { layer: info.layer } : {}), + kind: info.kind, + bind_addr: info.bindAddr, + bind_port: info.bindPort, + ...(info.targetHost !== undefined ? { target_host: info.targetHost } : {}), + ...(info.targetPort !== undefined ? { target_port: info.targetPort } : {}), + transport_mode: info.transportMode, + status: info.status, + created_at: info.createdAt, + ...(info.pid !== undefined ? { pid: info.pid } : {}), + ...(info.exitCode !== undefined ? { exit_code: info.exitCode } : {}), + ...(info.lastError !== undefined ? { last_error: info.lastError } : {}), + }; +} + +/** closeForward 结果的对外投影(同 forwardInfoToPublic) */ +export function closeForwardResultToPublic(res: CloseForwardResult): PublicCloseForwardResult { + return { + forward_id: res.forwardId, + forwardId: res.forwardId, + status: res.status, + ...(res.detail !== undefined ? { detail: res.detail } : {}), + }; +} + export interface NormalizedForwardSpec { kind: DynamicForwardKind; flag: "-L" | "-R" | "-D"; @@ -797,10 +864,16 @@ export class SshForwardManager { socket.destroy(); return; } + const reportFailure = (message: string): void => { + if (entry.closing) return; + entry.info.lastError = message; + this.log.warn(`[filaxis] 转发 ${entry.info.forwardId} ${message}`); + }; let child: ChildProcess; try { child = this.deps.spawnBridge(bridgeArgv); - } catch { + } catch (error) { + reportFailure(`穿层桥接子进程启动失败: ${error instanceof Error ? error.message : String(error)}`); socket.destroy(); return; } @@ -818,15 +891,48 @@ export class SshForwardManager { socket.on("error", teardownConn); socket.once("close", teardownConn); - child.once("error", teardownConn); + let childError = false; + child.once("error", (error) => { + childError = true; + reportFailure(`穿层桥接子进程异常: ${error.message}`); + teardownConn(); + }); child.once("close", () => { bridgeConns.delete(conn); teardownConn(); }); child.stdin?.on("error", teardownConn); child.stdout?.on("error", teardownConn); - child.stderr?.on("data", () => undefined); + // 桥接子进程的 stderr 不是数据面(不进隧道),但也不能丢:内层连不上 + // 目标端口、桥工具启动失败等原因全写在这里。真机排查时连接只会「立刻 + // 断开、零报错」,死因只能手工复现 spawn 才看得见。留尾部一段,子进程 + // 没送出任何数据就退出时记日志并挂到转发记录上。 + let relayedBytes = 0; + let stderrTail = ""; + child.stdout?.on("data", (d: Buffer) => { relayedBytes += d.length; }); + child.stderr?.on("data", (d: Buffer) => { + stderrTail = (stderrTail + d.toString("utf-8")).slice(-2048); + }); child.stderr?.on("error", () => undefined); + const bridgeDied = (code: number | null, signal: NodeJS.Signals | null): string => { + const why = stderrTail.trim().split(/\r?\n/).filter(Boolean).slice(-4).join(" | "); + return `穿层桥接子进程未送出数据即退出 (code=${code ?? signal})${why ? `: ${why}` : ""}`; + }; + child.once("close", (code, signal) => { + if (entry.closing || childError || relayedBytes > 0) return; + if (teardownStarted && signal !== null && !stderrTail.trim()) return; + const failed = code !== 0 || signal !== null; + if (code === 0 && signal === null && !stderrTail.trim()) { + // 客户端连上不发数据就断开也会走到这里,不当作故障 + this.log.debug(`[filaxis] 转发 ${entry.info.forwardId} ${bridgeDied(code, signal)}`); + return; + } + if (failed) reportFailure(bridgeDied(code, signal)); + else { + entry.info.lastError = bridgeDied(code, signal); + this.log.info(`[filaxis] 转发 ${entry.info.forwardId} ${entry.info.lastError}`); + } + }); if (child.stdin) socket.pipe(child.stdin); if (child.stdout) child.stdout.pipe(socket); diff --git a/src/ssh-helpers.ts b/src/ssh-helpers.ts index 7fc81cc..d04ab89 100644 --- a/src/ssh-helpers.ts +++ b/src/ssh-helpers.ts @@ -150,8 +150,8 @@ function assertBareHost(target: string): void { } /** ssh 命令行参数(spawn 数组与 ssh -G 解析共用) */ -export function sshArgsFor(hop: SshHop): string[] { - return renderSshArgs(hop, process.platform === "win32"); +export function sshArgsFor(hop: SshHop, opts: { interactive?: boolean } = {}): string[] { + return renderSshArgs(hop, process.platform === "win32", false, opts.interactive === true); } function quoteWindowsProxyArg(value: string): string { @@ -170,7 +170,7 @@ function knownHostsOption(file: string, windows: boolean): string { return `UserKnownHostsFile=${quoted}`; } -function renderSshArgs(hop: SshHop, windowsProxy: boolean, remote = false): string[] { +function renderSshArgs(hop: SshHop, windowsProxy: boolean, remote = false, interactive = remote): string[] { if (!isHopObj(hop) || !hop.conn) { assertBareHost(hopHost(hop)); return [hopHost(hop)]; @@ -196,7 +196,8 @@ function renderSshArgs(hop: SshHop, windowsProxy: boolean, remote = false): stri 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}`); + const batchOpt = interactive ? "" : "-o BatchMode=yes "; + args.push("-o", `ProxyCommand=ssh ${batchOpt}${hk}${keyOpt}${portOpt}-W %h:%p ${target}`); } if (keyFile) args.push("-i", remote ? keyFile : expandHomePath(keyFile)); if (port) args.push("-p", String(port)); @@ -329,18 +330,26 @@ export function assertNoLikelyTypoKeys(config: Record | undefin * 自治建链选项(AC-12:host key 策略显式可配): * - ConnectTimeout=10(先于握手超时暴露真相);ServerAlive 30×3(静默死亡 ~90s 内暴露) * - hostKeyPolicy:tofu(缺省,accept-new)/ strict(yes + 可选 UserKnownHostsFile) - * 不加 BatchMode:禁交互提示会抹掉「等待输入」这个可感知状态——感知到 prompt 后 - * 把原文直交调用方,而不是假装它不存在。 + * - **BatchMode=yes(非交互子进程的缺省,2026-11-26)**:exec 通道/观察窗/转发/文件传输 + * 都是没有终端的一次性 ssh——遇到口令/密码提示时它应答不了,也不会失败。Windows 上 + * 无控制台的进程直接停在提示上、零输出,直到调用方超时且终态 unknown 不可重试 + * (实测:缺密钥时挂满 timeoutMs;加 BatchMode 后 414ms 报 Permission denied)。 + * agent 认证不受影响;带口令的私钥须先装入 ssh-agent。文件中转模式早已自带。 + * - **PTY 登录链例外**(`interactive: true`,见 rootSshSpawnArgs / hopSshCommand):那边 + * 交互提示会回显进 PTY,是「等待输入」的可感知状态——要原样直交调用方,而不是 + * 让它当场失败。逐跳登录(su -/密码类)只有这条路能走。 * 渲染只含密钥/known_hosts **路径**,永不包含其内容(AC-12 无泄漏红线)。 */ -export function autonomousSshOpts(conn?: SshConnParams): string[] { - return renderAutonomousSshOpts(conn, false); +export function autonomousSshOpts(conn?: SshConnParams, opts: { interactive?: boolean } = {}): string[] { + return renderAutonomousSshOpts(conn, false, opts.interactive === true); } -function renderAutonomousSshOpts(conn: SshConnParams | undefined, remote: boolean): string[] { +function renderAutonomousSshOpts(conn: SshConnParams | undefined, remote: boolean, interactive = remote): 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"]; + // remote(PTY 内再嵌一层 ssh 做逐跳登录)同属交互链——缺省即 interactive + if (!interactive) opts.push("-o", "BatchMode=yes"); if (conn?.hostKeyPolicy === "strict") { opts.push("-o", "StrictHostKeyChecking=yes"); } else { @@ -360,7 +369,7 @@ function renderAutonomousSshOpts(conn: SshConnParams | undefined, remote: boolea * (第一条命令付握手建 master,后续任何进程同 dest 毫秒级复用)。 */ export function muxSocketPath(destArgs: string[], dir?: string): string { - const destKey = crypto.createHash("sha256").update(destArgs.join("")).digest("hex").slice(0, 16); + const destKey = crypto.createHash("sha256").update(destArgs.join("\0")).digest("hex").slice(0, 16); const muxDir = dir ?? join(tmpdir(), "filaxis-mux"); try { if (!existsSync(muxDir)) mkdirSync(muxDir, { recursive: true }); } catch { /* 并发竞态容忍 */ } return join(muxDir, `cm-${destKey}`); @@ -391,9 +400,9 @@ export function muxFlagsFor(destArgs: string[], opts: { disable?: boolean; dir?: ]; } -/** root 层 spawn 全参数(含 -tt 强制 PTY) */ +/** root 层 spawn 全参数(含 -tt 强制 PTY)。PTY 登录链保留交互提示(不加 BatchMode) */ export function rootSshSpawnArgs(destArgs: string[], conn?: SshConnParams): string[] { - return ["-tt", ...autonomousSshOpts(conn), ...destArgs]; + return ["-tt", ...autonomousSshOpts(conn, { interactive: true }), ...destArgs]; } /** PTY 内 hop 登录命令(选项语义与 root 对齐) */ @@ -461,6 +470,182 @@ async function lookupSshIdentity(hop: SshHop, logger?: FilaxisLogger): Promise; +} + +/** MSYS(Git Bash)ssh 输出的 POSIX 形态盘符路径转回本机形态(文件在场的判定用) */ +function nativePath(p: string): string { + return process.platform === "win32" ? p.replace(/^\/([a-zA-Z])\//, (_m, d: string) => `${d.toUpperCase()}:\/`) : p; +} + +/** 身份与配置来源探测(认证失败诊断用,DSH 评估 2026-11-26 #1b):与真实连接共用 + * sshArgsFor 渲染——解析结果就是连接时生效的那份。失败返回 null(诊断退化为不含 + * 来源段:探测自身不得掩盖原始错误)。 */ +export async function describeSshIdentitySource(hop: SshHop, logger?: FilaxisLogger): Promise { + let stdout = ""; + let stderr = ""; + try { + // argv 构造也在 try 内:非法主机(前导 -)会让 sshArgsFor 抛错——同样按「探测失败」处理 + const argv = ["-v", "-G", ...sshArgsFor(hop)]; + if (sshFileStdioRequested()) { + const r = await spawnWithFileRedirect(argv, "", { timeoutMs: 5000, logger }); + if (r.exitCode !== 0) return null; + stdout = r.stdout; + stderr = r.stderr; + } else { + const { execFile } = await import("node:child_process"); + const { promisify } = await import("node:util"); + ({ stdout, stderr } = await promisify(execFile)("ssh", argv, { + timeout: 5000, windowsHide: true, env: openSshEnvironment(process.env, logger), + })); + } + } catch { + return null; + } + const out = stdout.replace(/\r\n/g, "\n"); + const dbg = stderr.replace(/\r\n/g, "\n"); + const user = out.match(/^user (\S+)$/m)?.[1]; + const hostname = out.match(/^hostname (\S+)$/m)?.[1]; + const port = out.match(/^port (\S+)$/m)?.[1]; + if (!user || !hostname || !port) return null; + const configFiles = [...dbg.matchAll(/^debug\d+: Reading configuration data (.+)$/gm)].map((m) => m[1]!.trim()); + const identityFiles = [...out.matchAll(/^identityfile (.+)$/gm)].map((m) => { + const path = m[1]!.trim(); + return { path, exists: existsSync(nativePath(expandHomePath(path))) }; + }); + return { configFiles, user, hostname, port, identityFiles }; +} + +export type SshFailureKind = "auth" | "resolve" | "unreachable" | "hostkey" | "other"; + +export interface AuthFailureDiagnosisInput { + role: "jump" | "target"; + /** 人读落点(user@host 或 host,可带端口) */ + label: string; + /** 是否显式给了用户名——没给时解析出的用户名值得单独提醒 */ + userGiven: boolean; + /** 目标:--key / keyFile 传入的路径;跳板恒为空(--key 不传给跳板) */ + keyFile?: string; + source: SshIdentitySource | null; + /** 失败类别(缺省 auth):resolve=主机名/别名解析不出;unreachable=连不上 */ + kind?: Extract; + /** 诊断探测带回的 ssh 原始报错行——原样直交 */ + sshLines?: string[]; +} + +/** + * 连接失败诊断(纯函数):把角色(跳板/目标)、类别、探测到的来源与出路拼成可操作文案。 + * source 为 null(探测失败)时只保留不依赖来源的说明。 + */ +export function formatAuthFailureDiagnosis(input: AuthFailureDiagnosisInput): string { + const lines: string[] = []; + const kind = input.kind ?? "auth"; + const isJump = input.role === "jump"; + const what = isJump ? "跳板" : "目标"; + // 目标串可能为空(坏层文件/空 target)——留一对空反引号等于没说 + const label = input.label.trim() || "(空目标——检查 --host 或层文件里的 target)"; + if (kind === "auth") { + lines.push(isJump ? `[跳板认证失败] 跳板 \`${label}\` 拒绝了认证(Permission denied)。` : `[目标认证失败] \`${label}\` 拒绝了认证(Permission denied)。`); + if (isJump) { + lines.push(" --key 只用于目标主机,不会传给跳板——跳板的用户名与密钥取自 ssh 配置:"); + } else { + lines.push(" exec 通道没有终端,口令/密码/私钥口令的提示无法应答(BatchMode)——带口令的私钥请先装入 ssh-agent:"); + } + } else if (kind === "resolve") { + lines.push(`[${what}无法解析] ${what} \`${label}\` 解析不出地址。`); + lines.push(` ${what}别名或主机名由**本运行环境**的 ssh 配置与 DNS 解析——沙箱、服务进程、远端会话的工作环境里可能没有该别名(本机命令行能连 ≠ 这里能连):`); + } else { + lines.push(`[${what}不可达] 连不上${what} \`${label}\`。`); + lines.push(" 核对下面的地址与端口是否符合预期;网络、防火墙、VPN、对方 sshd 是否在监听:"); + } + const s = input.source; + if (s) { + lines.push(` 实际读取的配置文件:${s.configFiles.length ? s.configFiles.join(";") : "(无)"}`); + lines.push(` 解析为:user=${s.user}${input.userGiven ? "" : "(未显式指定)"} hostname=${s.hostname} port=${s.port}`); + if (kind === "auth") { + const present = s.identityFiles.filter((f) => f.exists); + const absent = s.identityFiles.filter((f) => !f.exists); + lines.push(` 在场的身份文件:${present.length ? present.map((f) => f.path).join(";") : "(无)"}`); + if (absent.length) lines.push(` (另有 ${absent.length} 个身份文件不存在:${absent.slice(0, 3).map((f) => f.path).join("、")}${absent.length > 3 ? " 等" : ""})`); + if (!present.length) { + lines.push(" ⚠ 没有任何在场的身份文件——这就是被拒的原因"); + } + if (!input.userGiven && present.length) { + lines.push(" (未显式指定用户名——若上面的 user 不是期望的登录用户,就是被拒的原因之一)"); + } + } + } + if (!isJump && input.keyFile) { + const ok = existsSync(nativePath(expandHomePath(input.keyFile))); + lines.push(` --key:${input.keyFile}${ok ? "" : "(文件不存在!)"}`); + } + if (isJump && kind === "auth") { + lines.push(" 出路(任选其一):① 在 ssh config 里给跳板配 Host 条目并写 IdentityFile,-J 改用该别名;② 把密钥装入 ssh-agent;③ SDK 用结构化 jump:{ host, user, keyFile }"); + } else if (isJump && kind === "resolve") { + lines.push(" 出路:改用 user@host[:port] 字面量,或在运行环境的 ssh config 里补上该条目后重试"); + } + if (input.sshLines?.length) { + lines.push(" [ssh 原始输出·直交]"); + for (const l of input.sshLines) lines.push(` ${l}`); + } + return "\n" + lines.join("\n"); +} + +/** ssh 报错里值得直交的行(其余 debug 噪声不带回) */ +const SSH_FAILURE_LINE_RE = /Permission denied|Could not resolve hostname|Name or service not known|Connection (timed out|refused|closed|reset)|No route to host|Network is unreachable|Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|kex_exchange_identification|banner exchange|Too many authentication failures|Operation timed out|not accessible: No such file|Load key|no such identity|Bad configuration option|command-line line \d+/; + +/** 该报错行点名的主机是不是 host(`user@host: …` / `hostname host:` / `host host port` / `by host` / `to host port`) */ +function sshLineNamesHost(line: string, host: string): boolean { + if (!host) return false; + return [`@${host}:`, `hostname ${host}:`, `hostname ${host} `, `host ${host} `, `host ${host}:`, `by ${host} `, `to ${host} port`, `to ${host}:`] + .some((needle) => line.includes(needle)); +} + +export interface SshFailureVerdict { + /** 失败发生在哪一段:jump=跳板(ProxyCommand 内层),target=目标段,none=没有可判读的失败行 */ + stage: "jump" | "target" | "none"; + kind: SshFailureKind | null; + /** ssh 原始报错行(去重、截断) */ + lines: string[]; +} + +/** 带主机名的报错行形态:`user@host: …` / `Could not resolve hostname host` / `connect to host host port N` / `… by host port N` */ +const SSH_NAMED_LINE_RE = /@[^@\s]+: |hostname \S+|host \S+ port \d+|by \S+ port \d+/; + +/** + * ssh 诊断输出的归属判定(纯函数):失败点归到跳板段或目标段。 + * 归属看第一条**点名了主机**的报错行——`Permission denied, please try again.` 这类不带 + * 主机的重试提示会排在真正的拒绝行前面(真机抓回:只看首行会把跳板被拒归给目标)。 + * 跳板段先失败时不会有目标段的报错,所以第一条点名行即失败点。 + */ +export function classifySshFailure(rawStderr: string, jumpHost: string | null): SshFailureVerdict { + const lines: string[] = []; + for (const raw of rawStderr.replace(/\r\n/g, "\n").split("\n")) { + const line = raw.replace(/^debug\d+:\s*/, "").trim(); + if (!line || !SSH_FAILURE_LINE_RE.test(line) || lines.includes(line.slice(0, 200))) continue; + lines.push(line.slice(0, 200)); + if (lines.length >= 8) break; + } + const first = lines[0]; + if (!first) return { stage: "none", kind: null, lines }; + const kind: SshFailureKind = /Permission denied|Too many authentication failures/.test(first) ? "auth" + : /Could not resolve hostname|Name or service not known/.test(first) ? "resolve" + : /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/.test(first) ? "hostkey" + : /Connection (timed out|refused|closed|reset)|No route to host|Network is unreachable|kex_exchange_identification|banner exchange|Operation timed out/.test(first) ? "unreachable" + : "other"; + const named = lines.find((l) => SSH_NAMED_LINE_RE.test(l)); + const stage: SshFailureVerdict["stage"] = named && jumpHost && sshLineNamesHost(named, jumpHost) ? "jump" : "target"; + return { stage, kind, lines }; +} + /** 层的完整途经身份链(target + hops),供回环检测 */ export function layerPathIdentities(desc: RuntimeDescriptor): SshHop[] { const hops: SshHop[] = Array.isArray(desc.config?.sshHops) ? (desc.config.sshHops as SshHop[]) : []; @@ -519,6 +704,10 @@ export function tokenizeArgv(line: string): string[] { export const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`; +function sshEnterTokens(command: string): string[] { + return tokenizeArgv(command).filter((arg) => arg !== "-t" && arg !== "-tt"); +} + /** 环境变量名合法性(拼入远端命令前的红线——防 argv/引号注入) */ export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; @@ -558,16 +747,15 @@ export function renderExecChannel( /** 单层进入命令的非交互重放形态(docker:-it→-i + shell 追加 -s;ssh:剥 -t + * 远端命令位接 sh -s) */ const replayTokens = (raw: string): string[] | { unreachable: true; reason: string; step: string } => { - // -it / -t → -i(非交互);进入命令须以 shell 结尾(内层读 stdin) - const cleaned = raw.replace(/(^|\s)-(it|ti)\b/g, "$1-i").replace(/(^|\s)-t\b/g, "$1-i").trim(); // ssh 形态(用户实测反馈):`ssh remote-vm` 不以 shell 结尾,但远端命令位 // 可直接接 sh -s(ssh host sh -s = stdin 管道链,零嵌套引用)——并非真不可 // 直达。注意清洗语义与 docker 相反:ssh 的 -t 是「强制 PTY」须**剥掉** // (换成 -i 会变成 identity file 指认,完全跑偏) - if (/^ssh(\s|$)/.test(cleaned)) { - const stripped = cleaned.replace(/(^|\s)-+(tt|t)\b/g, "$1").replace(/\s+/g, " ").trim(); - return [...tokenizeArgv(stripped), "sh", "-s"]; + if (/^ssh(\s|$)/.test(raw.trim())) { + return [...sshEnterTokens(raw.trim()), "sh", "-s"]; } + // -it / -t → -i(非交互);进入命令须以 shell 结尾(内层读 stdin) + const cleaned = raw.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 { @@ -590,11 +778,11 @@ export function renderExecChannel( if (steps.length > 0) { const first = replayTokens(steps[0]!.cmd); if ("unreachable" in first) return { kind: "unreachable", reason: first.reason, step: first.step }; - remoteArgs.push(...first); + remoteArgs.push(...first.map(quoteSshShellArg)); for (const s of steps.slice(1)) { const t = replayTokens(s.cmd); if ("unreachable" in t) return { kind: "unreachable", reason: t.reason, step: t.step }; - innerLayers.push(t.join(" ")); + innerLayers.push(t.map(quoteSshShellArg).join(" ")); } } // 终层远端 shell:POSIX sh 通吃(包装脚本纯 POSIX——报告 #3:FreeBSD/Alpine 无 bash @@ -634,24 +822,28 @@ export function renderEnterBridgeCommand(steps: EnterStep[], innerCommand: strin 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); + const parsed = sshEnterTokens(trimmed); 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]; + // ssh 跳比 docker/bash 尾形态多一层 shell 解析:本机 spawn 的整串命令先被 + // 跳板 sh 消费一次,嵌套 ssh 再把多个参数按空格拼接(引号结构全丢)。若只 + // 按单层引号渲染,目标侧拿到的已是 `sh -c exec ...`——dash 的裸 exec(无参 + // 数)会按 POSIX 语义直接终结 shell,后面的命令全部不执行(真机实锤:穿层 + // 转发 listener 活着、连接即断、零报错)。所以把 `sh -c <内层>` 整体再包一 + // 层引号作为嵌套 ssh 的单个命令参数;每多一跳 ssh 就多一层,逐跳累积。 + current = [...parsed.map(shellQuote), shellQuote(`sh -c ${shellQuote(current)}`)].join(" "); + continue; + } + 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, + }; } + const 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 4f495b8..acfcd59 100644 --- a/src/ssh-pty-driver.ts +++ b/src/ssh-pty-driver.ts @@ -31,6 +31,7 @@ import type { import { autonomousSshOpts, SSH_INPUT_WAIT_RE, enterStepsOf, hopLabel, rootSshSpawnArgs, cdTargetArg, sshArgsFor, renderExecChannel, shellQuote, muxFlagsFor, assertNoLikelyTypoKeys, envPrefixOf, ENV_NAME_RE, type SshConnParams, type SshHop, ENTER_ALIAS_KEYS, + classifySshFailure, describeSshIdentitySource, formatAuthFailureDiagnosis, parseJumpSpec, } 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"; @@ -361,7 +362,13 @@ ${command} if (this.rawArrived) resolve(); else this.firstOutWaiter = resolve; }); - await Promise.race([firstOut, new Promise((r) => setTimeout(r, 8000))]); + // 竞速定时器必须清(DSH 评估 2026-11-26 #4):首输出先到时 race 已 settle,但 8s + // 定时器仍挂在事件循环上。常驻进程无感;一次性 CLI(--no-daemon --pty)不调 + // process.exit、靠事件循环排空退出——结果早已打印,进程却被拖到 attach+8s 才退 + //(实测 8360ms,同一命令不带 --pty 为 694ms) + let quietTimer: ReturnType | undefined; + await Promise.race([firstOut, new Promise((r) => { quietTimer = setTimeout(r, 8000); })]); + clearTimeout(quietTimer); await new Promise((r) => setTimeout(r, 600)); } @@ -619,7 +626,7 @@ export class SshPtyDriver implements RuntimeDriver { this.log.warn(`[SshPty] 内层 shell 已退出,层退化:${evidence}——连接仍在但已非本层环境`); }; - this.link.attach(rootSshSpawnArgs(sshArgsFor(rootHop), connParams), this.log); + this.link.attach(rootSshSpawnArgs(sshArgsFor(rootHop, { interactive: true }), connParams), this.log); try { await this.link.handshake(`ssh ${hopLabel(rootHop)}`); } catch (error) { this.link.kill(); throw error; } for (const hop of hops) { @@ -861,8 +868,11 @@ export class SshPtyDriver implements RuntimeDriver { // 的握手成本从「每条命令」降到「每 10min 窗口首条」(ControlPersist=600); // 与观察流同一 socket(exec/observe 同主机共享一条主连接) const destArgs = sshArgsFor(rootHop); - const sshOptions = autonomousSshOpts(connParams); - if (fileStdio) sshOptions.unshift("-T", "-o", "BatchMode=yes", "-o", "ClearAllForwardings=yes"); + const sshOptions = autonomousSshOpts(connParams); // 非交互子进程:已含 BatchMode=yes(认证失败当场报错,不挂在提示上) + // mux socket 名按 [...sshOptions, ...destArgs] 哈希——exec 与观察窗/转发都经 + // autonomousSshOpts 取同一份选项,socket 名才一致、master 才能共享(勿在 + // 个别调用点往 sshOptions 里单方面加选项) + if (fileStdio) sshOptions.unshift("-T", "-o", "ClearAllForwardings=yes"); const argv = [...sshOptions, ...muxFlagsFor(destArgs, { sshOptions }), ...destArgs, "--", ...render.remoteArgs]; // 显式 stdio 模式覆盖(DeepSeek Harness 反馈):FILAXIS_SSH_STDIO_MODE=inherit // 直接走文件中转(管道句柄在受限沙箱里被拦截——ssh 秒退 255 零输出) @@ -950,8 +960,12 @@ export class SshPtyDriver implements RuntimeDriver { if (!completion) { // 沙箱 stdio 管道损坏诊断(DeepSeek Harness 反馈):秒退 255+ // 零输出=管道句柄被拦截的指纹——一次文件中转重试(cmd/sh 的 > - // 是文件句柄非管道句柄,沙箱放行);重试仍败才报错附双模式现场 - if (isBrokenStdioExit(code, evidence, errorOutput, Date.now() - spawnAt)) { + // 是文件句柄非管道句柄,沙箱放行);重试仍败才报错附双模式现场。 + // **带跳板时不套这个指纹**(DSH 评估 2026-11-26 真机发现):ProxyCommand + // 模式下 ssh 把自身 stderr 指向 /dev/null——跳板解析失败/认证被拒/ + // 不可达一概是「255 + 零输出 + 秒退」,套上去就把真实原因换成一句 + //「疑似沙箱管道损坏、去设文件中转」。按收到的原始报错诊断。 + if (!connParams?.jump && isBrokenStdioExit(code, evidence, errorOutput, Date.now() - spawnAt)) { // 沙箱 stdio 管道损坏指纹(DeepSeek Harness 反馈)。**不自动重放** //(Sol 78 P1-2):首轮结果未知=远端可能已执行副作用——非幂等命令 // 重试违宪(tmux spawn 错误同款纪律「勿盲目重试非幂等命令」)。 @@ -966,20 +980,13 @@ export class SshPtyDriver implements RuntimeDriver { }); return; } - finish(() => { - // 连接层失败诊断(试用反馈 #29:-J/--host 传 ssh-config 别名在沙箱/ - // 远端环境「不认」——别名解析依赖**运行环境**的 ~/.ssh/config,本机 - // 有的别名沙箱里没有。报错直交 + 指引,缩短排障路径) - const connFail = /Could not resolve hostname|Connection (timed out|refused|closed)|Permission denied|Host key verification failed|no route to host/i.test(errorOutput); - const diag = connFail - ? "\n[连接层失败] ssh 本身没建起链——若 --host/-J 传的是 ssh-config 别名,注意别名解析用的是**本运行环境**的 ~/.ssh/config(沙箱/远端会话可能没有该条目:改用 user@host[:port] 字面量或先补 config)" - : ""; - const e = new Error( - `命令未完成(无完成哨兵——通道中断/进程被信号终止,close code=${code})${stdinErr ? `;stdin 管道错误: ${stdinErr.message}` : ""}。半截现场 stdout 尾 500 字符:\n${evidence.slice(-500)}\nstderr 尾 300:\n${errorOutput.slice(-300)}${diag}`, - ) as Error & { outcome: "unknown" }; - e.outcome = "unknown"; - reject(e); - }); + const base = `命令未完成(无完成哨兵——通道中断/进程被信号终止,close code=${code})${stdinErr ? `;stdin 管道错误: ${stdinErr.message}` : ""}。半截现场 stdout 尾 500 字符:\n${evidence.slice(-500)}\nstderr 尾 300:\n${errorOutput.slice(-300)}`; + const report = (diag: string) => finish(() => reject(withUnknownOutcome(new Error(base + diag)))); + if (code !== 255 || evidence.length > 0) { + report(""); + return; + } + void connFailureDiagnosis(rootHop, connParams, errorOutput, this.log).then(report, () => report(ALIAS_HINT)); return; } // 哨兵在场:退出码以哨兵为准(code===null 的信号杀竞态也不伪 0) @@ -1084,6 +1091,61 @@ export class SshPtyDriver implements RuntimeDriver { } } +const ALIAS_HINT = + "\n[连接层失败] ssh 本身没建起链——若 --host/-J 传的是 ssh-config 别名,注意别名解析用的是**本运行环境**的 ~/.ssh/config(沙箱/远端会话可能没有该条目:改用 user@host[:port] 字面量或先补 config)"; + +function withUnknownOutcome(e: Error): Error & { outcome: "unknown" } { + return Object.assign(e, { outcome: "unknown" as const }); +} + +/** 带上 ssh 原始报错行(直交) */ +function withSshLines(diag: string, lines: string[] | undefined): string { + if (!lines?.length) return diag; + return diag + "\n [ssh 原始输出·直交]\n" + lines.map((l) => ` ${l}`).join("\n"); +} + +const jumpLabelOf = (js: { host: string; user?: string; port?: number }): string => + `${js.user ? `${js.user}@` : ""}${js.host}${js.port ? `:${js.port}` : ""}`; + +/** 根据原始 SSH 报错定位连接阶段。需要补充凭据来源时只读取本地 SSH 配置。 */ +async function connFailureDiagnosis(rootHop: SshHop, connParams: SshConnParams | undefined, errorOutput: string, logger: FilaxisLogger): Promise { + const jump = connParams?.jump; + try { + const js = jump ? parseJumpSpec(jump) : undefined; + const { stage, kind, lines } = classifySshFailure(errorOutput, js?.host ?? null); + if (stage === "none") { + return js && !errorOutput.trim() + ? "\n[SSH] 跳板连接未返回诊断输出,失败位置无法确认。" + : ""; + } + if (js && stage === "jump") { + const label = jumpLabelOf(js); + if (kind !== "auth" && kind !== "resolve" && kind !== "unreachable") { + return withSshLines("\n[跳板连接失败] ssh 在跳板段报错。", lines); + } + const source = kind === "auth" ? await describeSshIdentitySource( + { host: js.host, conn: { user: js.user, port: js.port, keyFile: js.keyFile } }, logger) : null; + return formatAuthFailureDiagnosis({ + role: "jump", label, userGiven: js.user != null, kind, source, sshLines: lines, + }); + } + if (kind !== "auth" && (!js || kind !== "resolve")) return withSshLines(ALIAS_HINT, lines); + const target = typeof rootHop === "string" ? rootHop : rootHop.host; + return formatAuthFailureDiagnosis({ + role: "target", + label: `${target}${connParams?.port ? `:${connParams.port}` : ""}`, + userGiven: target.includes("@") || Boolean(connParams?.user), + kind, + keyFile: kind === "auth" ? connParams?.keyFile : undefined, + source: kind === "auth" ? await describeSshIdentitySource(rootHop, logger) : null, + sshLines: lines, + }); + } catch { + return ALIAS_HINT; + } +} +export const __testConnFailureDiagnosis = connFailureDiagnosis; // 测试导出面 + /** shell 单引号安全引用 */ function q(s: string): string { return `'${s.replace(/'/g, "'\\''")}'`; diff --git a/tests/agent-toolkit.test.ts b/tests/agent-toolkit.test.ts index 6782323..ace4d55 100644 --- a/tests/agent-toolkit.test.ts +++ b/tests/agent-toolkit.test.ts @@ -1668,3 +1668,93 @@ describe("audit regression fixes (P1/P2/P3)", () => { } }, 30_000); }); + +// --------------------------------------------------------------------------- +// DSH + GLM-5.4 使用评估(2026-11-26)#6:run_batch 的 command_file 与层通配 +// --------------------------------------------------------------------------- +describe("run_batch:command_file 与层通配(DSH 评估 2026-11-26 #6)", () => { + test("command_file 引用脚本文件替代 command:命令原样进文件,免 JSON 转义", async () => { + const fs = await import("node:fs"); + const os = await import("node:os"); + const path = await import("node:path"); + const { TOOL_DEFS } = await import("../src/agent-toolkit.js"); + const d = fs.mkdtempSync(path.join(os.tmpdir(), "fx-tk-cf-")); + try { + const tk = createAgentToolkit(new RuntimeStack(), {}); + const f = path.join(d, "snap.sh"); + fs.writeFileSync(f, "printf '%s\\n' \"it's\" 'a \"quoted\" word'\n"); + const r = await tk.handlers.run_batch({ steps: [{ id: "cf", kind: "exec", command_file: f }] }); + expect(r.status).toBe("ok"); + expect(r.steps[0]!.stdout).toContain("it's"); + expect(r.steps[0]!.stdout).toContain('a "quoted" word'); + // 二者互斥;驼峰 commandFile 在 MCP 面不是合法字段(字段名统一 snake_case) + await expect(tk.handlers.run_batch({ steps: [{ id: "s", kind: "exec", command: "x", command_file: f }] })).rejects.toThrow(/互斥/); + await expect(tk.handlers.run_batch({ steps: [{ id: "s", kind: "exec", commandFile: f }] })).rejects.toThrow(/未知字段/); + // schema 把 command_file 暴露给调用方 + const batchTool = TOOL_DEFS.find((t) => t.function.name === "run_batch")!; + const params = batchTool.function.parameters as { properties: { steps: { items: { properties: Record } } } }; + expect(params.properties.steps.items.properties).toHaveProperty("command_file"); + } finally { + fs.rmSync(d, { recursive: true, force: true }); + } + }, 30_000); + + test("已存层:未注册的层名与层通配命中入口注入的层表时按需加载,且不抢默认层", async () => { + // 三路互通(用户 2026-11-26 定调:CLI / MCP / SDK 本来就该认同一份层)。 + // 入口注入读取函数;工具集自身不读用户目录。 + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const stack = new RuntimeStack(); + await stack.addLayer("q-a", new LocalRuntimeDriver()); + let reads = 0; + const store: Record = { "sv-1": { driver: "local" }, "sv-2": { driver: "local" } }; + const tk = createAgentToolkit(stack, { savedLayers: () => { reads++; return store; } }); + try { + // 通配:已存的那两个此刻才注册 + const r = await tk.handlers.run_batch({ layer: "sv-?", steps: [{ id: "hi", kind: "exec", command: "printf hi" }] }); + expect(r.status).toBe("ok"); + expect(r.steps.map((s) => s.id).sort()).toEqual(["hi@sv-1", "hi@sv-2"]); + expect([...stack.layers.keys()].sort()).toEqual(["q-a", "sv-1", "sv-2"]); + // 被顺带加载的层不抢默认层 + expect(stack.activeLayer?.name).not.toMatch(/^sv-/); + + // 精确层名:单个工具也认已存层 + const rc = await tk.handlers.run_command({ layer: "sv-1", command: "printf named" }) as { stdout: string }; + expect(rc.stdout).toContain("named"); + + // 进程存活期间新保存的层也认(读取函数每次调用、不缓存) + store["sv-3"] = { driver: "local" }; + const r3 = await tk.handlers.run_batch({ layer: "sv-3", steps: [{ id: "x", kind: "exec", command: "printf three" }] }); + // 单层计划保留原步骤 id;层字段指向新加载的已存层 + expect(r3.steps[0]!.id).toBe("x"); + expect(r3.steps[0]!.layer).toBe("sv-3"); + + // 哪边都没有:点名说清;坏档:原样报出,不当空表 + await expect(tk.handlers.run_batch({ layer: "ghost", steps: [{ id: "s", kind: "exec", command: "x" }] })) + .rejects.toThrow(/未注册,也不在已存层表里/); + const broken = createAgentToolkit(new RuntimeStack(), { savedLayers: () => { throw new Error("层快照必须是对象"); } }); + await expect(broken.handlers.run_batch({ layer: "a-*", steps: [{ id: "s", kind: "exec", command: "x" }] })) + .rejects.toThrow(/层快照必须是对象/); + expect(reads).toBeGreaterThan(0); + } finally { + await Promise.all([...stack.layers.keys()].map((n) => stack.removeLayer(n, { destroy: true }))); + } + }, 30_000); + + test("layer 通配按已注册层名展开;无匹配则拒绝(不落到默认层)", async () => { + const { LocalRuntimeDriver } = await import("../src/local-driver.js"); + const stack = new RuntimeStack(); + await stack.addLayer("q-a", new LocalRuntimeDriver()); + await stack.addLayer("q-b", new LocalRuntimeDriver()); + await stack.addLayer("keep", new LocalRuntimeDriver()); + const tk = createAgentToolkit(stack, {}); + try { + const r = await tk.handlers.run_batch({ layer: "q-?", steps: [{ id: "hi", kind: "exec", command: "printf hi" }] }); + expect(r.status).toBe("ok"); + expect(r.steps.map((s) => s.id).sort()).toEqual(["hi@q-a", "hi@q-b"]); + await expect(tk.handlers.run_batch({ layer: "zz-*", steps: [{ id: "s", kind: "exec", command: "x" }] })) + .rejects.toThrow(/未匹配任何已注册层/); + } finally { + await Promise.all([...stack.layers.keys()].map((n) => stack.removeLayer(n, { destroy: true }))); + } + }, 30_000); +}); diff --git a/tests/batch.test.ts b/tests/batch.test.ts index 39a1ad6..0f1a80e 100644 --- a/tests/batch.test.ts +++ b/tests/batch.test.ts @@ -2,12 +2,12 @@ * 批次组合(runBatch)测试——local driver 真跑: * DAG 依赖边 / fail-fast / 多 hunk 原子 / expectExit / 计划校验 / CLI 冒烟 */ -import { describe, expect, test } from "bun:test"; +import { afterAll, describe, expect, test } from "bun:test"; import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { LocalRuntimeDriver } from "../src/local-driver.js"; -import { runBatch, editFileMulti, type RuntimeDriver } from "../src/index.js"; +import { runBatch, expandBatchLayerWildcards, expandLayerPattern, hasLayerWildcard, editFileMulti, type RuntimeDriver, type BatchPlan } from "../src/index.js"; import { createAgentToolkit } from "../src/agent-toolkit.js"; import { RuntimeStack } from "../src/runtime-stack.js"; @@ -185,7 +185,8 @@ 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", windowsHide: true }); + // --no-daemon:测试不取决于机器上是否有真实 Daemon 在跑(否则会连上去执行) + const out = execSync(`bun bin/filaxis.ts batch --no-daemon --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 +201,7 @@ describe("toolkit run_batch + CLI batch 冒烟", () => { })); let errOut = ""; try { - execSync(`bun bin/filaxis.ts batch --request-file "${plan2}"`, { encoding: "utf-8", stdio: "pipe", windowsHide: true }); + execSync(`bun bin/filaxis.ts batch --no-daemon --request-file "${plan2}"`, { encoding: "utf-8", stdio: "pipe", windowsHide: true }); } catch (e) { errOut = String((e as { stdout?: string }).stdout ?? ""); } @@ -219,6 +220,19 @@ test("空 steps → 显式拒绝(内核级守卫,不再只靠 CLI)", async await expect(runBatch(drv, {} as never)).rejects.toThrow(/steps 需非空/); }); +// DSH 真机巡检踩中(2026-11-26):`layers` 与 `layer` 一字之差被静默忽略,计划落回 +// 默认层在调用方本机执行——「想扫集群、结果扫了自己」。拼错的顶层字段必须当场拒绝。 +test("未知顶层字段 → 显式拒绝(layers≠layer 案)", async () => { + const drv = new LocalRuntimeDriver(); + await expect(runBatch(drv, { layers: "q-*", steps: [{ id: "x", kind: "exec", command: "hostname" }] } as never)) + .rejects.toThrow(/未知顶层字段 'layers'/); + await expect(runBatch(drv, { steps: [{ id: "x", kind: "exec", command: "true" }], layerr: 1 } as never)) + .rejects.toThrow(/未知顶层字段 'layerr'/); + // 合法四字段不受影响 + const r = await runBatch(drv, { steps: [{ id: "ok", kind: "exec", command: "true" }], layer: undefined, stopOnFail: false, maxParallel: 1 }); + expect(r.steps[0]!.status).toBe("ok"); +}); + describe("runBatch layer 数组扇出", () => { function makeMockResolver( execImpl: (layer: string, command: string) => Promise<{ stdout: string; stderr: string; exitCode: number }>, @@ -454,3 +468,325 @@ describe("runBatch layer 数组扇出", () => { expect(calls).toHaveLength(0); }); }); + +// --------------------------------------------------------------------------- +// DSH + GLM-5.4 使用评估(2026-11-26)反馈 #6:exec 步骤 commandFile 与层通配 +// --------------------------------------------------------------------------- +describe("runBatch:commandFile(DSH 评估 2026-11-26 #6)", () => { + // 自建临时目录:文件顶层的 dir 会被前面的用例在收尾时删掉 + const cfDir = mkdtempSync(join(tmpdir(), "fx-batch-cf-")); + test("脚本文件内联为命令:引号/$()/多行原样送达,BOM 与 CRLF 归一", async () => { + const drv = new LocalRuntimeDriver(); + const f = join(cfDir, "snap.sh"); + // 模拟 Windows 编辑器产物:UTF-8 BOM + CRLF 行尾(\r 到 bash 里会被当成命令名的一部分) + const body = [ + "echo \"## $(hostname) load=$(cut -d' ' -f1-3 /proc/loadavg 2>/dev/null || echo n/a)\"", + "printf '%s\\n' \"it's\" 'a \"quoted\" word'", + ].join("\r\n"); + writeFileSync(f, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(body, "utf-8")])); + const r = await runBatch(drv, { steps: [{ id: "snap", kind: "exec", commandFile: f }] }); + expect(r.status).toBe("ok"); + expect(r.steps[0]!.stdout).toContain("## "); + expect(r.steps[0]!.stdout).toContain("it's"); + expect(r.steps[0]!.stdout).toContain('a "quoted" word'); + }, 30_000); + + test("校验阶段拒绝(零副作用):互斥 / 文件缺失 / 空文件 / 缺命令;且不改写调用方计划", async () => { + const seen: string[] = []; + const drv = { + descriptor: { driver: "fake" }, + exec: async (c: string) => { seen.push(c); return { stdout: "", stderr: "", exitCode: 0 }; }, + } as unknown as RuntimeDriver; + const good = join(cfDir, "good.sh"); + writeFileSync(good, "echo ok\n"); + const empty = join(cfDir, "empty.sh"); + writeFileSync(empty, " \n\t\n"); + const cases: Array<[BatchPlan, RegExp]> = [ + [{ steps: [{ id: "s", kind: "exec", command: "echo a", commandFile: good }] }, /互斥/], + [{ steps: [{ id: "s", kind: "exec", commandFile: join(cfDir, "absent.sh") }] }, /读取失败/], + [{ steps: [{ id: "s", kind: "exec", commandFile: empty }] }, /内容为空/], + [{ steps: [{ id: "s", kind: "exec" }] }, /缺 command/], + [{ steps: [{ id: "s", kind: "exec", commandFile: " " }] }, /需为非空字符串路径/], + ]; + for (const [plan, re] of cases) { + await expect(runBatch(drv, plan)).rejects.toThrow(re); + } + expect(seen).toEqual([]); // 五种非法计划一步都没执行 + // 解析结果只进内部展开副本——调用方的计划对象不被改写 + const plan: BatchPlan = { steps: [{ id: "s", kind: "exec", commandFile: good }] }; + const r = await runBatch(drv, plan); + expect(r.status).toBe("ok"); + expect(seen).toEqual(["echo ok\n"]); + expect((plan.steps[0] as { command?: string }).command).toBeUndefined(); + }, 30_000); +}); + +describe("层通配展开(DSH 评估 2026-11-26 #6)", () => { + const known = ["m", "q-0-6", "q-0-9", "q-4-5", "q-4-8", "db.prod"]; + + test("expandLayerPattern:* 与 ?;点号是字面;精确名优先;无通配原样", () => { + expect(expandLayerPattern("q-*", known)).toEqual(["q-0-6", "q-0-9", "q-4-5", "q-4-8"]); // 保持已知层名的顺序 + expect(expandLayerPattern("q-?-6", known)).toEqual(["q-0-6"]); + expect(expandLayerPattern("db.*", ["db.prod", "dbXprod"])).toEqual(["db.prod"]); // . 不是任意字符 + expect(expandLayerPattern("db.prod", known)).toEqual(["db.prod"]); + expect(expandLayerPattern("a*b", ["a*b", "axb"])).toEqual(["a*b"]); // 层名本身含 * 也不会被当模式 + expect(expandLayerPattern("nope", known)).toEqual(["nope"]); // 无通配:原样交回(由层解析函数裁决存不存在) + expect(expandLayerPattern("q-z*", known)).toEqual([]); + expect(hasLayerWildcard("q-*")).toBe(true); + expect(hasLayerWildcard("q-?-6")).toBe(true); + expect(hasLayerWildcard("m")).toBe(false); + }); + + test("expandBatchLayerWildcards:顶层与步骤层都展开;无匹配整批拒绝;无通配原引用", () => { + const base: BatchPlan = { + layer: "q-*", + steps: [ + { id: "snap", kind: "exec", command: "echo x" }, + { id: "one", kind: "exec", command: "echo y", layer: "q-4-*" }, + { id: "mix", kind: "exec", command: "echo z", layer: ["q-4-5", "q-4-8", "m", "q-4-*"] }, + { id: "any", kind: "exec", command: "echo w", layer: "*" }, + ], + }; + const out = expandBatchLayerWildcards(base, known); + expect(out.layer).toEqual(["q-0-6", "q-0-9", "q-4-5", "q-4-8"]); + expect(out.steps[0]!.layer).toBeUndefined(); // 未覆盖层:继承顶层展开 + expect(out.steps[1]!.layer).toEqual(["q-4-5", "q-4-8"]); + expect(out.steps[2]!.layer).toEqual(["q-4-5", "q-4-8", "m"]); // 数组去重,保持首次出现的位置 + expect(out.steps[3]!.layer).toEqual(known); + // 调用方的计划不被改写 + expect(base.layer).toBe("q-*"); + expect(base.steps[1]!.layer).toBe("q-4-*"); + // 无匹配:把 "zz-*" 原样交下去会被当成一个不存在的层名——必须在入口拒绝 + expect(() => expandBatchLayerWildcards({ steps: [{ id: "s", kind: "exec", command: "x", layer: "zz-*" }] }, known)) + .toThrow(/步骤 's' 的 layer 的层通配 'zz-\*' 未匹配任何已存层/); + expect(() => expandBatchLayerWildcards({ layer: "zz-*", steps: [{ id: "s", kind: "exec", command: "x" }] }, known, "已注册层")) + .toThrow(/计划 layer 的层通配 'zz-\*' 未匹配任何已注册层/); + const plain: BatchPlan = { layer: ["m", "nope"], steps: [{ id: "s", kind: "exec", command: "x", layer: ["q-4-5", "m"] }] }; + expect(expandBatchLayerWildcards(plain, known)).toBe(plain); // 不含通配:同一对象引用 + }); + + test("展开结果交给 runBatch:按名解析到各层并行执行(id@layer)", async () => { + const plan = expandBatchLayerWildcards({ layer: "q-*", steps: [{ id: "snap", kind: "exec", command: "echo hi" }] }, ["q-0-6", "q-4-5"]); + const names: string[] = []; + const drivers: LocalRuntimeDriver[] = []; + const r = await runBatch(async (name) => { + names.push(name!); + const d = new LocalRuntimeDriver(); + drivers.push(d); + return d; + }, plan); + await Promise.all(drivers.map((d) => d.destroy())); + expect(r.status).toBe("ok"); + expect(r.steps.map((s) => s.id).sort()).toEqual(["snap@q-0-6", "snap@q-4-5"]); + expect(names.sort()).toEqual(["q-0-6", "q-4-5"]); + }, 30_000); +}); + +// --------------------------------------------------------------------------- +// CLI batch(DSH 评估 2026-11-26 #6):开关 / 层通配 / commandFile +// --------------------------------------------------------------------------- +describe("CLI batch:开关 / 层通配 / commandFile(DSH 评估 2026-11-26 #6)", () => { + const cliDir = mkdtempSync(join(tmpdir(), "fx-batch-cli-")); + const fwd = (p: string) => p.replace(/\\/g, "/"); + const layerStore = fwd(join(cliDir, "layers.json")); + writeFileSync(layerStore, JSON.stringify({ + "fx-a": { driver: "local" }, "fx-b": { driver: "local" }, "fx-c": { driver: "local" }, "keep": { driver: "local" }, + })); + const cli = (args: string[], plan: unknown) => { + const r = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "batch", "--no-daemon", ...args, "--stdin-json"], { + stdin: Buffer.from(JSON.stringify(plan)), + stdout: "pipe", stderr: "pipe", windowsHide: true, + env: { ...process.env, FILAXIS_LAYERS: layerStore }, // 层文件隔离:不碰 ~/.filaxis/layers.json + }); + return { out: r.stdout.toString(), err: r.stderr.toString(), code: r.exitCode }; + }; + const snap = { steps: [{ id: "hi", kind: "exec", command: "printf x" }] }; + + test("--layer 通配与计划内通配:按已存层名展开为 hi@<层>;未命中的层不执行", () => { + const byFlag = cli(["--layer", "fx-*"], snap); + expect(byFlag.code).toBe(0); + for (const l of ["fx-a", "fx-b", "fx-c"]) expect(byFlag.out).toContain(`[ok] hi@${l} (exec`); + expect(byFlag.out).not.toContain("hi@keep"); + expect(byFlag.out).not.toContain("[ok] hi (exec"); // 不再在默认层(本机)多跑一遍 + const byPlan = cli([], { ...snap, layer: "fx-?" }); + expect(byPlan.code).toBe(0); + expect(byPlan.out).toContain("[ok] hi@fx-b (exec"); + expect(byPlan.out).not.toContain("hi@keep"); + }, 60_000); + + test("通配无匹配:整批拒绝、零输出(不把 'zz-*' 当层名、更不落到默认层执行)", () => { + const r = cli(["--layer", "zz-*"], snap); + expect(r.code).toBe(1); + expect(r.out).toBe(""); + expect(r.err).toContain("未匹配任何已存层"); + }, 30_000); + + test("CLI batch keeps plan validation errors after wildcard support", () => { + for (const [plan, message] of [ + [{ layer: "*", steps: {} }, "steps"], + [{ ...snap, layer: 123 }, "需为非空字符串"], + [{ ...snap, layer: ["fx-a", "fx-a"] }, "含重复层名"], + [{ ...snap, layer: ["fx-*", "fx-*"] }, "含重复层名"], + [{ steps: [{ id: "read", kind: "read", path: "x", commandFile: "a.sh" }] }, "只支持 kind='exec'"], + ] as const) { + const r = cli([], plan); + expect(r.code).toBe(1); + expect(r.out).toBe(""); + expect(r.err).toContain(message); + expect(r.err).toContain("批次计划非法"); + } + }, 30_000); + + test("--no-stop-on-fail:失败后其余步骤照看(缺省失败即停时标 skipped);--max-parallel 1 保序", () => { + const plan = { steps: [{ id: "boom", kind: "exec", command: "exit 7" }, { id: "rest", kind: "exec", command: "printf SURVIVED" }] }; + const fastFail = cli(["--max-parallel", "1"], plan); + expect(fastFail.code).toBe(1); + expect(fastFail.out).toContain("[fail] boom (exec"); + expect(fastFail.out).toContain("[skipped] rest"); + expect(fastFail.out).not.toContain("SURVIVED"); // 缺省:一台失败,其余都不看 + const inspect = cli(["--max-parallel", "1", "--no-stop-on-fail"], plan); + expect(inspect.code).toBe(1); // 有失败步骤,批次整体仍报 fail + expect(inspect.out).toContain("[fail] boom (exec"); + expect(inspect.out).toContain("[ok] rest (exec"); + expect(inspect.out).toContain("SURVIVED"); + }, 60_000); + + test("命令行开关覆盖计划里的 stopOnFail / maxParallel", () => { + // 可观测的执行顺序与副作用:boom 睡 0.4s 后才写文件再失败;rest 立即写。 + // 计划里写的是「失败即停 + 并行度 8」(rest 会抢在 boom 前面落笔)——命令行 + // --max-parallel 1 --no-stop-on-fail 必须盖过它:rest 照看,且排在 boom 之后 + const order = fwd(join(cliDir, "order.txt")); + const plan = { + stopOnFail: true, maxParallel: 8, + steps: [ + { id: "boom", kind: "exec", command: `sleep 0.4; printf boom >> ${order}; exit 7` }, + { id: "rest", kind: "exec", command: `printf rest >> ${order}` }, + ], + }; + const overridden = cli(["--max-parallel", "1", "--no-stop-on-fail"], plan); + expect(overridden.out).toContain("[ok] rest (exec"); // --no-stop-on-fail 胜出:其余步骤照看 + expect(readFileSync(order, "utf-8")).toBe("boomrest"); // --max-parallel 1 胜出:rest 在 boom 之后 + rmSync(order, { force: true }); + // 对照:不给开关,计划里的并行度 8 生效——rest 抢先落笔 + const asPlanned = cli([], plan); + expect(readFileSync(order, "utf-8").startsWith("rest")).toBe(true); + }, 60_000); + + test("--max-parallel 参数校验:0 与非数字拒绝;负数/缺值按 batch 参数规则拒绝;一律零输出", () => { + for (const bad of ["0", "abc"]) { + const r = cli(["--max-parallel", bad], snap); + expect(r.code).toBe(1); + expect(r.out).toBe(""); + expect(r.err).toContain("--max-parallel 需要一个正数字"); + } + // 以 - 开头的值被 batch 的参数预检当成下一个选项(既有规则) + const negative = cli(["--max-parallel", "-1"], snap); + expect(negative.code).toBe(1); + expect(negative.out).toBe(""); + expect(negative.err).toContain("--max-parallel 需要参数值"); + const missing = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "batch", "--no-daemon", "--stdin-json", "--max-parallel"], { + stdin: Buffer.from(JSON.stringify(snap)), stdout: "pipe", stderr: "pipe", windowsHide: true, + env: { ...process.env, FILAXIS_LAYERS: layerStore }, + }); + expect(missing.exitCode).toBe(1); + expect(missing.stdout.toString()).toBe(""); + expect(missing.stderr.toString()).toContain("--max-parallel 需要参数值"); + }, 60_000); + + test("commandFile:exec 步骤引用脚本文件(相对路径按调用方工作目录;引号/$()/多行零转义)", () => { + const script = fwd(join(cliDir, "snap.sh")); + writeFileSync(script, "echo \"## $(hostname)\"\nprintf '%s\\n' \"it's\" 'a \"quoted\" word'\n"); + const abs = cli([], { steps: [{ id: "cf", kind: "exec", commandFile: script }] }); + expect(abs.code).toBe(0); + expect(abs.out).toContain("[ok] cf (exec"); + expect(abs.out).toContain("## "); + expect(abs.out).toContain('a "quoted" word'); + // 相对路径:相对 CLI 进程的工作目录(CLI 入口用绝对路径,工作目录切到临时目录) + const rel = Bun.spawnSync([process.execPath, fwd(join(process.cwd(), "bin/filaxis.ts")), "batch", "--no-daemon", "--stdin-json"], { + cwd: cliDir, + stdin: Buffer.from(JSON.stringify({ steps: [{ id: "cf", kind: "exec", commandFile: "snap.sh" }] })), + stdout: "pipe", stderr: "pipe", windowsHide: true, + env: { ...process.env, FILAXIS_LAYERS: layerStore }, + }); + expect(rel.exitCode).toBe(0); + expect(rel.stdout.toString()).toContain("it's"); + // 读不出:整批拒绝、零输出 + const absent = cli([], { steps: [{ id: "cf", kind: "exec", commandFile: fwd(join(cliDir, "absent.sh")) }] }); + expect(absent.code).toBe(1); + expect(absent.out).toBe(""); + expect(absent.err).toContain("commandFile 读取失败"); + }, 60_000); + + afterAll(() => { + rmSync(cliDir, { recursive: true, force: true }); + }); +}); + +// --------------------------------------------------------------------------- +// CLI exec 输出(DSH 评估 2026-11-26 #5c):完成标记原先紧跟 stdout 写入就发 stderr +// --------------------------------------------------------------------------- +describe("CLI exec 输出(DSH 评估 2026-11-26 #5c)", () => { + test("--json:单行结构化结果——退出码/用户/两路输出分字段,进程退出码照常透传", async () => { + const { userInfo } = await import("node:os"); + const r = Bun.spawnSync( + [process.execPath, "bin/filaxis.ts", "exec", "--no-daemon", "--json", "--", "printf 'a\\nb\\n'; printf 'e' >&2; exit 3"], + { stdout: "pipe", stderr: "pipe", windowsHide: true }, + ); + expect(r.stderr.toString()).toBe(""); // 不再往 stderr 写「[exit=N user=…]」标记行 + expect(r.stdout.toString().trimEnd().split("\n")).toHaveLength(1); // 单行 + const parsed = JSON.parse(r.stdout.toString()) as { exitCode: number; effectiveUser: unknown; stdout: string; stderr: string }; + expect(parsed.exitCode).toBe(3); + expect(parsed.stdout).toBe("a\nb\n"); + expect(parsed.stderr).toBe("e"); + expect(parsed.effectiveUser).toBe(userInfo().username); // 本地层:执行用户=本机登录用户 + expect(r.exitCode).toBe(3); + }, 30_000); + + const sh = process.env.FILAXIS_SHELL || Bun.which("sh"); + test.skipIf(!sh)("文本模式经 2>&1 合流:完成标记恒在末尾,正文一行不少", () => { + const n = 20000; + // 经 sh 合流(与调用方写 `filaxis … 2>&1` 同形)。大输出下 stdout 是异步排队—— + // 标记若不等它排空就发 stderr,合流后就会插进正文中间 + const command = `i=1; while [ "$i" -le ${n} ]; do echo "$i"; i=$((i + 1)); done`; + const r = Bun.spawnSync([sh!, "-c", `${JSON.stringify(process.execPath)} bin/filaxis.ts exec --no-daemon -- '${command}' 2>&1`], { + stdout: "pipe", stderr: "pipe", windowsHide: true, + }); + const lines = r.stdout.toString().split(/\r?\n/); + const markerIdx = lines.findIndex((l) => /^\[exit=0 user=/.test(l)); + expect(markerIdx).toBeGreaterThan(n); // 标记在全部正文之后 + expect(lines.slice(markerIdx + 1).join("")).toBe(""); // 标记之后没有任何正文 + expect(lines[0]).toBe("1"); + expect(lines[n - 1]).toBe(String(n)); + expect(r.exitCode).toBe(0); + }, 60_000); +}); + +// --------------------------------------------------------------------------- +// CLI 已存层分派(DSH 评估 2026-11-26 排查中顺带发现):一次性模式曾把任何已存层 +// 无条件包成 SSH 驱动——driver:"local" 的条目变成对空主机名的 ssh 连接 +// --------------------------------------------------------------------------- +describe("CLI 已存层分派(一次性模式)", () => { + test("按 descriptor 的 driver 分派:local 层本地执行;不认识的 driver 明确报错——不再一律当 SSH", () => { + const d = mkdtempSync(join(tmpdir(), "fx-batch-saved-")); + const store = join(d, "layers.json"); + writeFileSync(store, JSON.stringify({ loc: { driver: "local" }, odd: { driver: "tmux" } })); + const run = (layer: string) => Bun.spawnSync([process.execPath, "bin/filaxis.ts", "exec", "--no-daemon", "--layer", layer, "--", "printf LOCAL_OK"], { + stdout: "pipe", stderr: "pipe", windowsHide: true, + env: { ...process.env, FILAXIS_LAYERS: store }, // 层文件隔离 + }); + try { + const local = run("loc"); + expect(local.stdout.toString()).toContain("LOCAL_OK"); + expect(local.exitCode).toBe(0); + // 修前:new SshPtyDriver({driver:"local"}) → ssh 连空主机名(落到 localhost 的 sshd) + expect(local.stderr.toString()).not.toContain("Permission denied"); + const odd = run("odd"); + expect(odd.exitCode).toBe(1); + expect(odd.stdout.toString()).toBe(""); + expect(odd.stderr.toString()).toContain("一次性模式"); + expect(odd.stderr.toString()).not.toContain("Permission denied"); + } finally { + rmSync(d, { recursive: true, force: true }); + } + }, 30_000); +}); diff --git a/tests/cli-help.test.ts b/tests/cli-help.test.ts index ec9c6ab..cc0ee81 100644 --- a/tests/cli-help.test.ts +++ b/tests/cli-help.test.ts @@ -80,7 +80,9 @@ test.each([ }); test("CLI treats --help after -- as command data", () => { - const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "exec", "--", "printf '%s' --help"], { stderr: "pipe", windowsHide: true }); + // --no-daemon:否则会探到机器上正在跑的真实 Daemon 并经它执行 + // 预算 30s:全量并发下 spawnSync(bun CLI) 在 Windows 本机实测会超缺省 5s(轻载 ~1.2s) + const result = Bun.spawnSync([process.execPath, "bin/filaxis.ts", "exec", "--no-daemon", "--", "printf '%s' --help"], { stderr: "pipe", windowsHide: true, timeout: 30000 }); expect(result.exitCode).toBe(0); expect(result.stdout.toString()).toBe("--help"); -}); +}, 45000); // 比子进程超时宽 15s:超时要以断言失败呈现,不是用例自身超时 diff --git a/tests/daemon.test.ts b/tests/daemon.test.ts index 13496c8..735080f 100644 --- a/tests/daemon.test.ts +++ b/tests/daemon.test.ts @@ -396,7 +396,8 @@ describe("DaemonServer & DaemonClient RPC", () => { 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" }); + // CLI --json 对外为 snake_case(forward_id 为主名;forwardId 保留为兼容别名) + expect(JSON.parse(removed.stdout)).toEqual({ forward_id: "fwd-id", forwardId: "fwd-id", status: "unknown", detail: "fixture unverified" }); } finally { await srv.stop(); rmSync(dir, { recursive: true, force: true }); @@ -634,13 +635,13 @@ describe("CLI daemon / forward / stream E2E", () => { 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 infoL = JSON.parse(okL.stdout) as { kind: string; bind_port: number; target_host: string; target_port: number }; + expect(infoL).toMatchObject({ forward_id: expect.any(String), kind: "local", bind_port: 54321, target_host: "127.0.0.1", target_port: 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 infoD = JSON.parse(okD.stdout) as { kind: string; bind_port: number }; + expect(infoD).toMatchObject({ kind: "dynamic", bind_port: 54321 }); const badD = await runCliAsync(["forward", "add", "--layer", "prod", "-D", "-1"], dir); expect(badD.exitCode).toBe(1); @@ -1121,3 +1122,51 @@ describe("CLI daemon / forward / stream E2E", () => { expect(() => parseAddrToUrl("[::1]")).toThrow(/非法 Daemon 监听地址/); }); }); + +// --------------------------------------------------------------------------- +// DSH + GLM-5.4 使用评估(2026-11-26)#5a/#5b:forward list +// --------------------------------------------------------------------------- +describe("CLI forward list(DSH 评估 2026-11-26 #5a/#5b)", () => { + test("默认只报在用的转发;--all 连已停止的一并列出;--json 为 snake_case 且带 forwardId 兼容别名", async () => { + const dir = makeTempDir("fx-daemon-forward-list-"); + const srv = new DaemonServer({ daemonDir: dir }); + try { + await srv.start(); + const driver = new SshPtyDriver({ driver: "ssh", target: "fixture.invalid" }); + const info = (forwardId: string, status: "active" | "stopped" | "exited" | "unknown") => ({ + forwardId, kind: "local" as const, bindAddr: "127.0.0.1", bindPort: 43210, transportMode: "subprocess" as const, status, createdAt: 1, + }); + // remove 之后条目以 stopped 留在表里(给 closeForward 做幂等判定)——列表查询不该再报它 + driver.listForwards = () => [info("live", "active"), info("gone", "stopped"), info("dead", "exited"), info("unsure", "unknown")]; + await srv.stack.addLayer("fixture", driver); + + const plain = await runCliAsync(["forward", "list", "--layer", "fixture"], dir); + expect(plain.exitCode).toBe(0); + expect(plain.stdout).toContain("live |"); + expect(plain.stdout).toContain("unsure |"); // 终止未确认:不能当已停隐藏 + expect(plain.stdout).not.toContain("gone |"); // 修前:remove 过的照样列出,与「无活跃转发」文案自相矛盾 + expect(plain.stdout).not.toContain("dead |"); + + const all = await runCliAsync(["forward", "list", "--layer", "fixture", "--all"], dir); + expect(all.exitCode).toBe(0); + for (const id of ["live |", "unsure |", "gone |", "dead |"]) expect(all.stdout).toContain(id); + + const json = await runCliAsync(["forward", "list", "--layer", "fixture", "--json"], dir); + const parsed = JSON.parse(json.stdout) as Array>; + expect(parsed.map((f) => f.forward_id)).toEqual(["live", "unsure"]); + expect(parsed[0]).toMatchObject({ + forward_id: "live", forwardId: "live", kind: "local", bind_addr: "127.0.0.1", bind_port: 43210, + transport_mode: "subprocess", status: "active", created_at: 1, + }); + // 记录里除兼容别名外不再有驼峰键(与参数 forward_id、观察窗 window_id 同一命名风格) + expect(Object.keys(parsed[0]!).filter((k) => /[a-z][A-Z]/.test(k) && k !== "forwardId")).toEqual([]); + + const allJson = await runCliAsync(["forward", "list", "--layer", "fixture", "--all", "--json"], dir); + const allParsed = JSON.parse(allJson.stdout) as Array<{ forward_id: string }>; + expect(allParsed.map((f) => f.forward_id)).toEqual(["live", "gone", "dead", "unsure"]); + } finally { + await srv.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); // 本机实测 ~25s(起停 Daemon + 三次 CLI) +}); diff --git a/tests/file-edit.test.ts b/tests/file-edit.test.ts index 597a29f..d030185 100644 --- a/tests/file-edit.test.ts +++ b/tests/file-edit.test.ts @@ -489,13 +489,13 @@ describe("CLI 冒烟(bun bin/filaxis.ts)", () => { // --layer 与 --host 互斥 let err1 = ""; try { - execSync('bun bin/filaxis.ts exec --layer nginx --host x -- "echo 1"', { encoding: "utf-8", env, stdio: "pipe", windowsHide: true }); + execSync('bun bin/filaxis.ts exec --no-daemon --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", windowsHide: true }); + execSync('bun bin/filaxis.ts exec --no-daemon --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 后清单空 diff --git a/tests/mcp-proxy.test.ts b/tests/mcp-proxy.test.ts index f6a2c76..aae72ac 100644 --- a/tests/mcp-proxy.test.ts +++ b/tests/mcp-proxy.test.ts @@ -5,10 +5,11 @@ 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 { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import * as http from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { createInterface } from "node:readline"; import { PassThrough } from "node:stream"; import { createAgentToolkit, @@ -108,25 +109,31 @@ describe("manage_layers dynamic forwarding & 12-tool surface", () => { 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()) + // 结果记录为 snake_case(forward_id 主名;forwardId 仅兼容别名)——与参数命名一致 + expect((await manage_layers({ action: "forward_list" })).forwards.map((f) => f.forward_id).sort()) .toEqual(["injected", "named"]); stack.setActive("named"); - expect((await manage_layers({ action: "forward_list" })).forwards.map((f) => f.forwardId).sort()) + expect((await manage_layers({ action: "forward_list" })).forwards.map((f) => f.forward_id).sort()) .toEqual(["injected", "named"]); - expect((await manage_layers({ action: "forward_list", layer: "named" })).forwards.map((f) => f.forwardId)) + expect((await manage_layers({ action: "forward_list", layer: "named" })).forwards.map((f) => f.forward_id)) .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 })) + await expect(manage_layers({ action: "forward_remove", forward_id: opened.forward.forward_id })) .resolves.toMatchObject({ status: "stopped" }); - expect(named.listForwards()).toMatchObject([{ forwardId: "named", status: "active" }]); + expect(named.listForwards()).toMatchObject([{ forwardId: "named", status: "active" }]); // SDK 类型保持驼峰 + // forward_list 缺省只报仍在用的转发:刚 remove 的 "injected"(stopped 墓碑)不再出现; + // include_closed=true 才连墓碑一并返回 + expect((await manage_layers({ action: "forward_list" })).forwards.map((f) => f.forward_id)).toEqual(["named"]); + expect((await manage_layers({ action: "forward_list", include_closed: true })).forwards.map((f) => f.forward_id).sort()) + .toEqual(["injected", "named"]); 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"]); + expect(remaining.forwards.map((f) => f.forward_id).sort()).toEqual(["named", "unregistered"]); await expect(manage_layers({ action: "forward_remove", forward_id: "unregistered" })) .resolves.toMatchObject({ status: "stopped" }); } finally { @@ -215,17 +222,21 @@ describe("manage_layers dynamic forwarding & 12-tool surface", () => { expect(added.structuredContent).toMatchObject({ action: "forward_add", forward: { - forwardId: "mcp-r1", + forward_id: "mcp-r1", layer: "ssh-main", kind: "remote", - bindPort: 45123, + bind_port: 45123, status: "active", }, }); + // 别名与主名同值(兼容期);record 的其余字段也是 snake_case + const addedForward = (added.structuredContent as { forward: Record }).forward; + expect(addedForward.forwardId).toBe("mcp-r1"); + expect(Object.keys(addedForward).some((k) => /[a-z][A-Z]/.test(k) && k !== "forwardId")).toBe(false); 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)) + expect((listed.structuredContent as { forwards: Array<{ forward_id: string }> }).forwards.map((f) => f.forward_id)) .toEqual(["mcp-r1"]); const removed = await call(5, { action: "forward_remove", forward_id: "mcp-r1" }); @@ -331,7 +342,7 @@ describe("DaemonServer MCP HTTP/SSE & McpStdioProxy", () => { 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)) + expect((fwdListResp.result as { structuredContent: { forwards: Array<{ forward_id: string }> } }).structuredContent.forwards.map((f) => f.forward_id)) .toEqual(["cli-fwd"]); p2.send({ @@ -610,6 +621,46 @@ describe("DaemonServer MCP HTTP/SSE & McpStdioProxy", () => { } }, 15_000); + test("filaxis-mcp --layer honors the saved target while a daemon is running", async () => { + const dir = makeTempDir("fx-mcp-bin-layer-"); + const srv = new DaemonServer({ daemonDir: dir }); + let child: ChildProcess | undefined; + try { + await srv.start(); + const store = join(dir, "layers.json"); + const records = Object.fromEntries(["first", "second"].map((name) => { + const cwd = join(dir, name); + mkdirSync(cwd); + writeFileSync(join(cwd, "marker.txt"), name); + return [name, { driver: "local", cwd }]; + })); + writeFileSync(store, JSON.stringify(records)); + const proc = spawn(process.execPath, ["bin/filaxis-mcp.ts", "--daemon-dir", dir, "--layer", "first"], { + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, FILAXIS_LAYERS: store, FILAXIS_NO_DAEMON: "0" }, + windowsHide: true, + }); + child = proc; + const responses: Array> = []; + createInterface({ input: proc.stdout }).on("line", (line) => responses.push(JSON.parse(line))); + for (const [id, layer, marker] of [[1, undefined, "first"], [2, "second", "second"]] as const) { + proc.stdin.write(JSON.stringify({ + jsonrpc: "2.0", id, method: "tools/call", + params: { name: "read_path", arguments: { path: "marker.txt", layer } }, + }) + "\n"); + expect((await waitForResponse(responses, id)).result).toMatchObject({ + content: [{ type: "text", text: expect.stringContaining(marker) }], + }); + } + proc.stdin.end(); + expect(await new Promise((resolve) => proc.once("close", resolve))).toBe(0); + } finally { + if (child?.exitCode === null) child.kill("SIGTERM"); + await srv.stop(); + 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" }); diff --git a/tests/mcp-server.test.ts b/tests/mcp-server.test.ts index 065b3bd..f8c3421 100644 --- a/tests/mcp-server.test.ts +++ b/tests/mcp-server.test.ts @@ -153,7 +153,9 @@ describe("MCP Server(REQ-0003)", () => { await Promise.all([...stack.layers.keys()].map((name) => stack.removeLayer(name, { destroy: true }))); rmSync(dir, { recursive: true, force: true }); } - }); + // 预算补齐:二十余次本地驱动调用,每次起子进程——Windows 上实测 ~5.6s 撞 bun 缺省 5s + //(v0.2.12 基线在本机即超时,与被测行为无关) + }, 45_000); test("transfer_file puts and gets bytes on the selected layer and report verification", async () => { const dir = mkdtempSync(join(tmpdir(), "fx-mcp-transfer-")); @@ -263,8 +265,8 @@ describe("MCP Server(REQ-0003)", () => { structuredContent: { status: "ok", steps: [{ layer: "first", stdout: "from first" }, { layer: "second", stdout: "from second" }] }, }); expect(calls).toEqual(["first:one", "second:two"]); - steps[1]!.layer = "missing"; - f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "run_batch", arguments: { layer: "first", steps } } }); + const missingLayerSteps = [steps[0], { ...steps[1], layer: "missing" }]; + f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "run_batch", arguments: { layer: "first", steps: missingLayerSteps } } }); expect((await waitId(f, 2)).result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("missing") }] }); expect(calls).toHaveLength(2); const typo = { id: "typo", kind: "exec", command: "no", layre: "second" }; diff --git a/tests/ssh-forward.test.ts b/tests/ssh-forward.test.ts index 995ef9e..6d004a8 100644 --- a/tests/ssh-forward.test.ts +++ b/tests/ssh-forward.test.ts @@ -628,14 +628,51 @@ describe("enterPipeline layer-penetrating dynamic forwarding (stdio-bridge)", () ], 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'"); + // ssh 跳的 `sh -c <内层>` 必须整体再包一层引号(嵌套 ssh 会把参数按空格 + // 拼接,单层引号在跳板 sh 就被消费掉) + expect(nested.command).toContain("'ssh' '-T' 'vm-b' 'sh -c"); expect(nested.command).toContain("socat"); } + const quoted = renderEnterBridgeCommand([{ cmd: "ssh -tt -i '/tmp/key -t name' vm-b" }], inner); + expect(quoted).toMatchObject({ kind: "ok", command: expect.stringContaining("'ssh' '-T' '-i' '/tmp/key -t name' 'vm-b'") }); + const bad = renderEnterBridgeCommand([{ cmd: "su - app" }], inner); expect(bad.kind).toBe("unreachable"); }); + test("DSH 真机回归 2026-11-26:ssh 跳的引号层级 = 跳数 + 内层(裸 exec 终结 shell 案)", () => { + // 真机病链:单层引号在跳板 sh 被消费 → 嵌套 ssh 空格拼接 → 目标收到 + // `sh -c exec ...` → dash 的裸 exec 直接退出 shell → python 桥根本没跑, + // 转发 listener 活着但连接即断、零报错。钉住:每多一跳 ssh,内层多一层引号。 + const inner = buildInnerTcpBridgeCmd("python3", "127.0.0.1", 22); + + const oneHop = renderEnterBridgeCommand([{ cmd: "ssh root@10.0.0.12" }], inner); + expect(oneHop.kind).toBe("ok"); + if (oneHop.kind === "ok") { + // 末段是单个引号包裹的 `sh -c <内层>`(引号作为字符保留在参数里) + expect(oneHop.command.startsWith("'ssh' '-T' 'root@10.0.0.12' ")).toBe(true); + expect(oneHop.command).toContain("'sh -c"); + // 内层整体作为嵌套 ssh 的一个参数存在,不是裸拼的 'sh' '-c' + expect(oneHop.command).not.toContain("'sh' '-c'"); + // 双重引号包裹:内层脚本与参数在两层转义后仍存活,且以目标参数收尾 + expect(oneHop.command).toContain("exec python3 -u -c"); + expect(oneHop.command).toContain("127.0.0.1"); + expect(oneHop.command).toMatch(/22'\\'''$/); + } + + const twoHops = renderEnterBridgeCommand([ + { cmd: "ssh jump-a" }, + { cmd: "ssh -t 10.0.0.12" }, + ], inner); + expect(twoHops.kind).toBe("ok"); + if (twoHops.kind === "ok") { + // 两跳:`sh -c ` 出现两次(每跳一层) + expect(twoHops.command.match(/sh -c /g)?.length).toBe(2); + expect(twoHops.command).toContain("'sh -c"); + } + }); + 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", @@ -727,6 +764,49 @@ describe("enterPipeline layer-penetrating dynamic forwarding (stdio-bridge)", () } }, 15_000); + test("真机回归 2026-11-26:桥接子进程未送出数据即退出时,死因(stderr 尾部)挂到转发记录上,不再无声", async () => { + // 真机两次踩中:内层连不上目标端口(ConnectionRefused)/ 桥命令在远端没跑起来, + // stderr 里写得清清楚楚,但产品把它丢弃——外面只看到连接立刻断开、零报错。 + let failToSpawn = false; + const drv = new SshPtyDriver({ + driver: "ssh", + target: "ops@host", + config: { enterPipeline: [{ cmd: "docker exec -it web bash" }] }, + }, { + _forwardDeps: { + spawnBridge: () => { + if (failToSpawn) throw new Error("bridge unavailable"); + return spawn(process.execPath, [ + "-e", + "process.stderr.write('Traceback (most recent call last):\\nConnectionRefusedError: [Errno 111] Connection refused\\n');process.exit(2);", + ], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + }, + }, + }); + drv.exec = async () => ({ stdout: "node\n", stderr: "", exitCode: 0 }); + const info = await drv.openForward({ id: "ctr-dead", kind: "L", targetHost: "127.0.0.1", targetPort: 22 }); + expect(info.transportMode).toBe("stdio-bridge"); + // 连一下触发桥子进程;连接会被关闭 + const connectAndWait = () => new Promise((resolve) => { + const c = net.createConnection({ host: "127.0.0.1", port: info.bindPort }); + c.on("error", () => undefined); + c.once("close", () => resolve()); + c.once("connect", () => c.write("x")); + }); + try { + await connectAndWait(); + await new Promise((r) => setTimeout(r, 300)); + const listed = drv.listForwards().find((f) => f.forwardId === "ctr-dead"); + expect(listed?.lastError).toContain("未送出数据即退出"); + expect(listed?.lastError).toContain("ConnectionRefusedError"); + failToSpawn = true; + await connectAndWait(); + expect(drv.listForwards()[0]?.lastError).toContain("bridge unavailable"); + } finally { + await drv.destroy(); + } + }, 15_000); + test("keeps a disconnected bridge child addressable until its exit is verified", async () => { let spawned!: () => void; let killAttempted!: () => void; diff --git a/tests/ssh-transport.test.ts b/tests/ssh-transport.test.ts index 55f72d0..c192606 100644 --- a/tests/ssh-transport.test.ts +++ b/tests/ssh-transport.test.ts @@ -53,19 +53,19 @@ describe("ssh-helpers", () => { expect(sshArgsFor({ host: "192.0.2.10", conn: { user: "root", port: 2222, jump: "jump", keyFile: "~/id_ed", forwards: [{ kind: "L", port: 8080, target: "localhost:80" }] } })) .toEqual([ // ProxyCommand 等价形态(跳板白名单+sh 引用+策略随主连接——Astra 十一轮 #1/#2) - "-o", `ProxyCommand=ssh -o StrictHostKeyChecking=accept-new -W %h:%p ${proxyHost("jump")}`, + "-o", `ProxyCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -W %h:%p ${proxyHost("jump")}`, "-i", expect.any(String), "-p", "2222", "-L", "8080:localhost:80", "root@192.0.2.10", ]); // 跳板串 [host]:port / host:port / user@[host]:port → 命令行 -p 展开(引用包裹) expect(sshArgsFor({ host: "t", conn: { jump: "[127.0.0.1]:2222" } })[1]) - .toBe(`ProxyCommand=ssh -o StrictHostKeyChecking=accept-new -p 2222 -W %h:%p ${proxyHost("127.0.0.1")}`); + .toBe(`ProxyCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -p 2222 -W %h:%p ${proxyHost("127.0.0.1")}`); expect(sshArgsFor({ host: "t", conn: { jump: "root@h:2222" } })[1]) - .toBe(`ProxyCommand=ssh -o StrictHostKeyChecking=accept-new -p 2222 -W %h:%p ${proxyHost("root@h")}`); + .toBe(`ProxyCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -p 2222 -W %h:%p ${proxyHost("root@h")}`); expect(sshArgsFor({ host: "t", conn: { jump: "u@[198.51.100.9]:2200" } })[1]) - .toBe(`ProxyCommand=ssh -o StrictHostKeyChecking=accept-new -p 2200 -W %h:%p ${proxyHost("u@198.51.100.9")}`); + .toBe(`ProxyCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -p 2200 -W %h:%p ${proxyHost("u@198.51.100.9")}`); // IPv6 字面量 expect(sshArgsFor({ host: "t", conn: { jump: "[::1]:2200" } })[1]) - .toBe(`ProxyCommand=ssh -o StrictHostKeyChecking=accept-new -p 2200 -W %h:%p ${proxyHost("::1")}`); + .toBe(`ProxyCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -p 2200 -W %h:%p ${proxyHost("::1")}`); }); // GPT Astra 十一轮 #1:jump 原文拼入经 shell 执行的 ProxyCommand = 命令注入入口。 @@ -111,7 +111,7 @@ describe("ssh-helpers", () => { hostKeyPolicy: "strict", knownHostsFile: "C:\\SSH data\\known_hosts", } }); - expect(args[1]).toBe('ProxyCommand=ssh -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=\\"C:/SSH data/known_hosts\\"" -i "C:\\SSH data\\id_jump" -W %h:%p jump.example'); + expect(args[1]).toBe('ProxyCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=\\"C:/SSH data/known_hosts\\"" -i "C:\\SSH data\\id_jump" -W %h:%p jump.example'); }); // GPT Astra 十一轮 #3:多跳逗号链显式拒绝(旧 -J 直传时跳板策略裸奔)——指引 sshInto @@ -269,6 +269,11 @@ describe("ssh-helpers", () => { if (r2.kind === "ok") { expect(r2.remoteArgs).toEqual(["ssh", "remote-vm", "-p", "2222", "sh", "-s", "sh", "-s"]); // -tt 剥除 } + const quoted = renderExecChannel([{ cmd: "ssh -t -i '/tmp/key -t name' remote-vm" }], "x", { marker: "M", nonceWrapped: "( x )" }); + expect(quoted).toMatchObject({ + kind: "ok", + remoteArgs: ["ssh", "-i", "'/tmp/key -t name'", "remote-vm", "sh", "-s", "sh", "-s"], + }); }); // 多层 enter(用户实测实锤):旧形态全层塞 argv——第一层 sh -s 吞掉脚本、后续层 @@ -1605,3 +1610,227 @@ describe("Sol 90:PTY 自然退出快速感知", () => { expect(Date.now() - t0).toBeLessThan(3_000); // 修前:ready 不翻 false——干等到 5s 超时 }, 15_000); }); + +// --------------------------------------------------------------------------- +// DSH + GLM-5.4 使用评估(2026-11-26):非交互 BatchMode / 认证诊断 / mux 哈希锚点 +// --------------------------------------------------------------------------- +describe("DSH 评估 2026-11-26:ssh 自主化选项与认证诊断", () => { + /** [-o, 值, -o, 值…] → ["-o 值", …] */ + const pairs = (opts: string[]) => opts.filter((_, i) => i % 2 === 0).map((k, j) => `${k} ${opts[j * 2 + 1]}`); + + test("非交互子进程缺省 BatchMode=yes;PTY 登录链(root attach / hop 登录)不带", async () => { + const h = await import("../src/ssh-helpers.js"); + // exec 通道 / 观察窗 / 转发 / 文件传输都从这一处取选项——无终端的 ssh 遇到口令提示 + // 应答不了,让它当场失败而不是零输出挂到调用方超时 + expect(pairs(h.autonomousSshOpts())).toContain("-o BatchMode=yes"); + expect(pairs(h.autonomousSshOpts({ hostKeyPolicy: "strict", knownHostsFile: "~/.ssh/kh" }))).toContain("-o BatchMode=yes"); + expect(pairs(h.autonomousSshOpts(undefined, { interactive: true }))).not.toContain("-o BatchMode=yes"); + // PTY 登录链:-tt 强制终端,提示会回显进 PTY——保留交互(不加 BatchMode) + const root = h.rootSshSpawnArgs(["root@example.invalid"]); + expect(root[0]).toBe("-tt"); + expect(root.includes("BatchMode=yes")).toBe(false); + const withJump = { host: "target", conn: { jump: "jump" } }; + expect(h.sshArgsFor(withJump)[1]).toContain("BatchMode=yes"); + expect(h.sshArgsFor(withJump, { interactive: true })[1]).not.toContain("BatchMode"); + const hopCmd = h.hopSshCommand({ host: "example.invalid", conn: { user: "root" } }); + expect(hopCmd.startsWith("ssh ")).toBe(true); + expect(hopCmd).not.toContain("BatchMode"); + }); + + test("mux socket 目录名哈希锚点(参数间以 NUL 分隔——防拼接歧义)", async () => { + const { muxSocketPath } = await import("../src/ssh-helpers.js"); + const os = await import("node:os"); + const path = await import("node:path"); + const fs = await import("node:fs"); + const d = path.join(os.tmpdir(), "fx-mux-anchor"); + try { + const tail = (args: string[]) => muxSocketPath(args, d).split(/[\\/]/).pop(); + // v0.2.12 发布版的取值:分隔符当时是字符串字面量里的真 NUL 字节(补丁事故), + // 现为转义序列——运行时字符串不变,哈希逐项相同 + expect(tail(["root@h", "-i", "k"])).toBe("cm-19f1562a3ad5d1a4"); + expect(tail(["-p", "22", "u@h"])).toBe("cm-9d6035f41ff0fc39"); + expect(tail(["a"])).toBe("cm-ca978112ca1bbdca"); + expect(tail(["ab", "c"])).toBe("cm-6c032e631d39a14d"); + expect(tail(["a", "bc"])).toBe("cm-40bb547d936bbd31"); // 与 ["ab","c"] 不同:NUL 分隔的意义 + } finally { + fs.rmSync(d, { recursive: true, force: true }); + } + }); + + test.skipIf(!Bun.which("ssh"))("describeSshIdentitySource:本地 ssh -v -G 解析(不连网)给出用户/主机/端口与身份文件在场情况", async () => { + const { describeSshIdentitySource } = await import("../src/ssh-helpers.js"); + const src = await describeSshIdentitySource("localhost"); + expect(src).not.toBeNull(); + expect(src!.hostname).toBe("localhost"); + expect(src!.port).toMatch(/^\d+$/); + expect(src!.user.length).toBeGreaterThan(0); + expect(src!.identityFiles.every((f) => typeof f.path === "string" && typeof f.exists === "boolean")).toBe(true); + expect(Array.isArray(src!.configFiles)).toBe(true); + // 探测自身失败返回 null(诊断不得掩盖原始错误):非法主机名(前导 -)与 ssh 拒绝的参数 + expect(await describeSshIdentitySource("-bad-host")).toBeNull(); + }, 20_000); + + test("formatAuthFailureDiagnosis:跳板角色点明 --key 不传给跳板并给三条出路;无在场身份文件时点破", async () => { + const { formatAuthFailureDiagnosis } = await import("../src/ssh-helpers.js"); + const mk = (exists: boolean) => ({ + configFiles: ["C:/Users/u/.ssh/config"], user: "root", hostname: "10.0.0.1", port: "22", + identityFiles: [{ path: "~/.ssh/id_ed25519", exists }, { path: "~/.ssh/id_rsa", exists: false }], + }); + const jumpNoKey = formatAuthFailureDiagnosis({ role: "jump", label: "root@10.0.0.1", userGiven: true, source: mk(false) }); + expect(jumpNoKey).toContain("[跳板认证失败]"); + expect(jumpNoKey).toContain("跳板 `root@10.0.0.1`"); + expect(jumpNoKey).toContain("--key 只用于目标主机,不会传给跳板"); + expect(jumpNoKey).toContain("实际读取的配置文件:C:/Users/u/.ssh/config"); + expect(jumpNoKey).toContain("解析为:user=root hostname=10.0.0.1 port=22"); + expect(jumpNoKey).not.toContain("未显式指定"); // 给了用户名就不啰嗦 + expect(jumpNoKey).toContain("没有任何在场的身份文件"); + expect(jumpNoKey).toContain("①"); + expect(jumpNoKey).toContain("②"); + expect(jumpNoKey).toContain("③"); + // 目标角色:在场的与缺席的分开列(缺席的折叠计数);--key 文件不在场要点破 + const target = formatAuthFailureDiagnosis({ role: "target", label: "root@10.0.0.1", userGiven: false, keyFile: "D:/keys/absent", source: mk(true) }); + expect(target).toContain("[目标认证失败]"); + expect(target).toContain("在场的身份文件:~/.ssh/id_ed25519"); + expect(target).toContain("另有 1 个身份文件不存在:~/.ssh/id_rsa"); + expect(target).not.toContain("没有任何在场的身份文件"); + expect(target).toContain("未显式指定"); + expect(target).toContain("--key:D:/keys/absent(文件不存在!)"); + expect(target).not.toContain("出路"); // 出路三条是跳板专属 + // 探测失败:只留不依赖来源的说明,不崩 + const degraded = formatAuthFailureDiagnosis({ role: "jump", label: "j", userGiven: false, source: null }); + expect(degraded).toContain("[跳板认证失败]"); + expect(degraded).not.toContain("实际读取的配置文件"); + expect(degraded).not.toContain("没有任何在场的身份文件"); // 来源未知时不下这个结论 + }); + + test.skipIf(!Bun.which("ssh"))("connFailureDiagnosis:按被拒的角色分流;非认证类连接失败保持通用提示", async () => { + const { __testConnFailureDiagnosis } = await import("../src/ssh-pty-driver.js"); + const { noopLogger } = await import("../src/logger.js"); + const conn = { jump: "root@jump.example.invalid" } as never; + const jumpDenied = await __testConnFailureDiagnosis("root@target.example.invalid", conn, + "root@jump.example.invalid: Permission denied (publickey).\n\nConnection closed by UNKNOWN port 65535\n", noopLogger); + expect(jumpDenied).toContain("[跳板认证失败]"); + expect(jumpDenied).toContain("跳板 `root@jump.example.invalid`"); + // 目标被拒(跳板正常):目标角色,不误判成跳板 + const targetDenied = await __testConnFailureDiagnosis("root@target.example.invalid", conn, + "root@target.example.invalid: Permission denied (publickey,password).\n", noopLogger); + expect(targetDenied).toContain("[目标认证失败]"); + expect(targetDenied).not.toContain("[跳板认证失败]"); + // 不带跳板的解析失败:ssh 的报错可见,保持通用提示(不附认证类诊断) + const plainUnresolved = await __testConnFailureDiagnosis("root@target.example.invalid", undefined, + "ssh: Could not resolve hostname target.example.invalid: No such host is known.\n", noopLogger); + expect(plainUnresolved).toContain("[连接层失败]"); + expect(plainUnresolved).not.toContain("认证失败"); + // 报告原始失败的位置,保留目标的错误行。 + const unresolved = await __testConnFailureDiagnosis("root@target.example.invalid", conn, + "ssh: Could not resolve hostname target.example.invalid: No such host is known.\n", noopLogger); + expect(unresolved).toContain("[目标无法解析]"); + expect(unresolved).toContain("Could not resolve hostname target.example.invalid"); + const silent = await __testConnFailureDiagnosis("root@target.example.invalid", conn, "", noopLogger); + expect(silent).toContain("失败位置无法确认"); + // 与连接层无关的输出:不附诊断 + expect(await __testConnFailureDiagnosis("h", undefined, "some other failure output", noopLogger)).toBe(""); + }, 60_000); +}); + +// DSH 评估 2026-11-26 #4:exec --no-daemon --pty 稳定 8.1s——结果早已打印,进程却等握手 +// 竞速的 8s 定时器到期才退(CLI 不调 process.exit,靠事件循环排空退出)。 +describe("DSH 评估 2026-11-26 #4:一次性 PTY 进程不被握手定时器拖住", () => { + test.skipIf(!Bun.which("ssh"))("握手结束后进程随事件循环排空退出(不留 8s 竞速定时器)", async () => { + const os = await import("node:os"); + const path = await import("node:path"); + const fs = await import("node:fs"); + const { pathToFileURL } = await import("node:url"); + const d = fs.mkdtempSync(path.join(os.tmpdir(), "fx-oneshot-")); + const script = path.join(d, "oneshot.ts"); + const modUrl = pathToFileURL(path.join(process.cwd(), "src", "ssh-pty-driver.ts")).href; + fs.writeFileSync(script, [ + `const { __testPtyLink } = await import(${JSON.stringify(modUrl)});`, + "const link = new __testPtyLink();", + "try { await link.attach(['-V']); await link.handshake('oneshot'); } catch { /* ssh -V 即退:握手按预期失败 */ }", + "console.log('HANDSHAKE_DONE');", + "// 刻意不调 process.exit:与 CLI 一次性进程一致,靠事件循环排空退出", + "", + ].join("\n")); + try { + const t0 = Date.now(); + const p = Bun.spawn([process.execPath, script], { stdout: "pipe", stderr: "pipe", windowsHide: true }); + const [out, code] = await Promise.all([new Response(p.stdout).text(), p.exited]); + const elapsed = Date.now() - t0; + expect(out).toContain("HANDSHAKE_DONE"); + expect(code).toBe(0); + // 修前:握手后进程被拖到 attach+8s 才退(真机 8360ms;修后 1187ms) + expect(elapsed).toBeLessThan(6_000); + } finally { + fs.rmSync(d, { recursive: true, force: true }); + } + }, 30_000); +}); + +// --------------------------------------------------------------------------- +// DSH 评估 2026-11-26(真机发现):带跳板时 ssh 把代理进程的 stderr 指向 /dev/null—— +// 跳板段的任何失败都是「255 + 零输出」。诊断探测带 -v 重放把报错带回后,按报错行 +// 判定失败发生在哪一段。 +// --------------------------------------------------------------------------- +describe("DSH 评估 2026-11-26:ssh 报错行归属判定(classifySshFailure)", () => { + test("跳板被拒:不带主机的重试提示排在前面时,仍归到跳板段", async () => { + const { classifySshFailure } = await import("../src/ssh-helpers.js"); + // 真机实录(vm-homelab,跳板 nosuchuser@127.0.0.1:3322):首版只看第一条报错行—— + // 「Permission denied, please try again.」不带主机名,被归给了目标 + const v = classifySshFailure([ + "OpenSSH_10.0p2 Debian-7+deb13u4, OpenSSL 3.5.9 29 Sep 2026", + "debug1: Offering public key: /root/.ssh/id_ed25519 ED25519 SHA256:…", + "Permission denied, please try again.", + "nosuchuser@127.0.0.1: Permission denied (publickey,password).", + "kex_exchange_identification: Connection closed by remote host", + "Connection closed by UNKNOWN port 65535", + ].join("\n"), "127.0.0.1"); + expect(v.stage).toBe("jump"); + expect(v.kind).toBe("auth"); + expect(v.lines).toContain("nosuchuser@127.0.0.1: Permission denied (publickey,password)."); + expect(v.lines[0]).toBe("Permission denied, please try again."); + expect(v.lines.some((l) => l.startsWith("debug1:"))).toBe(false); // debug 前缀已剥; Offering 之类的进度行不带回 + }); + + test("跳板别名解析不出 / 跳板端口不通:归跳板段,类别分别为 resolve / unreachable", async () => { + const { classifySshFailure } = await import("../src/ssh-helpers.js"); + const unresolved = classifySshFailure( + "debug1: Reading configuration data /root/.ssh/config\nssh: Could not resolve hostname no-such-alias-xyz: Name or service not known\nkex_exchange_identification: Connection closed by remote host\n", + "no-such-alias-xyz", + ); + expect(unresolved.stage).toBe("jump"); + expect(unresolved.kind).toBe("resolve"); + expect(unresolved.lines).toEqual([ + "ssh: Could not resolve hostname no-such-alias-xyz: Name or service not known", + "kex_exchange_identification: Connection closed by remote host", + ]); + const refused = classifySshFailure("ssh: connect to host 127.0.0.1 port 9: Connection refused\r\nConnection closed by UNKNOWN port 65535\r\n", "127.0.0.1"); + expect(refused.stage).toBe("jump"); + expect(refused.kind).toBe("unreachable"); + expect(refused.lines).toHaveLength(2); // CRLF 归一后仍是两行 + }); + + test("跳板已连通、目标被拒:归目标段;无跳板时一律目标段", async () => { + const { classifySshFailure } = await import("../src/ssh-helpers.js"); + const targetDenied = classifySshFailure("nosuchuser@localhost: Permission denied (publickey,password).\n", "127.0.0.1"); + expect(targetDenied.stage).toBe("target"); + expect(targetDenied.kind).toBe("auth"); + // 「Connection closed by remote host」不带具体主机——不点名跳板 + const kex = classifySshFailure("kex_exchange_identification: Connection closed by remote host\n", "jump.example"); + expect(kex.stage).toBe("target"); + expect(kex.kind).toBe("unreachable"); + expect(classifySshFailure("root@h: Permission denied (publickey).\n", null).stage).toBe("target"); + // 跳板与目标同名:第一条点名行即失败点(跳板段先失败) + expect(classifySshFailure("u@same: Permission denied (publickey).\n", "same").stage).toBe("jump"); + }); + + test("没有可判读的报错行:stage=none(连接探测成功时不附误导诊断);最多带回 8 行", async () => { + const { classifySshFailure } = await import("../src/ssh-helpers.js"); + const ok = classifySshFailure("debug1: Authentication succeeded (publickey).\ndebug1: channel 0: new session\n", "j"); + expect(ok).toEqual({ stage: "none", kind: null, lines: [] }); + const many = classifySshFailure(Array.from({ length: 20 }, (_, i) => `h${i}: Permission denied (publickey).`).join("\n"), "j"); + expect(many.lines).toHaveLength(8); + const hostkey = classifySshFailure("root@h: Host key verification failed.\n", "j"); + expect(hostkey.kind).toBe("hostkey"); + }); +});