Move provider to a plugin-architecture (#661)

* refactor: introduce provider plugin registry

* refactor: move provider CLI to plugins

* docs: add provider plugin implementation notes

* refactor: shift provider runtime logic into plugins

* refactor: add plugin defaults and summaries

* docs: update provider plugin notes

* feat(commands): add /commands slash list

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* Tests: align google shared expectations

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* refactor: move provider routing into plugins

* test: align agent routing expectations

* docs: update provider plugin notes

* refactor: route replies via provider plugins

* docs: note route-reply plugin hooks

* refactor: extend provider plugin contract

* refactor: derive provider status from plugins

* refactor: unify gateway provider control

* refactor: use plugin metadata in auto-reply

* fix: parenthesize cron target selection

* refactor: derive gateway methods from plugins

* refactor: generalize provider logout

* refactor: route provider logout through plugins

* refactor: move WhatsApp web login methods into plugin

* refactor: generalize provider log prefixes

* refactor: centralize default chat provider

* refactor: derive provider lists from registry

* refactor: move provider reload noops into plugins

* refactor: resolve web login provider via alias

* refactor: derive CLI provider options from plugins

* refactor: derive prompt provider list from plugins

* style: apply biome lint fixes

* fix: resolve provider routing edge cases

* docs: update provider plugin refactor notes

* fix(gateway): harden agent provider routing

* refactor: move provider routing into plugins

* refactor: move provider CLI to plugins

* refactor: derive provider lists from registry

* fix: restore slash command parsing

* refactor: align provider ids for schema

* refactor: unify outbound target resolution

* fix: keep outbound labels stable

* feat: add msteams to cron surfaces

* fix: clean up lint build issues

* refactor: localize chat provider alias normalization

* refactor: drive gateway provider lists from plugins

* docs: update provider plugin notes

* style: format message-provider

* fix: avoid provider registry init cycles

* style: sort message-provider imports

* fix: relax provider alias map typing

* refactor: move provider routing into plugins

* refactor: add plugin pairing/config adapters

* refactor: route pairing and provider removal via plugins

* refactor: align auto-reply provider typing

* test: stabilize telegram media mocks

* docs: update provider plugin refactor notes

* refactor: pluginize outbound targets

* refactor: pluginize provider selection

* refactor: generalize text chunk limits

* docs: update provider plugin notes

* refactor: generalize group session/config

* fix: normalize provider id for room detection

* fix: avoid provider init in system prompt

* style: formatting cleanup

* refactor: normalize agent delivery targets

* test: update outbound delivery labels

* chore: fix lint regressions

* refactor: extend provider plugin adapters

* refactor: move elevated/block streaming defaults to plugins

* refactor: defer outbound send deps to plugins

* docs: note plugin-driven streaming/elevated defaults

* refactor: centralize webchat provider constant

* refactor: add provider setup adapters

* refactor: delegate provider add config to plugins

* docs: document plugin-driven provider add

* refactor: add plugin state/binding metadata

* refactor: build agent provider status from plugins

* docs: note plugin-driven agent bindings

* refactor: centralize internal provider constant usage

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* refactor: centralize default chat provider

* refactor: centralize WhatsApp target normalization

* refactor: move provider routing into plugins

* refactor: normalize agent delivery targets

* chore: fix lint regressions

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* feat: expand provider plugin adapters

* refactor: route auto-reply via provider plugins

* fix: align WhatsApp target normalization

* fix: normalize WhatsApp targets for groups and E.164 (#631) (thanks @imfing)

* refactor: centralize WhatsApp target normalization

* feat: add /config chat config updates

* docs: add /config get alias

* feat(commands): add /commands slash list

* refactor: centralize default chat provider

* style: apply biome lint fixes

* chore: fix lint regressions

* fix: clean up whatsapp allowlist typing

* style: format config command helpers

* refactor: pluginize tool threading context

* refactor: normalize session announce targets

* docs: note new plugin threading and announce hooks

* refactor: pluginize message actions

* docs: update provider plugin actions notes

* fix: align provider action adapters

* refactor: centralize webchat checks

* style: format message provider helpers

* refactor: move provider onboarding into adapters

* docs: note onboarding provider adapters

* feat: add msteams onboarding adapter

* style: organize onboarding imports

* fix: normalize msteams allowFrom types

* feat: add plugin text chunk limits

* refactor: use plugin chunk limit fallbacks

* feat: add provider mention stripping hooks

* style: organize provider plugin type imports

* refactor: generalize health snapshots

* refactor: update macOS health snapshot handling

* docs: refresh health snapshot notes

* style: format health snapshot updates

* refactor: drive security warnings via plugins

* docs: note provider security adapter

* style: format provider security adapters

* refactor: centralize provider account defaults

* refactor: type gateway client identity constants

* chore: regen gateway protocol swift

* fix: degrade health on failed provider probe

* refactor: centralize pairing approve hint

* docs: add plugin CLI command references

* refactor: route auth and tool sends through plugins

* docs: expand provider plugin hooks

* refactor: document provider docking touchpoints

* refactor: normalize internal provider defaults

* refactor: streamline outbound delivery wiring

* refactor: make provider onboarding plugin-owned

* refactor: support provider-owned agent tools

* refactor: move telegram draft chunking into telegram module

* refactor: infer provider tool sends via extractToolSend

* fix: repair plugin onboarding imports

* refactor: de-dup outbound target normalization

* style: tidy plugin and agent imports

* refactor: data-drive provider selection line

* fix: satisfy lint after provider plugin rebase

* test: deflake gateway-cli coverage

* style: format gateway-cli coverage test

* refactor(provider-plugins): simplify provider ids

* test(pairing-cli): avoid provider-specific ternary

* style(macos): swiftformat HealthStore

* refactor(sandbox): derive provider tool denylist

* fix(sandbox): avoid plugin init in defaults

* refactor(provider-plugins): centralize provider aliases

* style(test): satisfy biome

* refactor(protocol): v3 providers.status maps

* refactor(ui): adapt to protocol v3

* refactor(macos): adapt to protocol v3

* test: update providers.status v3 fixtures

* refactor(gateway): map provider runtime snapshot

* test(gateway): update reload runtime snapshot

* refactor(whatsapp): normalize heartbeat provider id

* docs(refactor): update provider plugin notes

* style: satisfy biome after rebase

* fix: describe sandboxed elevated in prompt

* feat(gateway): add agent image attachments + live probe

* refactor: derive CLI provider options from plugins

* fix(gateway): harden agent provider routing

* fix(gateway): harden agent provider routing

* refactor: align provider ids for schema

* fix(protocol): keep agent provider string

* fix(gateway): harden agent provider routing

* fix(protocol): keep agent provider string

* refactor: normalize agent delivery targets

* refactor: support provider-owned agent tools

* refactor(config): provider-keyed elevated allowFrom

* style: satisfy biome

* fix(gateway): appease provider narrowing

* style: satisfy biome

* refactor(reply): move group intro hints into plugin

* fix(reply): avoid plugin registry init cycle

* refactor(providers): add lightweight provider dock

* refactor(gateway): use typed client id in connect

* refactor(providers): document docks and avoid init cycles

* refactor(providers): make media limit helper generic

* fix(providers): break plugin registry import cycles

* style: satisfy biome

* refactor(status-all): build providers table from plugins

* refactor(gateway): delegate web login to provider plugin

* refactor(provider): drop web alias

* refactor(provider): lazy-load monitors

* style: satisfy lint/format

* style: format status-all providers table

* style: swiftformat gateway discovery model

* test: make reload plan plugin-driven

* fix: avoid token stringification in status-all

* refactor: make provider IDs explicit in status

* feat: warn on signal/imessage provider runtime errors

* test: cover gateway provider runtime warnings in status

* fix: add runtime kind to provider status issues

* test: cover health degradation on probe failure

* fix: keep routeReply lightweight

* style: organize routeReply imports

* refactor(web): extract auth-store helpers

* refactor(whatsapp): lazy login imports

* refactor(outbound): route replies via plugin outbound

* docs: update provider plugin notes

* style: format provider status issues

* fix: make sandbox scope warning wrap-safe

* refactor: load outbound adapters from provider plugins

* docs: update provider plugin outbound notes

* style(macos): fix swiftformat lint

* docs: changelog for provider plugins

* fix(macos): satisfy swiftformat

* fix(macos): open settings via menu action

* style: format after rebase

* fix(macos): open Settings via menu action

---------

Co-authored-by: LK <luke@kyohere.com>
Co-authored-by: Luke K (pr-0f3t) <2609441+lc0rp@users.noreply.github.com>
Co-authored-by: Xin <xin@imfing.com>
This commit is contained in:
Peter Steinberger
2026-01-11 11:45:25 +00:00
committed by GitHub
parent 23eec7d841
commit 7acd26a2fc
232 changed files with 13642 additions and 10809 deletions

View File

@@ -1,56 +1,12 @@
import type { ClawdbotConfig } from "../../config/config.js";
import type { ChatProviderId } from "../../providers/registry.js";
import {
DEFAULT_ACCOUNT_ID,
normalizeAccountId,
} from "../../routing/session-key.js";
import { getProviderPlugin } from "../../providers/plugins/index.js";
import type {
ProviderId,
ProviderSetupInput,
} from "../../providers/plugins/types.js";
import { normalizeAccountId } from "../../routing/session-key.js";
type ChatProvider = ChatProviderId;
function providerHasAccounts(cfg: ClawdbotConfig, provider: ChatProvider) {
if (provider === "whatsapp") return true;
const base = (cfg as Record<string, unknown>)[provider] as
| { accounts?: Record<string, unknown> }
| undefined;
return Boolean(base?.accounts && Object.keys(base.accounts).length > 0);
}
function shouldStoreNameInAccounts(
cfg: ClawdbotConfig,
provider: ChatProvider,
accountId: string,
): boolean {
if (provider === "whatsapp") return true;
if (accountId !== DEFAULT_ACCOUNT_ID) return true;
return providerHasAccounts(cfg, provider);
}
function migrateBaseNameToDefaultAccount(
cfg: ClawdbotConfig,
provider: ChatProvider,
): ClawdbotConfig {
if (provider === "whatsapp") return cfg;
const base = (cfg as Record<string, unknown>)[provider] as
| { name?: string; accounts?: Record<string, Record<string, unknown>> }
| undefined;
const baseName = base?.name?.trim();
if (!baseName) return cfg;
const accounts: Record<string, Record<string, unknown>> = {
...base?.accounts,
};
const defaultAccount = accounts[DEFAULT_ACCOUNT_ID] ?? {};
if (!defaultAccount.name) {
accounts[DEFAULT_ACCOUNT_ID] = { ...defaultAccount, name: baseName };
}
const { name: _ignored, ...rest } = base ?? {};
return {
...cfg,
[provider]: {
...rest,
accounts,
},
} as ClawdbotConfig;
}
type ChatProvider = ProviderId;
export function applyAccountName(params: {
cfg: ClawdbotConfig;
@@ -58,65 +14,12 @@ export function applyAccountName(params: {
accountId: string;
name?: string;
}): ClawdbotConfig {
const trimmed = params.name?.trim();
if (!trimmed) return params.cfg;
const accountId = normalizeAccountId(params.accountId);
if (params.provider === "whatsapp") {
return {
...params.cfg,
whatsapp: {
...params.cfg.whatsapp,
accounts: {
...params.cfg.whatsapp?.accounts,
[accountId]: {
...params.cfg.whatsapp?.accounts?.[accountId],
name: trimmed,
},
},
},
};
}
const key = params.provider;
const useAccounts = shouldStoreNameInAccounts(params.cfg, key, accountId);
if (!useAccounts && accountId === DEFAULT_ACCOUNT_ID) {
const baseConfig = (params.cfg as Record<string, unknown>)[key];
const safeBase =
typeof baseConfig === "object" && baseConfig
? (baseConfig as Record<string, unknown>)
: {};
return {
...params.cfg,
[key]: {
...safeBase,
name: trimmed,
},
} as ClawdbotConfig;
}
const base = (params.cfg as Record<string, unknown>)[key] as
| { name?: string; accounts?: Record<string, Record<string, unknown>> }
| undefined;
const baseAccounts: Record<
string,
Record<string, unknown>
> = base?.accounts ?? {};
const existingAccount = baseAccounts[accountId] ?? {};
const baseWithoutName =
accountId === DEFAULT_ACCOUNT_ID
? (({ name: _ignored, ...rest }) => rest)(base ?? {})
: (base ?? {});
return {
...params.cfg,
[key]: {
...baseWithoutName,
accounts: {
...baseAccounts,
[accountId]: {
...existingAccount,
name: trimmed,
},
},
},
} as ClawdbotConfig;
const plugin = getProviderPlugin(params.provider);
const apply = plugin?.setup?.applyAccountName;
return apply
? apply({ cfg: params.cfg, accountId, name: params.name })
: params.cfg;
}
export function applyProviderAccountConfig(params: {
@@ -140,205 +43,25 @@ export function applyProviderAccountConfig(params: {
useEnv?: boolean;
}): ClawdbotConfig {
const accountId = normalizeAccountId(params.accountId);
const name = params.name?.trim() || undefined;
const namedConfig = applyAccountName({
cfg: params.cfg,
provider: params.provider,
accountId,
name,
});
const next =
accountId !== DEFAULT_ACCOUNT_ID
? migrateBaseNameToDefaultAccount(namedConfig, params.provider)
: namedConfig;
if (params.provider === "whatsapp") {
const entry = {
...next.whatsapp?.accounts?.[accountId],
...(params.authDir ? { authDir: params.authDir } : {}),
enabled: true,
};
return {
...next,
whatsapp: {
...next.whatsapp,
accounts: {
...next.whatsapp?.accounts,
[accountId]: entry,
},
},
};
}
if (params.provider === "telegram") {
if (accountId === DEFAULT_ACCOUNT_ID) {
return {
...next,
telegram: {
...next.telegram,
enabled: true,
...(params.useEnv
? {}
: params.tokenFile
? { tokenFile: params.tokenFile }
: params.token
? { botToken: params.token }
: {}),
},
};
}
return {
...next,
telegram: {
...next.telegram,
enabled: true,
accounts: {
...next.telegram?.accounts,
[accountId]: {
...next.telegram?.accounts?.[accountId],
enabled: true,
...(params.tokenFile
? { tokenFile: params.tokenFile }
: params.token
? { botToken: params.token }
: {}),
},
},
},
};
}
if (params.provider === "discord") {
if (accountId === DEFAULT_ACCOUNT_ID) {
return {
...next,
discord: {
...next.discord,
enabled: true,
...(params.useEnv ? {} : params.token ? { token: params.token } : {}),
},
};
}
return {
...next,
discord: {
...next.discord,
enabled: true,
accounts: {
...next.discord?.accounts,
[accountId]: {
...next.discord?.accounts?.[accountId],
enabled: true,
...(params.token ? { token: params.token } : {}),
},
},
},
};
}
if (params.provider === "slack") {
if (accountId === DEFAULT_ACCOUNT_ID) {
return {
...next,
slack: {
...next.slack,
enabled: true,
...(params.useEnv
? {}
: {
...(params.botToken ? { botToken: params.botToken } : {}),
...(params.appToken ? { appToken: params.appToken } : {}),
}),
},
};
}
return {
...next,
slack: {
...next.slack,
enabled: true,
accounts: {
...next.slack?.accounts,
[accountId]: {
...next.slack?.accounts?.[accountId],
enabled: true,
...(params.botToken ? { botToken: params.botToken } : {}),
...(params.appToken ? { appToken: params.appToken } : {}),
},
},
},
};
}
if (params.provider === "signal") {
if (accountId === DEFAULT_ACCOUNT_ID) {
return {
...next,
signal: {
...next.signal,
enabled: true,
...(params.signalNumber ? { account: params.signalNumber } : {}),
...(params.cliPath ? { cliPath: params.cliPath } : {}),
...(params.httpUrl ? { httpUrl: params.httpUrl } : {}),
...(params.httpHost ? { httpHost: params.httpHost } : {}),
...(params.httpPort ? { httpPort: Number(params.httpPort) } : {}),
},
};
}
return {
...next,
signal: {
...next.signal,
enabled: true,
accounts: {
...next.signal?.accounts,
[accountId]: {
...next.signal?.accounts?.[accountId],
enabled: true,
...(params.signalNumber ? { account: params.signalNumber } : {}),
...(params.cliPath ? { cliPath: params.cliPath } : {}),
...(params.httpUrl ? { httpUrl: params.httpUrl } : {}),
...(params.httpHost ? { httpHost: params.httpHost } : {}),
...(params.httpPort ? { httpPort: Number(params.httpPort) } : {}),
},
},
},
};
}
if (params.provider === "imessage") {
if (accountId === DEFAULT_ACCOUNT_ID) {
return {
...next,
imessage: {
...next.imessage,
enabled: true,
...(params.cliPath ? { cliPath: params.cliPath } : {}),
...(params.dbPath ? { dbPath: params.dbPath } : {}),
...(params.service ? { service: params.service } : {}),
...(params.region ? { region: params.region } : {}),
},
};
}
return {
...next,
imessage: {
...next.imessage,
enabled: true,
accounts: {
...next.imessage?.accounts,
[accountId]: {
...next.imessage?.accounts?.[accountId],
enabled: true,
...(params.cliPath ? { cliPath: params.cliPath } : {}),
...(params.dbPath ? { dbPath: params.dbPath } : {}),
...(params.service ? { service: params.service } : {}),
...(params.region ? { region: params.region } : {}),
},
},
},
};
}
return next;
const plugin = getProviderPlugin(params.provider);
const apply = plugin?.setup?.applyAccountConfig;
if (!apply) return params.cfg;
const input: ProviderSetupInput = {
name: params.name,
token: params.token,
tokenFile: params.tokenFile,
botToken: params.botToken,
appToken: params.appToken,
signalNumber: params.signalNumber,
cliPath: params.cliPath,
dbPath: params.dbPath,
service: params.service,
region: params.region,
authDir: params.authDir,
httpUrl: params.httpUrl,
httpHost: params.httpHost,
httpPort: params.httpPort,
useEnv: params.useEnv,
};
return apply({ cfg: params.cfg, accountId, input });
}

View File

@@ -1,5 +1,9 @@
import { writeConfigFile } from "../../config/config.js";
import { normalizeChatProviderId } from "../../providers/registry.js";
import {
getProviderPlugin,
normalizeProviderId,
} from "../../providers/plugins/index.js";
import type { ProviderId } from "../../providers/plugins/types.js";
import {
DEFAULT_ACCOUNT_ID,
normalizeAccountId,
@@ -75,25 +79,12 @@ export async function providersAddCommand(
if (wantsNames) {
for (const provider of selection) {
const accountId = accountIds[provider] ?? DEFAULT_ACCOUNT_ID;
const existingName =
provider === "whatsapp"
? nextConfig.whatsapp?.accounts?.[accountId]?.name
: provider === "telegram"
? (nextConfig.telegram?.accounts?.[accountId]?.name ??
nextConfig.telegram?.name)
: provider === "discord"
? (nextConfig.discord?.accounts?.[accountId]?.name ??
nextConfig.discord?.name)
: provider === "slack"
? (nextConfig.slack?.accounts?.[accountId]?.name ??
nextConfig.slack?.name)
: provider === "signal"
? (nextConfig.signal?.accounts?.[accountId]?.name ??
nextConfig.signal?.name)
: provider === "imessage"
? (nextConfig.imessage?.accounts?.[accountId]?.name ??
nextConfig.imessage?.name)
: undefined;
const plugin = getProviderPlugin(provider as ProviderId);
const account = plugin?.config.resolveAccount(nextConfig, accountId) as
| { name?: string }
| undefined;
const snapshot = plugin?.config.describeAccount?.(account, nextConfig);
const existingName = snapshot?.name ?? account?.name;
const name = await prompter.text({
message: `${provider} account name (${accountId})`,
initialValue: existingName,
@@ -114,76 +105,48 @@ export async function providersAddCommand(
return;
}
const provider = normalizeChatProviderId(opts.provider);
const provider = normalizeProviderId(opts.provider);
if (!provider) {
runtime.error(`Unknown provider: ${String(opts.provider ?? "")}`);
runtime.exit(1);
return;
}
const accountId = normalizeAccountId(opts.account);
const plugin = getProviderPlugin(provider);
if (!plugin?.setup?.applyAccountConfig) {
runtime.error(`Provider ${provider} does not support add.`);
runtime.exit(1);
return;
}
const accountId =
plugin.setup.resolveAccountId?.({ cfg, accountId: opts.account }) ??
normalizeAccountId(opts.account);
const useEnv = opts.useEnv === true;
if (provider === "telegram") {
if (useEnv && accountId !== DEFAULT_ACCOUNT_ID) {
runtime.error(
"TELEGRAM_BOT_TOKEN can only be used for the default account.",
);
runtime.exit(1);
return;
}
if (!useEnv && !opts.token && !opts.tokenFile) {
runtime.error(
"Telegram requires --token or --token-file (or --use-env).",
);
runtime.exit(1);
return;
}
}
if (provider === "discord") {
if (useEnv && accountId !== DEFAULT_ACCOUNT_ID) {
runtime.error(
"DISCORD_BOT_TOKEN can only be used for the default account.",
);
runtime.exit(1);
return;
}
if (!useEnv && !opts.token) {
runtime.error("Discord requires --token (or --use-env).");
runtime.exit(1);
return;
}
}
if (provider === "slack") {
if (useEnv && accountId !== DEFAULT_ACCOUNT_ID) {
runtime.error(
"Slack env tokens can only be used for the default account.",
);
runtime.exit(1);
return;
}
if (!useEnv && (!opts.botToken || !opts.appToken)) {
runtime.error(
"Slack requires --bot-token and --app-token (or --use-env).",
);
runtime.exit(1);
return;
}
}
if (provider === "signal") {
if (
!opts.signalNumber &&
!opts.httpUrl &&
!opts.httpHost &&
!opts.httpPort &&
!opts.cliPath
) {
runtime.error(
"Signal requires --signal-number or --http-url/--http-host/--http-port/--cli-path.",
);
runtime.exit(1);
return;
}
const validationError = plugin.setup.validateInput?.({
cfg,
accountId,
input: {
name: opts.name,
token: opts.token,
tokenFile: opts.tokenFile,
botToken: opts.botToken,
appToken: opts.appToken,
signalNumber: opts.signalNumber,
cliPath: opts.cliPath,
dbPath: opts.dbPath,
service: opts.service,
region: opts.region,
authDir: opts.authDir,
httpUrl: opts.httpUrl,
httpHost: opts.httpHost,
httpPort: opts.httpPort,
useEnv,
},
});
if (validationError) {
runtime.error(validationError);
runtime.exit(1);
return;
}
const nextConfig = applyProviderAccountConfig({

View File

@@ -4,44 +4,19 @@ import {
loadAuthProfileStore,
} from "../../agents/auth-profiles.js";
import { withProgress } from "../../cli/progress.js";
import {
listDiscordAccountIds,
resolveDiscordAccount,
} from "../../discord/accounts.js";
import {
listIMessageAccountIds,
resolveIMessageAccount,
} from "../../imessage/accounts.js";
import {
formatUsageReportLines,
loadProviderUsageSummary,
} from "../../infra/provider-usage.js";
import { resolveMSTeamsCredentials } from "../../msteams/token.js";
import {
type ChatProviderId,
listChatProviders,
} from "../../providers/registry.js";
import { DEFAULT_ACCOUNT_ID } from "../../routing/session-key.js";
import { listProviderPlugins } from "../../providers/plugins/index.js";
import { buildProviderAccountSnapshot } from "../../providers/plugins/status.js";
import type {
ProviderAccountSnapshot,
ProviderPlugin,
} from "../../providers/plugins/types.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import {
listSignalAccountIds,
resolveSignalAccount,
} from "../../signal/accounts.js";
import {
listSlackAccountIds,
resolveSlackAccount,
} from "../../slack/accounts.js";
import {
listTelegramAccountIds,
resolveTelegramAccount,
} from "../../telegram/accounts.js";
import { formatDocsLink } from "../../terminal/links.js";
import { theme } from "../../terminal/theme.js";
import {
listWhatsAppAccountIds,
resolveWhatsAppAuthDir,
} from "../../web/accounts.js";
import { webAuthExists } from "../../web/session.js";
import { formatProviderAccountLabel, requireValidConfig } from "./shared.js";
export type ProvidersListOptions = {
@@ -77,6 +52,49 @@ function formatLinked(value: boolean): string {
return value ? theme.success("linked") : theme.warn("not linked");
}
function shouldShowConfigured(provider: ProviderPlugin): boolean {
return provider.meta.showConfigured !== false;
}
function formatAccountLine(params: {
provider: ProviderPlugin;
snapshot: ProviderAccountSnapshot;
}): string {
const { provider, snapshot } = params;
const label = formatProviderAccountLabel({
provider: provider.id,
accountId: snapshot.accountId,
name: snapshot.name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
const bits: string[] = [];
if (snapshot.linked !== undefined) {
bits.push(formatLinked(snapshot.linked));
}
if (
shouldShowConfigured(provider) &&
typeof snapshot.configured === "boolean"
) {
bits.push(formatConfigured(snapshot.configured));
}
if (snapshot.tokenSource) {
bits.push(formatTokenSource(snapshot.tokenSource));
}
if (snapshot.botTokenSource) {
bits.push(formatSource("bot", snapshot.botTokenSource));
}
if (snapshot.appTokenSource) {
bits.push(formatSource("app", snapshot.appTokenSource));
}
if (snapshot.baseUrl) {
bits.push(`base=${theme.muted(snapshot.baseUrl)}`);
}
if (typeof snapshot.enabled === "boolean") {
bits.push(formatEnabled(snapshot.enabled));
}
return `- ${label}: ${bits.join(", ")}`;
}
async function loadUsageWithProgress(
runtime: RuntimeEnv,
): Promise<Awaited<ReturnType<typeof loadProviderUsageSummary>> | null> {
@@ -99,118 +117,7 @@ export async function providersListCommand(
if (!cfg) return;
const includeUsage = opts.usage !== false;
const accountIdsByProvider: Record<ChatProviderId, string[]> = {
whatsapp: listWhatsAppAccountIds(cfg),
telegram: listTelegramAccountIds(cfg),
discord: listDiscordAccountIds(cfg),
slack: listSlackAccountIds(cfg),
signal: listSignalAccountIds(cfg),
imessage: listIMessageAccountIds(cfg),
msteams: [DEFAULT_ACCOUNT_ID],
};
const lineBuilders: Record<
ChatProviderId,
(accountId: string) => Promise<string>
> = {
telegram: async (accountId) => {
const account = resolveTelegramAccount({ cfg, accountId });
const label = formatProviderAccountLabel({
provider: "telegram",
accountId,
name: account.name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
return `- ${label}: ${formatConfigured(Boolean(account.token))}, ${formatTokenSource(
account.tokenSource,
)}, ${formatEnabled(account.enabled)}`;
},
whatsapp: async (accountId) => {
const { authDir } = resolveWhatsAppAuthDir({ cfg, accountId });
const linked = await webAuthExists(authDir);
const name = cfg.whatsapp?.accounts?.[accountId]?.name;
const label = formatProviderAccountLabel({
provider: "whatsapp",
accountId,
name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
return `- ${label}: ${formatLinked(linked)}, ${formatEnabled(
cfg.whatsapp?.accounts?.[accountId]?.enabled ??
cfg.web?.enabled ??
true,
)}`;
},
discord: async (accountId) => {
const account = resolveDiscordAccount({ cfg, accountId });
const label = formatProviderAccountLabel({
provider: "discord",
accountId,
name: account.name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
return `- ${label}: ${formatConfigured(Boolean(account.token))}, ${formatTokenSource(
account.tokenSource,
)}, ${formatEnabled(account.enabled)}`;
},
slack: async (accountId) => {
const account = resolveSlackAccount({ cfg, accountId });
const configured = Boolean(account.botToken && account.appToken);
const label = formatProviderAccountLabel({
provider: "slack",
accountId,
name: account.name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
return `- ${label}: ${formatConfigured(configured)}, ${formatSource(
"bot",
account.botTokenSource,
)}, ${formatSource("app", account.appTokenSource)}, ${formatEnabled(
account.enabled,
)}`;
},
signal: async (accountId) => {
const account = resolveSignalAccount({ cfg, accountId });
const label = formatProviderAccountLabel({
provider: "signal",
accountId,
name: account.name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
return `- ${label}: ${formatConfigured(account.configured)}, base=${theme.muted(
account.baseUrl,
)}, ${formatEnabled(account.enabled)}`;
},
imessage: async (accountId) => {
const account = resolveIMessageAccount({ cfg, accountId });
const label = formatProviderAccountLabel({
provider: "imessage",
accountId,
name: account.name,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
return `- ${label}: ${formatEnabled(account.enabled)}`;
},
msteams: async (accountId) => {
const label = formatProviderAccountLabel({
provider: "msteams",
accountId,
providerStyle: theme.accent,
accountStyle: theme.heading,
});
const configured = Boolean(resolveMSTeamsCredentials(cfg.msteams));
const enabled = cfg.msteams?.enabled !== false;
return `- ${label}: ${formatConfigured(configured)}, ${formatEnabled(
enabled,
)}`;
},
};
const plugins = listProviderPlugins();
const authStore = loadAuthProfileStore();
const authProfiles = Object.entries(authStore.profiles).map(
@@ -225,19 +132,11 @@ export async function providersListCommand(
);
if (opts.json) {
const usage = includeUsage ? await loadProviderUsageSummary() : undefined;
const payload = {
chat: {
whatsapp: accountIdsByProvider.whatsapp,
telegram: accountIdsByProvider.telegram,
discord: accountIdsByProvider.discord,
slack: accountIdsByProvider.slack,
signal: accountIdsByProvider.signal,
imessage: accountIdsByProvider.imessage,
msteams: accountIdsByProvider.msteams,
},
auth: authProfiles,
...(usage ? { usage } : {}),
};
const chat: Record<string, string[]> = {};
for (const plugin of plugins) {
chat[plugin.id] = plugin.config.listAccountIds(cfg);
}
const payload = { chat, auth: authProfiles, ...(usage ? { usage } : {}) };
runtime.log(JSON.stringify(payload, null, 2));
return;
}
@@ -245,12 +144,21 @@ export async function providersListCommand(
const lines: string[] = [];
lines.push(theme.heading("Chat providers:"));
for (const meta of listChatProviders()) {
const accounts = accountIdsByProvider[meta.id];
for (const plugin of plugins) {
const accounts = plugin.config.listAccountIds(cfg);
if (!accounts || accounts.length === 0) continue;
for (const accountId of accounts) {
const line = await lineBuilders[meta.id](accountId);
lines.push(line);
const snapshot = await buildProviderAccountSnapshot({
plugin,
cfg,
accountId,
});
lines.push(
formatAccountLine({
provider: plugin,
snapshot,
}),
);
}
}

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import { parseLogLine } from "../../logging/parse-log-line.js";
import { getResolvedLoggerSettings } from "../../logging.js";
import { listProviderPlugins } from "../../providers/plugins/index.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import { theme } from "../../terminal/theme.js";
@@ -15,13 +16,8 @@ type LogLine = ReturnType<typeof parseLogLine>;
const DEFAULT_LIMIT = 200;
const MAX_BYTES = 1_000_000;
const PROVIDERS = new Set([
"whatsapp",
"telegram",
"discord",
"slack",
"signal",
"imessage",
const PROVIDERS = new Set<string>([
...listProviderPlugins().map((plugin) => plugin.id),
"all",
]);

View File

@@ -1,19 +1,15 @@
import { type ClawdbotConfig, writeConfigFile } from "../../config/config.js";
import { listDiscordAccountIds } from "../../discord/accounts.js";
import { listIMessageAccountIds } from "../../imessage/accounts.js";
import { resolveProviderDefaultAccountId } from "../../providers/plugins/helpers.js";
import {
listChatProviders,
normalizeChatProviderId,
} from "../../providers/registry.js";
getProviderPlugin,
listProviderPlugins,
normalizeProviderId,
} from "../../providers/plugins/index.js";
import {
DEFAULT_ACCOUNT_ID,
normalizeAccountId,
} from "../../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import { listSignalAccountIds } from "../../signal/accounts.js";
import { listSlackAccountIds } from "../../slack/accounts.js";
import { listTelegramAccountIds } from "../../telegram/accounts.js";
import { listWhatsAppAccountIds } from "../../web/accounts.js";
import { createClackPrompter } from "../../wizard/clack-prompter.js";
import {
type ChatProvider,
@@ -29,22 +25,9 @@ export type ProvidersRemoveOptions = {
};
function listAccountIds(cfg: ClawdbotConfig, provider: ChatProvider): string[] {
switch (provider) {
case "whatsapp":
return listWhatsAppAccountIds(cfg);
case "telegram":
return listTelegramAccountIds(cfg);
case "discord":
return listDiscordAccountIds(cfg);
case "slack":
return listSlackAccountIds(cfg);
case "signal":
return listSignalAccountIds(cfg);
case "imessage":
return listIMessageAccountIds(cfg);
case "msteams":
return [DEFAULT_ACCOUNT_ID];
}
const plugin = getProviderPlugin(provider);
if (!plugin) return [];
return plugin.config.listAccountIds(cfg);
}
export async function providersRemoveCommand(
@@ -57,7 +40,7 @@ export async function providersRemoveCommand(
const useWizard = shouldUseWizard(params);
const prompter = useWizard ? createClackPrompter() : null;
let provider = normalizeChatProviderId(opts.provider);
let provider = normalizeProviderId(opts.provider);
let accountId = normalizeAccountId(opts.account);
const deleteConfig = Boolean(opts.delete);
@@ -65,9 +48,9 @@ export async function providersRemoveCommand(
await prompter.intro("Remove provider account");
provider = (await prompter.select({
message: "Provider",
options: listChatProviders().map((meta) => ({
value: meta.id,
label: meta.label,
options: listProviderPlugins().map((plugin) => ({
value: plugin.id,
label: plugin.meta.label,
})),
})) as ChatProvider;
@@ -110,139 +93,40 @@ export async function providersRemoveCommand(
}
}
const plugin = getProviderPlugin(provider);
if (!plugin) {
runtime.error(`Unknown provider: ${provider}`);
runtime.exit(1);
return;
}
const resolvedAccountId =
normalizeAccountId(accountId) ??
resolveProviderDefaultAccountId({ plugin, cfg });
const accountKey = resolvedAccountId || DEFAULT_ACCOUNT_ID;
let next = { ...cfg };
const accountKey = accountId || DEFAULT_ACCOUNT_ID;
const setAccountEnabled = (key: ChatProvider, enabled: boolean) => {
if (key === "whatsapp") {
next = {
...next,
whatsapp: {
...next.whatsapp,
accounts: {
...next.whatsapp?.accounts,
[accountKey]: {
...next.whatsapp?.accounts?.[accountKey],
enabled,
},
},
},
};
return;
}
const base = (next as Record<string, unknown>)[key] as
| {
accounts?: Record<string, Record<string, unknown>>;
enabled?: boolean;
}
| undefined;
const baseAccounts: Record<
string,
Record<string, unknown>
> = base?.accounts ?? {};
const existingAccount = baseAccounts[accountKey] ?? {};
if (accountKey === DEFAULT_ACCOUNT_ID && !base?.accounts) {
next = {
...next,
[key]: {
...base,
enabled,
},
} as ClawdbotConfig;
return;
}
next = {
...next,
[key]: {
...base,
accounts: {
...baseAccounts,
[accountKey]: {
...existingAccount,
enabled,
},
},
},
} as ClawdbotConfig;
};
const deleteAccount = (key: ChatProvider) => {
if (key === "whatsapp") {
const accounts = { ...next.whatsapp?.accounts };
delete accounts[accountKey];
next = {
...next,
whatsapp: {
...next.whatsapp,
accounts: Object.keys(accounts).length ? accounts : undefined,
},
};
return;
}
const base = (next as Record<string, unknown>)[key] as
| {
accounts?: Record<string, Record<string, unknown>>;
enabled?: boolean;
}
| undefined;
if (accountKey !== DEFAULT_ACCOUNT_ID) {
const accounts = { ...base?.accounts };
delete accounts[accountKey];
next = {
...next,
[key]: {
...base,
accounts: Object.keys(accounts).length ? accounts : undefined,
},
} as ClawdbotConfig;
return;
}
if (base?.accounts && Object.keys(base.accounts).length > 0) {
const accounts = { ...base.accounts };
delete accounts[accountKey];
next = {
...next,
[key]: {
...base,
accounts: Object.keys(accounts).length ? accounts : undefined,
...(key === "telegram"
? { botToken: undefined, tokenFile: undefined, name: undefined }
: key === "discord"
? { token: undefined, name: undefined }
: key === "slack"
? { botToken: undefined, appToken: undefined, name: undefined }
: key === "signal"
? {
account: undefined,
httpUrl: undefined,
httpHost: undefined,
httpPort: undefined,
cliPath: undefined,
name: undefined,
}
: key === "imessage"
? {
cliPath: undefined,
dbPath: undefined,
service: undefined,
region: undefined,
name: undefined,
}
: {}),
},
} as ClawdbotConfig;
return;
}
// No accounts map: remove entire provider section.
const clone = { ...next } as Record<string, unknown>;
delete clone[key];
next = clone as ClawdbotConfig;
};
if (deleteConfig) {
deleteAccount(provider);
if (!plugin.config.deleteAccount) {
runtime.error(`Provider ${provider} does not support delete.`);
runtime.exit(1);
return;
}
next = plugin.config.deleteAccount({
cfg: next,
accountId: resolvedAccountId,
});
} else {
setAccountEnabled(provider, false);
if (!plugin.config.setAccountEnabled) {
runtime.error(`Provider ${provider} does not support disable.`);
runtime.exit(1);
return;
}
next = plugin.config.setAccountEnabled({
cfg: next,
accountId: resolvedAccountId,
enabled: false,
});
}
await writeConfigFile(next);

View File

@@ -3,13 +3,13 @@ import {
readConfigFileSnapshot,
} from "../../config/config.js";
import {
type ChatProviderId,
getChatProviderMeta,
} from "../../providers/registry.js";
getProviderPlugin,
type ProviderId,
} from "../../providers/plugins/index.js";
import { DEFAULT_ACCOUNT_ID } from "../../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
export type ChatProvider = ChatProviderId;
export type ChatProvider = ProviderId;
export async function requireValidConfig(
runtime: RuntimeEnv = defaultRuntime,
@@ -39,8 +39,10 @@ export function formatAccountLabel(params: {
return base;
}
export const providerLabel = (provider: ChatProvider) =>
getChatProviderMeta(provider).label;
export const providerLabel = (provider: ChatProvider) => {
const plugin = getProviderPlugin(provider);
return plugin?.meta.label ?? provider;
};
export function formatProviderAccountLabel(params: {
provider: ChatProvider;

View File

@@ -3,45 +3,15 @@ import {
type ClawdbotConfig,
readConfigFileSnapshot,
} from "../../config/config.js";
import {
listDiscordAccountIds,
resolveDiscordAccount,
} from "../../discord/accounts.js";
import { callGateway } from "../../gateway/call.js";
import {
listIMessageAccountIds,
resolveIMessageAccount,
} from "../../imessage/accounts.js";
import { formatAge } from "../../infra/provider-summary.js";
import { collectProvidersStatusIssues } from "../../infra/providers-status-issues.js";
import { resolveMSTeamsCredentials } from "../../msteams/token.js";
import { listChatProviders } from "../../providers/registry.js";
import { DEFAULT_ACCOUNT_ID } from "../../routing/session-key.js";
import { listProviderPlugins } from "../../providers/plugins/index.js";
import { buildProviderAccountSnapshot } from "../../providers/plugins/status.js";
import type { ProviderAccountSnapshot } from "../../providers/plugins/types.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import {
listSignalAccountIds,
resolveSignalAccount,
} from "../../signal/accounts.js";
import {
listSlackAccountIds,
resolveSlackAccount,
} from "../../slack/accounts.js";
import {
listTelegramAccountIds,
resolveTelegramAccount,
} from "../../telegram/accounts.js";
import { formatDocsLink } from "../../terminal/links.js";
import { theme } from "../../terminal/theme.js";
import { normalizeE164 } from "../../utils.js";
import {
listWhatsAppAccountIds,
resolveWhatsAppAccount,
} from "../../web/accounts.js";
import {
getWebAuthAgeMs,
readWebSelfId,
webAuthExists,
} from "../../web/session.js";
import {
type ChatProvider,
formatProviderAccountLabel,
@@ -155,33 +125,24 @@ export function formatGatewayProvidersStatusLines(
return `- ${labelText}: ${bits.join(", ")}`;
});
const plugins = listProviderPlugins();
const accountsByProvider = payload.providerAccounts as
| Record<string, unknown>
| undefined;
const accountPayloads: Partial<
Record<ChatProvider, Array<Record<string, unknown>>>
> = {
whatsapp: Array.isArray(payload.whatsappAccounts)
? (payload.whatsappAccounts as Array<Record<string, unknown>>)
: undefined,
telegram: Array.isArray(payload.telegramAccounts)
? (payload.telegramAccounts as Array<Record<string, unknown>>)
: undefined,
discord: Array.isArray(payload.discordAccounts)
? (payload.discordAccounts as Array<Record<string, unknown>>)
: undefined,
slack: Array.isArray(payload.slackAccounts)
? (payload.slackAccounts as Array<Record<string, unknown>>)
: undefined,
signal: Array.isArray(payload.signalAccounts)
? (payload.signalAccounts as Array<Record<string, unknown>>)
: undefined,
imessage: Array.isArray(payload.imessageAccounts)
? (payload.imessageAccounts as Array<Record<string, unknown>>)
: undefined,
};
Record<string, Array<Record<string, unknown>>>
> = {};
for (const plugin of plugins) {
const raw = accountsByProvider?.[plugin.id];
if (Array.isArray(raw)) {
accountPayloads[plugin.id] = raw as Array<Record<string, unknown>>;
}
}
for (const meta of listChatProviders()) {
const accounts = accountPayloads[meta.id];
for (const plugin of plugins) {
const accounts = accountPayloads[plugin.id];
if (accounts && accounts.length > 0) {
lines.push(...accountLines(meta.id, accounts));
lines.push(...accountLines(plugin.id as ChatProvider, accounts));
}
}
@@ -264,115 +225,21 @@ async function formatConfigProvidersStatusLines(
return `- ${labelText}: ${bits.join(", ")}`;
});
const accounts = {
whatsapp: listWhatsAppAccountIds(cfg).map((accountId) => {
const account = resolveWhatsAppAccount({ cfg, accountId });
const dmPolicy = account.dmPolicy ?? cfg.whatsapp?.dmPolicy ?? "pairing";
const allowFrom = (account.allowFrom ?? cfg.whatsapp?.allowFrom ?? [])
.map(normalizeE164)
.filter(Boolean)
.slice(0, 2);
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: true,
linked: undefined,
dmPolicy,
allowFrom,
};
}),
telegram: listTelegramAccountIds(cfg).map((accountId) => {
const account = resolveTelegramAccount({ cfg, accountId });
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: Boolean(account.token?.trim()),
tokenSource: account.tokenSource,
mode: account.config.webhookUrl ? "webhook" : "polling",
};
}),
discord: listDiscordAccountIds(cfg).map((accountId) => {
const account = resolveDiscordAccount({ cfg, accountId });
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: Boolean(account.token?.trim()),
tokenSource: account.tokenSource,
};
}),
slack: listSlackAccountIds(cfg).map((accountId) => {
const account = resolveSlackAccount({ cfg, accountId });
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured:
Boolean(account.botToken?.trim()) &&
Boolean(account.appToken?.trim()),
botTokenSource: account.botTokenSource,
appTokenSource: account.appTokenSource,
};
}),
signal: listSignalAccountIds(cfg).map((accountId) => {
const account = resolveSignalAccount({ cfg, accountId });
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: account.configured,
baseUrl: account.baseUrl,
};
}),
imessage: listIMessageAccountIds(cfg).map((accountId) => {
const account = resolveIMessageAccount({ cfg, accountId });
const imsgConfigured = Boolean(
account.config.cliPath ||
account.config.dbPath ||
account.config.allowFrom ||
account.config.service ||
account.config.region,
);
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: imsgConfigured,
};
}),
msteams: [
{
accountId: DEFAULT_ACCOUNT_ID,
enabled: cfg.msteams?.enabled !== false,
configured: Boolean(resolveMSTeamsCredentials(cfg.msteams)),
dmPolicy: cfg.msteams?.dmPolicy ?? "pairing",
allowFrom: (cfg.msteams?.allowFrom ?? [])
.map((value) => String(value ?? "").trim())
.filter(Boolean)
.slice(0, 2),
},
],
} satisfies Partial<Record<ChatProvider, Array<Record<string, unknown>>>>;
// WhatsApp linked info (config-only best-effort).
try {
const webLinked = await webAuthExists();
const authAgeMs = getWebAuthAgeMs();
const authAge = authAgeMs === null ? "" : ` auth ${formatAge(authAgeMs)}`;
const { e164 } = readWebSelfId();
lines.push(
`WhatsApp: ${webLinked ? "linked" : "not linked"}${e164 ? ` ${e164}` : ""}${webLinked ? authAge : ""}`,
);
} catch {
// ignore
}
for (const meta of listChatProviders()) {
const providerAccounts = accounts[meta.id];
if (providerAccounts && providerAccounts.length > 0) {
lines.push(...accountLines(meta.id, providerAccounts));
const plugins = listProviderPlugins();
for (const plugin of plugins) {
const accountIds = plugin.config.listAccountIds(cfg);
if (!accountIds.length) continue;
const snapshots: ProviderAccountSnapshot[] = [];
for (const accountId of accountIds) {
const snapshot = await buildProviderAccountSnapshot({
plugin,
cfg,
accountId,
});
snapshots.push(snapshot);
}
if (snapshots.length > 0) {
lines.push(...accountLines(plugin.id as ChatProvider, snapshots));
}
}