From b76b594eae7b8571c484a7e1edc38891567c2bcf Mon Sep 17 00:00:00 2001 From: corolin Date: Mon, 23 Nov 2026 11:12:59 +0800 Subject: [PATCH] Prepare Filaxis 0.2.8 with batch SSH connections --- CHANGELOG.md | 5 + docs/skills/SKILL.en.md | 3 +- docs/skills/SKILL.md | 3 +- package.json | 2 +- src/agent-toolkit.ts | 182 ++++++++++++++++++++++++++++------ src/index.ts | 5 +- src/mcp-server.ts | 17 +++- src/runtime-stack.ts | 14 ++- src/ssh-helpers.ts | 38 +++++-- tests/integration-ssh.test.ts | 13 ++- tests/mcp-server.test.ts | 64 ++++++++++++ tests/runtime-stack.test.ts | 35 +++++++ 12 files changed, 333 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00143bd..6d681d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ --- +## 0.2.8 + +- MCP 和 Agent Toolkit 的 `push_ssh` 可按目标或 SSH 配置别名列表批量建立命名层,逐目标报告新建、复用或连接失败,并返回可用于 `run_batch.layer` 的实际层名。 +- 建立命名 SSH 层时按有效 OpenSSH 配置判断连接是否可复用。共享同一内网地址且经不同代理的 SSH 别名会分别建连。 + ## 0.2.7 - SDK `runBatch`、CLI `batch` 和 MCP `run_batch` 支持在计划或步骤的 `layer` 中指定多个命名层。多层步骤按 `id@layer` 报告,`after` 等待前置步骤的所有实例成功,整个批次共享并发上限。 diff --git a/docs/skills/SKILL.en.md b/docs/skills/SKILL.en.md index d9ba4c7..3eca3eb 100644 --- a/docs/skills/SKILL.en.md +++ b/docs/skills/SKILL.en.md @@ -1,6 +1,6 @@ --- name: filaxis-runtime -version: 0.2.7 +version: 0.2.8 description: | Entry skill guide for the Filaxis remote execution runtime (@syrkos/filaxis) — 30-second execution mode selector, MCP/CLI/SDK recipes, and core execution contracts for reliable SSH, Docker, and multi-hop agent operations. @@ -58,6 +58,7 @@ filaxis exec --layer --timeout 8000 -- "(printf 'PING\n'; sleep 1) | nc 1 ## MCP Practical Guidelines - **Batch inspection and multi-step fixes with `run_batch`**: Combine multiple `read_file`, `run_command`, `edit_file`, `put`, and `get` steps into a single parallel `run_batch` call instead of sequential single-tool loops. +- **Batch SSH connections**: Call `push_ssh` with `{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`. Strings can be SSH config aliases resolved in the runtime environment. Targets are attempted in order and individual connection failures are reported without stopping the batch. Pass the deduplicated `layers` from successful and reused connections directly to `run_batch.layer`. `active_layer` reports the default layer at the end of the call. - **Layer targeting precedence & multi-layer fan-out**: Both top-level `layer` and per-step `layer` accept either a single layer name or a non-empty array of layer names (top-level sets the batch default; per-step overrides only that step; omitting both uses the active default layer). Multi-layer arrays expand each step into `id@layer` instances that run in parallel up to `max_parallel` (single-element arrays keep the original `id`), and downstream `after` dependencies wait for all expanded instances to succeed (`kind: "get"` rejects multi-layer arrays to avoid overwriting the same `local_path`). `filaxis batch --request-file plan.json` shares the same precedence and array expansion (step `layer` > plan `layer` > `--layer`/`--host` > local). - **Local targeting**: Layer arrays look up registered or saved names. SDK callers can register the local host with `stack.addLayer("local", { driver: "local" })`. The CLI and standalone MCP server leave the local default unnamed. - **Concurrency & ordering (`max_parallel` and `after`)**: Independent steps run in parallel up to `max_parallel`. Use `after: ["step-id"]` to serialize dependent steps (e.g., edit config -> validate -> reload service), even across layers. diff --git a/docs/skills/SKILL.md b/docs/skills/SKILL.md index 2c0154c..8dc8106 100644 --- a/docs/skills/SKILL.md +++ b/docs/skills/SKILL.md @@ -1,6 +1,6 @@ --- name: filaxis-runtime -version: 0.2.7 +version: 0.2.8 description: | 牵丝 Filaxis 远程执行运行时的技能剧本总入口——选型决策树(exec 还是观察还是会话)+ 核心契约速查 + 四份场景剧本索引。 @@ -45,6 +45,7 @@ filaxis exec --layer <名> --timeout 8000 -- "(printf 'PING ``` **MCP 形态实战指引**(第十二季盲测 B 组教训): +- 多个 SSH 目标可用一次 `push_ssh` 调用,例如 `{"targets":["web-01",{"host":"db-01","name":"db","jump":"bastion"}]}`。字符串可用运行环境 SSH 配置里的别名。按输入顺序建连,单个目标失败后继续尝试。返回的 `layers` 只含建连成功或复用的实际层名,并已去重,非空时可直接传给 `run_batch.layer`。批量结果的 `active_layer` 是调用结束时的默认层。 - **定位/巡检期用 `run_batch` 打包**——多个 read_file/run_command 一次调用并行 执行(B 组逐个调 18 步 vs CLI 组打包 11 步——这是 MCP 形态省步数的最大杠杆); - `run_batch` 的顶层 `layer` 和步骤 `layer` 均支持传单个层名或层名数组(也可同时传:顶层是批次默认值,步骤的 `layer` 仅覆盖本步;两处都省略时使用调用时的默认层)。传多个层名数组时,步骤按 `id@layer` 展开并在 `max_parallel` 并发池内并行执行,下游 `after` 需等被依赖步骤的所有展开实例均 ok 后才启动(`kind: "get"` 不支持多层数组,防并发覆盖同一 `local_path`);单元素数组保留原 `id`。结果逐步标明命名层。 diff --git a/package.json b/package.json index 9adc079..feae155 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@syrkos/filaxis", - "version": "0.2.7", + "version": "0.2.8", "description": "牵丝 Filaxis — 面向自动化与 Agent 的远程执行运行时 SDK(Syrkos · 漩核)。千里一线,执行有迹。", "type": "module", "license": "Apache-2.0", diff --git a/src/agent-toolkit.ts b/src/agent-toolkit.ts index 80e3fbf..5865a94 100644 --- a/src/agent-toolkit.ts +++ b/src/agent-toolkit.ts @@ -18,6 +18,7 @@ import type { TransferResult } from "./file-transfer.js"; import { BATCH_STEP_KINDS, runBatch, type BatchLayerTarget, type BatchStepWithDeps } from "./batch.js"; import type { RuntimeDriver } from "./driver.js"; import { SessionOwnership, type StopResult } from "./session-ownership.js"; +import { sshArgsFor } from "./ssh-helpers.js"; export interface AgentToolDef { type: "function"; @@ -46,6 +47,35 @@ function agentTransferResult({ writeMode, ...result }: LayerFileTransferResult): return { ...result, write_mode: writeMode }; } +export interface PushSshTarget { + host: string; + port?: number; + user?: string; + key?: string; + jump?: string; + name?: string; +} + +export interface PushSshResult { + layer: string; + reused: boolean; + reused_from?: string; + note?: string; +} + +export interface PushSshBatchArgs { + targets: Array; +} + +export interface PushSshBatchResult { + status: "ok" | "partial" | "fail"; + active_layer?: string; + layers: string[]; + results: Array<{ host: string; name: string } & ( + ({ status: "ok" } & PushSshResult) | { status: "fail"; error: string } + )>; +} + export interface AgentToolHandlers { run_command(args: { command: string; timeout_ms?: number; layer?: string }): Promise<{ stdout: string; stderr: string; exit_code: number; effective_user?: string; @@ -69,9 +99,8 @@ export interface AgentToolHandlers { }>; stop_and_verify(args: { session_id: string; layer?: string }): Promise; // ── 层族(第十季命名层注册表——Paramiko 式句柄寻址)── - push_ssh(args: { host: string; port?: number; user?: string; key?: string; jump?: string; name?: string }): Promise<{ - layer: string; reused: boolean; reused_from?: string; note?: string; - }>; + push_ssh(args: PushSshBatchArgs & Partial>): Promise; + push_ssh(args: PushSshTarget & { targets?: never }): Promise; push_into(args: { enter_cmd: string; label?: string; from?: string; name?: string }): Promise<{ layer: string; target?: string; }>; @@ -119,6 +148,70 @@ const fileTransferProperties = { }; const layerNameSchema = { type: "string", minLength: 1, pattern: "\\S" }; +const sshHostSchema = { type: "string", minLength: 1, pattern: "^\\S+$", description: "目标主机(user@host 或运行环境的 SSH 配置别名)" }; +const sshTargetSchema = { + type: "object", + additionalProperties: false, + properties: { + host: sshHostSchema, + port: { type: "integer", minimum: 1, maximum: 65535, description: "SSH 端口" }, + user: { type: "string", description: "登录用户名" }, + key: { type: "string", description: "私钥文件路径(-i)" }, + jump: { type: "string", description: "跳板(-J,途径机不占层)" }, + name: { ...layerNameSchema, description: "层名(省略时使用 host)" }, + }, + required: ["host"], +}; +const sshTargetsSchema = { + type: "array", + minItems: 1, + description: "按顺序尝试的目标。字符串可直接使用当前运行环境的 SSH 配置别名", + items: { anyOf: [sshHostSchema, sshTargetSchema] }, +}; + +function sshConnection({ host, port, user, key, jump, name }: PushSshTarget) { + const connParams = { + ...(port != null ? { port: Number(port) } : {}), + ...(user ? { user: String(user) } : {}), + ...(key ? { keyFile: String(key) } : {}), + ...(jump ? { jump: String(jump) } : {}), + }; + return { host: String(host), name: name ?? String(host), connParams }; +} + +function sshBatchTargets(targets: PushSshBatchArgs["targets"]) { + if (!Array.isArray(targets) || !targets.length) throw new Error("push_ssh 的 targets 需为非空数组"); + const names = new Set(); + return Array.from(targets, (entry, index) => { + const raw = typeof entry === "string" ? { host: entry } : entry; + const label = `targets[${index}]`; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${label} 需为主机名或对象`); + if (Object.keys(raw).some((key) => !Object.hasOwn(sshTargetSchema.properties, key))) { + throw new Error(`${label} 含未知连接字段`); + } + for (const field of ["host", "user", "key", "jump", "name"] as const) { + const value = raw[field]; + if (field !== "host" && value === undefined) continue; + if (typeof value !== "string" || !value.trim() || /[\x00-\x1f\x7f]/.test(value)) { + throw new Error(`${label}.${field} 需为非空字符串且不能含控制字符`); + } + } + if (!/^[^@\s]+(?:@[^@\s]+)?$/.test(raw.host) || raw.host.startsWith("-") + || (raw.user !== undefined && (/[\s@]/.test(raw.user) || raw.host.includes("@")))) { + throw new Error(`${label} 的 host 或 user 无效`); + } + if (raw.port !== undefined && (!Number.isInteger(raw.port) || raw.port < 1 || raw.port > 65535)) { + throw new Error(`${label}.port 需为 1 到 65535 的整数`); + } + const connection = sshConnection(raw); + // Check the same target and jump argument rules as the actual SSH driver. + sshArgsFor({ host: connection.host, conn: connection.connParams }); + if (names.has(connection.name)) throw new Error(`targets 含重复层名 '${connection.name}'`); + names.add(connection.name); + return connection; + }); +} + const batchLayerSchema = (description: string) => ({ anyOf: [ layerNameSchema, @@ -379,19 +472,21 @@ export const TOOL_DEFS: AgentToolDef[] = [ function: { name: "push_ssh", description: - "建立命名 ssh 层(成为默认层——后续工具缺省落它)。同落点幂等复用(reused=true 返回既有层," + - "不重复建连)+ 落点校验(宁重连不错主机)。跳板传 jump(-J 不占层)。", + "建立命名 SSH 层。单个目标传 host,批量传 targets(主机、SSH 配置别名或连接对象的数组)。" + + "批量按输入顺序尝试,返回各目标结果。layers 非空时可直接传给 run_batch。新建层成为默认层。" + + "同落点可复用,结果中的 layer 是实际层名。跳板传 jump。", parameters: { type: "object", - properties: { - host: { type: "string", description: "目标主机(user@host 或 ssh config 别名)" }, - port: { type: "number", description: "SSH 端口(非 22 时指定)" }, - user: { type: "string", description: "登录用户名" }, - key: { type: "string", description: "私钥文件路径(-i)" }, - jump: { type: "string", description: "跳板(-J:途径机不占层)" }, - name: { type: "string", description: "层名(缺省=host;注册表内唯一,显式寻址用)" }, - }, - required: ["host"], + properties: { ...sshTargetSchema.properties, targets: sshTargetsSchema }, + oneOf: [ + sshTargetSchema, + { + type: "object", + additionalProperties: false, + properties: { targets: sshTargetsSchema }, + required: ["targets"], + }, + ], }, }, }, @@ -476,6 +571,49 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption if (layerName) return stack.layer(layerName).driver; return stack.active ?? await layer(); }; + const connectSsh = async ({ host, name, connParams }: ReturnType): Promise => { + const result = await stack.addLayer(name, { + driver: "ssh", target: host, + config: Object.keys(connParams).length ? { connParams } : undefined, + }); + return { + layer: result.handle.name, reused: result.reused, reused_from: result.reusedFrom, + note: result.reused ? "落点已由既有层持有——幂等复用(未重复建连)" : "新层已建并成为默认层", + }; + }; + function pushSsh(args: PushSshTarget & { targets?: never }): Promise; + function pushSsh(args: PushSshBatchArgs & Partial>): Promise; + async function pushSsh(args: PushSshTarget | PushSshBatchArgs): Promise { + if (!("targets" in args)) { + if (typeof args.host !== "string" || !args.host.trim()) { + throw new Error("push_ssh 需提供单目标 host 或批量 targets"); + } + return connectSsh(sshConnection(args)); + } + if (Object.keys(args).some((key) => key !== "targets")) throw new Error("push_ssh 的 targets 必须单独提供"); + const targets = sshBatchTargets(args.targets); + const results: PushSshBatchResult["results"] = []; + const layers = new Set(); + let failures = 0; + // Serial registration preserves RuntimeStack's landing reuse and default-layer order. + for (const target of targets) { + const { host, name } = target; + try { + const result = await connectSsh(target); + layers.add(result.layer); + results.push({ host, name, status: "ok", ...result }); + } catch (error) { + failures++; + results.push({ host, name, status: "fail", error: error instanceof Error ? error.message : String(error) }); + } + } + return { + status: failures === 0 ? "ok" : failures === targets.length ? "fail" : "partial", + active_layer: stack.activeLayer?.name, + layers: [...layers], + results, + }; + } const transferFile = async (operation: "put" | "get", args: AgentFilePutArgs): Promise => { const { local_path, remote_path, layer: layerName, transport, timeout_ms, write_mode, ...unknownFields } = args; const extra = Object.keys(unknownFields); @@ -679,21 +817,7 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption return { window_id, closed: true }; }, // ── 层族(第十季命名层注册表)── - async push_ssh({ host, port, user, key, jump, name }) { - const connParams: Record = {}; - if (port != null) connParams.port = Number(port); - if (user) connParams.user = String(user); - if (key) connParams.keyFile = String(key); - if (jump) connParams.jump = String(jump); - const r = await stack.addLayer(name ?? String(host), { - driver: "ssh", target: String(host), - config: Object.keys(connParams).length ? { connParams } : undefined, - }); - return { - layer: r.handle.name, reused: r.reused, reused_from: r.reusedFrom, - note: r.reused ? "落点已由既有层持有——幂等复用(未重复建连)" : "新层已建并成为默认层", - }; - }, + push_ssh: pushSsh, async push_into(args) { // 参数别名宽收(第十二季语法糖):enter_cmd / enterCommand / enter_command / enterCmd // 等价——Agent 手滑完整词不再静默漏建层(同款事故:enterCommand 拼错→裸宿主机层) diff --git a/src/index.ts b/src/index.ts index 1a5f835..c2c15e9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,7 +30,10 @@ export type { FileTransferTransport, LayerFileTransferOptions, LayerFileTransfer export * from "./layer-env.js"; export { resolveLocalShell } from "./shell-discovery.js"; export { createAgentToolkit } from "./agent-toolkit.js"; -export type { AgentToolkit, AgentToolDef, AgentToolHandlers, AgentToolkitOptions } from "./agent-toolkit.js"; +export type { + AgentToolkit, AgentToolDef, AgentToolHandlers, AgentToolkitOptions, + PushSshTarget, PushSshResult, PushSshBatchArgs, PushSshBatchResult, +} from "./agent-toolkit.js"; export { discoverLayer } from "./layer-discovery.js"; export type { DiscoverLayerOptions, DiscoverLayerResult } from "./layer-discovery.js"; export * from "./stream-window.js"; diff --git a/src/mcp-server.ts b/src/mcp-server.ts index a965e8b..94d250b 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -17,7 +17,7 @@ import * as readline from "node:readline"; import { version } from "../package.json" with { type: "json" }; -import { TOOL_DEFS, type AgentToolHandlers, type AgentToolkit } from "./agent-toolkit.js"; +import { TOOL_DEFS, type AgentToolHandlers, type AgentToolkit, type PushSshBatchResult, type PushSshResult } from "./agent-toolkit.js"; import { noopLogger, type FilaxisLogger } from "./logger.js"; const MCP_PROTOCOL_VERSION = "2025-06-18"; @@ -231,6 +231,17 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea const result = value as Awaited>; return [`exit=${result.exit_code}`, ...outputPreviews(result, COMMAND_PREVIEW_BYTES)].join("\n"); } + if (name === "push_ssh") { + const result = value as PushSshResult | PushSshBatchResult; + if ("results" in result) { + const overview = `status=${result.status}${result.active_layer ? ` | active_layer=${singleLine(result.active_layer)}` : ""}`; + const lines = result.results.map((target) => target.status === "ok" + ? `[ok] ${singleLine(target.name)} | layer=${singleLine(target.layer)} | reused=${target.reused}` + : `[fail] ${singleLine(target.name)} | ${singleLine(preview(target.error, BATCH_DETAIL_BYTES, FULL_OUTPUT_HINT))}`); + const summary = [overview, ...lines].join("\n"); + return jsonStringBytes(summary) <= BATCH_TEXT_JSON_BYTES ? summary : limitBatchText(summary, FULL_OUTPUT_HINT); + } + } if (name === "run_batch") { const result = value as Awaited>; const overview = `status=${result.status}${result.failed_step ? ` | failed_step=${result.failed_step}` : ""}`; @@ -276,6 +287,10 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea return summarize(value); } +function singleLine(text: string): string { + return text.replace(/[\p{Cc}\u2028\u2029]/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`); +} + function jsonStringBytes(text: string): number { return Buffer.byteLength(JSON.stringify(text), "utf8"); } diff --git a/src/runtime-stack.ts b/src/runtime-stack.ts index 0af062f..e0c2f19 100644 --- a/src/runtime-stack.ts +++ b/src/runtime-stack.ts @@ -15,7 +15,7 @@ import { RuntimeFactory } from "./factory.js"; import { EventBus } from "./events.js"; import { settleRejection } from "./async-guard.js"; import { - enterStepsOf, layerDisplayName, layerPathIdentities, resolveSshIdentity, ENTER_ALIAS_KEYS, + enterStepsOf, layerDisplayName, layerPathIdentities, resolveSshIdentity, resolveSshReuseKey, ENTER_ALIAS_KEYS, hopHost, type SshHop, type SshConnParams, } from "./ssh-helpers.js"; import type { SessionEvent } from "./session-types.js"; @@ -697,7 +697,7 @@ export class RuntimeStack { }, }); return contextKey(descriptor) === contextKey(candidate); - }); + }, resolveSshReuseKey); } private static sshHopContext(hop?: SshHop): unknown { @@ -708,8 +708,12 @@ export class RuntimeStack { /** terminal=true:identity 命中在该层路径**末节点**(同落点构造性成立,免 hostname 探测); * false:命中途经节点(identity 撞了中间跳——hostname 落点校验把关) */ - private async findIdentityHopHit(dest: SshHop, compatible?: (candidate: RuntimeDescriptor) => boolean): Promise<{ handle: LayerHandle; terminal: boolean } | undefined> { - const destId = await resolveSshIdentity(dest, this.log); + private async findIdentityHopHit( + dest: SshHop, + compatible?: (candidate: RuntimeDescriptor) => boolean, + resolve: (hop: SshHop, logger: FilaxisLogger) => Promise = resolveSshIdentity, + ): Promise<{ handle: LayerHandle; terminal: boolean } | undefined> { + const destId = await resolve(dest, this.log); if (!destId || destId.startsWith("unresolved:")) { // 解析不可达(DNS/离线)——identity 不可靠,跳过判重(建层失败由 connect 兜底) return undefined; @@ -725,7 +729,7 @@ export class RuntimeStack { for (let i = 0; i < path.length; i++) { const candidate = path[i]!; if (JSON.stringify(RuntimeStack.sshHopContext(candidate)) !== context) continue; - if ((await resolveSshIdentity(candidate, this.log)) === destId) { + if ((await resolve(candidate, this.log)) === destId) { return { handle: h, terminal: i === path.length - 1 }; } } diff --git a/src/ssh-helpers.ts b/src/ssh-helpers.ts index 9befbb8..e098557 100644 --- a/src/ssh-helpers.ts +++ b/src/ssh-helpers.ts @@ -396,9 +396,23 @@ export function hopSshCommand(hop: SshHop): string { export const SSH_INPUT_WAIT_RE = /(?:password|passphrase|verification\s+code|login|密码|口令)[^\n]*[::]\s*$|yes\s*\/\s*no|are you sure|continue connecting/i; -const identityCache = new Map(); +interface SshIdentity { + landing: string; + reuseKey: string; +} + +const identityCache = new Map(); /** 连接身份解析(ssh -G 本地解析不连网);失败回退 unresolved: 前缀(视为不相同,不误拦) */ export async function resolveSshIdentity(hop: SshHop, logger?: FilaxisLogger): Promise { + return (await lookupSshIdentity(hop, logger))?.landing ?? `unresolved:${hopHost(hop)}`; +} + +/** Identity for connection reuse, including the effective OpenSSH configuration. */ +export async function resolveSshReuseKey(hop: SshHop, logger?: FilaxisLogger): Promise { + return (await lookupSshIdentity(hop, logger))?.reuseKey; +} + +async function lookupSshIdentity(hop: SshHop, logger?: FilaxisLogger): Promise { const cacheKey = typeof hop === "string" ? hop : JSON.stringify(hop); const cached = identityCache.get(cacheKey); if (cached) return cached; @@ -407,21 +421,31 @@ export async function resolveSshIdentity(hop: SshHop, logger?: FilaxisLogger): P let stdout: string; if (sshFileStdioRequested()) { const result = await spawnWithFileRedirect(argv, "", { timeoutMs: 8000, logger }); - if (result.exitCode !== 0) return `unresolved:${hopHost(hop)}`; + if (result.exitCode !== 0) return undefined; stdout = result.stdout; } else { const { execFile } = await import("node:child_process"); const { promisify } = await import("node:util"); ({ stdout } = await promisify(execFile)("ssh", argv, { timeout: 8000, env: openSshEnvironment(process.env, logger) })); } - const h = stdout.match(/^hostname (\S+)$/m)?.[1] ?? hopHost(hop); - const p = stdout.match(/^port (\d+)$/m)?.[1] ?? "22"; - const u = stdout.match(/^user (\S+)$/m)?.[1] ?? ""; - const id = `${u ? u + "@" : ""}${h}:${p}`; + const config = stdout.replace(/\r\n/g, "\n"); + const h = config.match(/^hostname (\S+)$/m)?.[1]; + const p = config.match(/^port (\d+)$/m)?.[1]; + const u = config.match(/^user (\S+)$/m)?.[1]; + if (!h || !p || !u) return undefined; + const { createHash } = await import("node:crypto"); + // A proxy or a config token can expand the original alias at connect time. + // Keep it when the effective configuration can still depend on it. + const aliasSensitive = /^proxy(?:command|jump) (?!none$).+$/m.test(config) || /%n/.test(config); + const effective = aliasSensitive ? config : config.replace(/^host .*\n/m, ""); + const id = { + landing: `${u}@${h}:${p}`, + reuseKey: createHash("sha256").update(effective).update(aliasSensitive ? hopHost(hop) : "").digest("hex"), + }; identityCache.set(cacheKey, id); return id; } catch { - return `unresolved:${hopHost(hop)}`; + return undefined; } } diff --git a/tests/integration-ssh.test.ts b/tests/integration-ssh.test.ts index aea2895..b02d4b6 100644 --- a/tests/integration-ssh.test.ts +++ b/tests/integration-ssh.test.ts @@ -685,12 +685,21 @@ describe("第十一季:批量组合(CI 真机)", () => { const toolkit = createAgentToolkit(stack); try { await stack.addLayer("controller", { driver: "local" }); - await toolkit.handlers.push_ssh({ host: TARGET, name: "remote" }); + const connections = await toolkit.handlers.push_ssh({ targets: [ + { host: TARGET, name: "remote" }, { host: TARGET, name: "duplicate-landing" }, + ] }); + expect(connections).toMatchObject({ + status: "ok", active_layer: "remote", layers: ["remote"], + results: [ + { layer: "remote", reused: false }, + { layer: "remote", reused: true }, + ], + }); const result = await toolkit.handlers.run_batch({ layer: "controller", steps: [ { id: "local", kind: "exec", command: "printf controller" }, - { id: "syntax", kind: "exec", layer: "remote", command: "if true; then\n echo unfinished", expect_exit: [2], after: ["local"] }, + { id: "syntax", kind: "exec", layer: connections.layers, command: "if true; then\n echo unfinished", expect_exit: [2], after: ["local"] }, { id: "script", kind: "exec", layer: "remote", command: "cat <<'END'\n'quoted' $HOME\nEND\n# final comment", after: ["syntax"] }, { id: "done", kind: "exec", command: "printf done", after: ["script"] }, ], diff --git a/tests/mcp-server.test.ts b/tests/mcp-server.test.ts index bab983e..0834e38 100644 --- a/tests/mcp-server.test.ts +++ b/tests/mcp-server.test.ts @@ -469,6 +469,70 @@ test("MCP opens, reads, and closes a continuous window by ID", async () => { }, 20_000); describe("MCP layer array fan-out", () => { + test("push_ssh validates all batch targets and reports usable layers after partial failure", async () => { + const stack = new RuntimeStack(); + const addLayer = stack.addLayer.bind(stack); + const attempted: Array<{ name: string; descriptor: Parameters[1] }> = []; + stack.addLayer = async (name, descriptor) => { + attempted.push({ name, descriptor }); + if (name === "unreachable") throw new Error("fixture connection failed"); + if (name === "same-host") return { handle: stack.layer("web"), reused: true, reusedFrom: "web" }; + return addLayer(name, new LocalRuntimeDriver()); + }; + const f = mcpFixture(stack); + const call = async (id: number, name: string, args: Record) => { + f.write({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }); + return (await waitId(f, id)).result; + }; + try { + const invalid = [ + { targets: [] }, + { targets: ["web", { host: "other", name: "web" }] }, + { targets: ["web", { host: "db", port: 0 }] }, + { targets: ["web", { host: "db", jump: "one,two" }] }, + { targets: ["web", { host: "deploy@db", user: "other" }] }, + { targets: ["web", "deploy@"] }, + { targets: ["web", { host: "db", name: "db\n01" }] }, + { targets: ["web"], host: "db" }, + { hosts: ["web"] }, + ]; + for (const [index, args] of invalid.entries()) { + expect(await call(index, "push_ssh", args)).toMatchObject({ isError: true }); + } + expect(attempted).toHaveLength(0); + expect(await call(10, "push_ssh", { targets: [ + "web", "unreachable", { host: "db", name: "database", port: 2222, user: "deploy", jump: "bastion" }, "same-host", + ] })).toMatchObject({ + isError: false, + content: [{ text: expect.stringContaining("[fail] unreachable | fixture connection failed") }], + structuredContent: { + status: "partial", + active_layer: "database", + layers: ["web", "database"], + results: [ + { host: "web", name: "web", status: "ok", layer: "web", reused: false }, + { host: "unreachable", status: "fail" }, + { host: "db", name: "database", status: "ok", layer: "database", reused: false }, + { host: "same-host", status: "ok", layer: "web", reused: true, reused_from: "web" }, + ], + }, + }); + expect(attempted[2]).toEqual({ + name: "database", + descriptor: { driver: "ssh", target: "db", config: { connParams: { port: 2222, user: "deploy", jump: "bastion" } } }, + }); + expect(await call(11, "push_ssh", { targets: ["unreachable"] })).toMatchObject({ + structuredContent: { status: "fail", layers: [], active_layer: "database" }, + }); + expect(await call(12, "push_ssh", { host: "single" })).toMatchObject({ + structuredContent: { layer: "single", reused: false }, + }); + } finally { + f.close(); + await Promise.all([...stack.layers.keys()].map((name) => stack.removeLayer(name, { destroy: true }))); + } + }); + test("tools/list exposes string | string[] schema for run_batch layer and step layer", async () => { const f = mcpFixture(); try { diff --git a/tests/runtime-stack.test.ts b/tests/runtime-stack.test.ts index 3d2d35e..bbd64af 100644 --- a/tests/runtime-stack.test.ts +++ b/tests/runtime-stack.test.ts @@ -3,6 +3,9 @@ * + 命名层注册表状态机(第十季 Layer 渗透——Paramiko 式句柄) */ import { describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, join } from "node:path"; import { EventBus } from "../src/events.js"; import { RuntimeStack } from "../src/runtime-stack.js"; import { createAgentToolkit } from "../src/agent-toolkit.js"; @@ -1313,6 +1316,38 @@ describe("Sol 77:索引销毁中跳过/嵌套不互覆", () => { }, 15_000); }); +test.skipIf(process.platform === "win32")("SSH aliases with different proxy routes get distinct named layers", async () => { + const dir = mkdtempSync(join(tmpdir(), "filaxis-ssh-route-")); + const savedPath = process.env.PATH; + const stack = new RuntimeStack(); + stack.connect = async (descriptor) => new MockLayerDriver(descriptor) as unknown as RuntimeDriver; + try { + writeFileSync(join(dir, "ssh"), [ + "#!/bin/sh", + 'test "$1" = -G || exit 1', + 'printf "host %s\\nuser deploy\\nhostname 10.0.0.5\\nport 22\\n" "$2"', + 'case "$2" in', + ' fx-route-a) printf "proxyjump bastion-a\\n";;', + ' fx-route-b) printf "proxyjump bastion-b\\n";;', + 'esac', + ].join("\n") + "\n", { mode: 0o700 }); + process.env.PATH = [dir, savedPath].filter(Boolean).join(delimiter); + const add = (name: string, target: string) => stack.addLayer(name, { driver: "ssh", target }); + const first = await add("routed-a", "fx-route-a"); + const second = await add("routed-b", "fx-route-b"); + expect(second.reused).toBe(false); + expect(second.handle.driver).not.toBe(first.handle.driver); + expect((await add("same-route", "fx-route-a")).handle).toBe(first.handle); + const direct = await add("direct", "fx-direct-a"); + expect((await add("direct-alias", "fx-direct-b")).handle).toBe(direct.handle); + } finally { + if (savedPath === undefined) delete process.env.PATH; + else process.env.PATH = savedPath; + await Promise.all([...stack.layers.keys()].map((name) => stack.removeLayer(name))); + rmSync(dir, { recursive: true, force: true }); + } +}); + test("sshInto only reuses a landing with matching connection settings", async () => { const stack = new RuntimeStack(); let pushed = 0;