openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
246 lines (245 loc) • 9.58 kB
JavaScript
import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, xn as literal } from "../../schemas-Cy6abvsu.mjs";
import { n as jsonResult } from "../../tool-results-CcV0sxnb.mjs";
import { f as readStringArrayParam, m as readToolStringParam } from "../../common-njQNtpnW.mjs";
import { i as buildChannelConfigSchema, s as buildMultiAccountChannelSchema } from "../../config-schema-BxWrycwn.mjs";
import { v as defineChannelMessageAdapter } from "../../channel-outbound-DQFse8vD.mjs";
import { r as buildSecretInputSchema } from "../../secret-input-CpgOwFAi.mjs";
import { n as createStaticReplyToModeResolver } from "../../threading-helpers-DELk4nUS.mjs";
import "../../conversation-runtime-CefOz30L.mjs";
import "../../channel-config-schema-Zup0A2Ue.mjs";
import "../../channel-actions-DxuDuzvg.mjs";
import "../../channel-core-irqoURKA.mjs";
import { f as buildOpenGroupPolicyWarning } from "../../channel-policy-Br2lSetS.mjs";
import { t as extractToolSend } from "../../tool-send-CK3R3Dzk.mjs";
import { i as resolveXAccount, r as resolveDefaultXAccountId, t as listXAccountIds } from "../../accounts-Bg4ihS1J.mjs";
import { r as normalizeXUserId } from "../../allowlist-Cvibwhmj.mjs";
import { t as getXRuntime } from "../../runtime-SL1x_YwB.mjs";
import { a as X_GUEST_TOOLS, i as resolveXSenderTier, r as resolveXGuestToolPolicy } from "../../guest-policy-BBy19wHq.mjs";
import { t as MAX_X_GUEST_MENTIONS_PER_AUTHOR_PER_DAY } from "../../guest-usage-B1U2k5CF.mjs";
import { n as xReplyOutcomeGuidance, t as readXReplyOutcome } from "../../outcome-BjLomHVm.mjs";
import { t as channelSecrets } from "../../secret-contract-Cy-s7LcJ.mjs";
import { t as normalizeXReplyTarget } from "../../target-DJYoeDs8.mjs";
//#region extensions/x/src/config-schema.ts
const XAccountSchema = object({
name: string().optional(),
enabled: boolean().optional(),
configWrites: boolean().optional(),
autoPublishWorkSessions: boolean().optional(),
userId: string().regex(/^\d+$/).optional(),
username: string().regex(/^[A-Za-z0-9_]{1,15}$/).optional(),
clientId: string().min(1).optional(),
clientSecret: buildSecretInputSchema().optional(),
refreshToken: buildSecretInputSchema().optional(),
bearerToken: buildSecretInputSchema().optional(),
costLimits: object({
dailyUsd: number().finite().nonnegative().optional(),
monthlyUsd: number().finite().nonnegative().optional(),
cycleStartDay: number().int().min(1).max(28).optional()
}).strict().optional(),
events: object({
mode: _enum([
"auto",
"stream",
"poll"
]).optional(),
pollSeconds: number().int().min(15).optional()
}).strict().optional(),
allowFrom: array(string().regex(/^(?:x:)?\d+$/i)).optional(),
verifiedFromGitHub: object({
repo: string().regex(/^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/(?!\.{1,2}$)[A-Za-z0-9_.-]{1,100}$/).optional(),
minPermission: _enum([
"push",
"maintain",
"admin"
]).optional(),
refreshMinutes: number().int().min(15).optional(),
token: buildSecretInputSchema().optional()
}).strict().optional(),
groupPolicy: _enum([
"allowlist",
"open",
"disabled"
]).optional(),
dmPolicy: literal("disabled").optional(),
threadContext: object({ maxPosts: number().int().min(2).max(100).optional() }).strict().optional(),
guests: object({
enabled: boolean().optional(),
maxMentionsPerAuthorPerDay: number().int().min(0).max(MAX_X_GUEST_MENTIONS_PER_AUTHOR_PER_DAY).optional(),
threadContextMaxPosts: number().int().min(2).max(100).optional(),
tools: object({
allow: array(_enum(X_GUEST_TOOLS)).optional(),
deny: array(string()).optional()
}).strict().optional()
}).strict().optional(),
replySignature: string().max(140).optional(),
failureRoute: object({
channel: string().min(1).refine((e) => e.trim().toLowerCase() !== "x"),
to: string().min(1),
accountId: string().min(1).optional()
}).strict().optional()
});
const XConfigSchema = buildMultiAccountChannelSchema(XAccountSchema, {
accountSchema: XAccountSchema,
accountsMode: "catchall"
});
//#endregion
//#region extensions/x/src/channel.ts
const send = async (e) => (await import("../../send-BhUVtTMy.mjs")).sendXDelivery(e);
const senderGuidance = "X turns come from verified users and guests. Every turn starts with a host-generated sender line. Verified users may request work sessions; guests receive repository answers only.";
const message = defineChannelMessageAdapter({
id: "x",
send: {
text: send,
media: send
}
});
const xPlugin = {
id: "x",
meta: {
id: "x",
label: "X (Twitter)",
selectionLabel: "X (Twitter mentions)",
docsPath: "/channels/x",
docsLabel: "x",
blurb: "Allowlisted mentions with thread context and public replies.",
order: 85
},
capabilities: {
chatTypes: ["group"],
media: true,
reactions: false,
threads: true,
polls: false,
nativeCommands: false,
blockStreaming: false
},
reload: { configPrefixes: ["channels.x"] },
configSchema: buildChannelConfigSchema(XConfigSchema),
config: {
listAccountIds: listXAccountIds,
defaultAccountId: resolveDefaultXAccountId,
resolveAccount: resolveXAccount,
inspectAccount: (e, t) => {
const n = resolveXAccount(e, t);
return {
accountId: n.accountId,
enabled: n.enabled,
configured: n.configured,
name: n.name
};
},
isEnabled: (e) => e.enabled,
isConfigured: (e) => e.configured,
describeAccount: (e) => ({
accountId: e.accountId,
enabled: e.enabled,
configured: e.configured,
name: e.name,
dmPolicy: "disabled"
}),
resolveAllowFrom: ({ cfg: e, accountId: t }) => resolveXAccount(e, t).config.allowFrom,
formatAllowFrom: ({ allowFrom: e }) => e.flatMap((e) => normalizeXUserId(String(e)) ?? [])
},
secrets: channelSecrets,
agentPrompt: {
messageToolHints: () => [senderGuidance, "X supports native proof attachments: up to four images or one MP4 video/GIF. Prefer inspected native media over sign-in links when useful; public work-session replies still require explicit approval."],
inboundFormattingHints: () => ({
text_markup: "plain_text",
rules: [
senderGuidance,
"Replies are public plain text with optional native image/video attachments; documentation URLs may be cited.",
xReplyOutcomeGuidance
]
})
},
groups: {
resolveRequireMention: () => true,
resolveToolPolicy: ({ cfg: e, accountId: t, senderId: n }) => {
const r = resolveXAccount(e, t);
return resolveXSenderTier(r, n) === "maintainer" ? void 0 : resolveXGuestToolPolicy(r);
}
},
security: { collectWarnings: ({ account: e }) => e.config.groupPolicy === "open" && !e.config.guests?.enabled ? [buildOpenGroupPolicyWarning({
surface: "X public replies",
openBehavior: "does not admit guests while guest mode is off",
remediation: "Use channels.x.guests.enabled=true for repository-only guest answers, or set channels.x.groupPolicy=\"allowlist\" for maintainers only."
})] : [] },
messaging: {
targetPrefixes: ["x"],
normalizeTarget: normalizeXReplyTarget,
inferTargetChatType: () => "group",
targetResolver: {
looksLikeId: (e) => Boolean(normalizeXReplyTarget(e)),
hint: "x:<postId> or https://x.com/<handle>/status/<postId>"
}
},
threading: { resolveReplyToMode: createStaticReplyToModeResolver("all") },
actions: {
describeMessageTool: ({ cfg: e, accountId: t }) => (t ? [resolveXAccount(e, t)] : listXAccountIds(e).map((t) => resolveXAccount(e, t))).some((e) => e.enabled && e.configured) ? {
actions: ["send"],
capabilities: []
} : null,
supportsAction: ({ action: e }) => e === "send",
extractToolSend: ({ args: e }) => extractToolSend(e, "sendMessage"),
handleAction: async ({ action: e, params: t, cfg: n, accountId: r, sessionKey: i, mediaAccess: a, mediaLocalRoots: o, mediaReadFile: s, assertDirectAdapterHandoff: c }) => {
if (e !== "send") throw new Error(`X does not support ${e}.`);
const l = readXReplyOutcome(readToolStringParam(t, "message") ?? "");
if (l.outcome === "failure") throw new Error("X does not post failure replies; report the failure in this session.");
const u = await send({
cfg: n,
accountId: r,
to: readToolStringParam(t, "to", { required: true }),
text: l.text,
mediaUrl: readToolStringParam(t, "media"),
mediaUrls: readStringArrayParam(t, "mediaUrls"),
mediaAccess: a,
mediaLocalRoots: o,
mediaReadFile: s,
assertDirectAdapterHandoff: c,
sessionKey: i
});
return jsonResult({
ok: true,
messageId: u.messageId
});
}
},
message,
outbound: {
deliveryMode: "direct",
sendPayloadGroupsMedia: true,
deliveryCapabilities: { durableFinal: { payload: true } },
sendText: send,
sendMedia: send,
sendPayload: async (e) => {
const t = await send({
...e,
text: e.payload.text ?? "",
mediaUrl: e.payload.mediaUrl,
mediaUrls: e.payload.mediaUrls
});
await e.onDeliveryResult?.(t);
return t;
}
},
status: {
defaultRuntime: {
accountId: "default",
running: false
},
buildChannelSummary: ({ snapshot: e }) => e,
buildAccountSnapshot: async ({ account: e, runtime: t, cfg: n }) => ({
...t,
accountId: e.accountId,
name: e.name,
enabled: e.enabled,
configured: e.configured,
dmPolicy: "disabled",
guests: await (await import("../../guests-BjXsNglm.mjs")).getXGuestStatus(getXRuntime(), e, n),
verifiedFromGitHub: await (await import("../../verified-github-BM6sVdyi.mjs")).getXGitHubStatus(getXRuntime(), e)
})
},
gateway: { startAccount: async (e) => (await import("../../monitor-BofVVXEw.mjs")).startXAccount(e) }
};
//#endregion
export { xPlugin };