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

@@ -7,9 +7,14 @@ import {
resolveStorePath,
} from "../config/sessions.js";
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
import { DEFAULT_CHAT_PROVIDER } from "../providers/registry.js";
import { normalizeMainKey } from "../routing/session-key.js";
import type { RuntimeEnv } from "../runtime.js";
import { normalizeMessageProvider } from "../utils/message-provider.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
normalizeMessageProvider,
} from "../utils/message-provider.js";
import { agentCommand } from "./agent.js";
type AgentGatewayResult = {
@@ -124,7 +129,8 @@ export async function agentViaGatewayCommand(
sessionId: opts.sessionId,
});
const provider = normalizeMessageProvider(opts.provider) ?? "whatsapp";
const provider =
normalizeMessageProvider(opts.provider) ?? DEFAULT_CHAT_PROVIDER;
const idempotencyKey = opts.runId?.trim() || randomIdempotencyKey();
const response = await withProgress(
@@ -151,8 +157,8 @@ export async function agentViaGatewayCommand(
},
expectFinal: true,
timeoutMs: gatewayTimeoutMs,
clientName: "cli",
mode: "cli",
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
}),
);

View File

@@ -33,7 +33,11 @@ import {
type ThinkLevel,
type VerboseLevel,
} from "../auto-reply/thinking.js";
import { type CliDeps, createDefaultDeps } from "../cli/deps.js";
import {
type CliDeps,
createDefaultDeps,
createOutboundSendDeps,
} from "../cli/deps.js";
import { type ClawdbotConfig, loadConfig } from "../config/config.js";
import {
DEFAULT_IDLE_MINUTES,
@@ -58,15 +62,21 @@ import {
normalizeOutboundPayloadsForJson,
} from "../infra/outbound/payloads.js";
import { resolveOutboundTarget } from "../infra/outbound/targets.js";
import {
getProviderPlugin,
normalizeProviderId,
} from "../providers/plugins/index.js";
import type { ProviderOutboundTargetMode } from "../providers/plugins/types.js";
import { DEFAULT_CHAT_PROVIDER } from "../providers/registry.js";
import { normalizeMainKey } from "../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import { applyVerboseOverride } from "../sessions/level-overrides.js";
import { resolveSendPolicy } from "../sessions/send-policy.js";
import {
normalizeMessageProvider,
isInternalMessageProvider,
resolveGatewayMessageProvider,
resolveMessageProvider,
} from "../utils/message-provider.js";
import { normalizeE164 } from "../utils.js";
/** Image content block for Claude API multimodal messages. */
type ImageContent = {
@@ -91,6 +101,7 @@ type AgentCommandOpts = {
/** Message provider context (webchat|voicewake|whatsapp|...). */
messageProvider?: string;
provider?: string; // delivery provider (whatsapp|telegram|...)
deliveryTargetMode?: ProviderOutboundTargetMode;
bestEffortDeliver?: boolean;
abortSignal?: AbortSignal;
lane?: string;
@@ -204,10 +215,6 @@ export async function agentCommand(
});
const workspaceDir = workspace.dir;
const allowFrom = (cfg.whatsapp?.allowFrom ?? [])
.map((val) => normalizeE164(val))
.filter((val) => val.length > 1);
const thinkOverride = normalizeThinkLevel(opts.thinking);
const thinkOnce = normalizeThinkLevel(opts.thinkingOnce);
if (opts.thinking && !thinkOverride) {
@@ -570,7 +577,13 @@ export async function agentCommand(
const deliver = opts.deliver === true;
const bestEffortDeliver = opts.bestEffortDeliver === true;
const deliveryProvider =
normalizeMessageProvider(opts.provider) ?? "whatsapp";
resolveGatewayMessageProvider(opts.provider) ?? DEFAULT_CHAT_PROVIDER;
// Provider docking: delivery providers are resolved via plugin registry.
const deliveryPlugin = !isInternalMessageProvider(deliveryProvider)
? getProviderPlugin(
normalizeProviderId(deliveryProvider) ?? deliveryProvider,
)
: undefined;
const logDeliveryError = (err: unknown) => {
const message = `Delivery failed (${deliveryProvider}${deliveryTarget ? ` to ${deliveryTarget}` : ""}): ${String(err)}`;
@@ -579,20 +592,19 @@ export async function agentCommand(
};
const isDeliveryProviderKnown =
deliveryProvider === "whatsapp" ||
deliveryProvider === "telegram" ||
deliveryProvider === "discord" ||
deliveryProvider === "slack" ||
deliveryProvider === "signal" ||
deliveryProvider === "imessage" ||
deliveryProvider === "webchat";
isInternalMessageProvider(deliveryProvider) || Boolean(deliveryPlugin);
const targetMode: ProviderOutboundTargetMode =
opts.deliveryTargetMode ?? (opts.to ? "explicit" : "implicit");
const resolvedTarget =
deliver && isDeliveryProviderKnown
deliver && isDeliveryProviderKnown && deliveryProvider
? resolveOutboundTarget({
provider: deliveryProvider,
to: opts.to,
allowFrom,
cfg,
accountId:
targetMode === "implicit" ? sessionEntry?.lastAccountId : undefined,
mode: targetMode,
})
: null;
const deliveryTarget = resolvedTarget?.ok ? resolvedTarget.to : undefined;
@@ -643,12 +655,8 @@ export async function agentCommand(
}
if (
deliver &&
(deliveryProvider === "whatsapp" ||
deliveryProvider === "telegram" ||
deliveryProvider === "discord" ||
deliveryProvider === "slack" ||
deliveryProvider === "signal" ||
deliveryProvider === "imessage")
deliveryProvider &&
!isInternalMessageProvider(deliveryProvider)
) {
if (deliveryTarget) {
await deliverOutboundPayloads({
@@ -659,14 +667,7 @@ export async function agentCommand(
bestEffort: bestEffortDeliver,
onError: (err) => logDeliveryError(err),
onPayload: logPayload,
deps: {
sendWhatsApp: deps.sendMessageWhatsApp,
sendTelegram: deps.sendMessageTelegram,
sendDiscord: deps.sendMessageDiscord,
sendSlack: deps.sendMessageSlack,
sendSignal: deps.sendMessageSignal,
sendIMessage: deps.sendMessageIMessage,
},
deps: createOutboundSendDeps(deps, cfg),
});
}
}

View File

@@ -14,17 +14,11 @@ import {
writeConfigFile,
} from "../config/config.js";
import { resolveSessionTranscriptsDirForAgent } from "../config/sessions.js";
import { resolveProviderDefaultAccountId } from "../providers/plugins/helpers.js";
import {
listDiscordAccountIds,
resolveDefaultDiscordAccountId,
resolveDiscordAccount,
} from "../discord/accounts.js";
import {
listIMessageAccountIds,
resolveDefaultIMessageAccountId,
resolveIMessageAccount,
} from "../imessage/accounts.js";
import { resolveMSTeamsCredentials } from "../msteams/token.js";
getProviderPlugin,
listProviderPlugins,
} from "../providers/plugins/index.js";
import {
type ChatProviderId,
getChatProviderMeta,
@@ -37,28 +31,7 @@ import {
} from "../routing/session-key.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import {
listSignalAccountIds,
resolveDefaultSignalAccountId,
resolveSignalAccount,
} from "../signal/accounts.js";
import {
listSlackAccountIds,
resolveDefaultSlackAccountId,
resolveSlackAccount,
} from "../slack/accounts.js";
import {
listTelegramAccountIds,
resolveDefaultTelegramAccountId,
resolveTelegramAccount,
} from "../telegram/accounts.js";
import { resolveUserPath } from "../utils.js";
import {
listWhatsAppAccountIds,
resolveDefaultWhatsAppAccountId,
resolveWhatsAppAuthDir,
} from "../web/accounts.js";
import { webAuthExists } from "../web/session.js";
import { createClackPrompter } from "../wizard/clack-prompter.js";
import { WizardCancelledError } from "../wizard/prompts.js";
import { applyAuthChoice, warnIfModelConfigLooksOff } from "./auth-choice.js";
@@ -486,97 +459,46 @@ async function buildProviderStatusIndex(
): Promise<Map<string, ProviderAccountStatus>> {
const map = new Map<string, ProviderAccountStatus>();
for (const accountId of listWhatsAppAccountIds(cfg)) {
const { authDir } = resolveWhatsAppAuthDir({ cfg, accountId });
const linked = await webAuthExists(authDir);
const enabled =
cfg.whatsapp?.accounts?.[accountId]?.enabled ?? cfg.web?.enabled ?? true;
const hasConfig = Boolean(cfg.whatsapp);
map.set(providerAccountKey("whatsapp", accountId), {
provider: "whatsapp",
accountId,
name: cfg.whatsapp?.accounts?.[accountId]?.name,
state: linked ? "linked" : "not linked",
enabled,
configured: linked || hasConfig,
});
}
for (const accountId of listTelegramAccountIds(cfg)) {
const account = resolveTelegramAccount({ cfg, accountId });
const configured = Boolean(account.token);
map.set(providerAccountKey("telegram", accountId), {
provider: "telegram",
accountId,
name: account.name,
state: configured ? "configured" : "not configured",
enabled: account.enabled,
configured,
});
}
for (const accountId of listDiscordAccountIds(cfg)) {
const account = resolveDiscordAccount({ cfg, accountId });
const configured = Boolean(account.token);
map.set(providerAccountKey("discord", accountId), {
provider: "discord",
accountId,
name: account.name,
state: configured ? "configured" : "not configured",
enabled: account.enabled,
configured,
});
}
for (const accountId of listSlackAccountIds(cfg)) {
const account = resolveSlackAccount({ cfg, accountId });
const configured = Boolean(account.botToken && account.appToken);
map.set(providerAccountKey("slack", accountId), {
provider: "slack",
accountId,
name: account.name,
state: configured ? "configured" : "not configured",
enabled: account.enabled,
configured,
});
}
for (const accountId of listSignalAccountIds(cfg)) {
const account = resolveSignalAccount({ cfg, accountId });
map.set(providerAccountKey("signal", accountId), {
provider: "signal",
accountId,
name: account.name,
state: account.configured ? "configured" : "not configured",
enabled: account.enabled,
configured: account.configured,
});
}
for (const accountId of listIMessageAccountIds(cfg)) {
const account = resolveIMessageAccount({ cfg, accountId });
map.set(providerAccountKey("imessage", accountId), {
provider: "imessage",
accountId,
name: account.name,
state: account.enabled ? "enabled" : "disabled",
enabled: account.enabled,
configured: Boolean(cfg.imessage),
});
}
{
const accountId = DEFAULT_ACCOUNT_ID;
const hasCreds = Boolean(resolveMSTeamsCredentials(cfg.msteams));
const hasConfig = Boolean(cfg.msteams);
const enabled = cfg.msteams?.enabled !== false;
map.set(providerAccountKey("msteams", accountId), {
provider: "msteams",
accountId,
state: hasCreds ? "configured" : "not configured",
enabled,
configured: hasCreds || hasConfig,
});
for (const plugin of listProviderPlugins()) {
const accountIds = plugin.config.listAccountIds(cfg);
for (const accountId of accountIds) {
const account = plugin.config.resolveAccount(cfg, accountId);
const snapshot = plugin.config.describeAccount?.(account, cfg);
const enabled = plugin.config.isEnabled
? plugin.config.isEnabled(account, cfg)
: typeof snapshot?.enabled === "boolean"
? snapshot.enabled
: (account as { enabled?: boolean }).enabled;
const configured = plugin.config.isConfigured
? await plugin.config.isConfigured(account, cfg)
: snapshot?.configured;
const resolvedEnabled = typeof enabled === "boolean" ? enabled : true;
const resolvedConfigured =
typeof configured === "boolean" ? configured : true;
const state =
plugin.status?.resolveAccountState?.({
account,
cfg,
configured: resolvedConfigured,
enabled: resolvedEnabled,
}) ??
(typeof snapshot?.linked === "boolean"
? snapshot.linked
? "linked"
: "not linked"
: resolvedConfigured
? "configured"
: "not configured");
const name = snapshot?.name ?? (account as { name?: string }).name;
map.set(providerAccountKey(plugin.id, accountId), {
provider: plugin.id,
accountId,
name,
state,
enabled,
configured,
});
}
}
return map;
@@ -586,33 +508,20 @@ function resolveDefaultAccountId(
cfg: ClawdbotConfig,
provider: ChatProviderId,
): string {
switch (provider) {
case "whatsapp":
return resolveDefaultWhatsAppAccountId(cfg) || DEFAULT_ACCOUNT_ID;
case "telegram":
return resolveDefaultTelegramAccountId(cfg) || DEFAULT_ACCOUNT_ID;
case "discord":
return resolveDefaultDiscordAccountId(cfg) || DEFAULT_ACCOUNT_ID;
case "slack":
return resolveDefaultSlackAccountId(cfg) || DEFAULT_ACCOUNT_ID;
case "signal":
return resolveDefaultSignalAccountId(cfg) || DEFAULT_ACCOUNT_ID;
case "imessage":
return resolveDefaultIMessageAccountId(cfg) || DEFAULT_ACCOUNT_ID;
case "msteams":
return DEFAULT_ACCOUNT_ID;
}
const plugin = getProviderPlugin(provider);
if (!plugin) return DEFAULT_ACCOUNT_ID;
return resolveProviderDefaultAccountId({ plugin, cfg });
}
function shouldShowProviderEntry(
entry: ProviderAccountStatus,
cfg: ClawdbotConfig,
): boolean {
if (entry.provider === "whatsapp") {
return entry.state === "linked" || Boolean(cfg.whatsapp);
}
if (entry.provider === "imessage") {
return Boolean(cfg.imessage);
const plugin = getProviderPlugin(entry.provider);
if (!plugin) return Boolean(entry.configured);
if (plugin.meta.showConfigured === false) {
const providerConfig = (cfg as Record<string, unknown>)[plugin.id];
return Boolean(entry.configured) || Boolean(providerConfig);
}
return Boolean(entry.configured);
}
@@ -777,9 +686,11 @@ function buildProviderBindings(params: {
const accountId = params.accountIds?.[provider]?.trim();
if (accountId) {
match.accountId = accountId;
} else if (provider === "whatsapp") {
const defaultId = resolveDefaultWhatsAppAccountId(params.config);
match.accountId = defaultId || DEFAULT_ACCOUNT_ID;
} else {
const plugin = getProviderPlugin(provider);
if (plugin?.meta.forceAccountBinding) {
match.accountId = resolveDefaultAccountId(params.config, provider);
}
}
bindings.push({ agentId, match });
}
@@ -809,9 +720,11 @@ function parseBindingSpecs(params: {
errors.push(`Invalid binding "${trimmed}" (empty account id).`);
continue;
}
if (!accountId && provider === "whatsapp") {
accountId = resolveDefaultWhatsAppAccountId(params.config);
if (!accountId) accountId = DEFAULT_ACCOUNT_ID;
if (!accountId) {
const plugin = getProviderPlugin(provider);
if (plugin?.meta.forceAccountBinding) {
accountId = resolveDefaultAccountId(params.config, provider);
}
}
const match: AgentBinding["match"] = { provider };
if (accountId) match.accountId = accountId;

View File

@@ -288,9 +288,12 @@ export function noteSandboxScopeWarnings(cfg: ClawdbotConfig) {
if (overrides.length === 0) continue;
warnings.push(
`- agents.list (id "${agentId}") sandbox ${overrides.join(
"/",
)} overrides ignored\n scope resolves to "shared".`,
[
`- agents.list (id "${agentId}") sandbox ${overrides.join(
"/",
)} overrides ignored.`,
` scope resolves to "shared".`,
].join("\n"),
);
}

View File

@@ -1,29 +1,25 @@
import type { ClawdbotConfig } from "../config/config.js";
import { readProviderAllowFromStore } from "../pairing/pairing-store.js";
import { readTelegramAllowFromStore } from "../telegram/pairing-store.js";
import { resolveTelegramToken } from "../telegram/token.js";
import { resolveProviderDefaultAccountId } from "../providers/plugins/helpers.js";
import { listProviderPlugins } from "../providers/plugins/index.js";
import type { ProviderId } from "../providers/plugins/types.js";
import { note } from "../terminal/note.js";
import { normalizeE164 } from "../utils.js";
export async function noteSecurityWarnings(cfg: ClawdbotConfig) {
const warnings: string[] = [];
const warnDmPolicy = async (params: {
label: string;
provider:
| "telegram"
| "signal"
| "imessage"
| "discord"
| "slack"
| "whatsapp";
provider: ProviderId;
dmPolicy: string;
allowFrom?: Array<string | number> | null;
policyPath?: string;
allowFromPath: string;
approveHint: string;
normalizeEntry?: (raw: string) => string;
}) => {
const dmPolicy = params.dmPolicy;
const policyPath = params.policyPath ?? `${params.allowFromPath}policy`;
const configAllowFrom = (params.allowFrom ?? []).map((v) =>
String(v).trim(),
);
@@ -45,7 +41,6 @@ export async function noteSecurityWarnings(cfg: ClawdbotConfig) {
).length;
if (dmPolicy === "open") {
const policyPath = `${params.allowFromPath}policy`;
const allowFromPath = `${params.allowFromPath}allowFrom`;
warnings.push(
`- ${params.label} DMs: OPEN (${policyPath}="open"). Anyone can DM it.`,
@@ -59,7 +54,6 @@ export async function noteSecurityWarnings(cfg: ClawdbotConfig) {
}
if (dmPolicy === "disabled") {
const policyPath = `${params.allowFromPath}policy`;
warnings.push(
`- ${params.label} DMs: disabled (${policyPath}="disabled").`,
);
@@ -67,7 +61,6 @@ export async function noteSecurityWarnings(cfg: ClawdbotConfig) {
}
if (allowCount === 0) {
const policyPath = `${params.allowFromPath}policy`;
warnings.push(
`- ${params.label} DMs: locked (${policyPath}="${dmPolicy}") with no allowlist; unknown senders will be blocked / get a pairing code.`,
);
@@ -75,121 +68,50 @@ export async function noteSecurityWarnings(cfg: ClawdbotConfig) {
}
};
const telegramConfigured = Boolean(cfg.telegram);
const { token: telegramToken } = resolveTelegramToken(cfg);
if (telegramConfigured && telegramToken.trim()) {
const dmPolicy = cfg.telegram?.dmPolicy ?? "pairing";
const configAllowFrom = (cfg.telegram?.allowFrom ?? []).map((v) =>
String(v).trim(),
);
const hasWildcard = configAllowFrom.includes("*");
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
const allowCount = Array.from(
new Set([
...configAllowFrom
.filter((v) => v !== "*")
.map((v) => v.replace(/^(telegram|tg):/i, ""))
.filter(Boolean),
...storeAllowFrom.filter((v) => v !== "*"),
]),
).length;
if (dmPolicy === "open") {
warnings.push(
`- Telegram DMs: OPEN (telegram.dmPolicy="open"). Anyone who can find the bot can DM it.`,
);
if (!hasWildcard) {
warnings.push(
`- Telegram DMs: config invalid — dmPolicy "open" requires telegram.allowFrom to include "*".`,
);
}
} else if (dmPolicy === "disabled") {
warnings.push(`- Telegram DMs: disabled (telegram.dmPolicy="disabled").`);
} else if (allowCount === 0) {
warnings.push(
`- Telegram DMs: locked (telegram.dmPolicy="${dmPolicy}") with no allowlist; unknown senders will be blocked / get a pairing code.`,
);
warnings.push(
` Approve via: clawdbot pairing list telegram / clawdbot pairing approve telegram <code>`,
);
for (const plugin of listProviderPlugins()) {
if (!plugin.security) continue;
const accountIds = plugin.config.listAccountIds(cfg);
const defaultAccountId = resolveProviderDefaultAccountId({
plugin,
cfg,
accountIds,
});
const account = plugin.config.resolveAccount(cfg, defaultAccountId);
const enabled = plugin.config.isEnabled
? plugin.config.isEnabled(account, cfg)
: true;
if (!enabled) continue;
const configured = plugin.config.isConfigured
? await plugin.config.isConfigured(account, cfg)
: true;
if (!configured) continue;
const dmPolicy = plugin.security.resolveDmPolicy?.({
cfg,
accountId: defaultAccountId,
account,
});
if (dmPolicy) {
await warnDmPolicy({
label: plugin.meta.label ?? plugin.id,
provider: plugin.id,
dmPolicy: dmPolicy.policy,
allowFrom: dmPolicy.allowFrom,
policyPath: dmPolicy.policyPath,
allowFromPath: dmPolicy.allowFromPath,
approveHint: dmPolicy.approveHint,
normalizeEntry: dmPolicy.normalizeEntry,
});
}
const groupPolicy = cfg.telegram?.groupPolicy ?? "open";
const groupAllowlistConfigured =
cfg.telegram?.groups && Object.keys(cfg.telegram.groups).length > 0;
if (groupPolicy === "open" && !groupAllowlistConfigured) {
warnings.push(
`- Telegram groups: open (groupPolicy="open") with no telegram.groups allowlist; mention-gating applies but any group can add + ping.`,
);
if (plugin.security.collectWarnings) {
const extra = await plugin.security.collectWarnings({
cfg,
accountId: defaultAccountId,
account,
});
if (extra?.length) warnings.push(...extra);
}
}
if (cfg.discord?.enabled !== false) {
await warnDmPolicy({
label: "Discord",
provider: "discord",
dmPolicy: cfg.discord?.dm?.policy ?? "pairing",
allowFrom: cfg.discord?.dm?.allowFrom ?? [],
allowFromPath: "discord.dm.",
approveHint:
"Approve via: clawdbot pairing list discord / clawdbot pairing approve discord <code>",
normalizeEntry: (raw) =>
raw.replace(/^(discord|user):/i, "").replace(/^<@!?(\d+)>$/, "$1"),
});
}
if (cfg.slack?.enabled !== false) {
await warnDmPolicy({
label: "Slack",
provider: "slack",
dmPolicy: cfg.slack?.dm?.policy ?? "pairing",
allowFrom: cfg.slack?.dm?.allowFrom ?? [],
allowFromPath: "slack.dm.",
approveHint:
"Approve via: clawdbot pairing list slack / clawdbot pairing approve slack <code>",
normalizeEntry: (raw) => raw.replace(/^(slack|user):/i, ""),
});
}
if (cfg.signal?.enabled !== false) {
await warnDmPolicy({
label: "Signal",
provider: "signal",
dmPolicy: cfg.signal?.dmPolicy ?? "pairing",
allowFrom: cfg.signal?.allowFrom ?? [],
allowFromPath: "signal.",
approveHint:
"Approve via: clawdbot pairing list signal / clawdbot pairing approve signal <code>",
normalizeEntry: (raw) =>
normalizeE164(raw.replace(/^signal:/i, "").trim()),
});
}
if (cfg.imessage?.enabled !== false) {
await warnDmPolicy({
label: "iMessage",
provider: "imessage",
dmPolicy: cfg.imessage?.dmPolicy ?? "pairing",
allowFrom: cfg.imessage?.allowFrom ?? [],
allowFromPath: "imessage.",
approveHint:
"Approve via: clawdbot pairing list imessage / clawdbot pairing approve imessage <code>",
});
}
if (cfg.whatsapp) {
await warnDmPolicy({
label: "WhatsApp",
provider: "whatsapp",
dmPolicy: cfg.whatsapp?.dmPolicy ?? "pairing",
allowFrom: cfg.whatsapp?.allowFrom ?? [],
allowFromPath: "whatsapp.",
approveHint:
"Approve via: clawdbot pairing list whatsapp / clawdbot pairing approve whatsapp <code>",
normalizeEntry: (raw) => normalizeE164(raw),
});
}
if (warnings.length > 0) {
note(warnings.join("\n"), "Security");
}

View File

@@ -28,7 +28,15 @@ const probeGateway = vi.fn(async ({ url }: { url: string }) => {
error: null,
close: null,
health: { ok: true },
status: { web: { linked: false }, sessions: { count: 0 } },
status: {
linkProvider: {
id: "whatsapp",
label: "WhatsApp",
linked: false,
authAgeMs: null,
},
sessions: { count: 0 },
},
presence: [
{ mode: "gateway", reason: "self", host: "local", ip: "127.0.0.1" },
],
@@ -52,7 +60,15 @@ const probeGateway = vi.fn(async ({ url }: { url: string }) => {
error: null,
close: null,
health: { ok: true },
status: { web: { linked: true }, sessions: { count: 2 } },
status: {
linkProvider: {
id: "whatsapp",
label: "WhatsApp",
linked: true,
authAgeMs: 5_000,
},
sessions: { count: 2 },
},
presence: [
{ mode: "gateway", reason: "self", host: "remote", ip: "100.64.0.2" },
],

View File

@@ -10,7 +10,7 @@ vi.mock("../gateway/call.js", () => ({
callGateway: (...args: unknown[]) => callGatewayMock(...args),
}));
vi.mock("../web/session.js", () => ({
vi.mock("../web/auth-store.js", () => ({
webAuthExists: vi.fn(async () => true),
getWebAuthAgeMs: vi.fn(() => 0),
logWebSelfId: (...args: unknown[]) => logWebSelfIdMock(...args),
@@ -32,22 +32,29 @@ describe("healthCommand (coverage)", () => {
ok: true,
ts: Date.now(),
durationMs: 5,
web: {
linked: true,
authAgeMs: 5 * 60_000,
connect: { ok: true, status: 200, elapsedMs: 10 },
},
telegram: {
configured: true,
probe: {
ok: true,
elapsedMs: 7,
bot: { username: "bot" },
webhook: { url: "https://example.com/h" },
providers: {
whatsapp: {
linked: true,
authAgeMs: 5 * 60_000,
},
telegram: {
configured: true,
probe: {
ok: true,
elapsedMs: 7,
bot: { username: "bot" },
webhook: { url: "https://example.com/h" },
},
},
discord: {
configured: false,
},
},
discord: {
configured: false,
providerOrder: ["whatsapp", "telegram", "discord"],
providerLabels: {
whatsapp: "WhatsApp",
telegram: "Telegram",
discord: "Discord",
},
heartbeatSeconds: 60,
sessions: {
@@ -64,7 +71,7 @@ describe("healthCommand (coverage)", () => {
expect(runtime.exit).not.toHaveBeenCalled();
expect(runtime.log.mock.calls.map((c) => String(c[0])).join("\n")).toMatch(
/Web: linked/i,
/WhatsApp: linked/i,
);
expect(logWebSelfIdMock).toHaveBeenCalled();
});

View File

@@ -23,9 +23,10 @@ vi.mock("../config/sessions.js", () => ({
loadSessionStore: () => testStore,
}));
vi.mock("../web/session.js", () => ({
vi.mock("../web/auth-store.js", () => ({
webAuthExists: vi.fn(async () => true),
getWebAuthAgeMs: vi.fn(() => 1234),
readWebSelfId: vi.fn(() => ({ e164: null, jid: null })),
logWebSelfId: vi.fn(),
}));
@@ -49,10 +50,16 @@ describe("getHealthSnapshot", () => {
};
vi.stubEnv("TELEGRAM_BOT_TOKEN", "");
vi.stubEnv("DISCORD_BOT_TOKEN", "");
const snap = (await getHealthSnapshot(10)) satisfies HealthSummary;
const snap = (await getHealthSnapshot({
timeoutMs: 10,
})) satisfies HealthSummary;
expect(snap.ok).toBe(true);
expect(snap.telegram.configured).toBe(false);
expect(snap.telegram.probe).toBeUndefined();
const telegram = snap.providers.telegram as {
configured?: boolean;
probe?: unknown;
};
expect(telegram.configured).toBe(false);
expect(telegram.probe).toBeUndefined();
expect(snap.sessions.count).toBe(2);
expect(snap.sessions.recent[0]?.key).toBe("foo");
});
@@ -98,11 +105,19 @@ describe("getHealthSnapshot", () => {
}),
);
const snap = await getHealthSnapshot(25);
expect(snap.telegram.configured).toBe(true);
expect(snap.telegram.probe?.ok).toBe(true);
expect(snap.telegram.probe?.bot?.username).toBe("bot");
expect(snap.telegram.probe?.webhook?.url).toMatch(/^https:/);
const snap = await getHealthSnapshot({ timeoutMs: 25 });
const telegram = snap.providers.telegram as {
configured?: boolean;
probe?: {
ok?: boolean;
bot?: { username?: string };
webhook?: { url?: string };
};
};
expect(telegram.configured).toBe(true);
expect(telegram.probe?.ok).toBe(true);
expect(telegram.probe?.bot?.username).toBe("bot");
expect(telegram.probe?.webhook?.url).toMatch(/^https:/);
expect(calls.some((c) => c.includes("/getMe"))).toBe(true);
expect(calls.some((c) => c.includes("/getWebhookInfo"))).toBe(true);
});
@@ -151,9 +166,13 @@ describe("getHealthSnapshot", () => {
}),
);
const snap = await getHealthSnapshot(25);
expect(snap.telegram.configured).toBe(true);
expect(snap.telegram.probe?.ok).toBe(true);
const snap = await getHealthSnapshot({ timeoutMs: 25 });
const telegram = snap.providers.telegram as {
configured?: boolean;
probe?: { ok?: boolean };
};
expect(telegram.configured).toBe(true);
expect(telegram.probe?.ok).toBe(true);
expect(calls.some((c) => c.includes("bott-file/getMe"))).toBe(true);
fs.rmSync(tmpDir, { recursive: true, force: true });
@@ -178,11 +197,15 @@ describe("getHealthSnapshot", () => {
}),
);
const snap = await getHealthSnapshot(25);
expect(snap.telegram.configured).toBe(true);
expect(snap.telegram.probe?.ok).toBe(false);
expect(snap.telegram.probe?.status).toBe(401);
expect(snap.telegram.probe?.error).toMatch(/unauthorized/i);
const snap = await getHealthSnapshot({ timeoutMs: 25 });
const telegram = snap.providers.telegram as {
configured?: boolean;
probe?: { ok?: boolean; status?: number; error?: string };
};
expect(telegram.configured).toBe(true);
expect(telegram.probe?.ok).toBe(false);
expect(telegram.probe?.status).toBe(401);
expect(telegram.probe?.error).toMatch(/unauthorized/i);
});
it("captures unexpected probe exceptions as errors", async () => {
@@ -197,9 +220,13 @@ describe("getHealthSnapshot", () => {
}),
);
const snap = await getHealthSnapshot(25);
expect(snap.telegram.configured).toBe(true);
expect(snap.telegram.probe?.ok).toBe(false);
expect(snap.telegram.probe?.error).toMatch(/network down/i);
const snap = await getHealthSnapshot({ timeoutMs: 25 });
const telegram = snap.providers.telegram as {
configured?: boolean;
probe?: { ok?: boolean; error?: string };
};
expect(telegram.configured).toBe(true);
expect(telegram.probe?.ok).toBe(false);
expect(telegram.probe?.error).toMatch(/network down/i);
});
});

View File

@@ -21,15 +21,20 @@ describe("healthCommand", () => {
it("outputs JSON from gateway", async () => {
const snapshot: HealthSummary = {
ok: true,
ts: Date.now(),
durationMs: 5,
web: {
linked: true,
authAgeMs: 5000,
connect: { ok: true, elapsedMs: 10 },
providers: {
whatsapp: { linked: true, authAgeMs: 5000 },
telegram: { configured: true, probe: { ok: true, elapsedMs: 1 } },
discord: { configured: false },
},
providerOrder: ["whatsapp", "telegram", "discord"],
providerLabels: {
whatsapp: "WhatsApp",
telegram: "Telegram",
discord: "Discord",
},
telegram: { configured: true, probe: { ok: true, elapsedMs: 1 } },
discord: { configured: false },
heartbeatSeconds: 60,
sessions: {
path: "/tmp/sessions.json",
@@ -44,18 +49,27 @@ describe("healthCommand", () => {
expect(runtime.exit).not.toHaveBeenCalled();
const logged = runtime.log.mock.calls[0]?.[0] as string;
const parsed = JSON.parse(logged) as HealthSummary;
expect(parsed.web.linked).toBe(true);
expect(parsed.telegram.configured).toBe(true);
expect(parsed.providers.whatsapp?.linked).toBe(true);
expect(parsed.providers.telegram?.configured).toBe(true);
expect(parsed.sessions.count).toBe(1);
});
it("prints text summary when not json", async () => {
callGatewayMock.mockResolvedValueOnce({
ok: true,
ts: Date.now(),
durationMs: 5,
web: { linked: false, authAgeMs: null },
telegram: { configured: false },
discord: { configured: false },
providers: {
whatsapp: { linked: false, authAgeMs: null },
telegram: { configured: false },
discord: { configured: false },
},
providerOrder: ["whatsapp", "telegram", "discord"],
providerLabels: {
whatsapp: "WhatsApp",
telegram: "Telegram",
discord: "Discord",
},
heartbeatSeconds: 60,
sessions: { path: "/tmp/sessions.json", count: 0, recent: [] },
} satisfies HealthSummary);

View File

@@ -1,19 +1,26 @@
import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js";
import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
import { type DiscordProbe, probeDiscord } from "../discord/probe.js";
import { buildGatewayConnectionDetails, callGateway } from "../gateway/call.js";
import { info } from "../globals.js";
import type { RuntimeEnv } from "../runtime.js";
import { probeTelegram, type TelegramProbe } from "../telegram/probe.js";
import { resolveTelegramToken } from "../telegram/token.js";
import { resolveWhatsAppAccount } from "../web/accounts.js";
import { resolveHeartbeatSeconds } from "../web/reconnect.js";
import { formatErrorMessage } from "../infra/errors.js";
import { resolveProviderDefaultAccountId } from "../providers/plugins/helpers.js";
import {
getWebAuthAgeMs,
logWebSelfId,
webAuthExists,
} from "../web/session.js";
getProviderPlugin,
listProviderPlugins,
} from "../providers/plugins/index.js";
import type { ProviderAccountSnapshot } from "../providers/plugins/types.js";
import type { RuntimeEnv } from "../runtime.js";
import { resolveHeartbeatSeconds } from "../web/reconnect.js";
export type ProviderHealthSummary = {
configured?: boolean;
linked?: boolean;
authAgeMs?: number | null;
probe?: unknown;
lastProbeAt?: number | null;
[key: string]: unknown;
};
export type HealthSummary = {
/**
@@ -24,24 +31,9 @@ export type HealthSummary = {
ok: true;
ts: number;
durationMs: number;
web: {
linked: boolean;
authAgeMs: number | null;
connect?: {
ok: boolean;
status?: number | null;
error?: string | null;
elapsedMs?: number | null;
};
};
telegram: {
configured: boolean;
probe?: TelegramProbe;
};
discord: {
configured: boolean;
probe?: DiscordProbe;
};
providers: Record<string, ProviderHealthSummary>;
providerOrder: string[];
providerLabels: Record<string, string>;
heartbeatSeconds: number;
sessions: {
path: string;
@@ -56,13 +48,110 @@ export type HealthSummary = {
const DEFAULT_TIMEOUT_MS = 10_000;
export async function getHealthSnapshot(
timeoutMs?: number,
): Promise<HealthSummary> {
const isAccountEnabled = (account: unknown): boolean => {
if (!account || typeof account !== "object") return true;
const enabled = (account as { enabled?: boolean }).enabled;
return enabled !== false;
};
const asRecord = (value: unknown): Record<string, unknown> | null =>
value && typeof value === "object"
? (value as Record<string, unknown>)
: null;
const formatProbeLine = (probe: unknown): string | null => {
const record = asRecord(probe);
if (!record) return null;
const ok = typeof record.ok === "boolean" ? record.ok : undefined;
if (ok === undefined) return null;
const elapsedMs =
typeof record.elapsedMs === "number" ? record.elapsedMs : null;
const status = typeof record.status === "number" ? record.status : null;
const error = typeof record.error === "string" ? record.error : null;
const bot = asRecord(record.bot);
const botUsername =
bot && typeof bot.username === "string" ? bot.username : null;
const webhook = asRecord(record.webhook);
const webhookUrl =
webhook && typeof webhook.url === "string" ? webhook.url : null;
if (ok) {
let label = "ok";
if (botUsername) label += ` (@${botUsername})`;
if (elapsedMs != null) label += ` (${elapsedMs}ms)`;
if (webhookUrl) label += ` - webhook ${webhookUrl}`;
return label;
}
let label = `failed (${status ?? "unknown"})`;
if (error) label += ` - ${error}`;
return label;
};
export const formatHealthProviderLines = (summary: HealthSummary): string[] => {
const providers = summary.providers ?? {};
const providerOrder =
summary.providerOrder?.length > 0
? summary.providerOrder
: Object.keys(providers);
const lines: string[] = [];
for (const providerId of providerOrder) {
const providerSummary = providers[providerId];
if (!providerSummary) continue;
const plugin = getProviderPlugin(providerId as never);
const label =
summary.providerLabels?.[providerId] ?? plugin?.meta.label ?? providerId;
const linked =
typeof providerSummary.linked === "boolean"
? providerSummary.linked
: null;
if (linked !== null) {
if (linked) {
const authAgeMs =
typeof providerSummary.authAgeMs === "number"
? providerSummary.authAgeMs
: null;
const authLabel =
authAgeMs != null
? ` (auth age ${Math.round(authAgeMs / 60000)}m)`
: "";
lines.push(`${label}: linked${authLabel}`);
} else {
lines.push(`${label}: not linked`);
}
continue;
}
const configured =
typeof providerSummary.configured === "boolean"
? providerSummary.configured
: null;
if (configured === false) {
lines.push(`${label}: not configured`);
continue;
}
const probeLine = formatProbeLine(providerSummary.probe);
if (probeLine) {
lines.push(`${label}: ${probeLine}`);
continue;
}
if (configured === true) {
lines.push(`${label}: configured`);
continue;
}
lines.push(`${label}: unknown`);
}
return lines;
};
export async function getHealthSnapshot(params?: {
timeoutMs?: number;
probe?: boolean;
}): Promise<HealthSummary> {
const timeoutMs = params?.timeoutMs;
const cfg = loadConfig();
const account = resolveWhatsAppAccount({ cfg });
const linked = await webAuthExists(account.authDir);
const authAgeMs = getWebAuthAgeMs(account.authDir);
const heartbeatSeconds = resolveHeartbeatSeconds(cfg, undefined);
const storePath = resolveStorePath(cfg.session?.store);
const store = loadSessionStore(storePath);
@@ -78,27 +167,81 @@ export async function getHealthSnapshot(
const start = Date.now();
const cappedTimeout = Math.max(1000, timeoutMs ?? DEFAULT_TIMEOUT_MS);
const { token: telegramToken } = resolveTelegramToken(cfg);
const telegramConfigured = telegramToken.trim().length > 0;
const telegramProxy = cfg.telegram?.proxy;
const telegramProbe = telegramConfigured
? await probeTelegram(telegramToken.trim(), cappedTimeout, telegramProxy)
: undefined;
const doProbe = params?.probe !== false;
const providers: Record<string, ProviderHealthSummary> = {};
const providerOrder = listProviderPlugins().map((plugin) => plugin.id);
const providerLabels: Record<string, string> = {};
const discordToken =
process.env.DISCORD_BOT_TOKEN ?? cfg.discord?.token ?? "";
const discordConfigured = discordToken.trim().length > 0;
const discordProbe = discordConfigured
? await probeDiscord(discordToken.trim(), cappedTimeout)
: undefined;
for (const plugin of listProviderPlugins()) {
providerLabels[plugin.id] = plugin.meta.label ?? plugin.id;
const accountIds = plugin.config.listAccountIds(cfg);
const defaultAccountId = resolveProviderDefaultAccountId({
plugin,
cfg,
accountIds,
});
const account = plugin.config.resolveAccount(cfg, defaultAccountId);
const enabled = plugin.config.isEnabled
? plugin.config.isEnabled(account, cfg)
: isAccountEnabled(account);
const configured = plugin.config.isConfigured
? await plugin.config.isConfigured(account, cfg)
: true;
let probe: unknown;
let lastProbeAt: number | null = null;
if (enabled && configured && doProbe && plugin.status?.probeAccount) {
try {
probe = await plugin.status.probeAccount({
account,
timeoutMs: cappedTimeout,
cfg,
});
lastProbeAt = Date.now();
} catch (err) {
probe = { ok: false, error: formatErrorMessage(err) };
lastProbeAt = Date.now();
}
}
const snapshot: ProviderAccountSnapshot = {
accountId: defaultAccountId,
enabled,
configured,
};
if (probe !== undefined) snapshot.probe = probe;
if (lastProbeAt) snapshot.lastProbeAt = lastProbeAt;
const summary = plugin.status?.buildProviderSummary
? await plugin.status.buildProviderSummary({
account,
cfg,
defaultAccountId,
snapshot,
})
: undefined;
const record =
summary && typeof summary === "object"
? (summary as ProviderHealthSummary)
: ({
configured,
probe,
lastProbeAt,
} satisfies ProviderHealthSummary);
if (record.configured === undefined) record.configured = configured;
if (record.lastProbeAt === undefined && lastProbeAt) {
record.lastProbeAt = lastProbeAt;
}
providers[plugin.id] = record;
}
const summary: HealthSummary = {
ok: true,
ts: Date.now(),
durationMs: Date.now() - start,
web: { linked, authAgeMs },
telegram: { configured: telegramConfigured, probe: telegramProbe },
discord: { configured: discordConfigured, probe: discordProbe },
providers,
providerOrder,
providerLabels,
heartbeatSeconds,
sessions: {
path: storePath,
@@ -140,47 +283,29 @@ export async function healthCommand(
runtime.log(` ${line}`);
}
}
runtime.log(
summary.web.linked
? `Web: linked (auth age ${summary.web.authAgeMs ? `${Math.round(summary.web.authAgeMs / 60000)}m` : "unknown"})`
: "Web: not linked (run clawdbot providers login)",
);
if (summary.web.linked) {
const cfg = loadConfig();
const account = resolveWhatsAppAccount({ cfg });
logWebSelfId(account.authDir, runtime, true);
for (const line of formatHealthProviderLines(summary)) {
runtime.log(line);
}
if (summary.web.connect) {
const base = summary.web.connect.ok
? info(`Connect: ok (${summary.web.connect.elapsedMs}ms)`)
: `Connect: failed (${summary.web.connect.status ?? "unknown"})`;
runtime.log(
base +
(summary.web.connect.error ? ` - ${summary.web.connect.error}` : ""),
);
const cfg = loadConfig();
for (const plugin of listProviderPlugins()) {
const providerSummary = summary.providers?.[plugin.id];
if (!providerSummary || providerSummary.linked !== true) continue;
if (!plugin.status?.logSelfId) continue;
const accountIds = plugin.config.listAccountIds(cfg);
const defaultAccountId = resolveProviderDefaultAccountId({
plugin,
cfg,
accountIds,
});
const account = plugin.config.resolveAccount(cfg, defaultAccountId);
plugin.status.logSelfId({
account,
cfg,
runtime,
includeProviderPrefix: true,
});
}
const tgLabel = summary.telegram.configured
? summary.telegram.probe?.ok
? info(
`Telegram: ok${summary.telegram.probe.bot?.username ? ` (@${summary.telegram.probe.bot.username})` : ""} (${summary.telegram.probe.elapsedMs}ms)` +
(summary.telegram.probe.webhook?.url
? ` - webhook ${summary.telegram.probe.webhook.url}`
: ""),
)
: `Telegram: failed (${summary.telegram.probe?.status ?? "unknown"})${summary.telegram.probe?.error ? ` - ${summary.telegram.probe.error}` : ""}`
: "Telegram: not configured";
runtime.log(tgLabel);
const discordLabel = summary.discord.configured
? summary.discord.probe?.ok
? info(
`Discord: ok${summary.discord.probe.bot?.username ? ` (@${summary.discord.probe.bot.username})` : ""} (${summary.discord.probe.elapsedMs}ms)`,
)
: `Discord: failed (${summary.discord.probe?.status ?? "unknown"})${summary.discord.probe?.error ? ` - ${summary.discord.probe.error}` : ""}`
: "Discord: not configured";
runtime.log(discordLabel);
runtime.log(info(`Heartbeat interval: ${summary.heartbeatSeconds}s`));
runtime.log(
info(

View File

@@ -1,8 +1,4 @@
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import { handleDiscordAction } from "../agents/tools/discord-actions.js";
import { handleSlackAction } from "../agents/tools/slack-actions.js";
import { handleTelegramAction } from "../agents/tools/telegram-actions.js";
import { handleWhatsAppAction } from "../agents/tools/whatsapp-actions.js";
import type { CliDeps } from "../cli/deps.js";
import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js";
@@ -24,7 +20,13 @@ import {
sendPoll,
} from "../infra/outbound/message.js";
import { resolveMessageProviderSelection } from "../infra/outbound/provider-selection.js";
import { dispatchProviderMessageAction } from "../providers/plugins/message-actions.js";
import type { ProviderMessageActionName } from "../providers/plugins/types.js";
import type { RuntimeEnv } from "../runtime.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
type MessageAction =
| "send"
@@ -277,6 +279,8 @@ export async function messageCommand(
provider: opts.provider,
});
const provider = providerSelection.provider;
const accountId = optionalString(opts.account);
const actionParams = opts as Record<string, unknown>;
const outboundDeps: OutboundSendDeps = {
sendWhatsApp: deps.sendMessageWhatsApp,
sendTelegram: deps.sendMessageTelegram,
@@ -304,7 +308,7 @@ export async function messageCommand(
dryRun: opts.dryRun,
media: optionalString(opts.media),
gifPlayback: opts.gifPlayback,
account: optionalString(opts.account),
account: accountId,
};
if (opts.dryRun) {
@@ -312,72 +316,20 @@ export async function messageCommand(
return;
}
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "sendMessage",
to,
content: message,
mediaUrl: optionalString(opts.media),
replyTo: optionalString(opts.replyTo),
},
cfg,
);
const payload = extractToolPayload(result);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
runtime.log(success(`Sent via ${provider}.`));
}
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "sendMessage",
to,
content: message,
mediaUrl: optionalString(opts.media),
threadTs:
optionalString(opts.threadId) ?? optionalString(opts.replyTo),
accountId: optionalString(opts.account),
},
cfg,
);
const payload = extractToolPayload(result);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
runtime.log(success(`Sent via ${provider}.`));
}
return;
}
if (provider === "telegram") {
const buttonsJson = optionalString(opts.buttonsJson);
let buttons: unknown;
if (buttonsJson) {
try {
buttons = JSON.parse(buttonsJson);
} catch {
throw new Error("buttons-json must be valid JSON");
}
}
const result = await handleTelegramAction(
{
action: "sendMessage",
to,
content: message,
mediaUrl: optionalString(opts.media),
replyToMessageId: optionalString(opts.replyTo),
messageThreadId: optionalString(opts.threadId),
accountId: optionalString(opts.account),
buttons,
},
cfg,
);
const payload = extractToolPayload(result);
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
const payload = extractToolPayload(handled);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
@@ -400,10 +352,13 @@ export async function messageCommand(
provider,
mediaUrl: optionalString(opts.media),
gifPlayback: opts.gifPlayback,
accountId: optionalString(opts.account),
accountId,
dryRun: opts.dryRun,
deps: outboundDeps,
gateway: { clientName: "cli", mode: "cli" },
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}),
);
logSendResult(result, sendOpts, runtime);
@@ -434,26 +389,29 @@ export async function messageCommand(
durationHours,
provider,
dryRun: true,
gateway: { clientName: "cli", mode: "cli" },
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
});
logPollDryRun(result, runtime);
return;
}
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "poll",
to,
question,
answers: options,
allowMultiselect,
durationHours: durationHours ?? undefined,
content: optionalString(opts.message),
},
cfg,
);
const payload = extractToolPayload(result);
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
const payload = extractToolPayload(handled);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
@@ -478,7 +436,10 @@ export async function messageCommand(
durationHours,
provider,
dryRun: opts.dryRun,
gateway: { clientName: "cli", mode: "cli" },
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}),
);
@@ -522,612 +483,24 @@ export async function messageCommand(
return;
}
if (action === "react") {
const messageId = requireString(opts.messageId, "message-id");
const emoji = optionalString(opts.emoji) ?? "";
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "react",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
emoji,
remove: opts.remove,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "react",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
emoji,
remove: opts.remove,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "telegram") {
const result = await handleTelegramAction(
{
action: "react",
chatId: requireString(opts.to, "to"),
messageId,
emoji,
remove: opts.remove,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "whatsapp") {
const result = await handleWhatsAppAction(
{
action: "react",
chatJid: requireString(opts.to, "to"),
messageId,
emoji,
remove: opts.remove,
participant: optionalString(opts.participant),
accountId: optionalString(opts.account),
fromMe: opts.fromMe,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`React is not supported for provider ${provider}.`);
}
if (action === "reactions") {
const messageId = requireString(opts.messageId, "message-id");
const limit = parseIntOption(opts.limit, "limit");
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "reactions",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
limit,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "reactions",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
limit,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Reactions are not supported for provider ${provider}.`);
}
if (action === "read") {
const limit = parseIntOption(opts.limit, "limit");
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "readMessages",
channelId: requireString(opts.channelId ?? opts.to, "to"),
limit,
before: optionalString(opts.before),
after: optionalString(opts.after),
around: optionalString(opts.around),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "readMessages",
channelId: requireString(opts.channelId ?? opts.to, "to"),
limit,
before: optionalString(opts.before),
after: optionalString(opts.after),
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Read is not supported for provider ${provider}.`);
}
if (action === "edit") {
const messageId = requireString(opts.messageId, "message-id");
const message = requireString(opts.message, "message");
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "editMessage",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
content: message,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "editMessage",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
content: message,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Edit is not supported for provider ${provider}.`);
}
if (action === "delete") {
const messageId = requireString(opts.messageId, "message-id");
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "deleteMessage",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "deleteMessage",
channelId: requireString(opts.channelId ?? opts.to, "to"),
messageId,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Delete is not supported for provider ${provider}.`);
}
if (action === "pin" || action === "unpin" || action === "list-pins") {
const channelId = requireString(opts.channelId ?? opts.to, "to");
const messageId =
action === "list-pins"
? undefined
: requireString(opts.messageId, "message-id");
if (provider === "discord") {
const result = await handleDiscordAction(
{
action:
action === "pin"
? "pinMessage"
: action === "unpin"
? "unpinMessage"
: "listPins",
channelId,
messageId,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action:
action === "pin"
? "pinMessage"
: action === "unpin"
? "unpinMessage"
: "listPins",
channelId,
messageId,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Pins are not supported for provider ${provider}.`);
}
if (action === "permissions") {
if (provider !== "discord") {
throw new Error(
`Permissions are only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "permissions",
channelId: requireString(opts.channelId ?? opts.to, "to"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
runtime.log(JSON.stringify(extractToolPayload(handled), null, 2));
return;
}
if (action === "thread-create") {
if (provider !== "discord") {
throw new Error(
`Thread create is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "threadCreate",
channelId: requireString(opts.channelId ?? opts.to, "to"),
name: requireString(opts.threadName, "thread-name"),
messageId: optionalString(opts.messageId),
autoArchiveMinutes: parseIntOption(
opts.autoArchiveMin,
"auto-archive-min",
),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "thread-list") {
if (provider !== "discord") {
throw new Error(
`Thread list is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "threadList",
guildId: requireString(opts.guildId, "guild-id"),
channelId: optionalString(opts.channelId),
includeArchived: opts.includeArchived,
before: optionalString(opts.before),
limit: parseIntOption(opts.limit, "limit"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "thread-reply") {
if (provider !== "discord") {
throw new Error(
`Thread reply is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "threadReply",
channelId: requireString(opts.channelId ?? opts.to, "to"),
content: requireString(opts.message, "message"),
mediaUrl: optionalString(opts.media),
replyTo: optionalString(opts.replyTo),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "search") {
if (provider !== "discord") {
throw new Error(
`Search is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "searchMessages",
guildId: requireString(opts.guildId, "guild-id"),
content: requireString(opts.query, "query"),
channelId: optionalString(opts.channelId),
channelIds: toStringArray(opts.channelIds),
authorId: optionalString(opts.authorId),
authorIds: toStringArray(opts.authorIds),
limit: parseIntOption(opts.limit, "limit"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "sticker") {
if (provider !== "discord") {
throw new Error(
`Sticker send is only supported for Discord (provider=${provider}).`,
);
}
const stickerIds = toStringArray(opts.stickerId);
if (stickerIds.length === 0) {
throw new Error("sticker-id required");
}
const result = await handleDiscordAction(
{
action: "sticker",
to: requireString(opts.to, "to"),
stickerIds,
content: optionalString(opts.message),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "member-info") {
const userId = requireString(opts.userId, "user-id");
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "memberInfo",
guildId: requireString(opts.guildId, "guild-id"),
userId,
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{
action: "memberInfo",
userId,
accountId: optionalString(opts.account),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Member info is not supported for provider ${provider}.`);
}
if (action === "role-info") {
if (provider !== "discord") {
throw new Error(
`Role info is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{ action: "roleInfo", guildId: requireString(opts.guildId, "guild-id") },
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "emoji-list") {
if (provider === "discord") {
const result = await handleDiscordAction(
{
action: "emojiList",
guildId: requireString(opts.guildId, "guild-id"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (provider === "slack") {
const result = await handleSlackAction(
{ action: "emojiList", accountId: optionalString(opts.account) },
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Emoji list is not supported for provider ${provider}.`);
}
if (action === "emoji-upload") {
if (provider !== "discord") {
throw new Error(
`Emoji upload is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "emojiUpload",
guildId: requireString(opts.guildId, "guild-id"),
name: requireString(opts.emojiName, "emoji-name"),
mediaUrl: requireString(opts.media, "media"),
roleIds: toStringArray(opts.roleIds),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "sticker-upload") {
if (provider !== "discord") {
throw new Error(
`Sticker upload is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "stickerUpload",
guildId: requireString(opts.guildId, "guild-id"),
name: requireString(opts.stickerName, "sticker-name"),
description: requireString(opts.stickerDesc, "sticker-desc"),
tags: requireString(opts.stickerTags, "sticker-tags"),
mediaUrl: requireString(opts.media, "media"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "role-add" || action === "role-remove") {
if (provider !== "discord") {
throw new Error(
`Role changes are only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: action === "role-add" ? "roleAdd" : "roleRemove",
guildId: requireString(opts.guildId, "guild-id"),
userId: requireString(opts.userId, "user-id"),
roleId: requireString(opts.roleId, "role-id"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "channel-info") {
if (provider !== "discord") {
throw new Error(
`Channel info is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "channelInfo",
channelId: requireString(opts.channelId, "channel-id"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "channel-list") {
if (provider !== "discord") {
throw new Error(
`Channel list is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "channelList",
guildId: requireString(opts.guildId, "guild-id"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "voice-status") {
if (provider !== "discord") {
throw new Error(
`Voice status is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "voiceStatus",
guildId: requireString(opts.guildId, "guild-id"),
userId: requireString(opts.userId, "user-id"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "event-list") {
if (provider !== "discord") {
throw new Error(
`Event list is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{ action: "eventList", guildId: requireString(opts.guildId, "guild-id") },
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "event-create") {
if (provider !== "discord") {
throw new Error(
`Event create is only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: "eventCreate",
guildId: requireString(opts.guildId, "guild-id"),
name: requireString(opts.eventName, "event-name"),
startTime: requireString(opts.startTime, "start-time"),
endTime: optionalString(opts.endTime),
description: optionalString(opts.desc),
channelId: optionalString(opts.channelId),
location: optionalString(opts.location),
entityType: optionalString(opts.eventType),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
if (action === "timeout" || action === "kick" || action === "ban") {
if (provider !== "discord") {
throw new Error(
`Moderation actions are only supported for Discord (provider=${provider}).`,
);
}
const result = await handleDiscordAction(
{
action: action as "timeout" | "kick" | "ban",
guildId: requireString(opts.guildId, "guild-id"),
userId: requireString(opts.userId, "user-id"),
durationMinutes: parseIntOption(opts.durationMin, "duration-min"),
until: optionalString(opts.until),
reason: optionalString(opts.reason),
deleteMessageDays: parseIntOption(opts.deleteDays, "delete-days"),
},
cfg,
);
runtime.log(JSON.stringify(extractToolPayload(result), null, 2));
return;
}
throw new Error(`Unknown action: ${opts.action ?? "unknown"}`);
throw new Error(
`Action ${action} is not supported for provider ${provider}.`,
);
}

View File

@@ -19,6 +19,10 @@ import { pickPrimaryTailnetIPv4 } from "../infra/tailnet.js";
import { runCommandWithTimeout } from "../process/exec.js";
import type { RuntimeEnv } from "../runtime.js";
import { stylePromptTitle } from "../terminal/prompt-style.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { CONFIG_DIR, resolveUserPath } from "../utils.js";
import { VERSION } from "../version.js";
import type {
@@ -332,8 +336,8 @@ export async function probeGatewayReachable(params: {
password: params.password,
method: "health",
timeoutMs,
clientName: "clawdbot-probe",
mode: "probe",
clientName: GATEWAY_CLIENT_NAMES.PROBE,
mode: GATEWAY_CLIENT_MODES.PROBE,
});
return { ok: true };
} catch (err) {

View File

@@ -8,6 +8,10 @@ import { WebSocket } from "ws";
import { PROTOCOL_VERSION } from "../gateway/protocol/index.js";
import { rawDataToString } from "../infra/ws.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
async function getFreePort(): Promise<number> {
return await new Promise((resolve, reject) => {
@@ -66,10 +70,11 @@ async function connectReq(params: { url: string; token?: string }) {
minProtocol: PROTOCOL_VERSION,
maxProtocol: PROTOCOL_VERSION,
client: {
name: "vitest",
id: GATEWAY_CLIENT_NAMES.TEST,
displayName: "vitest",
version: "dev",
platform: process.platform,
mode: "test",
mode: GATEWAY_CLIENT_MODES.TEST,
},
caps: [],
auth: params.token ? { token: params.token } : undefined,

View File

@@ -8,6 +8,10 @@ import { WebSocket } from "ws";
import { PROTOCOL_VERSION } from "../gateway/protocol/index.js";
import { rawDataToString } from "../infra/ws.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
async function getFreePort(): Promise<number> {
return await new Promise((resolve, reject) => {
@@ -91,10 +95,11 @@ async function connectReq(params: { url: string; token?: string }) {
minProtocol: PROTOCOL_VERSION,
maxProtocol: PROTOCOL_VERSION,
client: {
name: "vitest",
id: GATEWAY_CLIENT_NAMES.TEST,
displayName: "vitest",
version: "dev",
platform: process.platform,
mode: "test",
mode: GATEWAY_CLIENT_MODES.TEST,
},
caps: [],
auth: params.token ? { token: params.token } : undefined,

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
import { listProviderPlugins } from "../../providers/plugins/index.js";
import type { ProviderChoice } from "../onboard-types.js";
import type { ProviderOnboardingAdapter } from "./types.js";
const PROVIDER_ONBOARDING_ADAPTERS = () =>
new Map<ProviderChoice, ProviderOnboardingAdapter>(
listProviderPlugins()
.map((plugin) =>
plugin.onboarding
? ([plugin.id as ProviderChoice, plugin.onboarding] as const)
: null,
)
.filter(
(
entry,
): entry is readonly [ProviderChoice, ProviderOnboardingAdapter] =>
Boolean(entry),
),
);
export function getProviderOnboardingAdapter(
provider: ProviderChoice,
): ProviderOnboardingAdapter | undefined {
return PROVIDER_ONBOARDING_ADAPTERS().get(provider);
}
export function listProviderOnboardingAdapters(): ProviderOnboardingAdapter[] {
return Array.from(PROVIDER_ONBOARDING_ADAPTERS().values());
}

View File

@@ -0,0 +1 @@
export * from "../../providers/plugins/onboarding-types.js";

View File

@@ -309,8 +309,10 @@ describe("providers command", () => {
it("formats gateway provider status lines in registry order", () => {
const lines = formatGatewayProvidersStatusLines({
telegramAccounts: [{ accountId: "default", configured: true }],
whatsappAccounts: [{ accountId: "default", linked: true }],
providerAccounts: {
telegram: [{ accountId: "default", configured: true }],
whatsapp: [{ accountId: "default", linked: true }],
},
});
const telegramIndex = lines.findIndex((line) =>
@@ -326,14 +328,16 @@ describe("providers command", () => {
it("surfaces Discord privileged intent issues in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({
discordAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
application: { intents: { messageContent: "disabled" } },
},
],
providerAccounts: {
discord: [
{
accountId: "default",
enabled: true,
configured: true,
application: { intents: { messageContent: "disabled" } },
},
],
},
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/Message Content Intent is disabled/i);
@@ -342,23 +346,25 @@ describe("providers command", () => {
it("surfaces Discord permission audit issues in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({
discordAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
audit: {
unresolvedChannels: 1,
channels: [
{
channelId: "111",
ok: false,
missing: ["ViewChannel", "SendMessages"],
},
],
providerAccounts: {
discord: [
{
accountId: "default",
enabled: true,
configured: true,
audit: {
unresolvedChannels: 1,
channels: [
{
channelId: "111",
ok: false,
missing: ["ViewChannel", "SendMessages"],
},
],
},
},
},
],
],
},
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/permission audit/i);
@@ -367,14 +373,16 @@ describe("providers command", () => {
it("surfaces Telegram privacy-mode hints when allowUnmentionedGroups is enabled", () => {
const lines = formatGatewayProvidersStatusLines({
telegramAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
allowUnmentionedGroups: true,
},
],
providerAccounts: {
telegram: [
{
accountId: "default",
enabled: true,
configured: true,
allowUnmentionedGroups: true,
},
],
},
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/Telegram Bot API privacy mode/i);
@@ -382,25 +390,27 @@ describe("providers command", () => {
it("surfaces Telegram group membership audit issues in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({
telegramAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
audit: {
hasWildcardUnmentionedGroups: true,
unresolvedGroups: 1,
groups: [
{
chatId: "-1001",
ok: false,
status: "left",
error: "not in group",
},
],
providerAccounts: {
telegram: [
{
accountId: "default",
enabled: true,
configured: true,
audit: {
hasWildcardUnmentionedGroups: true,
unresolvedGroups: 1,
groups: [
{
chatId: "-1001",
ok: false,
status: "left",
error: "not in group",
},
],
},
},
},
],
],
},
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/membership probing is not possible/i);
@@ -409,40 +419,44 @@ describe("providers command", () => {
it("surfaces WhatsApp auth/runtime hints when unlinked or disconnected", () => {
const unlinked = formatGatewayProvidersStatusLines({
whatsappAccounts: [
{ accountId: "default", enabled: true, linked: false },
],
providerAccounts: {
whatsapp: [{ accountId: "default", enabled: true, linked: false }],
},
});
expect(unlinked.join("\n")).toMatch(/WhatsApp/i);
expect(unlinked.join("\n")).toMatch(/Not linked/i);
const disconnected = formatGatewayProvidersStatusLines({
whatsappAccounts: [
{
accountId: "default",
enabled: true,
linked: true,
running: true,
connected: false,
reconnectAttempts: 5,
lastError: "connection closed",
},
],
providerAccounts: {
whatsapp: [
{
accountId: "default",
enabled: true,
linked: true,
running: true,
connected: false,
reconnectAttempts: 5,
lastError: "connection closed",
},
],
},
});
expect(disconnected.join("\n")).toMatch(/disconnected/i);
});
it("surfaces Signal runtime errors in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({
signalAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "signal-cli unreachable",
},
],
providerAccounts: {
signal: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "signal-cli unreachable",
},
],
},
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/signal/i);
@@ -451,15 +465,17 @@ describe("providers command", () => {
it("surfaces iMessage runtime errors in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({
imessageAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "imsg permission denied",
},
],
providerAccounts: {
imessage: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "imsg permission denied",
},
],
},
});
expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/imessage/i);

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));
}
}

View File

@@ -11,6 +11,7 @@ import {
resolveMainSessionKey,
resolveStorePath,
} from "../config/sessions.js";
import { normalizeProviderId } from "../providers/registry.js";
import {
buildAgentMainSessionKey,
normalizeAgentId,
@@ -21,6 +22,7 @@ import {
import type { RuntimeEnv } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { colorize, isRich, theme } from "../terminal/theme.js";
import { INTERNAL_MESSAGE_PROVIDER } from "../utils/message-provider.js";
type SandboxExplainOptions = {
session?: string;
@@ -30,16 +32,6 @@ type SandboxExplainOptions = {
const SANDBOX_DOCS_URL = "https://docs.clawd.bot/sandbox";
const KNOWN_PROVIDER_KEYS = new Set([
"whatsapp",
"telegram",
"discord",
"slack",
"signal",
"imessage",
"webchat",
]);
function normalizeExplainSessionKey(params: {
cfg: ClawdbotConfig;
agentId: string;
@@ -73,9 +65,9 @@ function inferProviderFromSessionKey(params: {
const configuredMainKey = normalizeMainKey(params.cfg.session?.mainKey);
if (parts[0] === configuredMainKey) return undefined;
const candidate = parts[0]?.trim().toLowerCase();
return candidate && KNOWN_PROVIDER_KEYS.has(candidate)
? candidate
: undefined;
if (!candidate) return undefined;
if (candidate === INTERNAL_MESSAGE_PROVIDER) return INTERNAL_MESSAGE_PROVIDER;
return normalizeProviderId(candidate) ?? undefined;
}
function resolveActiveProvider(params: {
@@ -96,43 +88,15 @@ function resolveActiveProvider(params: {
)
.trim()
.toLowerCase();
if (candidate && KNOWN_PROVIDER_KEYS.has(candidate)) return candidate;
if (candidate === INTERNAL_MESSAGE_PROVIDER) return INTERNAL_MESSAGE_PROVIDER;
const normalized = normalizeProviderId(candidate);
if (normalized) return normalized;
return inferProviderFromSessionKey({
cfg: params.cfg,
sessionKey: params.sessionKey,
});
}
function resolveElevatedAllowListForProvider(params: {
provider: string;
allowFrom?: Record<string, Array<string | number> | undefined>;
discordFallback?: Array<string | number>;
}): Array<string | number> | undefined {
switch (params.provider) {
case "whatsapp":
return params.allowFrom?.whatsapp;
case "telegram":
return params.allowFrom?.telegram;
case "discord": {
const hasExplicit = Boolean(
params.allowFrom && Object.hasOwn(params.allowFrom, "discord"),
);
if (hasExplicit) return params.allowFrom?.discord;
return params.discordFallback;
}
case "slack":
return params.allowFrom?.slack;
case "signal":
return params.allowFrom?.signal;
case "imessage":
return params.allowFrom?.imessage;
case "webchat":
return params.allowFrom?.webchat;
default:
return undefined;
}
}
export async function sandboxExplainCommand(
opts: SandboxExplainOptions,
runtime: RuntimeEnv,
@@ -182,26 +146,11 @@ export async function sandboxExplainCommand(
const elevatedAgentEnabled = elevatedAgent?.enabled !== false;
const elevatedEnabled = elevatedGlobalEnabled && elevatedAgentEnabled;
const discordFallback =
provider === "discord" ? cfg.discord?.dm?.allowFrom : undefined;
const globalAllow = provider
? resolveElevatedAllowListForProvider({
provider,
allowFrom: elevatedGlobal?.allowFrom as unknown as Record<
string,
Array<string | number> | undefined
>,
discordFallback,
})
? elevatedGlobal?.allowFrom?.[provider]
: undefined;
const agentAllow = provider
? resolveElevatedAllowListForProvider({
provider,
allowFrom: elevatedAgent?.allowFrom as unknown as Record<
string,
Array<string | number> | undefined
>,
})
? elevatedAgent?.allowFrom?.[provider]
: undefined;
const allowTokens = (values?: Array<string | number>) =>
@@ -233,10 +182,7 @@ export async function sandboxExplainCommand(
if (provider && globalAllowTokens.length === 0) {
elevatedFailures.push({
gate: "allowFrom",
key:
provider === "discord" && discordFallback
? "tools.elevated.allowFrom.discord (or discord.dm.allowFrom fallback)"
: `tools.elevated.allowFrom.${provider}`,
key: `tools.elevated.allowFrom.${provider}`,
});
}
if (provider && elevatedAgent?.allowFrom && agentAllowTokens.length === 0) {

View File

@@ -425,6 +425,7 @@ export async function statusAllCommand(
});
const providerRows = providers.rows.map((row) => ({
providerId: row.id,
Provider: row.provider,
Enabled: row.enabled ? ok("ON") : muted("OFF"),
State:
@@ -447,27 +448,8 @@ export async function statusAllCommand(
}
return map;
})();
const providerKeyForLabel = (label: string) => {
switch (label) {
case "WhatsApp":
return "whatsapp";
case "Telegram":
return "telegram";
case "Discord":
return "discord";
case "Slack":
return "slack";
case "Signal":
return "signal";
case "iMessage":
return "imessage";
default:
return label.toLowerCase();
}
};
const providerRowsWithIssues = providerRows.map((row) => {
const providerKey = providerKeyForLabel(row.Provider);
const issues = providerIssuesByProvider.get(providerKey) ?? [];
const issues = providerIssuesByProvider.get(row.providerId) ?? [];
if (issues.length === 0) return row;
const issue = issues[0];
const suffix = ` · ${warn(`gateway: ${String(issue.message).slice(0, 90)}`)}`;

View File

@@ -1,46 +1,35 @@
import crypto from "node:crypto";
import fs from "node:fs";
import type { ClawdbotConfig } from "../../config/config.js";
import {
listDiscordAccountIds,
resolveDiscordAccount,
} from "../../discord/accounts.js";
import {
listIMessageAccountIds,
resolveIMessageAccount,
} from "../../imessage/accounts.js";
import { resolveMSTeamsCredentials } from "../../msteams/token.js";
import {
listSignalAccountIds,
resolveSignalAccount,
} from "../../signal/accounts.js";
import {
listSlackAccountIds,
resolveSlackAccount,
} from "../../slack/accounts.js";
import {
listTelegramAccountIds,
resolveTelegramAccount,
} from "../../telegram/accounts.js";
import { normalizeE164 } from "../../utils.js";
import {
listWhatsAppAccountIds,
resolveWhatsAppAccount,
} from "../../web/accounts.js";
import {
getWebAuthAgeMs,
readWebSelfId,
webAuthExists,
} from "../../web/session.js";
import { resolveProviderDefaultAccountId } from "../../providers/plugins/helpers.js";
import { listProviderPlugins } from "../../providers/plugins/index.js";
import type {
ProviderAccountSnapshot,
ProviderId,
ProviderPlugin,
} from "../../providers/plugins/types.js";
import { formatAge } from "./format.js";
export type ProviderRow = {
id: ProviderId;
provider: string;
enabled: boolean;
state: "ok" | "setup" | "warn" | "off";
detail: string;
};
type ProviderAccountRow = {
accountId: string;
account: unknown;
enabled: boolean;
configured: boolean;
snapshot: ProviderAccountSnapshot;
};
const asRecord = (value: unknown): Record<string, unknown> =>
value && typeof value === "object" ? (value as Record<string, unknown>) : {};
function summarizeSources(sources: Array<string | undefined>): {
label: string;
parts: string[];
@@ -85,6 +74,242 @@ function formatTokenHint(
return `${head}${tail} · len ${t.length}`;
}
const formatAccountLabel = (params: { accountId: string; name?: string }) => {
const base = params.accountId || "default";
if (params.name?.trim()) return `${base} (${params.name.trim()})`;
return base;
};
const resolveAccountEnabled = (
plugin: ProviderPlugin,
account: unknown,
cfg: ClawdbotConfig,
): boolean => {
if (plugin.config.isEnabled) return plugin.config.isEnabled(account, cfg);
const enabled = asRecord(account).enabled;
return enabled !== false;
};
const resolveAccountConfigured = async (
plugin: ProviderPlugin,
account: unknown,
cfg: ClawdbotConfig,
): Promise<boolean> => {
if (plugin.config.isConfigured) {
return await plugin.config.isConfigured(account, cfg);
}
const configured = asRecord(account).configured;
return configured !== false;
};
const buildAccountSnapshot = (params: {
plugin: ProviderPlugin;
account: unknown;
cfg: ClawdbotConfig;
accountId: string;
enabled: boolean;
configured: boolean;
}): ProviderAccountSnapshot => {
const described = params.plugin.config.describeAccount?.(
params.account,
params.cfg,
);
return {
enabled: params.enabled,
configured: params.configured,
...described,
accountId: params.accountId,
};
};
const formatAllowFrom = (params: {
plugin: ProviderPlugin;
cfg: ClawdbotConfig;
accountId?: string | null;
allowFrom: Array<string | number>;
}) => {
if (params.plugin.config.formatAllowFrom) {
return params.plugin.config.formatAllowFrom({
cfg: params.cfg,
accountId: params.accountId,
allowFrom: params.allowFrom,
});
}
return params.allowFrom.map((entry) => String(entry).trim()).filter(Boolean);
};
const buildAccountNotes = (params: {
plugin: ProviderPlugin;
cfg: ClawdbotConfig;
entry: ProviderAccountRow;
}) => {
const { plugin, cfg, entry } = params;
const notes: string[] = [];
const snapshot = entry.snapshot;
if (snapshot.enabled === false) notes.push("disabled");
if (snapshot.dmPolicy) notes.push(`dm:${snapshot.dmPolicy}`);
if (snapshot.tokenSource && snapshot.tokenSource !== "none") {
notes.push(`token:${snapshot.tokenSource}`);
}
if (snapshot.botTokenSource && snapshot.botTokenSource !== "none") {
notes.push(`bot:${snapshot.botTokenSource}`);
}
if (snapshot.appTokenSource && snapshot.appTokenSource !== "none") {
notes.push(`app:${snapshot.appTokenSource}`);
}
if (snapshot.baseUrl) notes.push(snapshot.baseUrl);
if (snapshot.port != null) notes.push(`port:${snapshot.port}`);
if (snapshot.cliPath) notes.push(`cli:${snapshot.cliPath}`);
if (snapshot.dbPath) notes.push(`db:${snapshot.dbPath}`);
const allowFrom =
plugin.config.resolveAllowFrom?.({ cfg, accountId: snapshot.accountId }) ??
snapshot.allowFrom;
if (allowFrom?.length) {
const formatted = formatAllowFrom({
plugin,
cfg,
accountId: snapshot.accountId,
allowFrom,
}).slice(0, 3);
if (formatted.length > 0) notes.push(`allow:${formatted.join(",")}`);
}
return notes;
};
function resolveLinkFields(summary: unknown): {
linked: boolean | null;
authAgeMs: number | null;
selfE164: string | null;
} {
const rec = asRecord(summary);
const linked = typeof rec.linked === "boolean" ? rec.linked : null;
const authAgeMs = typeof rec.authAgeMs === "number" ? rec.authAgeMs : null;
const self = asRecord(rec.self);
const selfE164 =
typeof self.e164 === "string" && self.e164.trim() ? self.e164.trim() : null;
return { linked, authAgeMs, selfE164 };
}
function collectMissingPaths(accounts: ProviderAccountRow[]): string[] {
const missing: string[] = [];
for (const entry of accounts) {
const accountRec = asRecord(entry.account);
const snapshotRec = asRecord(entry.snapshot);
for (const key of [
"tokenFile",
"botTokenFile",
"appTokenFile",
"cliPath",
"dbPath",
"authDir",
]) {
const raw =
(accountRec[key] as string | undefined) ??
(snapshotRec[key] as string | undefined);
const ok = existsSyncMaybe(raw);
if (ok === false) missing.push(String(raw));
}
}
return missing;
}
function summarizeTokenConfig(params: {
plugin: ProviderPlugin;
cfg: ClawdbotConfig;
accounts: ProviderAccountRow[];
showSecrets: boolean;
}): { state: "ok" | "setup" | "warn" | null; detail: string | null } {
const enabled = params.accounts.filter((a) => a.enabled);
if (enabled.length === 0) return { state: null, detail: null };
const accountRecs = enabled.map((a) => asRecord(a.account));
const hasBotOrAppTokenFields = accountRecs.some(
(r) => "botToken" in r || "appToken" in r,
);
const hasTokenField = accountRecs.some((r) => "token" in r);
if (!hasBotOrAppTokenFields && !hasTokenField) {
return { state: null, detail: null };
}
if (hasBotOrAppTokenFields) {
const ready = enabled.filter((a) => {
const rec = asRecord(a.account);
const bot = typeof rec.botToken === "string" ? rec.botToken.trim() : "";
const app = typeof rec.appToken === "string" ? rec.appToken.trim() : "";
return Boolean(bot) && Boolean(app);
});
const partial = enabled.filter((a) => {
const rec = asRecord(a.account);
const bot = typeof rec.botToken === "string" ? rec.botToken.trim() : "";
const app = typeof rec.appToken === "string" ? rec.appToken.trim() : "";
const hasBot = Boolean(bot);
const hasApp = Boolean(app);
return (hasBot && !hasApp) || (!hasBot && hasApp);
});
if (partial.length > 0) {
return {
state: "warn",
detail: `partial tokens (need bot+app) · accounts ${partial.length}`,
};
}
if (ready.length === 0) {
return { state: "setup", detail: "no tokens (need bot+app)" };
}
const botSources = summarizeSources(
ready.map((a) => a.snapshot.botTokenSource ?? "none"),
);
const appSources = summarizeSources(
ready.map((a) => a.snapshot.appTokenSource ?? "none"),
);
const sample = ready[0]?.account ? asRecord(ready[0].account) : {};
const botToken = typeof sample.botToken === "string" ? sample.botToken : "";
const appToken = typeof sample.appToken === "string" ? sample.appToken : "";
const botHint = botToken.trim()
? formatTokenHint(botToken, { showSecrets: params.showSecrets })
: "";
const appHint = appToken.trim()
? formatTokenHint(appToken, { showSecrets: params.showSecrets })
: "";
const hint =
botHint || appHint
? ` (bot ${botHint || "?"}, app ${appHint || "?"})`
: "";
return {
state: "ok",
detail: `tokens ok (bot ${botSources.label}, app ${appSources.label})${hint} · accounts ${ready.length}/${enabled.length || 1}`,
};
}
const ready = enabled.filter((a) => {
const rec = asRecord(a.account);
return typeof rec.token === "string" ? Boolean(rec.token.trim()) : false;
});
if (ready.length === 0) {
return { state: "setup", detail: "no token" };
}
const sources = summarizeSources(ready.map((a) => a.snapshot.tokenSource));
const sample = ready[0]?.account ? asRecord(ready[0].account) : {};
const token = typeof sample.token === "string" ? sample.token : "";
const hint = token.trim()
? ` (${formatTokenHint(token, { showSecrets: params.showSecrets })})`
: "";
return {
state: "ok",
detail: `token ${sources.label}${hint} · accounts ${ready.length}/${enabled.length || 1}`,
};
}
// `status --all` providers table.
// Keep this generic: provider-specific rules belong in the provider plugin.
export async function buildProvidersTable(
cfg: ClawdbotConfig,
opts?: { showSecrets?: boolean },
@@ -104,266 +329,141 @@ export async function buildProvidersTable(
rows: Array<Record<string, string>>;
}> = [];
// WhatsApp
const waEnabled = cfg.web?.enabled !== false;
const waLinked = waEnabled ? await webAuthExists().catch(() => false) : false;
const waAuthAgeMs = waLinked ? getWebAuthAgeMs() : null;
const waSelf = waLinked ? readWebSelfId().e164 : undefined;
const waAccounts = waLinked
? listWhatsAppAccountIds(cfg).map((accountId) =>
resolveWhatsAppAccount({ cfg, accountId }),
)
: [];
rows.push({
provider: "WhatsApp",
enabled: waEnabled,
state: !waEnabled ? "off" : waLinked ? "ok" : "setup",
detail: waEnabled
? waLinked
? `linked${waSelf ? ` ${waSelf}` : ""}${waAuthAgeMs ? ` · auth ${formatAge(waAuthAgeMs)}` : ""} · accounts ${waAccounts.length || 1}`
: "not linked (run clawdbot login)"
: "disabled",
});
if (waLinked) {
const waRows =
waAccounts.length > 0 ? waAccounts : [resolveWhatsAppAccount({ cfg })];
details.push({
title: "WhatsApp accounts",
columns: ["Account", "Status", "Notes"],
rows: waRows.map((account) => {
const allowFrom = (account.allowFrom ?? cfg.whatsapp?.allowFrom ?? [])
.map(normalizeE164)
.filter(Boolean)
.slice(0, 3);
const dmPolicy =
account.dmPolicy ?? cfg.whatsapp?.dmPolicy ?? "pairing";
const notes: string[] = [];
if (!account.enabled) notes.push("disabled");
if (account.selfChatMode) notes.push("self-chat");
notes.push(`dm:${dmPolicy}`);
if (allowFrom.length) notes.push(`allow:${allowFrom.join(",")}`);
return {
Account: account.name?.trim()
? `${account.accountId} (${account.name.trim()})`
: account.accountId,
Status: account.enabled ? "OK" : "OFF",
Notes: notes.join(" · "),
};
}),
for (const plugin of listProviderPlugins()) {
const accountIds = plugin.config.listAccountIds(cfg);
const defaultAccountId = resolveProviderDefaultAccountId({
plugin,
cfg,
accountIds,
});
}
const resolvedAccountIds =
accountIds.length > 0 ? accountIds : [defaultAccountId];
// Telegram
const tgEnabled = cfg.telegram?.enabled !== false;
const tgAccounts = listTelegramAccountIds(cfg).map((accountId) =>
resolveTelegramAccount({ cfg, accountId }),
);
const tgEnabledAccounts = tgAccounts.filter((a) => a.enabled);
const tgTokenAccounts = tgEnabledAccounts.filter((a) => a.token?.trim());
const tgSources = summarizeSources(tgTokenAccounts.map((a) => a.tokenSource));
const tgSampleToken = tgTokenAccounts[0]?.token?.trim() || "";
const tgTokenHint = tgSampleToken
? formatTokenHint(tgSampleToken, { showSecrets })
: "";
const tgMissingFiles: string[] = [];
const tgGlobalTokenFileExists = existsSyncMaybe(cfg.telegram?.tokenFile);
if (
tgEnabled &&
cfg.telegram?.tokenFile?.trim() &&
tgGlobalTokenFileExists === false
) {
tgMissingFiles.push("telegram.tokenFile");
}
for (const accountId of listTelegramAccountIds(cfg)) {
const tokenFile =
cfg.telegram?.accounts?.[accountId]?.tokenFile?.trim() || "";
const ok = existsSyncMaybe(tokenFile);
if (tgEnabled && tokenFile && ok === false) {
tgMissingFiles.push(`telegram.accounts.${accountId}.tokenFile`);
const accounts: ProviderAccountRow[] = [];
for (const accountId of resolvedAccountIds) {
const account = plugin.config.resolveAccount(cfg, accountId);
const enabled = resolveAccountEnabled(plugin, account, cfg);
const configured = await resolveAccountConfigured(plugin, account, cfg);
const snapshot = buildAccountSnapshot({
plugin,
cfg,
accountId,
account,
enabled,
configured,
});
accounts.push({ accountId, account, enabled, configured, snapshot });
}
const anyEnabled = accounts.some((a) => a.enabled);
const enabledAccounts = accounts.filter((a) => a.enabled);
const configuredAccounts = enabledAccounts.filter((a) => a.configured);
const defaultEntry =
accounts.find((a) => a.accountId === defaultAccountId) ?? accounts[0];
const summary = plugin.status?.buildProviderSummary
? await plugin.status.buildProviderSummary({
account: defaultEntry?.account ?? {},
cfg,
defaultAccountId,
snapshot:
defaultEntry?.snapshot ??
({ accountId: defaultAccountId } as ProviderAccountSnapshot),
})
: undefined;
const link = resolveLinkFields(summary);
const missingPaths = collectMissingPaths(enabledAccounts);
const tokenSummary = summarizeTokenConfig({
plugin,
cfg,
accounts,
showSecrets,
});
const issues = plugin.status?.collectStatusIssues
? plugin.status.collectStatusIssues(accounts.map((a) => a.snapshot))
: [];
const label = plugin.meta.label ?? plugin.id;
const state = (() => {
if (!anyEnabled) return "off";
if (missingPaths.length > 0) return "warn";
if (issues.length > 0) return "warn";
if (link.linked === false) return "setup";
if (tokenSummary.state) return tokenSummary.state;
if (link.linked === true) return "ok";
if (configuredAccounts.length > 0) return "ok";
return "setup";
})();
const detail = (() => {
if (!anyEnabled) {
if (!defaultEntry) return "disabled";
return (
plugin.config.disabledReason?.(defaultEntry.account, cfg) ??
"disabled"
);
}
if (missingPaths.length > 0) return `missing file (${missingPaths[0]})`;
if (issues.length > 0) return issues[0]?.message ?? "misconfigured";
if (link.linked !== null) {
const base = link.linked ? "linked" : "not linked";
const extra: string[] = [];
if (link.linked && link.selfE164) extra.push(link.selfE164);
if (link.linked && link.authAgeMs != null && link.authAgeMs >= 0) {
extra.push(`auth ${formatAge(link.authAgeMs)}`);
}
if (accounts.length > 1 || plugin.meta.forceAccountBinding) {
extra.push(`accounts ${accounts.length || 1}`);
}
return extra.length > 0 ? `${base} · ${extra.join(" · ")}` : base;
}
if (tokenSummary.detail) return tokenSummary.detail;
if (configuredAccounts.length > 0) {
const head = "configured";
if (accounts.length <= 1 && !plugin.meta.forceAccountBinding)
return head;
return `${head} · accounts ${configuredAccounts.length}/${enabledAccounts.length || 1}`;
}
const reason =
defaultEntry && plugin.config.unconfiguredReason
? plugin.config.unconfiguredReason(defaultEntry.account, cfg)
: null;
return reason ?? "not configured";
})();
rows.push({
id: plugin.id,
provider: label,
enabled: anyEnabled,
state,
detail,
});
if (configuredAccounts.length > 0) {
details.push({
title: `${label} accounts`,
columns: ["Account", "Status", "Notes"],
rows: configuredAccounts.map((entry) => {
const notes = buildAccountNotes({ plugin, cfg, entry });
return {
Account: formatAccountLabel({
accountId: entry.accountId,
name: entry.snapshot.name,
}),
Status: entry.enabled !== false ? "OK" : "WARN",
Notes: notes.join(" · "),
};
}),
});
}
}
const tgMisconfigured = tgMissingFiles.length > 0;
rows.push({
provider: "Telegram",
enabled: tgEnabled,
state: !tgEnabled
? "off"
: tgMisconfigured
? "warn"
: tgTokenAccounts.length > 0
? "ok"
: "setup",
detail: tgEnabled
? tgMisconfigured
? `token file missing (${tgMissingFiles[0]})`
: tgTokenAccounts.length > 0
? `bot token ${tgSources.label}${tgTokenHint ? ` (${tgTokenHint})` : ""} · accounts ${tgTokenAccounts.length}/${tgEnabledAccounts.length || 1}`
: "no bot token (TELEGRAM_BOT_TOKEN / telegram.botToken)"
: "disabled",
});
// Discord
const dcEnabled = cfg.discord?.enabled !== false;
const dcAccounts = listDiscordAccountIds(cfg).map((accountId) =>
resolveDiscordAccount({ cfg, accountId }),
);
const dcEnabledAccounts = dcAccounts.filter((a) => a.enabled);
const dcTokenAccounts = dcEnabledAccounts.filter((a) => a.token?.trim());
const dcSources = summarizeSources(dcTokenAccounts.map((a) => a.tokenSource));
const dcSampleToken = dcTokenAccounts[0]?.token?.trim() || "";
const dcTokenHint = dcSampleToken
? formatTokenHint(dcSampleToken, { showSecrets })
: "";
rows.push({
provider: "Discord",
enabled: dcEnabled,
state: !dcEnabled ? "off" : dcTokenAccounts.length > 0 ? "ok" : "setup",
detail: dcEnabled
? dcTokenAccounts.length > 0
? `bot token ${dcSources.label}${dcTokenHint ? ` (${dcTokenHint})` : ""} · accounts ${dcTokenAccounts.length}/${dcEnabledAccounts.length || 1}`
: "no bot token (DISCORD_BOT_TOKEN / discord.token)"
: "disabled",
});
// Slack
const slEnabled = cfg.slack?.enabled !== false;
const slAccounts = listSlackAccountIds(cfg).map((accountId) =>
resolveSlackAccount({ cfg, accountId }),
);
const slEnabledAccounts = slAccounts.filter((a) => a.enabled);
const slReady = slEnabledAccounts.filter(
(a) => Boolean(a.botToken?.trim()) && Boolean(a.appToken?.trim()),
);
const slPartial = slEnabledAccounts.filter(
(a) =>
(a.botToken?.trim() && !a.appToken?.trim()) ||
(!a.botToken?.trim() && a.appToken?.trim()),
);
const slHasAnyToken = slEnabledAccounts.some(
(a) => Boolean(a.botToken?.trim()) || Boolean(a.appToken?.trim()),
);
const slBotSources = summarizeSources(
slReady.map((a) => a.botTokenSource ?? "none"),
);
const slAppSources = summarizeSources(
slReady.map((a) => a.appTokenSource ?? "none"),
);
const slSample = slReady[0] ?? null;
const slBotHint =
slSample?.botToken?.trim() && slSample.botTokenSource !== "none"
? formatTokenHint(slSample.botToken, { showSecrets })
: "";
const slAppHint =
slSample?.appToken?.trim() && slSample.appTokenSource !== "none"
? formatTokenHint(slSample.appToken, { showSecrets })
: "";
rows.push({
provider: "Slack",
enabled: slEnabled,
state: !slEnabled
? "off"
: slPartial.length > 0
? "warn"
: slReady.length > 0
? "ok"
: "setup",
detail: slEnabled
? slPartial.length > 0
? `partial tokens (need bot+app) · accounts ${slPartial.length}`
: slReady.length > 0
? `tokens ok (bot ${slBotSources.label}${slBotHint ? ` ${slBotHint}` : ""}, app ${slAppSources.label}${slAppHint ? ` ${slAppHint}` : ""}) · accounts ${slReady.length}/${slEnabledAccounts.length || 1}`
: slHasAnyToken
? "tokens incomplete (need bot+app)"
: "no tokens (SLACK_BOT_TOKEN + SLACK_APP_TOKEN)"
: "disabled",
});
// Signal
const siEnabled = cfg.signal?.enabled !== false;
const siAccounts = listSignalAccountIds(cfg).map((accountId) =>
resolveSignalAccount({ cfg, accountId }),
);
const siEnabledAccounts = siAccounts.filter((a) => a.enabled);
const siConfiguredAccounts = siEnabledAccounts.filter((a) => a.configured);
const siSample = siConfiguredAccounts[0] ?? siEnabledAccounts[0] ?? null;
const siBaseUrl = siSample?.baseUrl?.trim() ? siSample.baseUrl.trim() : "";
rows.push({
provider: "Signal",
enabled: siEnabled,
state: !siEnabled
? "off"
: siConfiguredAccounts.length > 0
? "ok"
: "setup",
detail: siEnabled
? siConfiguredAccounts.length > 0
? `configured${siBaseUrl ? ` · baseUrl ${siBaseUrl}` : ""} · accounts ${siConfiguredAccounts.length}/${siEnabledAccounts.length || 1}`
: "default config (no overrides)"
: "disabled",
});
// iMessage
const imEnabled = cfg.imessage?.enabled !== false;
const imAccounts = listIMessageAccountIds(cfg).map((accountId) =>
resolveIMessageAccount({ cfg, accountId }),
);
const imEnabledAccounts = imAccounts.filter((a) => a.enabled);
const imConfiguredAccounts = imEnabledAccounts.filter((a) => a.configured);
const imSample = imEnabledAccounts[0] ?? null;
const imCliPath = imSample?.config?.cliPath?.trim() || "";
const imDbPath = imSample?.config?.dbPath?.trim() || "";
rows.push({
provider: "iMessage",
enabled: imEnabled,
state: !imEnabled
? "off"
: imConfiguredAccounts.length > 0
? "ok"
: "setup",
detail: imEnabled
? imConfiguredAccounts.length > 0
? `configured${imCliPath ? ` · cliPath ${imCliPath}` : ""}${imDbPath ? ` · dbPath ${imDbPath}` : ""} · accounts ${imConfiguredAccounts.length}/${imEnabledAccounts.length || 1}`
: "default config (no overrides)"
: "disabled",
});
// MS Teams
const msEnabled = cfg.msteams?.enabled !== false;
const msCreds = resolveMSTeamsCredentials(cfg.msteams);
const msAppId =
cfg.msteams?.appId?.trim() || process.env.MSTEAMS_APP_ID?.trim();
const msAppPassword =
cfg.msteams?.appPassword?.trim() ||
process.env.MSTEAMS_APP_PASSWORD?.trim();
const msTenantId =
cfg.msteams?.tenantId?.trim() || process.env.MSTEAMS_TENANT_ID?.trim();
const msMissing = [
!msAppId ? "appId" : null,
!msAppPassword ? "appPassword" : null,
!msTenantId ? "tenantId" : null,
].filter(Boolean) as string[];
const msAnyPresent = Boolean(msAppId || msAppPassword || msTenantId);
const msPasswordHint = msAppPassword
? formatTokenHint(msAppPassword, { showSecrets })
: "";
rows.push({
provider: "MS Teams",
enabled: msEnabled,
state: !msEnabled
? "off"
: msCreds
? "ok"
: msAnyPresent
? "warn"
: "setup",
detail: msEnabled
? msCreds
? `credentials set${msPasswordHint ? ` (password ${msPasswordHint})` : ""}`
: msAnyPresent
? `credentials incomplete (missing ${msMissing.join(", ")})`
: "no credentials (MSTEAMS_APP_ID / _PASSWORD / _TENANT_ID)"
: "disabled",
});
return {
rows,

View File

@@ -39,6 +39,88 @@ vi.mock("../config/sessions.js", () => ({
resolveMainSessionKey: mocks.resolveMainSessionKey,
resolveStorePath: mocks.resolveStorePath,
}));
vi.mock("../providers/plugins/index.js", () => ({
listProviderPlugins: () =>
[
{
id: "whatsapp",
meta: {
id: "whatsapp",
label: "WhatsApp",
selectionLabel: "WhatsApp",
docsPath: "/platforms/whatsapp",
blurb: "mock",
},
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
status: {
buildProviderSummary: async () => ({ linked: true, authAgeMs: 5000 }),
},
},
{
id: "signal",
meta: {
id: "signal",
label: "Signal",
selectionLabel: "Signal",
docsPath: "/platforms/signal",
blurb: "mock",
},
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
status: {
collectStatusIssues: (accounts: Array<Record<string, unknown>>) =>
accounts
.filter(
(account) =>
typeof account.lastError === "string" && account.lastError,
)
.map((account) => ({
provider: "signal",
accountId:
typeof account.accountId === "string"
? account.accountId
: "default",
message: `Provider error: ${String(account.lastError)}`,
})),
},
},
{
id: "imessage",
meta: {
id: "imessage",
label: "iMessage",
selectionLabel: "iMessage",
docsPath: "/platforms/mac",
blurb: "mock",
},
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
status: {
collectStatusIssues: (accounts: Array<Record<string, unknown>>) =>
accounts
.filter(
(account) =>
typeof account.lastError === "string" && account.lastError,
)
.map((account) => ({
provider: "imessage",
accountId:
typeof account.accountId === "string"
? account.accountId
: "default",
message: `Provider error: ${String(account.lastError)}`,
})),
},
},
] as unknown,
}));
vi.mock("../web/session.js", () => ({
webAuthExists: mocks.webAuthExists,
getWebAuthAgeMs: mocks.getWebAuthAgeMs,
@@ -128,7 +210,7 @@ describe("statusCommand", () => {
it("prints JSON when requested", async () => {
await statusCommand({ json: true }, runtime as never);
const payload = JSON.parse((runtime.log as vi.Mock).mock.calls[0][0]);
expect(payload.web.linked).toBe(true);
expect(payload.linkProvider.linked).toBe(true);
expect(payload.sessions.count).toBe(1);
expect(payload.sessions.path).toBe("/tmp/sessions.json");
expect(payload.sessions.defaults.model).toBeTruthy();
@@ -147,7 +229,7 @@ describe("statusCommand", () => {
expect(logs.some((l) => l.includes("Dashboard"))).toBe(true);
expect(logs.some((l) => l.includes("macos 14.0 (arm64)"))).toBe(true);
expect(logs.some((l) => l.includes("Providers"))).toBe(true);
expect(logs.some((l) => l.includes("Telegram"))).toBe(true);
expect(logs.some((l) => l.includes("WhatsApp"))).toBe(true);
expect(logs.some((l) => l.includes("Sessions"))).toBe(true);
expect(logs.some((l) => l.includes("+1000"))).toBe(true);
expect(logs.some((l) => l.includes("50%"))).toBe(true);
@@ -196,24 +278,26 @@ describe("statusCommand", () => {
configSnapshot: null,
});
mocks.callGateway.mockResolvedValueOnce({
signalAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "signal-cli unreachable",
},
],
imessageAccounts: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "imessage permission denied",
},
],
providerAccounts: {
signal: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "signal-cli unreachable",
},
],
imessage: [
{
accountId: "default",
enabled: true,
configured: true,
running: false,
lastError: "imessage permission denied",
},
],
},
});
(runtime.log as vi.Mock).mockClear();

View File

@@ -10,7 +10,11 @@ import {
} from "../agents/defaults.js";
import { resolveConfiguredModelRef } from "../agents/model-selection.js";
import { withProgress } from "../cli/progress.js";
import { loadConfig, resolveGatewayPort } from "../config/config.js";
import {
type ClawdbotConfig,
loadConfig,
resolveGatewayPort,
} from "../config/config.js";
import {
loadSessionStore,
resolveMainSessionKey,
@@ -39,14 +43,19 @@ import {
type UpdateCheckResult,
} from "../infra/update-check.js";
import { runExec } from "../process/exec.js";
import { resolveProviderDefaultAccountId } from "../providers/plugins/helpers.js";
import { listProviderPlugins } from "../providers/plugins/index.js";
import type {
ProviderAccountSnapshot,
ProviderId,
ProviderPlugin,
} from "../providers/plugins/types.js";
import type { RuntimeEnv } from "../runtime.js";
import { renderTable } from "../terminal/table.js";
import { theme } from "../terminal/theme.js";
import { VERSION } from "../version.js";
import { resolveWhatsAppAccount } from "../web/accounts.js";
import { resolveHeartbeatSeconds } from "../web/reconnect.js";
import { getWebAuthAgeMs, webAuthExists } from "../web/session.js";
import type { HealthSummary } from "./health.js";
import { formatHealthProviderLines, type HealthSummary } from "./health.js";
import { resolveControlUiLinks } from "./onboard-helpers.js";
import { formatGatewayAuthUsed } from "./status-all/format.js";
import { buildProvidersTable } from "./status-all/providers.js";
@@ -75,7 +84,12 @@ export type SessionStatus = {
};
export type StatusSummary = {
web: { linked: boolean; authAgeMs: number | null };
linkProvider?: {
id: ProviderId;
label: string;
linked: boolean;
authAgeMs: number | null;
};
heartbeatSeconds: number;
providerSummary: string[];
queuedSystemEvents: string[];
@@ -87,11 +101,64 @@ export type StatusSummary = {
};
};
type LinkProviderContext = {
linked: boolean;
authAgeMs: number | null;
account?: unknown;
accountId?: string;
plugin: ProviderPlugin;
};
async function resolveLinkProviderContext(
cfg: ClawdbotConfig,
): Promise<LinkProviderContext | null> {
for (const plugin of listProviderPlugins()) {
const accountIds = plugin.config.listAccountIds(cfg);
const defaultAccountId = resolveProviderDefaultAccountId({
plugin,
cfg,
accountIds,
});
const account = plugin.config.resolveAccount(cfg, defaultAccountId);
const enabled = plugin.config.isEnabled
? plugin.config.isEnabled(account, cfg)
: true;
const configured = plugin.config.isConfigured
? await plugin.config.isConfigured(account, cfg)
: true;
const snapshot = plugin.config.describeAccount
? plugin.config.describeAccount(account, cfg)
: ({
accountId: defaultAccountId,
enabled,
configured,
} as ProviderAccountSnapshot);
const summary = plugin.status?.buildProviderSummary
? await plugin.status.buildProviderSummary({
account,
cfg,
defaultAccountId,
snapshot,
})
: undefined;
const summaryRecord = summary as Record<string, unknown> | undefined;
const linked =
summaryRecord && typeof summaryRecord.linked === "boolean"
? summaryRecord.linked
: null;
if (linked === null) continue;
const authAgeMs =
summaryRecord && typeof summaryRecord.authAgeMs === "number"
? summaryRecord.authAgeMs
: null;
return { linked, authAgeMs, account, accountId: defaultAccountId, plugin };
}
return null;
}
export async function getStatusSummary(): Promise<StatusSummary> {
const cfg = loadConfig();
const account = resolveWhatsAppAccount({ cfg });
const linked = await webAuthExists(account.authDir);
const authAgeMs = getWebAuthAgeMs(account.authDir);
const linkContext = await resolveLinkProviderContext(cfg);
const heartbeatSeconds = resolveHeartbeatSeconds(cfg, undefined);
const providerSummary = await buildProviderSummary(cfg, {
colorize: true,
@@ -161,7 +228,14 @@ export async function getStatusSummary(): Promise<StatusSummary> {
const recent = sessions.slice(0, 5);
return {
web: { linked, authAgeMs },
linkProvider: linkContext
? {
id: linkContext.plugin.id,
label: linkContext.plugin.meta.label ?? "Provider",
linked: linkContext.linked,
authAgeMs: linkContext.authAgeMs,
}
: undefined,
heartbeatSeconds,
providerSummary,
queuedSystemEvents,
@@ -865,24 +939,6 @@ export async function statusCommand(
}
return map;
})();
const providerKeyForLabel = (label: string) => {
switch (label) {
case "WhatsApp":
return "whatsapp";
case "Telegram":
return "telegram";
case "Discord":
return "discord";
case "Slack":
return "slack";
case "Signal":
return "signal";
case "iMessage":
return "imessage";
default:
return label.toLowerCase();
}
};
runtime.log(
renderTable({
width: tableWidth,
@@ -893,8 +949,7 @@ export async function statusCommand(
{ key: "Detail", header: "Detail", flex: true, minWidth: 24 },
],
rows: providers.rows.map((row) => {
const providerKey = providerKeyForLabel(row.provider);
const issues = providerIssuesByProvider.get(providerKey) ?? [];
const issues = providerIssuesByProvider.get(row.id) ?? [];
const effectiveState =
row.state === "off" ? "off" : issues.length > 0 ? "warn" : row.state;
const issueSuffix =
@@ -977,32 +1032,24 @@ export async function statusCommand(
Status: ok("reachable"),
Detail: `${health.durationMs}ms`,
});
rows.push({
Provider: "Telegram",
Status: health.telegram.configured
? health.telegram.probe?.ok
? ok("OK")
: warn("WARN")
: muted("OFF"),
Detail: health.telegram.configured
? health.telegram.probe?.ok
? `@${health.telegram.probe.bot?.username ?? "unknown"} · ${health.telegram.probe.elapsedMs}ms`
: (health.telegram.probe?.error ?? "probe failed")
: "not configured",
});
rows.push({
Provider: "Discord",
Status: health.discord.configured
? health.discord.probe?.ok
? ok("OK")
: warn("WARN")
: muted("OFF"),
Detail: health.discord.configured
? health.discord.probe?.ok
? `@${health.discord.probe.bot?.username ?? "unknown"} · ${health.discord.probe.elapsedMs}ms`
: (health.discord.probe?.error ?? "probe failed")
: "not configured",
});
for (const line of formatHealthProviderLines(health)) {
const colon = line.indexOf(":");
if (colon === -1) continue;
const provider = line.slice(0, colon).trim();
const detail = line.slice(colon + 1).trim();
const normalized = detail.toLowerCase();
const status = (() => {
if (normalized.startsWith("ok")) return ok("OK");
if (normalized.startsWith("failed")) return warn("WARN");
if (normalized.startsWith("not configured")) return muted("OFF");
if (normalized.startsWith("configured")) return ok("OK");
if (normalized.startsWith("linked")) return ok("LINKED");
if (normalized.startsWith("not linked")) return warn("UNLINKED");
return warn("WARN");
})();
rows.push({ Provider: provider, Status: status, Detail: detail });
}
runtime.log(
renderTable({