UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

288 lines (287 loc) • 9.9 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { i as throwCollectedErrors, n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs"; import { n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { n as closeOwnedStdioProcess, r as createOwnedStdioProcess, t as OwnedStdioCleanupError } from "./owned-stdio-D7AQWLYW.mjs"; import { t as parseMcpDockerCommand } from "./mcp-docker-command-Cs1DrAOj.mjs"; import fs from "node:fs/promises"; import { PassThrough } from "node:stream"; import { JSONRPCMessageSchema } from "@modelcontextprotocol/core"; import { STDIO_DEFAULT_MAX_BUFFER_SIZE, serializeMessage } from "@modelcontextprotocol/client"; import { getDefaultEnvironment } from "@modelcontextprotocol/client/stdio"; //#region src/agents/mcp-stdio-frame-decoder.ts var McpStdioFrameError = class extends Error {}; var McpStdioFrameDecoder = class { constructor(e, t = "strict-proxy") { this.maxFrameBytes = e; this.mode = t; this.pending = Buffer.alloc(0); this.pendingBytes = 0; this.chunk = Buffer.alloc(0); this.cursor = 0; } append(e) { if (this.mode === "transport" && this.pendingBytes + e.length > this.maxFrameBytes) { this.clear(); throw new Error(`ReadBuffer exceeded maximum size of ${this.maxFrameBytes} bytes`); } let t = this.pendingBytes; let n = 0; while (t + e.length - n > this.maxFrameBytes) { const r = e.indexOf(10, n); if (r < 0 || t + r + 1 - n > this.maxFrameBytes) throw new McpStdioFrameError("response exceeded the line-size limit"); n = r + 1; t = 0; } this.chunk = e; this.cursor = 0; } readMessage() { while (this.cursor < this.chunk.length) { const e = this.chunk.indexOf(10, this.cursor); if (e < 0) { this.appendPending(this.chunk.subarray(this.cursor)); this.chunk = Buffer.alloc(0); this.cursor = 0; return null; } let t = this.chunk.subarray(this.cursor, e); this.cursor = e + 1; if (this.pendingBytes > 0) { this.appendPending(t); t = this.pending.subarray(0, this.pendingBytes); this.pending = Buffer.alloc(0); this.pendingBytes = 0; } if (this.cursor === this.chunk.length) { this.chunk = Buffer.alloc(0); this.cursor = 0; } if (t.length === 0 && this.mode === "strict-proxy") continue; let n; try { n = JSON.parse(t.toString("utf8")); } catch (e) { if (this.mode === "transport") throw e; throw new McpStdioFrameError("proxy returned invalid JSON", { cause: e }); } if (this.mode === "transport") return JSONRPCMessageSchema.parse(n); if (!isRecord(n) || n.jsonrpc !== "2.0") throw new McpStdioFrameError("proxy returned an invalid JSON-RPC version"); if (("result" in n || "error" in n) && !Number.isSafeInteger(n.id)) throw new McpStdioFrameError("proxy returned an invalid response id"); try { return JSONRPCMessageSchema.parse(n); } catch (e) { throw new McpStdioFrameError("proxy returned an invalid JSON-RPC message", { cause: e }); } } return null; } clear() { this.pending = Buffer.alloc(0); this.pendingBytes = 0; this.chunk = Buffer.alloc(0); this.cursor = 0; } appendPending(e) { const t = this.pendingBytes + e.length; if (t > this.pending.length) { const e = Math.min(this.maxFrameBytes, Math.max(t, this.pending.length * 2)); const n = Buffer.allocUnsafe(e); this.pending.copy(n, 0, 0, this.pendingBytes); this.pending = n; } e.copy(this.pending, this.pendingBytes); this.pendingBytes = t; } }; //#endregion //#region src/agents/mcp-stdio-transport.ts /** * OpenClaw stdio transport wrapper for MCP server subprocesses. */ const log = createSubsystemLogger("mcp/stdio"); var OpenClawStdioClientTransport = class extends EventTarget { constructor(e) { super(); this.serverParams = e; this.stderrStream = new PassThrough(); this.forceRequested = false; this.closeNotified = false; this.startupAbort = new AbortController(); this.readBuffer = e.decoder ?? new McpStdioFrameDecoder(STDIO_DEFAULT_MAX_BUFFER_SIZE, "transport"); } async start() { if (this.starting || this.closing) throw new Error("OpenClawStdioClientTransport already started or closed; Client.connect() starts transports automatically."); this.starting = this.startProcess(); return this.starting; } async startProcess() { const e = this.serverParams.prepareDataDir?.trim(); if (e) try { await fs.mkdir(e, { recursive: true }); } catch (t) { const n = new Error(`unable to prepare PLUGIN_DATA directory "${e}": ${formatErrorMessage(t)}`, { cause: t }); materializeErrorStack(n); throw n; } if (this.startupAbort.signal.aborted) { const e = /* @__PURE__ */ new Error("MCP stdio transport is closed"); materializeErrorStack(e); throw e; } try { const e = this.serverParams.exactEnv ? mergeProcessEnv([this.serverParams.env]) : mergeProcessEnv([getDefaultEnvironment(), this.serverParams.env]); const t = parseMcpDockerCommand(this.serverParams.command, this.serverParams.args); if (t.kind === "unsafe") log.warn(`Docker MCP container custody unavailable: ${t.reason}. Use a direct docker run argument array for automatic cleanup.`); else if (t.kind === "docker") { const { prepareMcpDockerLaunch: n } = await import("./mcp-docker-custody-xbrimqfI.mjs"); this.docker = await n(t, e, this.serverParams.cwd); } if (this.startupAbort.signal.aborted) throw new Error("MCP stdio transport is closed"); const n = await createOwnedStdioProcess({ argv: this.docker ? [this.docker.command, ...this.docker.args] : [this.serverParams.command, ...this.serverParams.args ?? []], cwd: this.serverParams.cwd, env: this.docker?.env ?? e, ...this.serverParams.exactEnv ? { exactEnv: true } : {}, ...this.docker ? { assertCurrent: this.docker.assertCurrent } : { abortSignal: this.startupAbort.signal }, stderrDestination: this.stderrStream }); this.process = n; n.onError((e) => this.notifyError(e)); const receive = (e) => { if (this.closing) return; try { this.readBuffer.append(e); this.processReadBuffer(); } catch (e) { this.notifyError(e instanceof Error ? e : new Error(String(e))); this.close().catch(() => {}); } }; n.onStdout((e) => { if (!n.supportsRawOutput) receive(Buffer.from(e)); }, receive); n.wait().then((e) => { try { this.dispatchEvent(new Event("exit")); this.onexit?.(e); } catch (e) { this.notifyError(e instanceof Error ? e : new Error(String(e))); } finally { this.close().catch(() => {}); this.notifyClosed(); } }, (e) => { this.notifyError(e instanceof Error ? e : new Error(String(e))); this.close().catch(() => {}); this.notifyClosed(); }); } catch (e) { materializeErrorStack(e); if (e instanceof OwnedStdioCleanupError) { this.startupCleanupError = e; recordAgentCleanupFailure(); } if (this.docker && !this.process) { const e = this.docker.close(this.startupCleanupError ? void 0 : Promise.resolve()).catch((e) => { recordAgentCleanupFailure(); this.notifyError(e instanceof Error ? e : new Error(String(e))); }); if (!this.startupCleanupError) await e; } this.notifyError(e instanceof Error ? e : new Error(String(e))); throw e; } } get stderr() { return this.stderrStream; } get pid() { return this.process?.pid ?? null; } get cleanupResult() { return this.cleanup; } notifyError(e) { this.dispatchEvent(new Event("error")); this.onerror?.(e); } notifyClosed() { if (this.closeNotified) return; this.closeNotified = true; this.onclose?.(); } processReadBuffer() { while (!this.closing) try { const e = this.readBuffer.readMessage(); if (e === null) break; this.onmessage?.(e); } catch (e) { this.notifyError(e instanceof Error ? e : new Error(String(e))); } } close() { if (this.starting && !this.process) this.startupAbort.abort(); this.closing ??= (async () => { await this.starting?.catch(() => void 0); try { const e = []; if (this.docker) try { await this.docker.close(this.process?.wait() ?? (this.startupCleanupError ? void 0 : Promise.resolve())); } catch (t) { e.push(t); } if (this.startupCleanupError) e.push(this.startupCleanupError); if (this.process) try { this.cleanup = await closeOwnedStdioProcess(this.process, { force: this.forceRequested }); } catch (t) { e.push(t); } throwCollectedErrors(e, "MCP container and host-process cleanup failed"); } catch (e) { materializeErrorStack(e); recordAgentCleanupFailure(); throw e; } finally { this.process = void 0; this.readBuffer.clear(); this.stderrStream.end(); this.notifyClosed(); } })(); this.closing.catch(() => recordAgentCleanupFailure()); return this.closing; } /** Retire RPC admission now; the returned promise still joins owned-process cleanup. */ retire() { const e = this.close(); this.readBuffer.clear(); this.notifyClosed(); return e; } terminate() { if (!this.docker) this.process?.kill("SIGTERM"); return this.retire(); } forceClose() { this.forceRequested = true; if (this.docker) this.docker.force(); else this.process?.kill("SIGKILL"); return this.close(); } send(e) { return new Promise((t, n) => { const r = this.closing ? void 0 : this.process?.stdin; if (!r) throw new Error("Not connected"); const i = serializeMessage(e); r.write(i, (e) => { if (e) n(e); else t(); }); }); } }; //#endregion export { McpStdioFrameDecoder as n, McpStdioFrameError as r, OpenClawStdioClientTransport as t };