openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
774 lines (773 loc) • 30.1 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { y as sortUniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { r as getInProcessGatewayRequestContext } from "./gateway-request-scope-BvvDhs5D.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { E as parseSessionDeliveryRoute, j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { t as normalizeRouteBindingChannelId } from "./binding-scope-C3Xc3l9P.mjs";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { t as isDeliverableMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs";
import { n as getLoadedChannelPlugin, t as getChannelPlugin } from "./registry-ByqVE5S3.mjs";
import "./message-channel-DTYVLJT1.mjs";
import "./plugins-BoMiRtiY.mjs";
import { r as stripTargetProviderPrefix } from "./channel-target-prefix-tRLuyxKs.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { t as SessionRowProjectionBinding } from "./session-row-projection-binding-TqlL_YAz.mjs";
import { r as loadExactSessionEntryReadOnly } from "./session-accessor.sqlite-exact-read-CbvqUmsG.mjs";
import { r as readExactSessionDeliveryContext } from "./delivery-info-DGIoojvH.mjs";
import { i as listRouteBindings } from "./bindings-C2C-UuI7.mjs";
import { t as CHANNEL_MESSAGE_ACTION_NAMES } from "./message-action-names-BPsScVN2.mjs";
import { d as resolveAllowedMessageActions } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { t as createCachedToolSchema } from "./cached-schema-DxTpNYje.mjs";
import { n as stringEnum } from "./string-enum-DXKqjXG0.mjs";
import { a as optionalNonNegativeIntegerSchema, n as channelTargetsSchema, o as optionalPositiveIntegerSchema, t as channelTargetSchema } from "./typebox-BwU4K8-3.mjs";
import { t as gatewayCallOptionSchemaProperties } from "./gateway-schema-CGh2ao1T.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { a as resolveChannelMessageToolSchemaPropertiesSteps, d as runMessageActionDiscoveryAsync, n as listCrossChannelSchemaSupportedMessageActionsSteps, r as listMessageActionDiscoveryChannels, s as resolveCurrentMessageActionDiscoverySteps, u as runMessageActionDiscovery } from "./message-action-discovery-D58BOJ5F.mjs";
import { n as resolveImplicitMessageActionTarget, r as actionHasTarget } from "./message-action-normalization-BoubNx7z.mjs";
import { n as listChannelSupportedActionsSteps } from "./channel-tools-DpmP6M7X.mjs";
import { n as SHARED_POLL_CREATION_PARAM_NAMES, t as POLL_CREATION_PARAM_DEFS } from "./poll-params-CdaOp94w.mjs";
import { Type } from "typebox";
//#region src/agents/tools/message-tool-schema.ts
const MESSAGE_TOOL_SEND_TEXT_DESCRIPTION = "Text for action=\"send\". A send needs message or another send payload such as media, attachments, or presentation.";
function optionalStringSchema(e) {
return Type.Optional(Type.String(e === void 0 ? void 0 : { description: e }));
}
function optionalBooleanSchema(e) {
return Type.Optional(Type.Boolean(e === void 0 ? void 0 : { description: e }));
}
function buildRoutingSchema(e) {
const t = {
channel: optionalStringSchema(),
target: Type.Optional(channelTargetSchema()),
targets: Type.Optional(channelTargetsSchema()),
accountId: optionalStringSchema(),
dryRun: optionalBooleanSchema()
};
if (e.includeTeamId) t.teamId = optionalStringSchema("Team or workspace ID for channel-create, channel-info, channel-list, or conversation-open.");
return t;
}
const presentationCommandActionSchema = Type.Object({
type: Type.Literal("command"),
command: Type.String()
});
const presentationCallbackActionSchema = Type.Object({
type: Type.Literal("callback"),
value: Type.String()
});
const presentationCommandOrCallbackActionSchema = Type.Union([presentationCommandActionSchema, presentationCallbackActionSchema]);
const presentationButtonActionSchema = Type.Union([
presentationCommandActionSchema,
presentationCallbackActionSchema,
Type.Object({
type: Type.Literal("url"),
url: Type.String()
}),
Type.Object({
type: Type.Literal("web-app"),
url: Type.String(),
widgetId: optionalStringSchema()
}),
Type.Object({
type: Type.Literal("web-app"),
url: optionalStringSchema(),
widgetId: Type.String()
})
]);
const presentationOptionSchema = Type.Object({
label: Type.String(),
action: Type.Optional(presentationCommandOrCallbackActionSchema),
value: optionalStringSchema()
});
const presentationButtonSchema = Type.Object({
label: Type.String(),
action: Type.Optional(presentationButtonActionSchema),
value: optionalStringSchema(),
url: optionalStringSchema(),
webApp: Type.Optional(Type.Object({ url: Type.String() })),
web_app: Type.Optional(Type.Object({ url: Type.String() })),
disabled: optionalBooleanSchema(),
reusable: optionalBooleanSchema(),
style: Type.Optional(stringEnum([
"primary",
"secondary",
"success",
"danger"
]))
});
const presentationChartSegmentSchema = Type.Object({
label: Type.String(),
value: Type.Number()
});
const presentationChartSeriesSchema = Type.Object({
name: Type.String(),
values: Type.Array(Type.Number(), { minItems: 1 })
});
const presentationBlockSchema = Type.Object({
type: stringEnum([
"text",
"context",
"divider",
"buttons",
"select",
"chart",
"table"
]),
text: optionalStringSchema(),
buttons: Type.Optional(Type.Array(presentationButtonSchema)),
placeholder: optionalStringSchema(),
options: Type.Optional(Type.Array(presentationOptionSchema)),
chartType: Type.Optional(stringEnum([
"pie",
"bar",
"area",
"line"
])),
title: optionalStringSchema(),
segments: Type.Optional(Type.Array(presentationChartSegmentSchema, { minItems: 1 })),
categories: Type.Optional(Type.Array(Type.String(), { minItems: 1 })),
series: Type.Optional(Type.Array(presentationChartSeriesSchema, { minItems: 1 })),
xLabel: optionalStringSchema(),
yLabel: optionalStringSchema(),
caption: optionalStringSchema(),
headers: Type.Optional(Type.Array(Type.String(), { minItems: 1 })),
rows: Type.Optional(Type.Array(Type.Array(Type.Unsafe({ type: ["string", "number"] }), { minItems: 1 }), { minItems: 1 })),
rowHeaderColumnIndex: Type.Optional(Type.Integer({ minimum: 0 }))
});
const presentationMessageSchema = Type.Object({
title: optionalStringSchema(),
tone: Type.Optional(stringEnum([
"info",
"success",
"warning",
"danger",
"neutral"
])),
blocks: Type.Array(presentationBlockSchema)
}, { description: "Rich text/chart/table/button/select/context; unsupported degrades to text." });
function buildSendSchema(e) {
const t = {
message: optionalStringSchema(MESSAGE_TOOL_SEND_TEXT_DESCRIPTION),
effectId: optionalStringSchema("sendWithEffect id/name."),
effect: optionalStringSchema("Alias for effectId."),
media: optionalStringSchema("Media URL/path. data: use buffer."),
filename: optionalStringSchema(),
buffer: optionalStringSchema("Base64/data-URL attachment."),
contentType: optionalStringSchema(),
mimeType: optionalStringSchema(),
caption: optionalStringSchema(),
attachments: Type.Optional(Type.Array(Type.Object({
type: Type.Optional(stringEnum([
"image",
"audio",
"video",
"file"
])),
media: optionalStringSchema(),
name: optionalStringSchema(),
mimeType: optionalStringSchema()
}), { description: "Attachments; each uses media." })),
replyTo: optionalStringSchema(),
threadId: optionalStringSchema(),
asVoice: optionalBooleanSchema("Send audio as a voice note; combines with voiceText."),
voiceText: optionalStringSchema("Text to synthesize; message remains visible."),
voiceProvider: optionalStringSchema("Per-send speech provider override."),
voiceId: optionalStringSchema("Per-send speech voice override."),
silent: optionalBooleanSchema(),
quoteText: optionalStringSchema("Telegram reply quote text."),
gifPlayback: optionalBooleanSchema(),
forceDocument: optionalBooleanSchema("Send media as document; no compression."),
asDocument: optionalBooleanSchema("Alias for forceDocument.")
};
if (e.includeClawHub) t.clawhub = Type.Optional(Type.Object({
query: Type.String({
minLength: 1,
maxLength: 160
}),
kind: Type.Optional(stringEnum(["plugin", "skill"]))
}, {
additionalProperties: false,
description: "Official plugin/skill cards in current chat; user chooses install. Omit kind: plugins, then skills."
}));
if (e.includePresentation) t.presentation = Type.Optional(presentationMessageSchema);
if (e.includeBestEffort) t.bestEffort = optionalBooleanSchema("Ordinary reply omit/true; false only requiring durable delivery.");
if (e.includeDeliveryPin) t.delivery = Type.Optional(Type.Object({ pin: Type.Optional(Type.Union([Type.Boolean(), Type.Object({
enabled: Type.Boolean(),
notify: optionalBooleanSchema(),
required: optionalBooleanSchema()
})])) }, { description: "Delivery prefs; pin when supported." }));
return t;
}
const POLL_SCHEMA_BUILDERS = {
string: optionalStringSchema,
stringArray: () => Type.Optional(Type.Array(Type.String())),
positiveInteger: optionalPositiveIntegerSchema,
boolean: optionalBooleanSchema
};
function buildPollSchema() {
const e = {
pollId: optionalStringSchema(),
pollOptionId: optionalStringSchema("Poll answer id."),
pollOptionIds: Type.Optional(Type.Array(Type.String({ description: "Poll answer ids for multiselect." }))),
pollOptionIndex: Type.Optional(Type.Integer({
minimum: 1,
description: "1-based poll option number."
})),
pollOptionIndexes: Type.Optional(Type.Array(Type.Integer({
minimum: 1,
description: "1-based poll option numbers for multiselect."
})))
};
for (const t of SHARED_POLL_CREATION_PARAM_NAMES) {
const n = POLL_CREATION_PARAM_DEFS[t];
if (!n) continue;
e[t] = POLL_SCHEMA_BUILDERS[n.kind]();
}
return e;
}
const MESSAGE_SCHEMA_GROUPS = [
{
build: () => ({
messageId: optionalStringSchema("Target read/react/edit/delete/pin/unpin id; reactions default current inbound."),
message_id: optionalStringSchema("snake_case alias of messageId; same defaults."),
emoji: optionalStringSchema("Unicode emoji; channels may also support custom emoji."),
remove: optionalBooleanSchema(),
trackToolCalls: optionalBooleanSchema("Use the reacted message for this turn's status reaction lifecycle."),
track_tool_calls: optionalBooleanSchema("snake_case alias of trackToolCalls."),
targetAuthor: optionalStringSchema(),
targetAuthorUuid: optionalStringSchema(),
groupId: optionalStringSchema()
}),
actions: [
"react",
"reactions",
"read",
"edit",
"delete",
"unsend",
"pin",
"unpin",
"reply",
"thread-create"
]
},
{
build: () => ({
limit: optionalPositiveIntegerSchema({ description: "Maximum number of results to return." }),
pageSize: optionalPositiveIntegerSchema(),
pageToken: optionalStringSchema(),
before: optionalStringSchema(),
after: optionalStringSchema(),
around: optionalStringSchema(),
fromMe: optionalBooleanSchema(),
includeArchived: optionalBooleanSchema()
}),
actions: [
"read",
"reactions",
"search",
"thread-list",
"channel-list",
"channel-info",
"list-pins",
"event-list",
"sticker-search",
"emoji-list"
]
},
{
build: () => ({ query: optionalStringSchema() }),
actions: [
"search",
"sticker-search",
"channel-list"
]
},
{
build: buildPollSchema,
actions: ["poll", "poll-vote"]
},
{
build: () => ({
channelId: optionalStringSchema("Channel id filter."),
chatId: optionalStringSchema("Chat id for chat metadata."),
channelIds: Type.Optional(Type.Array(Type.String({ description: "Channel id filter." }))),
memberId: optionalStringSchema(),
memberIdType: optionalStringSchema(),
guildId: optionalStringSchema(),
userId: optionalStringSchema("member-info/moderation/participant user id; member-info uses userId, not target."),
openId: optionalStringSchema(),
unionId: optionalStringSchema(),
authorId: optionalStringSchema(),
authorIds: Type.Optional(Type.Array(Type.String())),
roleId: optionalStringSchema(),
roleIds: Type.Optional(Type.Array(Type.String())),
participant: optionalStringSchema(),
includeMembers: optionalBooleanSchema(),
members: optionalBooleanSchema(),
scope: optionalStringSchema(),
kind: optionalStringSchema()
}),
actions: [
"search",
"thread-list",
"thread-create",
"thread-reply",
"channel-info",
"channel-list",
"channel-create",
"channel-edit",
"channel-delete",
"channel-move",
"category-create",
"category-edit",
"category-delete",
"topic-create",
"topic-edit",
"permissions",
"member-info",
"role-info",
"role-add",
"role-remove",
"addParticipant",
"removeParticipant",
"renameGroup",
"setGroupIcon",
"leaveGroup",
"event-create",
"event-list",
"timeout",
"kick",
"ban",
"emoji-list",
"emoji-upload",
"sticker-upload",
"voice-status",
"download-file"
]
},
{
build: () => ({
fileId: optionalStringSchema(),
emojiName: optionalStringSchema("Name for an uploaded custom emoji."),
stickerId: Type.Optional(Type.Array(Type.String())),
stickerName: optionalStringSchema(),
stickerDesc: optionalStringSchema(),
stickerTags: optionalStringSchema()
}),
actions: [
"sticker",
"sticker-search",
"sticker-upload",
"emoji-list",
"emoji-upload",
"download-file",
"upload-file"
]
},
{
build: () => ({
threadName: optionalStringSchema(),
autoArchiveMin: optionalPositiveIntegerSchema(),
appliedTags: Type.Optional(Type.Array(Type.String()))
}),
actions: [
"thread-create",
"thread-list",
"thread-reply"
]
},
{
build: () => ({
eventName: optionalStringSchema(),
eventType: optionalStringSchema(),
startTime: optionalStringSchema(),
endTime: optionalStringSchema(),
desc: optionalStringSchema(),
location: optionalStringSchema(),
image: optionalStringSchema("Event cover image URL/path.")
}),
actions: ["event-create", "event-list"]
},
{
build: () => ({
reason: optionalStringSchema(),
deleteDays: optionalNonNegativeIntegerSchema({ maximum: 7 }),
durationMin: optionalNonNegativeIntegerSchema(),
until: optionalStringSchema()
}),
actions: [
"timeout",
"kick",
"ban",
"delete",
"unsend"
]
},
{
build: () => ({
name: optionalStringSchema(),
channelType: Type.Optional(Type.Integer({
minimum: 0,
description: "Numeric channel type; avoids schema type collision."
})),
parentId: optionalStringSchema(),
topic: optionalStringSchema(),
position: optionalNonNegativeIntegerSchema(),
nsfw: optionalBooleanSchema(),
rateLimitPerUser: optionalNonNegativeIntegerSchema(),
categoryId: optionalStringSchema(),
clearParent: optionalBooleanSchema("Clear parent/category when supported.")
}),
actions: [
"channel-create",
"channel-edit",
"channel-move",
"category-create",
"category-edit",
"category-delete",
"topic-create",
"topic-edit",
"renameGroup",
"setGroupIcon"
]
},
{
build: () => ({
activityType: optionalStringSchema("Activity type: playing, streaming, listening, watching, competing, custom."),
activityName: optionalStringSchema("Activity name shown in sidebar; ignored for custom."),
activityUrl: optionalStringSchema("Streaming URL; streaming type only."),
activityState: optionalStringSchema("State text; custom type uses as status text."),
status: optionalStringSchema("Bot status: online, dnd, idle, invisible.")
}),
actions: [
"set-presence",
"set-profile",
"voice-status"
]
}
];
function buildMessageToolSchemaFromActions(e, t) {
return messageToolSchemas({
actions: e,
options: t
});
}
const messageToolSchemas = createCachedToolSchema({
key: ({ actions: e, options: t }) => JSON.stringify([
e,
t.includeClawHub === true,
t.includePresentation,
t.includeDeliveryPin,
t.includeBestEffort,
t.extraProperties ? Type.Object(t.extraProperties) : null
]),
build: ({ actions: e, options: t }) => buildMessageToolSchema$1(e, t)
});
function buildMessageToolSchema$1(e, t) {
const n = {
...t,
includeTeamId: e.some((e) => e === "channel-info" || e === "channel-list" || e === "channel-create" || e === "conversation-open")
};
const r = {
...buildRoutingSchema(n),
...buildSendSchema(n),
...gatewayCallOptionSchemaProperties()
};
const i = new Set(e);
for (const e of MESSAGE_SCHEMA_GROUPS) if (e.actions.some((e) => i.has(e))) Object.assign(r, e.build());
return Type.Object({
action: stringEnum(e, { description: "Select one action. For action=\"send\", provide message or another send payload; fields for other actions do not count as send content." }),
...r,
...n.extraProperties,
final: Type.Optional(Type.Boolean({ description: "For source replies, set false for progress; set true, or omit, for a completed send. For react, set true when adding a reaction to the current source message is your complete response; omit or set false when more work follows. A confirmed final source reply ends the turn." }))
});
}
const MessageToolSchema = buildMessageToolSchemaFromActions(CHANNEL_MESSAGE_ACTION_NAMES, {
includePresentation: true,
includeDeliveryPin: true,
includeBestEffort: false
});
//#endregion
//#region src/agents/tools/message-tool-discovery.ts
function readMessageToolSessionBinding(e) {
const t = e?.agentSessionKey;
const n = e?.agentId ?? parseAgentSessionKey(t)?.agentId;
if (!t || !n || !e?.config) return;
const r = {
agentId: n,
storePath: resolveSessionStorePathCore(e.config.session?.store, { agentId: n }),
sessionKey: t,
projection: "list"
};
const i = getInProcessGatewayRequestContext()?.sessionRowProjectionOwner;
return {
scope: r,
current: i instanceof SessionRowProjectionBinding ? i.readCommittedEntry({
...r,
key: t
}) : void 0
};
}
/** Released synchronous SDK factories retain the existing synchronous session reader. */
function readMessageToolSessionEntry(e) {
const t = readMessageToolSessionBinding(e);
return t?.current ? t.current.entry : t ? loadExactSessionEntryReadOnly(t.scope)?.entry : void 0;
}
async function prepareMessageToolSessionBinding(e) {
const t = readMessageToolSessionBinding(e);
return t?.current ? t.current.entry : t ? await readSessionEntryReadOnlyInWorker(t.scope) : void 0;
}
function formatSessionDeliveryTarget(e, t, n) {
return (t === "direct" || t === "dm") && getChannelPlugin(e)?.messaging?.directTargetStyle === "user-prefixed" ? `user:${n}` : n;
}
function resolveSessionDeliveryChatType(e) {
if (e === "direct" || e === "dm") return "direct";
return e === "group" || e === "channel" ? e : void 0;
}
async function recoverSessionCanonicalPeerId(e) {
const { request: t } = e;
if (!t || normalizeOptionalString(t.params.target) || Array.isArray(t.params.targets) && t.params.targets.length > 0 || actionHasTarget(t.action, t.params, {
channel: e.channel,
aliasSpec: t.preparedMessageToolCatalog ? t.preparedMessageToolCatalog.getChannel(e.channel)?.actions?.messageActionTargetAliases?.[t.action] ?? null : void 0
})) return e.peerId;
const n = getChannelPlugin(e.channel);
if (n?.messaging?.targetIdComparison !== "case-sensitive") return e.peerId;
const r = await readExactSessionDeliveryContext({
cfg: t.config,
sessionKey: e.sessionKey,
sessionId: e.sessionId
});
const i = t.accountId ?? resolveChannelDefaultAccountId({
plugin: n,
cfg: t.config
});
if (normalizeMessageChannel(r?.channel) !== e.channel || normalizeAccountId(r?.accountId) !== normalizeAccountId(i)) return e.peerId;
const a = normalizeOptionalString(r?.to);
const o = a ? stripTargetProviderPrefix(a, e.channel, r?.channel ?? "") : void 0;
return o && o.toLowerCase() === e.peerId.toLowerCase() ? o : e.peerId;
}
function inferDeliveryFromSessionKey(e, t) {
const n = parseSessionDeliveryRoute(e);
if (!n) return null;
const r = normalizeMessageChannel(n.channel);
if (!r || r === "webchat") return null;
const i = n.accountId ? resolveAgentAccountId(n.accountId) : void 0;
const a = t ?? n.peerId;
return {
accountId: i,
channel: r,
chatType: resolveSessionDeliveryChatType(n.peerKind),
threadId: n.threadId,
to: formatSessionDeliveryTarget(r, n.peerKind, a)
};
}
/** A session can receive WebChat prompts independently of its delivery route. */
function supportsMessageToolPromptReactions(e) {
return Boolean(e?.agentSessionKey) || normalizeMessageChannel(e?.currentChannelProvider) === "webchat";
}
function resolveMessageToolDefinitionContext(e, t) {
if (!e?.agentSessionKey) return resolveEffectiveCurrentChannelContext(e);
const n = inferDeliveryFromSessionKey(e.agentSessionKey);
const r = t?.delivery?.kind === "external" ? t.delivery : void 0;
return {
currentChannelProvider: r?.context.channel ?? n?.channel ?? (parseAgentSessionKey(e.agentSessionKey)?.rest.startsWith("dashboard:") ? "webchat" : void 0),
currentChannelId: r?.context.to ?? n?.to,
currentChatType: r?.origin.chatType ?? n?.chatType,
currentThreadTs: r?.context.threadId?.toString() ?? n?.threadId,
accountId: r?.context.accountId ?? n?.accountId
};
}
function resolveMessageToolScheduledAccountScope(e, t) {
const n = t?.cronRunContinuation;
const r = n?.scheduledToolPolicy?.mode === "account" ? {
...n.scheduledToolPolicy,
ownerOrigin: n.scheduledToolCallerOrigin
} : e;
if (r?.mode !== "account") return;
const i = r.ownerOrigin;
return i?.kind === "local" ? { accountId: r.ownerAccountId } : i?.kind === "external" ? {
accountId: r.ownerAccountId,
channels: [i.channel]
} : void 0;
}
function resolveEffectiveCurrentChannelContext(e) {
return projectCurrentChannelContext(e, inferDeliveryFromSessionKey(e?.agentSessionKey));
}
/** Use the message tool's effective route and target defaulting for reply guidance. */
function hasMessageToolSourceConversation(e) {
const t = resolveEffectiveCurrentChannelContext(e);
const n = normalizeMessageChannel(t.currentChannelProvider);
return Boolean(n && isDeliverableMessageChannel(n) && resolveImplicitMessageActionTarget(t, "send"));
}
/** Recover opaque peer casing through the session owner only when executing an inferred send. */
async function resolveEffectiveCurrentChannelContextForRequest(e, t) {
if (!t) return resolveEffectiveCurrentChannelContext(e);
const n = parseSessionDeliveryRoute(e?.agentSessionKey);
const r = n && normalizeMessageChannel(n.channel);
const i = n && r && normalizeMessageChannel(e?.currentChannelProvider) === "webchat" ? await recoverSessionCanonicalPeerId({
request: t,
channel: r,
peerId: n.peerId,
sessionKey: e?.agentSessionKey,
sessionId: e?.sessionId
}) : void 0;
return projectCurrentChannelContext(e, inferDeliveryFromSessionKey(e?.agentSessionKey, i));
}
function projectCurrentChannelContext(e, t) {
const n = e?.currentChannelProvider;
const r = e?.currentChannelId;
const i = normalizeMessageChannel(n) === "webchat" ? t : null;
if (!i?.to) return {
currentChannelProvider: n,
currentChannelId: r,
currentChatType: e?.currentChatType,
currentMessagingTarget: e?.currentMessagingTarget
};
return {
accountId: i.accountId,
currentChannelProvider: i.channel,
currentChannelId: i.to,
currentChatType: i.chatType,
currentMessagingTarget: i.to,
currentThreadTs: i.threadId
};
}
function resolveDiscoveryAccountId(e, t, n) {
const r = e.scheduledAccountScope;
const i = normalizeMessageChannel(t);
return r && (r.channels === void 0 || i !== void 0 && r.channels.some((e) => normalizeMessageChannel(e) === i)) ? r.accountId : n;
}
function buildMessageActionDiscoveryInput(e, t) {
return {
cfg: e.cfg,
...t ? { channel: t } : {},
chatType: e.currentChatType,
currentChannelId: e.currentChannelId,
currentThreadTs: e.currentThreadTs,
currentMessageId: e.currentMessageId,
accountId: resolveDiscoveryAccountId(e, t, e.currentAccountId),
sessionKey: e.sessionKey,
sessionId: e.sessionId,
agentId: e.agentId,
requesterSenderId: e.requesterSenderId,
senderIsOwner: e.senderIsOwner,
preparedMessageToolCatalog: e.preparedMessageToolCatalog
};
}
function resolveMessageToolDiscoveryChannels(e) {
const t = normalizeMessageChannel(e.currentChannelProvider);
const n = /* @__PURE__ */ new Set();
if (t && t !== "webchat") n.add(t);
if (e.agentId) for (const t of listRouteBindings(e.cfg)) {
const r = normalizeRouteBindingChannelId(t.match.channel);
if (r && normalizeAgentId(t.agentId) === normalizeAgentId(e.agentId)) n.add(r);
}
return listMessageActionDiscoveryChannels(e.preparedMessageToolCatalog).filter((t) => e.isScheduledRun || n.size === 0 || n.has(t.id)).toSorted((e, t) => e.id.localeCompare(t.id));
}
function* resolveMessageToolSchemaActionsSteps(e) {
const t = normalizeMessageChannel(e.currentChannelProvider);
const n = new Set(t ? ["send"] : ["send", "broadcast"]);
if (t) for (const r of yield* listChannelSupportedActionsSteps(buildMessageActionDiscoveryInput(e, t))) n.add(r);
for (const r of resolveMessageToolDiscoveryChannels(e)) {
if (r.id === t) continue;
const i = buildMessageActionDiscoveryInput(e, r.id);
const a = t ? yield* listCrossChannelSchemaSupportedMessageActionsSteps(i) : yield* listChannelSupportedActionsSteps(i);
for (const e of a) n.add(e);
}
return Array.from(n);
}
function resolveMessageToolActionSchemaActions(e) {
return runMessageActionDiscovery(resolveMessageToolActionSchemaActionsSteps(e));
}
function* resolveMessageToolActionSchemaActionsSteps(e) {
const t = yield* resolveMessageToolSchemaActionsSteps(e);
if (e.supportsPromptReactions && !t.includes("react")) t.push("react");
const n = resolveAllowedMessageActions({
cfg: e.cfg,
agentId: e.agentId
});
if (!n) return sortUniqueStrings(t);
const r = new Set(n);
const i = t.filter((e) => r.has(e));
return sortUniqueStrings(i.length > 0 ? i : n);
}
function* resolveIncludeCapabilitySteps(e, t) {
const n = normalizeMessageChannel(e.currentChannelProvider);
if (n) {
if ((yield* resolveCurrentMessageActionDiscoverySteps(buildMessageActionDiscoveryInput(e, n), { includeCapabilities: true }))?.capabilities.includes(t)) return true;
}
for (const r of resolveMessageToolDiscoveryChannels(e)) {
if (r.id === n) continue;
const i = resolveDiscoveryAccountId(e, r.id, void 0);
if ((yield {
pluginId: r.id,
actions: r.actions,
context: {
cfg: e.cfg,
...i !== void 0 ? { accountId: i } : {}
},
includeCapabilities: true
}).capabilities.includes(t)) return true;
}
return false;
}
function resolveIncludeBestEffort(e) {
const t = normalizeMessageChannel(e.currentChannelProvider);
if (!t) return false;
const n = e.preparedMessageToolCatalog?.getChannel(t);
if (e.preparedMessageToolCatalog) return n?.reconcilesUnknownSend ?? false;
const r = getLoadedChannelPlugin(t)?.message ?? getChannelPlugin(t)?.message;
return r?.durableFinal?.capabilities?.reconcileUnknownSend === true && typeof r.durableFinal.reconcileUnknownSend === "function";
}
function buildMessageToolSchema(e, t) {
return runMessageActionDiscovery(buildMessageToolSchemaSteps(e, t));
}
function* buildMessageToolSchemaSteps(e, t) {
const n = yield* resolveIncludeCapabilitySteps(e, "presentation");
const r = yield* resolveIncludeCapabilitySteps(e, "delivery-pin");
const i = resolveIncludeBestEffort(e);
const a = yield* resolveChannelMessageToolSchemaPropertiesSteps({
channels: resolveMessageToolDiscoveryChannels(e),
...buildMessageActionDiscoveryInput(e, normalizeMessageChannel(e.currentChannelProvider) ?? void 0),
resolveAccountIdForChannel: e.scheduledAccountScope ? (t, n) => resolveDiscoveryAccountId(e, t, n) : void 0
});
return buildMessageToolSchemaFromActions(t.length > 0 ? t : ["send"], {
includeClawHub: normalizeMessageChannel(e.currentChannelProvider) === INTERNAL_MESSAGE_CHANNEL,
includePresentation: n,
includeDeliveryPin: r,
includeBestEffort: i,
extraProperties: e.supportsPromptReactions && t.includes("react") ? {
...a,
emoji: Type.Optional(Type.String({ description: "One Unicode emoji for the current WebChat prompt; explicit external channels validate their own emoji." }))
} : a
});
}
function resolveMessageToolDiscoveryAsync(e) {
return runMessageActionDiscoveryAsync(resolveMessageToolDiscoverySteps(e));
}
function* resolveMessageToolDiscoverySteps(e) {
const t = yield* resolveMessageToolActionSchemaActionsSteps(e);
return {
actions: t,
schema: yield* buildMessageToolSchemaSteps(e, t)
};
}
function resolveAgentAccountId(e) {
const t = normalizeOptionalString(e);
return t ? normalizeAccountId(t) : void 0;
}
function buildMessageToolDescription(e) {
const t = "Send/manage channel messages.";
if (e && e.length > 0) {
const n = sortUniqueStrings(e);
const r = `${t} Supports actions: ${n.join(", ")}.`;
return n.includes("read") ? `${r} Missing thread context: action="read" + threadId.` : r;
}
return `${t} Action families (availability depends on the channel): sending/editing/unsend, reactions, polls, pins, threads, file upload/download, moderation (timeout/kick/ban), roles, channel + category management, profile/presence.`;
}
//#endregion
export { readMessageToolSessionEntry as a, resolveEffectiveCurrentChannelContextForRequest as c, resolveMessageToolDiscoveryAsync as d, resolveMessageToolScheduledAccountScope as f, prepareMessageToolSessionBinding as i, resolveMessageToolActionSchemaActions as l, MessageToolSchema as m, buildMessageToolSchema as n, resolveAgentAccountId as o, supportsMessageToolPromptReactions as p, hasMessageToolSourceConversation as r, resolveEffectiveCurrentChannelContext as s, buildMessageToolDescription as t, resolveMessageToolDefinitionContext as u };