openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
510 lines (509 loc) • 20.8 kB
JavaScript
import { n as normalizeAccountId, r as normalizeOptionalAccountId } from "./account-id-BqKT3GuY.mjs";
import { t as normalizeChatType } from "./chat-type-CL5nBDaO.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import "./message-channel-normalize-CFHSufeo.mjs";
import { i as resolveChannelPluginRegistration } from "./registry-ByqVE5S3.mjs";
import { t as normalizeConversationReadInvocationOrigin } from "./conversation-read-origin-DMlgOstF.mjs";
import { r as resolveChannelMessageActionFacts } from "./message-action-names-BPsScVN2.mjs";
import { i as withChannelReadAuthority } from "./channel-read-authority-BVl4WY3A.mjs";
import { u as enforceMessageActionAllowlist } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { g as assertOutboundHandoffCurrent } from "./delivery-queue-reconciliation-CQDy7zg8.mjs";
import { r as validateExplicitMessageAccountSelection } from "./message-account-selection-DxhPXlSt.mjs";
//#region src/channels/plugins/message-action-current-conversation.ts
const HOST_TARGET_KIND_PREFIXES = [
"user",
"channel",
"room",
"chat",
"group",
"dm",
"conversation"
];
function isHostConversationTargetKind(e) {
return HOST_TARGET_KIND_PREFIXES.some((t) => t === e);
}
function normalizeHostConversationTarget(e) {
if (typeof e.value !== "string") return;
const t = e.value.trim();
const n = e.normalizeTarget ? e.normalizeTarget(t)?.trim() : t;
if (!n) return;
const r = [e.channel, ...e.providerPrefixes ?? []].map((e) => e.trim().toLowerCase()).filter((e) => Boolean(e) && !isHostConversationTargetKind(e));
const i = n.toLowerCase();
const a = r.find((e) => i.startsWith(`${e}:`));
const o = a ? n.slice(a.length + 1).trim() : n;
if (!o) return;
const s = o.match(/^(user|channel|room|chat|group|dm|conversation):(.*)$/i);
if (s) {
const e = s[2]?.trim();
const t = s[1]?.toLowerCase();
if (!e || !t || !isHostConversationTargetKind(t)) return;
return {
id: e,
kind: t
};
}
return {
id: o,
...e.impliedKind ? { kind: e.impliedKind } : {}
};
}
function targetKey(e) {
return `${e.kind ?? ""}\0${e.id}`;
}
function addHostConversationTarget(e, t) {
if (t) e.set(targetKey(t), t);
}
function hasConflictingTargetKinds(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) {
if (!n.kind) continue;
const e = t.get(n.id);
if (e && e !== n.kind) return true;
t.set(n.id, n.kind);
}
return false;
}
function currentTargetsMatchRequested(e) {
const t = e.currentTargets.filter((t) => t.id === e.requestedTarget.id);
if (t.length === 0 || !e.requestedTarget.kind) return t.length > 0;
const n = t.filter((e) => e.kind);
if (n.length === 0) {
if (!e.requestedTargets.some((t) => t.id === e.requestedTarget.id && !t.kind)) return false;
if (e.currentChatType === "direct") return e.requestedTarget.kind === "user" || e.requestedTarget.kind === "dm";
if (e.currentChatType === "group") return e.requestedTarget.kind === "group" || e.requestedTarget.kind === "room";
if (e.currentChatType === "channel") return e.requestedTarget.kind === "channel";
return false;
}
return n.some((t) => t.kind === e.requestedTarget.kind);
}
function hasMatchingCurrentAccountContext(e) {
const t = e.accountId?.trim() ?? "";
const n = e.requesterAccountId?.trim() ?? "";
if (!n) return false;
if (t && !normalizeOptionalAccountId(t) || !normalizeOptionalAccountId(n)) return false;
return normalizeAccountId(t) === normalizeAccountId(n);
}
function hasMatchingCurrentProviderContext(e) {
const t = e.toolContext?.currentChannelProvider?.trim().toLowerCase();
return Boolean(t && t === e.channel.trim().toLowerCase());
}
function hasCurrentConversationTarget(e) {
return [e.toolContext?.currentChannelId, e.toolContext?.currentMessagingTarget].some((e) => typeof e === "string" && Boolean(e.trim()));
}
function hasTargetInput(e) {
if (typeof e === "string") return Boolean(e.trim());
return typeof e === "number" && Number.isFinite(e);
}
function resolveExactCurrentConversationMatch(e) {
if (!hasMatchingCurrentProviderContext(e.ctx) || !hasMatchingCurrentAccountContext(e.ctx)) return false;
const t = e.pluginTrust === "bundled" ? e.plugin.messaging?.normalizeTarget : void 0;
const n = e.plugin.messaging?.targetPrefixes;
const normalize = (r, i) => normalizeHostConversationTarget({
value: r,
channel: e.ctx.channel,
impliedKind: i,
normalizeTarget: t,
providerPrefixes: n
});
const r = e.pluginTrust === "bundled" ? e.plugin.actions?.messageActionTargetAliases?.[e.ctx.action] : void 0;
const i = new Set(r?.deliveryTargetAliases ?? []);
const a = /* @__PURE__ */ new Map();
for (const [t, n] of [
["target", void 0],
["to", void 0],
["channelId", "channel"],
["roomId", "room"],
["chatId", "chat"]
]) {
const r = e.ctx.params[t];
if (i.has(t)) continue;
const o = normalize(r, n);
if (hasTargetInput(r) && !o) return false;
addHostConversationTarget(a, o);
}
let o = false;
let s;
if (e.pluginTrust === "bundled") {
o = (r?.deliveryTargetAliases ?? []).some((t) => hasTargetInput(e.ctx.params[t]));
const t = r?.resolveDeliveryTarget?.({ args: e.ctx.params });
s = normalize(t);
if (o && !t || t !== void 0 && !s) return false;
addHostConversationTarget(a, s);
}
const c = s ? targetKey(s) : void 0;
const l = Array.from(a.values()).filter((e) => targetKey(e) !== c);
const u = Array.from(a.values());
if (hasConflictingTargetKinds(u)) return false;
const d = /* @__PURE__ */ new Map();
for (const t of [e.ctx.toolContext?.currentChannelId, e.ctx.toolContext?.currentMessagingTarget]) addHostConversationTarget(d, normalize(t));
const f = Array.from(d.values());
if (f.length === 0 || hasConflictingTargetKinds(f)) return false;
if (u.length === 0) return false;
const p = normalizeChatType(e.ctx.toolContext?.currentChatType);
const matchesCurrentTarget = (e) => currentTargetsMatchRequested({
currentTargets: f,
requestedTargets: u,
requestedTarget: e,
currentChatType: p
});
if (u.every(matchesCurrentTarget)) return true;
if (e.pluginTrust !== "bundled" || !o || !e.ctx.toolContext || !r?.matchesCurrentConversationAsync && !r?.matchesCurrentConversation || !l.every(matchesCurrentTarget)) return false;
const m = {
args: e.ctx.params,
accountId: normalizeAccountId(e.ctx.accountId),
toolContext: e.ctx.toolContext
};
const h = r.matchesCurrentConversationAsync;
if (h) return () => h(m);
return r.matchesCurrentConversation?.(m) === true;
}
//#endregion
//#region src/channels/plugins/message-action-dispatch.ts
/** Admit preparation and execution against the same invocation configuration. */
async function prepareMessageActionWriteAuthority(e) {
const { context: t, plugin: n } = e;
const { action: r, channel: i, accountId: a } = t;
if (!e.hasRegistrationAuthority || !n.actions?.writeAuthorityActions?.includes(r)) throw new Error(`Scheduled ${i}:${r} requires an active bundled or verified official plugin with write authorization support. Update and reload a supported plugin, then retry.`);
const assertCurrent = () => {
e.assertCurrent();
t.assertDirectAdapterHandoff?.();
};
assertCurrent();
const o = t.cfg;
enforceMessageActionAllowlist({
cfg: o,
agentId: t.agentId,
action: r
});
await validateExplicitMessageAccountSelection({
cfg: o,
channel: i,
accountId: a,
plugin: n
});
assertCurrent();
const s = {
cfg: o,
accountId: a,
agentId: t.agentId ?? void 0,
sessionKey: t.sessionKey ?? void 0,
sessionId: t.sessionId ?? void 0,
requesterSenderId: t.requesterSenderId ?? void 0,
senderIsOwner: t.senderIsOwner
};
const c = n.actions.describeMessageToolAsync ? await n.actions.describeMessageToolAsync(s) : n.actions.describeMessageTool(s);
assertCurrent();
if (!c?.actions?.includes(r)) throw new Error(`Scheduled ${i}:${r} is disabled for this account.`);
return {
...t,
accountId: a,
assertDirectAdapterHandoff: assertCurrent
};
}
function isFencedProviderReadAction(e) {
return resolveChannelMessageActionFacts(e)?.fencedRead === true;
}
/** Host admission stays action-specific; a plugin declaration never adds actions. */
function isScheduledMessageWriteAction(e) {
return resolveChannelMessageActionFacts(e)?.scheduledWrite !== void 0;
}
/** Validates a live scheduled grant's scope; each action consumer owns admission. */
function resolveScheduledMessageActionAccess(e) {
const t = e.authorization?.scheduled;
if (!t) return;
const n = t.assertSourceCurrent ?? t.assertCurrent;
n();
const r = t.policy;
if (r.mode === "trusted") return {
kind: "trusted-operator",
assertCurrent: n
};
if (!e.accountId || normalizeAccountId(e.accountId) !== r.ownerAccountId) throw new Error(`Scheduled ${e.channel}:${e.action} cannot use another creator account.`);
if (e.action === "channel-edit" && normalizeMessageChannel(e.channel) === "discord") {
const e = t.channelRequester;
if (!e) throw new Error("This account-bound automation needs fresh Discord requester authorization for channel-edit. From its original Discord conversation and account, edit it with an explicit toolsAllow cap including message, or recreate it there.");
if (e.channel !== "discord" || e.accountId !== r.ownerAccountId) throw new Error("Scheduled Discord channel-edit requires its authenticated requester account and channel.");
return {
kind: "account",
channelRequester: e,
assertCurrent: n
};
}
const i = r.ownerOrigin;
if (!i || i.kind === "unknown" || i.kind === "external" && normalizeMessageChannel(e.channel) !== i.channel) throw new Error(`Scheduled ${e.channel}:${e.action} requires matching recorded creator origin.`);
return {
kind: "account",
assertCurrent: n
};
}
function resolveMessageActionReadEnforcement(e) {
const t = e.actions?.providerOwnedReadGates;
if (t === true || t?.includes(e.action) === true) {
const t = e.actions?.readAuthorityActions?.includes(e.action) === true && isFencedProviderReadAction(e.action);
if (e.pluginOrigin === "bundled") return {
kind: "provider-owned",
pluginTrust: "bundled",
fenced: t
};
if (e.hasReadAuthority && t) return {
kind: "provider-owned",
pluginTrust: "external",
fenced: true
};
}
return {
kind: "host-exact-current",
pluginTrust: e.pluginOrigin === "bundled" ? "bundled" : "external"
};
}
function attachExternalCurrentTargetSibling(e) {
if (e.origin === "direct-operator" || e.actionPolicy.kind !== "conversation-read" || e.enforcement.kind !== "host-exact-current" || e.enforcement.pluginTrust !== "external") return e.ctx;
const t = typeof e.ctx.params.target === "string" ? e.ctx.params.target.trim() : "";
if (!t) return e.ctx;
const n = e.ctx.params.to;
if (typeof n !== "string" || n.trim() !== t) return e.ctx;
const r = e.plugin.messaging?.targetPrefixes;
const i = normalizeHostConversationTarget({
value: t,
channel: e.ctx.channel,
providerPrefixes: r
});
if (!i) return e.ctx;
const a = [e.ctx.toolContext?.currentMessagingTarget, e.ctx.toolContext?.currentChannelId].find((t) => {
const n = normalizeHostConversationTarget({
value: t,
channel: e.ctx.channel,
providerPrefixes: r
});
return n?.id === i.id && (!i.kind || !n.kind || n.kind === i.kind);
});
if (!a) return e.ctx;
return {
...e.ctx,
params: {
...e.ctx.params,
to: a.trim()
}
};
}
function canonicalizeExternalExactCurrentTarget(e) {
const t = e.params.target;
const n = [e.params.to, e.params.channelId].find((e) => typeof e === "string" && Boolean(e.trim()));
if (typeof t === "string" && t.trim() && n) e.params.target = n;
}
function prepareMessageActionReadContext(e) {
const t = resolveChannelMessageActionFacts(e.action)?.readPolicy;
if (!t) return;
const n = resolveChannelPluginRegistration(e.channel);
if (!n) return;
const r = e.action;
const i = n.captureReadAuthority?.();
const a = i?.() === true;
const o = resolveMessageActionReadEnforcement({
action: r,
actions: n.plugin.actions,
pluginOrigin: n.origin,
hasReadAuthority: a
});
const s = isFencedProviderReadAction(r) && o.kind === "provider-owned" && o.fenced ? resolveScheduledMessageActionAccess({
authorization: e.messageActionAuthorization,
action: r,
channel: e.channel,
accountId: e.accountId
}) : void 0;
const c = s ? s.kind === "trusted-operator" ? "direct-operator" : "delegated" : normalizeConversationReadInvocationOrigin(e.conversationReadOrigin);
const { messageActionAuthorization: l, ...u } = e;
const d = {
...u,
action: r,
conversationReadOrigin: c
};
const f = e.assertDirectAdapterHandoff;
const p = o.kind === "provider-owned" && o.fenced && !e.messageActionAuthorization?.scheduled && e.toolContext === void 0 && e.requesterAccountId === void 0 ? e.messageActionAuthorization?.assertDashboardReadCurrent : void 0;
const m = (c !== "direct-operator" || s) && o.kind === "provider-owned" && o.fenced ? () => {
f?.();
p?.();
s?.assertCurrent();
if (!i?.()) throw new Error(`Plugin ${e.channel} read authority is no longer active.`);
} : void 0;
return {
actionContext: d,
plugin: n.plugin,
origin: c,
actionPolicy: t,
enforcement: o,
scheduledAccess: s,
assertDashboardReadCurrent: p,
hasRegistrationAuthority: a,
assertReadAuthorityCurrent: m,
assertAliasAuthorityCurrent: () => {
f?.();
p?.();
s?.assertCurrent();
const t = n.captureReadAuthority && !i?.() ? void 0 : resolveChannelPluginRegistration(e.channel, { loadedOnly: true });
if (t?.plugin !== n.plugin || t.origin !== n.origin) throw new Error(`Plugin ${e.channel} alias authority is no longer active.`);
}
};
}
function isExternalDelegatedMessageActionRead(e) {
return Boolean(e && e.origin !== "direct-operator" && e.actionPolicy.kind === "conversation-read" && e.enforcement.kind === "host-exact-current" && e.enforcement.pluginTrust === "external");
}
/** The shared host decision before any read-capable plugin callback runs. */
function resolveMessageActionConversationReadGate(e) {
if (e.actionPolicy.kind === "none" || e.origin === "direct-operator") return true;
if (e.enforcement.kind === "provider-owned") {
if (e.enforcement.fenced && e.enforcement.pluginTrust === "external" && !e.scheduledAccess && !e.assertDashboardReadCurrent && (!hasMatchingCurrentProviderContext(e.ctx) || !hasMatchingCurrentAccountContext(e.ctx) || !hasCurrentConversationTarget(e.ctx))) throw new Error(`Delegated ${e.ctx.channel}:${e.ctx.action} requires current provider and account context.`);
return true;
}
return e.enforcement.pluginTrust === "bundled" && e.actionPolicy.targetlessCache === "bundled-current-context" && hasMatchingCurrentProviderContext(e.ctx) && hasMatchingCurrentAccountContext(e.ctx) && hasCurrentConversationTarget(e.ctx) || resolveExactCurrentConversationMatch({
ctx: e.ctx,
plugin: e.plugin,
pluginTrust: e.enforcement.pluginTrust
});
}
function enforceMessageActionConversationReadMatch(e, t) {
if (!t) throw new Error(`Delegated ${e.ctx.channel}:${e.ctx.action} requires the exact current conversation and account for this plugin.`);
if (e.actionPolicy.kind === "conversation-read" && e.origin !== "direct-operator" && e.enforcement.kind === "host-exact-current" && e.enforcement.pluginTrust === "external") canonicalizeExternalExactCurrentTarget(e.ctx);
}
function enforceMessageActionConversationReadGate(e) {
enforceMessageActionConversationReadMatch(e, resolveMessageActionConversationReadGate(e) === true);
}
async function prepareScheduledMessageWriteContext(e, t) {
const n = t.actionContext.action;
const r = resolveChannelMessageActionFacts(n)?.scheduledWrite;
if (!r || !e.messageActionAuthorization?.scheduled) return;
const i = e.accountId ?? resolveChannelDefaultAccountId({
plugin: t.plugin,
cfg: e.cfg
});
const a = resolveScheduledMessageActionAccess({
authorization: e.messageActionAuthorization,
action: n,
channel: e.channel,
accountId: i
});
if (!a) return;
const o = a.kind === "account" ? a.channelRequester : void 0;
if (r === "operator" && a.kind !== "trusted-operator" && !o) throw new Error(`Scheduled ${e.channel}:${n} requires a job authorized by an operator. Account jobs cannot inherit operator administration.`);
if (r === "provider") {
const r = t.plugin.actions?.providerOwnedReadGates;
if (r !== true && !r?.includes(n)) throw new Error(`Scheduled ${e.channel}:${n} requires provider-owned target authorization.`);
}
return prepareMessageActionWriteAuthority({
context: {
...t.actionContext,
accountId: i,
...o ? {
requesterAccountId: o.accountId,
requesterSenderId: o.senderId,
senderIsOwner: false,
toolContext: void 0
} : { senderIsOwner: r === "operator" ? true : t.actionContext.senderIsOwner },
conversationReadOrigin: r === "operator" ? t.actionContext.conversationReadOrigin : a.kind === "trusted-operator" ? "direct-operator" : "delegated",
assertDirectAdapterHandoff: t.assertAliasAuthorityCurrent
},
plugin: t.plugin,
hasRegistrationAuthority: t.hasRegistrationAuthority,
assertCurrent: a.assertCurrent
});
}
/** Admit provider preparation before resolving an external target. */
async function prepareExternalMessageActionTargetForResolution(e) {
const t = prepareMessageActionReadContext(e);
const n = t && await prepareScheduledMessageWriteContext(e, t);
if (n) return {
params: e.params,
accountId: n.accountId,
assertTargetAuthorityCurrent: n.assertDirectAdapterHandoff
};
if (t?.assertReadAuthorityCurrent) {
t.assertReadAuthorityCurrent();
enforceMessageActionConversationReadGate({
ctx: t.actionContext,
...t
});
return {
params: e.params,
assertReadAuthorityCurrent: t.assertReadAuthorityCurrent
};
}
if (!isExternalDelegatedMessageActionRead(t)) return { params: e.params };
const r = attachExternalCurrentTargetSibling({
ctx: t.actionContext,
...t
});
enforceMessageActionConversationReadGate({
ctx: r,
...t
});
return { params: r.params };
}
/** Defers delegated external target interpretation to the attested Gateway boundary. */
function shouldDeferExternalMessageActionTargetResolution(e) {
const t = prepareMessageActionReadContext(e);
return isExternalDelegatedMessageActionRead(t) || Boolean(t?.assertReadAuthorityCurrent) || Boolean(t && e.messageActionAuthorization?.scheduled && isScheduledMessageWriteAction(t.actionContext.action));
}
/**
* Runs a channel message action if the target plugin supports it.
*/
async function dispatchChannelMessageAction(e) {
const t = prepareMessageActionReadContext(e);
if (!t) return null;
const n = e.messageActionAuthorization?.scheduled && isScheduledMessageWriteAction(t.actionContext.action) ? await prepareScheduledMessageWriteContext(e, t) : void 0;
const run = (e) => withChannelReadAuthority(t.assertReadAuthorityCurrent, async () => {
const { plugin: r } = t;
const i = r.actions;
if (!i?.handleAction) return null;
const a = attachExternalCurrentTargetSibling({
ctx: e,
...t
});
const o = {
ctx: a,
...t
};
const s = n && resolveChannelMessageActionFacts(e.action)?.scheduledWrite === "provider" ? true : resolveMessageActionConversationReadGate(o);
let c;
if (typeof s === "function") {
t.assertAliasAuthorityCurrent();
c = await s();
t.assertAliasAuthorityCurrent();
} else c = s;
enforceMessageActionConversationReadMatch(o, c);
if (r.actions?.requiresTrustedRequesterSender?.({
action: a.action,
toolContext: a.toolContext
}) && !a.requesterSenderId?.trim()) throw new Error(`Trusted sender identity is required for ${a.channel}:${a.action} in tool-driven contexts.`);
if (i.supportsAction && !i.supportsAction({ action: a.action })) return null;
try {
await a.onPlatformSendDispatch?.();
} catch (e) {
assertOutboundHandoffCurrent(a.assertDirectAdapterHandoff);
throw e;
}
assertOutboundHandoffCurrent(a.assertDirectAdapterHandoff);
t.assertReadAuthorityCurrent?.();
if (typeof s === "function") t.assertAliasAuthorityCurrent();
return await i.handleAction(a);
});
if (!n) return await run(t.actionContext);
/** Retain an admitted writer's request guard through provider settlement. */
const r = n;
let i = true;
const assertCurrent = () => {
if (!i) throw new Error(`Scheduled ${r.channel}:${r.action} invocation is no longer active.`);
r.assertDirectAdapterHandoff?.();
};
try {
assertCurrent();
return await run({
...r,
assertDirectAdapterHandoff: assertCurrent
});
} finally {
i = false;
}
}
//#endregion
export { shouldDeferExternalMessageActionTargetResolution as a, prepareExternalMessageActionTargetForResolution as i, isFencedProviderReadAction as n, isScheduledMessageWriteAction as r, dispatchChannelMessageAction as t };