UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

463 lines (462 loc) • 14.8 kB
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { i as createAbortError } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import "./errors-BKzCeTYb.mjs"; import { a as normalizeReservedToolNames } from "./agent-bundle-mcp-names-856aMFJA.mjs"; import { o as setPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs"; import { i as logWarn, t as logDebug } from "./logger-CIwfuhOU.mjs"; import { n as resolveStdioMcpServerLaunchConfig, t as describeStdioMcpServerLaunchConfig } from "./mcp-stdio-BbrQn34X.mjs"; import { n as loadEnabledBundleLspConfig } from "./bundle-lsp-BPvu9pN4.mjs"; import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { a as resolveWindowsSpawnProgram, r as materializeWindowsSpawnProgram } from "./windows-spawn-BcHMKZuG.mjs"; import { n as closeOwnedStdioProcess, r as createOwnedStdioProcess, t as OwnedStdioCleanupError } from "./owned-stdio-D7AQWLYW.mjs"; import { t as createPendingRequestRegistry } from "./pending-request-registry-C9qiZTaJ.mjs"; //#region src/agents/agent-bundle-lsp-runtime.ts const LSP_SHUTDOWN_GRACE_MS = 500; const LSP_PROCESS_TREE_KILL_GRACE_MS = 1e3; const activeBundleLspSessions = /* @__PURE__ */ new Set(); const warnedWithheldEnv = /* @__PURE__ */ new Set(); function failLspSession(e, t) { e.failure ??= t; e.pendingRequests.rejectAll(e.failure); } function lspProcessExitError(e, t, n) { return /* @__PURE__ */ new Error(`LSP server "${e.serverName}" exited (${n ?? t ?? "unknown"})`); } function attachLspProcessHandlers(e) { e.process.onError((t, n) => { if (n === "stderr") logWarn(`bundle-lsp:${e.serverName}: stderr failed: ${String(t)}`); else { e.forceClose = true; failLspSession(e, t); } }); e.process.onExit((t, n) => { e.failure ??= lspProcessExitError(e, t, n); }); e.process.wait().then(({ code: t, signal: n }) => failLspSession(e, lspProcessExitError(e, t, n)), (t) => failLspSession(e, toErrorObject(t, "LSP process failed"))); e.process.onStdout(() => {}, (t) => handleIncomingData(e, t)); e.process.onStderr(() => {}); } function encodeLspMessage(e) { const t = JSON.stringify(e); return `Content-Length: ${Buffer.byteLength(t, "utf-8")}\r\n\r\n${t}`; } const LSP_HEADER_SEPARATOR = Buffer.from("\r\n\r\n", "ascii"); const MAX_LSP_HEADER_BYTES = 8192; const MAX_LSP_BODY_BYTES = 67108864; const LSP_BODY_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); var LspFramingError = class extends Error { constructor(...e) { super(...e); this.name = "LspFramingError"; } }; function framingError(e, t) { return { ok: false, messages: e, error: new LspFramingError(`LSP framing error: ${t}`) }; } function parseContentLength(e) { const t = []; for (const n of e.split("\r\n")) { const e = n.indexOf(":"); if (e === -1) return new LspFramingError("LSP framing error: header line must contain a colon"); if (n.slice(0, e).trim().toLowerCase() === "content-length") t.push(n.slice(e + 1).trim()); } if (t.length !== 1) return new LspFramingError(`LSP framing error: expected exactly one Content-Length header, received ${t.length}`); const n = t[0]; if (n === void 0 || !/^[0-9]+$/.test(n)) return new LspFramingError("LSP framing error: Content-Length must be decimal digits"); const r = Number(n); if (!Number.isSafeInteger(r) || r <= 0) return new LspFramingError("LSP framing error: Content-Length must be a positive safe integer"); if (r > MAX_LSP_BODY_BYTES) return new LspFramingError(`LSP framing error: Content-Length exceeds ${MAX_LSP_BODY_BYTES} bytes`); return r; } function parseLspMessages(e) { const t = []; let n = 0; while (true) { if (!e.body) { const r = e.buffer.subarray(n, e.length); const i = r.indexOf(LSP_HEADER_SEPARATOR); if (i === -1) { const e = MAX_LSP_HEADER_BYTES + LSP_HEADER_SEPARATOR.length - 1; return r.length > e ? framingError(t, `header exceeds ${MAX_LSP_HEADER_BYTES} bytes`) : { ok: true, messages: t, consumed: n }; } if (i > MAX_LSP_HEADER_BYTES) return framingError(t, `header exceeds ${MAX_LSP_HEADER_BYTES} bytes`); const a = parseContentLength(r.subarray(0, i).toString("ascii")); if (a instanceof LspFramingError) return { ok: false, messages: t, error: a }; const o = n + i + LSP_HEADER_SEPARATOR.length; e.body = { start: o, end: o + a }; } if (e.length < e.body.end) return { ok: true, messages: t, consumed: n }; let r; try { r = LSP_BODY_DECODER.decode(e.buffer.subarray(e.body.start, e.body.end)); } catch { return framingError(t, "body is not valid UTF-8"); } try { t.push(JSON.parse(r)); } catch (e) { return framingError(t, `body is not valid JSON: ${e instanceof Error ? e.message : String(e)}`); } n = e.body.end; e.body = void 0; } } function lspAbortError(e) { return e?.reason instanceof Error ? e.reason : createAbortError("LSP request aborted", { cause: e?.reason }); } function throwIfLspAborted(e) { if (e?.aborted) throw lspAbortError(e); } function lspSessionDisposedError() { return /* @__PURE__ */ new Error("LSP session disposed"); } function sendRequest(e, t, n, r) { if (e.disposed && t !== "shutdown") return Promise.reject(lspSessionDisposedError()); if (e.failure) return Promise.reject(e.failure); if (r?.aborted) return Promise.reject(lspAbortError(r)); const i = ++e.requestId; const onAbort = () => { const t = e.pendingRequests.take(i); if (!t) return; try { e.process.stdin?.write(encodeLspMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id: i } })); } catch {} t.reject(lspAbortError(r)); }; const a = e.pendingRequests.add(i, { value: void 0, timeoutMs: t === "shutdown" ? LSP_SHUTDOWN_GRACE_MS : 1e4, timeoutError: () => /* @__PURE__ */ new Error(`LSP request ${t} timed out`), dispose: () => r?.removeEventListener("abort", onAbort) }); if (!a) return Promise.reject(/* @__PURE__ */ new Error(`LSP request id collision: ${i}`)); r?.addEventListener("abort", onAbort, { once: true }); const o = { jsonrpc: "2.0", id: i, method: t, params: n }; try { const t = encodeLspMessage(o); e.process.stdin?.write(t); } catch (e) { a.reject(e); } return a.promise; } function handleIncomingData(e, t) { const n = typeof t === "string" ? Buffer.from(t, "utf8") : t; const r = e.input; const i = r.length + n.length; if (i > r.buffer.length) { const e = Math.max(i, Math.min(Math.max(4096, r.buffer.length * 2), MAX_LSP_HEADER_BYTES + LSP_HEADER_SEPARATOR.length + MAX_LSP_BODY_BYTES)); const t = Buffer.allocUnsafe(e); r.buffer.copy(t, 0, 0, r.length); r.buffer = t; } n.copy(r.buffer, r.length); r.length = i; const a = parseLspMessages(r); if (!a.ok || a.consumed === r.length) e.input = { buffer: Buffer.alloc(0), length: 0 }; else if (a.consumed > 0) { r.buffer = Buffer.from(r.buffer.subarray(a.consumed, r.length)); r.length -= a.consumed; if (r.body) { r.body.start -= a.consumed; r.body.end -= a.consumed; } } for (const t of a.messages) { if (typeof t !== "object" || t === null) continue; const n = t; if ("id" in n && typeof n.id === "number") { const t = e.pendingRequests.take(n.id); if (t) { if ("error" in n) t.reject(new Error(JSON.stringify(n.error))); else t.resolve(n.result); } } if ("method" in n && !("id" in n)) logDebug(`bundle-lsp:${e.serverName}: notification ${String(n.method)}`); } if (!a.ok) { e.forceClose = true; failLspSession(e, a.error); disposeSession(e).catch(() => {}); } } async function initializeSession(e, t) { const n = await sendRequest(e, "initialize", { processId: process.pid, rootUri: null, capabilities: { textDocument: { hover: { contentFormat: ["plaintext", "markdown"] }, completion: { completionItem: { snippetSupport: false } }, definition: {}, references: {} } } }, t); throwIfLspAborted(t); e.process.stdin?.write(encodeLspMessage({ jsonrpc: "2.0", method: "initialized", params: {} })); e.initialized = true; return n?.capabilities ?? {}; } function disposeSession(e) { if (e.disposal) return e.disposal; e.disposed = true; e.pendingRequests.rejectAll(lspSessionDisposedError()); e.disposal = (async () => { if (e.initialized && !e.failure) try { await sendRequest(e, "shutdown").catch(() => void 0); e.process.stdin?.write(encodeLspMessage({ jsonrpc: "2.0", method: "exit", params: null })); } catch {} e.pendingRequests.rejectAll(lspSessionDisposedError()); try { await closeOwnedStdioProcess(e.process, { graceMs: LSP_PROCESS_TREE_KILL_GRACE_MS, force: e.forceClose }); } catch (t) { recordAgentCleanupFailure(); logWarn(`bundle-lsp:${e.serverName}: process cleanup could not confirm descendant shutdown; inspect this server before retrying automatic recovery.`); throw t; } finally { activeBundleLspSessions.delete(e); } })(); return e.disposal; } async function disposeSessions(e) { if ((await Promise.allSettled(Array.from(e, (e) => disposeSession(e)))).some((e) => e.status === "rejected")) recordAgentCleanupFailure(); } function createLspPositionTool(e) { return { name: `lsp_${e.method}_${e.session.serverName}`, label: e.label, description: e.description, parameters: { type: "object", properties: { uri: { type: "string", description: "File URI (file:///path/to/file)" }, line: { type: "number", description: "Zero-based line number" }, character: { type: "number", description: "Zero-based character offset" }, ...e.method === "references" ? { includeDeclaration: { type: "boolean", description: "Include the declaration in results" } } : {} }, required: [ "uri", "line", "character" ] }, execute: async (t, n, r) => { const i = n; const a = await sendRequest(e.session, `textDocument/${e.method}`, { textDocument: { uri: i.uri }, position: { line: i.line, character: i.character }, ...e.method === "references" ? { context: { includeDeclaration: i.includeDeclaration ?? true } } : {} }, r); return { content: [{ type: "text", text: a !== null && a !== void 0 ? JSON.stringify(a, null, 2) : `No ${e.method} result from ${e.session.serverName}` }], details: { lspServer: e.session.serverName, lspMethod: e.method } }; } }; } function buildLspTools(e) { const t = e.serverName; return [ { method: "hover", label: `LSP Hover (${t})`, description: `Get hover information for a symbol at a position in a file via the ${t} language server.` }, { method: "definition", label: `LSP Go to Definition (${t})`, description: `Find the definition of a symbol at a position in a file via the ${t} language server.` }, { method: "references", label: `LSP Find References (${t})`, description: `Find all references to a symbol at a position in a file via the ${t} language server.` } ].filter(({ method: t }) => e.capabilities[`${t}Provider`]).map((t) => createLspPositionTool({ session: e, ...t })); } async function createBundleLspToolRuntime(e) { throwIfLspAborted(e.abortSignal); const t = loadEnabledBundleLspConfig({ workspaceDir: e.workspaceDir, cfg: e.cfg, manifestRegistry: e.manifestRegistry }); for (const e of t.diagnostics) logWarn(`bundle-lsp: ${e.pluginId}: ${e.message}`); if (Object.keys(t.config.lspServers).length === 0) return { tools: [], sessions: [], dispose: async () => {} }; const { collectWithheldLspEnvNames: n, formatWithheldLspEnvHints: r, LSP_ENV_PASSTHROUGH_DOCS_URL: i, resolveLspServerEnv: a } = await import("./agent-bundle-lsp-env-BDMUfsKF.mjs"); function warnWithheldLspEnvOnce(e, t) { const a = r(n({ parentEnv: process.env, childEnv: t })).join(" "); const o = `${e}\0${a}`; if (!a || warnedWithheldEnv.has(o)) return; warnedWithheldEnv.add(o); logWarn(`bundle-lsp: server "${e}" starts without these Gateway environment variables. ${a} See ${i}`); } const o = normalizeReservedToolNames(e.reservedToolNames); const s = []; const c = []; try { for (const [n, r] of Object.entries(t.config.lspServers)) { throwIfLspAborted(e.abortSignal); const t = resolveStdioMcpServerLaunchConfig(r); if (!t.ok) { logWarn(`bundle-lsp: skipped server "${n}" because ${t.reason}.`); continue; } const i = t.config; let l; try { const t = a(i.env); if (n !== void 0) warnWithheldLspEnvOnce(n, t); const r = resolveWindowsSpawnProgram({ command: i.command, env: t, allowShellFallback: true }); const u = materializeWindowsSpawnProgram(r, i.args ?? []); l = { serverName: n, process: await createOwnedStdioProcess({ argv: [u.command, ...u.argv], env: t, exactEnv: true, cwd: i.cwd, abortSignal: e.abortSignal, ...u.shell === true ? { windowsShell: true } : {} }), requestId: 0, pendingRequests: createPendingRequestRegistry(), input: { buffer: Buffer.alloc(0), length: 0 }, initialized: false, capabilities: {}, disposed: false, forceClose: false }; activeBundleLspSessions.add(l); attachLspProcessHandlers(l); throwIfLspAborted(e.abortSignal); const d = await initializeSession(l, e.abortSignal); throwIfLspAborted(e.abortSignal); l.capabilities = d; s.push(l); const f = buildLspTools(l); for (const e of f) { const t = normalizeOptionalLowercaseString(e.name); if (!t) continue; if (o.has(t)) { logWarn(`bundle-lsp: skipped tool "${e.name}" from server "${n}" because the name already exists.`); continue; } o.add(t); setPluginToolMeta(e, { pluginId: "bundle-lsp", optional: false }); c.push(e); } } catch (t) { if (l) await disposeSessions([l]); else if (t instanceof OwnedStdioCleanupError) recordAgentCleanupFailure(); if (!e.abortSignal?.aborted || t instanceof OwnedStdioCleanupError) logWarn(`bundle-lsp: failed to start server "${n}" (${describeStdioMcpServerLaunchConfig(i)}): ${String(t)}`); throwIfLspAborted(e.abortSignal); } } return { tools: c, sessions: s.map((e) => ({ serverName: e.serverName, capabilities: e.capabilities })), dispose: () => disposeSessions(s) }; } catch (e) { await disposeSessions(s); throw e; } } async function disposeAllBundleLspRuntimes() { await disposeSessions(activeBundleLspSessions); } //#endregion export { disposeAllBundleLspRuntimes as n, createBundleLspToolRuntime as t };