import type { OpenClawPluginApi } from "openclaw/plugin-sdk"; function userIdFromToken(token: string): string | undefined { try { const segment = token.split(".")[0]; const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4); return Buffer.from(padded, "base64").toString("utf8"); } catch { return undefined; } } function resolveDiscordUserIdFromAccount(api: OpenClawPluginApi, accountId: string): string | undefined { const root = (api.config as Record) || {}; const channels = (root.channels as Record) || {}; const discord = (channels.discord as Record) || {}; const accounts = (discord.accounts as Record>) || {}; const acct = accounts[accountId]; if (!acct?.token || typeof acct.token !== "string") return undefined; return userIdFromToken(acct.token); } export function resolveAccountId(api: OpenClawPluginApi, agentId: string): string | undefined { const root = (api.config as Record) || {}; const bindings = root.bindings as Array> | undefined; if (!Array.isArray(bindings)) return undefined; for (const b of bindings) { if (b.agentId === agentId) { const match = b.match as Record | undefined; if (match?.channel === "discord" && typeof match.accountId === "string") { return match.accountId; } } } return undefined; } export function buildAgentIdentity(api: OpenClawPluginApi, agentId: string): string | undefined { const root = (api.config as Record) || {}; const bindings = root.bindings as Array> | undefined; const agents = ((root.agents as Record)?.list as Array>) || []; if (!Array.isArray(bindings)) return undefined; let accountId: string | undefined; for (const b of bindings) { if (b.agentId === agentId) { const match = b.match as Record | undefined; if (match?.channel === "discord" && typeof match.accountId === "string") { accountId = match.accountId; break; } } } if (!accountId) return undefined; const agent = agents.find((a: Record) => a.id === agentId); const name = (agent?.name as string) || agentId; const discordUserId = resolveDiscordUserIdFromAccount(api, accountId); let identity = `You are ${name} (Discord account: ${accountId}`; if (discordUserId) identity += `, Discord userId: ${discordUserId}`; identity += `).`; return identity; } export function buildUserIdToAccountIdMap(api: OpenClawPluginApi): Map { const root = (api.config as Record) || {}; const channels = (root.channels as Record) || {}; const discord = (channels.discord as Record) || {}; const accounts = (discord.accounts as Record>) || {}; const map = new Map(); for (const [accountId, acct] of Object.entries(accounts)) { if (typeof acct.token === "string") { const userId = userIdFromToken(acct.token); if (userId) map.set(userId, accountId); } } return map; }