Move provider to a plugin-architecture (#661)

* refactor: introduce provider plugin registry

* refactor: move provider CLI to plugins

* docs: add provider plugin implementation notes

* refactor: shift provider runtime logic into plugins

* refactor: add plugin defaults and summaries

* docs: update provider plugin notes

* feat(commands): add /commands slash list

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* Tests: align google shared expectations

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* refactor: move provider routing into plugins

* test: align agent routing expectations

* docs: update provider plugin notes

* refactor: route replies via provider plugins

* docs: note route-reply plugin hooks

* refactor: extend provider plugin contract

* refactor: derive provider status from plugins

* refactor: unify gateway provider control

* refactor: use plugin metadata in auto-reply

* fix: parenthesize cron target selection

* refactor: derive gateway methods from plugins

* refactor: generalize provider logout

* refactor: route provider logout through plugins

* refactor: move WhatsApp web login methods into plugin

* refactor: generalize provider log prefixes

* refactor: centralize default chat provider

* refactor: derive provider lists from registry

* refactor: move provider reload noops into plugins

* refactor: resolve web login provider via alias

* refactor: derive CLI provider options from plugins

* refactor: derive prompt provider list from plugins

* style: apply biome lint fixes

* fix: resolve provider routing edge cases

* docs: update provider plugin refactor notes

* fix(gateway): harden agent provider routing

* refactor: move provider routing into plugins

* refactor: move provider CLI to plugins

* refactor: derive provider lists from registry

* fix: restore slash command parsing

* refactor: align provider ids for schema

* refactor: unify outbound target resolution

* fix: keep outbound labels stable

* feat: add msteams to cron surfaces

* fix: clean up lint build issues

* refactor: localize chat provider alias normalization

* refactor: drive gateway provider lists from plugins

* docs: update provider plugin notes

* style: format message-provider

* fix: avoid provider registry init cycles

* style: sort message-provider imports

* fix: relax provider alias map typing

* refactor: move provider routing into plugins

* refactor: add plugin pairing/config adapters

* refactor: route pairing and provider removal via plugins

* refactor: align auto-reply provider typing

* test: stabilize telegram media mocks

* docs: update provider plugin refactor notes

* refactor: pluginize outbound targets

* refactor: pluginize provider selection

* refactor: generalize text chunk limits

* docs: update provider plugin notes

* refactor: generalize group session/config

* fix: normalize provider id for room detection

* fix: avoid provider init in system prompt

* style: formatting cleanup

* refactor: normalize agent delivery targets

* test: update outbound delivery labels

* chore: fix lint regressions

* refactor: extend provider plugin adapters

* refactor: move elevated/block streaming defaults to plugins

* refactor: defer outbound send deps to plugins

* docs: note plugin-driven streaming/elevated defaults

* refactor: centralize webchat provider constant

* refactor: add provider setup adapters

* refactor: delegate provider add config to plugins

* docs: document plugin-driven provider add

* refactor: add plugin state/binding metadata

* refactor: build agent provider status from plugins

* docs: note plugin-driven agent bindings

* refactor: centralize internal provider constant usage

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

* refactor: centralize default chat provider

* refactor: centralize WhatsApp target normalization

* refactor: move provider routing into plugins

* refactor: normalize agent delivery targets

* chore: fix lint regressions

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

* feat: expand provider plugin adapters

* refactor: route auto-reply via provider plugins

* fix: align WhatsApp target normalization

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

* refactor: centralize WhatsApp target normalization

* feat: add /config chat config updates

* docs: add /config get alias

* feat(commands): add /commands slash list

* refactor: centralize default chat provider

* style: apply biome lint fixes

* chore: fix lint regressions

* fix: clean up whatsapp allowlist typing

* style: format config command helpers

* refactor: pluginize tool threading context

* refactor: normalize session announce targets

* docs: note new plugin threading and announce hooks

* refactor: pluginize message actions

* docs: update provider plugin actions notes

* fix: align provider action adapters

* refactor: centralize webchat checks

* style: format message provider helpers

* refactor: move provider onboarding into adapters

* docs: note onboarding provider adapters

* feat: add msteams onboarding adapter

* style: organize onboarding imports

* fix: normalize msteams allowFrom types

* feat: add plugin text chunk limits

* refactor: use plugin chunk limit fallbacks

* feat: add provider mention stripping hooks

* style: organize provider plugin type imports

* refactor: generalize health snapshots

* refactor: update macOS health snapshot handling

* docs: refresh health snapshot notes

* style: format health snapshot updates

* refactor: drive security warnings via plugins

* docs: note provider security adapter

* style: format provider security adapters

* refactor: centralize provider account defaults

* refactor: type gateway client identity constants

* chore: regen gateway protocol swift

* fix: degrade health on failed provider probe

* refactor: centralize pairing approve hint

* docs: add plugin CLI command references

* refactor: route auth and tool sends through plugins

* docs: expand provider plugin hooks

* refactor: document provider docking touchpoints

* refactor: normalize internal provider defaults

* refactor: streamline outbound delivery wiring

* refactor: make provider onboarding plugin-owned

* refactor: support provider-owned agent tools

* refactor: move telegram draft chunking into telegram module

* refactor: infer provider tool sends via extractToolSend

* fix: repair plugin onboarding imports

* refactor: de-dup outbound target normalization

* style: tidy plugin and agent imports

* refactor: data-drive provider selection line

* fix: satisfy lint after provider plugin rebase

* test: deflake gateway-cli coverage

* style: format gateway-cli coverage test

* refactor(provider-plugins): simplify provider ids

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

* style(macos): swiftformat HealthStore

* refactor(sandbox): derive provider tool denylist

* fix(sandbox): avoid plugin init in defaults

* refactor(provider-plugins): centralize provider aliases

* style(test): satisfy biome

* refactor(protocol): v3 providers.status maps

* refactor(ui): adapt to protocol v3

* refactor(macos): adapt to protocol v3

* test: update providers.status v3 fixtures

* refactor(gateway): map provider runtime snapshot

* test(gateway): update reload runtime snapshot

* refactor(whatsapp): normalize heartbeat provider id

* docs(refactor): update provider plugin notes

* style: satisfy biome after rebase

* fix: describe sandboxed elevated in prompt

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

* refactor: derive CLI provider options from plugins

* fix(gateway): harden agent provider routing

* fix(gateway): harden agent provider routing

* refactor: align provider ids for schema

* fix(protocol): keep agent provider string

* fix(gateway): harden agent provider routing

* fix(protocol): keep agent provider string

* refactor: normalize agent delivery targets

* refactor: support provider-owned agent tools

* refactor(config): provider-keyed elevated allowFrom

* style: satisfy biome

* fix(gateway): appease provider narrowing

* style: satisfy biome

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

* fix(reply): avoid plugin registry init cycle

* refactor(providers): add lightweight provider dock

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

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

* refactor(providers): make media limit helper generic

* fix(providers): break plugin registry import cycles

* style: satisfy biome

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

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

* refactor(provider): drop web alias

* refactor(provider): lazy-load monitors

* style: satisfy lint/format

* style: format status-all providers table

* style: swiftformat gateway discovery model

* test: make reload plan plugin-driven

* fix: avoid token stringification in status-all

* refactor: make provider IDs explicit in status

* feat: warn on signal/imessage provider runtime errors

* test: cover gateway provider runtime warnings in status

* fix: add runtime kind to provider status issues

* test: cover health degradation on probe failure

* fix: keep routeReply lightweight

* style: organize routeReply imports

* refactor(web): extract auth-store helpers

* refactor(whatsapp): lazy login imports

* refactor(outbound): route replies via plugin outbound

* docs: update provider plugin notes

* style: format provider status issues

* fix: make sandbox scope warning wrap-safe

* refactor: load outbound adapters from provider plugins

* docs: update provider plugin outbound notes

* style(macos): fix swiftformat lint

* docs: changelog for provider plugins

* fix(macos): satisfy swiftformat

* fix(macos): open settings via menu action

* style: format after rebase

* fix(macos): open Settings via menu action

---------

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

View File

@@ -1,12 +1,18 @@
import type { Command } from "commander";
import type { CronJob, CronSchedule } from "../cron/types.js";
import { danger } from "../globals.js";
import { listProviderPlugins } from "../providers/plugins/index.js";
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { colorize, isRich, theme } from "../terminal/theme.js";
import type { GatewayRpcOpts } from "./gateway-rpc.js";
import { addGatewayClientOptions, callGatewayFromCli } from "./gateway-rpc.js";
const CRON_PROVIDER_OPTIONS = [
"last",
...listProviderPlugins().map((plugin) => plugin.id),
].join("|");
async function warnIfCronSchedulerDisabled(opts: GatewayRpcOpts) {
try {
const res = (await callGatewayFromCli("cron.status", opts, {})) as {
@@ -304,7 +310,7 @@ export function registerCronCli(program: Command) {
.option("--deliver", "Deliver agent output", false)
.option(
"--provider <provider>",
"Delivery provider (last|whatsapp|telegram|discord|slack|signal|imessage)",
`Delivery provider (${CRON_PROVIDER_OPTIONS})`,
"last",
)
.option(
@@ -571,7 +577,7 @@ export function registerCronCli(program: Command) {
.option("--deliver", "Deliver agent output", false)
.option(
"--provider <provider>",
"Delivery provider (last|whatsapp|telegram|discord|slack|signal|imessage)",
`Delivery provider (${CRON_PROVIDER_OPTIONS})`,
)
.option(
"--to <dest>",

View File

@@ -50,6 +50,10 @@ import { getResolvedLoggerSettings } from "../logging.js";
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { colorize, isRich, theme } from "../terminal/theme.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { createDefaultDeps } from "./deps.js";
import { withProgress } from "./progress.js";
@@ -236,8 +240,8 @@ async function probeGatewayStatus(opts: {
password: opts.password,
method: "status",
timeoutMs: opts.timeoutMs,
clientName: "cli",
mode: "cli",
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
...(opts.configPath ? { configPath: opts.configPath } : {}),
}),
);

View File

@@ -1,5 +1,7 @@
import type { ClawdbotConfig } from "../config/config.js";
import { sendMessageDiscord } from "../discord/send.js";
import { sendMessageIMessage } from "../imessage/send.js";
import type { OutboundSendDeps } from "../infra/outbound/deliver.js";
import { sendMessageMSTeams } from "../msteams/send.js";
import { logWebSelfId, sendMessageWhatsApp } from "../providers/web/index.js";
import { sendMessageSignal } from "../signal/send.js";
@@ -28,4 +30,29 @@ export function createDefaultDeps(): CliDeps {
};
}
// Provider docking: extend this mapping when adding new outbound send deps.
export function createOutboundSendDeps(
deps: CliDeps,
cfg: ClawdbotConfig,
): OutboundSendDeps {
return {
sendWhatsApp: deps.sendMessageWhatsApp,
sendTelegram: deps.sendMessageTelegram,
sendDiscord: deps.sendMessageDiscord,
sendSlack: deps.sendMessageSlack,
sendSignal: deps.sendMessageSignal,
sendIMessage: deps.sendMessageIMessage,
// Provider docking: MS Teams send requires full cfg (credentials), wrap to match OutboundSendDeps.
sendMSTeams: deps.sendMessageMSTeams
? async (to, text, opts) =>
await deps.sendMessageMSTeams({
cfg,
to,
text,
mediaUrl: opts?.mediaUrl,
})
: undefined,
};
}
export { logWebSelfId };

View File

@@ -112,13 +112,13 @@ describe("gateway-cli coverage", () => {
registerGatewayCli(program);
await program.parseAsync(
["gateway", "call", "health", "--params", '{"x":1}'],
["gateway", "call", "health", "--params", '{"x":1}', "--json"],
{ from: "user" },
);
expect(callGateway).toHaveBeenCalledTimes(1);
expect(runtimeLogs.join("\n")).toContain('"ok": true');
});
}, 15_000);
it("registers gateway status and routes to gatewayStatusCommand", async () => {
runtimeLogs.length = 0;
@@ -133,7 +133,7 @@ describe("gateway-cli coverage", () => {
await program.parseAsync(["gateway", "status", "--json"], { from: "user" });
expect(gatewayStatusCommand).toHaveBeenCalledTimes(1);
});
}, 15_000);
it("registers gateway discover and prints JSON", async () => {
runtimeLogs.length = 0;

View File

@@ -5,6 +5,10 @@ import path from "node:path";
import type { Command } from "commander";
import { resolveDefaultAgentWorkspaceDir } from "../agents/workspace.js";
import { gatewayStatusCommand } from "../commands/gateway-status.js";
import {
formatHealthProviderLines,
type HealthSummary,
} from "../commands/health.js";
import { handleReset } from "../commands/onboard-helpers.js";
import {
CONFIG_PATH_CLAWDBOT,
@@ -40,6 +44,10 @@ import {
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { colorize, isRich, theme } from "../terminal/theme.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { resolveUserPath } from "../utils.js";
import { forceFreePortAndWait } from "./ports.js";
import { withProgress } from "./progress.js";
@@ -523,8 +531,8 @@ const callGatewayCli = async (
params,
expectFinal: Boolean(opts.expectFinal),
timeoutMs: Number(opts.timeout ?? 10_000),
clientName: "cli",
mode: "cli",
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
}),
);
@@ -947,28 +955,12 @@ export function registerGatewayCli(program: Command) {
durationMs != null ? ` (${durationMs}ms)` : ""
}`,
);
if (obj.web && typeof obj.web === "object") {
const web = obj.web as Record<string, unknown>;
const linked = web.linked === true;
defaultRuntime.log(
`Web: ${linked ? "linked" : "not linked"}${
typeof web.authAgeMs === "number" && linked
? ` (${Math.round(web.authAgeMs / 60_000)}m)`
: ""
}`,
);
}
if (obj.telegram && typeof obj.telegram === "object") {
const tg = obj.telegram as Record<string, unknown>;
defaultRuntime.log(
`Telegram: ${tg.configured === true ? "configured" : "not configured"}`,
);
}
if (obj.discord && typeof obj.discord === "object") {
const dc = obj.discord as Record<string, unknown>;
defaultRuntime.log(
`Discord: ${dc.configured === true ? "configured" : "not configured"}`,
);
if (obj.providers && typeof obj.providers === "object") {
for (const line of formatHealthProviderLines(
obj as HealthSummary,
)) {
defaultRuntime.log(line);
}
}
} catch (err) {
defaultRuntime.error(String(err));

View File

@@ -1,5 +1,9 @@
import type { Command } from "commander";
import { callGateway } from "../gateway/call.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { withProgress } from "./progress.js";
export type GatewayRpcOpts = {
@@ -41,8 +45,8 @@ export async function callGatewayFromCli(
params,
expectFinal: extra?.expectFinal ?? Boolean(opts.expectFinal),
timeoutMs: Number(opts.timeout ?? 10_000),
clientName: "cli",
mode: "cli",
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
}),
);
}

View File

@@ -4,6 +4,10 @@ import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { theme } from "../terminal/theme.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import {
type CameraFacing,
cameraTempPath,
@@ -152,8 +156,8 @@ const callGatewayCli = async (
method,
params,
timeoutMs: Number(opts.timeout ?? 10_000),
clientName: "cli",
mode: "cli",
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
}),
);

View File

@@ -3,40 +3,33 @@ import { describe, expect, it, vi } from "vitest";
const listProviderPairingRequests = vi.fn();
const approveProviderPairingCode = vi.fn();
const notifyPairingApproved = vi.fn();
const pairingIdLabels: Record<string, string> = {
telegram: "telegramUserId",
discord: "discordUserId",
};
const requirePairingAdapter = vi.fn((provider: string) => ({
idLabel: pairingIdLabels[provider] ?? "userId",
}));
const listPairingProviders = vi.fn(() => ["telegram", "discord"]);
const resolvePairingProvider = vi.fn((raw: string) => raw);
vi.mock("../pairing/pairing-store.js", () => ({
listProviderPairingRequests,
approveProviderPairingCode,
}));
vi.mock("../telegram/send.js", () => ({
sendMessageTelegram: vi.fn(),
}));
vi.mock("../discord/send.js", () => ({
sendMessageDiscord: vi.fn(),
}));
vi.mock("../slack/send.js", () => ({
sendMessageSlack: vi.fn(),
}));
vi.mock("../signal/send.js", () => ({
sendMessageSignal: vi.fn(),
}));
vi.mock("../imessage/send.js", () => ({
sendMessageIMessage: vi.fn(),
vi.mock("../providers/plugins/pairing.js", () => ({
listPairingProviders,
resolvePairingProvider,
notifyPairingApproved,
requirePairingAdapter,
}));
vi.mock("../config/config.js", () => ({
loadConfig: vi.fn().mockReturnValue({}),
}));
vi.mock("../telegram/token.js", () => ({
resolveTelegramToken: vi.fn().mockReturnValue({ token: "t" }),
}));
describe("pairing cli", () => {
it("labels Telegram ids as telegramUserId", async () => {
const { registerPairingCli } = await import("./pairing-cli.js");

View File

@@ -1,78 +1,27 @@
import type { Command } from "commander";
import { loadConfig } from "../config/config.js";
import { sendMessageDiscord } from "../discord/send.js";
import { sendMessageIMessage } from "../imessage/send.js";
import { sendMessageMSTeams } from "../msteams/send.js";
import { PROVIDER_ID_LABELS } from "../pairing/pairing-labels.js";
import { resolvePairingIdLabel } from "../pairing/pairing-labels.js";
import {
approveProviderPairingCode,
listProviderPairingRequests,
type PairingProvider,
} from "../pairing/pairing-store.js";
import { sendMessageSignal } from "../signal/send.js";
import { sendMessageSlack } from "../slack/send.js";
import { sendMessageTelegram } from "../telegram/send.js";
import { resolveTelegramToken } from "../telegram/token.js";
import {
listPairingProviders,
notifyPairingApproved,
resolvePairingProvider,
} from "../providers/plugins/pairing.js";
const PROVIDERS: PairingProvider[] = [
"telegram",
"signal",
"imessage",
"discord",
"slack",
"whatsapp",
"msteams",
];
const PROVIDERS: PairingProvider[] = listPairingProviders();
function parseProvider(raw: unknown): PairingProvider {
const value = (
typeof raw === "string"
? raw
: typeof raw === "number" || typeof raw === "boolean"
? String(raw)
: ""
)
.trim()
.toLowerCase();
if ((PROVIDERS as string[]).includes(value)) return value as PairingProvider;
throw new Error(
`Invalid provider: ${value || "(empty)"} (expected one of: ${PROVIDERS.join(", ")})`,
);
return resolvePairingProvider(raw);
}
async function notifyApproved(provider: PairingProvider, id: string) {
const message =
"✅ Clawdbot access approved. Send a message to start chatting.";
if (provider === "telegram") {
const cfg = loadConfig();
const { token } = resolveTelegramToken(cfg);
if (!token) throw new Error("telegram token not configured");
await sendMessageTelegram(id, message, { token });
return;
}
if (provider === "discord") {
await sendMessageDiscord(`user:${id}`, message);
return;
}
if (provider === "slack") {
await sendMessageSlack(`user:${id}`, message);
return;
}
if (provider === "signal") {
await sendMessageSignal(id, message);
return;
}
if (provider === "imessage") {
await sendMessageIMessage(id, message);
return;
}
if (provider === "msteams") {
const cfg = loadConfig();
await sendMessageMSTeams({ cfg, to: id, text: message });
return;
}
// WhatsApp: approval still works (store); notifying requires an active web session.
const cfg = loadConfig();
await notifyPairingApproved({ providerId: provider, id, cfg });
}
export function registerPairingCli(program: Command) {
@@ -105,7 +54,7 @@ export function registerPairingCli(program: Command) {
}
for (const r of requests) {
const meta = r.meta ? JSON.stringify(r.meta) : "";
const idLabel = PROVIDER_ID_LABELS[provider];
const idLabel = resolvePairingIdLabel(provider);
console.log(
`${r.code} ${idLabel}=${r.id}${meta ? ` meta=${meta}` : ""} ${r.createdAt}`,
);

View File

@@ -28,6 +28,8 @@ import {
} from "../config/config.js";
import { danger, setVerbose } from "../globals.js";
import { autoMigrateLegacyState } from "../infra/state-migrations.js";
import { listProviderPlugins } from "../providers/plugins/index.js";
import { DEFAULT_CHAT_PROVIDER } from "../providers/registry.js";
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { isRich, theme } from "../terminal/theme.js";
@@ -67,6 +69,9 @@ function collectOption(value: string, previous: string[] = []): string[] {
export function buildProgram() {
const program = new Command();
const PROGRAM_VERSION = VERSION;
const providerOptions = listProviderPlugins().map((plugin) => plugin.id);
const messageProviderOptions = providerOptions.join("|");
const agentProviderOptions = ["last", ...providerOptions].join("|");
program
.name("clawdbot")
@@ -591,10 +596,7 @@ ${theme.muted("Docs:")} ${formatDocsLink("/message", "docs.clawd.bot/message")}`
const withMessageBase = (command: Command) =>
command
.option(
"--provider <provider>",
"Provider: whatsapp|telegram|discord|slack|signal|imessage",
)
.option("--provider <provider>", `Provider: ${messageProviderOptions}`)
.option("--account <id>", "Provider account id")
.option("--json", "Output result as JSON", false)
.option("--dry-run", "Print payload and skip sending", false)
@@ -1061,7 +1063,7 @@ ${theme.muted("Docs:")} ${formatDocsLink("/message", "docs.clawd.bot/message")}`
.option("--verbose <on|off>", "Persist agent verbose level for the session")
.option(
"--provider <provider>",
"Delivery provider: whatsapp|telegram|discord|slack|signal|imessage (default: whatsapp)",
`Delivery provider: ${agentProviderOptions} (default: ${DEFAULT_CHAT_PROVIDER})`,
)
.option(
"--local",
@@ -1220,7 +1222,7 @@ ${theme.muted("Docs:")} ${formatDocsLink(
program
.command("status")
.description("Show local status (gateway, agents, sessions, auth)")
.description("Show provider health and recent session recipients")
.option("--json", "Output JSON instead of text", false)
.option("--all", "Full diagnosis (read-only, pasteable)", false)
.option("--usage", "Show provider usage/quota snapshots", false)

View File

@@ -1,8 +1,12 @@
import { loadConfig } from "../config/config.js";
import { setVerbose } from "../globals.js";
import { loginWeb, logoutWeb } from "../provider-web.js";
import { resolveProviderDefaultAccountId } from "../providers/plugins/helpers.js";
import {
getProviderPlugin,
normalizeProviderId,
} from "../providers/plugins/index.js";
import { DEFAULT_CHAT_PROVIDER } from "../providers/registry.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import { resolveWhatsAppAccount } from "../web/accounts.js";
type ProviderAuthOptions = {
provider?: string;
@@ -10,44 +14,55 @@ type ProviderAuthOptions = {
verbose?: boolean;
};
function normalizeProvider(raw?: string): "whatsapp" | "web" {
const value = String(raw ?? "whatsapp")
.trim()
.toLowerCase();
if (value === "whatsapp" || value === "web") return value;
throw new Error(`Unsupported provider: ${value}`);
}
export async function runProviderLogin(
opts: ProviderAuthOptions,
runtime: RuntimeEnv = defaultRuntime,
) {
const provider = normalizeProvider(opts.provider);
const providerInput = opts.provider ?? DEFAULT_CHAT_PROVIDER;
const providerId = normalizeProviderId(providerInput);
if (!providerId) {
throw new Error(`Unsupported provider: ${providerInput}`);
}
const plugin = getProviderPlugin(providerId);
if (!plugin?.auth?.login) {
throw new Error(`Provider ${providerId} does not support login`);
}
// Auth-only flow: do not mutate provider config here.
setVerbose(Boolean(opts.verbose));
await loginWeb(
Boolean(opts.verbose),
provider,
undefined,
const cfg = loadConfig();
const accountId =
opts.account?.trim() || resolveProviderDefaultAccountId({ plugin, cfg });
await plugin.auth.login({
cfg,
accountId,
runtime,
opts.account,
);
verbose: Boolean(opts.verbose),
providerInput,
});
}
export async function runProviderLogout(
opts: ProviderAuthOptions,
runtime: RuntimeEnv = defaultRuntime,
) {
const _provider = normalizeProvider(opts.provider);
const providerInput = opts.provider ?? DEFAULT_CHAT_PROVIDER;
const providerId = normalizeProviderId(providerInput);
if (!providerId) {
throw new Error(`Unsupported provider: ${providerInput}`);
}
const plugin = getProviderPlugin(providerId);
if (!plugin?.gateway?.logoutAccount) {
throw new Error(`Provider ${providerId} does not support logout`);
}
// Auth-only flow: resolve account + clear session state only.
const cfg = loadConfig();
const account = resolveWhatsAppAccount({
const accountId =
opts.account?.trim() || resolveProviderDefaultAccountId({ plugin, cfg });
const account = plugin.config.resolveAccount(cfg, accountId);
await plugin.gateway.logoutAccount({
cfg,
accountId: opts.account,
});
await logoutWeb({
accountId,
account,
runtime,
authDir: account.authDir,
isLegacyAuthDir: account.isLegacyAuthDir,
});
}

View File

@@ -169,9 +169,9 @@ export function registerProvidersCli(program: Command) {
providers
.command("logout")
.description("Log out of a provider session (WhatsApp Web only)")
.description("Log out of a provider session (if supported)")
.option("--provider <provider>", "Provider alias (default: whatsapp)")
.option("--account <id>", "WhatsApp account id (accountId)")
.option("--account <id>", "Account id (accountId)")
.action(async (opts) => {
try {
await runProviderLogout(