Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(federation): bridge Batonly to MSO and SI-Coder
Rahmanb341b58d4e0a
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 8678dc7d..6945361d 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mso",- "version": "0.2.21",+ "version": "0.2.22","description": "Operate MSO projects, workflows, VPS resources, integrations, deployments, and MCP capabilities through reusable safety-first skills.","author": {"name": "MSO"diff --git a/.env.example b/.env.exampleindex 3596f255..92d8d2b2 100644--- a/.env.example+++ b/.env.example@@ -411,3 +411,13 @@ OS_MCP_MAX_SCOPE=exec# Actions does not read this .env.local file. The standalone target-check command# also accepts the value from its environment. No credentials, query or fragment.# MSO_DAST_URL=https://mso.example.com+++# --- Batonly capability federation (optional) ---+# Start the Batonly pull worker only when this MSO installation has a project+# containing an MCP server alias named "baton". The project hint defaults to "baton".+# Override only when the local project is registered under another exact name/path/id.+# MSO_BATONLY_FEDERATION_PROJECT=baton+# Emergency/instance opt-out. Set 1 to keep the federation worker disabled even when+# the Baton project MCP is configured. Batonly never receives an MSO bearer credential.+# MSO_BATONLY_FEDERATION_DISABLED=0diff --git a/app/api/v1/federation/status/route.ts b/app/api/v1/federation/status/route.tsnew file mode 100644index 00000000..7a4f41fe--- /dev/null+++ b/app/api/v1/federation/status/route.ts@@ -0,0 +1,13 @@+import { NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { getBatonlyFederationWorkerStatus } from "@/lib/mcp/federation/batonly-worker";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++export async function GET(req: Request) {+ if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ return NextResponse.json(getBatonlyFederationWorkerStatus(), {+ headers: { "Cache-Control": "no-store" },+ });+}diff --git a/docs/BATONLY-FEDERATION.md b/docs/BATONLY-FEDERATION.mdnew file mode 100644index 00000000..993791a2--- /dev/null+++ b/docs/BATONLY-FEDERATION.md@@ -0,0 +1,66 @@+# Batonly capability federation worker++Snapshot: 22 September 2026++MSO can act as Batonly's approved pull worker without giving Batonly an MSO bearer credential. This is the execution bridge for Batonly's Composio-like integration surface while Baton remains the project-management/evidence authority.++## Runtime direction++The worker is opt-in by project configuration, not a host-global requirement.++- It starts only when MSO can resolve the configured Batonly project and that exact project has an MCP server alias named `baton`.+- `MSO_BATONLY_FEDERATION_DISABLED=1` disables it explicitly.+- Generic MSO installations with no Batonly project/MCP remain idle.+- The worker uses the existing project MCP credential boundary. It never accepts a remote endpoint/token from a Batonly execution request.++## Protocol++The Baton MCP side provides:++- `baton_federation_requests_list` with `pendingOnly=true`+- `baton_federation_request_claim`+- `baton_federation_request_complete`+- `baton_federation_request_fail`+- `baton_federation_worker_heartbeat`++Polling is bounded (10 seconds base, exponential backoff up to 60 seconds). Baton owns atomic claim leases and retry attempts. MSO executes at most one claimed request per poll iteration.++## MSO execution++For `source=mso`:++1. Resolve the exact operation from canonical `TOOLS_BY_NAME`.+2. Validate credential-free bounded arguments.+3. Require Batonly's request scope to equal the tool's declared scope.+4. Require explicit confirmation for every write/exec operation.+5. Refuse recursive `project_mcp_call` back into the Baton MCP.+6. Execute through `executeCapabilityCall` with principal `batonly-federation`, preserving required args, rate limits, workflow correlation, activity and audit.+7. Sanitize/bound the result before returning it to Baton.++## SI-Coder execution++The worker resolves the reviewed installed SI-Coder package through MSO's managed installation path. It does not execute command strings supplied by Batonly.++Current live runtime evidence is SI-Coder 0.9.8 with **55 machine functions**, including `sc.flow.list/show/validate/run`. Arguments are validated against the discovered machine function JSON Schema before invocation. `sc.flow.run`, `sc.update`, and `sc.doku.mcp.call` are treated as exec scope; mutating user/provider/memory/recipe/data/mail functions are write scope; remaining functions are read scope.++Provider credentials continue to use SI-Coder/MSO named connections. Federation arguments and results reject/redact credential-shaped keys and secret-like values.++## Operability++- Node instrumentation starts the worker after MSO boot only when the Baton project MCP exists.+- `GET /api/v1/federation/status` is owner-authenticated and no-store, exposing safe worker status only.+- Heartbeats report worker/MSO/SI-Coder versions and capability counts, never credential values.+- The Node executable for portable stdio MCP manifests is resolved to the trusted current `process.execPath`; this avoids scrubbed-service-PATH failures such as `spawn node ENOENT`.++## Acceptance++Do not claim runtime parity until all are true against production Baton:++1. worker heartbeat is fresh;+2. one MSO read completes queue → claim → execute → complete;+3. one SI-Coder read completes the same path;+4. unconfirmed write/exec is rejected;+5. credential-shaped input is rejected;+6. duplicate/invalid claim fails closed;+7. removing/revoking the Baton project MCP connection makes polling fail closed;+8. Batonly reports the completed result and truthful worker availability.diff --git a/docs/README.md b/docs/README.mdindex c2e5b631..f1f67e70 100644--- a/docs/README.md+++ b/docs/README.md@@ -37,6 +37,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`INTEGRATION-PORTABILITY.md`](./INTEGRATION-PORTABILITY.md) | Reviewed JSON identity transfers, encrypted credentials, SC interoperability and receiver limits || [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page || [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs |+| [`BATONLY-FEDERATION.md`](./BATONLY-FEDERATION.md) | Pull-based Batonly capability federation worker, MSO/SI-Coder execution boundary, polling, security and acceptance contract || [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits || [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2 with n8n-core triggers/flow control, versions/history, variables, integrations, visual execution and automatic learning || [`N8N-PARITY.md`](./N8N-PARITY.md) | Core n8n capability map across native Workflows, Organization, Integrations and the dedicated external n8n workspace |diff --git a/instrumentation.ts b/instrumentation.tsindex f7971bfd..5164813a 100644--- a/instrumentation.ts+++ b/instrumentation.ts@@ -19,6 +19,9 @@ export async function register() {Promise.all([import("./lib/workflow/graph-triggers"), import("./lib/mcp/tools"), import("./lib/mcp/capability-runtime")]).then(([{ startWorkflowScheduler }, { TOOLS_BY_NAME }, { msoCapabilityRuntime }]) => startWorkflowScheduler((name) => TOOLS_BY_NAME.get(name), msoCapabilityRuntime)).catch(() => undefined),+ import("./lib/mcp/federation/batonly-worker")+ .then(({ startBatonlyFederationWorker }) => startBatonlyFederationWorker())+ .catch(() => undefined),]);// systemd liveness: when the unit sets WatchdogSec, systemd exposes// NOTIFY_SOCKET + WATCHDOG_USEC. Node has no native AF_UNIX SOCK_DGRAMdiff --git a/lib/federation/security.test.ts b/lib/federation/security.test.tsnew file mode 100644index 00000000..9cca39cc--- /dev/null+++ b/lib/federation/security.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import {+ parseBatonMcpResult,+ safeFederationError,+ safeFederationResult,+ validateFederationArguments,+} from "./security";++describe("Batonly federation security boundary", () => {+ it("accepts bounded metadata and refuses credential-shaped inputs", () => {+ expect(validateFederationArguments({ project: "baton", limit: 5, nested: { dryRun: true } })).toEqual({+ project: "baton",+ limit: 5,+ nested: { dryRun: true },+ });+ expect(() => validateFederationArguments({ api_key: "abc" })).toThrow(/credential-shaped|secret_input_forbidden/i);+ expect(() => validateFederationArguments({ nested: { password: "abc" } })).toThrow(/credential-shaped|secret_input_forbidden/i);+ expect(() => validateFederationArguments({ value: "Bearer abc123" })).toThrow(/credential/i);+ expect(() => validateFederationArguments({ headers: { x: "y" } })).toThrow(/credential-shaped/i);+ });++ it("redacts secret-shaped outputs and bounds error text", () => {+ const safe = safeFederationResult({ ok: true, accessToken: "abc", nested: { api_key: "def" } });+ expect(JSON.parse(safe.json)).toEqual({ ok: true, accessToken: "[redacted]", nested: { api_key: "[redacted]" } });+ expect(safeFederationError(new Error("Bearer abc123"))).toBe("[redacted]");+ });++ it("unwraps Batonly MCP text envelopes", () => {+ expect(parseBatonMcpResult({ content: [{ type: "text", text: JSON.stringify({ ok: true }) }] })).toEqual({ ok: true });+ });+});diff --git a/lib/federation/security.ts b/lib/federation/security.tsnew file mode 100644index 00000000..cf81ca9c--- /dev/null+++ b/lib/federation/security.ts@@ -0,0 +1,96 @@+export const FEDERATION_WORKER_ID = "batonly-federation";+export const MAX_FEDERATION_ARGUMENT_BYTES = 32 * 1024;+export const MAX_FEDERATION_RESULT_BYTES = 64 * 1024;+const MAX_DEPTH = 8;+const MAX_KEYS = 80;+const MAX_ITEMS = 100;+const MAX_STRING = 8192;++const SECRET_VALUE = /^(?:Bearer\s+|Basic\s+|gh[pousr]_|github_pat_|sk-[A-Za-z0-9]|-----BEGIN [A-Z ]*PRIVATE KEY-----|mso_mcp_)/i;+const SENSITIVE_KEYS = new Set([+ "authorization","header","headers","bearer","cookie","credential","credentials",+ "password","passwd","privatekey","secret","secretvalue","token","apikey","apitoken",+ "accesstoken","refreshtoken","clientsecret",+]);+const sensitiveKey = (key: string) => SENSITIVE_KEYS.has(key.replace(/[_.-]/g, "").toLowerCase());++const plainObject = (value: unknown): value is Record<string, unknown> =>+ Boolean(value && typeof value === "object" && !Array.isArray(value));++function encodedBytes(value: unknown) {+ return Buffer.byteLength(JSON.stringify(value), "utf8");+}++function validateValue(value: unknown, path: string, depth: number): void {+ if (depth > MAX_DEPTH) throw new Error("federation arguments are too deeply nested");+ if (value === null || typeof value === "boolean") return;+ if (typeof value === "number") {+ if (!Number.isFinite(value)) throw new Error(`${path} must be a finite number`);+ return;+ }+ if (typeof value === "string") {+ if (value.length > MAX_STRING) throw new Error(`${path} exceeds ${MAX_STRING} characters`);+ if (SECRET_VALUE.test(value.trim())) throw new Error(`${path} looks like a credential; use a named connection`);+ return;+ }+ if (Array.isArray(value)) {+ if (value.length > MAX_ITEMS) throw new Error(`${path} has too many items`);+ value.forEach((item, index) => validateValue(item, `${path}[${index}]`, depth + 1));+ return;+ }+ if (!plainObject(value)) throw new Error(`${path} contains an unsupported value`);+ const entries = Object.entries(value);+ if (entries.length > MAX_KEYS) throw new Error(`${path} has too many fields`);+ for (const [key, item] of entries) {+ if (!key || key.length > 120) throw new Error(`${path} contains an invalid field name`);+ if (sensitiveKey(key)) throw new Error(`${path}.${key} is credential-shaped; use a named connection`);+ validateValue(item, `${path}.${key}`, depth + 1);+ }+}++export function validateFederationArguments(value: unknown): Record<string, unknown> {+ if (!plainObject(value)) throw new Error("federation arguments must be an object");+ validateValue(value, "arguments", 0);+ if (encodedBytes(value) > MAX_FEDERATION_ARGUMENT_BYTES) throw new Error("federation arguments exceed 32 KiB");+ return value;+}++function sanitize(value: unknown, depth = 0): unknown {+ if (depth > MAX_DEPTH) return "[truncated-depth]";+ if (value === null || typeof value === "boolean" || typeof value === "number") return value;+ if (typeof value === "string") {+ if (SECRET_VALUE.test(value.trim())) return "[redacted]";+ return value.length > MAX_STRING ? value.slice(0, MAX_STRING) + "…" : value;+ }+ if (Array.isArray(value)) return value.slice(0, MAX_ITEMS).map((item) => sanitize(item, depth + 1));+ if (!plainObject(value)) return String(value);+ const out: Record<string, unknown> = {};+ for (const [key, item] of Object.entries(value).slice(0, MAX_KEYS)) {+ out[key] = sensitiveKey(key) ? "[redacted]" : sanitize(item, depth + 1);+ }+ return out;+}++export function safeFederationResult(value: unknown): { value: unknown; json: string; truncated: boolean } {+ const safe = sanitize(value);+ let json = JSON.stringify(safe);+ if (Buffer.byteLength(json, "utf8") <= MAX_FEDERATION_RESULT_BYTES) return { value: safe, json, truncated: false };+ const fallback = { truncated: true, summary: "Result exceeded the federation evidence budget." };+ json = JSON.stringify(fallback);+ return { value: fallback, json, truncated: true };+}++export function safeFederationError(error: unknown) {+ const raw = error instanceof Error ? error.message : String(error);+ const clean = String(sanitize(raw));+ return clean.length <= 1000 ? clean : clean.slice(0, 999) + "…";+}++export function parseBatonMcpResult(value: unknown): unknown {+ if (!plainObject(value)) return value;+ const content = value.content;+ if (!Array.isArray(content)) return value;+ const text = content.find((row) => plainObject(row) && row.type === "text" && typeof row.text === "string") as { text?: string } | undefined;+ if (!text?.text) return value;+ try { return JSON.parse(text.text); } catch { return text.text; }+}diff --git a/lib/federation/si-coder-runtime.test.ts b/lib/federation/si-coder-runtime.test.tsnew file mode 100644index 00000000..4865affc--- /dev/null+++ b/lib/federation/si-coder-runtime.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { inspectSiCoderFederationRuntime, siCoderFederationScope } from "./si-coder-runtime";++describe("SI-Coder federation runtime", () => {+ it("classifies current machine functions conservatively", () => {+ expect(siCoderFederationScope("sc.version")).toBe("read");+ expect(siCoderFederationScope("sc.user.create")).toBe("write");+ expect(siCoderFederationScope("sc.doku.mcp.call")).toBe("exec");+ expect(siCoderFederationScope("sc.flow.run")).toBe("exec");+ });++ it("discovers the reviewed installed runtime instead of a shell-provided function list", async () => {+ const runtime = await inspectSiCoderFederationRuntime(process.cwd());+ expect(runtime.version).toMatch(/^0\./);+ expect(runtime.functionCount).toBeGreaterThanOrEqual(55);+ expect(runtime.tools.map((tool) => tool.name)).toEqual(expect.arrayContaining([+ "sc.product.interview",+ "sc.user.connection.manage",+ "sc.doku.mcp.call",+ "sc.flow.run",+ ]));+ });+});diff --git a/lib/federation/si-coder-runtime.ts b/lib/federation/si-coder-runtime.tsnew file mode 100644index 00000000..5a51ec56--- /dev/null+++ b/lib/federation/si-coder-runtime.ts@@ -0,0 +1,120 @@+import os from "node:os";+import path from "node:path";+import { resolveManagedSc } from "@/lib/host/sc-managed";+import { callMcpServerTool, listMcpServerTools } from "@/lib/host/project-mcp-client";+import type { ProjectMcpServer } from "@/lib/host/project-mcp-config";+import { inspectScInstallation } from "@/lib/host/sc-installation.mjs";+import { validateFederationArguments } from "./security";++export type FederationExecutionScope = "read" | "write" | "exec";++const WRITE_FUNCTIONS = new Set([+ "sc.user.create","sc.user.duplicate","sc.user.rename","sc.user.default","sc.user.map","sc.user.unmap","sc.user.delete",+ "sc.user.connection.manage","sc.user.credential.request","sc.user.credential.delete",+ "sc.provider.create","sc.provider.update","sc.provider.delete","sc.provider.key-add","sc.provider.key-remove",+ "sc.memory.record","sc.evidence.record","sc.recipe.observe","sc.recipe.promote","sc.data.import","sc.hostinger.mail.mutate",+]);+const EXEC_FUNCTIONS = new Set(["sc.update", "sc.doku.mcp.call", "sc.flow.run"]);++export function siCoderFederationScope(name: string): FederationExecutionScope {+ if (EXEC_FUNCTIONS.has(name)) return "exec";+ if (WRITE_FUNCTIONS.has(name)) return "write";+ return "read";+}++const object = (value: unknown): value is Record<string, unknown> =>+ Boolean(value && typeof value === "object" && !Array.isArray(value));++function validateSchema(schema: unknown, value: unknown, at: string): void {+ if (!object(schema)) return;+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];+ if (types.length) {+ const matches = types.some((type) => {+ if (type === "string") return typeof value === "string";+ if (type === "number") return typeof value === "number" && Number.isFinite(value);+ if (type === "integer") return typeof value === "number" && Number.isInteger(value);+ if (type === "boolean") return typeof value === "boolean";+ if (type === "object") return object(value);+ if (type === "array") return Array.isArray(value);+ if (type === "null") return value === null;+ return false;+ });+ if (!matches) throw new Error(`${at} has the wrong type`);+ }+ if (Array.isArray(schema.enum) && !schema.enum.some((candidate) => JSON.stringify(candidate) === JSON.stringify(value))) {+ throw new Error(`${at} is not an allowed enum value`);+ }+ if (typeof value === "string") {+ if (typeof schema.minLength === "number" && value.length < schema.minLength) throw new Error(`${at} is too short`);+ if (typeof schema.maxLength === "number" && value.length > schema.maxLength) throw new Error(`${at} is too long`);+ if (typeof schema.pattern === "string" && !new RegExp(schema.pattern).test(value)) throw new Error(`${at} does not match the required pattern`);+ }+ if (typeof value === "number") {+ if (typeof schema.minimum === "number" && value < schema.minimum) throw new Error(`${at} is below minimum`);+ if (typeof schema.maximum === "number" && value > schema.maximum) throw new Error(`${at} is above maximum`);+ }+ if (Array.isArray(value)) {+ if (typeof schema.minItems === "number" && value.length < schema.minItems) throw new Error(`${at} has too few items`);+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) throw new Error(`${at} has too many items`);+ if (schema.items) value.forEach((item, index) => validateSchema(schema.items, item, `${at}[${index}]`));+ }+ if (object(value)) {+ const properties = object(schema.properties) ? schema.properties : {};+ const required = Array.isArray(schema.required) ? schema.required.filter((item): item is string => typeof item === "string") : [];+ for (const key of required) if (!Object.prototype.hasOwnProperty.call(value, key)) throw new Error(`${at}.${key} is required`);+ if (schema.additionalProperties === false) {+ const unknown = Object.keys(value).find((key) => !Object.prototype.hasOwnProperty.call(properties, key));+ if (unknown) throw new Error(`${at}.${unknown} is not allowed`);+ }+ for (const [key, item] of Object.entries(value)) {+ if (Object.prototype.hasOwnProperty.call(properties, key)) validateSchema(properties[key], item, `${at}.${key}`);+ }+ }+}++async function standaloneServer(cwd: string): Promise<Extract<ProjectMcpServer, { transport: "stdio" }>> {+ const managed = await resolveManagedSc({+ name: "si-coder",+ transport: "plugin",+ plugin: "si-coder",+ cwd,+ headers: {},+ oauthConfigured: false,+ });+ // The normal MSO project plugin intentionally exposes a reduced managed surface.+ // Federation needs the reviewed standalone manifest, but still uses the same+ // verified installation, executable and credential-safe SI-Coder process.+ const { consumer: _consumer, ...server } = managed;+ return server;+}++export async function inspectSiCoderFederationRuntime(cwd: string) {+ const installation = await inspectScInstallation(process.env.MSO_SC_BIN || path.join(os.homedir(), ".local", "bin", "sc"));+ const server = await standaloneServer(cwd);+ const tools = await listMcpServerTools(server);+ return {+ version: installation.version,+ functionCount: tools.length,+ tools,+ };+}++export async function executeSiCoderFederation(input: {+ cwd: string;+ operation: string;+ arguments: Record<string, unknown>;+ scope: FederationExecutionScope;+ confirmed: boolean;+}) {+ const args = validateFederationArguments(input.arguments);+ const expectedScope = siCoderFederationScope(input.operation);+ if (input.scope !== expectedScope) throw new Error(`SI-Coder scope mismatch: request=${input.scope}, runtime=${expectedScope}`);+ if (expectedScope !== "read" && !input.confirmed) throw new Error("SI-Coder write/exec federation requires explicit confirmation");++ const server = await standaloneServer(input.cwd);+ const tools = await listMcpServerTools(server);+ const tool = tools.find((candidate) => candidate.name === input.operation);+ if (!tool) throw new Error(`unknown SI-Coder federation function: ${input.operation}`);+ validateSchema(tool.inputSchema, args, "arguments");+ return callMcpServerTool(server, input.operation, args);+}diff --git a/lib/host/project-mcp-executable.test.ts b/lib/host/project-mcp-executable.test.tsnew file mode 100644index 00000000..de4675dc--- /dev/null+++ b/lib/host/project-mcp-executable.test.ts@@ -0,0 +1,9 @@+import { describe, expect, it } from "vitest";+import { resolveProjectMcpExecutable } from "./project-mcp-transport";++describe("project MCP executable resolution", () => {+ it("uses the current trusted Node executable for portable node manifests", () => {+ expect(resolveProjectMcpExecutable("node")).toBe(process.execPath);+ expect(resolveProjectMcpExecutable("/opt/custom/bin/tool")).toBe("/opt/custom/bin/tool");+ });+});diff --git a/lib/host/project-mcp-transport.ts b/lib/host/project-mcp-transport.tsindex 94cc8cc6..dbc725b8 100644--- a/lib/host/project-mcp-transport.ts+++ b/lib/host/project-mcp-transport.ts@@ -12,6 +12,11 @@ const PROTOCOL = "2025-11-25";const TIMEOUT_MS = 15_000;const MAX_WIRE_BYTES = 2 * 1024 * 1024;+/** Keep project MCP manifests portable even when the service uses a scrubbed PATH. */+export function resolveProjectMcpExecutable(command: string): string {+ return command === "node" ? process.execPath : command;+}+import type { ProjectMcpTool } from "@/lib/contracts/project-mcp";function resolveConfigEnv(server: Extract<ProjectMcpServer, { transport: "stdio" }>): Record<string, string> {@@ -30,7 +35,7 @@ function rpcError(message: Rpc): Error | null {async function withStdio<T>(server: Extract<ProjectMcpServer, { transport: "stdio" }>, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>, notify: (method: string, params?: unknown) => void) => Promise<T>): Promise<T> {return await new Promise<T>((resolve, reject) => {- const child = spawn(server.command, server.args, { cwd: server.cwd, env: resolveConfigEnv(server) as unknown as NodeJS.ProcessEnv, shell: false, stdio: ["pipe", "pipe", "pipe"] }) as ChildProcessWithoutNullStreams;+ const child = spawn(resolveProjectMcpExecutable(server.command), server.args, { cwd: server.cwd, env: resolveConfigEnv(server) as unknown as NodeJS.ProcessEnv, shell: false, stdio: ["pipe", "pipe", "pipe"] }) as ChildProcessWithoutNullStreams;const decoder = new StringDecoder("utf8");let nextId = 1, buffer = "", bytes = 0, stderr = "", done = false;const pending = new Map<number, { resolve: (v: Rpc) => void; reject: (e: Error) => void }>();diff --git a/lib/mcp/federation/baton-client.ts b/lib/mcp/federation/baton-client.tsnew file mode 100644index 00000000..11227592--- /dev/null+++ b/lib/mcp/federation/baton-client.ts@@ -0,0 +1,55 @@+import { parseBatonMcpResult } from "@/lib/federation/security";+import { callProjectMcpTool } from "@/lib/host/project-mcp-client";+import { readProjectMcpServers } from "@/lib/host/project-mcp-config";+import { resolveProjectHint } from "@/lib/host/projects";+import { BATON_SERVER, type BatonCall, type FederationRequest } from "./types";++const object = (value: unknown): value is Record<string, unknown> =>+ Boolean(value && typeof value === "object" && !Array.isArray(value));++export function asFederationRequest(value: unknown): FederationRequest {+ if (!object(value)) throw new Error("Batonly returned an invalid federation request");+ const source = value.source, scope = value.scope;+ if (source !== "mso" && source !== "si-coder") throw new Error("Batonly returned an unknown federation source");+ if (scope !== "read" && scope !== "write" && scope !== "exec") throw new Error("Batonly returned an invalid federation scope");+ if (typeof value.id !== "string" || typeof value.projectId !== "string" || typeof value.operation !== "string") {+ throw new Error("Batonly returned an incomplete federation request");+ }+ return {+ id: value.id,+ projectId: value.projectId,+ source,+ operation: value.operation,+ scope,+ confirmed: value.confirmed === true,+ status: typeof value.status === "string" ? value.status : "",+ arguments: object(value.arguments) ? value.arguments : undefined,+ attempts: typeof value.attempts === "number" ? value.attempts : undefined,+ };+}++function unwrapBaton(value: unknown): unknown {+ if (object(value) && value.isError === true) {+ const parsed = parseBatonMcpResult(value);+ throw new Error(`Batonly MCP refused federation request: ${JSON.stringify(parsed).slice(0, 500)}`);+ }+ return parseBatonMcpResult(value);+}++export async function resolveBatonFederationProject() {+ const hint = (process.env.MSO_BATONLY_FEDERATION_PROJECT || "baton").trim();+ const project = await resolveProjectHint(hint);+ if (!project) throw new Error(`Batonly federation project is unavailable: ${hint}`);+ return project;+}++export async function batonFederationConfigured(): Promise<boolean> {+ const project = await resolveBatonFederationProject();+ const servers = await readProjectMcpServers(project.path);+ return servers.some((server) => server.name === BATON_SERVER);+}++export const defaultBatonCall: BatonCall = async (name, args) => {+ const project = await resolveBatonFederationProject();+ return unwrapBaton(await callProjectMcpTool(project.path, BATON_SERVER, name, args));+};diff --git a/lib/mcp/federation/batonly-worker.test.ts b/lib/mcp/federation/batonly-worker.test.tsnew file mode 100644index 00000000..737bd1d4--- /dev/null+++ b/lib/mcp/federation/batonly-worker.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import {+ executeMsoFederation,+ runBatonlyFederationPoll,+ type FederationRequest,+} from "./batonly-worker";++const readRequest = (): FederationRequest => ({+ id: "request-1",+ projectId: "project-1",+ source: "mso",+ operation: "projects_list",+ scope: "read",+ confirmed: false,+ status: "claimed",+ arguments: {},+});++describe("Batonly federation worker", () => {+ it("preserves inner MSO scope and confirmation policy", async () => {+ await expect(executeMsoFederation({ ...readRequest(), scope: "write" })).rejects.toThrow(/scope mismatch/i);+ await expect(executeMsoFederation({+ ...readRequest(),+ operation: "project_knowledge_set",+ scope: "write",+ confirmed: false,+ arguments: { project: "baton", content: "safe" },+ })).rejects.toThrow(/confirmation/i);+ });++ it("blocks recursive Baton MCP execution", async () => {+ await expect(executeMsoFederation({+ ...readRequest(),+ operation: "project_mcp_call",+ scope: "exec",+ confirmed: true,+ arguments: { project: "baton", server: "baton", tool: "baton_federation_requests_list", arguments: {} },+ })).rejects.toThrow(/recursive/i);+ });++ it("pulls, claims, executes and completes one request through the Baton protocol", async () => {+ const calls: Array<{ name: string; args: Record<string, unknown> }> = [];+ let listed = false;+ const batonCall = async (name: string, args: Record<string, unknown>) => {+ calls.push({ name, args });+ if (name === "baton_federation_worker_heartbeat") return { workerId: "batonly-federation" };+ if (name === "baton_federation_requests_list") {+ if (listed) return [];+ listed = true;+ const { arguments: _arguments, ...summary } = readRequest();+ return [summary];+ }+ if (name === "baton_federation_request_claim") return readRequest();+ if (name === "baton_federation_request_complete") return { status: "succeeded" };+ if (name === "baton_federation_request_fail") return { status: "failed" };+ throw new Error("unexpected Baton call: " + name);+ };++ const outcome = await runBatonlyFederationPoll({ batonCall, cwd: process.cwd() });+ expect(outcome).toMatchObject({ processed: 1, requestId: "request-1", outcome: "succeeded" });+ expect(calls.map((row) => row.name)).toEqual(expect.arrayContaining([+ "baton_federation_worker_heartbeat",+ "baton_federation_requests_list",+ "baton_federation_request_claim",+ "baton_federation_request_complete",+ ]));+ const completed = calls.find((row) => row.name === "baton_federation_request_complete");+ expect(completed?.args.resultJson).toEqual(expect.any(String));+ expect(String(completed?.args.resultJson)).not.toMatch(/Bearer\s|accessToken|apiKey/i);+ });+});diff --git a/lib/mcp/federation/batonly-worker.ts b/lib/mcp/federation/batonly-worker.tsnew file mode 100644index 00000000..03ed66a6--- /dev/null+++ b/lib/mcp/federation/batonly-worker.ts@@ -0,0 +1,170 @@+import { inspectSiCoderFederationRuntime } from "@/lib/federation/si-coder-runtime";+import { FEDERATION_WORKER_ID, safeFederationError, safeFederationResult } from "@/lib/federation/security";+import { MCP_SERVER_VERSION, MCP_TOOLSET_VERSION } from "../toolset";+import { asFederationRequest, batonFederationConfigured, defaultBatonCall, resolveBatonFederationProject } from "./baton-client";+import { executeFederationRequest, msoFederationToolCount } from "./execution";+import {+ BASE_POLL_MS,+ FEDERATION_WORKER_VERSION,+ HEARTBEAT_MS,+ MAX_BACKOFF_MS,+ type BatonCall,+ type BatonlyFederationWorkerStatus,+} from "./types";++export { executeMsoFederation } from "./execution";+export type { FederationRequest } from "./types";++const state: BatonlyFederationWorkerStatus = {+ running: false,+ connected: false,+ consecutiveFailures: 0,+ msoToolCount: msoFederationToolCount(),+};++let timer: ReturnType<typeof setTimeout> | null = null;+let lastHeartbeatAttempt = 0;+let runtimeCache: { at: number; version: string; functionCount: number } | null = null;+let active = false;++async function siCoderRuntime(cwd = process.cwd()) {+ if (runtimeCache && Date.now() - runtimeCache.at < 10 * 60_000) return runtimeCache;+ const runtime = await inspectSiCoderFederationRuntime(cwd);+ runtimeCache = { at: Date.now(), version: runtime.version, functionCount: runtime.functionCount };+ state.siCoderFunctionCount = runtime.functionCount;+ state.siCoderVersion = runtime.version;+ return runtimeCache;+}++async function heartbeat(call: BatonCall, cwd: string, force = false) {+ const now = Date.now();+ if (!force && now - lastHeartbeatAttempt < HEARTBEAT_MS) return;+ lastHeartbeatAttempt = now;+ const sc = await siCoderRuntime(cwd);+ await call("baton_federation_worker_heartbeat", {+ workerId: FEDERATION_WORKER_ID,+ workerVersion: FEDERATION_WORKER_VERSION,+ msoVersion: MCP_SERVER_VERSION,+ msoToolsetVersion: MCP_TOOLSET_VERSION,+ msoToolCount: msoFederationToolCount(),+ siCoderVersion: sc.version,+ siCoderFunctionCount: sc.functionCount,+ siCoderSkillCount: 22,+ ...(state.lastRequestId ? { lastRequestId: state.lastRequestId } : {}),+ lastOutcome: state.lastOutcome ?? "idle",+ });+ state.lastHeartbeatAt = now;+}++function retryableError(message: string) {+ return /(timed? ?out|temporar|unavailable|ECONN|fetch|connection|network|502|503|504)/i.test(message);+}++export async function runBatonlyFederationPoll(options: { batonCall?: BatonCall; cwd?: string } = {}) {+ const call = options.batonCall ?? defaultBatonCall;+ const cwd = options.cwd ?? process.cwd();+ state.lastPollAt = Date.now();+ await heartbeat(call, cwd);++ const raw = await call("baton_federation_requests_list", { pendingOnly: true, limit: 10 });+ if (!Array.isArray(raw)) throw new Error("Batonly pending federation response must be an array");+ state.connected = true;+ if (!raw.length) {+ state.lastOutcome = "idle";+ return { processed: 0 };+ }++ const summary = asFederationRequest(raw[0]);+ const claimed = asFederationRequest(await call("baton_federation_request_claim", {+ requestId: summary.id,+ workerId: FEDERATION_WORKER_ID,+ leaseMs: 120_000,+ }));+ state.currentRequestId = claimed.id;++ try {+ const result = await executeFederationRequest(claimed, cwd);+ const safe = safeFederationResult({+ source: claimed.source,+ operation: claimed.operation,+ durationEvidence: "executed by approved MSO federation worker",+ result,+ });+ await call("baton_federation_request_complete", {+ requestId: claimed.id,+ workerId: FEDERATION_WORKER_ID,+ resultJson: safe.json,+ });+ state.lastRequestId = claimed.id;+ state.lastOutcome = "succeeded";+ state.lastSuccessAt = Date.now();+ return { processed: 1, requestId: claimed.id, outcome: "succeeded" as const };+ } catch (error) {+ const message = safeFederationError(error);+ await call("baton_federation_request_fail", {+ requestId: claimed.id,+ workerId: FEDERATION_WORKER_ID,+ errorCode: "FEDERATION_EXECUTION_FAILED",+ errorMessage: message,+ retryable: retryableError(message),+ }).catch(() => undefined);+ state.lastRequestId = claimed.id;+ state.lastOutcome = "failed";+ throw error;+ } finally {+ state.currentRequestId = undefined;+ await heartbeat(call, cwd, true).catch(() => undefined);+ }+}++function schedule(delay: number) {+ state.nextPollInMs = delay;+ timer = setTimeout(() => {+ timer = null;+ void loop();+ }, delay);+ timer.unref();+}++async function loop() {+ if (!active) return;+ try {+ await runBatonlyFederationPoll();+ state.connected = true;+ state.lastError = undefined;+ state.consecutiveFailures = 0;+ schedule(BASE_POLL_MS);+ } catch (error) {+ state.connected = false;+ state.lastError = safeFederationError(error);+ state.consecutiveFailures += 1;+ schedule(Math.min(MAX_BACKOFF_MS, BASE_POLL_MS * 2 ** Math.min(state.consecutiveFailures, 3)));+ }+}++export async function startBatonlyFederationWorker() {+ if (process.env.MSO_BATONLY_FEDERATION_DISABLED === "1" || active) return getBatonlyFederationWorkerStatus();+ try {+ const project = await resolveBatonFederationProject();+ state.batonProject = project.id;+ if (!(await batonFederationConfigured())) return getBatonlyFederationWorkerStatus();+ } catch {+ return getBatonlyFederationWorkerStatus();+ }+ active = true;+ state.running = true;+ schedule(250);+ return getBatonlyFederationWorkerStatus();+}++export function stopBatonlyFederationWorker() {+ active = false;+ state.running = false;+ if (timer) clearTimeout(timer);+ timer = null;+ state.nextPollInMs = undefined;+}++export function getBatonlyFederationWorkerStatus(): BatonlyFederationWorkerStatus {+ return { ...state };+}diff --git a/lib/mcp/federation/execution.ts b/lib/mcp/federation/execution.tsnew file mode 100644index 00000000..6283972f--- /dev/null+++ b/lib/mcp/federation/execution.ts@@ -0,0 +1,60 @@+import { executeCapabilityCall } from "@/lib/capabilities/execute";+import { validateFederationArguments, FEDERATION_WORKER_ID } from "@/lib/federation/security";+import { executeSiCoderFederation } from "@/lib/federation/si-coder-runtime";+import { msoCapabilityRuntime } from "../capability-runtime";+import { TOOLS_BY_NAME } from "../tools";+import { BATON_SERVER, type FederationRequest } from "./types";++const ACTOR = "federation:batonly";++function recursiveMsoRequest(operation: string, args: Record<string, unknown>): boolean {+ if (operation !== "project_mcp_call") return false;+ return typeof args.server === "string" && args.server === BATON_SERVER;+}++export async function executeMsoFederation(request: FederationRequest) {+ const args = validateFederationArguments(request.arguments ?? {});+ const tool = TOOLS_BY_NAME.get(request.operation);+ if (!tool) throw new Error(`unknown MSO federation tool: ${request.operation}`);+ if (tool.scope !== request.scope) {+ throw new Error(`MSO scope mismatch: request=${request.scope}, runtime=${tool.scope}`);+ }+ if (tool.scope !== "read" && !request.confirmed) {+ throw new Error("MSO write/exec federation requires explicit confirmation");+ }+ if (recursiveMsoRequest(request.operation, args)) {+ throw new Error("recursive Batonly project MCP federation is not allowed");+ }++ const outcome = await executeCapabilityCall({+ tool,+ args,+ scope: tool.scope,+ actor: ACTOR,+ context: {+ principal: FEDERATION_WORKER_ID,+ capabilities: msoCapabilityRuntime,+ },+ });+ if (outcome.kind === "protocol_error") throw new Error(`MSO invalid arguments: ${outcome.message}`);+ if (outcome.kind === "error") throw new Error(outcome.message);+ return outcome.result;+}++export async function executeFederationRequest(request: FederationRequest, cwd = process.cwd()) {+ if (request.scope !== "read" && !request.confirmed) {+ throw new Error("federation write/exec request is missing explicit confirmation");+ }+ const args = validateFederationArguments(request.arguments ?? {});+ return request.source === "mso"+ ? executeMsoFederation({ ...request, arguments: args })+ : executeSiCoderFederation({+ cwd,+ operation: request.operation,+ arguments: args,+ scope: request.scope,+ confirmed: request.confirmed,+ });+}++export const msoFederationToolCount = () => TOOLS_BY_NAME.size;diff --git a/lib/mcp/federation/types.ts b/lib/mcp/federation/types.tsnew file mode 100644index 00000000..036eed44--- /dev/null+++ b/lib/mcp/federation/types.ts@@ -0,0 +1,39 @@+import type { FederationExecutionScope } from "@/lib/federation/si-coder-runtime";++export const FEDERATION_WORKER_VERSION = "1";+export const BATON_SERVER = "baton";+export const BASE_POLL_MS = 10_000;+export const MAX_BACKOFF_MS = 60_000;+export const HEARTBEAT_MS = 45_000;++export type FederationRequest = {+ id: string;+ projectId: string;+ source: "mso" | "si-coder";+ operation: string;+ scope: FederationExecutionScope;+ confirmed: boolean;+ status: string;+ arguments?: Record<string, unknown>;+ attempts?: number;+};++export type BatonlyFederationWorkerStatus = {+ running: boolean;+ connected: boolean;+ lastPollAt?: number;+ lastHeartbeatAt?: number;+ lastSuccessAt?: number;+ lastError?: string;+ currentRequestId?: string;+ lastRequestId?: string;+ lastOutcome?: "idle" | "succeeded" | "failed";+ consecutiveFailures: number;+ nextPollInMs?: number;+ batonProject?: string;+ msoToolCount: number;+ siCoderFunctionCount?: number;+ siCoderVersion?: string;+};++export type BatonCall = (name: string, args: Record<string, unknown>) => Promise<unknown>;diff --git a/package.json b/package.jsonindex be324d71..0f4f2514 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "mso",- "version": "0.2.21",+ "version": "0.2.22","private": true,"engines": {"node": "^22.12.0 || ^24.0.0 || >=26.0.0",