openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
255 lines (254 loc) • 8.47 kB
JavaScript
import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { n as deriveContextPromptTokens } from "./usage-CHLnzpJG.mjs";
import { o as copyReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { s as getGroupThreadDispatchContext } from "./group-thread-context-DFimpu_J.mjs";
import { n as estimateAggregateUsageCost } from "./usage-format-BisQoUIV.mjs";
import { n as resolveAgentIdentity } from "./identity-Cd2mxvzm.mjs";
import { a as hasOutboundReplyContent } from "./reply-payload-CwASJYas.mjs";
import { t as finalizeInboundContext } from "./inbound-context-0zDtB0Zn.mjs";
import { d as summarizeOutboundPayloadForTransport } from "./payloads-CQvywZOF.mjs";
import { u as markReplyDispatchBeforeDeliverDeadlineOwned } from "./reply-dispatcher-DVZA5pVi.mjs";
import { l as toPluginMessageContext, n as deriveInboundMessageHookContext, r as resolveInboundReplyHookTarget } from "./message-hook-mappers-BCrhfgqk.mjs";
import { a as normalizeEmptyPayloadForDelivery } from "./deliver-payload-CXD-N8EQ.mjs";
//#region src/auto-reply/reply/reply-payload-sending-hook.ts
async function runReplyPayloadSendingHook(e, t = getGlobalHookRunner()) {
if (!t?.hasHooks("reply_payload_sending")) return e.payload;
const n = await t.runReplyPayloadSending({
payload: e.payload,
kind: e.kind,
channel: e.channel,
sessionKey: e.sessionKey,
runId: e.runId,
usageState: e.usageState
}, e.context);
if (n?.cancel) return null;
const r = n?.payload ?? e.payload;
return copyReplyPayloadMetadata(e.payload, r);
}
//#endregion
//#region src/auto-reply/reply/reply-usage-state.ts
const TTL_MS = 3e5;
const MAX_REPLY_USAGE_STATE_ENTRIES = 1024;
const store = /* @__PURE__ */ new Map();
function projectHookUsage(e) {
if (!e) return;
const { input: t, output: n, cacheRead: r, cacheWrite: i, total: a } = e;
return {
input: t,
output: n,
cacheRead: r,
cacheWrite: i,
total: a
};
}
function buildReplyUsageState(e) {
const t = e.fallbackExhausted ? void 0 : e.winnerProvider;
const n = e.fallbackExhausted ? void 0 : e.winnerModel;
return {
provider: e.provider,
model: e.model,
resolvedRef: t && n ? `${t}/${n}` : void 0,
reasoningEffort: e.reasoningEffort,
fastMode: e.fastMode,
fallbackUsed: e.fallbackUsed,
agentId: e.agentId,
sessionId: e.sessionId,
chatType: e.chatType,
authMode: e.authMode,
overrideSource: e.overrideSource,
requested: e.requestedProvider && e.requestedModel ? `${e.requestedProvider}/${e.requestedModel}` : void 0,
turnUsd: estimateAggregateUsageCost({
usage: e.usage,
provider: e.provider,
model: e.model,
config: e.config,
agentDir: e.agentDir
}),
durationMs: e.durationMs,
identity: resolveAgentIdentity(e.config, e.agentId),
compactionCount: e.compactionCount,
contextTokenBudget: asFiniteNumber(e.contextTokenBudget),
contextUsedTokens: asFiniteNumber(e.contextUsedTokens) ?? deriveContextPromptTokens(e),
usage: projectHookUsage(e.usage),
lastUsage: projectHookUsage(e.lastCallUsage)
};
}
function prune(e) {
for (const [t, n] of store) if (n.expiresAt < e) store.delete(t);
pruneMapToMaxSize(store, MAX_REPLY_USAGE_STATE_ENTRIES);
}
function recordReplyUsageState(e, t) {
if (!e) return;
const n = Date.now();
store.set(e, {
snapshot: t,
expiresAt: n + TTL_MS
});
prune(n);
}
function consumeReplyUsageState(e) {
if (!e) return;
const t = store.get(e);
return t && t.expiresAt >= Date.now() ? t.snapshot : void 0;
}
//#endregion
//#region src/infra/outbound/deliver-hooks.ts
function buildInboundReplyPayloadSendingBeforeDeliver(e, t, n) {
const r = finalizeInboundContext(e);
const i = deriveInboundMessageHookContext(r);
return markReplyDispatchBeforeDeliverDeadlineOwned(async (e, a) => {
const o = getGroupThreadDispatchContext();
const s = o?.ctx ?? r;
const c = o ? deriveInboundMessageHookContext(o.ctx) : i;
const l = o ? o.runState.runId : t.runId;
const u = await runReplyPayloadSendingHook({
payload: e,
kind: a.kind,
channel: s.Surface ?? s.Provider,
sessionKey: s.SessionKey,
runId: l,
usageState: consumeReplyUsageState(l),
context: {
...toPluginMessageContext(c),
runId: l
}
});
if (!u) {
await n?.(e, a, "cancelled_by_reply_payload_sending_hook");
return null;
}
if (!hasOutboundReplyContent(u)) {
await n?.(u, a, "empty_after_reply_payload_sending_hook");
return null;
}
return u;
});
}
/** Legacy dispatcher-owned `message_sending` stage retained for low-level SDK compatibility. */
function buildLegacyInboundMessageSendingBeforeDeliver(e) {
const t = getGlobalHookRunner();
if (!t?.hasHooks("message_sending")) return;
const n = finalizeInboundContext(e);
const r = deriveInboundMessageHookContext(n);
const i = resolveInboundReplyHookTarget(n, r);
return markReplyDispatchBeforeDeliverDeadlineOwned(async (e) => {
if (!e.text) return e;
const n = getGroupThreadDispatchContext();
const a = await t.runMessageSending({
content: e.text,
to: i
}, {
...toPluginMessageContext(r),
...n ? {
sessionKey: n.ctx.SessionKey,
runId: n.runState.runId
} : {}
});
if (a?.cancel) return null;
return a?.content == null ? e : copyReplyPayloadMetadata(e, {
...e,
text: a.content
});
});
}
/** Run media-aware message policy before a core owner can capture projected output. */
function buildProjectedInboundMessageSendingBeforeDeliver(e) {
const t = finalizeInboundContext(e);
const n = deriveInboundMessageHookContext(t);
const r = resolveInboundReplyHookTarget(t, n);
return markReplyDispatchBeforeDeliverDeadlineOwned(async (e) => {
const i = getGlobalHookRunner();
const a = await applyMessageSendingHook({
hookRunner: i,
enabled: i?.hasHooks("message_sending") ?? false,
payload: e,
payloadSummary: summarizeOutboundPayloadForTransport(e),
to: r,
channel: n.channelId,
accountId: n.accountId,
replyToId: e.replyToId ?? t.ReplyToIdFull ?? t.ReplyToId,
threadId: t.MessageThreadId,
sessionKey: t.SessionKey
});
if (a.cancelled) return null;
return normalizeEmptyPayloadForDelivery(a.payload);
});
}
async function applyMessageSendingHook(e) {
const unchanged = () => ({
cancelled: false,
changed: false,
payload: e.payload
});
if (!e.enabled) return unchanged();
try {
const t = getGroupThreadDispatchContext();
const n = await e.hookRunner.runMessageSending({
to: e.to,
content: e.payloadSummary.hookContent ?? e.payloadSummary.text,
replyToId: e.replyToId ?? void 0,
threadId: e.threadId ?? void 0,
metadata: {
channel: e.channel,
accountId: e.accountId,
mediaUrls: e.payloadSummary.mediaUrls
}
}, {
channelId: e.channel,
accountId: e.accountId ?? void 0,
conversationId: e.to,
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...t ? {
sessionKey: t.ctx.SessionKey,
runId: t.runState.runId
} : {}
});
if (n?.cancel) {
const { cancelReason: e, metadata: t } = n;
return {
...unchanged(),
cancelled: true,
hookEffect: e || t ? {
...e ? { cancelReason: e } : {},
...t ? { metadata: t } : {}
} : void 0
};
}
if (n?.content == null) return unchanged();
const r = e.payloadSummary.hookContent && !e.payloadSummary.text;
return {
cancelled: false,
changed: true,
payload: copyReplyPayloadMetadata(e.payload, {
...e.payload,
[r ? "spokenText" : "text"]: n.content
})
};
} catch {
return unchanged();
}
}
async function applyReplyPayloadSendingHook(e, t = getGlobalHookRunner()) {
if (!e.hook) return {
cancelled: false,
payload: e.payload,
changed: false
};
const n = await runReplyPayloadSendingHook({
payload: e.payload,
kind: e.hook.kind,
...e.hook.channel ? { channel: e.hook.channel } : {},
...e.hook.sessionKey ? { sessionKey: e.hook.sessionKey } : {},
...e.hook.runId ? { runId: e.hook.runId } : {},
context: e.hook.context
}, t);
return {
cancelled: !n,
payload: n ?? e.payload,
changed: n !== null && n !== e.payload
};
}
//#endregion
export { buildProjectedInboundMessageSendingBeforeDeliver as a, buildLegacyInboundMessageSendingBeforeDeliver as i, applyReplyPayloadSendingHook as n, buildReplyUsageState as o, buildInboundReplyPayloadSendingBeforeDeliver as r, recordReplyUsageState as s, applyMessageSendingHook as t };