openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
712 lines (711 loc) • 23.4 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { a as throwIfSettledRejected } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Pn as number, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { i as extractFirstTextBlock } from "./chat-message-content-DNUdbbJ8.mjs";
import { c as isMeaningfulMediaFact, p as readPersistedMediaFacts } from "./media-facts-B-0Dpo5L.mjs";
import { randomUUID } from "node:crypto";
import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
//#region src/mcp/channel-shared.ts
const ClaudePermissionRequestSchema = object({
method: literal("notifications/claude/channel/permission_request"),
params: object({
request_id: string(),
tool_name: string(),
description: string(),
input_preview: string()
})
});
function summarizeResult(e, t) {
return { content: [{
type: "text",
text: `${e}: ${t}`
}] };
}
function summarizeStructuredResult(e, t, n) {
return {
content: [{
type: "text",
text: `${e}: ${t}\n\n${JSON.stringify(n, null, 2)}`
}],
structuredContent: n
};
}
/** Convert a Gateway session row into a reply-capable conversation descriptor. */
function toConversation(e) {
const t = normalizeOptionalLowercaseString(normalizeOptionalString(e.deliveryContext?.channel) ?? normalizeOptionalString(e.lastChannel) ?? normalizeOptionalString(e.channel) ?? normalizeOptionalString(e.origin?.provider));
const n = normalizeOptionalString(e.deliveryContext?.to) ?? normalizeOptionalString(e.lastTo);
if (!t || !n) return null;
return {
sessionKey: e.key,
channel: t,
to: n,
accountId: normalizeOptionalString(e.deliveryContext?.accountId) ?? normalizeOptionalString(e.lastAccountId) ?? normalizeOptionalString(e.origin?.accountId),
threadId: e.deliveryContext?.threadId ?? e.lastThreadId ?? e.origin?.threadId,
label: normalizeOptionalString(e.label),
displayName: normalizeOptionalString(e.displayName),
derivedTitle: normalizeOptionalString(e.derivedTitle),
lastMessagePreview: normalizeOptionalString(e.lastMessagePreview),
updatedAt: typeof e.updatedAt === "number" ? e.updatedAt : null
};
}
function matchEventFilter(e, t) {
if (e.cursor <= t.afterCursor) return false;
if (!t.sessionKey) return true;
return "sessionKey" in e && e.sessionKey === t.sessionKey;
}
/** Return non-text content blocks plus canonical persisted media from a raw message payload. */
function extractAttachmentsFromMessage(e) {
if (!e || typeof e !== "object") return [];
const t = e.content;
const n = Array.isArray(t) ? t.filter((e) => {
if (!e || typeof e !== "object") return false;
return normalizeOptionalString(e.type) !== "text";
}) : [];
const r = (readPersistedMediaFacts(e) ?? []).filter(isMeaningfulMediaFact).map((e) => ({
type: "openclaw_media",
media: Object.fromEntries(Object.entries(e).filter(([, e]) => e !== void 0))
}));
return [...n, ...r];
}
//#endregion
//#region src/mcp/channel-bridge.ts
const CLAUDE_PERMISSION_REPLY_RE = /^(yes|no)\s+([a-km-z]{5})$/i;
const QUEUE_LIMIT = 1e3;
const PENDING_CLAUDE_PERMISSION_TTL_MS = 36e5;
const PENDING_APPROVAL_DEFAULT_TTL_MS = 18e5;
const PENDING_SWEEP_INTERVAL_MS = 3e5;
/** Connects the MCP server surface to a Gateway client and queues channel events for polling. */
var OpenClawChannelBridge = class {
constructor(e, t) {
this.cfg = e;
this.params = t;
this.gateway = null;
this.queue = [];
this.pendingWaiters = /* @__PURE__ */ new Set();
this.pendingClaudePermissions = /* @__PURE__ */ new Map();
this.pendingApprovals = /* @__PURE__ */ new Map();
this.pendingSweepInterval = null;
this.server = null;
this.cursor = 0;
this.closed = false;
this.ready = false;
this.started = false;
this.retryingInitialConnect = false;
this.readiness = createDeferredCore();
this.verbose = t.verbose;
this.claudeChannelMode = t.claudeChannelMode;
}
setServer(e) {
this.server = e;
}
/** Start the Gateway connection and resolve only after session subscription succeeds. */
async start() {
if (this.started) {
await this.readiness.promise;
return;
}
this.started = true;
const [{ resolveGatewayClientBootstrap: e }, { GatewayClient: t }, { startGatewayClientWhenEventLoopReady: n }, { APPROVALS_SCOPE: r, READ_SCOPE: i, WRITE_SCOPE: a }, { GATEWAY_CLIENT_CAPS: o, GATEWAY_CLIENT_MODES: s, GATEWAY_CLIENT_NAMES: c }] = await Promise.all([
import("./client-bootstrap-DnfXdX1c.mjs"),
import("./client-CiRpnpgB.mjs"),
import("./readiness-CTpHC-IS.mjs"),
import("./method-scopes-BRZbaJbk.mjs"),
import("./client-info-B3Jgw5Z8.mjs")
]);
const l = await e({
config: this.cfg,
gatewayUrl: this.params.gatewayUrl,
explicitAuth: {
token: this.params.gatewayToken,
password: this.params.gatewayPassword
},
env: process.env
});
if (this.closed) {
this.readiness.resolve();
return;
}
this.gateway = new t({
url: l.url,
deviceAuthScope: l.deviceAuthScope,
...l.sshTunnel ? { sshTunnel: l.sshTunnel } : {},
token: l.auth.token,
password: l.auth.password,
preauthHandshakeTimeoutMs: l.preauthHandshakeTimeoutMs,
tlsFingerprint: l.tlsFingerprint,
clientName: c.CLI,
clientDisplayName: "OpenClaw MCP",
clientVersion: VERSION,
mode: s.CLI,
caps: [o.APPROVALS],
scopes: [
i,
a,
r
],
requestTimeoutMs: 18e4,
onEvent: (e) => {
this.dispatchGatewayEvent(e);
},
onHelloOk: () => {
this.retryingInitialConnect = false;
this.handleHelloOk();
},
onConnectError: (e) => {
if (shouldRetryInitialMcpGatewayConnect(e)) {
this.retryingInitialConnect = true;
return;
}
this.readiness.reject(e);
},
onClose: (e, t) => {
if (!this.ready && !this.closed && !this.retryingInitialConnect) this.readiness.reject(/* @__PURE__ */ new Error(`gateway closed before ready (${e}): ${t}`));
this.retryingInitialConnect = false;
}
});
if (!(await n(this.gateway, { clientOptions: { preauthHandshakeTimeoutMs: l.preauthHandshakeTimeoutMs } })).ready) this.readiness.reject(/* @__PURE__ */ new Error("gateway event loop readiness timeout"));
await this.readiness.promise;
}
/** Wait until the bridge has subscribed to Gateway session events. */
async waitUntilReady() {
await this.readiness.promise;
}
/** Stop Gateway IO and release waiters so MCP shutdown cannot hang on pending polls. */
async close() {
if (this.closed) return;
this.closed = true;
this.readiness.resolve();
if (this.pendingSweepInterval) {
clearInterval(this.pendingSweepInterval);
this.pendingSweepInterval = null;
}
this.pendingClaudePermissions.clear();
this.pendingApprovals.clear();
for (const e of this.pendingWaiters) e.settle(null);
const e = this.gateway;
this.gateway = null;
await e?.stopAndWait();
}
/** List Gateway sessions that have enough routing metadata to be channel conversations. */
async listConversations(e) {
await this.waitUntilReady();
const t = await this.requestGateway("sessions.list", {
limit: e?.limit ?? 50,
search: e?.search,
includeDerivedTitles: e?.includeDerivedTitles ?? true,
includeLastMessage: e?.includeLastMessage ?? true
});
const n = normalizeOptionalLowercaseString(e?.channel);
return (t.sessions ?? []).map(toConversation).filter((e) => Boolean(e)).filter((e) => !n || e.channel === n);
}
async getConversation(e) {
const t = e.trim();
if (!t) return null;
await this.waitUntilReady();
const n = await this.requestGateway("sessions.describe", {
key: t,
includeDerivedTitles: true,
includeLastMessage: true
});
return n.session ? toConversation(n.session) : null;
}
async readMessages(e, t = 20) {
await this.waitUntilReady();
return (await this.requestGateway("sessions.get", {
key: e,
limit: t
})).messages ?? [];
}
async readMessage(e, t) {
await this.waitUntilReady();
const n = await this.requestGateway("chat.message.get", {
sessionKey: e,
messageId: t
});
return n.ok === true ? n.message ?? null : null;
}
/** Send a reply using the same channel route stored on the conversation. */
async sendMessage(e) {
const t = await this.getConversation(e.sessionKey);
if (!t) throw new Error(`Conversation not found for session ${e.sessionKey}`);
return await this.requestGateway("send", {
to: t.to,
channel: t.channel,
accountId: t.accountId,
threadId: t.threadId == null ? void 0 : String(t.threadId),
message: e.text,
sessionKey: t.sessionKey,
idempotencyKey: randomUUID()
});
}
listPendingApprovals() {
this.sweepPendingExpired();
return [...this.pendingApprovals.values()].map((e) => e.approval).toSorted((e, t) => (e.createdAtMs ?? 0) - (t.createdAtMs ?? 0));
}
async respondToApproval(e) {
return await this.requestGateway(e.kind === "exec" ? "exec.approval.resolve" : "plugin.approval.resolve", {
id: e.id,
decision: e.decision
});
}
/** Poll queued events after a cursor without consuming them. */
pollEvents(e, t = 20) {
const n = this.queue.filter((t) => matchEventFilter(t, e)).slice(0, t);
const r = this.resolveCursorGap(e.afterCursor);
return {
events: n,
nextCursor: n.at(-1)?.cursor ?? (r ? r.oldest_available_cursor - 1 : e.afterCursor),
...r ? { gap: r } : {}
};
}
/** Wait for the next matching event, returning a closed outcome on every settle path. */
async waitForEvent(e, t = 3e4, n) {
n?.throwIfAborted();
const r = this.queue.find((t) => matchEventFilter(t, e));
const i = this.resolveCursorGap(e.afterCursor);
if (r || i) return {
event: r ?? null,
...i ? { gap: i } : {}
};
return await new Promise((r) => {
const onAbort = () => i.settle(null);
const i = {
filter: e,
settle: (t) => {
this.pendingWaiters.delete(i);
clearTimeout(a);
n?.removeEventListener("abort", onAbort);
const o = this.resolveCursorGap(e.afterCursor);
r({
event: t,
...o ? { gap: o } : {}
});
}
};
const a = setTimeout(() => {
i.settle(null);
}, t);
n?.addEventListener("abort", onAbort, { once: true });
this.pendingWaiters.add(i);
});
}
/** Accept a Claude channel permission notification and expose it through event polling. */
async handleClaudePermissionRequest(e) {
if (this.closed) return;
this.pendingClaudePermissions.set(e.requestId, Date.now());
this.ensurePendingSweeper();
this.enqueue({
cursor: ++this.cursor,
type: "claude_permission_request",
requestId: e.requestId,
toolName: e.toolName,
description: e.description,
inputPreview: e.inputPreview
});
if (this.verbose) process.stderr.write(`openclaw mcp: pending Claude permission ${e.requestId}\n`);
}
async requestGateway(e, t) {
if (!this.gateway) throw new Error("Gateway client is not ready");
return await this.gateway.request(e, t);
}
async sendNotification(e) {
if (!this.server || this.closed) return "unavailable";
try {
await this.server.server.notification(e);
return "delivered";
} catch (t) {
if (this.closed) return "unavailable";
process.stderr.write(`openclaw mcp: notification ${e.method} failed\n`);
if (this.verbose) process.stderr.write(`openclaw mcp: notification ${e.method} error: ${String(t)}\n`);
return "failed";
}
}
async handleHelloOk() {
try {
await this.requestGateway("sessions.subscribe", {});
this.ready = true;
this.readiness.resolve();
} catch (e) {
this.readiness.reject(e instanceof Error ? e : new Error(String(e)));
}
}
resolveCursorGap(e) {
const t = this.queue[0]?.cursor;
return t !== void 0 && e < t - 1 ? {
requested_after_cursor: e,
oldest_available_cursor: t
} : void 0;
}
enqueue(e) {
this.queue.push(e);
while (this.queue.length > QUEUE_LIMIT) this.queue.shift();
for (const t of this.pendingWaiters) {
const n = matchEventFilter(e, t.filter);
if (n || this.resolveCursorGap(t.filter.afterCursor)) t.settle(n ? e : null);
}
}
trackApproval(e, t) {
if (this.closed) return;
const n = normalizeOptionalString(t.id);
if (!n) return;
this.pendingApprovals.set(n, {
approval: {
kind: e,
id: n,
request: t.request && typeof t.request === "object" ? t.request : void 0,
createdAtMs: typeof t.createdAtMs === "number" ? t.createdAtMs : void 0,
expiresAtMs: typeof t.expiresAtMs === "number" ? t.expiresAtMs : void 0
},
trackedAtMs: Date.now()
});
this.ensurePendingSweeper();
}
ensurePendingSweeper() {
if (this.pendingSweepInterval || this.closed) return;
this.pendingSweepInterval = setInterval(() => {
this.sweepPendingExpired();
}, PENDING_SWEEP_INTERVAL_MS);
this.pendingSweepInterval.unref();
}
sweepPendingExpired(e = Date.now()) {
for (const [t, n] of this.pendingClaudePermissions) if (e - n >= PENDING_CLAUDE_PERMISSION_TTL_MS) this.pendingClaudePermissions.delete(t);
for (const [t, n] of this.pendingApprovals) if (e >= (n.approval.expiresAtMs ?? n.trackedAtMs + PENDING_APPROVAL_DEFAULT_TTL_MS)) this.pendingApprovals.delete(t);
if (this.pendingSweepInterval && this.pendingClaudePermissions.size === 0 && this.pendingApprovals.size === 0) {
clearInterval(this.pendingSweepInterval);
this.pendingSweepInterval = null;
}
}
resolveTrackedApproval(e) {
const t = normalizeOptionalString(e.id);
if (t) this.pendingApprovals.delete(t);
}
async dispatchGatewayEvent(e) {
try {
await this.handleGatewayEvent(e);
} catch (t) {
process.stderr.write(`openclaw mcp: gateway event ${e.event} failed\n`);
if (this.verbose) process.stderr.write(`openclaw mcp: gateway event ${e.event} error: ${String(t)}\n`);
}
}
async handleGatewayEvent(e) {
switch (e.event) {
case "session.message":
await this.handleSessionMessageEvent(e.payload);
return;
case "exec.approval.requested":
case "plugin.approval.requested": {
const t = e.payload ?? {};
const n = e.event === "exec.approval.requested" ? "exec" : "plugin";
this.trackApproval(n, t);
this.enqueue({
cursor: ++this.cursor,
type: n === "exec" ? "exec_approval_requested" : "plugin_approval_requested",
raw: t
});
return;
}
case "exec.approval.resolved":
case "plugin.approval.resolved": {
const t = e.payload ?? {};
this.resolveTrackedApproval(t);
this.enqueue({
cursor: ++this.cursor,
type: e.event === "exec.approval.resolved" ? "exec_approval_resolved" : "plugin_approval_resolved",
raw: t
});
}
}
}
async handleSessionMessageEvent(e) {
const t = normalizeOptionalString(e.sessionKey);
if (!t) return;
const n = toConversation({
key: t,
lastChannel: e.lastChannel,
lastTo: e.lastTo,
lastAccountId: e.lastAccountId,
lastThreadId: e.lastThreadId
}) ?? void 0;
const r = normalizeOptionalString(e.message?.role);
const i = extractFirstTextBlock(e.message);
const a = i ? CLAUDE_PERMISSION_REPLY_RE.exec(i) : null;
if (r === "user" && e.senderIsOwner === true && a) {
const e = normalizeOptionalLowercaseString(a[2]);
if (e && this.pendingClaudePermissions.has(e)) {
if (await this.sendNotification({
method: "notifications/claude/channel/permission",
params: {
request_id: e,
behavior: normalizeLowercaseStringOrEmpty(a[1]).startsWith("y") ? "allow" : "deny"
}
}) === "delivered") this.pendingClaudePermissions.delete(e);
return;
}
}
this.enqueue({
cursor: ++this.cursor,
type: "message",
sessionKey: t,
conversation: n,
messageId: normalizeOptionalString(e.messageId),
messageSeq: typeof e.messageSeq === "number" ? e.messageSeq : void 0,
role: r,
text: i,
raw: e
});
if (this.claudeChannelMode === "off" || r !== "user" || !n) return;
await this.sendNotification({
method: "notifications/claude/channel",
params: {
content: i ?? "[non-text message]",
meta: {
session_key: t,
channel: n.channel,
to: n.to,
account_id: n.accountId ?? "",
thread_id: n.threadId == null ? "" : String(n.threadId),
message_id: normalizeOptionalString(e.messageId) ?? ""
}
}
});
}
};
function shouldRetryInitialMcpGatewayConnect(e) {
if (e.name === "GatewayClientRequestError" && "retryable" in e && typeof e.retryable === "boolean") return e.retryable;
const t = e.message.toLowerCase();
return t.includes("gateway request timeout for connect") || t.includes("gateway connect challenge timeout");
}
//#endregion
//#region src/mcp/channel-server.ts
function getChannelMcpCapabilities(e) {
if (e === "off") return;
return { experimental: {
"claude/channel": {},
"claude/channel/permission": {}
} };
}
/** Serve the channel MCP server over stdio until transport or process shutdown. */
async function serveOpenClawChannelMcp(e = {}) {
const { captureRuntimeConfigAsyncReader: t } = await import("./config/config.js");
const n = await t()();
const r = e.claudeChannelMode ?? "auto";
const i = getChannelMcpCapabilities(r);
const a = new McpServer({
name: "openclaw",
version: VERSION
}, i ? { capabilities: i } : void 0);
const o = new OpenClawChannelBridge(n, {
gatewayUrl: e.gatewayUrl,
gatewayToken: e.gatewayToken,
gatewayPassword: e.gatewayPassword,
claudeChannelMode: r,
verbose: e.verbose ?? false
});
o.setServer(a);
a.server.setNotificationHandler("notifications/claude/channel/permission_request", { params: ClaudePermissionRequestSchema.shape.params }, async (e) => {
await o.handleClaudePermissionRequest({
requestId: e.request_id,
toolName: e.tool_name,
description: e.description,
inputPreview: e.input_preview
});
});
a.registerTool("conversations_list", {
description: "List OpenClaw channel-backed conversations available through session routes.",
inputSchema: object({
limit: number().int().min(1).max(500).optional(),
search: string().optional(),
channel: string().optional(),
includeDerivedTitles: boolean().optional(),
includeLastMessage: boolean().optional()
})
}, async (e) => {
const t = await o.listConversations(e);
return summarizeStructuredResult("conversations", t.length, { conversations: t });
});
a.registerTool("conversation_get", {
description: "Get one OpenClaw conversation by session key.",
inputSchema: object({ session_key: string().min(1) })
}, async ({ session_key: e }) => {
const t = await o.getConversation(e);
if (!t) return {
content: [{
type: "text",
text: `conversation not found: ${e}`
}],
isError: true
};
return {
content: [{
type: "text",
text: `conversation ${t.sessionKey}`
}],
structuredContent: { conversation: t }
};
});
a.registerTool("messages_read", {
description: "Read recent messages for one OpenClaw conversation.",
inputSchema: object({
session_key: string().min(1),
limit: number().int().min(1).max(200).optional()
})
}, async ({ session_key: e, limit: t }) => {
const n = await o.readMessages(e, t);
return summarizeStructuredResult("messages", n.length, { messages: n });
});
a.registerTool("attachments_fetch", {
description: "List non-text attachments for a message in one OpenClaw conversation.",
inputSchema: object({
session_key: string().min(1),
message_id: string().min(1)
})
}, async ({ session_key: e, message_id: t }) => {
const n = await o.readMessage(e, t);
if (!n) return {
content: [{
type: "text",
text: `message not found: ${t}`
}],
isError: true
};
const r = extractAttachmentsFromMessage(n);
return {
...summarizeResult("attachments", r.length),
structuredContent: {
attachments: r,
message: n
}
};
});
a.registerTool("events_poll", {
description: "Poll queued OpenClaw conversation events since a cursor.",
inputSchema: object({
after_cursor: number().int().min(0).optional(),
session_key: string().optional(),
limit: number().int().min(1).max(200).optional()
})
}, async ({ after_cursor: e, session_key: t, limit: n }) => {
const { events: r, nextCursor: i, gap: a } = o.pollEvents({
afterCursor: e ?? 0,
sessionKey: normalizeOptionalString(t)
}, n);
return {
...summarizeResult("events", r.length),
structuredContent: {
events: r,
next_cursor: i,
...a ? { gap: a } : {}
}
};
});
a.registerTool("events_wait", {
description: "Wait for the next queued OpenClaw conversation event.",
inputSchema: object({
after_cursor: number().int().min(0).optional(),
session_key: string().optional(),
timeout_ms: number().int().min(1).max(3e5).optional()
})
}, async ({ after_cursor: e, session_key: t, timeout_ms: n }, r) => {
const { event: i, gap: a } = await o.waitForEvent({
afterCursor: e ?? 0,
sessionKey: normalizeOptionalString(t)
}, n, r.mcpReq.signal);
return {
content: [{
type: "text",
text: i ? `event ${i.cursor}` : a ? `event gap before ${a.oldest_available_cursor}` : "timeout"
}],
structuredContent: {
event: i,
...a ? { gap: a } : {}
}
};
});
a.registerTool("messages_send", {
description: "Send a message back through the same OpenClaw conversation route.",
inputSchema: object({
session_key: string().min(1),
text: string().min(1)
})
}, async ({ session_key: e, text: t }) => {
return {
content: [{
type: "text",
text: "sent"
}],
structuredContent: { result: await o.sendMessage({
sessionKey: e,
text: t
}) }
};
});
a.registerTool("permissions_list_open", {
description: "List open OpenClaw exec or plugin approval requests visible through the Gateway.",
inputSchema: object({})
}, async () => {
const e = o.listPendingApprovals();
return {
...summarizeResult("approvals", e.length),
structuredContent: { approvals: e }
};
});
a.registerTool("permissions_respond", {
description: "Allow or deny one pending OpenClaw exec or plugin approval request.",
inputSchema: object({
kind: _enum(["exec", "plugin"]),
id: string().min(1),
decision: _enum([
"allow-once",
"allow-always",
"deny"
])
})
}, async ({ kind: e, id: t, decision: n }) => {
return {
content: [{
type: "text",
text: "approval resolved"
}],
structuredContent: { result: await o.respondToApproval({
kind: e,
id: t,
decision: n
}) }
};
});
const s = new StdioServerTransport();
let c;
const { promise: l, resolve: u } = createDeferredCore();
const shutdown = () => {
if (c) return;
c = Promise.resolve().then(async () => {
const e = await Promise.allSettled([o.close(), a.close()]);
throwIfSettledRejected(e, "OpenClaw channel MCP shutdown failed");
});
process.stdin.off("end", shutdown);
process.stdin.off("close", shutdown);
process.off("SIGINT", shutdown);
process.off("SIGTERM", shutdown);
c.then(u, u);
};
s["onclose"] = shutdown;
process.stdin.once("end", shutdown);
process.stdin.once("close", shutdown);
process.once("SIGINT", shutdown);
process.once("SIGTERM", shutdown);
try {
await a.connect(s);
await o.start();
await l;
await c;
} finally {
shutdown();
await l;
await c;
}
}
//#endregion
export { serveOpenClawChannelMcp };