import type { OpenClawPluginApi } from "openclaw/plugin-sdk"; import { initTurnOrder } from "../turn-manager.js"; import { fetchVisibleChannelBotAccountIds } from "./channel-members.js"; const channelSeenAccounts = new Map>(); const channelBootstrapTried = new Set(); function getAllBotAccountIds(api: OpenClawPluginApi): string[] { const root = (api.config as Record) || {}; const bindings = root.bindings as Array> | undefined; if (!Array.isArray(bindings)) return []; const ids: string[] = []; for (const b of bindings) { const match = b.match as Record | undefined; if (match?.channel === "discord" && typeof match.accountId === "string") { ids.push(match.accountId); } } return ids; } function getChannelBotAccountIds(api: OpenClawPluginApi, channelId: string): string[] { const allBots = new Set(getAllBotAccountIds(api)); const seen = channelSeenAccounts.get(channelId); if (!seen) return []; return [...seen].filter((id) => allBots.has(id)); } export function recordChannelAccount(channelId: string, accountId: string): boolean { let seen = channelSeenAccounts.get(channelId); if (!seen) { seen = new Set(); channelSeenAccounts.set(channelId, seen); } if (seen.has(accountId)) return false; seen.add(accountId); return true; } export async function ensureTurnOrder(api: OpenClawPluginApi, channelId: string): Promise { let botAccounts = getChannelBotAccountIds(api, channelId); if (botAccounts.length === 0 && !channelBootstrapTried.has(channelId)) { channelBootstrapTried.add(channelId); const discovered = await fetchVisibleChannelBotAccountIds(api, channelId).catch(() => [] as string[]); for (const aid of discovered) recordChannelAccount(channelId, aid); botAccounts = getChannelBotAccountIds(api, channelId); } if (botAccounts.length > 0) { initTurnOrder(channelId, botAccounts); } }