Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 等待前置步骤的所有实例成功,整个批次共享并发上限。
Expand Down
3 changes: 2 additions & 1 deletion docs/skills/SKILL.en.md
Original file line number Diff line number Diff line change
@@ -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.

Expand Down Expand Up @@ -58,6 +58,7 @@ filaxis exec --layer <name> --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.
Expand Down
3 changes: 2 additions & 1 deletion docs/skills/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: filaxis-runtime
version: 0.2.7
version: 0.2.8
description: |
牵丝 Filaxis 远程执行运行时的技能剧本总入口——选型决策树(exec 还是观察还是会话)+ 核心契约速查 + 四份场景剧本索引。

Expand Down Expand Up @@ -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`。结果逐步标明命名层。
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
182 changes: 153 additions & 29 deletions src/agent-toolkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string | PushSshTarget>;
}

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;
Expand All @@ -69,9 +99,8 @@ export interface AgentToolHandlers {
}>;
stop_and_verify(args: { session_id: string; layer?: string }): Promise<StopResult>;
// ── 层族(第十季命名层注册表——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<Record<keyof PushSshTarget, never>>): Promise<PushSshBatchResult>;
push_ssh(args: PushSshTarget & { targets?: never }): Promise<PushSshResult>;
push_into(args: { enter_cmd: string; label?: string; from?: string; name?: string }): Promise<{
layer: string; target?: string;
}>;
Expand Down Expand Up @@ -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<string>();
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,
Expand Down Expand Up @@ -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"],
},
],
},
},
},
Expand Down Expand Up @@ -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<typeof sshConnection>): Promise<PushSshResult> => {
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<PushSshResult>;
function pushSsh(args: PushSshBatchArgs & Partial<Record<keyof PushSshTarget, never>>): Promise<PushSshBatchResult>;
async function pushSsh(args: PushSshTarget | PushSshBatchArgs): Promise<PushSshResult | PushSshBatchResult> {
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<string>();
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<AgentFileTransferResult> => {
const { local_path, remote_path, layer: layerName, transport, timeout_ms, write_mode, ...unknownFields } = args;
const extra = Object.keys(unknownFields);
Expand Down Expand Up @@ -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<string, unknown> = {};
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 拼错→裸宿主机层)
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
17 changes: 16 additions & 1 deletion src/mcp-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -231,6 +231,17 @@ function summarizeToolResult(name: string, value: unknown, textOnlyBatch: boolea
const result = value as Awaited<ReturnType<AgentToolHandlers["run_command"]>>;
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<ReturnType<AgentToolHandlers["run_batch"]>>;
const overview = `status=${result.status}${result.failed_step ? ` | failed_step=${result.failed_step}` : ""}`;
Expand Down Expand Up @@ -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");
}
Expand Down
Loading