From 17f4142e0a2cdb2916fe45fe24d44912959e4be9 Mon Sep 17 00:00:00 2001 From: corolin Date: Mon, 23 Nov 2026 10:46:15 +0800 Subject: [PATCH] Prepare Filaxis 0.2.7 with multi-layer batches --- CHANGELOG.md | 5 + docs/skills/SKILL.en.md | 7 +- docs/skills/SKILL.md | 7 +- package.json | 2 +- src/agent-toolkit.ts | 29 +++- src/batch.ts | 277 ++++++++++++++++++++++------------ src/index.ts | 2 +- src/mcp-server.ts | 2 +- tests/batch.test.ts | 238 ++++++++++++++++++++++++++++- tests/integration-ssh.test.ts | 2 + tests/mcp-server.test.ts | 95 ++++++++++++ 11 files changed, 552 insertions(+), 114 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d17678..00143bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ --- +## 0.2.7 + +- SDK `runBatch`、CLI `batch` 和 MCP `run_batch` 支持在计划或步骤的 `layer` 中指定多个命名层。多层步骤按 `id@layer` 报告,`after` 等待前置步骤的所有实例成功,整个批次共享并发上限。 +- 批次启动前拒绝重复层名、展开后的 ID 冲突和可能覆盖同一本地文件的多层下载。MCP 文本模式按展开实例和实际采集的输出流分摊预算。 + ## 0.2.6 - Docker 镜像补齐本地执行所需的 Bash,默认 MCP 层可直接执行命令。 diff --git a/docs/skills/SKILL.en.md b/docs/skills/SKILL.en.md index e2b8cd3..d9ba4c7 100644 --- a/docs/skills/SKILL.en.md +++ b/docs/skills/SKILL.en.md @@ -1,6 +1,6 @@ --- name: filaxis-runtime -version: 0.2.6 +version: 0.2.7 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,9 +58,10 @@ 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. -- **Layer targeting precedence**: Top-level `layer` sets the batch default; per-step `layer` overrides only that step; omitting both uses the active default layer. `filaxis batch --request-file plan.json` shares the same precedence (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). +- **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. -- **Cross-batch coordination**: `after` applies within a single batch. Serialize concurrent batches modifying the same resource externally (e.g., keyed by environment identity + file path). +- **Resource coordination**: `after` references the original step IDs declared in the same batch. Fan-out executes once per layer name, and different names may point to the same environment. Serialize operations that modify the same resource using its environment identity and file path. - **Text vs. structured output**: `run_batch` text previews share 4 KiB across streams and cap at 8 KiB total (prioritizing failed steps and edit guarantees). Clients that only read text blocks can pass `output: "text"`; use the default `output: "full"` to read full `structuredContent`. `run_command` previews up to 8 KiB per stream. - **Start working right after connecting**: Do not waste turns running `hostname` or `list_layers` after `push_ssh`/`push_into` — the first `run_command`'s exit code and output confirm the layer. - **Targeted file reading & minimal edits**: Inspect specific line ranges or recent logs (`sed -n '20,40p' ` or `docker logs --tail 30 `). For `edit_file`, copy only the exact target lines with minimal unique context into `old`. diff --git a/docs/skills/SKILL.md b/docs/skills/SKILL.md index 52879f7..2c0154c 100644 --- a/docs/skills/SKILL.md +++ b/docs/skills/SKILL.md @@ -1,6 +1,6 @@ --- name: filaxis-runtime -version: 0.2.6 +version: 0.2.7 description: | 牵丝 Filaxis 远程执行运行时的技能剧本总入口——选型决策树(exec 还是观察还是会话)+ 核心契约速查 + 四份场景剧本索引。 @@ -47,10 +47,11 @@ filaxis exec --layer <名> --timeout 8000 -- "(printf 'PING **MCP 形态实战指引**(第十二季盲测 B 组教训): - **定位/巡检期用 `run_batch` 打包**——多个 read_file/run_command 一次调用并行 执行(B 组逐个调 18 步 vs CLI 组打包 11 步——这是 MCP 形态省步数的最大杠杆); -- `run_batch` 的顶层 `layer` 和步骤 `layer` 可以同时传。顶层是批次默认值,步骤的 `layer` 只覆盖本步。两处都省略的步骤使用调用时的默认层。结果逐步标明命名层。 +- `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`,全省略时使用本机。 +- 层名数组只查已注册或保存的层。SDK 可用 `stack.addLayer("local", { driver: "local" })` 把本机加入命名层;CLI 和独立 MCP 服务的本机默认目标不会自动注册为 `local`。 - `max_parallel` 是整个批次的并发上限。无依赖的步骤可以并行,包括同层的独立巡检。需要先改配置、再验证、最后重载时,用 `after` 引用前置步骤的 `id`。依赖可以跨层,前置步骤成功后才会启动后续步骤。 -- `after` 的作用域是当前批次。多个批次可能同时修改同一资源时,由调用方按实际资源串行化,例如用「环境身份 + 配置路径」作为互斥键。同一环境可能有多个层名。`run_batch` 本身不提供跨批次资源锁。 +- `after` 引用当前批次计划里声明的原始步骤 ID。同一环境可能有多个层名,扇出按层名各执行一次。多个步骤或批次可能同时修改同一资源时,由调用方按实际资源串行化,例如用「环境身份 + 配置路径」作为互斥键。 - `run_batch` 文本逐步展示状态、退出码、编辑的写入方式和锁状态,以及 stdout/stderr 预览。所有输出流共用 4 KiB,整个文本字段序列化后最多 8 KiB,超出时优先显示失败步骤和编辑保障。只看文本块的 MCP 客户端请传 `output: "text"`。需要完整输出时用默认的 `output: "full"`,从 `structuredContent` 取。`run_command` 的文本各流最多预览 8 KiB。 - `output: "text"` 在本机和 SSH 层按预算采集 `exec` / `read` 预览,并继续读取完成哨兵来核实退出码。SSH 文件中转仍在磁盘接收完整输出,回读只取有界的首尾。其他层需要支持限量采集才能在文本模式下执行这些步骤。 - 建链后立即干活,**不要**逐个 hostname/list_layers 验证——首个 run_command diff --git a/package.json b/package.json index 5782261..9adc079 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@syrkos/filaxis", - "version": "0.2.6", + "version": "0.2.7", "description": "牵丝 Filaxis — 面向自动化与 Agent 的远程执行运行时 SDK(Syrkos · 漩核)。千里一线,执行有迹。", "type": "module", "license": "Apache-2.0", diff --git a/src/agent-toolkit.ts b/src/agent-toolkit.ts index ec83035..80e3fbf 100644 --- a/src/agent-toolkit.ts +++ b/src/agent-toolkit.ts @@ -15,7 +15,7 @@ import type { 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 BatchStepWithDeps } from "./batch.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"; @@ -80,7 +80,7 @@ export interface AgentToolHandlers { }>; remove_layer(args: { name: string; destroy?: boolean }): Promise<{ removed: string }>; // ── 批次组合(第十一季:一次调用描述多原子操作——减少 Planner 轮次)── - run_batch(args: { steps: Array>; stop_on_fail?: boolean; max_parallel?: number; layer?: string; output?: "text" | "full" }): Promise<{ + run_batch(args: { steps: Array>; stop_on_fail?: boolean; max_parallel?: number; layer?: BatchLayerTarget; output?: "text" | "full" }): Promise<{ status: "ok" | "fail"; failed_step?: string; steps: Array<{ id: string; layer?: string; kind: string; status: string; exit_code?: number; outcome?: "unknown"; stdout?: string; stderr?: string; error?: string; skipped_because?: string; @@ -118,6 +118,15 @@ const fileTransferProperties = { timeout_ms: { type: "integer", minimum: 1, maximum: 2147483647, description: "每次 SSH 命令或 SFTP 进程的超时毫秒数,缺省 120000" }, }; +const layerNameSchema = { type: "string", minLength: 1, pattern: "\\S" }; +const batchLayerSchema = (description: string) => ({ + anyOf: [ + layerNameSchema, + { type: "array", minItems: 1, uniqueItems: true, items: layerNameSchema }, + ], + description, +}); + /** 工具定义单一来源(REQ-0003 MCP tools/list 同源序列化——零漂移) */ export const TOOL_DEFS: AgentToolDef[] = [ // run_batch 置顶(第十三季黑盒实测:Lazy schema 按序读 6 个基础 @@ -129,9 +138,10 @@ export const TOOL_DEFS: AgentToolDef[] = [ name: "run_batch", description: "批次组合:一次调用描述多个文件或命令操作(exec/edit/read/put/get),按依赖边(after)拓扑执行——" + - "步骤 layer 可覆盖批次 layer;after 可跨层引用步骤 id。无依赖步骤并行,顺序链靠 after 显式保序;默认任一步失败即停(未启动步骤标 " + - "skipped)。返回逐步骤状态与证据(退出码/输出/编辑明细)。**不做自动回滚**(配置恢复≠运行" + - "状态回滚——重载可能已产生外部副作用),失败现场交回调用方决策。", + "批次与步骤 layer 均支持层名或层名数组。多个层名按 id@layer 展开,单个层名保留原 id;kind=get 只接受单层。" + + "after 引用计划中声明的步骤 id,等待该步骤在所有目标层成功。" + + "无依赖步骤并行,顺序链靠 after 显式保序;默认任一步失败即停(未启动步骤标 skipped)。返回逐步骤状态与证据(退出码/输出/编辑明细)。" + + "**不做自动回滚**(配置恢复≠运行状态回滚——重载可能已产生外部副作用),失败现场交回调用方决策。", parameters: { type: "object", additionalProperties: false, @@ -147,7 +157,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ ...fileTransferProperties, id: { type: "string", description: "步骤唯一 id(after 引用用)" }, kind: { type: "string", enum: BATCH_STEP_KINDS }, - layer: { type: "string", minLength: 1, description: "当前步骤的目标层名,覆盖批次默认层" }, + layer: batchLayerSchema("覆盖批次默认层。多个层名按 id@layer 展开,单元素数组保留原 id;kind=get 只接受单层"), command: { type: "string", description: "kind=exec:shell 命令" }, expect_exit: { type: "array", items: { type: "number" }, description: "kind=exec:预期退出码集合(缺省 [0])" }, timeout_ms: { type: "number", description: "kind=exec:超时毫秒" }, @@ -173,7 +183,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ }, stop_on_fail: { type: "boolean", description: "失败即停(缺省 true)" }, max_parallel: { type: "number", description: "并行度上限(缺省 3)" }, - layer: { type: "string", minLength: 1, description: "批次默认目标层名(缺省=调用时的默认层)" }, + layer: batchLayerSchema("批次默认目标层名或层名数组(缺省=调用时的默认层;传数组时未覆盖 layer 的步骤自动展开到各层并行执行)"), output: { type: "string", enum: ["text", "full"], description: "MCP 输出模式。text 适合只读文本块的客户端,保留简短预览;full(默认)另在 structuredContent 保留完整输出" }, }, required: ["steps"], @@ -185,7 +195,7 @@ export const TOOL_DEFS: AgentToolDef[] = [ function: { name: "run_command", description: - "执行会自行结束的一次性命令(多条命令/多文件操作请改用 run_batch 一次并行打包;" + + "执行会自行结束的一次性命令(多条命令或多文件操作请用 run_batch;同一命令发往多个层时可传 layer 数组;" + "持续盯实时输出且不关心退出码的命令如 tail -f 请改用 observe_stream 直接启动并流式读取;" + "需后台起停服务、等就绪标记并核实进程退出码的任务请改用 spawn_and_observe)。" + "退出码如实返回(非零不是异常——是数据,供条件分支);只有无法执行(超时/中断/连接死)才报错。stdout 与 stderr 分离返回。", @@ -541,6 +551,9 @@ export function createAgentToolkit(stack: RuntimeStack, opts: AgentToolkitOption get layer(): Promise { return layer(); }, // 惰性 getter(失败不缓存+注册命名表——Hydrogen R7 #4) handlers: { async run_command({ command, timeout_ms, layer: layerName }) { + if (Array.isArray(layerName)) { + throw new Error("run_command 的 layer 仅支持单个层名;同一命令发往多个层请改用 run_batch 并传 layer 数组"); + } const drv = await resolveDrv(layerName); const r = await drv.exec(command, { timeoutMs: timeout_ms }); return { diff --git a/src/batch.ts b/src/batch.ts index 4213438..1632a51 100644 --- a/src/batch.ts +++ b/src/batch.ts @@ -69,13 +69,28 @@ export interface BatchGetStep extends BatchFileTransferStep { export type BatchStep = BatchExecStep | BatchEditStep | BatchReadStep | BatchPutStep | BatchGetStep; export const BATCH_STEP_KINDS = ["exec", "edit", "read", "put", "get"] as const satisfies readonly BatchStep["kind"][]; +/** 目标层:单个层名或同步展开到多个层的层名数组 */ +export type BatchLayerTarget = string | string[]; + /** 依赖边:after 列出的步骤全部 ok 后才启动;无 after = 就绪即可并行 */ -export type BatchStepWithDeps = BatchStep & { after?: string[]; layer?: string }; +export type BatchStepWithDeps = BatchStep & { after?: string[]; layer?: BatchLayerTarget }; + +type ResolvedBatchStep = BatchStep & { layer?: string }; + +interface BatchStepGroup { + order: number; + after: string[]; + steps: ResolvedBatchStep[]; + dependents: BatchStepGroup[]; + pendingDependencies: number; + pendingSuccesses: number; + nextStep: number; +} export interface BatchPlan { steps: BatchStepWithDeps[]; - /** 默认命名层。步骤可覆盖;命名层需要传入层解析函数。 */ - layer?: string; + /** 默认命名层(支持数组扇出)。步骤可覆盖;命名层需要传入层解析函数。 */ + layer?: BatchLayerTarget; /** 失败即停(缺省 true——未启动步骤标 skipped) */ stopOnFail?: boolean; /** 并行度上限(缺省 3;exec 通道每并行步一条 ssh 子进程) */ @@ -134,36 +149,61 @@ export async function runBatch( // 绕过 CLI 的消费方拿到「成功执行了零个步骤」的假成功) throw new Error(`批次计划非法:steps 需非空数组(kind 可为 ${BATCH_STEP_KINDS.join("、")})`); } - if (plan.layer !== undefined && !nonEmptyString(plan.layer)) throw new Error("批次计划非法:layer 需非空字符串"); + const planLayers = validateLayerTarget(plan.layer, "layer"); if (plan.stopOnFail !== undefined && typeof plan.stopOnFail !== "boolean") throw new Error("stopOnFail 需为布尔值"); - const byId = new Map(); - for (const [index, s] of plan.steps.entries()) { - if (!nonEmptyString(s?.id)) throw new Error(`批次计划非法:steps[${index}].id 需非空字符串`); - if (byId.has(s.id)) throw new Error(`批次计划非法:id 重复 '${s.id}'`); - // kind 前置校验(Sol 55 P2-E):未知 kind 曾在 runStep 执行中才抛——计划里 - // 合法步骤已跑过(exec 已执行)才报未知类型。零副作用阶段拦死 - if (!BATCH_STEP_KINDS.includes(s.kind)) { - throw new Error(`批次计划非法:未知 kind '${s.kind}'(合法: ${BATCH_STEP_KINDS.join("、")})`); + const groups = new Map(); + const expandedSteps: ResolvedBatchStep[] = []; + const expandedIds = new Set(); + for (const [index, step] of plan.steps.entries()) { + if (!nonEmptyString(step?.id)) throw new Error(`批次计划非法:steps[${index}].id 需非空字符串`); + if (groups.has(step.id)) throw new Error(`批次计划非法:id 重复 '${step.id}'`); + if (!BATCH_STEP_KINDS.includes(step.kind)) { + throw new Error(`批次计划非法:未知 kind '${step.kind}'(合法: ${BATCH_STEP_KINDS.join("、")})`); } - validateStep(s); - byId.set(s.id, s); + const targetLayers = validateStep(step) ?? planLayers ?? [undefined]; + if (step.kind === "get" && targetLayers.length > 1) { + throw new Error(`批次计划非法:步骤 '${step.id}' 的 kind='get' 不支持多个目标层(并发下载会覆盖同一 local_path),请拆分为独立步骤`); + } + const { after: dependencies, ...operation } = step; + 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) => { + const id = targetLayers.length === 1 ? step.id : `${step.id}@${layer}`; + if (expandedIds.has(id)) throw new Error(`批次计划非法:展开后的步骤 id 冲突 '${id}'`); + expandedIds.add(id); + return { ...operation, id, layer }; + }); + for (const instance of steps) expandedSteps.push(instance); + const after = [...new Set(dependencies)]; + groups.set(step.id, { + order: index, after, steps, dependents: [], + pendingDependencies: after.length, pendingSuccesses: steps.length, nextStep: 0, + }); } - for (const s of plan.steps) { - for (const dep of s.after ?? []) { - if (!byId.has(dep)) throw new Error(`批次计划非法:步骤 '${s.id}' 的 after 引用未知步骤 '${dep}'`); + + const roots: BatchStepGroup[] = []; + for (const [id, group] of groups) { + if (group.steps.length > 1 && expandedIds.has(id)) { + throw new Error(`批次计划非法:展开后的步骤 id 冲突 '${id}'`); } + for (const dep of group.after) { + const prerequisite = groups.get(dep); + if (!prerequisite) throw new Error(`批次计划非法:步骤 '${id}' 的 after 引用未知步骤 '${dep}'`); + prerequisite.dependents.push(group); + } + if (group.pendingDependencies === 0) roots.push(group); } - // 环检测(DFS 三色) - const color = new Map(); // 1=在途 2=完成 - const visit = (id: string, trail: string[]): void => { - const c = color.get(id); - if (c === 1) throw new Error(`批次计划非法:依赖环(${[...trail, id].join(" → ")})`); - if (c === 2) return; - color.set(id, 1); - for (const dep of byId.get(id)!.after ?? []) visit(dep, [...trail, id]); - color.set(id, 2); - }; - for (const s of plan.steps) visit(s.id, []); + // Validate the logical DAG without expanding dependency edges between instances. + const ordered = roots.slice(); + const remaining = new Map(); + for (const group of ordered) { + for (const dependent of group.dependents) { + const count = (remaining.get(dependent) ?? dependent.pendingDependencies) - 1; + remaining.set(dependent, count); + if (count === 0) ordered.push(dependent); + } + } + if (ordered.length !== groups.size) throw new Error("批次计划非法:存在依赖环"); // ── 执行(就绪并行 + fail-fast)── const reports = new Map(); @@ -175,92 +215,109 @@ export async function runBatch( throw new Error(`maxParallel 非法(${plan.maxParallel})——须为 ≥1 的数字`); } const maxParallel = Math.floor(rawP); - const layerFor = (step: BatchStepWithDeps) => step.layer ?? plan.layer; - const names = new Set(plan.steps.map(layerFor)); + const { previewBudgetBytes } = options; + if (previewBudgetBytes !== undefined && (!Number.isSafeInteger(previewBudgetBytes) || previewBudgetBytes < 0)) { + throw new Error("previewBudgetBytes 需为非负整数"); + } + const names = new Set(expandedSteps.map((s) => s.layer)); const drivers = new Map(); if (typeof target === "function") { for (const name of names) { if (name !== undefined) drivers.set(name, await target(name)); } if (names.has(undefined)) drivers.set(undefined, await target()); + for (const [name, driver] of drivers) { + if (!driver) throw new Error(`批次计划非法:未解析到运行层 '${name ?? "(默认)"}'`); + } } else { if ([...names].some((name) => name !== undefined)) throw new Error("批次计划指定了 layer,需要层解析函数"); drivers.set(undefined, target); } - const { previewBudgetBytes } = options; let previewBytes: number | undefined; if (previewBudgetBytes !== undefined) { - if (!Number.isSafeInteger(previewBudgetBytes) || previewBudgetBytes < 0) throw new Error("previewBudgetBytes 需为非负整数"); let streams = 0; - for (const step of plan.steps) { + for (const step of expandedSteps) { if (step.kind !== "exec" && step.kind !== "read") continue; - const driver = drivers.get(layerFor(step))!; - if (!driver.supportsBoundedExec && !(step.kind === "read" && driver.fs.readFilePreview)) { + const driver = drivers.get(step.layer)!; + const nativeRead = step.kind === "read" && typeof driver.fs.readFilePreview === "function"; + if (!nativeRead && !driver.supportsBoundedExec) { throw new Error(`步骤 '${step.id}' 的运行层不支持限制输出采集,请使用 full 模式`); } - streams += step.kind === "exec" ? 2 : 1; + streams += nativeRead ? 1 : 2; } previewBytes = Math.floor(previewBudgetBytes / Math.max(1, streams)); } - const stepIdentity = (step: BatchStepWithDeps) => { - const layer = layerFor(step); - return { id: step.id, kind: step.kind, ...(layer !== undefined ? { layer } : {}) }; - }; + const stepIdentity = (step: ResolvedBatchStep) => ({ + id: step.id, + kind: step.kind, + ...(step.layer !== undefined ? { layer: step.layer } : {}), + }); let failedStep: string | undefined; - const done = (id: string): boolean => reports.get(id)?.status === "ok"; - const ready = (): BatchStepWithDeps[] => - plan.steps.filter((s) => !reports.has(s.id) && (s.after ?? []).every(done)); + // Prefer earlier eligible steps as before, with a heap of ready group heads. + const ready = roots.slice(); + const enqueue = (group: BatchStepGroup): void => { + let index = ready.length; + while (index > 0) { + const parent = Math.floor((index - 1) / 2); + if (ready[parent]!.order < group.order) break; + ready[index] = ready[parent]!; + index = parent; + } + ready[index] = group; + }; + const removeHead = (): void => { + const last = ready.pop()!; + if (!ready.length) return; + let index = 0; + while (index * 2 + 1 < ready.length) { + let child = index * 2 + 1; + if (ready[child + 1] && ready[child + 1]!.order < ready[child]!.order) child++; + if (last.order < ready[child]!.order) break; + ready[index] = ready[child]!; + index = child; + } + ready[index] = last; + }; - for (;;) { - if (failedStep && stopOnFail) { - // fail-fast:未启动步骤全标 skipped;已启动的并行兄弟照常等完成(其结果已记录) - for (const s of plan.steps) { - if (!reports.has(s.id)) { - reports.set(s.id, { - ...stepIdentity(s), status: "skipped", - skippedBecause: `批次失败于 '${failedStep}'(fail-fast)`, - }); + const inflight = new Set>(); + const pull = (): void => { + while (ready.length && inflight.size < maxParallel && !(failedStep && stopOnFail)) { + const group = ready[0]!; + const step = group.steps[group.nextStep++]!; + if (group.nextStep === group.steps.length) removeHead(); + const task = runStep(drivers.get(step.layer)!, step, previewBytes).then((report) => { + reports.set(step.id, { ...stepIdentity(step), ...report }); + if (report.status === "fail") { + failedStep ??= step.id; + } else if (--group.pendingSuccesses === 0) { + for (const dependent of group.dependents) { + if (--dependent.pendingDependencies === 0) enqueue(dependent); + } } - } - break; - } - // 工作池调度(Hydrogen R4 #4):曾按批 Promise.all=波次屏障——同批 1 个慢 - // 步骤拖住全部空槽、就绪的后续步骤干等。改为 N worker 竞争拉取:完成即补位 - const running = new Set(); - const inflight = new Set>(); - const pull = (): void => { - while (inflight.size < maxParallel) { - if (failedStep && stopOnFail) return; - const next = ready().find((st) => !running.has(st.id)); - if (!next) return; - running.add(next.id); - const t = runStep(drivers.get(layerFor(next))!, next, previewBytes).then((r) => { - reports.set(next.id, { ...stepIdentity(next), ...r }); - if (r.status === "fail" && !failedStep) failedStep = next.id; - }).finally(() => { - inflight.delete(t); - pull(); // 完成即补位(空闲槽立即吃下一个就绪步骤) - }); - inflight.add(t); - } - }; - pull(); - while (inflight.size > 0) await Promise.all([...inflight]); - // fail-fast 已触发 → 回循环头统一标 skipped(保留原 fail-fast 文案语义) - if (failedStep && stopOnFail) continue; - // 池收尾后仍无报告的步骤=被失败依赖卡死(stopOnFail=false 路径) - const stuck = plan.steps.filter((s) => !reports.has(s.id)); - for (const s of stuck) { - reports.set(s.id, { - ...stepIdentity(s), status: "skipped", - skippedBecause: `依赖步骤未 ok(${(s.after ?? []).filter((d) => !done(d)).join(", ")})`, + }).finally(() => { + inflight.delete(task); + pull(); }); + inflight.add(task); + } + }; + pull(); + while (inflight.size) await Promise.all([...inflight]); + + for (const group of groups.values()) { + const skipped = group.steps.filter((step) => !reports.has(step.id)); + if (!skipped.length) continue; + const skippedBecause = failedStep && stopOnFail + ? `批次失败于 '${failedStep}'(fail-fast)` + : `依赖步骤未 ok(${group.after.flatMap((dep) => groups.get(dep)!.steps + .filter((step) => reports.get(step.id)?.status !== "ok").map((step) => step.id)).join(", ")})`; + for (const step of skipped) { + reports.set(step.id, { ...stepIdentity(step), status: "skipped", skippedBecause }); } - break; } - const steps = plan.steps.map((s) => reports.get(s.id)!); + const steps = expandedSteps.map((s) => reports.get(s.id)!); return { status: failedStep ? "fail" : "ok", steps, failedStep }; } @@ -268,38 +325,66 @@ function nonEmptyString(value: unknown): value is string { return typeof value === "string" && value.trim().length > 0; } -function validateStep(step: BatchStepWithDeps): void { +function validateLayerTarget(value: unknown, label: string): string[] | undefined { + if (value === undefined) return undefined; + if (typeof value === "string") { + if (!nonEmptyString(value)) { + throw new Error(`批次计划非法:${label} 需为非空字符串或非空字符串数组`); + } + return [value]; + } + if (Array.isArray(value)) { + if (value.length === 0) { + throw new Error(`批次计划非法:${label} 需为非空字符串或非空字符串数组`); + } + const seen = new Set(); + for (const name of value) { + if (!nonEmptyString(name)) { + throw new Error(`批次计划非法:${label} 需为非空字符串或非空字符串数组`); + } + if (seen.has(name)) { + throw new Error(`批次计划非法:${label} 含重复层名 '${name}'`); + } + seen.add(name); + } + return [...seen]; + } + throw new Error(`批次计划非法:${label} 需为非空字符串或非空字符串数组`); +} + +function validateStep(step: BatchStepWithDeps): string[] | undefined { const invalid = (field: string, expected: string): never => { throw new Error(`批次计划非法:步骤 '${step.id}' 的 ${field} ${expected}`); }; - if (step.layer !== undefined && !nonEmptyString(step.layer)) invalid("layer", "需非空字符串"); - if (step.after !== undefined && (!Array.isArray(step.after) || !step.after.every(nonEmptyString))) { + const stepLayers = validateLayerTarget(step.layer, `步骤 '${step.id}' 的 layer`); + if (step.after !== undefined && (!Array.isArray(step.after) || ![...step.after].every(nonEmptyString))) { invalid("after", "需为步骤 id 数组"); } if (step.kind === "exec") { if (!nonEmptyString(step.command)) invalid("command", "需非空字符串"); if (step.timeoutMs !== undefined && (!Number.isFinite(step.timeoutMs) || step.timeoutMs <= 0)) invalid("timeout_ms/timeoutMs", "需为正数"); - if (step.expectExit !== undefined && (!Array.isArray(step.expectExit) || !step.expectExit.every(Number.isSafeInteger))) { + if (step.expectExit !== undefined && (!Array.isArray(step.expectExit) || ![...step.expectExit].every(Number.isSafeInteger))) { invalid("expect_exit/expectExit", "需为整数数组"); } - return; + return stepLayers; } if (step.kind === "put" || step.kind === "get") { try { validateFileTransferFields(step.kind, step); } catch (error) { invalid("传输参数", (error as Error).message); } - return; + return stepLayers; } if (!nonEmptyString(step.path)) invalid("path", "需非空字符串"); if (step.kind === "edit") { - if (!Array.isArray(step.hunks) || !step.hunks.length || !step.hunks.every((h) => + if (!Array.isArray(step.hunks) || !step.hunks.length || ![...step.hunks].every((h) => typeof h?.old === "string" && h.old.length > 0 && typeof h.new === "string" && (h.all === undefined || typeof h.all === "boolean"))) { invalid("hunks", "需为非空数组,每项须含非空字符串 old、字符串 new,以及可选布尔值 all"); } if (step.writeMode !== undefined && step.writeMode !== "auto" && step.writeMode !== "inplace") invalid("write_mode/writeMode", "须为 auto 或 inplace"); } + return stepLayers; } -async function runStep(drv: RuntimeDriver, s: BatchStepWithDeps, previewBytes?: number): Promise { +async function runStep(drv: RuntimeDriver, s: ResolvedBatchStep, previewBytes?: number): Promise { const startedAt = Date.now(); const base = { id: s.id, kind: s.kind, startedAt }; try { @@ -337,7 +422,7 @@ async function runStep(drv: RuntimeDriver, s: BatchStepWithDeps, previewBytes?: let content: string; if (previewBytes === undefined) { content = await drv.fs.readFile(s.path); - } else if (drv.fs.readFilePreview) { + } else if (typeof drv.fs.readFilePreview === "function") { content = await drv.fs.readFilePreview(s.path, previewBytes); } else { const path = shellQuote(s.path); diff --git a/src/index.ts b/src/index.ts index acdb5b9..1a5f835 100644 --- a/src/index.ts +++ b/src/index.ts @@ -40,6 +40,6 @@ export { editFile, editFileMulti, EditConflictError } from "./file-edit.js"; export type { EditFileOptions, EditFileResult, EditFileMultiResult, EditMultiHunk } from "./file-edit.js"; export { runBatch } from "./batch.js"; export type { - BatchPlan, BatchStep, BatchStepWithDeps, BatchExecStep, BatchEditStep, BatchReadStep, BatchPutStep, BatchGetStep, + BatchPlan, BatchLayerTarget, BatchStep, BatchStepWithDeps, BatchExecStep, BatchEditStep, BatchReadStep, BatchPutStep, BatchGetStep, BatchReport, BatchStepReport, BatchStepStatus, } from "./batch.js"; diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 558c7b5..a965e8b 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -136,7 +136,7 @@ export class McpServer { // 几个基础 schema 就动手——高杠杆组合工具被藏视野外。instructions // 在任何 schema 读取之前必达,是唯一可靠的发现面) instructions: [ - "【先看这行】多文件读取/多命令巡检/定位排查 → 优先 run_batch(一次调用并行打包,不要逐个工具循环);读工具 schema 时同轮并发读取(逐个读每步一趟 LLM);", + "【先看这行】多文件读取/多命令巡检/同命令发往多层/定位排查 → 优先 run_batch(一次调用并行打包,支持传 layer 数组自动扇出,不要逐个工具循环);读工具 schema 时同轮并发读取(逐个读每步一趟 LLM);", "持续查看日志 → observe_stream 开窗、read_stream 回看或续读、close_stream 关闭;等就绪或错误模式 → spawn_and_observe;", "edit_file 支持 write_mode:'inplace'(bind mount 保 inode 免重启);", "在 MCP 服务主机与目标层之间传输文件用 put_file 和 get_file。", diff --git a/tests/batch.test.ts b/tests/batch.test.ts index 4996875..4305948 100644 --- a/tests/batch.test.ts +++ b/tests/batch.test.ts @@ -7,7 +7,7 @@ import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from "no import { tmpdir } from "node:os"; import { join } from "node:path"; import { LocalRuntimeDriver } from "../src/local-driver.js"; -import { runBatch, editFileMulti } from "../src/index.js"; +import { runBatch, editFileMulti, type RuntimeDriver } from "../src/index.js"; import { createAgentToolkit } from "../src/agent-toolkit.js"; import { RuntimeStack } from "../src/runtime-stack.js"; @@ -218,3 +218,239 @@ test("空 steps → 显式拒绝(内核级守卫,不再只靠 CLI)", async await expect(runBatch(drv, { steps: [] })).rejects.toThrow(/steps 需非空/); await expect(runBatch(drv, {} as never)).rejects.toThrow(/steps 需非空/); }); + +describe("runBatch layer 数组扇出", () => { + function makeMockResolver( + execImpl: (layer: string, command: string) => Promise<{ stdout: string; stderr: string; exitCode: number }>, + missing: Set = new Set(), + ) { + const calls: string[] = []; + const drivers = new Map(); + const resolve = async (layer?: string): Promise => { + const name = layer ?? "__default__"; + if (missing.has(name)) throw new Error(`层 '${name}' 不存在`); + if (!drivers.has(name)) { + drivers.set(name, { + descriptor: { driver: "mock", target: name }, + supportsBoundedExec: true, + async exec(command: string) { + calls.push(`${name}:${command}`); + return execImpl(name, command); + }, + } as unknown as RuntimeDriver); + } + return drivers.get(name)!; + }; + return { resolve, calls }; + } + + test("步骤级 layer 数组按 id@layer 展开并行,stopOnFail=false 时兄弟层继续执行", async () => { + const { resolve, calls } = makeMockResolver(async (layer, cmd) => ({ + stdout: `${layer}:${cmd}`, + stderr: layer === "b" ? "boom" : "", + exitCode: layer === "b" ? 2 : 0, + })); + const r = await runBatch(resolve, { + stopOnFail: false, + steps: [ + { id: "check", kind: "exec", layer: ["a", "b", "c"], command: "uptime" }, + ], + }); + expect(r.status).toBe("fail"); + expect(r.failedStep).toBe("check@b"); + expect(r.steps.map((s) => ({ id: s.id, layer: s.layer, status: s.status, exitCode: s.exitCode }))).toEqual([ + { id: "check@a", layer: "a", status: "ok", exitCode: 0 }, + { id: "check@b", layer: "b", status: "fail", exitCode: 2 }, + { id: "check@c", layer: "c", status: "ok", exitCode: 0 }, + ]); + expect(calls).toHaveLength(3); + }); + + test("计划级 layer 数组扇出未覆盖步骤,步骤覆盖单层时保留原 id", async () => { + const { resolve, calls } = makeMockResolver(async (layer, cmd) => ({ + stdout: `${layer}:${cmd}`, + stderr: "", + exitCode: 0, + })); + const r = await runBatch(resolve, { + layer: ["a", "b"], + steps: [ + { id: "probe", kind: "exec", command: "uname -a" }, + { id: "solo", kind: "exec", layer: "c", command: "hostname" }, + ], + }); + expect(r.status).toBe("ok"); + expect(r.steps.map((s) => ({ id: s.id, layer: s.layer, stdout: s.stdout }))).toEqual([ + { id: "probe@a", layer: "a", stdout: "a:uname -a" }, + { id: "probe@b", layer: "b", stdout: "b:uname -a" }, + { id: "solo", layer: "c", stdout: "c:hostname" }, + ]); + expect(calls).toEqual(["a:uname -a", "b:uname -a", "c:hostname"]); + }); + + test("单元素数组 layer: ['a'] 保留原步骤 id(不加 @a 后缀)", async () => { + const { resolve } = makeMockResolver(async (layer) => ({ stdout: layer, stderr: "", exitCode: 0 })); + const r = await runBatch(resolve, { + steps: [{ id: "single", kind: "exec", layer: ["a"], command: "id" }], + }); + expect(r.status).toBe("ok"); + expect(r.steps).toHaveLength(1); + expect(r.steps[0]).toMatchObject({ id: "single", layer: "a", status: "ok", stdout: "a" }); + }); + + test("after 扇入:需等待所有展开实例 ok;部分失败(stopOnFail=false)时下游标 skipped 并指出失败实例", async () => { + const order: string[] = []; + const { resolve } = makeMockResolver(async (layer, cmd) => { + if (cmd === "fan" && layer === "a") await new Promise((r) => setTimeout(r, 30)); + order.push(`${cmd}@${layer}`); + return { stdout: layer, stderr: "", exitCode: 0 }; + }); + const okReport = await runBatch(resolve, { + maxParallel: 2, + steps: [ + { id: "fan", kind: "exec", layer: ["a", "b"], command: "fan" }, + { id: "join", kind: "exec", layer: "c", command: "join", after: ["fan"] }, + ], + }); + expect(okReport.status).toBe("ok"); + expect(order[order.length - 1]).toBe("join@c"); + expect(order.slice(0, 2).sort()).toEqual(["fan@a", "fan@b"]); + + const { resolve: resolveFail, calls: failCalls } = makeMockResolver(async (layer, cmd) => ({ + stdout: `${layer}:${cmd}`, + stderr: "", + exitCode: cmd === "fan" && layer === "b" ? 1 : 0, + })); + const failReport = await runBatch(resolveFail, { + stopOnFail: false, + steps: [ + { id: "fan", kind: "exec", layer: ["a", "b"], command: "fan" }, + { id: "join", kind: "exec", layer: "c", command: "join", after: ["fan"] }, + ], + }); + expect(failReport.status).toBe("fail"); + expect(failCalls).toEqual(["a:fan", "b:fan"]); + const joinStep = failReport.steps.find((s) => s.id === "join")!; + expect(joinStep.status).toBe("skipped"); + expect(joinStep.skippedBecause).toContain("fan@b"); + }); + + test("扇入完成后立即补满并发池,并保持就绪步骤的计划优先级", async () => { + const releaseJoin = Promise.withResolvers(); + const bothStarted = Promise.withResolvers(); + let started = 0; + const { resolve, calls } = makeMockResolver(async (_layer, command) => { + if (command === "join") { + if (++started === 2) bothStarted.resolve(); + await releaseJoin.promise; + } + return { stdout: "", stderr: "", exitCode: 0 }; + }); + const batch = runBatch(resolve, { + maxParallel: 2, + steps: [ + { id: "join", kind: "exec", layer: ["a", "b"], command: "join", after: ["root", "root"] }, + { id: "root", kind: "exec", layer: "c", command: "root" }, + ], + }); + try { + await bothStarted.promise; + expect(calls).toEqual(["c:root", "a:join", "b:join"]); + } finally { + releaseJoin.resolve(); + } + expect((await batch).status).toBe("ok"); + + const { resolve: resolveOrdered, calls: orderedCalls } = makeMockResolver(async () => ({ + stdout: "", stderr: "", exitCode: 0, + })); + await runBatch(resolveOrdered, { + maxParallel: 1, + steps: [ + { id: "join", kind: "exec", layer: ["a", "b"], command: "join", after: ["root"] }, + { id: "root", kind: "exec", layer: "c", command: "root" }, + { id: "last", kind: "exec", layer: "c", command: "last" }, + ], + }); + expect(orderedCalls).toEqual(["c:root", "a:join", "b:join", "c:last"]); + }); + + test("文本预算按 read 的采集通道分摊,exec 回读计入 stderr", async () => { + const limits: Array = []; + const native = { fs: { async readFilePreview(_path: string, limit: number) { + limits.push(limit); + return "native"; + } } } as unknown as RuntimeDriver; + const fallback = { + supportsBoundedExec: true, + fs: {}, + async exec(_command: string, options?: { maxOutputBytes?: number }) { + limits.push(options?.maxOutputBytes); + return { stdout: "fallback", stderr: "", exitCode: 0 }; + }, + } as unknown as RuntimeDriver; + const report = await runBatch((name) => name === "native" ? native : fallback, { + steps: [{ id: "read", kind: "read", path: "/file", layer: ["native", "fallback"] }], + }, { previewBudgetBytes: 300 }); + expect(limits).toEqual([100, 100]); + expect(report.steps.map((step) => step.stdout)).toEqual(["native", "fallback"]); + }); + + test("零副作用校验:空数组/非法元素/重复层名/展开 id 冲突/get 多层/缺失层均在执行前拒绝", async () => { + const { resolve, calls } = makeMockResolver( + async (layer) => ({ stdout: layer, stderr: "", exitCode: 0 }), + new Set(["missing"]), + ); + // 计划级空数组 + await expect(runBatch(resolve, { + layer: [], + steps: [{ id: "s", kind: "exec", command: "echo 1" }], + })).rejects.toThrow(/非空字符串或非空字符串数组/); + // 步骤级空数组 + await expect(runBatch(resolve, { + steps: [{ id: "s", kind: "exec", layer: [], command: "echo 1" }], + })).rejects.toThrow(/非空字符串或非空字符串数组/); + // 非法元素 + await expect(runBatch(resolve, { + steps: [{ id: "s", kind: "exec", layer: ["a", " "], command: "echo 1" }], + })).rejects.toThrow(/非空字符串或非空字符串数组/); + // 重复层名 + await expect(runBatch(resolve, { + steps: [{ id: "s", kind: "exec", layer: ["a", "a"], command: "echo 1" }], + })).rejects.toThrow(/含重复层名 'a'/); + const sparse = new Array(2); + sparse[0] = "a"; + const neverResolve = () => { throw new Error("invalid plan reached the layer resolver"); }; + await expect(runBatch(neverResolve, { + layer: sparse, + steps: [{ id: "s", kind: "exec", command: "echo 1" }], + })).rejects.toThrow(/非空字符串或非空字符串数组/); + // 展开后的 id 冲突 + await expect(runBatch(resolve, { + steps: [ + { id: "check", kind: "exec", layer: ["a", "b"], command: "echo 1" }, + { id: "check@a", kind: "exec", layer: "c", command: "echo 2" }, + ], + })).rejects.toThrow(/展开后的步骤 id 冲突 'check@a'/); + await expect(runBatch(neverResolve, { + steps: [ + { id: "check", kind: "exec", layer: ["a", "b"], command: "echo 1" }, + { id: "check@a", kind: "exec", layer: ["c", "d"], command: "echo 2" }, + ], + })).rejects.toThrow(/展开后的步骤 id 冲突 'check@a'/); + // kind=get 多层拒绝 + await expect(runBatch(resolve, { + steps: [ + { id: "dl", kind: "get", layer: ["a", "b"], localPath: "./out.bin", remotePath: "/tmp/out.bin" }, + ], + })).rejects.toThrow(/kind='get' 不支持多个目标层/); + // 数组中含缺失层:先于任何步骤执行报错(零副作用) + await expect(runBatch(resolve, { + steps: [ + { id: "ok_first", kind: "exec", layer: "a", command: "echo ok" }, + { id: "fan", kind: "exec", layer: ["a", "missing"], command: "echo nope" }, + ], + })).rejects.toThrow(/层 'missing' 不存在/); + expect(calls).toHaveLength(0); + }); +}); diff --git a/tests/integration-ssh.test.ts b/tests/integration-ssh.test.ts index 9bf9688..aea2895 100644 --- a/tests/integration-ssh.test.ts +++ b/tests/integration-ssh.test.ts @@ -760,6 +760,8 @@ describe("第十一季:CLI 层快照(CI 真机)", () => { expect(run({ layer: "root", steps: [first, second] }, "tmp")) .toMatch(/first .*layer=root[^\n]*\n\/\r?\n.*second .*layer=tmp[^\n]*\n\/tmp\r?\nbatch ok/); expect(run({ steps: [first] }, "tmp")).toMatch(/first .*layer=tmp[^\n]*\n\/tmp\r?\nbatch ok/); + const fan = run({ layer: ["root", "tmp"], steps: [first, second] }, "tmp"); + expect(fan).toMatch(/first@root .*layer=root[^\n]*\n\/\r?\n.*first@tmp .*layer=tmp[^\n]*\n\/tmp\r?\n.*second .*layer=tmp[^\n]*\n\/tmp\r?\nbatch ok/); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/tests/mcp-server.test.ts b/tests/mcp-server.test.ts index a73bec4..bab983e 100644 --- a/tests/mcp-server.test.ts +++ b/tests/mcp-server.test.ts @@ -467,3 +467,98 @@ test("MCP opens, reads, and closes a continuous window by ID", async () => { fixture.close(); } }, 20_000); + +describe("MCP layer array fan-out", () => { + test("tools/list exposes string | string[] schema for run_batch layer and step layer", async () => { + const f = mcpFixture(); + try { + f.write({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + const { result } = await waitId(f, 1) as { + result: { tools: Array<{ name: string; inputSchema: { properties: Record } }> }; + }; + const batchTool = result.tools.find((t) => t.name === "run_batch")!; + const expectedAnyOf = [ + { type: "string", minLength: 1, pattern: "\\S" }, + { type: "array", minItems: 1, uniqueItems: true, items: { type: "string", minLength: 1, pattern: "\\S" } }, + ]; + expect(batchTool.inputSchema.properties.layer).toMatchObject({ anyOf: expectedAnyOf }); + const stepsSchema = batchTool.inputSchema.properties.steps as { + items: { properties: Record }; + }; + expect(stepsSchema.items.properties.layer).toMatchObject({ anyOf: expectedAnyOf }); + } finally { f.close(); } + }); + + test("run_batch fans out layer array in full and text modes and divides bounded output budget", async () => { + const stack = new RuntimeStack(); + const first = new LocalRuntimeDriver(); + const second = new LocalRuntimeDriver(); + const maxBytesSeen: number[] = []; + const origFirstExec = first.exec.bind(first); + const origSecondExec = second.exec.bind(second); + first.exec = (cmd, opts) => { + if (opts?.maxOutputBytes !== undefined) maxBytesSeen.push(opts.maxOutputBytes); + return origFirstExec(cmd, opts); + }; + second.exec = (cmd, opts) => { + if (opts?.maxOutputBytes !== undefined) maxBytesSeen.push(opts.maxOutputBytes); + return origSecondExec(cmd, opts); + }; + await stack.addLayer("first", first); + await stack.addLayer("second", second); + const f = mcpFixture(stack); + try { + const steps = [{ id: "fan", kind: "exec", command: "printf 'LINE_%s' 'ok'" }]; + f.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { + name: "run_batch", arguments: { layer: ["first", "second"], steps }, + } }); + const fullRes = (await waitId(f, 1, 20_000)).result as { + isError: boolean; + content: Array<{ text: string }>; + structuredContent: { status: string; steps: Array<{ id: string; layer?: string; stdout?: string }> }; + }; + expect(fullRes.isError).toBe(false); + expect(fullRes.content[0]!.text).toContain("fan@first (exec) | status=ok | layer=first"); + expect(fullRes.content[0]!.text).toContain("fan@second (exec) | status=ok | layer=second"); + expect(fullRes.structuredContent).toMatchObject({ + status: "ok", + steps: [ + { id: "fan@first", layer: "first", stdout: "LINE_ok" }, + { id: "fan@second", layer: "second", stdout: "LINE_ok" }, + ], + }); + + // text mode: 1 exec step across 2 layers = 4 streams → 4096 / 4 = 1024 bytes per stream + const textSteps = [{ id: "bounded", kind: "exec", command: `printf '%s' '${"A".repeat(1500)}'` }]; + f.write({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { + name: "run_batch", arguments: { layer: ["first", "second"], steps: textSteps, output: "text" }, + } }); + const textRes = (await waitId(f, 2, 20_000)).result as { + isError: boolean; + content: Array<{ text: string }>; + }; + expect(textRes.isError).toBe(false); + expect(textRes).not.toHaveProperty("structuredContent"); + expect(maxBytesSeen).toEqual([1024, 1024]); + expect(textRes.content[0]!.text).toContain("bounded@first (exec) | status=ok | layer=first"); + expect(textRes.content[0]!.text).toContain("bounded@second (exec) | status=ok | layer=second"); + expect(textRes.content[0]!.text).toContain("[采集阶段已截断 "); + } finally { + f.close(); + await stack.removeLayer("first", { destroy: true }); + await stack.removeLayer("second", { destroy: true }); + } + }, 30_000); + + test("run_command rejects array layer and points caller to run_batch", async () => { + const f = mcpFixture(); + try { + f.write({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { + name: "run_command", arguments: { command: "echo hi", layer: ["a", "b"] }, + } }); + const res = (await waitId(f, 1)).result as { isError: boolean; content: Array<{ text: string }> }; + expect(res.isError).toBe(true); + expect(res.content[0]!.text).toContain("run_batch"); + } finally { f.close(); } + }); +});