openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
559 lines (558 loc) • 19.2 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { n as resolveInboundDebounceMs, t as createInboundDebouncer } from "./inbound-debounce-CDC2NIvq.mjs";
import { l as withSessionEntryReadOnlyInWorker, o as readSessionUpdatedAtInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { o as readSessionUpdatedAtCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs";
import { a as resolveSessionTranscriptRuntimeTarget } from "./session-accessor.transcript-target-njOktg4F.mjs";
import "./sessions-D5Vvu3AE.mjs";
import "./group-thread-context-DFimpu_J.mjs";
import { n as readChannelIngressStoreAllowFromForDmPolicy } from "./store-allow-from-qX0U8hg9.mjs";
import "./location-oMDzIggt.mjs";
import { l as normalizeOutboundReplyPayload } from "./reply-payload-CwASJYas.mjs";
import { t as expandAllowFromWithAccessGroups } from "./access-groups-TMZDMoGF.mjs";
import { n as resolveDmGroupAccessWithLists, t as DM_GROUP_ACCESS_REASON } from "./dm-policy-shared-DYfj6q8U.mjs";
import { o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs";
import "./mentions-CACvAvae.mjs";
import "./dispatch-vEUtrodM.mjs";
import { r as isControlCommandMessage } from "./command-detection-BdYTt9PO.mjs";
import { t as appendPreparedTranscriptEvent } from "./session-transcript-event-f6QomfAt.mjs";
import { a as resolveEnvelopeFormatOptions } from "./envelope-C1e0Wmhj.mjs";
import "./media-C-9Rs9OV.mjs";
import { i as filterChannelInboundSupplementalContext, n as buildHostChannelInboundEventContext, t as buildChannelInboundEventContext } from "./context-BpxG76OD.mjs";
import { n as publicChannelTurnParams, t as publicChannelTurn } from "./reply-options-BcXKrUs5.mjs";
import "./live-DOXDs-ke.mjs";
import { t as runPreparedChannelTurn } from "./execution-CaU-Nl7N.mjs";
import { t as createChannelReplyPipeline } from "./reply-pipeline-BLDOfhMa.mjs";
import { n as dispatchAssembledChannelTurn, r as dispatchRoutedChannelTurn } from "./lifecycle-CvwfkTW3.mjs";
import { n as runChannelTurn } from "./run-channel-turn-DeX5OqYI.mjs";
import { n as createChannelInboundEnvelopeBuilderAsync, o as resolveInboundRouteEnvelopeBuilderWithRuntime } from "./envelope-BOSaj-EC.mjs";
import "./channel-access-compat-DrvFbl9c.mjs";
import "./direct-dm-guard-policy-DPFZ5Mlp.mjs";
import "./logging-DyCvEa9E.mjs";
//#region src/channels/direct-dm-access.ts
function toLegacyDmReasonCode(e) {
switch (e) {
case DM_GROUP_ACCESS_REASON.DM_POLICY_OPEN:
case DM_GROUP_ACCESS_REASON.DM_POLICY_DISABLED:
case DM_GROUP_ACCESS_REASON.DM_POLICY_ALLOWLISTED:
case DM_GROUP_ACCESS_REASON.DM_POLICY_PAIRING_REQUIRED:
case DM_GROUP_ACCESS_REASON.DM_POLICY_NOT_ALLOWLISTED: return e;
default: return DM_GROUP_ACCESS_REASON.DM_POLICY_NOT_ALLOWLISTED;
}
}
/**
* Resolves legacy direct-DM access lists, pairing-store entries, and command authorization.
* @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
*/
async function resolveInboundDirectDmAccessWithRuntime(e) {
const t = e.dmPolicy ?? "pairing";
const n = e.runtime.shouldComputeCommandAuthorized(e.rawBody, e.cfg);
const r = t === "pairing" ? await readChannelIngressStoreAllowFromForDmPolicy({
provider: e.channel,
accountId: e.accountId,
dmPolicy: t,
readStore: e.readStoreAllowFrom
}) : [];
const [i, a] = await Promise.all([e.allowFrom, r].map((t) => expandAllowFromWithAccessGroups({
cfg: e.cfg,
allowFrom: t,
channel: e.channel,
accountId: e.accountId,
senderId: e.senderId,
isSenderAllowed: e.isSenderAllowed,
resolveMembership: e.resolveAccessGroupMembership
})));
const o = resolveDmGroupAccessWithLists({
isGroup: false,
dmPolicy: t,
allowFrom: i,
storeAllowFrom: a,
groupAllowFromFallbackToAllowFrom: false,
isSenderAllowed: (t) => e.isSenderAllowed(e.senderId, t)
});
const s = toLegacyDmReasonCode(o.reasonCode);
const c = e.isSenderAllowed(e.senderId, o.effectiveAllowFrom);
const l = n ? e.runtime.resolveCommandAuthorizedFromAuthorizers?.({
useAccessGroups: true,
authorizers: [{
configured: o.effectiveAllowFrom.length > 0,
allowed: c
}],
modeWhenAccessGroupsOff: e.modeWhenAccessGroupsOff
}) ?? c : void 0;
return {
access: {
decision: o.decision,
reasonCode: s,
reason: o.reason,
effectiveAllowFrom: o.effectiveAllowFrom
},
shouldComputeAuth: n,
senderAllowedForCommands: c,
commandAuthorized: l
};
}
/**
* Creates a pre-crypto authorizer that can issue pairing challenges before payload decryption.
* @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
*/
function createPreCryptoDirectDmAuthorizer(e) {
return async (t) => {
const n = await e.resolveAccess(t.senderId);
const r = "access" in n ? n.access : n;
if (r.decision === "allow") return "allow";
if (r.decision === "pairing") {
await e.issuePairingChallenge?.({
senderId: t.senderId,
reply: t.reply
});
return "pairing";
}
e.onBlocked?.({
senderId: t.senderId,
reason: r.reason,
reasonCode: r.reasonCode
});
return "block";
};
}
//#endregion
//#region src/channels/direct-dm.ts
async function dispatchInboundDirectDm(e) {
const t = resolveAgentRoute({
cfg: e.cfg,
channel: e.channel,
accountId: e.accountId,
peer: e.peer
});
const n = e.resolveChannelIngress ? await e.resolveChannelIngress({
agentId: t.agentId,
sessionKey: t.sessionKey,
messageId: e.messageId,
inboundEventKind: "user_request"
}) : e.channelIngress;
const r = n === e.channelIngress ? e : {
...e,
channelIngress: n
};
const i = (await createChannelInboundEnvelopeBuilderAsync({
cfg: e.cfg,
route: t
}))({
channel: e.channelLabel,
from: e.conversationLabel,
body: e.rawBody,
timestamp: e.timestamp
});
const a = e.channelRuntime?.inbound?.buildContext;
const o = typeof a === "function" ? a : buildChannelInboundEventContext;
const s = await Promise.resolve(o({
channel: e.channel,
accountId: t.accountId,
provider: e.provider,
surface: e.surface,
messageId: e.messageId,
messageIdFull: e.messageId,
timestamp: e.timestamp,
from: e.senderAddress,
sender: {
id: e.senderId,
name: e.conversationLabel
},
conversation: {
kind: "direct",
id: e.peer.id,
routePeer: e.peer,
label: e.conversationLabel
},
route: {
agentId: t.agentId,
accountId: t.accountId,
routeSessionKey: t.sessionKey,
dispatchSessionKey: t.sessionKey
},
reply: {
to: e.recipientAddress,
originatingTo: e.originatingTo ?? e.senderAddress
},
message: {
body: i,
bodyForAgent: e.bodyForAgent ?? e.rawBody,
rawBody: e.rawBody,
commandBody: e.commandBody ?? e.rawBody
},
access: { commands: { authorized: e.commandAuthorized === true } },
channelIngress: r.channelIngress,
extra: {
NativeDirectUserId: e.peer.id,
OriginatingChannel: e.originatingChannel ?? e.channel,
...e.extraContext
}
}));
await dispatchRoutedChannelTurn(buildDirectDmTurnPlan(r, t, s));
return {
route: t,
ctxPayload: s
};
}
function buildDirectDmTurnPlan(e, t, n) {
const { onModelSelected: r, ...i } = createChannelReplyPipeline({
cfg: e.cfg,
agentId: t.agentId,
channel: e.channel,
accountId: t.accountId ?? e.accountId
});
return {
cfg: e.cfg,
channel: e.channel,
accountId: t.accountId ?? e.accountId,
route: {
agentId: t.agentId,
sessionKey: t.sessionKey
},
ctxPayload: n,
assertAuthority: e.assertAuthority,
record: { onRecordError: e.onRecordError },
delivery: {
deliver: async (t) => await e.deliver(normalizeOutboundReplyPayload(t)),
onError: e.onDispatchError
},
replyPipeline: i,
replyOptions: {
onModelSelected: r,
...e.turnAdoptionLifecycle ? { turnAdoptionLifecycle: e.turnAdoptionLifecycle } : {}
}
};
}
/** @deprecated Use dispatchInboundDirectDm. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
async function dispatchInboundDirectDmWithRuntime(e) {
warnPluginSdkDeprecation({
family: "channel-inbound-envelope",
method: "dispatchInboundDirectDmWithRuntime",
replacement: "dispatchInboundDirectDm"
});
const { route: t, buildEnvelope: n } = resolveInboundRouteEnvelopeBuilderWithRuntime({
cfg: e.cfg,
channel: e.channel,
accountId: e.accountId,
peer: e.peer,
runtime: e.runtime.channel,
sessionStore: e.cfg.session?.store
});
const { storePath: r, body: i } = n({
channel: e.channelLabel,
from: e.conversationLabel,
body: e.rawBody,
timestamp: e.timestamp
});
const a = e.runtime.channel.reply.finalizeInboundContext({
Body: i,
BodyForAgent: e.bodyForAgent ?? e.rawBody,
RawBody: e.rawBody,
CommandBody: e.commandBody ?? e.rawBody,
From: e.senderAddress,
To: e.recipientAddress,
SessionKey: t.sessionKey,
AccountId: t.accountId ?? e.accountId,
ChatType: "direct",
ConversationLabel: e.conversationLabel,
SenderId: e.senderId,
Provider: e.provider ?? e.channel,
Surface: e.surface ?? e.channel,
MessageSid: e.messageId,
MessageSidFull: e.messageId,
Timestamp: e.timestamp,
CommandAuthorized: e.commandAuthorized,
...e.inboundAccessAuthorized === true ? {
InboundAccessAuthorized: true,
ConversationRouteContextObserved: true
} : {},
ConversationRoutePeerId: e.peer.id,
OriginatingChannel: e.originatingChannel ?? e.channel,
OriginatingTo: e.originatingTo ?? e.senderAddress,
NativeDirectUserId: e.peer.id,
...e.extraContext
});
const o = buildDirectDmTurnPlan(e, t, a);
await e.runtime.channel.inbound.run({
channel: e.channel,
accountId: t.accountId ?? e.accountId,
raw: a,
adapter: {
ingest: () => ({
id: e.messageId,
timestamp: e.timestamp,
rawText: e.rawBody,
textForAgent: e.bodyForAgent,
textForCommands: e.commandBody,
raw: a
}),
resolveTurn: () => o
}
});
return {
route: t,
storePath: r,
ctxPayload: a
};
}
//#endregion
//#region src/channels/inbound-debounce-policy.ts
function shouldDebounceTextInbound(e) {
if (e.allowDebounce === false) return false;
if (e.hasMedia) return false;
const t = normalizeOptionalString(e.text) ?? "";
if (!t) return false;
return !isControlCommandMessage(t, e.cfg, e.commandOptions);
}
/** Snapshot timing by default; resolveDebounceMs opts into per-entry timing. */
function createChannelInboundDebouncer(e) {
const t = resolveInboundDebounceMs({
cfg: e.cfg,
channel: e.channel,
overrideMs: e.debounceMsOverride
});
const { cfg: n, channel: r, debounceMsOverride: i, ...a } = e;
return {
debounceMs: t,
debouncer: createInboundDebouncer({
debounceMs: t,
...a
})
};
}
//#endregion
//#region src/channels/session-envelope.ts
/** @deprecated Await resolveInboundSessionEnvelopeContextAsync. Retained during stable deprecation. */
function resolveInboundSessionEnvelopeContext(e) {
warnPluginSdkDeprecation({
family: "channel-inbound-envelope",
method: "resolveInboundSessionEnvelopeContext",
replacement: "await resolveInboundSessionEnvelopeContextAsync"
});
const t = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId });
return {
storePath: t,
envelopeOptions: resolveEnvelopeFormatOptions(e.cfg),
previousTimestamp: readSessionUpdatedAtCore({
storePath: t,
sessionKey: e.sessionKey
})
};
}
/** Prepares descriptive session facts before building an inbound envelope. */
async function resolveInboundSessionEnvelopeContextAsync(e) {
const t = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId });
return {
storePath: t,
envelopeOptions: resolveEnvelopeFormatOptions(e.cfg),
previousTimestamp: await readSessionUpdatedAtInWorker({
storePath: t,
sessionKey: e.sessionKey
})
};
}
//#endregion
//#region src/channels/inbound-event/classification.ts
function classifyChannelInboundEvent(e) {
if (e.unmentionedGroupPolicy !== "room_event") return "user_request";
if (e.conversation.kind !== "group" && e.conversation.kind !== "channel") return "user_request";
if (e.wasMentioned === true || e.hasControlCommand === true || e.hasAbortRequest === true || e.commandSource === "native") return "user_request";
return "room_event";
}
function resolveUnmentionedGroupInboundPolicy(e) {
const t = e.agentId ? resolveAgentConfig(e.cfg, e.agentId)?.groupChat : void 0;
if (t && Object.hasOwn(t, "unmentionedInbound")) return t.unmentionedInbound ?? "user_request";
return e.cfg.messages?.groupChat?.unmentionedInbound ?? "user_request";
}
//#endregion
//#region src/channels/feedback-reflection.ts
const DEFAULT_CHANNEL_FEEDBACK_REFLECTION_COOLDOWN_MS = 3e5;
const MAX_RESPONSE_CHARS = 500;
const MAX_COOLDOWN_ENTRIES = 500;
const lastReflectionBySession = /* @__PURE__ */ new Map();
async function recordChannelFeedbackEvent(e) {
const t = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId });
return withSessionEntryReadOnlyInWorker({
agentId: e.agentId,
sessionKey: e.sessionKey,
storePath: t
}, () => {}, async (n, r) => {
if (!n.ok) throw n.error;
if (!n.value?.sessionId) return false;
const i = await resolveSessionTranscriptRuntimeTarget({
...r.scope,
agentId: e.agentId,
sessionId: n.value.sessionId,
sessionKey: e.sessionKey,
storePath: r.scope?.storePath ?? t
});
await appendPreparedTranscriptEvent({
...i,
env: r.scope?.env
}, e.event, r.assertCurrent);
return true;
});
}
function buildReflectionPrompt(e) {
const t = e.thumbedDownResponse;
const n = t && t.length > MAX_RESPONSE_CHARS ? `${truncateUtf16Safe(t, MAX_RESPONSE_CHARS)}...` : t;
return [
"A user indicated your previous response wasn't helpful.",
n ? `\nYour response was:\n> ${n}` : void 0,
e.userComment ? `\nUser's comment: "${e.userComment}"` : void 0,
"\nBriefly reflect: what could you improve? Consider tone, length, accuracy, relevance, and specificity. Reply with one JSON object only: {\"learning\":\"...\",\"followUp\":false,\"userMessage\":\"\"}. Keep learning to 1-2 sentences. Set followUp only when the user needs a direct reply."
].filter(Boolean).join("\n");
}
function parseReflectionResponse(e) {
const t = e.trim();
const n = [t, ...t.match(/```(?:json)?\s*([\s\S]*?)```/i)?.slice(1, 2) ?? []];
for (const e of n) try {
const t = JSON.parse(e.trim());
const n = typeof t.learning === "string" ? t.learning.trim() : "";
if (!n) continue;
return {
learning: n,
followUp: t.followUp === true || typeof t.followUp === "string" && ["true", "yes"].includes(t.followUp.trim().toLowerCase()),
userMessage: (typeof t.userMessage === "string" ? t.userMessage.trim() : "") || void 0
};
} catch {}
return t ? {
learning: t,
followUp: false
} : null;
}
async function runChannelFeedbackReflection(e) {
const t = e.cooldownMs ?? 3e5;
if (Date.now() - (lastReflectionBySession.get(e.sessionKey) ?? Number.NEGATIVE_INFINITY) < t) return { status: "cooldown" };
const n = buildReflectionPrompt(e);
const r = Date.now();
const i = (await createChannelInboundEnvelopeBuilderAsync({
cfg: e.cfg,
route: {
agentId: e.agentId,
sessionKey: e.sessionKey
}
}))({
channel: e.channelLabel,
from: "system",
body: n,
timestamp: r
});
const a = `conversation:${e.conversationId}`;
const o = buildHostChannelInboundEventContext({
channelIngress: "unsupported",
channel: e.channel,
accountId: e.accountId,
messageId: `feedback-reflection:${r}`,
timestamp: r,
from: `${e.channel}:system:${e.conversationId}`,
sender: {
id: "system",
name: "system"
},
conversation: {
kind: e.conversationKind,
id: e.conversationId
},
route: {
agentId: e.agentId,
accountId: e.accountId,
routeSessionKey: e.sessionKey,
dispatchSessionKey: e.sessionKey
},
reply: {
to: a,
originatingTo: a
},
message: {
body: i,
bodyForAgent: n,
rawBody: n,
commandBody: n
},
access: { commands: { authorized: false } },
extra: { ConversationRouteContextObserved: false }
});
const s = [];
await dispatchRoutedChannelTurn({
cfg: e.cfg,
channel: e.channel,
accountId: e.accountId,
route: {
agentId: e.agentId,
sessionKey: e.sessionKey
},
ctxPayload: o,
record: { onRecordError: e.onRecordError },
delivery: {
deliver: async (e) => {
if (e.text) s.push(e.text);
return { visibleReplySent: false };
},
onError: (t) => e.onDispatchError?.(t)
},
replyPipeline: {}
});
const c = s.join("\n");
const l = parseReflectionResponse(c);
if (!l) return { status: "empty" };
lastReflectionBySession.set(e.sessionKey, Date.now());
if (lastReflectionBySession.size > MAX_COOLDOWN_ENTRIES) {
for (const [e, n] of lastReflectionBySession) if (Date.now() - n >= t) lastReflectionBySession.delete(e);
}
return {
status: "complete",
learning: l.learning,
storePath: resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId }),
followUp: l.followUp,
userMessage: l.userMessage,
responseLength: c.trim().length
};
}
//#endregion
//#region src/plugin-sdk/channel-inbound.ts
/**
* Builds inbound-event context for callers still passing `inboundTurnKind`.
*
* @deprecated Use `buildChannelInboundEventContext`.
*/
function buildChannelTurnContext(e) {
const t = e.message.inboundEventKind ?? e.message.inboundTurnKind;
const n = buildChannelInboundEventContext({
...e,
message: {
...e.message,
...t ? { inboundEventKind: t } : {}
}
});
return {
...n,
InboundTurnKind: n.InboundEventKind
};
}
/**
* Deprecated supplemental-context filter alias retained for channel SDK compatibility.
*
* @deprecated Use `filterChannelInboundSupplementalContext`.
*/
const filterChannelTurnSupplementalContext = filterChannelInboundSupplementalContext;
async function runPreparedInboundReply(e) {
return await runPreparedChannelTurn(e);
}
async function runChannelInboundEvent(e) {
return await runChannelTurn(publicChannelTurnParams(e));
}
async function dispatchChannelInboundReply(e) {
return await dispatchAssembledChannelTurn(publicChannelTurn(e));
}
async function dispatchChannelInboundTurn(e) {
return await dispatchRoutedChannelTurn(publicChannelTurn(e));
}
//#endregion
export { dispatchInboundDirectDmWithRuntime as _, runChannelInboundEvent as a, recordChannelFeedbackEvent as c, resolveUnmentionedGroupInboundPolicy as d, resolveInboundSessionEnvelopeContext as f, dispatchInboundDirectDm as g, shouldDebounceTextInbound as h, filterChannelTurnSupplementalContext as i, runChannelFeedbackReflection as l, createChannelInboundDebouncer as m, dispatchChannelInboundReply as n, runPreparedInboundReply as o, resolveInboundSessionEnvelopeContextAsync as p, dispatchChannelInboundTurn as r, DEFAULT_CHANNEL_FEEDBACK_REFLECTION_COOLDOWN_MS as s, buildChannelTurnContext as t, classifyChannelInboundEvent as u, createPreCryptoDirectDmAuthorizer as v, resolveInboundDirectDmAccessWithRuntime as y };