openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
263 lines (262 loc) • 9.27 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { io as validateChannelsPairingListParams, no as validateChannelsPairingApproveParams, ro as validateChannelsPairingDismissParams } from "./src-BX8OAe1J.mjs";
import { o as resolveChannelDmPolicy } from "./dm-access-l7x6KXfl.mjs";
import { r as listChannelPlugins } from "./registry-ByqVE5S3.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import "./plugins-BoMiRtiY.mjs";
import { a as resolvePluginDmPolicy, n as describeChannelAccount, r as resolveChannelAccount } from "./account-resolution-D7u1J1M0.mjs";
import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { n as respondUnavailable, r as respondUnavailableOnThrow, t as respondError } from "./response-C7fEiIN1.mjs";
import { n as defineValidatedGatewayHandler } from "./validation-DwNk6A-B.mjs";
import { i as hasConfiguredCommandOwners } from "./doctor-command-owner-Dul2IrrD.mjs";
import { r as notifyPairingApproved } from "./pairing-_jMW1PcQ.mjs";
import { o as resolveChannelPairingRequestId, t as CHANNEL_PAIRING_PENDING_TTL_MS } from "./pairing-store-model-wI-lqMxh.mjs";
import { a as listChannelPairingRequests, i as dismissChannelPairingRequest, n as approveChannelPairingCode, r as approveChannelPairingRequest } from "./pairing-store-Dwflz9v8.mjs";
import { t as captureLocalStateMutationGuard } from "./local-state-owner-CnxUSfeW.mjs";
import { t as bootstrapCommandOwnerFromPairing } from "./command-owner-D0-ytgJj.mjs";
//#region src/gateway/server-methods/channel-pairing.ts
var InvalidPairingTargetError = class extends Error {};
async function listPairingAccounts(e) {
const t = normalizeOptionalLowercaseString(e.channel);
const n = normalizeOptionalLowercaseString(e.accountId);
const r = listChannelPlugins().flatMap((e) => e.pairing ? [{
plugin: e,
pairing: e.pairing
}] : []);
if (t && !r.some(({ plugin: e }) => e.id === t)) throw new InvalidPairingTargetError(`unknown pairing channel: ${e.channel}`);
const i = [];
for (const { plugin: a, pairing: o } of r) {
if (t && a.id !== t) continue;
for (const t of a.config.listAccountIds(e.cfg)) {
if (n && t.toLowerCase() !== n) continue;
const r = await resolveChannelAccount({
plugin: a,
cfg: e.cfg,
accountId: t
});
if (!(a.config.isConfigured ? await a.config.isConfigured(r, e.cfg) : asOptionalRecord(r)?.configured !== false)) continue;
const s = asOptionalRecord(r);
if (((await resolvePluginDmPolicy({
plugin: a,
cfg: e.cfg,
accountId: t,
account: r
}))?.policy || resolveChannelDmPolicy({
account: s,
parent: asOptionalRecord(s?.config),
defaultPolicy: "pairing"
})) !== "pairing") continue;
const c = await describeChannelAccount({
plugin: a,
account: r,
cfg: e.cfg
});
const l = normalizeOptionalString(c?.name) ?? normalizeOptionalString(asOptionalRecord(r)?.name);
i.push({
plugin: a,
pairing: o,
accountId: t,
...l ? { accountLabel: l } : {}
});
}
}
return i;
}
async function resolvePairingAccount(e) {
try {
const t = await listPairingAccounts(e);
if (t.length === 1) return t[0] ?? null;
invalidPairingRequest(e.respond, `channel account does not use DM pairing: ${e.channel}:${e.accountId}`);
} catch (t) {
respondPairingFailure(e.respond, t);
}
return null;
}
function publicAccount(e) {
return {
channel: e.plugin.id,
channelLabel: e.plugin.meta.label,
accountId: e.accountId,
...e.accountLabel ? { accountLabel: e.accountLabel } : {},
notifySupported: Boolean(e.pairing.notifyApproval)
};
}
function publicRequest(e) {
const t = e.request.meta ? Object.fromEntries(Object.entries(e.request.meta).filter(([e, t]) => e !== "accountId" && e !== "senderId" && t)) : void 0;
const n = Date.parse(e.request.createdAt);
const r = e.request.meta?.senderId ?? e.request.id;
return {
requestId: resolveChannelPairingRequestId(e.account.plugin.id, e.request),
...publicAccount(e.account),
senderId: r,
senderLabel: e.account.pairing.idLabel,
...t && Object.keys(t).length > 0 ? { metadata: t } : {},
createdAt: e.request.createdAt,
lastSeenAt: e.request.lastSeenAt,
expiresAt: new Date(n + CHANNEL_PAIRING_PENDING_TTL_MS).toISOString()
};
}
function invalidPairingRequest(e, t) {
respondError(e, ErrorCodes.INVALID_REQUEST, t);
}
function respondPairingFailure(e, t) {
respondError(e, t instanceof InvalidPairingTargetError ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE, formatForLog(t));
}
function capturePairingCliGuard(e, t) {
if (!t.client?.connect.scopes?.includes("operator.admin")) {
t.respond(false, void 0, errorShape(ErrorCodes.FORBIDDEN, "missing scope: operator.admin", { details: { mutationAccepted: false } }));
return null;
}
try {
return captureLocalStateMutationGuard(e, t);
} catch (e) {
t.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, formatForLog(e), {
details: {
reason: "STATE_OWNER_CHANGED",
mutationAccepted: false
},
retryable: false
}));
return null;
}
}
const channelPairingHandlers = {
"channels.pairing.list": defineValidatedGatewayHandler("channels.pairing.list", validateChannelsPairingListParams, async (e) => {
const { params: t, respond: n, context: r } = e;
if ("format" in t) {
const r = capturePairingCliGuard(t.expectedOwnerId, e);
if (!r) return;
await respondUnavailableOnThrow(n, async () => {
const e = await listChannelPairingRequests(t.channel, process.env, t.accountId, r);
n(true, e, void 0);
});
return;
}
try {
const e = r.getRuntimeConfig();
const i = await listPairingAccounts({
cfg: e,
...t.channel ? { channel: t.channel } : {},
...t.accountId ? { accountId: t.accountId } : {}
});
const a = [];
for (const e of i) {
const t = await listChannelPairingRequests(e.plugin.id, process.env, e.accountId);
a.push(...t.map((t) => publicRequest({
account: e,
request: t
})));
}
n(true, {
accounts: i.map(publicAccount),
requests: a,
commandOwnerConfigured: hasConfiguredCommandOwners(e),
limits: {
pendingPerAccount: 3,
ttlMs: CHANNEL_PAIRING_PENDING_TTL_MS
}
}, void 0);
} catch (e) {
respondPairingFailure(n, e);
}
}),
"channels.pairing.approve": defineValidatedGatewayHandler("channels.pairing.approve", validateChannelsPairingApproveParams, async (e) => {
const { params: t, respond: n, context: r } = e;
if ("code" in t) {
const r = capturePairingCliGuard(t.expectedOwnerId, e);
if (!r) return;
await respondUnavailableOnThrow(n, async () => {
const e = await approveChannelPairingCode({
channel: t.channel,
code: t.code,
accountId: t.accountId,
assertCurrent: r
});
n(true, e, void 0);
});
return;
}
const i = r.getRuntimeConfig();
const a = await resolvePairingAccount({
...t,
cfg: i,
respond: n
});
if (!a) return;
try {
const e = await approveChannelPairingRequest({
channel: a.plugin.id,
accountId: a.accountId,
requestId: t.requestId,
pairingAdapter: a.pairing
});
if (!e) {
invalidPairingRequest(n, "pending DM access request no longer exists");
return;
}
let o = "not-requested";
if (t.bootstrapCommandOwner === true) try {
o = (await bootstrapCommandOwnerFromPairing({
channel: a.plugin.id,
id: e.id
})).status;
} catch (e) {
r.logGateway.warn(`DM pairing command-owner bootstrap failed channel=${a.plugin.id} account=${a.accountId}: ${formatForLog(e)}`);
o = "unavailable";
}
let s = "not-requested";
if (t.notify === true) {
if (!a.pairing.notifyApproval) s = "unsupported";
else try {
await notifyPairingApproved({
channelId: a.plugin.id,
accountId: a.accountId,
id: e.id,
cfg: i,
pairingAdapter: a.pairing,
...e.entry.meta ? { meta: e.entry.meta } : {}
});
s = "sent";
} catch (e) {
r.logGateway.warn(`DM pairing approval notification failed channel=${a.plugin.id} account=${a.accountId}: ${formatForLog(e)}`);
s = "failed";
}
}
n(true, {
requestId: t.requestId,
senderId: e.entry.meta?.senderId ?? e.id,
notification: s,
commandOwnerBootstrap: o
}, void 0);
} catch (e) {
respondUnavailable(n, e);
}
}),
"channels.pairing.dismiss": defineValidatedGatewayHandler("channels.pairing.dismiss", validateChannelsPairingDismissParams, async ({ params: e, respond: t, context: n }) => {
const r = await resolvePairingAccount({
...e,
cfg: n.getRuntimeConfig(),
respond: t
});
if (!r) return;
await respondUnavailableOnThrow(t, async () => {
const n = await dismissChannelPairingRequest({
channel: r.plugin.id,
accountId: r.accountId,
requestId: e.requestId
});
if (!n) {
invalidPairingRequest(t, "pending DM access request no longer exists");
return;
}
t(true, {
requestId: e.requestId,
senderId: n.entry.meta?.senderId ?? n.id
}, void 0);
});
})
};
//#endregion
export { channelPairingHandlers };