Refactor channel account management: move binding/editing to Channels, align Agents display, and simplify UX (#523)
This commit is contained in:
@@ -188,9 +188,27 @@ export async function handleAgentRoutes(
|
||||
try {
|
||||
const agentId = decodeURIComponent(parts[0]);
|
||||
const channelType = decodeURIComponent(parts[2]);
|
||||
const accountId = resolveAccountIdForAgent(agentId);
|
||||
await deleteChannelAccountConfig(channelType, accountId);
|
||||
const snapshot = await clearChannelBinding(channelType, accountId);
|
||||
const ownerId = agentId.trim().toLowerCase();
|
||||
const snapshotBefore = await listAgentsSnapshot();
|
||||
const ownedAccountIds = Object.entries(snapshotBefore.channelAccountOwners)
|
||||
.filter(([channelAccountKey, owner]) => {
|
||||
if (owner !== ownerId) return false;
|
||||
return channelAccountKey.startsWith(`${channelType}:`);
|
||||
})
|
||||
.map(([channelAccountKey]) => channelAccountKey.slice(channelAccountKey.indexOf(':') + 1));
|
||||
// Backward compatibility for legacy agentId->accountId mapping.
|
||||
if (ownedAccountIds.length === 0) {
|
||||
const legacyAccountId = resolveAccountIdForAgent(agentId);
|
||||
if (snapshotBefore.channelAccountOwners[`${channelType}:${legacyAccountId}`] === ownerId) {
|
||||
ownedAccountIds.push(legacyAccountId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const accountId of ownedAccountIds) {
|
||||
await deleteChannelAccountConfig(channelType, accountId);
|
||||
await clearChannelBinding(channelType, accountId);
|
||||
}
|
||||
const snapshot = await listAgentsSnapshot();
|
||||
scheduleGatewayReload(ctx, 'remove-agent-channel');
|
||||
sendJson(res, 200, { success: true, ...snapshot });
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,20 +1,29 @@
|
||||
import type { IncomingMessage, ServerResponse } from 'http';
|
||||
import {
|
||||
deleteChannelAccountConfig,
|
||||
deleteChannelConfig,
|
||||
getChannelFormValues,
|
||||
listConfiguredChannelAccounts,
|
||||
listConfiguredChannels,
|
||||
readOpenClawConfig,
|
||||
saveChannelConfig,
|
||||
setChannelDefaultAccount,
|
||||
setChannelEnabled,
|
||||
validateChannelConfig,
|
||||
validateChannelCredentials,
|
||||
} from '../../utils/channel-config';
|
||||
import {
|
||||
assignChannelAccountToAgent,
|
||||
clearAllBindingsForChannel,
|
||||
clearChannelBinding,
|
||||
listAgentsSnapshot,
|
||||
} from '../../utils/agent-config';
|
||||
import {
|
||||
ensureDingTalkPluginInstalled,
|
||||
ensureFeishuPluginInstalled,
|
||||
ensureQQBotPluginInstalled,
|
||||
ensureWeComPluginInstalled,
|
||||
} from '../../utils/plugin-install';
|
||||
import { assignChannelToAgent, clearAllBindingsForChannel } from '../../utils/agent-config';
|
||||
import { whatsAppLoginManager } from '../../utils/whatsapp-login';
|
||||
import type { HostApiContext } from '../context';
|
||||
import { parseJsonBody, sendJson } from '../route-utils';
|
||||
@@ -79,16 +88,167 @@ function isSameConfigValues(
|
||||
return true;
|
||||
}
|
||||
|
||||
function inferAgentIdFromAccountId(accountId: string): string {
|
||||
if (accountId === 'default') return 'main';
|
||||
return accountId;
|
||||
}
|
||||
|
||||
async function ensureScopedChannelBinding(channelType: string, accountId?: string): Promise<void> {
|
||||
// Multi-agent safety: only bind when the caller explicitly scopes the account.
|
||||
// Global channel saves (no accountId) must not override routing to "main".
|
||||
if (!accountId) return;
|
||||
await assignChannelToAgent(inferAgentIdFromAccountId(accountId), channelType).catch(() => undefined);
|
||||
const agents = await listAgentsSnapshot();
|
||||
if (!agents.entries || agents.entries.length === 0) return;
|
||||
|
||||
// Keep backward compatibility for the legacy default account.
|
||||
if (accountId === 'default') {
|
||||
if (agents.entries.some((entry) => entry.id === 'main')) {
|
||||
await assignChannelAccountToAgent('main', channelType, 'default');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Legacy compatibility: if accountId matches an existing agentId, keep auto-binding.
|
||||
if (agents.entries.some((entry) => entry.id === accountId)) {
|
||||
await assignChannelAccountToAgent(accountId, channelType, accountId);
|
||||
}
|
||||
}
|
||||
|
||||
interface GatewayChannelStatusPayload {
|
||||
channelOrder?: string[];
|
||||
channels?: Record<string, unknown>;
|
||||
channelAccounts?: Record<string, Array<{
|
||||
accountId?: string;
|
||||
configured?: boolean;
|
||||
connected?: boolean;
|
||||
running?: boolean;
|
||||
lastError?: string;
|
||||
name?: string;
|
||||
linked?: boolean;
|
||||
lastConnectedAt?: number | null;
|
||||
lastInboundAt?: number | null;
|
||||
lastOutboundAt?: number | null;
|
||||
}>>;
|
||||
channelDefaultAccountId?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface ChannelAccountView {
|
||||
accountId: string;
|
||||
name: string;
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
running: boolean;
|
||||
linked: boolean;
|
||||
lastError?: string;
|
||||
status: 'connected' | 'connecting' | 'disconnected' | 'error';
|
||||
isDefault: boolean;
|
||||
agentId?: string;
|
||||
}
|
||||
|
||||
interface ChannelAccountsView {
|
||||
channelType: string;
|
||||
defaultAccountId: string;
|
||||
status: 'connected' | 'connecting' | 'disconnected' | 'error';
|
||||
accounts: ChannelAccountView[];
|
||||
}
|
||||
|
||||
function computeAccountStatus(account: {
|
||||
connected?: boolean;
|
||||
linked?: boolean;
|
||||
running?: boolean;
|
||||
lastError?: string;
|
||||
lastConnectedAt?: number | null;
|
||||
lastInboundAt?: number | null;
|
||||
lastOutboundAt?: number | null;
|
||||
}): 'connected' | 'connecting' | 'disconnected' | 'error' {
|
||||
const now = Date.now();
|
||||
const recentMs = 10 * 60 * 1000;
|
||||
const hasRecentActivity =
|
||||
(typeof account.lastInboundAt === 'number' && now - account.lastInboundAt < recentMs)
|
||||
|| (typeof account.lastOutboundAt === 'number' && now - account.lastOutboundAt < recentMs)
|
||||
|| (typeof account.lastConnectedAt === 'number' && now - account.lastConnectedAt < recentMs);
|
||||
|
||||
if (account.connected === true || account.linked === true || hasRecentActivity) return 'connected';
|
||||
if (account.running === true && !account.lastError) return 'connecting';
|
||||
if (account.lastError) return 'error';
|
||||
return 'disconnected';
|
||||
}
|
||||
|
||||
function pickChannelStatus(accounts: ChannelAccountView[]): 'connected' | 'connecting' | 'disconnected' | 'error' {
|
||||
if (accounts.some((account) => account.status === 'connected')) return 'connected';
|
||||
if (accounts.some((account) => account.status === 'error')) return 'error';
|
||||
if (accounts.some((account) => account.status === 'connecting')) return 'connecting';
|
||||
return 'disconnected';
|
||||
}
|
||||
|
||||
async function buildChannelAccountsView(ctx: HostApiContext): Promise<ChannelAccountsView[]> {
|
||||
const [configuredChannels, configuredAccounts, openClawConfig, agentsSnapshot] = await Promise.all([
|
||||
listConfiguredChannels(),
|
||||
listConfiguredChannelAccounts(),
|
||||
readOpenClawConfig(),
|
||||
listAgentsSnapshot(),
|
||||
]);
|
||||
|
||||
let gatewayStatus: GatewayChannelStatusPayload | null;
|
||||
try {
|
||||
gatewayStatus = await ctx.gatewayManager.rpc<GatewayChannelStatusPayload>('channels.status', { probe: true });
|
||||
} catch {
|
||||
gatewayStatus = null;
|
||||
}
|
||||
|
||||
const channelTypes = new Set<string>([
|
||||
...configuredChannels,
|
||||
...Object.keys(configuredAccounts),
|
||||
...Object.keys(gatewayStatus?.channelAccounts || {}),
|
||||
]);
|
||||
|
||||
const channels: ChannelAccountsView[] = [];
|
||||
for (const channelType of channelTypes) {
|
||||
const channelAccountsFromConfig = configuredAccounts[channelType]?.accountIds ?? [];
|
||||
const hasLocalConfig = configuredChannels.includes(channelType) || Boolean(configuredAccounts[channelType]);
|
||||
const channelSection = openClawConfig.channels?.[channelType];
|
||||
const fallbackDefault =
|
||||
typeof channelSection?.defaultAccount === 'string' && channelSection.defaultAccount.trim()
|
||||
? channelSection.defaultAccount
|
||||
: 'default';
|
||||
const defaultAccountId = configuredAccounts[channelType]?.defaultAccountId
|
||||
?? gatewayStatus?.channelDefaultAccountId?.[channelType]
|
||||
?? fallbackDefault;
|
||||
const runtimeAccounts = gatewayStatus?.channelAccounts?.[channelType] ?? [];
|
||||
const hasRuntimeConfigured = runtimeAccounts.some((account) => account.configured === true);
|
||||
if (!hasLocalConfig && !hasRuntimeConfigured) {
|
||||
continue;
|
||||
}
|
||||
const runtimeAccountIds = runtimeAccounts
|
||||
.map((account) => account.accountId)
|
||||
.filter((accountId): accountId is string => typeof accountId === 'string' && accountId.trim().length > 0);
|
||||
const accountIds = Array.from(new Set([...channelAccountsFromConfig, ...runtimeAccountIds, defaultAccountId]));
|
||||
|
||||
const accounts: ChannelAccountView[] = accountIds.map((accountId) => {
|
||||
const runtime = runtimeAccounts.find((item) => item.accountId === accountId);
|
||||
const status = computeAccountStatus(runtime ?? {});
|
||||
return {
|
||||
accountId,
|
||||
name: runtime?.name || accountId,
|
||||
configured: channelAccountsFromConfig.includes(accountId) || runtime?.configured === true,
|
||||
connected: runtime?.connected === true,
|
||||
running: runtime?.running === true,
|
||||
linked: runtime?.linked === true,
|
||||
lastError: typeof runtime?.lastError === 'string' ? runtime.lastError : undefined,
|
||||
status,
|
||||
isDefault: accountId === defaultAccountId,
|
||||
agentId: agentsSnapshot.channelAccountOwners[`${channelType}:${accountId}`],
|
||||
};
|
||||
}).sort((left, right) => {
|
||||
if (left.accountId === defaultAccountId) return -1;
|
||||
if (right.accountId === defaultAccountId) return 1;
|
||||
return left.accountId.localeCompare(right.accountId);
|
||||
});
|
||||
|
||||
channels.push({
|
||||
channelType,
|
||||
defaultAccountId,
|
||||
status: pickChannelStatus(accounts),
|
||||
accounts,
|
||||
});
|
||||
}
|
||||
|
||||
return channels.sort((left, right) => left.channelType.localeCompare(right.channelType));
|
||||
}
|
||||
|
||||
export async function handleChannelRoutes(
|
||||
@@ -102,6 +262,52 @@ export async function handleChannelRoutes(
|
||||
return true;
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/channels/accounts' && req.method === 'GET') {
|
||||
try {
|
||||
const channels = await buildChannelAccountsView(ctx);
|
||||
sendJson(res, 200, { success: true, channels });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { success: false, error: String(error) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/channels/default-account' && req.method === 'PUT') {
|
||||
try {
|
||||
const body = await parseJsonBody<{ channelType: string; accountId: string }>(req);
|
||||
await setChannelDefaultAccount(body.channelType, body.accountId);
|
||||
scheduleGatewayChannelSaveRefresh(ctx, body.channelType, `channel:setDefaultAccount:${body.channelType}`);
|
||||
sendJson(res, 200, { success: true });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { success: false, error: String(error) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/channels/binding' && req.method === 'PUT') {
|
||||
try {
|
||||
const body = await parseJsonBody<{ channelType: string; accountId: string; agentId: string }>(req);
|
||||
await assignChannelAccountToAgent(body.agentId, body.channelType, body.accountId);
|
||||
scheduleGatewayChannelSaveRefresh(ctx, body.channelType, `channel:setBinding:${body.channelType}`);
|
||||
sendJson(res, 200, { success: true });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { success: false, error: String(error) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/channels/binding' && req.method === 'DELETE') {
|
||||
try {
|
||||
const body = await parseJsonBody<{ channelType: string; accountId: string }>(req);
|
||||
await clearChannelBinding(body.channelType, body.accountId);
|
||||
scheduleGatewayChannelSaveRefresh(ctx, body.channelType, `channel:clearBinding:${body.channelType}`);
|
||||
sendJson(res, 200, { success: true });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { success: false, error: String(error) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/channels/config/validate' && req.method === 'POST') {
|
||||
try {
|
||||
const body = await parseJsonBody<{ channelType: string }>(req);
|
||||
@@ -219,9 +425,16 @@ export async function handleChannelRoutes(
|
||||
if (url.pathname.startsWith('/api/channels/config/') && req.method === 'DELETE') {
|
||||
try {
|
||||
const channelType = decodeURIComponent(url.pathname.slice('/api/channels/config/'.length));
|
||||
await deleteChannelConfig(channelType);
|
||||
await clearAllBindingsForChannel(channelType);
|
||||
scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${channelType}`);
|
||||
const accountId = url.searchParams.get('accountId') || undefined;
|
||||
if (accountId) {
|
||||
await deleteChannelAccountConfig(channelType, accountId);
|
||||
await clearChannelBinding(channelType, accountId);
|
||||
scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:deleteAccount:${channelType}`);
|
||||
} else {
|
||||
await deleteChannelConfig(channelType);
|
||||
await clearAllBindingsForChannel(channelType);
|
||||
scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${channelType}`);
|
||||
}
|
||||
sendJson(res, 200, { success: true });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { success: false, error: String(error) });
|
||||
|
||||
@@ -92,6 +92,7 @@ export interface AgentsSnapshot {
|
||||
defaultAgentId: string;
|
||||
configuredChannelTypes: string[];
|
||||
channelOwners: Record<string, string>;
|
||||
channelAccountOwners: Record<string, string>;
|
||||
}
|
||||
|
||||
function formatModelLabel(model: unknown): string | null {
|
||||
@@ -266,10 +267,16 @@ function upsertBindingsForChannel(
|
||||
agentId: string | null,
|
||||
accountId?: string,
|
||||
): BindingConfig[] | undefined {
|
||||
const normalizedAgentId = agentId ? normalizeAgentIdForBinding(agentId) : '';
|
||||
const nextBindings = Array.isArray(bindings)
|
||||
? [...bindings as BindingConfig[]].filter((binding) => {
|
||||
if (!isChannelBinding(binding)) return true;
|
||||
if (binding.match?.channel !== channelType) return true;
|
||||
// Keep a single account binding per (agent, channelType). Rebinding to
|
||||
// another account should replace the previous one.
|
||||
if (normalizedAgentId && normalizeAgentIdForBinding(binding.agentId || '') === normalizedAgentId) {
|
||||
return false;
|
||||
}
|
||||
// Only remove binding that matches the exact accountId scope
|
||||
if (accountId) {
|
||||
return binding.match?.accountId !== accountId;
|
||||
@@ -290,6 +297,30 @@ function upsertBindingsForChannel(
|
||||
return nextBindings.length > 0 ? nextBindings : undefined;
|
||||
}
|
||||
|
||||
function assertAgentNotBoundToOtherChannel(
|
||||
bindings: unknown,
|
||||
agentId: string,
|
||||
nextChannelType: string,
|
||||
): void {
|
||||
if (!Array.isArray(bindings)) return;
|
||||
const normalizedAgentId = normalizeAgentIdForBinding(agentId);
|
||||
if (!normalizedAgentId) return;
|
||||
|
||||
const conflictChannels = new Set<string>();
|
||||
for (const binding of bindings) {
|
||||
if (!isChannelBinding(binding)) continue;
|
||||
if (normalizeAgentIdForBinding(binding.agentId || '') !== normalizedAgentId) continue;
|
||||
const boundChannel = binding.match?.channel;
|
||||
if (!boundChannel || boundChannel === nextChannelType) continue;
|
||||
conflictChannels.add(boundChannel);
|
||||
}
|
||||
|
||||
if (conflictChannels.size > 0) {
|
||||
const channels = Array.from(conflictChannels).sort().join(', ');
|
||||
throw new Error(`Agent "${agentId}" is already bound to channel(s): ${channels}. One agent can only bind one channel.`);
|
||||
}
|
||||
}
|
||||
|
||||
async function listExistingAgentIdsOnDisk(): Promise<Set<string>> {
|
||||
const ids = new Set<string>();
|
||||
const agentsDir = join(getOpenClawConfigDir(), 'agents');
|
||||
@@ -429,6 +460,7 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument): Promise<Age
|
||||
const { channelToAgent, accountToAgent } = getChannelBindingMap(config.bindings);
|
||||
const defaultAgentIdNorm = normalizeAgentIdForBinding(defaultAgentId);
|
||||
const channelOwners: Record<string, string> = {};
|
||||
const channelAccountOwners: Record<string, string> = {};
|
||||
|
||||
// Build per-agent channel lists from account-scoped bindings
|
||||
const agentChannelSets = new Map<string, Set<string>>();
|
||||
@@ -436,16 +468,24 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument): Promise<Age
|
||||
for (const channelType of configuredChannels) {
|
||||
const accountIds = listConfiguredAccountIdsForChannel(config, channelType);
|
||||
let primaryOwner: string | undefined;
|
||||
const hasExplicitAccountBindingForChannel = accountIds.some((accountId) =>
|
||||
accountToAgent.has(`${channelType}:${accountId}`),
|
||||
);
|
||||
|
||||
for (const accountId of accountIds) {
|
||||
const owner =
|
||||
accountToAgent.get(`${channelType}:${accountId}`)
|
||||
|| (accountId === DEFAULT_ACCOUNT_ID ? (channelToAgent.get(channelType) || defaultAgentIdNorm) : undefined);
|
||||
|| (
|
||||
accountId === DEFAULT_ACCOUNT_ID && !hasExplicitAccountBindingForChannel
|
||||
? (channelToAgent.get(channelType) || defaultAgentIdNorm)
|
||||
: undefined
|
||||
);
|
||||
|
||||
if (!owner) {
|
||||
continue;
|
||||
}
|
||||
|
||||
channelAccountOwners[`${channelType}:${accountId}`] = owner;
|
||||
primaryOwner ??= owner;
|
||||
const existing = agentChannelSets.get(owner) ?? new Set();
|
||||
existing.add(channelType);
|
||||
@@ -486,6 +526,7 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument): Promise<Age
|
||||
defaultAgentId,
|
||||
configuredChannelTypes: configuredChannels,
|
||||
channelOwners,
|
||||
channelAccountOwners,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -575,6 +616,7 @@ export async function deleteAgentConfig(agentId: string): Promise<{ snapshot: Ag
|
||||
|
||||
const config = await readOpenClawConfig() as AgentConfigDocument;
|
||||
const { agentsConfig, entries, defaultAgentId } = normalizeAgentsConfig(config);
|
||||
const snapshotBeforeDeletion = await buildSnapshotFromConfig(config);
|
||||
const removedEntry = entries.find((entry) => entry.id === agentId);
|
||||
const nextEntries = entries.filter((entry) => entry.id !== agentId);
|
||||
if (!removedEntry || nextEntries.length === entries.length) {
|
||||
@@ -596,8 +638,20 @@ export async function deleteAgentConfig(agentId: string): Promise<{ snapshot: Ag
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedAgentId = normalizeAgentIdForBinding(agentId);
|
||||
const legacyAccountId = resolveAccountIdForAgent(agentId);
|
||||
const ownedLegacyAccounts = new Set(
|
||||
Object.entries(snapshotBeforeDeletion.channelAccountOwners)
|
||||
.filter(([channelAccountKey, owner]) => {
|
||||
if (owner !== normalizedAgentId) return false;
|
||||
const accountId = channelAccountKey.slice(channelAccountKey.indexOf(':') + 1);
|
||||
return accountId === legacyAccountId;
|
||||
})
|
||||
.map(([channelAccountKey]) => channelAccountKey),
|
||||
);
|
||||
|
||||
await writeOpenClawConfig(config);
|
||||
await deleteAgentChannelAccounts(agentId);
|
||||
await deleteAgentChannelAccounts(agentId, ownedLegacyAccounts);
|
||||
await removeAgentRuntimeDirectory(agentId);
|
||||
// NOTE: workspace directory is NOT deleted here intentionally.
|
||||
// The caller (route handler) defers workspace removal until after
|
||||
@@ -618,6 +672,7 @@ export async function assignChannelToAgent(agentId: string, channelType: string)
|
||||
throw new Error(`Agent "${agentId}" not found`);
|
||||
}
|
||||
|
||||
assertAgentNotBoundToOtherChannel(config.bindings, agentId, channelType);
|
||||
const accountId = resolveAccountIdForAgent(agentId);
|
||||
config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, accountId);
|
||||
await writeOpenClawConfig(config);
|
||||
@@ -626,6 +681,29 @@ export async function assignChannelToAgent(agentId: string, channelType: string)
|
||||
});
|
||||
}
|
||||
|
||||
export async function assignChannelAccountToAgent(
|
||||
agentId: string,
|
||||
channelType: string,
|
||||
accountId: string,
|
||||
): Promise<AgentsSnapshot> {
|
||||
return withConfigLock(async () => {
|
||||
const config = await readOpenClawConfig() as AgentConfigDocument;
|
||||
const { entries } = normalizeAgentsConfig(config);
|
||||
if (!entries.some((entry) => entry.id === agentId)) {
|
||||
throw new Error(`Agent "${agentId}" not found`);
|
||||
}
|
||||
if (!accountId.trim()) {
|
||||
throw new Error('accountId is required');
|
||||
}
|
||||
|
||||
assertAgentNotBoundToOtherChannel(config.bindings, agentId, channelType);
|
||||
config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, accountId.trim());
|
||||
await writeOpenClawConfig(config);
|
||||
logger.info('Assigned channel account to agent', { agentId, channelType, accountId: accountId.trim() });
|
||||
return buildSnapshotFromConfig(config);
|
||||
});
|
||||
}
|
||||
|
||||
export async function clearChannelBinding(channelType: string, accountId?: string): Promise<AgentsSnapshot> {
|
||||
return withConfigLock(async () => {
|
||||
const config = await readOpenClawConfig() as AgentConfigDocument;
|
||||
|
||||
@@ -16,8 +16,7 @@ import { withConfigLock } from './config-mutex';
|
||||
const OPENCLAW_DIR = join(homedir(), '.openclaw');
|
||||
const CONFIG_FILE = join(OPENCLAW_DIR, 'openclaw.json');
|
||||
const WECOM_PLUGIN_ID = 'wecom';
|
||||
const FEISHU_PLUGIN_ID = 'openclaw-lark';
|
||||
const LEGACY_FEISHU_PLUGIN_ID = 'feishu-openclaw-plugin';
|
||||
const FEISHU_PLUGIN_ID_CANDIDATES = ['openclaw-lark', 'feishu-openclaw-plugin'] as const;
|
||||
const DEFAULT_ACCOUNT_ID = 'default';
|
||||
const CHANNEL_TOP_LEVEL_KEYS_TO_KEEP = new Set(['accounts', 'defaultAccount', 'enabled']);
|
||||
|
||||
@@ -53,6 +52,24 @@ function normalizeCredentialValue(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
async function resolveFeishuPluginId(): Promise<string> {
|
||||
const extensionRoot = join(homedir(), '.openclaw', 'extensions');
|
||||
for (const dirName of FEISHU_PLUGIN_ID_CANDIDATES) {
|
||||
const manifestPath = join(extensionRoot, dirName, 'openclaw.plugin.json');
|
||||
try {
|
||||
const raw = await readFile(manifestPath, 'utf-8');
|
||||
const parsed = JSON.parse(raw) as { id?: unknown };
|
||||
if (typeof parsed.id === 'string' && parsed.id.trim()) {
|
||||
return parsed.id.trim();
|
||||
}
|
||||
} catch {
|
||||
// ignore and try next candidate
|
||||
}
|
||||
}
|
||||
// Fallback to the modern id when extension manifests are not available yet.
|
||||
return FEISHU_PLUGIN_ID_CANDIDATES[0];
|
||||
}
|
||||
|
||||
// ── Types ────────────────────────────────────────────────────────
|
||||
|
||||
export interface ChannelConfigData {
|
||||
@@ -121,14 +138,15 @@ export async function writeOpenClawConfig(config: OpenClawConfig): Promise<void>
|
||||
|
||||
// ── Channel operations ───────────────────────────────────────────
|
||||
|
||||
function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: string): void {
|
||||
async function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: string): Promise<void> {
|
||||
if (channelType === 'feishu') {
|
||||
const feishuPluginId = await resolveFeishuPluginId();
|
||||
if (!currentConfig.plugins) {
|
||||
currentConfig.plugins = {
|
||||
allow: [FEISHU_PLUGIN_ID],
|
||||
allow: [feishuPluginId],
|
||||
enabled: true,
|
||||
entries: {
|
||||
[FEISHU_PLUGIN_ID]: { enabled: true }
|
||||
[feishuPluginId]: { enabled: true }
|
||||
}
|
||||
};
|
||||
} else {
|
||||
@@ -136,12 +154,12 @@ function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: strin
|
||||
const allow: string[] = Array.isArray(currentConfig.plugins.allow)
|
||||
? (currentConfig.plugins.allow as string[])
|
||||
: [];
|
||||
// Remove legacy IDs: 'feishu' (built-in) and old 'feishu-openclaw-plugin'
|
||||
// Keep only one active feishu plugin id to avoid doctor validation conflicts.
|
||||
const normalizedAllow = allow.filter(
|
||||
(pluginId) => pluginId !== 'feishu' && pluginId !== LEGACY_FEISHU_PLUGIN_ID
|
||||
(pluginId) => pluginId !== 'feishu' && !FEISHU_PLUGIN_ID_CANDIDATES.includes(pluginId as typeof FEISHU_PLUGIN_ID_CANDIDATES[number])
|
||||
);
|
||||
if (!normalizedAllow.includes(FEISHU_PLUGIN_ID)) {
|
||||
currentConfig.plugins.allow = [...normalizedAllow, FEISHU_PLUGIN_ID];
|
||||
if (!normalizedAllow.includes(feishuPluginId)) {
|
||||
currentConfig.plugins.allow = [...normalizedAllow, feishuPluginId];
|
||||
} else if (normalizedAllow.length !== allow.length) {
|
||||
currentConfig.plugins.allow = normalizedAllow;
|
||||
}
|
||||
@@ -149,14 +167,18 @@ function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: strin
|
||||
if (!currentConfig.plugins.entries) {
|
||||
currentConfig.plugins.entries = {};
|
||||
}
|
||||
// Remove legacy entries that would conflict with the current plugin ID
|
||||
// Remove conflicting feishu entries; keep only the resolved plugin id.
|
||||
delete currentConfig.plugins.entries['feishu'];
|
||||
delete currentConfig.plugins.entries[LEGACY_FEISHU_PLUGIN_ID];
|
||||
|
||||
if (!currentConfig.plugins.entries[FEISHU_PLUGIN_ID]) {
|
||||
currentConfig.plugins.entries[FEISHU_PLUGIN_ID] = {};
|
||||
for (const candidateId of FEISHU_PLUGIN_ID_CANDIDATES) {
|
||||
if (candidateId !== feishuPluginId) {
|
||||
delete currentConfig.plugins.entries[candidateId];
|
||||
}
|
||||
}
|
||||
currentConfig.plugins.entries[FEISHU_PLUGIN_ID].enabled = true;
|
||||
|
||||
if (!currentConfig.plugins.entries[feishuPluginId]) {
|
||||
currentConfig.plugins.entries[feishuPluginId] = {};
|
||||
}
|
||||
currentConfig.plugins.entries[feishuPluginId].enabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,7 +429,7 @@ export async function saveChannelConfig(
|
||||
const currentConfig = await readOpenClawConfig();
|
||||
const resolvedAccountId = accountId || DEFAULT_ACCOUNT_ID;
|
||||
|
||||
ensurePluginAllowlist(currentConfig, channelType);
|
||||
await ensurePluginAllowlist(currentConfig, channelType);
|
||||
|
||||
// Plugin-based channels (e.g. WhatsApp) go under plugins.entries, not channels
|
||||
if (PLUGIN_CHANNELS.includes(channelType)) {
|
||||
@@ -587,9 +609,23 @@ export async function deleteChannelAccountConfig(channelType: string, accountId:
|
||||
if (Object.keys(accounts).length === 0) {
|
||||
delete currentConfig.channels![channelType];
|
||||
} else {
|
||||
if (channelSection.defaultAccount === accountId) {
|
||||
const nextDefaultAccountId = Object.keys(accounts).sort((a, b) => {
|
||||
if (a === DEFAULT_ACCOUNT_ID) return -1;
|
||||
if (b === DEFAULT_ACCOUNT_ID) return 1;
|
||||
return a.localeCompare(b);
|
||||
})[0];
|
||||
if (nextDefaultAccountId) {
|
||||
channelSection.defaultAccount = nextDefaultAccountId;
|
||||
}
|
||||
}
|
||||
// Re-mirror default account credentials to top level after migration
|
||||
// stripped them (same rationale as saveChannelConfig).
|
||||
const defaultAccountData = accounts[DEFAULT_ACCOUNT_ID];
|
||||
const mirroredAccountId =
|
||||
typeof channelSection.defaultAccount === 'string' && channelSection.defaultAccount.trim()
|
||||
? channelSection.defaultAccount
|
||||
: DEFAULT_ACCOUNT_ID;
|
||||
const defaultAccountData = accounts[mirroredAccountId] ?? accounts[DEFAULT_ACCOUNT_ID];
|
||||
if (defaultAccountData) {
|
||||
for (const [key, value] of Object.entries(defaultAccountData)) {
|
||||
channelSection[key] = value;
|
||||
@@ -686,7 +722,85 @@ export async function listConfiguredChannels(): Promise<string[]> {
|
||||
return channels;
|
||||
}
|
||||
|
||||
export async function deleteAgentChannelAccounts(agentId: string): Promise<void> {
|
||||
export interface ConfiguredChannelAccounts {
|
||||
defaultAccountId: string;
|
||||
accountIds: string[];
|
||||
}
|
||||
|
||||
export async function listConfiguredChannelAccounts(): Promise<Record<string, ConfiguredChannelAccounts>> {
|
||||
const config = await readOpenClawConfig();
|
||||
const result: Record<string, ConfiguredChannelAccounts> = {};
|
||||
|
||||
if (!config.channels) {
|
||||
return result;
|
||||
}
|
||||
|
||||
for (const [channelType, section] of Object.entries(config.channels)) {
|
||||
if (!section || section.enabled === false) continue;
|
||||
|
||||
const accountIds = section.accounts && typeof section.accounts === 'object'
|
||||
? Object.keys(section.accounts).filter(Boolean)
|
||||
: [];
|
||||
|
||||
const defaultAccountId = typeof section.defaultAccount === 'string' && section.defaultAccount.trim()
|
||||
? section.defaultAccount
|
||||
: DEFAULT_ACCOUNT_ID;
|
||||
|
||||
if (accountIds.length === 0) {
|
||||
const hasAnyPayload = Object.keys(section).some((key) => !CHANNEL_TOP_LEVEL_KEYS_TO_KEEP.has(key));
|
||||
if (!hasAnyPayload) continue;
|
||||
result[channelType] = {
|
||||
defaultAccountId,
|
||||
accountIds: [DEFAULT_ACCOUNT_ID],
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
result[channelType] = {
|
||||
defaultAccountId,
|
||||
accountIds: accountIds.sort((a, b) => {
|
||||
if (a === DEFAULT_ACCOUNT_ID) return -1;
|
||||
if (b === DEFAULT_ACCOUNT_ID) return 1;
|
||||
return a.localeCompare(b);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function setChannelDefaultAccount(channelType: string, accountId: string): Promise<void> {
|
||||
return withConfigLock(async () => {
|
||||
const trimmedAccountId = accountId.trim();
|
||||
if (!trimmedAccountId) {
|
||||
throw new Error('accountId is required');
|
||||
}
|
||||
|
||||
const currentConfig = await readOpenClawConfig();
|
||||
const channelSection = currentConfig.channels?.[channelType];
|
||||
if (!channelSection) {
|
||||
throw new Error(`Channel "${channelType}" is not configured`);
|
||||
}
|
||||
|
||||
migrateLegacyChannelConfigToAccounts(channelSection, DEFAULT_ACCOUNT_ID);
|
||||
const accounts = channelSection.accounts as Record<string, ChannelConfigData> | undefined;
|
||||
if (!accounts || !accounts[trimmedAccountId]) {
|
||||
throw new Error(`Account "${trimmedAccountId}" is not configured for channel "${channelType}"`);
|
||||
}
|
||||
|
||||
channelSection.defaultAccount = trimmedAccountId;
|
||||
|
||||
const defaultAccountData = accounts[trimmedAccountId];
|
||||
for (const [key, value] of Object.entries(defaultAccountData)) {
|
||||
channelSection[key] = value;
|
||||
}
|
||||
|
||||
await writeOpenClawConfig(currentConfig);
|
||||
logger.info('Set channel default account', { channelType, accountId: trimmedAccountId });
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAgentChannelAccounts(agentId: string, ownedChannelAccounts?: Set<string>): Promise<void> {
|
||||
return withConfigLock(async () => {
|
||||
const currentConfig = await readOpenClawConfig();
|
||||
if (!currentConfig.channels) return;
|
||||
@@ -699,14 +813,31 @@ export async function deleteAgentChannelAccounts(agentId: string): Promise<void>
|
||||
migrateLegacyChannelConfigToAccounts(section, DEFAULT_ACCOUNT_ID);
|
||||
const accounts = section.accounts as Record<string, ChannelConfigData> | undefined;
|
||||
if (!accounts?.[accountId]) continue;
|
||||
if (ownedChannelAccounts && !ownedChannelAccounts.has(`${channelType}:${accountId}`)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
delete accounts[accountId];
|
||||
if (Object.keys(accounts).length === 0) {
|
||||
delete currentConfig.channels[channelType];
|
||||
} else {
|
||||
if (section.defaultAccount === accountId) {
|
||||
const nextDefaultAccountId = Object.keys(accounts).sort((a, b) => {
|
||||
if (a === DEFAULT_ACCOUNT_ID) return -1;
|
||||
if (b === DEFAULT_ACCOUNT_ID) return 1;
|
||||
return a.localeCompare(b);
|
||||
})[0];
|
||||
if (nextDefaultAccountId) {
|
||||
section.defaultAccount = nextDefaultAccountId;
|
||||
}
|
||||
}
|
||||
// Re-mirror default account credentials to top level after migration
|
||||
// stripped them (same rationale as saveChannelConfig).
|
||||
const defaultAccountData = accounts[DEFAULT_ACCOUNT_ID];
|
||||
const mirroredAccountId =
|
||||
typeof section.defaultAccount === 'string' && section.defaultAccount.trim()
|
||||
? section.defaultAccount
|
||||
: DEFAULT_ACCOUNT_ID;
|
||||
const defaultAccountData = accounts[mirroredAccountId] ?? accounts[DEFAULT_ACCOUNT_ID];
|
||||
if (defaultAccountData) {
|
||||
for (const [key, value] of Object.entries(defaultAccountData)) {
|
||||
section[key] = value;
|
||||
|
||||
@@ -131,12 +131,25 @@ async function discoverAgentIds(): Promise<string[]> {
|
||||
// ── OpenClaw Config Helpers ──────────────────────────────────────
|
||||
|
||||
const OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json');
|
||||
const FEISHU_PLUGIN_ID_CANDIDATES = ['openclaw-lark', 'feishu-openclaw-plugin'] as const;
|
||||
const VALID_COMPACTION_MODES = new Set(['default', 'safeguard']);
|
||||
|
||||
async function readOpenClawJson(): Promise<Record<string, unknown>> {
|
||||
return (await readJsonFile<Record<string, unknown>>(OPENCLAW_CONFIG_PATH)) ?? {};
|
||||
}
|
||||
|
||||
async function resolveInstalledFeishuPluginId(): Promise<string | null> {
|
||||
const extensionRoot = join(homedir(), '.openclaw', 'extensions');
|
||||
for (const dirName of FEISHU_PLUGIN_ID_CANDIDATES) {
|
||||
const manifestPath = join(extensionRoot, dirName, 'openclaw.plugin.json');
|
||||
const manifest = await readJsonFile<{ id?: unknown }>(manifestPath);
|
||||
if (typeof manifest?.id === 'string' && manifest.id.trim()) {
|
||||
return manifest.id.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeAgentsDefaultsCompactionMode(config: Record<string, unknown>): void {
|
||||
const agents = (config.agents && typeof config.agents === 'object'
|
||||
? config.agents as Record<string, unknown>
|
||||
@@ -1016,44 +1029,59 @@ export async function sanitizeOpenClawConfig(): Promise<void> {
|
||||
}
|
||||
|
||||
// ── plugins.entries.feishu cleanup ──────────────────────────────
|
||||
// The official feishu plugin registers its channel AS 'feishu' via
|
||||
// openclaw.plugin.json. An explicit entries.feishu.enabled=false
|
||||
// (set by older ClawX to disable the legacy built-in) blocks the
|
||||
// official plugin's channel from starting. Only clean up when the
|
||||
// new openclaw-lark plugin is already configured (to avoid removing
|
||||
// a legitimate old-style feishu plugin from users who haven't upgraded).
|
||||
// Normalize feishu plugin ids dynamically based on installed manifest.
|
||||
// Different environments may report either "openclaw-lark" or
|
||||
// "feishu-openclaw-plugin" as the runtime plugin id.
|
||||
if (typeof plugins === 'object' && !Array.isArray(plugins)) {
|
||||
const pluginsObj = plugins as Record<string, unknown>;
|
||||
const pEntries = pluginsObj.entries as Record<string, Record<string, unknown>> | undefined;
|
||||
const pEntries = (
|
||||
pluginsObj.entries && typeof pluginsObj.entries === 'object' && !Array.isArray(pluginsObj.entries)
|
||||
? pluginsObj.entries
|
||||
: {}
|
||||
) as Record<string, Record<string, unknown>>;
|
||||
if (!pluginsObj.entries || typeof pluginsObj.entries !== 'object' || Array.isArray(pluginsObj.entries)) {
|
||||
pluginsObj.entries = pEntries;
|
||||
}
|
||||
|
||||
// ── feishu-openclaw-plugin → openclaw-lark migration ────────
|
||||
// Plugin @larksuite/openclaw-lark ≥2026.3.12 changed its manifest
|
||||
// id from 'feishu-openclaw-plugin' to 'openclaw-lark'. Migrate
|
||||
// both plugins.allow and plugins.entries so Gateway validation
|
||||
// doesn't reject the config with "plugin not found".
|
||||
const LEGACY_FEISHU_ID = 'feishu-openclaw-plugin';
|
||||
const NEW_FEISHU_ID = 'openclaw-lark';
|
||||
if (Array.isArray(pluginsObj.allow)) {
|
||||
const allowArr = pluginsObj.allow as string[];
|
||||
const legacyIdx = allowArr.indexOf(LEGACY_FEISHU_ID);
|
||||
if (legacyIdx !== -1) {
|
||||
if (!allowArr.includes(NEW_FEISHU_ID)) {
|
||||
allowArr[legacyIdx] = NEW_FEISHU_ID;
|
||||
} else {
|
||||
allowArr.splice(legacyIdx, 1);
|
||||
}
|
||||
console.log(`[sanitize] Migrated plugins.allow: ${LEGACY_FEISHU_ID} → ${NEW_FEISHU_ID}`);
|
||||
const allowArr = Array.isArray(pluginsObj.allow) ? pluginsObj.allow as string[] : [];
|
||||
if (!Array.isArray(pluginsObj.allow)) {
|
||||
pluginsObj.allow = allowArr;
|
||||
}
|
||||
|
||||
const installedFeishuId = await resolveInstalledFeishuPluginId();
|
||||
const configuredFeishuId =
|
||||
FEISHU_PLUGIN_ID_CANDIDATES.find((id) => allowArr.includes(id))
|
||||
|| FEISHU_PLUGIN_ID_CANDIDATES.find((id) => Boolean(pEntries[id]));
|
||||
const canonicalFeishuId = installedFeishuId || configuredFeishuId || FEISHU_PLUGIN_ID_CANDIDATES[0];
|
||||
|
||||
const existingFeishuEntry =
|
||||
FEISHU_PLUGIN_ID_CANDIDATES.map((id) => pEntries[id]).find(Boolean)
|
||||
|| pEntries.feishu;
|
||||
|
||||
const normalizedAllow = allowArr.filter(
|
||||
(id) => id !== 'feishu' && !FEISHU_PLUGIN_ID_CANDIDATES.includes(id as typeof FEISHU_PLUGIN_ID_CANDIDATES[number]),
|
||||
);
|
||||
normalizedAllow.push(canonicalFeishuId);
|
||||
if (JSON.stringify(normalizedAllow) !== JSON.stringify(allowArr)) {
|
||||
pluginsObj.allow = normalizedAllow;
|
||||
modified = true;
|
||||
console.log(`[sanitize] Normalized plugins.allow for feishu -> ${canonicalFeishuId}`);
|
||||
}
|
||||
|
||||
if (existingFeishuEntry || !pEntries[canonicalFeishuId]) {
|
||||
pEntries[canonicalFeishuId] = {
|
||||
...(existingFeishuEntry || {}),
|
||||
...(pEntries[canonicalFeishuId] || {}),
|
||||
enabled: true,
|
||||
};
|
||||
modified = true;
|
||||
}
|
||||
for (const id of FEISHU_PLUGIN_ID_CANDIDATES) {
|
||||
if (id !== canonicalFeishuId && pEntries[id]) {
|
||||
delete pEntries[id];
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (pEntries?.[LEGACY_FEISHU_ID]) {
|
||||
if (!pEntries[NEW_FEISHU_ID]) {
|
||||
pEntries[NEW_FEISHU_ID] = pEntries[LEGACY_FEISHU_ID];
|
||||
}
|
||||
delete pEntries[LEGACY_FEISHU_ID];
|
||||
console.log(`[sanitize] Migrated plugins.entries: ${LEGACY_FEISHU_ID} → ${NEW_FEISHU_ID}`);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// ── wecom-openclaw-plugin → wecom migration ────────────────
|
||||
const LEGACY_WECOM_ID = 'wecom-openclaw-plugin';
|
||||
@@ -1080,27 +1108,27 @@ export async function sanitizeOpenClawConfig(): Promise<void> {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// ── Remove bare 'feishu' when openclaw-lark is present ─────────
|
||||
// ── Remove bare 'feishu' when canonical feishu plugin is present ──
|
||||
// The Gateway binary automatically adds bare 'feishu' to plugins.allow
|
||||
// because the openclaw-lark plugin registers the 'feishu' channel.
|
||||
// because the official plugin registers the 'feishu' channel.
|
||||
// However, there's no plugin with id='feishu', so Gateway validation
|
||||
// fails with "plugin not found: feishu". Remove it from allow[] and
|
||||
// disable the entries.feishu entry to prevent Gateway from re-adding it.
|
||||
const allowArr2 = Array.isArray(pluginsObj.allow) ? pluginsObj.allow as string[] : [];
|
||||
const hasNewFeishu = allowArr2.includes(NEW_FEISHU_ID) || !!pEntries?.[NEW_FEISHU_ID];
|
||||
if (hasNewFeishu) {
|
||||
const hasCanonicalFeishu = allowArr2.includes(canonicalFeishuId) || !!pEntries[canonicalFeishuId];
|
||||
if (hasCanonicalFeishu) {
|
||||
// Remove bare 'feishu' from plugins.allow
|
||||
const bareFeishuIdx = allowArr2.indexOf('feishu');
|
||||
if (bareFeishuIdx !== -1) {
|
||||
allowArr2.splice(bareFeishuIdx, 1);
|
||||
console.log('[sanitize] Removed bare "feishu" from plugins.allow (openclaw-lark is configured)');
|
||||
console.log('[sanitize] Removed bare "feishu" from plugins.allow (feishu plugin is configured)');
|
||||
modified = true;
|
||||
}
|
||||
// Disable bare 'feishu' in plugins.entries so Gateway won't re-add it
|
||||
if (pEntries?.feishu) {
|
||||
if (pEntries.feishu) {
|
||||
if (pEntries.feishu.enabled !== false) {
|
||||
pEntries.feishu.enabled = false;
|
||||
console.log('[sanitize] Disabled bare plugins.entries.feishu (openclaw-lark is configured)');
|
||||
console.log('[sanitize] Disabled bare plugins.entries.feishu (feishu plugin is configured)');
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user