mirror of
https://github.com/farcasclaudiu/openclaw.git
synced 2026-06-28 15:01:41 +03:00
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:
committed by
GitHub
parent
23eec7d841
commit
7acd26a2fc
@@ -1 +1,3 @@
|
||||
// Backwards-compatible entry point.
|
||||
// Implementation lives in `src/agents/cli-runner.ts` (so we can reuse the same runner for other CLIs).
|
||||
export { runClaudeCliAgent, runCliAgent } from "./cli-runner.js";
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
getProviderPlugin,
|
||||
normalizeProviderId,
|
||||
} from "../providers/plugins/index.js";
|
||||
|
||||
export type MessagingToolSend = {
|
||||
tool: string;
|
||||
provider: string;
|
||||
@@ -5,101 +10,29 @@ export type MessagingToolSend = {
|
||||
to?: string;
|
||||
};
|
||||
|
||||
const MESSAGING_TOOLS = new Set([
|
||||
"telegram",
|
||||
"whatsapp",
|
||||
"discord",
|
||||
"slack",
|
||||
"sessions_send",
|
||||
"message",
|
||||
]);
|
||||
const CORE_MESSAGING_TOOLS = new Set(["sessions_send", "message"]);
|
||||
|
||||
// Provider docking: any plugin with `actions` opts into messaging tool handling.
|
||||
export function isMessagingTool(toolName: string): boolean {
|
||||
return MESSAGING_TOOLS.has(toolName);
|
||||
if (CORE_MESSAGING_TOOLS.has(toolName)) return true;
|
||||
const providerId = normalizeProviderId(toolName);
|
||||
return Boolean(providerId && getProviderPlugin(providerId)?.actions);
|
||||
}
|
||||
|
||||
export function isMessagingToolSendAction(
|
||||
toolName: string,
|
||||
actionRaw: string,
|
||||
args: Record<string, unknown>,
|
||||
): boolean {
|
||||
const action = actionRaw.trim();
|
||||
const action = typeof args.action === "string" ? args.action.trim() : "";
|
||||
if (toolName === "sessions_send") return true;
|
||||
if (toolName === "message") {
|
||||
return action === "send" || action === "thread-reply";
|
||||
}
|
||||
return action === "sendMessage" || action === "threadReply";
|
||||
}
|
||||
|
||||
function normalizeSlackTarget(raw: string): string | undefined {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return undefined;
|
||||
const mentionMatch = trimmed.match(/^<@([A-Z0-9]+)>$/i);
|
||||
if (mentionMatch) return `user:${mentionMatch[1]}`.toLowerCase();
|
||||
if (trimmed.startsWith("user:")) {
|
||||
const id = trimmed.slice(5).trim();
|
||||
return id ? `user:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("channel:")) {
|
||||
const id = trimmed.slice(8).trim();
|
||||
return id ? `channel:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("slack:")) {
|
||||
const id = trimmed.slice(6).trim();
|
||||
return id ? `user:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("@")) {
|
||||
const id = trimmed.slice(1).trim();
|
||||
return id ? `user:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("#")) {
|
||||
const id = trimmed.slice(1).trim();
|
||||
return id ? `channel:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
return `channel:${trimmed}`.toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeDiscordTarget(raw: string): string | undefined {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return undefined;
|
||||
const mentionMatch = trimmed.match(/^<@!?(\d+)>$/);
|
||||
if (mentionMatch) return `user:${mentionMatch[1]}`.toLowerCase();
|
||||
if (trimmed.startsWith("user:")) {
|
||||
const id = trimmed.slice(5).trim();
|
||||
return id ? `user:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("channel:")) {
|
||||
const id = trimmed.slice(8).trim();
|
||||
return id ? `channel:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("discord:")) {
|
||||
const id = trimmed.slice(8).trim();
|
||||
return id ? `user:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
if (trimmed.startsWith("@")) {
|
||||
const id = trimmed.slice(1).trim();
|
||||
return id ? `user:${id}`.toLowerCase() : undefined;
|
||||
}
|
||||
return `channel:${trimmed}`.toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeTelegramTarget(raw: string): string | undefined {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return undefined;
|
||||
let normalized = trimmed;
|
||||
if (normalized.startsWith("telegram:")) {
|
||||
normalized = normalized.slice("telegram:".length).trim();
|
||||
} else if (normalized.startsWith("tg:")) {
|
||||
normalized = normalized.slice("tg:".length).trim();
|
||||
} else if (normalized.startsWith("group:")) {
|
||||
normalized = normalized.slice("group:".length).trim();
|
||||
}
|
||||
if (!normalized) return undefined;
|
||||
const tmeMatch =
|
||||
/^https?:\/\/t\.me\/([A-Za-z0-9_]+)$/i.exec(normalized) ??
|
||||
/^t\.me\/([A-Za-z0-9_]+)$/i.exec(normalized);
|
||||
if (tmeMatch?.[1]) normalized = `@${tmeMatch[1]}`;
|
||||
if (!normalized) return undefined;
|
||||
return `telegram:${normalized}`.toLowerCase();
|
||||
const providerId = normalizeProviderId(toolName);
|
||||
if (!providerId) return false;
|
||||
const plugin = getProviderPlugin(providerId);
|
||||
if (!plugin?.actions?.extractToolSend) return false;
|
||||
return Boolean(plugin.actions.extractToolSend({ args })?.to);
|
||||
}
|
||||
|
||||
export function normalizeTargetForProvider(
|
||||
@@ -107,14 +40,10 @@ export function normalizeTargetForProvider(
|
||||
raw?: string,
|
||||
): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
switch (provider.trim().toLowerCase()) {
|
||||
case "slack":
|
||||
return normalizeSlackTarget(raw);
|
||||
case "discord":
|
||||
return normalizeDiscordTarget(raw);
|
||||
case "telegram":
|
||||
return normalizeTelegramTarget(raw);
|
||||
default:
|
||||
return raw.trim().toLowerCase() || undefined;
|
||||
}
|
||||
const providerId = normalizeProviderId(provider);
|
||||
const plugin = providerId ? getProviderPlugin(providerId) : undefined;
|
||||
const normalized =
|
||||
plugin?.messaging?.normalizeTarget?.(raw) ??
|
||||
(raw.trim().toLowerCase() || undefined);
|
||||
return normalized || undefined;
|
||||
}
|
||||
|
||||
@@ -117,6 +117,7 @@ import {
|
||||
type SkillSnapshot,
|
||||
} from "./skills.js";
|
||||
import { buildAgentSystemPrompt } from "./system-prompt.js";
|
||||
import { buildToolSummaryMap } from "./tool-summaries.js";
|
||||
import { normalizeUsage, type UsageLike } from "./usage.js";
|
||||
import {
|
||||
filterBootstrapFilesForSession,
|
||||
@@ -644,6 +645,7 @@ function buildEmbeddedSystemPrompt(params: {
|
||||
runtimeInfo: params.runtimeInfo,
|
||||
sandboxInfo: params.sandboxInfo,
|
||||
toolNames: params.tools.map((tool) => tool.name),
|
||||
toolSummaries: buildToolSummaryMap(params.tools),
|
||||
modelAliasLines: params.modelAliasLines,
|
||||
userTimezone: params.userTimezone,
|
||||
userTime: params.userTime,
|
||||
|
||||
@@ -9,6 +9,10 @@ import { formatToolAggregate } from "../auto-reply/tool-meta.js";
|
||||
import { resolveStateDir } from "../config/paths.js";
|
||||
import { emitAgentEvent } from "../infra/agent-events.js";
|
||||
import { createSubsystemLogger } from "../logging.js";
|
||||
import {
|
||||
getProviderPlugin,
|
||||
normalizeProviderId,
|
||||
} from "../providers/plugins/index.js";
|
||||
import { truncateUtf16Safe } from "../utils.js";
|
||||
import type { BlockReplyChunking } from "./pi-embedded-block-chunker.js";
|
||||
import { EmbeddedBlockChunker } from "./pi-embedded-block-chunker.js";
|
||||
@@ -142,59 +146,37 @@ function extractMessagingToolSend(
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): MessagingToolSend | undefined {
|
||||
// Provider docking: new provider tools must implement plugin.actions.extractToolSend.
|
||||
const action = typeof args.action === "string" ? args.action.trim() : "";
|
||||
const accountIdRaw =
|
||||
typeof args.accountId === "string" ? args.accountId.trim() : undefined;
|
||||
const accountId = accountIdRaw ? accountIdRaw : undefined;
|
||||
if (toolName === "slack") {
|
||||
if (action !== "sendMessage") return undefined;
|
||||
const toRaw = typeof args.to === "string" ? args.to : undefined;
|
||||
if (!toRaw) return undefined;
|
||||
const to = normalizeTargetForProvider("slack", toRaw);
|
||||
return to
|
||||
? { tool: toolName, provider: "slack", accountId, to }
|
||||
: undefined;
|
||||
}
|
||||
if (toolName === "discord") {
|
||||
if (action === "sendMessage") {
|
||||
const toRaw = typeof args.to === "string" ? args.to : undefined;
|
||||
if (!toRaw) return undefined;
|
||||
const to = normalizeTargetForProvider("discord", toRaw);
|
||||
return to
|
||||
? { tool: toolName, provider: "discord", accountId, to }
|
||||
: undefined;
|
||||
}
|
||||
if (action === "threadReply") {
|
||||
const channelId =
|
||||
typeof args.channelId === "string" ? args.channelId.trim() : "";
|
||||
if (!channelId) return undefined;
|
||||
const to = normalizeTargetForProvider("discord", `channel:${channelId}`);
|
||||
return to
|
||||
? { tool: toolName, provider: "discord", accountId, to }
|
||||
: undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (toolName === "telegram") {
|
||||
if (action !== "sendMessage") return undefined;
|
||||
const toRaw = typeof args.to === "string" ? args.to : undefined;
|
||||
if (!toRaw) return undefined;
|
||||
const to = normalizeTargetForProvider("telegram", toRaw);
|
||||
return to
|
||||
? { tool: toolName, provider: "telegram", accountId, to }
|
||||
: undefined;
|
||||
}
|
||||
if (toolName === "message") {
|
||||
if (action !== "send" && action !== "thread-reply") return undefined;
|
||||
const toRaw = typeof args.to === "string" ? args.to : undefined;
|
||||
if (!toRaw) return undefined;
|
||||
const providerRaw =
|
||||
typeof args.provider === "string" ? args.provider.trim() : "";
|
||||
const provider = providerRaw ? providerRaw.toLowerCase() : "message";
|
||||
const providerId = providerRaw ? normalizeProviderId(providerRaw) : null;
|
||||
const provider =
|
||||
providerId ?? (providerRaw ? providerRaw.toLowerCase() : "message");
|
||||
const to = normalizeTargetForProvider(provider, toRaw);
|
||||
return to ? { tool: toolName, provider, accountId, to } : undefined;
|
||||
}
|
||||
return undefined;
|
||||
const providerId = normalizeProviderId(toolName);
|
||||
if (!providerId) return undefined;
|
||||
const plugin = getProviderPlugin(providerId);
|
||||
const extracted = plugin?.actions?.extractToolSend?.({ args });
|
||||
if (!extracted?.to) return undefined;
|
||||
const to = normalizeTargetForProvider(providerId, extracted.to);
|
||||
return to
|
||||
? {
|
||||
tool: toolName,
|
||||
provider: providerId,
|
||||
accountId: extracted.accountId ?? accountId,
|
||||
to,
|
||||
}
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function subscribeEmbeddedPiSession(params: {
|
||||
@@ -564,7 +546,10 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
typeof argsRecord.action === "string"
|
||||
? argsRecord.action.trim()
|
||||
: "";
|
||||
const isMessagingSend = isMessagingToolSendAction(toolName, action);
|
||||
const isMessagingSend = isMessagingToolSendAction(
|
||||
toolName,
|
||||
argsRecord,
|
||||
);
|
||||
if (isMessagingSend) {
|
||||
const sendTarget = extractMessagingToolSend(toolName, argsRecord);
|
||||
if (sendTarget) {
|
||||
|
||||
+3
-72
@@ -6,12 +6,10 @@ import {
|
||||
createWriteTool,
|
||||
readTool,
|
||||
} from "@mariozechner/pi-coding-agent";
|
||||
import { Type } from "@sinclair/typebox";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { detectMime } from "../media/mime.js";
|
||||
import { isSubagentSessionKey } from "../routing/session-key.js";
|
||||
import { resolveGatewayMessageProvider } from "../utils/message-provider.js";
|
||||
import { startWebLoginWithQr, waitForWebLogin } from "../web/login-qr.js";
|
||||
import {
|
||||
resolveAgentConfig,
|
||||
resolveAgentIdFromSessionKey,
|
||||
@@ -24,6 +22,7 @@ import {
|
||||
} from "./bash-tools.js";
|
||||
import { createClawdbotTools } from "./clawdbot-tools.js";
|
||||
import type { ModelAuthMode } from "./model-auth.js";
|
||||
import { listProviderAgentTools } from "./provider-tools.js";
|
||||
import type { SandboxContext, SandboxToolPolicy } from "./sandbox.js";
|
||||
import { assertSandboxPath } from "./sandbox-paths.js";
|
||||
import { cleanSchemaForGemini } from "./schema/clean-for-gemini.js";
|
||||
@@ -400,75 +399,6 @@ function createSandboxedEditTool(root: string) {
|
||||
return wrapSandboxPathGuard(base as unknown as AnyAgentTool, root);
|
||||
}
|
||||
|
||||
function createWhatsAppLoginTool(): AnyAgentTool {
|
||||
return {
|
||||
label: "WhatsApp Login",
|
||||
name: "whatsapp_login",
|
||||
description:
|
||||
"Generate a WhatsApp QR code for linking, or wait for the scan to complete.",
|
||||
// NOTE: Using Type.Unsafe for action enum instead of Type.Union([Type.Literal(...)])
|
||||
// because Claude API on Vertex AI rejects nested anyOf schemas as invalid JSON Schema.
|
||||
parameters: Type.Object({
|
||||
action: Type.Unsafe<"start" | "wait">({
|
||||
type: "string",
|
||||
enum: ["start", "wait"],
|
||||
}),
|
||||
timeoutMs: Type.Optional(Type.Number()),
|
||||
force: Type.Optional(Type.Boolean()),
|
||||
}),
|
||||
execute: async (_toolCallId, args) => {
|
||||
const action = (args as { action?: string })?.action ?? "start";
|
||||
if (action === "wait") {
|
||||
const result = await waitForWebLogin({
|
||||
timeoutMs:
|
||||
typeof (args as { timeoutMs?: unknown }).timeoutMs === "number"
|
||||
? (args as { timeoutMs?: number }).timeoutMs
|
||||
: undefined,
|
||||
});
|
||||
return {
|
||||
content: [{ type: "text", text: result.message }],
|
||||
details: { connected: result.connected },
|
||||
};
|
||||
}
|
||||
|
||||
const result = await startWebLoginWithQr({
|
||||
timeoutMs:
|
||||
typeof (args as { timeoutMs?: unknown }).timeoutMs === "number"
|
||||
? (args as { timeoutMs?: number }).timeoutMs
|
||||
: undefined,
|
||||
force:
|
||||
typeof (args as { force?: unknown }).force === "boolean"
|
||||
? (args as { force?: boolean }).force
|
||||
: false,
|
||||
});
|
||||
|
||||
if (!result.qrDataUrl) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: result.message,
|
||||
},
|
||||
],
|
||||
details: { qr: false },
|
||||
};
|
||||
}
|
||||
|
||||
const text = [
|
||||
result.message,
|
||||
"",
|
||||
"Open WhatsApp → Linked Devices and scan:",
|
||||
"",
|
||||
``,
|
||||
].join("\n");
|
||||
return {
|
||||
content: [{ type: "text", text }],
|
||||
details: { qr: true },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createClawdbotReadTool(base: AnyAgentTool): AnyAgentTool {
|
||||
return {
|
||||
...base,
|
||||
@@ -635,7 +565,8 @@ export function createClawdbotCodingTools(options?: {
|
||||
: []),
|
||||
bashTool as unknown as AnyAgentTool,
|
||||
processTool as unknown as AnyAgentTool,
|
||||
createWhatsAppLoginTool(),
|
||||
// Provider docking: include provider-defined agent tools (login, etc.).
|
||||
...listProviderAgentTools({ cfg: options?.config }),
|
||||
...createClawdbotTools({
|
||||
browserControlUrl: sandbox?.browser?.controlUrl,
|
||||
allowHostBrowserControl: sandbox ? sandbox.browserAllowHostControl : true,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { listProviderPlugins } from "../providers/plugins/index.js";
|
||||
import type { ProviderAgentTool } from "../providers/plugins/types.js";
|
||||
|
||||
export function listProviderAgentTools(params: {
|
||||
cfg?: ClawdbotConfig;
|
||||
}): ProviderAgentTool[] {
|
||||
// Provider docking: aggregate provider-owned tools (login, etc.).
|
||||
const tools: ProviderAgentTool[] = [];
|
||||
for (const plugin of listProviderPlugins()) {
|
||||
const entry = plugin.agentTools;
|
||||
if (!entry) continue;
|
||||
const resolved = typeof entry === "function" ? entry(params) : entry;
|
||||
if (Array.isArray(resolved)) tools.push(...resolved);
|
||||
}
|
||||
return tools;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
loadConfig,
|
||||
STATE_DIR_CLAWDBOT,
|
||||
} from "../config/config.js";
|
||||
import { PROVIDER_IDS } from "../providers/registry.js";
|
||||
import {
|
||||
buildAgentMainSessionKey,
|
||||
normalizeAgentId,
|
||||
@@ -176,13 +177,14 @@ const DEFAULT_TOOL_ALLOW = [
|
||||
"sessions_spawn",
|
||||
"session_status",
|
||||
];
|
||||
// Provider docking: keep sandbox policy aligned with provider tool names.
|
||||
const DEFAULT_TOOL_DENY = [
|
||||
"browser",
|
||||
"canvas",
|
||||
"nodes",
|
||||
"cron",
|
||||
"discord",
|
||||
"gateway",
|
||||
...PROVIDER_IDS,
|
||||
];
|
||||
export const DEFAULT_SANDBOX_BROWSER_IMAGE =
|
||||
"clawdbot-sandbox-browser:bookworm-slim";
|
||||
|
||||
+22
-14
@@ -1,7 +1,10 @@
|
||||
import type { ReasoningLevel, ThinkLevel } from "../auto-reply/thinking.js";
|
||||
import { SILENT_REPLY_TOKEN } from "../auto-reply/tokens.js";
|
||||
import { PROVIDER_IDS } from "../providers/registry.js";
|
||||
import type { EmbeddedContextFile } from "./pi-embedded-helpers.js";
|
||||
|
||||
const MESSAGE_PROVIDER_OPTIONS = PROVIDER_IDS.join("|");
|
||||
|
||||
export function buildAgentSystemPrompt(params: {
|
||||
workspaceDir: string;
|
||||
defaultThinkLevel?: ThinkLevel;
|
||||
@@ -10,6 +13,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
ownerNumbers?: string[];
|
||||
reasoningTagHint?: boolean;
|
||||
toolNames?: string[];
|
||||
toolSummaries?: Record<string, string>;
|
||||
modelAliasLines?: string[];
|
||||
userTimezone?: string;
|
||||
userTime?: string;
|
||||
@@ -42,7 +46,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
};
|
||||
};
|
||||
}) {
|
||||
const toolSummaries: Record<string, string> = {
|
||||
const coreToolSummaries: Record<string, string> = {
|
||||
read: "Read file contents",
|
||||
write: "Create or overwrite files",
|
||||
edit: "Make precise edits to files",
|
||||
@@ -51,7 +55,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
ls: "List directory contents",
|
||||
bash: "Run shell commands",
|
||||
process: "Manage background bash sessions",
|
||||
whatsapp_login: "Generate and wait for WhatsApp QR login",
|
||||
// Provider docking: add provider login tools here when a provider needs interactive linking.
|
||||
browser: "Control web browser",
|
||||
canvas: "Present/eval/snapshot the Canvas",
|
||||
nodes: "List/describe/notify/camera/screen on paired nodes",
|
||||
@@ -78,7 +82,6 @@ export function buildAgentSystemPrompt(params: {
|
||||
"ls",
|
||||
"bash",
|
||||
"process",
|
||||
"whatsapp_login",
|
||||
"browser",
|
||||
"canvas",
|
||||
"nodes",
|
||||
@@ -107,17 +110,25 @@ export function buildAgentSystemPrompt(params: {
|
||||
|
||||
const normalizedTools = canonicalToolNames.map((tool) => tool.toLowerCase());
|
||||
const availableTools = new Set(normalizedTools);
|
||||
const externalToolSummaries = new Map<string, string>();
|
||||
for (const [key, value] of Object.entries(params.toolSummaries ?? {})) {
|
||||
const normalized = key.trim().toLowerCase();
|
||||
if (!normalized || !value?.trim()) continue;
|
||||
externalToolSummaries.set(normalized, value.trim());
|
||||
}
|
||||
const extraTools = Array.from(
|
||||
new Set(normalizedTools.filter((tool) => !toolOrder.includes(tool))),
|
||||
);
|
||||
const enabledTools = toolOrder.filter((tool) => availableTools.has(tool));
|
||||
const toolLines = enabledTools.map((tool) => {
|
||||
const summary = toolSummaries[tool];
|
||||
const summary = coreToolSummaries[tool] ?? externalToolSummaries.get(tool);
|
||||
const name = resolveToolName(tool);
|
||||
return summary ? `- ${name}: ${summary}` : `- ${name}`;
|
||||
});
|
||||
for (const tool of extraTools.sort()) {
|
||||
toolLines.push(`- ${resolveToolName(tool)}`);
|
||||
const summary = coreToolSummaries[tool] ?? externalToolSummaries.get(tool);
|
||||
const name = resolveToolName(tool);
|
||||
toolLines.push(summary ? `- ${name}: ${summary}` : `- ${name}`);
|
||||
}
|
||||
|
||||
const hasGateway = availableTools.has("gateway");
|
||||
@@ -160,9 +171,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
const runtimeCapabilitiesLower = new Set(
|
||||
runtimeCapabilities.map((cap) => cap.toLowerCase()),
|
||||
);
|
||||
const telegramInlineButtonsEnabled =
|
||||
runtimeProvider === "telegram" &&
|
||||
runtimeCapabilitiesLower.has("inlinebuttons");
|
||||
const inlineButtonsEnabled = runtimeCapabilitiesLower.has("inlinebuttons");
|
||||
const skillsLines = skillsPrompt ? [skillsPrompt, ""] : [];
|
||||
const skillsSection = skillsPrompt
|
||||
? [
|
||||
@@ -188,7 +197,6 @@ export function buildAgentSystemPrompt(params: {
|
||||
"- ls: list directory contents",
|
||||
`- ${bashToolName}: run shell commands (supports background via yieldMs/background)`,
|
||||
`- ${processToolName}: manage background bash sessions`,
|
||||
"- whatsapp_login: generate a WhatsApp QR code and wait for linking",
|
||||
"- browser: control clawd's dedicated browser",
|
||||
"- canvas: present/eval/snapshot the Canvas",
|
||||
"- nodes: list/describe/notify/camera/screen on paired nodes",
|
||||
@@ -314,11 +322,11 @@ export function buildAgentSystemPrompt(params: {
|
||||
"### message tool",
|
||||
"- Use `message` for proactive sends + provider actions (polls, reactions, etc.).",
|
||||
"- For `action=send`, include `to` and `message`.",
|
||||
"- If multiple providers are configured, pass `provider` (whatsapp|telegram|discord|slack|signal|imessage|msteams).",
|
||||
telegramInlineButtonsEnabled
|
||||
? "- Telegram: inline buttons supported. Use `action=send` with `buttons=[[{text,callback_data}]]` (callback_data routes back as a user message)."
|
||||
: runtimeProvider === "telegram"
|
||||
? '- Telegram: inline buttons NOT enabled. If you need them, ask to add "inlineButtons" to telegram.capabilities or telegram.accounts.<id>.capabilities.'
|
||||
`- If multiple providers are configured, pass \`provider\` (${MESSAGE_PROVIDER_OPTIONS}).`,
|
||||
inlineButtonsEnabled
|
||||
? "- Inline buttons supported. Use `action=send` with `buttons=[[{text,callback_data}]]` (callback_data routes back as a user message)."
|
||||
: runtimeProvider
|
||||
? `- Inline buttons not enabled for ${runtimeProvider}. If you need them, ask to add "inlineButtons" to ${runtimeProvider}.capabilities or ${runtimeProvider}.accounts.<id>.capabilities.`
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { AgentTool } from "@mariozechner/pi-agent-core";
|
||||
|
||||
export function buildToolSummaryMap(
|
||||
tools: AgentTool[],
|
||||
): Record<string, string> {
|
||||
const summaries: Record<string, string> = {};
|
||||
for (const tool of tools) {
|
||||
const summary = tool.description?.trim() || tool.label?.trim();
|
||||
if (!summary) continue;
|
||||
summaries[tool.name.toLowerCase()] = summary;
|
||||
}
|
||||
return summaries;
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { callGateway } from "../../gateway/call.js";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
} from "../../utils/message-provider.js";
|
||||
|
||||
export const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789";
|
||||
|
||||
@@ -39,7 +43,8 @@ export async function callGatewayTool<T = unknown>(
|
||||
params,
|
||||
timeoutMs: gateway.timeoutMs,
|
||||
expectFinal: extra?.expectFinal,
|
||||
clientName: "agent",
|
||||
mode: "agent",
|
||||
clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
|
||||
clientDisplayName: "agent",
|
||||
mode: GATEWAY_CLIENT_MODES.BACKEND,
|
||||
});
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,8 @@
|
||||
import { callGateway } from "../../gateway/call.js";
|
||||
import {
|
||||
getProviderPlugin,
|
||||
normalizeProviderId,
|
||||
} from "../../providers/plugins/index.js";
|
||||
import type { AnnounceTarget } from "./sessions-send-helpers.js";
|
||||
import { resolveAnnounceTargetFromKey } from "./sessions-send-helpers.js";
|
||||
|
||||
@@ -10,9 +14,13 @@ export async function resolveAnnounceTarget(params: {
|
||||
const parsedDisplay = resolveAnnounceTargetFromKey(params.displayKey);
|
||||
const fallback = parsed ?? parsedDisplay ?? null;
|
||||
|
||||
// Most providers can derive (provider,to) from the session key directly.
|
||||
// WhatsApp is special: we may need lastAccountId from the session store.
|
||||
if (fallback && fallback.provider !== "whatsapp") return fallback;
|
||||
if (fallback) {
|
||||
const normalized = normalizeProviderId(fallback.provider);
|
||||
const plugin = normalized ? getProviderPlugin(normalized) : null;
|
||||
if (!plugin?.meta?.preferSessionLookupForAnnounceTarget) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const list = (await callGateway({
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import {
|
||||
getProviderPlugin,
|
||||
normalizeProviderId,
|
||||
} from "../../providers/plugins/index.js";
|
||||
|
||||
const ANNOUNCE_SKIP_TOKEN = "ANNOUNCE_SKIP";
|
||||
const REPLY_SKIP_TOKEN = "REPLY_SKIP";
|
||||
@@ -25,14 +29,19 @@ export function resolveAnnounceTargetFromKey(
|
||||
const id = rest.join(":").trim();
|
||||
if (!id) return null;
|
||||
if (!providerRaw) return null;
|
||||
const provider = providerRaw.toLowerCase();
|
||||
if (provider === "discord") {
|
||||
return { provider, to: `channel:${id}` };
|
||||
}
|
||||
if (provider === "signal") {
|
||||
return { provider, to: `group:${id}` };
|
||||
}
|
||||
return { provider, to: id };
|
||||
const normalizedProvider = normalizeProviderId(providerRaw);
|
||||
const provider = normalizedProvider ?? providerRaw.toLowerCase();
|
||||
const kindTarget = normalizedProvider
|
||||
? kind === "channel"
|
||||
? `channel:${id}`
|
||||
: `group:${id}`
|
||||
: id;
|
||||
const normalized = normalizedProvider
|
||||
? getProviderPlugin(normalizedProvider)?.messaging?.normalizeTarget?.(
|
||||
kindTarget,
|
||||
)
|
||||
: undefined;
|
||||
return { provider, to: normalized ?? kindTarget };
|
||||
}
|
||||
|
||||
export function buildAgentToAgentMessageContext(params: {
|
||||
|
||||
@@ -117,7 +117,12 @@ describe("resolveTextChunkLimit", () => {
|
||||
expect(resolveTextChunkLimit(undefined, "slack")).toBe(4000);
|
||||
expect(resolveTextChunkLimit(undefined, "signal")).toBe(4000);
|
||||
expect(resolveTextChunkLimit(undefined, "imessage")).toBe(4000);
|
||||
expect(resolveTextChunkLimit(undefined, "discord")).toBe(2000);
|
||||
expect(resolveTextChunkLimit(undefined, "discord")).toBe(4000);
|
||||
expect(
|
||||
resolveTextChunkLimit(undefined, "discord", undefined, {
|
||||
fallbackLimit: 2000,
|
||||
}),
|
||||
).toBe(2000);
|
||||
});
|
||||
|
||||
it("supports provider overrides", () => {
|
||||
|
||||
+42
-59
@@ -8,80 +8,63 @@ import {
|
||||
isSafeFenceBreak,
|
||||
parseFenceSpans,
|
||||
} from "../markdown/fences.js";
|
||||
import type { ProviderId } from "../providers/plugins/types.js";
|
||||
import { normalizeAccountId } from "../routing/session-key.js";
|
||||
import { INTERNAL_MESSAGE_PROVIDER } from "../utils/message-provider.js";
|
||||
|
||||
export type TextChunkProvider =
|
||||
| "whatsapp"
|
||||
| "telegram"
|
||||
| "discord"
|
||||
| "slack"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "webchat"
|
||||
| "msteams";
|
||||
export type TextChunkProvider = ProviderId | typeof INTERNAL_MESSAGE_PROVIDER;
|
||||
|
||||
const DEFAULT_CHUNK_LIMIT_BY_PROVIDER: Record<TextChunkProvider, number> = {
|
||||
whatsapp: 4000,
|
||||
telegram: 4000,
|
||||
discord: 2000,
|
||||
slack: 4000,
|
||||
signal: 4000,
|
||||
imessage: 4000,
|
||||
webchat: 4000,
|
||||
msteams: 4000,
|
||||
const DEFAULT_CHUNK_LIMIT = 4000;
|
||||
|
||||
type ProviderChunkConfig = {
|
||||
textChunkLimit?: number;
|
||||
accounts?: Record<string, { textChunkLimit?: number }>;
|
||||
};
|
||||
|
||||
function resolveChunkLimitForProvider(
|
||||
cfgSection: ProviderChunkConfig | undefined,
|
||||
accountId?: string | null,
|
||||
): number | undefined {
|
||||
if (!cfgSection) return undefined;
|
||||
const normalizedAccountId = normalizeAccountId(accountId);
|
||||
const accounts = cfgSection.accounts;
|
||||
if (accounts && typeof accounts === "object") {
|
||||
const direct = accounts[normalizedAccountId];
|
||||
if (typeof direct?.textChunkLimit === "number") {
|
||||
return direct.textChunkLimit;
|
||||
}
|
||||
const matchKey = Object.keys(accounts).find(
|
||||
(key) => key.toLowerCase() === normalizedAccountId.toLowerCase(),
|
||||
);
|
||||
const match = matchKey ? accounts[matchKey] : undefined;
|
||||
if (typeof match?.textChunkLimit === "number") {
|
||||
return match.textChunkLimit;
|
||||
}
|
||||
}
|
||||
return cfgSection.textChunkLimit;
|
||||
}
|
||||
|
||||
export function resolveTextChunkLimit(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
provider?: TextChunkProvider,
|
||||
accountId?: string | null,
|
||||
opts?: { fallbackLimit?: number },
|
||||
): number {
|
||||
const fallback =
|
||||
typeof opts?.fallbackLimit === "number" && opts.fallbackLimit > 0
|
||||
? opts.fallbackLimit
|
||||
: DEFAULT_CHUNK_LIMIT;
|
||||
const providerOverride = (() => {
|
||||
if (!provider) return undefined;
|
||||
const normalizedAccountId = normalizeAccountId(accountId);
|
||||
if (provider === "whatsapp") {
|
||||
return cfg?.whatsapp?.textChunkLimit;
|
||||
}
|
||||
if (provider === "telegram") {
|
||||
return (
|
||||
cfg?.telegram?.accounts?.[normalizedAccountId]?.textChunkLimit ??
|
||||
cfg?.telegram?.textChunkLimit
|
||||
);
|
||||
}
|
||||
if (provider === "discord") {
|
||||
return (
|
||||
cfg?.discord?.accounts?.[normalizedAccountId]?.textChunkLimit ??
|
||||
cfg?.discord?.textChunkLimit
|
||||
);
|
||||
}
|
||||
if (provider === "slack") {
|
||||
return (
|
||||
cfg?.slack?.accounts?.[normalizedAccountId]?.textChunkLimit ??
|
||||
cfg?.slack?.textChunkLimit
|
||||
);
|
||||
}
|
||||
if (provider === "signal") {
|
||||
return (
|
||||
cfg?.signal?.accounts?.[normalizedAccountId]?.textChunkLimit ??
|
||||
cfg?.signal?.textChunkLimit
|
||||
);
|
||||
}
|
||||
if (provider === "imessage") {
|
||||
return (
|
||||
cfg?.imessage?.accounts?.[normalizedAccountId]?.textChunkLimit ??
|
||||
cfg?.imessage?.textChunkLimit
|
||||
);
|
||||
}
|
||||
if (provider === "msteams") {
|
||||
return cfg?.msteams?.textChunkLimit;
|
||||
}
|
||||
return undefined;
|
||||
if (!provider || provider === INTERNAL_MESSAGE_PROVIDER) return undefined;
|
||||
const providerConfig = (cfg as Record<string, unknown> | undefined)?.[
|
||||
provider
|
||||
] as ProviderChunkConfig | undefined;
|
||||
return resolveChunkLimitForProvider(providerConfig, accountId);
|
||||
})();
|
||||
if (typeof providerOverride === "number" && providerOverride > 0) {
|
||||
return providerOverride;
|
||||
}
|
||||
if (provider) return DEFAULT_CHUNK_LIMIT_BY_PROVIDER[provider];
|
||||
return 4000;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function chunkText(text: string, limit: number): string[] {
|
||||
|
||||
@@ -1,72 +1,123 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { normalizeE164 } from "../utils.js";
|
||||
import type { ProviderDock } from "../providers/dock.js";
|
||||
import { getProviderDock, listProviderDocks } from "../providers/dock.js";
|
||||
import type { ProviderId } from "../providers/plugins/types.js";
|
||||
import { normalizeProviderId } from "../providers/registry.js";
|
||||
import type { MsgContext } from "./templating.js";
|
||||
|
||||
export type CommandAuthorization = {
|
||||
isWhatsAppProvider: boolean;
|
||||
providerId?: ProviderId;
|
||||
ownerList: string[];
|
||||
senderE164?: string;
|
||||
senderId?: string;
|
||||
isAuthorizedSender: boolean;
|
||||
from?: string;
|
||||
to?: string;
|
||||
};
|
||||
|
||||
function resolveProviderFromContext(
|
||||
ctx: MsgContext,
|
||||
cfg: ClawdbotConfig,
|
||||
): ProviderId | undefined {
|
||||
const direct =
|
||||
normalizeProviderId(ctx.Provider) ??
|
||||
normalizeProviderId(ctx.Surface) ??
|
||||
normalizeProviderId(ctx.OriginatingChannel);
|
||||
if (direct) return direct;
|
||||
const candidates = [ctx.From, ctx.To]
|
||||
.filter((value): value is string => Boolean(value?.trim()))
|
||||
.flatMap((value) => value.split(":").map((part) => part.trim()));
|
||||
for (const candidate of candidates) {
|
||||
const normalized = normalizeProviderId(candidate);
|
||||
if (normalized) return normalized;
|
||||
}
|
||||
const configured = listProviderDocks()
|
||||
.map((dock) => {
|
||||
if (!dock.config?.resolveAllowFrom) return null;
|
||||
const allowFrom = dock.config.resolveAllowFrom({
|
||||
cfg,
|
||||
accountId: ctx.AccountId,
|
||||
});
|
||||
if (!Array.isArray(allowFrom) || allowFrom.length === 0) return null;
|
||||
return dock.id;
|
||||
})
|
||||
.filter((value): value is ProviderId => Boolean(value));
|
||||
if (configured.length === 1) return configured[0];
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function formatAllowFromList(params: {
|
||||
dock?: ProviderDock;
|
||||
cfg: ClawdbotConfig;
|
||||
accountId?: string | null;
|
||||
allowFrom: Array<string | number>;
|
||||
}): string[] {
|
||||
const { dock, cfg, accountId, allowFrom } = params;
|
||||
if (!allowFrom || allowFrom.length === 0) return [];
|
||||
if (dock?.config?.formatAllowFrom) {
|
||||
return dock.config.formatAllowFrom({ cfg, accountId, allowFrom });
|
||||
}
|
||||
return allowFrom.map((entry) => String(entry).trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export function resolveCommandAuthorization(params: {
|
||||
ctx: MsgContext;
|
||||
cfg: ClawdbotConfig;
|
||||
commandAuthorized: boolean;
|
||||
}): CommandAuthorization {
|
||||
const { ctx, cfg, commandAuthorized } = params;
|
||||
const provider = (ctx.Provider ?? "").trim().toLowerCase();
|
||||
const from = (ctx.From ?? "").replace(/^whatsapp:/, "");
|
||||
const to = (ctx.To ?? "").replace(/^whatsapp:/, "");
|
||||
const hasWhatsappPrefix =
|
||||
(ctx.From ?? "").startsWith("whatsapp:") ||
|
||||
(ctx.To ?? "").startsWith("whatsapp:");
|
||||
const looksLikeE164 = (value: string) =>
|
||||
Boolean(value && /^\+?\d{3,}$/.test(value.replace(/[^\d+]/g, "")));
|
||||
const inferWhatsApp =
|
||||
!provider &&
|
||||
Boolean(cfg.whatsapp?.allowFrom?.length) &&
|
||||
(looksLikeE164(from) || looksLikeE164(to));
|
||||
const isWhatsAppProvider =
|
||||
provider === "whatsapp" || hasWhatsappPrefix || inferWhatsApp;
|
||||
|
||||
const configuredAllowFrom = isWhatsAppProvider
|
||||
? cfg.whatsapp?.allowFrom
|
||||
: undefined;
|
||||
const allowFromList =
|
||||
configuredAllowFrom?.filter((entry) => entry?.trim()) ?? [];
|
||||
const providerId = resolveProviderFromContext(ctx, cfg);
|
||||
const dock = providerId ? getProviderDock(providerId) : undefined;
|
||||
const from = (ctx.From ?? "").trim();
|
||||
const to = (ctx.To ?? "").trim();
|
||||
const allowFromRaw = dock?.config?.resolveAllowFrom
|
||||
? dock.config.resolveAllowFrom({ cfg, accountId: ctx.AccountId })
|
||||
: [];
|
||||
const allowFromList = formatAllowFromList({
|
||||
dock,
|
||||
cfg,
|
||||
accountId: ctx.AccountId,
|
||||
allowFrom: Array.isArray(allowFromRaw) ? allowFromRaw : [],
|
||||
});
|
||||
const allowAll =
|
||||
!isWhatsAppProvider ||
|
||||
allowFromList.length === 0 ||
|
||||
allowFromList.some((entry) => entry.trim() === "*");
|
||||
|
||||
const senderE164 = normalizeE164(
|
||||
ctx.SenderE164 ?? (isWhatsAppProvider ? from : ""),
|
||||
);
|
||||
const ownerCandidates =
|
||||
isWhatsAppProvider && !allowAll
|
||||
? allowFromList.filter((entry) => entry !== "*")
|
||||
: [];
|
||||
if (isWhatsAppProvider && !allowAll && ownerCandidates.length === 0 && to) {
|
||||
ownerCandidates.push(to);
|
||||
const ownerCandidates = allowAll
|
||||
? []
|
||||
: allowFromList.filter((entry) => entry !== "*");
|
||||
if (!allowAll && ownerCandidates.length === 0 && to) {
|
||||
const normalizedTo = formatAllowFromList({
|
||||
dock,
|
||||
cfg,
|
||||
accountId: ctx.AccountId,
|
||||
allowFrom: [to],
|
||||
})[0];
|
||||
if (normalizedTo) ownerCandidates.push(normalizedTo);
|
||||
}
|
||||
const ownerList = ownerCandidates
|
||||
.map((entry) => normalizeE164(entry))
|
||||
.filter((entry): entry is string => Boolean(entry));
|
||||
const ownerList = ownerCandidates;
|
||||
|
||||
const senderRaw = ctx.SenderId ?? ctx.SenderE164 ?? from;
|
||||
const senderId = senderRaw
|
||||
? formatAllowFromList({
|
||||
dock,
|
||||
cfg,
|
||||
accountId: ctx.AccountId,
|
||||
allowFrom: [senderRaw],
|
||||
})[0]
|
||||
: undefined;
|
||||
|
||||
const enforceOwner = Boolean(dock?.commands?.enforceOwnerForCommands);
|
||||
const isOwner =
|
||||
!isWhatsAppProvider ||
|
||||
!enforceOwner ||
|
||||
allowAll ||
|
||||
ownerList.length === 0 ||
|
||||
(senderE164 ? ownerList.includes(senderE164) : false);
|
||||
(senderId ? ownerList.includes(senderId) : false);
|
||||
const isAuthorizedSender = commandAuthorized && isOwner;
|
||||
|
||||
return {
|
||||
isWhatsAppProvider,
|
||||
providerId,
|
||||
ownerList,
|
||||
senderE164: senderE164 || undefined,
|
||||
senderId: senderId || undefined,
|
||||
isAuthorizedSender,
|
||||
from: from || undefined,
|
||||
to: to || undefined,
|
||||
|
||||
@@ -43,9 +43,8 @@ describe("control command parsing", () => {
|
||||
expect(hasControlCommand("/commands")).toBe(true);
|
||||
expect(hasControlCommand("/commands:")).toBe(true);
|
||||
expect(hasControlCommand("commands")).toBe(false);
|
||||
expect(hasControlCommand("/compact")).toBe(true);
|
||||
expect(hasControlCommand("/compact:")).toBe(true);
|
||||
expect(hasControlCommand("compact")).toBe(false);
|
||||
expect(hasControlCommand("/status")).toBe(true);
|
||||
expect(hasControlCommand("/status:")).toBe(true);
|
||||
expect(hasControlCommand("status")).toBe(false);
|
||||
expect(hasControlCommand("usage")).toBe(false);
|
||||
|
||||
@@ -55,6 +54,9 @@ describe("control command parsing", () => {
|
||||
expect(hasControlCommand(`${alias}:`)).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(hasControlCommand("/compact")).toBe(true);
|
||||
expect(hasControlCommand("/compact:")).toBe(true);
|
||||
expect(hasControlCommand("compact")).toBe(false);
|
||||
});
|
||||
|
||||
it("respects disabled config/debug commands", () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ClawdbotConfig } from "../config/types.js";
|
||||
import { listProviderDocks } from "../providers/dock.js";
|
||||
|
||||
export type CommandScope = "text" | "native" | "both";
|
||||
|
||||
@@ -263,8 +264,18 @@ export const CHAT_COMMANDS: ChatCommandDefinition[] = (() => {
|
||||
assertCommandRegistry(commands);
|
||||
return commands;
|
||||
})();
|
||||
let cachedNativeCommandSurfaces: Set<string> | null = null;
|
||||
|
||||
const NATIVE_COMMAND_SURFACES = new Set(["discord", "slack", "telegram"]);
|
||||
const getNativeCommandSurfaces = (): Set<string> => {
|
||||
if (!cachedNativeCommandSurfaces) {
|
||||
cachedNativeCommandSurfaces = new Set(
|
||||
listProviderDocks()
|
||||
.filter((dock) => dock.capabilities.nativeCommands)
|
||||
.map((dock) => dock.id),
|
||||
);
|
||||
}
|
||||
return cachedNativeCommandSurfaces;
|
||||
};
|
||||
|
||||
const TEXT_ALIAS_MAP: Map<string, TextAliasSpec> = (() => {
|
||||
const map = new Map<string, TextAliasSpec>();
|
||||
@@ -354,14 +365,18 @@ export function normalizeCommandBody(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed.startsWith("/")) return trimmed;
|
||||
|
||||
const colonMatch = trimmed.match(/^\/([^\s:]+)\s*:(.*)$/);
|
||||
const newline = trimmed.indexOf("\n");
|
||||
const singleLine =
|
||||
newline === -1 ? trimmed : trimmed.slice(0, newline).trim();
|
||||
|
||||
const colonMatch = singleLine.match(/^\/([^\s:]+)\s*:(.*)$/);
|
||||
const normalized = colonMatch
|
||||
? (() => {
|
||||
const [, command, rest] = colonMatch;
|
||||
const normalizedRest = rest.trimStart();
|
||||
return normalizedRest ? `/${command} ${normalizedRest}` : `/${command}`;
|
||||
})()
|
||||
: trimmed;
|
||||
: singleLine;
|
||||
|
||||
const lowered = normalized.toLowerCase();
|
||||
const exact = TEXT_ALIAS_MAP.get(lowered);
|
||||
@@ -380,44 +395,86 @@ export function normalizeCommandBody(raw: string): string {
|
||||
: tokenSpec.canonical;
|
||||
}
|
||||
|
||||
export function getCommandDetection(): { exact: Set<string>; regex: RegExp } {
|
||||
export function isCommandMessage(raw: string): boolean {
|
||||
const trimmed = normalizeCommandBody(raw);
|
||||
return trimmed.startsWith("/");
|
||||
}
|
||||
|
||||
export function getCommandDetection(_cfg?: ClawdbotConfig): {
|
||||
exact: Set<string>;
|
||||
regex: RegExp;
|
||||
} {
|
||||
if (cachedDetection) return cachedDetection;
|
||||
const exact = new Set<string>();
|
||||
const patterns: string[] = [];
|
||||
for (const command of CHAT_COMMANDS) {
|
||||
for (const alias of command.textAliases) {
|
||||
for (const cmd of CHAT_COMMANDS) {
|
||||
for (const alias of cmd.textAliases) {
|
||||
const normalized = alias.trim().toLowerCase();
|
||||
if (!normalized) continue;
|
||||
exact.add(normalized);
|
||||
const escaped = escapeRegExp(normalized);
|
||||
if (!escaped) continue;
|
||||
if (command.acceptsArgs) {
|
||||
if (cmd.acceptsArgs) {
|
||||
patterns.push(`${escaped}(?:\\s+.+|\\s*:\\s*.*)?`);
|
||||
} else {
|
||||
patterns.push(`${escaped}(?:\\s*:\\s*)?`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const regex = patterns.length
|
||||
? new RegExp(`^(?:${patterns.join("|")})$`, "i")
|
||||
: /$^/;
|
||||
cachedDetection = { exact, regex };
|
||||
cachedDetection = {
|
||||
exact,
|
||||
regex: patterns.length
|
||||
? new RegExp(`^(?:${patterns.join("|")})$`, "i")
|
||||
: /$^/,
|
||||
};
|
||||
return cachedDetection;
|
||||
}
|
||||
|
||||
export function supportsNativeCommands(surface?: string): boolean {
|
||||
export function maybeResolveTextAlias(raw: string, cfg?: ClawdbotConfig) {
|
||||
const trimmed = normalizeCommandBody(raw).trim();
|
||||
if (!trimmed.startsWith("/")) return null;
|
||||
const detection = getCommandDetection(cfg);
|
||||
const normalized = trimmed.toLowerCase();
|
||||
if (detection.exact.has(normalized)) return normalized;
|
||||
if (!detection.regex.test(normalized)) return null;
|
||||
const tokenMatch = normalized.match(/^\/([^\s:]+)(?:\s|$)/);
|
||||
if (!tokenMatch) return null;
|
||||
const tokenKey = `/${tokenMatch[1]}`;
|
||||
return TEXT_ALIAS_MAP.has(tokenKey) ? tokenKey : null;
|
||||
}
|
||||
|
||||
export function resolveTextCommand(
|
||||
raw: string,
|
||||
cfg?: ClawdbotConfig,
|
||||
): {
|
||||
command: ChatCommandDefinition;
|
||||
args?: string;
|
||||
} | null {
|
||||
const trimmed = normalizeCommandBody(raw).trim();
|
||||
const alias = maybeResolveTextAlias(trimmed, cfg);
|
||||
if (!alias) return null;
|
||||
const spec = TEXT_ALIAS_MAP.get(alias);
|
||||
if (!spec) return null;
|
||||
const command = CHAT_COMMANDS.find(
|
||||
(entry) => `/${entry.key}` === spec.canonical,
|
||||
);
|
||||
if (!command) return null;
|
||||
if (!spec.acceptsArgs) return { command };
|
||||
const args = trimmed.slice(alias.length).trim();
|
||||
return { command, args: args || undefined };
|
||||
}
|
||||
|
||||
export function isNativeCommandSurface(surface?: string): boolean {
|
||||
if (!surface) return false;
|
||||
return NATIVE_COMMAND_SURFACES.has(surface.toLowerCase());
|
||||
return getNativeCommandSurfaces().has(surface.toLowerCase());
|
||||
}
|
||||
|
||||
export function shouldHandleTextCommands(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
surface?: string;
|
||||
surface: string;
|
||||
commandSource?: "text" | "native";
|
||||
}): boolean {
|
||||
const { cfg, surface, commandSource } = params;
|
||||
const textEnabled = cfg.commands?.text !== false;
|
||||
if (commandSource === "native") return true;
|
||||
if (textEnabled) return true;
|
||||
return !supportsNativeCommands(surface);
|
||||
if (params.commandSource === "native") return true;
|
||||
if (params.cfg.commands?.text !== false) return true;
|
||||
return !isNativeCommandSurface(params.surface);
|
||||
}
|
||||
|
||||
@@ -800,7 +800,7 @@ describe("trigger handling", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to discord dm allowFrom for elevated approval", async () => {
|
||||
it("uses tools.elevated.allowFrom.discord for elevated approval", async () => {
|
||||
await withTempHome(async (home) => {
|
||||
const cfg = {
|
||||
agents: {
|
||||
@@ -809,11 +809,7 @@ describe("trigger handling", () => {
|
||||
workspace: join(home, "clawd"),
|
||||
},
|
||||
},
|
||||
discord: {
|
||||
dm: {
|
||||
allowFrom: ["steipete"],
|
||||
},
|
||||
},
|
||||
tools: { elevated: { allowFrom: { discord: ["steipete"] } } },
|
||||
session: { store: join(home, "sessions.json") },
|
||||
};
|
||||
|
||||
@@ -856,11 +852,6 @@ describe("trigger handling", () => {
|
||||
allowFrom: { discord: [] },
|
||||
},
|
||||
},
|
||||
discord: {
|
||||
dm: {
|
||||
allowFrom: ["steipete"],
|
||||
},
|
||||
},
|
||||
session: { store: join(home, "sessions.json") },
|
||||
};
|
||||
|
||||
|
||||
+42
-39
@@ -32,8 +32,14 @@ import {
|
||||
import { resolveSessionFilePath } from "../config/sessions.js";
|
||||
import { logVerbose } from "../globals.js";
|
||||
import { clearCommandLane, getQueueSize } from "../process/command-queue.js";
|
||||
import { getProviderDock } from "../providers/dock.js";
|
||||
import {
|
||||
CHAT_PROVIDER_ORDER,
|
||||
normalizeProviderId,
|
||||
} from "../providers/registry.js";
|
||||
import { normalizeMainKey } from "../routing/session-key.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
import { INTERNAL_MESSAGE_PROVIDER } from "../utils/message-provider.js";
|
||||
import { resolveCommandAuthorization } from "./command-auth.js";
|
||||
import { hasControlCommand } from "./command-detection.js";
|
||||
import {
|
||||
@@ -127,53 +133,41 @@ function slugAllowToken(value?: string) {
|
||||
return text.replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
const SENDER_PREFIXES = [
|
||||
...CHAT_PROVIDER_ORDER,
|
||||
INTERNAL_MESSAGE_PROVIDER,
|
||||
"user",
|
||||
"group",
|
||||
"channel",
|
||||
];
|
||||
const SENDER_PREFIX_RE = new RegExp(`^(${SENDER_PREFIXES.join("|")}):`, "i");
|
||||
|
||||
function stripSenderPrefix(value?: string) {
|
||||
if (!value) return "";
|
||||
const trimmed = value.trim();
|
||||
return trimmed.replace(
|
||||
/^(whatsapp|telegram|discord|signal|imessage|webchat|user|group|channel):/i,
|
||||
"",
|
||||
);
|
||||
return trimmed.replace(SENDER_PREFIX_RE, "");
|
||||
}
|
||||
|
||||
function resolveElevatedAllowList(
|
||||
allowFrom: AgentElevatedAllowFromConfig | undefined,
|
||||
provider: string,
|
||||
discordFallback?: Array<string | number>,
|
||||
fallbackAllowFrom?: Array<string | number>,
|
||||
): Array<string | number> | undefined {
|
||||
switch (provider) {
|
||||
case "whatsapp":
|
||||
return allowFrom?.whatsapp;
|
||||
case "telegram":
|
||||
return allowFrom?.telegram;
|
||||
case "discord": {
|
||||
const hasExplicit = Boolean(
|
||||
allowFrom && Object.hasOwn(allowFrom, "discord"),
|
||||
);
|
||||
if (hasExplicit) return allowFrom?.discord;
|
||||
return discordFallback;
|
||||
}
|
||||
case "signal":
|
||||
return allowFrom?.signal;
|
||||
case "imessage":
|
||||
return allowFrom?.imessage;
|
||||
case "webchat":
|
||||
return allowFrom?.webchat;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
if (!allowFrom) return fallbackAllowFrom;
|
||||
const value = allowFrom[provider];
|
||||
return Array.isArray(value) ? value : fallbackAllowFrom;
|
||||
}
|
||||
|
||||
function isApprovedElevatedSender(params: {
|
||||
provider: string;
|
||||
ctx: MsgContext;
|
||||
allowFrom?: AgentElevatedAllowFromConfig;
|
||||
discordFallback?: Array<string | number>;
|
||||
fallbackAllowFrom?: Array<string | number>;
|
||||
}): boolean {
|
||||
const rawAllow = resolveElevatedAllowList(
|
||||
params.allowFrom,
|
||||
params.provider,
|
||||
params.discordFallback,
|
||||
params.fallbackAllowFrom,
|
||||
);
|
||||
if (!rawAllow || rawAllow.length === 0) return false;
|
||||
|
||||
@@ -248,23 +242,24 @@ function resolveElevatedPermissions(params: {
|
||||
return { enabled, allowed: false, failures };
|
||||
}
|
||||
|
||||
const discordFallback =
|
||||
params.provider === "discord"
|
||||
? params.cfg.discord?.dm?.allowFrom
|
||||
: undefined;
|
||||
const normalizedProvider = normalizeProviderId(params.provider);
|
||||
const dockFallbackAllowFrom = normalizedProvider
|
||||
? getProviderDock(normalizedProvider)?.elevated?.allowFromFallback?.({
|
||||
cfg: params.cfg,
|
||||
accountId: params.ctx.AccountId,
|
||||
})
|
||||
: undefined;
|
||||
const fallbackAllowFrom = dockFallbackAllowFrom;
|
||||
const globalAllowed = isApprovedElevatedSender({
|
||||
provider: params.provider,
|
||||
ctx: params.ctx,
|
||||
allowFrom: globalConfig?.allowFrom,
|
||||
discordFallback,
|
||||
fallbackAllowFrom,
|
||||
});
|
||||
if (!globalAllowed) {
|
||||
failures.push({
|
||||
gate: "allowFrom",
|
||||
key:
|
||||
params.provider === "discord" && discordFallback
|
||||
? "tools.elevated.allowFrom.discord (or discord.dm.allowFrom fallback)"
|
||||
: `tools.elevated.allowFrom.${params.provider}`,
|
||||
key: `tools.elevated.allowFrom.${params.provider}`,
|
||||
});
|
||||
return { enabled, allowed: false, failures };
|
||||
}
|
||||
@@ -274,6 +269,7 @@ function resolveElevatedPermissions(params: {
|
||||
provider: params.provider,
|
||||
ctx: params.ctx,
|
||||
allowFrom: agentConfig.allowFrom,
|
||||
fallbackAllowFrom,
|
||||
})
|
||||
: true;
|
||||
if (!agentAllowed) {
|
||||
@@ -605,7 +601,8 @@ export async function getReplyFromConfig(
|
||||
agentCfg?.blockStreamingBreak === "message_end"
|
||||
? "message_end"
|
||||
: "text_end";
|
||||
const blockStreamingEnabled = resolvedBlockStreaming === "on";
|
||||
const blockStreamingEnabled =
|
||||
resolvedBlockStreaming === "on" && opts?.disableBlockStreaming !== true;
|
||||
const blockReplyChunking = blockStreamingEnabled
|
||||
? resolveBlockStreamingChunking(
|
||||
cfg,
|
||||
@@ -782,8 +779,13 @@ export async function getReplyFromConfig(
|
||||
: undefined;
|
||||
|
||||
const isEmptyConfig = Object.keys(cfg).length === 0;
|
||||
const skipWhenConfigEmpty = command.providerId
|
||||
? Boolean(
|
||||
getProviderDock(command.providerId)?.commands?.skipWhenConfigEmpty,
|
||||
)
|
||||
: false;
|
||||
if (
|
||||
command.isWhatsAppProvider &&
|
||||
skipWhenConfigEmpty &&
|
||||
isEmptyConfig &&
|
||||
command.from &&
|
||||
command.to &&
|
||||
@@ -854,6 +856,7 @@ export async function getReplyFromConfig(
|
||||
);
|
||||
const groupIntro = shouldInjectGroupIntro
|
||||
? buildGroupIntro({
|
||||
cfg,
|
||||
sessionCtx,
|
||||
sessionEntry,
|
||||
defaultActivation,
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
runEmbeddedPiAgent,
|
||||
} from "../../agents/pi-embedded.js";
|
||||
import { hasNonzeroUsage, type NormalizedUsage } from "../../agents/usage.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import {
|
||||
loadSessionStore,
|
||||
resolveSessionTranscriptPath,
|
||||
@@ -26,6 +27,9 @@ import {
|
||||
registerAgentRunContext,
|
||||
} from "../../infra/agent-events.js";
|
||||
import { isAudioFileName } from "../../media/mime.js";
|
||||
import { getProviderDock } from "../../providers/dock.js";
|
||||
import type { ProviderThreadingToolContext } from "../../providers/plugins/types.js";
|
||||
import { normalizeProviderId } from "../../providers/registry.js";
|
||||
import { defaultRuntime } from "../../runtime.js";
|
||||
import {
|
||||
estimateUsageCost,
|
||||
@@ -70,47 +74,32 @@ const BUN_FETCH_SOCKET_ERROR_RE = /socket connection was closed unexpectedly/i;
|
||||
const BLOCK_REPLY_SEND_TIMEOUT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Build Slack-specific threading context for tool auto-injection.
|
||||
* Returns undefined values for non-Slack providers.
|
||||
* Build provider-specific threading context for tool auto-injection.
|
||||
*/
|
||||
function buildSlackThreadingContext(params: {
|
||||
function buildThreadingToolContext(params: {
|
||||
sessionCtx: TemplateContext;
|
||||
config: { slack?: { replyToMode?: "off" | "first" | "all" } } | undefined;
|
||||
config: ClawdbotConfig | undefined;
|
||||
hasRepliedRef: { value: boolean } | undefined;
|
||||
}): {
|
||||
currentChannelId: string | undefined;
|
||||
currentThreadTs: string | undefined;
|
||||
replyToMode: "off" | "first" | "all" | undefined;
|
||||
hasRepliedRef: { value: boolean } | undefined;
|
||||
} {
|
||||
}): ProviderThreadingToolContext {
|
||||
const { sessionCtx, config, hasRepliedRef } = params;
|
||||
const isSlack = sessionCtx.Provider?.toLowerCase() === "slack";
|
||||
if (!isSlack) {
|
||||
return {
|
||||
currentChannelId: undefined,
|
||||
currentThreadTs: undefined,
|
||||
replyToMode: undefined,
|
||||
hasRepliedRef: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// If we're already inside a thread, never jump replies out of it (even in
|
||||
// replyToMode="off"/"first"). This keeps tool calls consistent with the
|
||||
// auto-reply path.
|
||||
const configuredReplyToMode = config?.slack?.replyToMode ?? "off";
|
||||
const effectiveReplyToMode = sessionCtx.ThreadLabel
|
||||
? ("all" as const)
|
||||
: configuredReplyToMode;
|
||||
|
||||
return {
|
||||
// Extract channel from "channel:C123" format
|
||||
currentChannelId: sessionCtx.To?.startsWith("channel:")
|
||||
? sessionCtx.To.slice("channel:".length)
|
||||
: undefined,
|
||||
currentThreadTs: sessionCtx.ReplyToId,
|
||||
replyToMode: effectiveReplyToMode,
|
||||
hasRepliedRef,
|
||||
};
|
||||
if (!config) return {};
|
||||
const provider = normalizeProviderId(sessionCtx.Provider);
|
||||
if (!provider) return {};
|
||||
const dock = getProviderDock(provider);
|
||||
if (!dock?.threading?.buildToolContext) return {};
|
||||
return (
|
||||
dock.threading.buildToolContext({
|
||||
cfg: config,
|
||||
accountId: sessionCtx.AccountId,
|
||||
context: {
|
||||
Provider: sessionCtx.Provider,
|
||||
To: sessionCtx.To,
|
||||
ReplyToId: sessionCtx.ReplyToId,
|
||||
ThreadLabel: sessionCtx.ThreadLabel,
|
||||
},
|
||||
hasRepliedRef,
|
||||
}) ?? {}
|
||||
);
|
||||
}
|
||||
|
||||
const isBunFetchSocketError = (message?: string) =>
|
||||
@@ -282,6 +271,7 @@ export async function runReplyAgent(params: {
|
||||
const replyToMode = resolveReplyToMode(
|
||||
followupRun.run.config,
|
||||
replyToChannel,
|
||||
sessionCtx.AccountId,
|
||||
);
|
||||
const applyReplyToMode = createReplyToModeFilterForChannel(
|
||||
replyToMode,
|
||||
@@ -437,8 +427,8 @@ export async function runReplyAgent(params: {
|
||||
messageProvider:
|
||||
sessionCtx.Provider?.trim().toLowerCase() || undefined,
|
||||
agentAccountId: sessionCtx.AccountId,
|
||||
// Slack threading context for tool auto-injection
|
||||
...buildSlackThreadingContext({
|
||||
// Provider threading context for tool auto-injection
|
||||
...buildThreadingToolContext({
|
||||
sessionCtx,
|
||||
config: followupRun.run.config,
|
||||
hasRepliedRef: opts?.hasRepliedRef,
|
||||
|
||||
@@ -1,29 +1,17 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { BlockStreamingCoalesceConfig } from "../../config/types.js";
|
||||
import { getProviderDock } from "../../providers/dock.js";
|
||||
import { normalizeProviderId, PROVIDER_IDS } from "../../providers/registry.js";
|
||||
import { normalizeAccountId } from "../../routing/session-key.js";
|
||||
import { INTERNAL_MESSAGE_PROVIDER } from "../../utils/message-provider.js";
|
||||
import { resolveTextChunkLimit, type TextChunkProvider } from "../chunk.js";
|
||||
|
||||
const DEFAULT_BLOCK_STREAM_MIN = 800;
|
||||
const DEFAULT_BLOCK_STREAM_MAX = 1200;
|
||||
const DEFAULT_BLOCK_STREAM_COALESCE_IDLE_MS = 1000;
|
||||
const DEFAULT_TELEGRAM_DRAFT_STREAM_MIN = 200;
|
||||
const DEFAULT_TELEGRAM_DRAFT_STREAM_MAX = 800;
|
||||
const PROVIDER_COALESCE_DEFAULTS: Partial<
|
||||
Record<TextChunkProvider, { minChars: number; idleMs: number }>
|
||||
> = {
|
||||
signal: { minChars: 1500, idleMs: 1000 },
|
||||
slack: { minChars: 1500, idleMs: 1000 },
|
||||
discord: { minChars: 1500, idleMs: 1000 },
|
||||
};
|
||||
|
||||
const BLOCK_CHUNK_PROVIDERS = new Set<TextChunkProvider>([
|
||||
"whatsapp",
|
||||
"telegram",
|
||||
"discord",
|
||||
"slack",
|
||||
"signal",
|
||||
"imessage",
|
||||
"webchat",
|
||||
"msteams",
|
||||
...PROVIDER_IDS,
|
||||
INTERNAL_MESSAGE_PROVIDER,
|
||||
]);
|
||||
|
||||
function normalizeChunkProvider(
|
||||
@@ -36,6 +24,29 @@ function normalizeChunkProvider(
|
||||
: undefined;
|
||||
}
|
||||
|
||||
type ProviderBlockStreamingConfig = {
|
||||
blockStreamingCoalesce?: BlockStreamingCoalesceConfig;
|
||||
accounts?: Record<
|
||||
string,
|
||||
{ blockStreamingCoalesce?: BlockStreamingCoalesceConfig }
|
||||
>;
|
||||
};
|
||||
|
||||
function resolveProviderBlockStreamingCoalesce(params: {
|
||||
cfg: ClawdbotConfig | undefined;
|
||||
providerKey?: TextChunkProvider;
|
||||
accountId?: string | null;
|
||||
}): BlockStreamingCoalesceConfig | undefined {
|
||||
const { cfg, providerKey, accountId } = params;
|
||||
if (!cfg || !providerKey) return undefined;
|
||||
const providerCfg = (cfg as Record<string, unknown>)[providerKey];
|
||||
if (!providerCfg || typeof providerCfg !== "object") return undefined;
|
||||
const normalizedAccountId = normalizeAccountId(accountId);
|
||||
const typed = providerCfg as ProviderBlockStreamingConfig;
|
||||
const accountCfg = typed.accounts?.[normalizedAccountId];
|
||||
return accountCfg?.blockStreamingCoalesce ?? typed.blockStreamingCoalesce;
|
||||
}
|
||||
|
||||
export type BlockStreamingCoalescing = {
|
||||
minChars: number;
|
||||
maxChars: number;
|
||||
@@ -53,7 +64,13 @@ export function resolveBlockStreamingChunking(
|
||||
breakPreference: "paragraph" | "newline" | "sentence";
|
||||
} {
|
||||
const providerKey = normalizeChunkProvider(provider);
|
||||
const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId);
|
||||
const providerId = providerKey ? normalizeProviderId(providerKey) : null;
|
||||
const providerChunkLimit = providerId
|
||||
? getProviderDock(providerId)?.outbound?.textChunkLimit
|
||||
: undefined;
|
||||
const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId, {
|
||||
fallbackLimit: providerChunkLimit,
|
||||
});
|
||||
const chunkCfg = cfg?.agents?.defaults?.blockStreamingChunk;
|
||||
const maxRequested = Math.max(
|
||||
1,
|
||||
@@ -74,39 +91,6 @@ export function resolveBlockStreamingChunking(
|
||||
return { minChars, maxChars, breakPreference };
|
||||
}
|
||||
|
||||
export function resolveTelegramDraftStreamingChunking(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
accountId?: string | null,
|
||||
): {
|
||||
minChars: number;
|
||||
maxChars: number;
|
||||
breakPreference: "paragraph" | "newline" | "sentence";
|
||||
} {
|
||||
const providerKey: TextChunkProvider = "telegram";
|
||||
const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId);
|
||||
const normalizedAccountId = normalizeAccountId(accountId);
|
||||
const draftCfg =
|
||||
cfg?.telegram?.accounts?.[normalizedAccountId]?.draftChunk ??
|
||||
cfg?.telegram?.draftChunk;
|
||||
|
||||
const maxRequested = Math.max(
|
||||
1,
|
||||
Math.floor(draftCfg?.maxChars ?? DEFAULT_TELEGRAM_DRAFT_STREAM_MAX),
|
||||
);
|
||||
const maxChars = Math.max(1, Math.min(maxRequested, textLimit));
|
||||
const minRequested = Math.max(
|
||||
1,
|
||||
Math.floor(draftCfg?.minChars ?? DEFAULT_TELEGRAM_DRAFT_STREAM_MIN),
|
||||
);
|
||||
const minChars = Math.min(minRequested, maxChars);
|
||||
const breakPreference =
|
||||
draftCfg?.breakPreference === "newline" ||
|
||||
draftCfg?.breakPreference === "sentence"
|
||||
? draftCfg.breakPreference
|
||||
: "paragraph";
|
||||
return { minChars, maxChars, breakPreference };
|
||||
}
|
||||
|
||||
export function resolveBlockStreamingCoalescing(
|
||||
cfg: ClawdbotConfig | undefined,
|
||||
provider?: string,
|
||||
@@ -118,54 +102,21 @@ export function resolveBlockStreamingCoalescing(
|
||||
},
|
||||
): BlockStreamingCoalescing | undefined {
|
||||
const providerKey = normalizeChunkProvider(provider);
|
||||
const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId);
|
||||
const normalizedAccountId = normalizeAccountId(accountId);
|
||||
const providerDefaults = providerKey
|
||||
? PROVIDER_COALESCE_DEFAULTS[providerKey]
|
||||
const providerId = providerKey ? normalizeProviderId(providerKey) : null;
|
||||
const providerChunkLimit = providerId
|
||||
? getProviderDock(providerId)?.outbound?.textChunkLimit
|
||||
: undefined;
|
||||
const providerCfg = (() => {
|
||||
if (!cfg || !providerKey) return undefined;
|
||||
if (providerKey === "whatsapp") {
|
||||
return (
|
||||
cfg.whatsapp?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ??
|
||||
cfg.whatsapp?.blockStreamingCoalesce
|
||||
);
|
||||
}
|
||||
if (providerKey === "telegram") {
|
||||
return (
|
||||
cfg.telegram?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ??
|
||||
cfg.telegram?.blockStreamingCoalesce
|
||||
);
|
||||
}
|
||||
if (providerKey === "discord") {
|
||||
return (
|
||||
cfg.discord?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ??
|
||||
cfg.discord?.blockStreamingCoalesce
|
||||
);
|
||||
}
|
||||
if (providerKey === "slack") {
|
||||
return (
|
||||
cfg.slack?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ??
|
||||
cfg.slack?.blockStreamingCoalesce
|
||||
);
|
||||
}
|
||||
if (providerKey === "signal") {
|
||||
return (
|
||||
cfg.signal?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ??
|
||||
cfg.signal?.blockStreamingCoalesce
|
||||
);
|
||||
}
|
||||
if (providerKey === "imessage") {
|
||||
return (
|
||||
cfg.imessage?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ??
|
||||
cfg.imessage?.blockStreamingCoalesce
|
||||
);
|
||||
}
|
||||
if (providerKey === "msteams") {
|
||||
return cfg.msteams?.blockStreamingCoalesce;
|
||||
}
|
||||
return undefined;
|
||||
})();
|
||||
const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId, {
|
||||
fallbackLimit: providerChunkLimit,
|
||||
});
|
||||
const providerDefaults = providerId
|
||||
? getProviderDock(providerId)?.streaming?.blockStreamingCoalesceDefaults
|
||||
: undefined;
|
||||
const providerCfg = resolveProviderBlockStreamingCoalesce({
|
||||
cfg,
|
||||
providerKey,
|
||||
accountId,
|
||||
});
|
||||
const coalesceCfg =
|
||||
providerCfg ?? cfg?.agents?.defaults?.blockStreamingCoalesce;
|
||||
const minRequested = Math.max(
|
||||
|
||||
@@ -54,9 +54,9 @@ import {
|
||||
triggerClawdbotRestart,
|
||||
} from "../../infra/restart.js";
|
||||
import { enqueueSystemEvent } from "../../infra/system-events.js";
|
||||
import type { ProviderId } from "../../providers/plugins/types.js";
|
||||
import { parseAgentSessionKey } from "../../routing/session-key.js";
|
||||
import { resolveSendPolicy } from "../../sessions/send-policy.js";
|
||||
import { normalizeE164 } from "../../utils.js";
|
||||
import { resolveCommandAuthorization } from "../command-auth.js";
|
||||
import {
|
||||
normalizeCommandBody,
|
||||
@@ -108,10 +108,10 @@ function resolveSessionEntryForKey(
|
||||
export type CommandContext = {
|
||||
surface: string;
|
||||
provider: string;
|
||||
isWhatsAppProvider: boolean;
|
||||
providerId?: ProviderId;
|
||||
ownerList: string[];
|
||||
isAuthorizedSender: boolean;
|
||||
senderE164?: string;
|
||||
senderId?: string;
|
||||
abortKey?: string;
|
||||
rawBodyNormalized: string;
|
||||
commandBodyNormalized: string;
|
||||
@@ -155,7 +155,7 @@ export async function buildStatusReply(params: {
|
||||
} = params;
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /status from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /status from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
@@ -359,10 +359,10 @@ export function buildCommandContext(params: {
|
||||
return {
|
||||
surface,
|
||||
provider,
|
||||
isWhatsAppProvider: auth.isWhatsAppProvider,
|
||||
providerId: auth.providerId,
|
||||
ownerList: auth.ownerList,
|
||||
isAuthorizedSender: auth.isAuthorizedSender,
|
||||
senderE164: auth.senderE164,
|
||||
senderId: auth.senderId,
|
||||
abortKey,
|
||||
rawBodyNormalized,
|
||||
commandBodyNormalized,
|
||||
@@ -448,7 +448,7 @@ export async function handleCommands(params: {
|
||||
command.commandBodyNormalized === "/new";
|
||||
if (resetRequested && !command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /reset from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /reset from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -472,22 +472,9 @@ export async function handleCommands(params: {
|
||||
reply: { text: "⚙️ Group activation only applies to group chats." },
|
||||
};
|
||||
}
|
||||
const activationOwnerList = command.ownerList;
|
||||
const activationSenderE164 = command.senderE164
|
||||
? normalizeE164(command.senderE164)
|
||||
: "";
|
||||
const isActivationOwner =
|
||||
!command.isWhatsAppProvider || activationOwnerList.length === 0
|
||||
? command.isAuthorizedSender
|
||||
: Boolean(activationSenderE164) &&
|
||||
activationOwnerList.includes(activationSenderE164);
|
||||
|
||||
if (
|
||||
!command.isAuthorizedSender ||
|
||||
(command.isWhatsAppProvider && !isActivationOwner)
|
||||
) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /activation from unauthorized sender in group: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /activation from unauthorized sender in group: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -515,7 +502,7 @@ export async function handleCommands(params: {
|
||||
if (allowTextCommands && sendPolicyCommand.hasCommand) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /send from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /send from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -552,7 +539,7 @@ export async function handleCommands(params: {
|
||||
if (allowTextCommands && command.commandBodyNormalized === "/restart") {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /restart from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /restart from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -598,7 +585,7 @@ export async function handleCommands(params: {
|
||||
if (allowTextCommands && helpRequested) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /help from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /help from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -609,7 +596,7 @@ export async function handleCommands(params: {
|
||||
if (allowTextCommands && commandsRequested) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /commands from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /commands from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -673,7 +660,7 @@ export async function handleCommands(params: {
|
||||
if (configCommand) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /config from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /config from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -805,7 +792,7 @@ export async function handleCommands(params: {
|
||||
if (debugCommand) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /debug from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /debug from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -832,13 +819,11 @@ export async function handleCommands(params: {
|
||||
reply: { text: "⚙️ Debug overrides: (none)" },
|
||||
};
|
||||
}
|
||||
const effectiveConfig = cfg ?? {};
|
||||
const json = JSON.stringify(overrides, null, 2);
|
||||
const effectiveJson = JSON.stringify(effectiveConfig, null, 2);
|
||||
return {
|
||||
shouldContinue: false,
|
||||
reply: {
|
||||
text: `⚙️ Debug overrides (memory-only):\n\`\`\`json\n${json}\n\`\`\`\n⚙️ Effective config (with overrides):\n\`\`\`json\n${effectiveJson}\n\`\`\``,
|
||||
text: `⚙️ Debug overrides (memory-only):\n\`\`\`json\n${json}\n\`\`\``,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -895,7 +880,7 @@ export async function handleCommands(params: {
|
||||
if (allowTextCommands && stopRequested) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /stop from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /stop from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
@@ -927,7 +912,7 @@ export async function handleCommands(params: {
|
||||
if (compactRequested) {
|
||||
if (!command.isAuthorizedSender) {
|
||||
logVerbose(
|
||||
`Ignoring /compact from unauthorized sender: ${command.senderE164 || "<unknown>"}`,
|
||||
`Ignoring /compact from unauthorized sender: ${command.senderId || "<unknown>"}`,
|
||||
);
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
|
||||
@@ -198,7 +198,11 @@ export function createFollowupRunner(params: {
|
||||
(queued.run.messageProvider?.toLowerCase() as
|
||||
| OriginatingChannelType
|
||||
| undefined);
|
||||
const replyToMode = resolveReplyToMode(queued.run.config, replyToChannel);
|
||||
const replyToMode = resolveReplyToMode(
|
||||
queued.run.config,
|
||||
replyToChannel,
|
||||
queued.originatingAccountId,
|
||||
);
|
||||
|
||||
const replyTaggedPayloads: ReplyPayload[] = applyReplyThreading({
|
||||
payloads: sanitizedPayloads,
|
||||
|
||||
+40
-173
@@ -1,181 +1,39 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { resolveProviderGroupRequireMention } from "../../config/group-policy.js";
|
||||
import type {
|
||||
GroupKeyResolution,
|
||||
SessionEntry,
|
||||
} from "../../config/sessions.js";
|
||||
import { resolveSlackAccount } from "../../slack/accounts.js";
|
||||
import { getProviderDock } from "../../providers/dock.js";
|
||||
import {
|
||||
getChatProviderMeta,
|
||||
normalizeProviderId,
|
||||
} from "../../providers/registry.js";
|
||||
import { isInternalMessageProvider } from "../../utils/message-provider.js";
|
||||
import { normalizeGroupActivation } from "../group-activation.js";
|
||||
import type { TemplateContext } from "../templating.js";
|
||||
|
||||
function normalizeDiscordSlug(value?: string | null) {
|
||||
if (!value) return "";
|
||||
let text = value.trim().toLowerCase();
|
||||
if (!text) return "";
|
||||
text = text.replace(/^[@#]+/, "");
|
||||
text = text.replace(/[\s_]+/g, "-");
|
||||
text = text.replace(/[^a-z0-9-]+/g, "-");
|
||||
text = text.replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
|
||||
return text;
|
||||
}
|
||||
|
||||
function normalizeSlackSlug(raw?: string | null) {
|
||||
const trimmed = raw?.trim().toLowerCase() ?? "";
|
||||
if (!trimmed) return "";
|
||||
const dashed = trimmed.replace(/\s+/g, "-");
|
||||
const cleaned = dashed.replace(/[^a-z0-9#@._+-]+/g, "-");
|
||||
return cleaned.replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
|
||||
}
|
||||
|
||||
function parseTelegramGroupId(value?: string | null) {
|
||||
const raw = value?.trim() ?? "";
|
||||
if (!raw) return { chatId: undefined, topicId: undefined };
|
||||
const parts = raw.split(":").filter(Boolean);
|
||||
if (
|
||||
parts.length >= 3 &&
|
||||
parts[1] === "topic" &&
|
||||
/^-?\d+$/.test(parts[0]) &&
|
||||
/^\d+$/.test(parts[2])
|
||||
) {
|
||||
return { chatId: parts[0], topicId: parts[2] };
|
||||
}
|
||||
if (parts.length >= 2 && /^-?\d+$/.test(parts[0]) && /^\d+$/.test(parts[1])) {
|
||||
return { chatId: parts[0], topicId: parts[1] };
|
||||
}
|
||||
return { chatId: raw, topicId: undefined };
|
||||
}
|
||||
|
||||
function resolveTelegramRequireMention(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
chatId?: string;
|
||||
topicId?: string;
|
||||
}): boolean | undefined {
|
||||
const { cfg, chatId, topicId } = params;
|
||||
if (!chatId) return undefined;
|
||||
const groupConfig = cfg.telegram?.groups?.[chatId];
|
||||
const groupDefault = cfg.telegram?.groups?.["*"];
|
||||
const topicConfig =
|
||||
topicId && groupConfig?.topics ? groupConfig.topics[topicId] : undefined;
|
||||
const defaultTopicConfig =
|
||||
topicId && groupDefault?.topics ? groupDefault.topics[topicId] : undefined;
|
||||
if (typeof topicConfig?.requireMention === "boolean") {
|
||||
return topicConfig.requireMention;
|
||||
}
|
||||
if (typeof defaultTopicConfig?.requireMention === "boolean") {
|
||||
return defaultTopicConfig.requireMention;
|
||||
}
|
||||
if (typeof groupConfig?.requireMention === "boolean") {
|
||||
return groupConfig.requireMention;
|
||||
}
|
||||
if (typeof groupDefault?.requireMention === "boolean") {
|
||||
return groupDefault.requireMention;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveDiscordGuildEntry(
|
||||
guilds: NonNullable<ClawdbotConfig["discord"]>["guilds"],
|
||||
groupSpace?: string,
|
||||
) {
|
||||
if (!guilds || Object.keys(guilds).length === 0) return null;
|
||||
const space = groupSpace?.trim();
|
||||
if (space && guilds[space]) return guilds[space];
|
||||
const normalized = normalizeDiscordSlug(space);
|
||||
if (normalized && guilds[normalized]) return guilds[normalized];
|
||||
if (normalized) {
|
||||
const match = Object.values(guilds).find(
|
||||
(entry) => normalizeDiscordSlug(entry?.slug ?? undefined) === normalized,
|
||||
);
|
||||
if (match) return match;
|
||||
}
|
||||
return guilds["*"] ?? null;
|
||||
}
|
||||
|
||||
export function resolveGroupRequireMention(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
ctx: TemplateContext;
|
||||
groupResolution?: GroupKeyResolution;
|
||||
}): boolean {
|
||||
const { cfg, ctx, groupResolution } = params;
|
||||
const provider =
|
||||
groupResolution?.provider ?? ctx.Provider?.trim().toLowerCase();
|
||||
const rawProvider = groupResolution?.provider ?? ctx.Provider?.trim();
|
||||
const provider = normalizeProviderId(rawProvider);
|
||||
if (!provider) return true;
|
||||
const groupId = groupResolution?.id ?? ctx.From?.replace(/^group:/, "");
|
||||
const groupRoom = ctx.GroupRoom?.trim() ?? ctx.GroupSubject?.trim();
|
||||
const groupSpace = ctx.GroupSpace?.trim();
|
||||
if (provider === "telegram") {
|
||||
const { chatId, topicId } = parseTelegramGroupId(groupId);
|
||||
const requireMention = resolveTelegramRequireMention({
|
||||
cfg,
|
||||
chatId,
|
||||
topicId,
|
||||
});
|
||||
if (typeof requireMention === "boolean") return requireMention;
|
||||
return resolveProviderGroupRequireMention({
|
||||
cfg,
|
||||
provider,
|
||||
groupId: chatId ?? groupId,
|
||||
});
|
||||
}
|
||||
if (provider === "whatsapp" || provider === "imessage") {
|
||||
return resolveProviderGroupRequireMention({
|
||||
cfg,
|
||||
provider,
|
||||
groupId,
|
||||
});
|
||||
}
|
||||
if (provider === "discord") {
|
||||
const guildEntry = resolveDiscordGuildEntry(
|
||||
cfg.discord?.guilds,
|
||||
groupSpace,
|
||||
);
|
||||
const channelEntries = guildEntry?.channels;
|
||||
if (channelEntries && Object.keys(channelEntries).length > 0) {
|
||||
const channelSlug = normalizeDiscordSlug(groupRoom);
|
||||
const entry =
|
||||
(groupId ? channelEntries[groupId] : undefined) ??
|
||||
(channelSlug
|
||||
? (channelEntries[channelSlug] ?? channelEntries[`#${channelSlug}`])
|
||||
: undefined) ??
|
||||
(groupRoom
|
||||
? channelEntries[normalizeDiscordSlug(groupRoom)]
|
||||
: undefined);
|
||||
if (entry && typeof entry.requireMention === "boolean") {
|
||||
return entry.requireMention;
|
||||
}
|
||||
}
|
||||
if (typeof guildEntry?.requireMention === "boolean") {
|
||||
return guildEntry.requireMention;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (provider === "slack") {
|
||||
const account = resolveSlackAccount({ cfg, accountId: ctx.AccountId });
|
||||
const channels = account.channels ?? {};
|
||||
const keys = Object.keys(channels);
|
||||
if (keys.length === 0) return true;
|
||||
const channelId = groupId?.trim();
|
||||
const channelName = groupRoom?.replace(/^#/, "");
|
||||
const normalizedName = normalizeSlackSlug(channelName);
|
||||
const candidates = [
|
||||
channelId ?? "",
|
||||
channelName ? `#${channelName}` : "",
|
||||
channelName ?? "",
|
||||
normalizedName,
|
||||
].filter(Boolean);
|
||||
let matched: { requireMention?: boolean } | undefined;
|
||||
for (const candidate of candidates) {
|
||||
if (candidate && channels[candidate]) {
|
||||
matched = channels[candidate];
|
||||
break;
|
||||
}
|
||||
}
|
||||
const fallback = channels["*"];
|
||||
const resolved = matched ?? fallback;
|
||||
if (typeof resolved?.requireMention === "boolean") {
|
||||
return resolved.requireMention;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const requireMention = getProviderDock(
|
||||
provider,
|
||||
)?.groups?.resolveRequireMention?.({
|
||||
cfg,
|
||||
groupId,
|
||||
groupRoom,
|
||||
groupSpace,
|
||||
accountId: ctx.AccountId,
|
||||
});
|
||||
if (typeof requireMention === "boolean") return requireMention;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -186,6 +44,7 @@ export function defaultGroupActivation(
|
||||
}
|
||||
|
||||
export function buildGroupIntro(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
sessionCtx: TemplateContext;
|
||||
sessionEntry?: SessionEntry;
|
||||
defaultActivation: "always" | "mention";
|
||||
@@ -196,14 +55,14 @@ export function buildGroupIntro(params: {
|
||||
params.defaultActivation;
|
||||
const subject = params.sessionCtx.GroupSubject?.trim();
|
||||
const members = params.sessionCtx.GroupMembers?.trim();
|
||||
const provider = params.sessionCtx.Provider?.trim().toLowerCase();
|
||||
const rawProvider = params.sessionCtx.Provider?.trim();
|
||||
const providerKey = rawProvider?.toLowerCase() ?? "";
|
||||
const providerId = normalizeProviderId(rawProvider);
|
||||
const providerLabel = (() => {
|
||||
if (!provider) return "chat";
|
||||
if (provider === "whatsapp") return "WhatsApp";
|
||||
if (provider === "telegram") return "Telegram";
|
||||
if (provider === "discord") return "Discord";
|
||||
if (provider === "webchat") return "WebChat";
|
||||
return `${provider.at(0)?.toUpperCase() ?? ""}${provider.slice(1)}`;
|
||||
if (!providerKey) return "chat";
|
||||
if (isInternalMessageProvider(providerKey)) return "WebChat";
|
||||
if (providerId) return getChatProviderMeta(providerId).label;
|
||||
return `${providerKey.at(0)?.toUpperCase() ?? ""}${providerKey.slice(1)}`;
|
||||
})();
|
||||
const subjectLine = subject
|
||||
? `You are replying inside the ${providerLabel} group "${subject}".`
|
||||
@@ -213,10 +72,18 @@ export function buildGroupIntro(params: {
|
||||
activation === "always"
|
||||
? "Activation: always-on (you receive every group message)."
|
||||
: "Activation: trigger-only (you are invoked only when explicitly mentioned; recent context may be included).";
|
||||
const whatsappIdsLine =
|
||||
provider === "whatsapp"
|
||||
? "WhatsApp IDs: SenderId is the participant JID; [message_id: ...] is the message id for reactions (use SenderId as participant)."
|
||||
: undefined;
|
||||
const groupId = params.sessionCtx.From?.replace(/^group:/, "");
|
||||
const groupRoom = params.sessionCtx.GroupRoom?.trim() ?? subject;
|
||||
const groupSpace = params.sessionCtx.GroupSpace?.trim();
|
||||
const providerIdsLine = providerId
|
||||
? getProviderDock(providerId)?.groups?.resolveGroupIntroHint?.({
|
||||
cfg: params.cfg,
|
||||
groupId,
|
||||
groupRoom,
|
||||
groupSpace,
|
||||
accountId: params.sessionCtx.AccountId,
|
||||
})
|
||||
: undefined;
|
||||
const silenceLine =
|
||||
activation === "always"
|
||||
? `If no response is needed, reply with exactly "${params.silentToken}" (and nothing else) so Clawdbot stays silent. Do not add any other words, punctuation, tags, markdown/code blocks, or explanations.`
|
||||
@@ -231,7 +98,7 @@ export function buildGroupIntro(params: {
|
||||
subjectLine,
|
||||
membersLine,
|
||||
activationLine,
|
||||
whatsappIdsLine,
|
||||
providerIdsLine,
|
||||
silenceLine,
|
||||
cautionLine,
|
||||
lurkLine,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { resolveAgentConfig } from "../../agents/agent-scope.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { getProviderDock } from "../../providers/dock.js";
|
||||
import { normalizeProviderId } from "../../providers/registry.js";
|
||||
import type { MsgContext } from "../templating.js";
|
||||
|
||||
function escapeRegExp(text: string): string {
|
||||
@@ -112,9 +114,14 @@ export function stripMentions(
|
||||
agentId?: string,
|
||||
): string {
|
||||
let result = text;
|
||||
const rawPatterns = resolveMentionPatterns(cfg, agentId);
|
||||
const patterns = normalizeMentionPatterns(rawPatterns);
|
||||
|
||||
const providerId = ctx.Provider ? normalizeProviderId(ctx.Provider) : null;
|
||||
const providerMentions = providerId
|
||||
? getProviderDock(providerId)?.mentions
|
||||
: undefined;
|
||||
const patterns = normalizeMentionPatterns([
|
||||
...resolveMentionPatterns(cfg, agentId),
|
||||
...(providerMentions?.stripPatterns?.({ ctx, cfg, agentId }) ?? []),
|
||||
]);
|
||||
for (const p of patterns) {
|
||||
try {
|
||||
const re = new RegExp(p, "gi");
|
||||
@@ -123,16 +130,15 @@ export function stripMentions(
|
||||
// ignore invalid regex
|
||||
}
|
||||
}
|
||||
const selfE164 = (ctx.To ?? "").replace(/^whatsapp:/, "");
|
||||
if (selfE164) {
|
||||
const esc = selfE164.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
result = result
|
||||
.replace(new RegExp(esc, "gi"), " ")
|
||||
.replace(new RegExp(`@${esc}`, "gi"), " ");
|
||||
if (providerMentions?.stripMentions) {
|
||||
result = providerMentions.stripMentions({
|
||||
text: result,
|
||||
ctx,
|
||||
cfg,
|
||||
agentId,
|
||||
});
|
||||
}
|
||||
// Generic mention patterns like @123456789 or plain digits
|
||||
result = result.replace(/@[0-9+]{5,}/g, " ");
|
||||
// Discord-style mentions (<@123> or <@!123>)
|
||||
result = result.replace(/<@!?\d+>/g, " ");
|
||||
return result.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
@@ -568,14 +568,7 @@ export function scheduleFollowupDrain(
|
||||
}
|
||||
})();
|
||||
}
|
||||
function defaultQueueModeForProvider(provider?: string): QueueMode {
|
||||
const normalized = provider?.trim().toLowerCase();
|
||||
if (normalized === "discord") return "collect";
|
||||
if (normalized === "webchat") return "collect";
|
||||
if (normalized === "whatsapp") return "collect";
|
||||
if (normalized === "telegram") return "collect";
|
||||
if (normalized === "imessage") return "collect";
|
||||
if (normalized === "signal") return "collect";
|
||||
function defaultQueueModeForProvider(_provider?: string): QueueMode {
|
||||
return "collect";
|
||||
}
|
||||
export function resolveQueueSettings(params: {
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { ReplyToMode } from "../../config/types.js";
|
||||
import { getProviderDock } from "../../providers/dock.js";
|
||||
import { normalizeProviderId } from "../../providers/registry.js";
|
||||
import type { OriginatingChannelType } from "../templating.js";
|
||||
import type { ReplyPayload } from "../types.js";
|
||||
|
||||
export function resolveReplyToMode(
|
||||
cfg: ClawdbotConfig,
|
||||
channel?: OriginatingChannelType,
|
||||
accountId?: string | null,
|
||||
): ReplyToMode {
|
||||
switch (channel) {
|
||||
case "telegram":
|
||||
return cfg.telegram?.replyToMode ?? "first";
|
||||
case "discord":
|
||||
return cfg.discord?.replyToMode ?? "off";
|
||||
case "slack":
|
||||
return cfg.slack?.replyToMode ?? "off";
|
||||
default:
|
||||
return "all";
|
||||
}
|
||||
const provider = normalizeProviderId(channel);
|
||||
if (!provider) return "all";
|
||||
const resolved = getProviderDock(provider)?.threading?.resolveReplyToMode?.({
|
||||
cfg,
|
||||
accountId,
|
||||
});
|
||||
return resolved ?? "all";
|
||||
}
|
||||
|
||||
export function createReplyToModeFilter(
|
||||
@@ -43,7 +43,11 @@ export function createReplyToModeFilterForChannel(
|
||||
mode: ReplyToMode,
|
||||
channel?: OriginatingChannelType,
|
||||
) {
|
||||
const provider = normalizeProviderId(channel);
|
||||
const allowTagsWhenOff = provider
|
||||
? Boolean(getProviderDock(provider)?.threading?.allowTagsWhenOff)
|
||||
: false;
|
||||
return createReplyToModeFilter(mode, {
|
||||
allowTagsWhenOff: channel === "slack",
|
||||
allowTagsWhenOff,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -236,11 +236,12 @@ describe("routeReply", () => {
|
||||
to: "conversation:19:abc@thread.tacv2",
|
||||
cfg,
|
||||
});
|
||||
expect(mocks.sendMessageMSTeams).toHaveBeenCalledWith({
|
||||
cfg,
|
||||
to: "conversation:19:abc@thread.tacv2",
|
||||
text: "hi",
|
||||
mediaUrl: undefined,
|
||||
});
|
||||
expect(mocks.sendMessageMSTeams).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
cfg,
|
||||
to: "conversation:19:abc@thread.tacv2",
|
||||
text: "hi",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,13 +10,8 @@
|
||||
import { resolveSessionAgentId } from "../../agents/agent-scope.js";
|
||||
import { resolveEffectiveMessagesConfig } from "../../agents/identity.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { sendMessageDiscord } from "../../discord/send.js";
|
||||
import { sendMessageIMessage } from "../../imessage/send.js";
|
||||
import { sendMessageMSTeams } from "../../msteams/send.js";
|
||||
import { sendMessageSignal } from "../../signal/send.js";
|
||||
import { sendMessageSlack } from "../../slack/send.js";
|
||||
import { sendMessageTelegram } from "../../telegram/send.js";
|
||||
import { sendMessageWhatsApp } from "../../web/outbound.js";
|
||||
import { normalizeProviderId } from "../../providers/registry.js";
|
||||
import { INTERNAL_MESSAGE_PROVIDER } from "../../utils/message-provider.js";
|
||||
import type { OriginatingChannelType } from "../templating.js";
|
||||
import type { ReplyPayload } from "../types.js";
|
||||
import { normalizeReplyPayload } from "./normalize-reply.js";
|
||||
@@ -93,118 +88,39 @@ export async function routeReply(
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const sendOne = async (params: {
|
||||
text: string;
|
||||
mediaUrl?: string;
|
||||
}): Promise<RouteReplyResult> => {
|
||||
if (abortSignal?.aborted) {
|
||||
return { ok: false, error: "Reply routing aborted" };
|
||||
}
|
||||
const { text, mediaUrl } = params;
|
||||
switch (channel) {
|
||||
case "telegram": {
|
||||
const replyToMessageId = replyToId
|
||||
? Number.parseInt(replyToId, 10)
|
||||
: undefined;
|
||||
const resolvedReplyToMessageId = Number.isFinite(replyToMessageId)
|
||||
? replyToMessageId
|
||||
: undefined;
|
||||
const result = await sendMessageTelegram(to, text, {
|
||||
mediaUrl,
|
||||
messageThreadId: threadId,
|
||||
replyToMessageId: resolvedReplyToMessageId,
|
||||
accountId,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
if (channel === INTERNAL_MESSAGE_PROVIDER) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Webchat routing not supported for queued replies",
|
||||
};
|
||||
}
|
||||
|
||||
case "slack": {
|
||||
const result = await sendMessageSlack(to, text, {
|
||||
mediaUrl,
|
||||
threadTs: replyToId,
|
||||
accountId,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
|
||||
case "discord": {
|
||||
const result = await sendMessageDiscord(to, text, {
|
||||
mediaUrl,
|
||||
replyTo: replyToId,
|
||||
accountId,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
|
||||
case "signal": {
|
||||
const result = await sendMessageSignal(to, text, {
|
||||
mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
|
||||
case "imessage": {
|
||||
const result = await sendMessageIMessage(to, text, {
|
||||
mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
|
||||
case "whatsapp": {
|
||||
const result = await sendMessageWhatsApp(to, text, {
|
||||
verbose: false,
|
||||
mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
|
||||
case "webchat": {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Webchat routing not supported for queued replies`,
|
||||
};
|
||||
}
|
||||
|
||||
case "msteams": {
|
||||
const result = await sendMessageMSTeams({
|
||||
cfg,
|
||||
to,
|
||||
text,
|
||||
mediaUrl,
|
||||
});
|
||||
return { ok: true, messageId: result.messageId };
|
||||
}
|
||||
|
||||
default: {
|
||||
const _exhaustive: never = channel;
|
||||
return { ok: false, error: `Unknown channel: ${String(_exhaustive)}` };
|
||||
}
|
||||
}
|
||||
};
|
||||
const provider = normalizeProviderId(channel) ?? null;
|
||||
if (!provider) {
|
||||
return { ok: false, error: `Unknown channel: ${String(channel)}` };
|
||||
}
|
||||
if (abortSignal?.aborted) {
|
||||
return { ok: false, error: "Reply routing aborted" };
|
||||
}
|
||||
|
||||
try {
|
||||
if (abortSignal?.aborted) {
|
||||
return { ok: false, error: "Reply routing aborted" };
|
||||
}
|
||||
if (mediaUrls.length === 0) {
|
||||
return await sendOne({ text });
|
||||
}
|
||||
|
||||
let last: RouteReplyResult | undefined;
|
||||
for (let i = 0; i < mediaUrls.length; i++) {
|
||||
if (abortSignal?.aborted) {
|
||||
return { ok: false, error: "Reply routing aborted" };
|
||||
}
|
||||
const mediaUrl = mediaUrls[i];
|
||||
const caption = i === 0 ? text : "";
|
||||
last = await sendOne({ text: caption, mediaUrl });
|
||||
if (!last.ok) return last;
|
||||
}
|
||||
|
||||
return last ?? { ok: true };
|
||||
// Provider docking: this is an execution boundary (we're about to send).
|
||||
// Keep the module cheap to import by loading outbound plumbing lazily.
|
||||
const { deliverOutboundPayloads } = await import(
|
||||
"../../infra/outbound/deliver.js"
|
||||
);
|
||||
const results = await deliverOutboundPayloads({
|
||||
cfg,
|
||||
provider,
|
||||
to,
|
||||
accountId: accountId ?? undefined,
|
||||
payloads: [normalized],
|
||||
replyToId: replyToId ?? null,
|
||||
threadId: threadId ?? null,
|
||||
abortSignal,
|
||||
});
|
||||
const last = results.at(-1);
|
||||
return { ok: true, messageId: last?.messageId };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
@@ -222,22 +138,10 @@ export async function routeReply(
|
||||
*/
|
||||
export function isRoutableChannel(
|
||||
channel: OriginatingChannelType | undefined,
|
||||
): channel is
|
||||
| "telegram"
|
||||
| "slack"
|
||||
| "discord"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "whatsapp"
|
||||
| "msteams" {
|
||||
if (!channel) return false;
|
||||
return [
|
||||
"telegram",
|
||||
"slack",
|
||||
"discord",
|
||||
"signal",
|
||||
"imessage",
|
||||
"whatsapp",
|
||||
"msteams",
|
||||
].includes(channel);
|
||||
): channel is Exclude<
|
||||
OriginatingChannelType,
|
||||
typeof INTERNAL_MESSAGE_PROVIDER
|
||||
> {
|
||||
if (!channel || channel === INTERNAL_MESSAGE_PROVIDER) return false;
|
||||
return normalizeProviderId(channel) !== null;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ import {
|
||||
type SessionScope,
|
||||
saveSessionStore,
|
||||
} from "../../config/sessions.js";
|
||||
import { getProviderDock } from "../../providers/dock.js";
|
||||
import { normalizeProviderId } from "../../providers/registry.js";
|
||||
import { normalizeMainKey } from "../../routing/session-key.js";
|
||||
import { resolveCommandAuthorization } from "../command-auth.js";
|
||||
import type { MsgContext, TemplateContext } from "../templating.js";
|
||||
@@ -236,7 +238,13 @@ export async function initSessionState(params: {
|
||||
const subject = ctx.GroupSubject?.trim();
|
||||
const space = ctx.GroupSpace?.trim();
|
||||
const explicitRoom = ctx.GroupRoom?.trim();
|
||||
const isRoomProvider = provider === "discord" || provider === "slack";
|
||||
const normalizedProvider = normalizeProviderId(provider);
|
||||
const isRoomProvider = Boolean(
|
||||
normalizedProvider &&
|
||||
getProviderDock(normalizedProvider)?.capabilities.chatTypes.includes(
|
||||
"channel",
|
||||
),
|
||||
);
|
||||
const nextRoom =
|
||||
explicitRoom ??
|
||||
(isRoomProvider && subject && subject.startsWith("#")
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import type { ProviderId } from "../providers/plugins/types.js";
|
||||
import type { InternalMessageProvider } from "../utils/message-provider.js";
|
||||
|
||||
/** Valid provider channels for message routing. */
|
||||
export type OriginatingChannelType =
|
||||
| "telegram"
|
||||
| "slack"
|
||||
| "discord"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "whatsapp"
|
||||
| "webchat"
|
||||
| "msteams";
|
||||
export type OriginatingChannelType = ProviderId | InternalMessageProvider;
|
||||
|
||||
export type MsgContext = {
|
||||
Body?: string;
|
||||
@@ -50,7 +45,7 @@ export type MsgContext = {
|
||||
SenderUsername?: string;
|
||||
SenderTag?: string;
|
||||
SenderE164?: string;
|
||||
/** Provider label (whatsapp|telegram|discord|imessage|...). */
|
||||
/** Provider label (e.g. whatsapp, telegram). */
|
||||
Provider?: string;
|
||||
/** Provider surface label (e.g. discord, slack). Prefer this over `Provider` when available. */
|
||||
Surface?: string;
|
||||
|
||||
+8
-2
@@ -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>",
|
||||
|
||||
@@ -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 } : {}),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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;
|
||||
|
||||
+16
-24
@@ -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));
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+15
-22
@@ -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");
|
||||
|
||||
+11
-62
@@ -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}`,
|
||||
);
|
||||
|
||||
+8
-6
@@ -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)
|
||||
|
||||
+39
-24
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+32
-31
@@ -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),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+62
-149
@@ -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;
|
||||
|
||||
@@ -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"),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+46
-124
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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" },
|
||||
],
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
+25
-11
@@ -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);
|
||||
|
||||
+212
-87
@@ -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(
|
||||
|
||||
+67
-694
@@ -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}.`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
+90
-1561
File diff suppressed because it is too large
Load Diff
@@ -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());
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "../../providers/plugins/onboarding-types.js";
|
||||
+100
-84
@@ -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);
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
+68
-160
@@ -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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
]);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)}`)}`;
|
||||
|
||||
@@ -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,
|
||||
|
||||
+104
-20
@@ -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();
|
||||
|
||||
+102
-55
@@ -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({
|
||||
|
||||
+15
-14
@@ -21,21 +21,22 @@ function resolveProviderGroups(
|
||||
provider: GroupPolicyProvider,
|
||||
accountId?: string | null,
|
||||
): ProviderGroups | undefined {
|
||||
if (provider === "whatsapp") return cfg.whatsapp?.groups;
|
||||
const normalizedAccountId = normalizeAccountId(accountId);
|
||||
if (provider === "telegram") {
|
||||
return (
|
||||
cfg.telegram?.accounts?.[normalizedAccountId]?.groups ??
|
||||
cfg.telegram?.groups
|
||||
);
|
||||
}
|
||||
if (provider === "imessage") {
|
||||
return (
|
||||
cfg.imessage?.accounts?.[normalizedAccountId]?.groups ??
|
||||
cfg.imessage?.groups
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
const providerConfig = (cfg as Record<string, unknown>)[provider] as
|
||||
| {
|
||||
accounts?: Record<string, { groups?: ProviderGroups }>;
|
||||
groups?: ProviderGroups;
|
||||
}
|
||||
| undefined;
|
||||
if (!providerConfig) return undefined;
|
||||
const accountGroups =
|
||||
providerConfig.accounts?.[normalizedAccountId]?.groups ??
|
||||
providerConfig.accounts?.[
|
||||
Object.keys(providerConfig.accounts ?? {}).find(
|
||||
(key) => key.toLowerCase() === normalizedAccountId.toLowerCase(),
|
||||
) ?? ""
|
||||
]?.groups;
|
||||
return accountGroups ?? providerConfig.groups;
|
||||
}
|
||||
|
||||
export function resolveProviderGroupPolicy(params: {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { normalizeProviderId } from "../providers/registry.js";
|
||||
import { normalizeAccountId } from "../routing/session-key.js";
|
||||
import type { ClawdbotConfig } from "./config.js";
|
||||
|
||||
@@ -49,43 +50,17 @@ export function resolveProviderCapabilities(params: {
|
||||
accountId?: string | null;
|
||||
}): string[] | undefined {
|
||||
const cfg = params.cfg;
|
||||
const provider = params.provider?.trim().toLowerCase();
|
||||
const provider = normalizeProviderId(params.provider);
|
||||
if (!cfg || !provider) return undefined;
|
||||
|
||||
switch (provider) {
|
||||
case "whatsapp":
|
||||
return resolveAccountCapabilities({
|
||||
cfg: cfg.whatsapp,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
case "telegram":
|
||||
return resolveAccountCapabilities({
|
||||
cfg: cfg.telegram,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
case "discord":
|
||||
return resolveAccountCapabilities({
|
||||
cfg: cfg.discord,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
case "slack":
|
||||
return resolveAccountCapabilities({
|
||||
cfg: cfg.slack,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
case "signal":
|
||||
return resolveAccountCapabilities({
|
||||
cfg: cfg.signal,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
case "imessage":
|
||||
return resolveAccountCapabilities({
|
||||
cfg: cfg.imessage,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
case "msteams":
|
||||
return normalizeCapabilities(cfg.msteams?.capabilities);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
const providerConfig = (cfg as Record<string, unknown>)[provider] as
|
||||
| {
|
||||
accounts?: Record<string, { capabilities?: string[] }>;
|
||||
capabilities?: string[];
|
||||
}
|
||||
| undefined;
|
||||
return resolveAccountCapabilities({
|
||||
cfg: providerConfig,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
}
|
||||
|
||||
+6
-17
@@ -6,6 +6,8 @@ import path from "node:path";
|
||||
import type { Skill } from "@mariozechner/pi-coding-agent";
|
||||
import JSON5 from "json5";
|
||||
import type { MsgContext } from "../auto-reply/templating.js";
|
||||
import type { ProviderId } from "../providers/plugins/types.js";
|
||||
import { PROVIDER_IDS } from "../providers/registry.js";
|
||||
import {
|
||||
buildAgentMainSessionKey,
|
||||
DEFAULT_AGENT_ID,
|
||||
@@ -63,15 +65,9 @@ export function clearSessionStoreCacheForTest(): void {
|
||||
|
||||
export type SessionScope = "per-sender" | "global";
|
||||
|
||||
const GROUP_SURFACES = new Set([
|
||||
"whatsapp",
|
||||
"telegram",
|
||||
"discord",
|
||||
"signal",
|
||||
"imessage",
|
||||
"webchat",
|
||||
"slack",
|
||||
]);
|
||||
export type SessionProviderId = ProviderId | "webchat";
|
||||
|
||||
const GROUP_SURFACES = new Set<string>([...PROVIDER_IDS, "webchat"]);
|
||||
|
||||
export type SessionChatType = "direct" | "group" | "room";
|
||||
|
||||
@@ -121,14 +117,7 @@ export type SessionEntry = {
|
||||
subject?: string;
|
||||
room?: string;
|
||||
space?: string;
|
||||
lastProvider?:
|
||||
| "whatsapp"
|
||||
| "telegram"
|
||||
| "discord"
|
||||
| "slack"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "webchat";
|
||||
lastProvider?: SessionProviderId;
|
||||
lastTo?: string;
|
||||
lastAccountId?: string;
|
||||
skillsSnapshot?: SessionSkillSnapshot;
|
||||
|
||||
+4
-10
@@ -101,16 +101,10 @@ export type WebConfig = {
|
||||
reconnect?: WebReconnectConfig;
|
||||
};
|
||||
|
||||
export type AgentElevatedAllowFromConfig = {
|
||||
whatsapp?: string[];
|
||||
telegram?: Array<string | number>;
|
||||
discord?: Array<string | number>;
|
||||
slack?: Array<string | number>;
|
||||
signal?: Array<string | number>;
|
||||
imessage?: Array<string | number>;
|
||||
msteams?: Array<string | number>;
|
||||
webchat?: Array<string | number>;
|
||||
};
|
||||
// Provider docking: allowlists keyed by provider id (and internal "webchat").
|
||||
export type AgentElevatedAllowFromConfig = Partial<
|
||||
Record<string, Array<string | number>>
|
||||
>;
|
||||
|
||||
export type IdentityConfig = {
|
||||
name?: string;
|
||||
|
||||
@@ -804,16 +804,9 @@ const ToolPolicySchema = z
|
||||
})
|
||||
.optional();
|
||||
|
||||
// Provider docking: allowlists keyed by provider id (no schema updates when adding providers).
|
||||
const ElevatedAllowFromSchema = z
|
||||
.object({
|
||||
whatsapp: z.array(z.string()).optional(),
|
||||
telegram: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
discord: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
slack: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
signal: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
imessage: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
webchat: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
})
|
||||
.record(z.string(), z.array(z.union([z.string(), z.number()])))
|
||||
.optional();
|
||||
|
||||
const AgentSandboxSchema = z
|
||||
|
||||
@@ -445,7 +445,7 @@ describe("runCronIsolatedAgentTurn", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("passes telegram token from config for delivery", async () => {
|
||||
it("delivers telegram via provider send", async () => {
|
||||
await withTempHome(async (home) => {
|
||||
const storePath = await writeSessionStore(home);
|
||||
const deps: CliDeps = {
|
||||
@@ -488,7 +488,7 @@ describe("runCronIsolatedAgentTurn", () => {
|
||||
expect(deps.sendMessageTelegram).toHaveBeenCalledWith(
|
||||
"123",
|
||||
"hello from cron",
|
||||
expect.objectContaining({ token: "t-1" }),
|
||||
expect.objectContaining({ verbose: false }),
|
||||
);
|
||||
} finally {
|
||||
if (prevTelegramToken === undefined) {
|
||||
@@ -500,7 +500,7 @@ describe("runCronIsolatedAgentTurn", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("delivers telegram topic targets with messageThreadId", async () => {
|
||||
it("delivers telegram topic targets via provider send", async () => {
|
||||
await withTempHome(async (home) => {
|
||||
const storePath = await writeSessionStore(home);
|
||||
const deps: CliDeps = {
|
||||
@@ -538,14 +538,14 @@ describe("runCronIsolatedAgentTurn", () => {
|
||||
|
||||
expect(res.status).toBe("ok");
|
||||
expect(deps.sendMessageTelegram).toHaveBeenCalledWith(
|
||||
"-1001234567890",
|
||||
"telegram:group:-1001234567890:topic:321",
|
||||
"hello from cron",
|
||||
expect.objectContaining({ messageThreadId: 321 }),
|
||||
expect.objectContaining({ verbose: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("delivers telegram shorthand topic suffixes with messageThreadId", async () => {
|
||||
it("delivers telegram shorthand topic suffixes via provider send", async () => {
|
||||
await withTempHome(async (home) => {
|
||||
const storePath = await writeSessionStore(home);
|
||||
const deps: CliDeps = {
|
||||
@@ -583,9 +583,9 @@ describe("runCronIsolatedAgentTurn", () => {
|
||||
|
||||
expect(res.status).toBe("ok");
|
||||
expect(deps.sendMessageTelegram).toHaveBeenCalledWith(
|
||||
"-1001234567890",
|
||||
"-1001234567890:321",
|
||||
"hello from cron",
|
||||
expect.objectContaining({ messageThreadId: 321 }),
|
||||
expect.objectContaining({ verbose: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -630,7 +630,7 @@ describe("runCronIsolatedAgentTurn", () => {
|
||||
expect(deps.sendMessageDiscord).toHaveBeenCalledWith(
|
||||
"channel:1122",
|
||||
"hello from cron",
|
||||
expect.objectContaining({ token: process.env.DISCORD_BOT_TOKEN }),
|
||||
expect.objectContaining({ verbose: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+104
-301
@@ -25,11 +25,6 @@ import {
|
||||
DEFAULT_AGENT_WORKSPACE_DIR,
|
||||
ensureAgentWorkspace,
|
||||
} from "../agents/workspace.js";
|
||||
import {
|
||||
chunkMarkdownText,
|
||||
chunkText,
|
||||
resolveTextChunkLimit,
|
||||
} from "../auto-reply/chunk.js";
|
||||
import {
|
||||
DEFAULT_HEARTBEAT_ACK_MAX_CHARS,
|
||||
stripHeartbeatToken,
|
||||
@@ -48,13 +43,20 @@ import {
|
||||
saveSessionStore,
|
||||
} from "../config/sessions.js";
|
||||
import { registerAgentRunContext } from "../infra/agent-events.js";
|
||||
import { parseTelegramTarget } from "../telegram/targets.js";
|
||||
import { resolveTelegramToken } from "../telegram/token.js";
|
||||
import { normalizeE164, truncateUtf16Safe } from "../utils.js";
|
||||
import { deliverOutboundPayloads } from "../infra/outbound/deliver.js";
|
||||
import { resolveMessageProviderSelection } from "../infra/outbound/provider-selection.js";
|
||||
import {
|
||||
isWhatsAppGroupJid,
|
||||
normalizeWhatsAppTarget,
|
||||
} from "../whatsapp/normalize.js";
|
||||
type OutboundProvider,
|
||||
resolveOutboundTarget,
|
||||
} from "../infra/outbound/targets.js";
|
||||
import { normalizeProviderId } from "../providers/plugins/index.js";
|
||||
import type { ProviderId } from "../providers/plugins/types.js";
|
||||
import { DEFAULT_CHAT_PROVIDER } from "../providers/registry.js";
|
||||
import {
|
||||
INTERNAL_MESSAGE_PROVIDER,
|
||||
normalizeMessageProvider,
|
||||
} from "../utils/message-provider.js";
|
||||
import { truncateUtf16Safe } from "../utils.js";
|
||||
import type { CronJob } from "./types.js";
|
||||
|
||||
export type RunCronAgentTurnResult = {
|
||||
@@ -109,69 +111,23 @@ function isHeartbeatOnlyResponse(
|
||||
});
|
||||
}
|
||||
|
||||
function getMediaList(payload: DeliveryPayload) {
|
||||
return payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
|
||||
}
|
||||
|
||||
async function deliverPayloadsWithMedia(params: {
|
||||
payloads: DeliveryPayload[];
|
||||
sendText: (text: string) => Promise<unknown>;
|
||||
sendMedia: (caption: string, mediaUrl: string) => Promise<unknown>;
|
||||
}) {
|
||||
for (const payload of params.payloads) {
|
||||
const mediaList = getMediaList(payload);
|
||||
if (mediaList.length === 0) {
|
||||
await params.sendText(payload.text ?? "");
|
||||
continue;
|
||||
}
|
||||
let first = true;
|
||||
for (const url of mediaList) {
|
||||
const caption = first ? (payload.text ?? "") : "";
|
||||
first = false;
|
||||
await params.sendMedia(caption, url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deliverChunkedPayloads(params: {
|
||||
payloads: DeliveryPayload[];
|
||||
chunkText: (text: string) => string[];
|
||||
sendText: (text: string) => Promise<unknown>;
|
||||
sendMedia: (caption: string, mediaUrl: string) => Promise<unknown>;
|
||||
}) {
|
||||
for (const payload of params.payloads) {
|
||||
const mediaList = getMediaList(payload);
|
||||
if (mediaList.length === 0) {
|
||||
for (const chunk of params.chunkText(payload.text ?? "")) {
|
||||
await params.sendText(chunk);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let first = true;
|
||||
for (const url of mediaList) {
|
||||
const caption = first ? (payload.text ?? "") : "";
|
||||
first = false;
|
||||
await params.sendMedia(caption, url);
|
||||
}
|
||||
}
|
||||
}
|
||||
function resolveDeliveryTarget(
|
||||
async function resolveDeliveryTarget(
|
||||
cfg: ClawdbotConfig,
|
||||
jobPayload: {
|
||||
provider?:
|
||||
| "last"
|
||||
| "whatsapp"
|
||||
| "telegram"
|
||||
| "discord"
|
||||
| "slack"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "msteams";
|
||||
provider?: "last" | ProviderId;
|
||||
to?: string;
|
||||
},
|
||||
) {
|
||||
const requestedProvider =
|
||||
): Promise<{
|
||||
provider: string;
|
||||
to?: string;
|
||||
accountId?: string;
|
||||
mode: "explicit" | "implicit";
|
||||
error?: Error;
|
||||
}> {
|
||||
const requestedRaw =
|
||||
typeof jobPayload.provider === "string" ? jobPayload.provider : "last";
|
||||
const requestedProvider =
|
||||
normalizeMessageProvider(requestedRaw) ?? requestedRaw;
|
||||
const explicitTo =
|
||||
typeof jobPayload.to === "string" && jobPayload.to.trim()
|
||||
? jobPayload.to.trim()
|
||||
@@ -184,60 +140,46 @@ function resolveDeliveryTarget(
|
||||
const store = loadSessionStore(storePath);
|
||||
const main = store[mainSessionKey];
|
||||
const lastProvider =
|
||||
main?.lastProvider && main.lastProvider !== "webchat"
|
||||
? main.lastProvider
|
||||
main?.lastProvider && main.lastProvider !== INTERNAL_MESSAGE_PROVIDER
|
||||
? (normalizeProviderId(main.lastProvider) ?? main.lastProvider)
|
||||
: undefined;
|
||||
const lastTo = typeof main?.lastTo === "string" ? main.lastTo.trim() : "";
|
||||
const lastAccountId = main?.lastAccountId;
|
||||
|
||||
const provider = (() => {
|
||||
if (
|
||||
requestedProvider === "whatsapp" ||
|
||||
requestedProvider === "telegram" ||
|
||||
requestedProvider === "discord" ||
|
||||
requestedProvider === "slack" ||
|
||||
requestedProvider === "signal" ||
|
||||
requestedProvider === "imessage"
|
||||
) {
|
||||
return requestedProvider;
|
||||
let provider =
|
||||
requestedProvider === "last"
|
||||
? lastProvider
|
||||
: requestedProvider === INTERNAL_MESSAGE_PROVIDER
|
||||
? undefined
|
||||
: normalizeProviderId(requestedProvider);
|
||||
if (!provider) {
|
||||
try {
|
||||
const selection = await resolveMessageProviderSelection({ cfg });
|
||||
provider = selection.provider;
|
||||
} catch {
|
||||
provider = lastProvider ?? DEFAULT_CHAT_PROVIDER;
|
||||
}
|
||||
return lastProvider ?? "whatsapp";
|
||||
})();
|
||||
}
|
||||
|
||||
const rawTo = explicitTo ?? (lastTo || undefined);
|
||||
const telegramTarget =
|
||||
provider === "telegram" && rawTo ? parseTelegramTarget(rawTo) : undefined;
|
||||
|
||||
const sanitizedWhatsappTo = (() => {
|
||||
if (provider !== "whatsapp") return rawTo;
|
||||
if (rawTo && isWhatsAppGroupJid(rawTo)) {
|
||||
return normalizeWhatsAppTarget(rawTo) ?? rawTo;
|
||||
}
|
||||
const rawAllow = cfg.whatsapp?.allowFrom ?? [];
|
||||
if (rawAllow.includes("*")) {
|
||||
return rawTo ? (normalizeWhatsAppTarget(rawTo) ?? rawTo) : rawTo;
|
||||
}
|
||||
const allowFrom = rawAllow
|
||||
.map((val) => normalizeE164(val))
|
||||
.filter((val) => val.length > 1);
|
||||
if (allowFrom.length === 0) {
|
||||
return rawTo ? (normalizeWhatsAppTarget(rawTo) ?? rawTo) : rawTo;
|
||||
}
|
||||
if (!rawTo) return allowFrom[0];
|
||||
const normalized = normalizeWhatsAppTarget(rawTo);
|
||||
if (normalized && allowFrom.includes(normalized)) return normalized;
|
||||
return allowFrom[0];
|
||||
})();
|
||||
|
||||
const to = (() => {
|
||||
if (provider === "telegram" && telegramTarget) return telegramTarget.chatId;
|
||||
if (provider === "whatsapp") return sanitizedWhatsappTo;
|
||||
return rawTo;
|
||||
})();
|
||||
const toCandidate = explicitTo ?? (lastTo || undefined);
|
||||
const mode: "explicit" | "implicit" = explicitTo ? "explicit" : "implicit";
|
||||
if (!toCandidate) {
|
||||
return { provider, to: undefined, accountId: lastAccountId, mode };
|
||||
}
|
||||
|
||||
const resolved = resolveOutboundTarget({
|
||||
provider: provider as Exclude<OutboundProvider, "none">,
|
||||
to: toCandidate,
|
||||
cfg,
|
||||
accountId: provider === lastProvider ? lastAccountId : undefined,
|
||||
mode,
|
||||
});
|
||||
return {
|
||||
provider,
|
||||
to,
|
||||
messageThreadId: telegramTarget?.messageThreadId,
|
||||
to: resolved.ok ? resolved.to : undefined,
|
||||
accountId: provider === lastProvider ? lastAccountId : undefined,
|
||||
mode,
|
||||
error: resolved.ok ? undefined : resolved.error,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -389,7 +331,7 @@ export async function runCronIsolatedAgentTurn(params: {
|
||||
params.job.payload.kind === "agentTurn" &&
|
||||
params.job.payload.bestEffortDeliver === true;
|
||||
|
||||
const resolvedDelivery = resolveDeliveryTarget(params.cfg, {
|
||||
const resolvedDelivery = await resolveDeliveryTarget(params.cfg, {
|
||||
provider:
|
||||
params.job.payload.kind === "agentTurn"
|
||||
? params.job.payload.provider
|
||||
@@ -399,7 +341,6 @@ export async function runCronIsolatedAgentTurn(params: {
|
||||
? params.job.payload.to
|
||||
: undefined,
|
||||
});
|
||||
const { token: telegramToken } = resolveTelegramToken(params.cfg);
|
||||
|
||||
const base =
|
||||
`[cron:${params.job.id} ${params.job.name}] ${params.message}`.trim();
|
||||
@@ -546,194 +487,56 @@ export async function runCronIsolatedAgentTurn(params: {
|
||||
delivery && isHeartbeatOnlyResponse(payloads, Math.max(0, ackMaxChars));
|
||||
|
||||
if (delivery && !skipHeartbeatDelivery) {
|
||||
if (resolvedDelivery.provider === "whatsapp") {
|
||||
if (!resolvedDelivery.to) {
|
||||
if (!bestEffortDeliver)
|
||||
return {
|
||||
status: "error",
|
||||
summary,
|
||||
error: "Cron delivery to WhatsApp requires a recipient.",
|
||||
};
|
||||
if (!resolvedDelivery.to) {
|
||||
const reason =
|
||||
resolvedDelivery.error?.message ??
|
||||
"Cron delivery requires a recipient (--to).";
|
||||
if (!bestEffortDeliver) {
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: "Delivery skipped (no WhatsApp recipient).",
|
||||
status: "error",
|
||||
summary,
|
||||
error: reason,
|
||||
};
|
||||
}
|
||||
const rawTo = resolvedDelivery.to;
|
||||
const to = normalizeWhatsAppTarget(rawTo) ?? rawTo;
|
||||
try {
|
||||
await deliverPayloadsWithMedia({
|
||||
payloads,
|
||||
sendText: (text) =>
|
||||
params.deps.sendMessageWhatsApp(to, text, { verbose: false }),
|
||||
sendMedia: (caption, mediaUrl) =>
|
||||
params.deps.sendMessageWhatsApp(to, caption, {
|
||||
verbose: false,
|
||||
mediaUrl,
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver)
|
||||
return { status: "error", summary, error: String(err) };
|
||||
return { status: "ok", summary };
|
||||
}
|
||||
} else if (resolvedDelivery.provider === "telegram") {
|
||||
if (!resolvedDelivery.to) {
|
||||
if (!bestEffortDeliver)
|
||||
return {
|
||||
status: "error",
|
||||
summary,
|
||||
error: "Cron delivery to Telegram requires a chatId.",
|
||||
};
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: "Delivery skipped (no Telegram chatId).",
|
||||
};
|
||||
}
|
||||
const chatId = resolvedDelivery.to;
|
||||
const messageThreadId = resolvedDelivery.messageThreadId;
|
||||
const textLimit = resolveTextChunkLimit(params.cfg, "telegram");
|
||||
try {
|
||||
await deliverChunkedPayloads({
|
||||
payloads,
|
||||
chunkText: (text) => chunkMarkdownText(text, textLimit),
|
||||
sendText: (text) =>
|
||||
params.deps.sendMessageTelegram(chatId, text, {
|
||||
verbose: false,
|
||||
token: telegramToken || undefined,
|
||||
messageThreadId,
|
||||
}),
|
||||
sendMedia: (caption, mediaUrl) =>
|
||||
params.deps.sendMessageTelegram(chatId, caption, {
|
||||
verbose: false,
|
||||
mediaUrl,
|
||||
token: telegramToken || undefined,
|
||||
messageThreadId,
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver)
|
||||
return { status: "error", summary, error: String(err) };
|
||||
return { status: "ok", summary };
|
||||
}
|
||||
} else if (resolvedDelivery.provider === "discord") {
|
||||
if (!resolvedDelivery.to) {
|
||||
if (!bestEffortDeliver)
|
||||
return {
|
||||
status: "error",
|
||||
summary,
|
||||
error:
|
||||
"Cron delivery to Discord requires --provider discord and --to <channelId|user:ID>",
|
||||
};
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: "Delivery skipped (no Discord destination).",
|
||||
};
|
||||
}
|
||||
const discordTarget = resolvedDelivery.to;
|
||||
try {
|
||||
await deliverPayloadsWithMedia({
|
||||
payloads,
|
||||
sendText: (text) =>
|
||||
params.deps.sendMessageDiscord(discordTarget, text, {
|
||||
token: process.env.DISCORD_BOT_TOKEN,
|
||||
}),
|
||||
sendMedia: (caption, mediaUrl) =>
|
||||
params.deps.sendMessageDiscord(discordTarget, caption, {
|
||||
token: process.env.DISCORD_BOT_TOKEN,
|
||||
mediaUrl,
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver)
|
||||
return { status: "error", summary, error: String(err) };
|
||||
return { status: "ok", summary };
|
||||
}
|
||||
} else if (resolvedDelivery.provider === "slack") {
|
||||
if (!resolvedDelivery.to) {
|
||||
if (!bestEffortDeliver)
|
||||
return {
|
||||
status: "error",
|
||||
summary,
|
||||
error:
|
||||
"Cron delivery to Slack requires --provider slack and --to <channelId|user:ID>",
|
||||
};
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: "Delivery skipped (no Slack destination).",
|
||||
};
|
||||
}
|
||||
const slackTarget = resolvedDelivery.to;
|
||||
const textLimit = resolveTextChunkLimit(params.cfg, "slack");
|
||||
try {
|
||||
await deliverChunkedPayloads({
|
||||
payloads,
|
||||
chunkText: (text) => chunkMarkdownText(text, textLimit),
|
||||
sendText: (text) => params.deps.sendMessageSlack(slackTarget, text),
|
||||
sendMedia: (caption, mediaUrl) =>
|
||||
params.deps.sendMessageSlack(slackTarget, caption, { mediaUrl }),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver)
|
||||
return { status: "error", summary, error: String(err) };
|
||||
return { status: "ok", summary };
|
||||
}
|
||||
} else if (resolvedDelivery.provider === "signal") {
|
||||
if (!resolvedDelivery.to) {
|
||||
if (!bestEffortDeliver)
|
||||
return {
|
||||
status: "error",
|
||||
summary,
|
||||
error: "Cron delivery to Signal requires a recipient.",
|
||||
};
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: "Delivery skipped (no Signal recipient).",
|
||||
};
|
||||
}
|
||||
const to = resolvedDelivery.to;
|
||||
const textLimit = resolveTextChunkLimit(params.cfg, "signal");
|
||||
try {
|
||||
await deliverChunkedPayloads({
|
||||
payloads,
|
||||
chunkText: (text) => chunkText(text, textLimit),
|
||||
sendText: (text) => params.deps.sendMessageSignal(to, text),
|
||||
sendMedia: (caption, mediaUrl) =>
|
||||
params.deps.sendMessageSignal(to, caption, { mediaUrl }),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver)
|
||||
return { status: "error", summary, error: String(err) };
|
||||
return { status: "ok", summary };
|
||||
}
|
||||
} else if (resolvedDelivery.provider === "imessage") {
|
||||
if (!resolvedDelivery.to) {
|
||||
if (!bestEffortDeliver)
|
||||
return {
|
||||
status: "error",
|
||||
summary,
|
||||
error: "Cron delivery to iMessage requires a recipient.",
|
||||
};
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: "Delivery skipped (no iMessage recipient).",
|
||||
};
|
||||
}
|
||||
const to = resolvedDelivery.to;
|
||||
const textLimit = resolveTextChunkLimit(params.cfg, "imessage");
|
||||
try {
|
||||
await deliverChunkedPayloads({
|
||||
payloads,
|
||||
chunkText: (text) => chunkText(text, textLimit),
|
||||
sendText: (text) => params.deps.sendMessageIMessage(to, text),
|
||||
sendMedia: (caption, mediaUrl) =>
|
||||
params.deps.sendMessageIMessage(to, caption, { mediaUrl }),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver)
|
||||
return { status: "error", summary, error: String(err) };
|
||||
return { status: "ok", summary };
|
||||
return {
|
||||
status: "skipped",
|
||||
summary: `Delivery skipped (${reason}).`,
|
||||
};
|
||||
}
|
||||
try {
|
||||
await deliverOutboundPayloads({
|
||||
cfg: params.cfg,
|
||||
provider: resolvedDelivery.provider as Exclude<
|
||||
OutboundProvider,
|
||||
"none"
|
||||
>,
|
||||
to: resolvedDelivery.to,
|
||||
accountId: resolvedDelivery.accountId,
|
||||
payloads,
|
||||
bestEffort: bestEffortDeliver,
|
||||
deps: {
|
||||
sendWhatsApp: params.deps.sendMessageWhatsApp,
|
||||
sendTelegram: params.deps.sendMessageTelegram,
|
||||
sendDiscord: params.deps.sendMessageDiscord,
|
||||
sendSlack: params.deps.sendMessageSlack,
|
||||
sendSignal: params.deps.sendMessageSignal,
|
||||
sendIMessage: params.deps.sendMessageIMessage,
|
||||
sendMSTeams: params.deps.sendMessageMSTeams
|
||||
? async (to, text, opts) =>
|
||||
await params.deps.sendMessageMSTeams({
|
||||
cfg: params.cfg,
|
||||
to,
|
||||
text,
|
||||
mediaUrl: opts?.mediaUrl,
|
||||
})
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
if (!bestEffortDeliver) {
|
||||
return { status: "error", summary, error: String(err) };
|
||||
}
|
||||
return { status: "ok", summary };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-9
@@ -1,3 +1,5 @@
|
||||
import type { ProviderId } from "../providers/plugins/types.js";
|
||||
|
||||
export type CronSchedule =
|
||||
| { kind: "at"; atMs: number }
|
||||
| { kind: "every"; everyMs: number; anchorMs?: number }
|
||||
@@ -6,6 +8,8 @@ export type CronSchedule =
|
||||
export type CronSessionTarget = "main" | "isolated";
|
||||
export type CronWakeMode = "next-heartbeat" | "now";
|
||||
|
||||
export type CronMessageProvider = ProviderId | "last";
|
||||
|
||||
export type CronPayload =
|
||||
| { kind: "systemEvent"; text: string }
|
||||
| {
|
||||
@@ -16,15 +20,7 @@ export type CronPayload =
|
||||
thinking?: string;
|
||||
timeoutSeconds?: number;
|
||||
deliver?: boolean;
|
||||
provider?:
|
||||
| "last"
|
||||
| "whatsapp"
|
||||
| "telegram"
|
||||
| "discord"
|
||||
| "slack"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "msteams";
|
||||
provider?: CronMessageProvider;
|
||||
to?: string;
|
||||
bestEffortDeliver?: boolean;
|
||||
};
|
||||
|
||||
@@ -386,7 +386,9 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
|
||||
const allowFrom = dmConfig?.allowFrom;
|
||||
const mediaMaxBytes =
|
||||
(opts.mediaMaxMb ?? discordCfg.mediaMaxMb ?? 8) * 1024 * 1024;
|
||||
const textLimit = resolveTextChunkLimit(cfg, "discord", account.accountId);
|
||||
const textLimit = resolveTextChunkLimit(cfg, "discord", account.accountId, {
|
||||
fallbackLimit: 2000,
|
||||
});
|
||||
const historyLimit = Math.max(
|
||||
0,
|
||||
opts.historyLimit ??
|
||||
@@ -1701,7 +1703,9 @@ function createDiscordNativeCommand(params: {
|
||||
await deliverDiscordInteractionReply({
|
||||
interaction,
|
||||
payload,
|
||||
textLimit: resolveTextChunkLimit(cfg, "discord", accountId),
|
||||
textLimit: resolveTextChunkLimit(cfg, "discord", accountId, {
|
||||
fallbackLimit: 2000,
|
||||
}),
|
||||
maxLinesPerMessage: discordConfig?.maxLinesPerMessage,
|
||||
preferFollowUp: didReply,
|
||||
});
|
||||
|
||||
+12
-4
@@ -7,6 +7,12 @@ import {
|
||||
resolveStateDir,
|
||||
} from "../config/config.js";
|
||||
import { pickPrimaryTailnetIPv4 } from "../infra/tailnet.js";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
type GatewayClientMode,
|
||||
type GatewayClientName,
|
||||
} from "../utils/message-provider.js";
|
||||
import { GatewayClient } from "./client.js";
|
||||
import { PROTOCOL_VERSION } from "./protocol/index.js";
|
||||
|
||||
@@ -18,10 +24,11 @@ export type CallGatewayOptions = {
|
||||
params?: unknown;
|
||||
expectFinal?: boolean;
|
||||
timeoutMs?: number;
|
||||
clientName?: string;
|
||||
clientName?: GatewayClientName;
|
||||
clientDisplayName?: string;
|
||||
clientVersion?: string;
|
||||
platform?: string;
|
||||
mode?: string;
|
||||
mode?: GatewayClientMode;
|
||||
instanceId?: string;
|
||||
minProtocol?: number;
|
||||
maxProtocol?: number;
|
||||
@@ -191,10 +198,11 @@ export async function callGateway<T = unknown>(
|
||||
token,
|
||||
password,
|
||||
instanceId: opts.instanceId ?? randomUUID(),
|
||||
clientName: opts.clientName ?? "cli",
|
||||
clientName: opts.clientName ?? GATEWAY_CLIENT_NAMES.CLI,
|
||||
clientDisplayName: opts.clientDisplayName,
|
||||
clientVersion: opts.clientVersion ?? "dev",
|
||||
platform: opts.platform,
|
||||
mode: opts.mode ?? "cli",
|
||||
mode: opts.mode ?? GATEWAY_CLIENT_MODES.CLI,
|
||||
minProtocol: opts.minProtocol ?? PROTOCOL_VERSION,
|
||||
maxProtocol: opts.maxProtocol ?? PROTOCOL_VERSION,
|
||||
onHelloOk: async () => {
|
||||
|
||||
+13
-5
@@ -2,6 +2,12 @@ import { randomUUID } from "node:crypto";
|
||||
import { WebSocket } from "ws";
|
||||
import { rawDataToString } from "../infra/ws.js";
|
||||
import { logDebug, logError } from "../logger.js";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
type GatewayClientMode,
|
||||
type GatewayClientName,
|
||||
} from "../utils/message-provider.js";
|
||||
import {
|
||||
type ConnectParams,
|
||||
type EventFrame,
|
||||
@@ -24,10 +30,11 @@ export type GatewayClientOptions = {
|
||||
token?: string;
|
||||
password?: string;
|
||||
instanceId?: string;
|
||||
clientName?: string;
|
||||
clientName?: GatewayClientName;
|
||||
clientDisplayName?: string;
|
||||
clientVersion?: string;
|
||||
platform?: string;
|
||||
mode?: string;
|
||||
mode?: GatewayClientMode;
|
||||
minProtocol?: number;
|
||||
maxProtocol?: number;
|
||||
onEvent?: (evt: EventFrame) => void;
|
||||
@@ -109,10 +116,11 @@ export class GatewayClient {
|
||||
minProtocol: this.opts.minProtocol ?? PROTOCOL_VERSION,
|
||||
maxProtocol: this.opts.maxProtocol ?? PROTOCOL_VERSION,
|
||||
client: {
|
||||
name: this.opts.clientName ?? "gateway-client",
|
||||
id: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
|
||||
displayName: this.opts.clientDisplayName,
|
||||
version: this.opts.clientVersion ?? "dev",
|
||||
platform: this.opts.platform ?? process.platform,
|
||||
mode: this.opts.mode ?? "backend",
|
||||
mode: this.opts.mode ?? GATEWAY_CLIENT_MODES.BACKEND,
|
||||
instanceId: this.opts.instanceId,
|
||||
},
|
||||
caps: [],
|
||||
@@ -135,7 +143,7 @@ export class GatewayClient {
|
||||
err instanceof Error ? err : new Error(String(err)),
|
||||
);
|
||||
const msg = `gateway connect failed: ${String(err)}`;
|
||||
if (this.opts.mode === "probe") logDebug(msg);
|
||||
if (this.opts.mode === GATEWAY_CLIENT_MODES.PROBE) logDebug(msg);
|
||||
else logError(msg);
|
||||
this.ws?.close(1008, "connect failed");
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { listProviderPlugins } from "../providers/plugins/index.js";
|
||||
import {
|
||||
buildGatewayReloadPlan,
|
||||
diffConfigPaths,
|
||||
@@ -35,11 +36,23 @@ describe("buildGatewayReloadPlan", () => {
|
||||
expect(plan.reloadHooks).toBe(true);
|
||||
});
|
||||
|
||||
it("restarts providers for web/telegram changes", () => {
|
||||
const plan = buildGatewayReloadPlan(["web.enabled", "telegram.botToken"]);
|
||||
it("restarts providers when provider config prefixes change", () => {
|
||||
const changedPaths = ["web.enabled", "telegram.botToken"];
|
||||
const plan = buildGatewayReloadPlan(changedPaths);
|
||||
expect(plan.restartGateway).toBe(false);
|
||||
expect(plan.restartProviders.has("whatsapp")).toBe(true);
|
||||
expect(plan.restartProviders.has("telegram")).toBe(true);
|
||||
const expected = new Set(
|
||||
listProviderPlugins()
|
||||
.filter((plugin) =>
|
||||
(plugin.reload?.configPrefixes ?? []).some((prefix) =>
|
||||
changedPaths.some(
|
||||
(path) => path === prefix || path.startsWith(`${prefix}.`),
|
||||
),
|
||||
),
|
||||
)
|
||||
.map((plugin) => plugin.id),
|
||||
);
|
||||
expect(expected.size).toBeGreaterThan(0);
|
||||
expect(plan.restartProviders).toEqual(expected);
|
||||
});
|
||||
|
||||
it("treats gateway.remote as no-op", () => {
|
||||
|
||||
@@ -5,20 +5,17 @@ import type {
|
||||
ConfigFileSnapshot,
|
||||
GatewayReloadMode,
|
||||
} from "../config/config.js";
|
||||
import {
|
||||
listProviderPlugins,
|
||||
type ProviderId,
|
||||
} from "../providers/plugins/index.js";
|
||||
|
||||
export type GatewayReloadSettings = {
|
||||
mode: GatewayReloadMode;
|
||||
debounceMs: number;
|
||||
};
|
||||
|
||||
export type ProviderKind =
|
||||
| "whatsapp"
|
||||
| "telegram"
|
||||
| "discord"
|
||||
| "slack"
|
||||
| "signal"
|
||||
| "imessage"
|
||||
| "msteams";
|
||||
export type ProviderKind = ProviderId;
|
||||
|
||||
export type GatewayReloadPlan = {
|
||||
changedPaths: string[];
|
||||
@@ -46,20 +43,14 @@ type ReloadAction =
|
||||
| "restart-browser-control"
|
||||
| "restart-cron"
|
||||
| "restart-heartbeat"
|
||||
| "restart-provider:whatsapp"
|
||||
| "restart-provider:telegram"
|
||||
| "restart-provider:discord"
|
||||
| "restart-provider:slack"
|
||||
| "restart-provider:signal"
|
||||
| "restart-provider:imessage"
|
||||
| "restart-provider:msteams";
|
||||
| `restart-provider:${ProviderId}`;
|
||||
|
||||
const DEFAULT_RELOAD_SETTINGS: GatewayReloadSettings = {
|
||||
mode: "hybrid",
|
||||
debounceMs: 300,
|
||||
};
|
||||
|
||||
const RELOAD_RULES: ReloadRule[] = [
|
||||
const BASE_RELOAD_RULES: ReloadRule[] = [
|
||||
{ prefix: "gateway.remote", kind: "none" },
|
||||
{ prefix: "gateway.reload", kind: "none" },
|
||||
{ prefix: "hooks.gmail", kind: "hot", actions: ["restart-gmail-watcher"] },
|
||||
@@ -69,29 +60,28 @@ const RELOAD_RULES: ReloadRule[] = [
|
||||
kind: "hot",
|
||||
actions: ["restart-heartbeat"],
|
||||
},
|
||||
{ prefix: "agent.heartbeat", kind: "hot", actions: ["restart-heartbeat"] },
|
||||
{ prefix: "cron", kind: "hot", actions: ["restart-cron"] },
|
||||
{
|
||||
prefix: "browser",
|
||||
kind: "hot",
|
||||
actions: ["restart-browser-control"],
|
||||
},
|
||||
{ prefix: "web", kind: "hot", actions: ["restart-provider:whatsapp"] },
|
||||
{ prefix: "telegram", kind: "hot", actions: ["restart-provider:telegram"] },
|
||||
{ prefix: "discord", kind: "hot", actions: ["restart-provider:discord"] },
|
||||
{ prefix: "slack", kind: "hot", actions: ["restart-provider:slack"] },
|
||||
{ prefix: "signal", kind: "hot", actions: ["restart-provider:signal"] },
|
||||
{ prefix: "imessage", kind: "hot", actions: ["restart-provider:imessage"] },
|
||||
{ prefix: "msteams", kind: "hot", actions: ["restart-provider:msteams"] },
|
||||
];
|
||||
|
||||
const BASE_RELOAD_RULES_TAIL: ReloadRule[] = [
|
||||
{ prefix: "identity", kind: "none" },
|
||||
{ prefix: "wizard", kind: "none" },
|
||||
{ prefix: "logging", kind: "none" },
|
||||
{ prefix: "models", kind: "none" },
|
||||
{ prefix: "agents", kind: "none" },
|
||||
{ prefix: "tools", kind: "none" },
|
||||
{ prefix: "bindings", kind: "none" },
|
||||
{ prefix: "audio", kind: "none" },
|
||||
{ prefix: "wizard", kind: "none" },
|
||||
{ prefix: "logging", kind: "none" },
|
||||
{ prefix: "models", kind: "none" },
|
||||
{ prefix: "agent", kind: "none" },
|
||||
{ prefix: "routing", kind: "none" },
|
||||
{ prefix: "messages", kind: "none" },
|
||||
{ prefix: "session", kind: "none" },
|
||||
{ prefix: "whatsapp", kind: "none" },
|
||||
{ prefix: "talk", kind: "none" },
|
||||
{ prefix: "skills", kind: "none" },
|
||||
{ prefix: "ui", kind: "none" },
|
||||
@@ -101,8 +91,39 @@ const RELOAD_RULES: ReloadRule[] = [
|
||||
{ prefix: "canvasHost", kind: "restart" },
|
||||
];
|
||||
|
||||
let cachedReloadRules: ReloadRule[] | null = null;
|
||||
|
||||
function listReloadRules(): ReloadRule[] {
|
||||
if (cachedReloadRules) return cachedReloadRules;
|
||||
// Provider docking: plugins contribute hot reload/no-op prefixes here.
|
||||
const providerReloadRules: ReloadRule[] = listProviderPlugins().flatMap(
|
||||
(plugin) => [
|
||||
...(plugin.reload?.configPrefixes ?? []).map(
|
||||
(prefix): ReloadRule => ({
|
||||
prefix,
|
||||
kind: "hot",
|
||||
actions: [`restart-provider:${plugin.id}` as ReloadAction],
|
||||
}),
|
||||
),
|
||||
...(plugin.reload?.noopPrefixes ?? []).map(
|
||||
(prefix): ReloadRule => ({
|
||||
prefix,
|
||||
kind: "none",
|
||||
}),
|
||||
),
|
||||
],
|
||||
);
|
||||
const rules = [
|
||||
...BASE_RELOAD_RULES,
|
||||
...providerReloadRules,
|
||||
...BASE_RELOAD_RULES_TAIL,
|
||||
];
|
||||
cachedReloadRules = rules;
|
||||
return rules;
|
||||
}
|
||||
|
||||
function matchRule(path: string): ReloadRule | null {
|
||||
for (const rule of RELOAD_RULES) {
|
||||
for (const rule of listReloadRules()) {
|
||||
if (path === rule.prefix || path.startsWith(`${rule.prefix}.`)) return rule;
|
||||
}
|
||||
return null;
|
||||
@@ -186,6 +207,11 @@ export function buildGatewayReloadPlan(
|
||||
};
|
||||
|
||||
const applyAction = (action: ReloadAction) => {
|
||||
if (action.startsWith("restart-provider:")) {
|
||||
const provider = action.slice("restart-provider:".length) as ProviderId;
|
||||
plan.restartProviders.add(provider);
|
||||
return;
|
||||
}
|
||||
switch (action) {
|
||||
case "reload-hooks":
|
||||
plan.reloadHooks = true;
|
||||
@@ -202,27 +228,6 @@ export function buildGatewayReloadPlan(
|
||||
case "restart-heartbeat":
|
||||
plan.restartHeartbeat = true;
|
||||
break;
|
||||
case "restart-provider:whatsapp":
|
||||
plan.restartProviders.add("whatsapp");
|
||||
break;
|
||||
case "restart-provider:telegram":
|
||||
plan.restartProviders.add("telegram");
|
||||
break;
|
||||
case "restart-provider:discord":
|
||||
plan.restartProviders.add("discord");
|
||||
break;
|
||||
case "restart-provider:slack":
|
||||
plan.restartProviders.add("slack");
|
||||
break;
|
||||
case "restart-provider:signal":
|
||||
plan.restartProviders.add("signal");
|
||||
break;
|
||||
case "restart-provider:imessage":
|
||||
plan.restartProviders.add("imessage");
|
||||
break;
|
||||
case "restart-provider:msteams":
|
||||
plan.restartProviders.add("msteams");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,10 @@ import { resolveClawdbotAgentDir } from "../agents/agent-paths.js";
|
||||
import { getApiKeyForModel } from "../agents/model-auth.js";
|
||||
import { ensureClawdbotModelsJson } from "../agents/models-config.js";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
} from "../utils/message-provider.js";
|
||||
import { resolveUserPath } from "../utils.js";
|
||||
import { GatewayClient } from "./client.js";
|
||||
import { renderCatNoncePngBase64 } from "./live-image-probe.js";
|
||||
@@ -115,7 +119,6 @@ function editDistance(a: string, b: string): number {
|
||||
|
||||
return prev[bLen] ?? Number.POSITIVE_INFINITY;
|
||||
}
|
||||
|
||||
async function getFreePort(): Promise<number> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const srv = createServer();
|
||||
@@ -179,9 +182,10 @@ async function connectClient(params: { url: string; token: string }) {
|
||||
const client = new GatewayClient({
|
||||
url: params.url,
|
||||
token: params.token,
|
||||
clientName: "vitest-live",
|
||||
clientName: GATEWAY_CLIENT_NAMES.TEST,
|
||||
clientDisplayName: "vitest-live",
|
||||
clientVersion: "dev",
|
||||
mode: "test",
|
||||
mode: GATEWAY_CLIENT_MODES.TEST,
|
||||
onHelloOk: () => stop(undefined, client),
|
||||
onConnectError: (err) => stop(err),
|
||||
onClose: (code, reason) =>
|
||||
@@ -491,7 +495,6 @@ describeLive("gateway live (dev agent, profile keys)", () => {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Regression: tool-call-only turn followed by a user message (OpenAI responses bug class).
|
||||
if (
|
||||
(model.provider === "openai" &&
|
||||
|
||||
@@ -5,6 +5,10 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
} from "../utils/message-provider.js";
|
||||
|
||||
import { GatewayClient } from "./client.js";
|
||||
import { startGatewayServer } from "./server.js";
|
||||
@@ -246,9 +250,10 @@ async function connectClient(params: { url: string; token: string }) {
|
||||
const client = new GatewayClient({
|
||||
url: params.url,
|
||||
token: params.token,
|
||||
clientName: "vitest-mock-openai",
|
||||
clientName: GATEWAY_CLIENT_NAMES.TEST,
|
||||
clientDisplayName: "vitest-mock-openai",
|
||||
clientVersion: "dev",
|
||||
mode: "test",
|
||||
mode: GATEWAY_CLIENT_MODES.TEST,
|
||||
onHelloOk: () => stop(undefined, client),
|
||||
onConnectError: (err) => stop(err),
|
||||
onClose: (code, reason) =>
|
||||
|
||||
@@ -8,6 +8,10 @@ import { describe, expect, it } from "vitest";
|
||||
import { WebSocket } from "ws";
|
||||
|
||||
import { rawDataToString } from "../infra/ws.js";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
} from "../utils/message-provider.js";
|
||||
import { PROTOCOL_VERSION } from "./protocol/index.js";
|
||||
|
||||
async function getFreePort(): Promise<number> {
|
||||
@@ -92,10 +96,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,
|
||||
@@ -133,9 +138,10 @@ async function connectClient(params: { url: string; token?: string }) {
|
||||
const client = new GatewayClient({
|
||||
url: params.url,
|
||||
token: params.token,
|
||||
clientName: "vitest-wizard",
|
||||
clientName: GATEWAY_CLIENT_NAMES.TEST,
|
||||
clientDisplayName: "vitest-wizard",
|
||||
clientVersion: "dev",
|
||||
mode: "test",
|
||||
mode: GATEWAY_CLIENT_MODES.TEST,
|
||||
onHelloOk: () => stop(undefined, client),
|
||||
onConnectError: (err) => stop(err),
|
||||
onClose: (code, reason) =>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import {
|
||||
listProviderPlugins,
|
||||
type ProviderId,
|
||||
} from "../providers/plugins/index.js";
|
||||
import { normalizeMessageProvider } from "../utils/message-provider.js";
|
||||
import {
|
||||
type HookMappingResolved,
|
||||
@@ -147,16 +151,10 @@ export type HookAgentPayload = {
|
||||
|
||||
const HOOK_PROVIDER_VALUES = [
|
||||
"last",
|
||||
"whatsapp",
|
||||
"telegram",
|
||||
"discord",
|
||||
"slack",
|
||||
"signal",
|
||||
"imessage",
|
||||
"msteams",
|
||||
] as const;
|
||||
...listProviderPlugins().map((plugin) => plugin.id),
|
||||
];
|
||||
|
||||
export type HookMessageProvider = (typeof HOOK_PROVIDER_VALUES)[number];
|
||||
export type HookMessageProvider = ProviderId | "last";
|
||||
|
||||
const hookProviderSet = new Set<string>(HOOK_PROVIDER_VALUES);
|
||||
export const HOOK_PROVIDER_ERROR = `provider must be ${HOOK_PROVIDER_VALUES.join("|")}`;
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type { SystemPresence } from "../infra/system-presence.js";
|
||||
import {
|
||||
GATEWAY_CLIENT_MODES,
|
||||
GATEWAY_CLIENT_NAMES,
|
||||
} from "../utils/message-provider.js";
|
||||
import { GatewayClient } from "./client.js";
|
||||
|
||||
export type GatewayProbeAuth = {
|
||||
@@ -56,9 +60,9 @@ export async function probeGateway(opts: {
|
||||
url: opts.url,
|
||||
token: opts.auth?.token,
|
||||
password: opts.auth?.password,
|
||||
clientName: "cli",
|
||||
clientName: GATEWAY_CLIENT_NAMES.CLI,
|
||||
clientVersion: "dev",
|
||||
mode: "probe",
|
||||
mode: GATEWAY_CLIENT_MODES.PROBE,
|
||||
instanceId,
|
||||
onConnectError: (err) => {
|
||||
connectError = formatError(err);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
export const GATEWAY_CLIENT_IDS = {
|
||||
WEBCHAT_UI: "webchat-ui",
|
||||
CONTROL_UI: "clawdbot-control-ui",
|
||||
WEBCHAT: "webchat",
|
||||
CLI: "cli",
|
||||
GATEWAY_CLIENT: "gateway-client",
|
||||
MACOS_APP: "clawdbot-macos",
|
||||
TEST: "test",
|
||||
FINGERPRINT: "fingerprint",
|
||||
PROBE: "clawdbot-probe",
|
||||
} as const;
|
||||
|
||||
export type GatewayClientId =
|
||||
(typeof GATEWAY_CLIENT_IDS)[keyof typeof GATEWAY_CLIENT_IDS];
|
||||
|
||||
// Back-compat naming (internal): these values are IDs, not display names.
|
||||
export const GATEWAY_CLIENT_NAMES = GATEWAY_CLIENT_IDS;
|
||||
export type GatewayClientName = GatewayClientId;
|
||||
|
||||
export const GATEWAY_CLIENT_MODES = {
|
||||
WEBCHAT: "webchat",
|
||||
CLI: "cli",
|
||||
UI: "ui",
|
||||
BACKEND: "backend",
|
||||
PROBE: "probe",
|
||||
TEST: "test",
|
||||
} as const;
|
||||
|
||||
export type GatewayClientMode =
|
||||
(typeof GATEWAY_CLIENT_MODES)[keyof typeof GATEWAY_CLIENT_MODES];
|
||||
|
||||
export type GatewayClientInfo = {
|
||||
id: GatewayClientId;
|
||||
displayName?: string;
|
||||
version: string;
|
||||
platform: string;
|
||||
deviceFamily?: string;
|
||||
modelIdentifier?: string;
|
||||
mode: GatewayClientMode;
|
||||
instanceId?: string;
|
||||
};
|
||||
|
||||
const GATEWAY_CLIENT_ID_SET = new Set<GatewayClientId>(
|
||||
Object.values(GATEWAY_CLIENT_IDS),
|
||||
);
|
||||
const GATEWAY_CLIENT_MODE_SET = new Set<GatewayClientMode>(
|
||||
Object.values(GATEWAY_CLIENT_MODES),
|
||||
);
|
||||
|
||||
export function normalizeGatewayClientId(
|
||||
raw?: string | null,
|
||||
): GatewayClientId | undefined {
|
||||
const normalized = raw?.trim().toLowerCase();
|
||||
if (!normalized) return undefined;
|
||||
return GATEWAY_CLIENT_ID_SET.has(normalized as GatewayClientId)
|
||||
? (normalized as GatewayClientId)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function normalizeGatewayClientName(
|
||||
raw?: string | null,
|
||||
): GatewayClientName | undefined {
|
||||
return normalizeGatewayClientId(raw);
|
||||
}
|
||||
|
||||
export function normalizeGatewayClientMode(
|
||||
raw?: string | null,
|
||||
): GatewayClientMode | undefined {
|
||||
const normalized = raw?.trim().toLowerCase();
|
||||
if (!normalized) return undefined;
|
||||
return GATEWAY_CLIENT_MODE_SET.has(normalized as GatewayClientMode)
|
||||
? (normalized as GatewayClientMode)
|
||||
: undefined;
|
||||
}
|
||||
@@ -86,8 +86,12 @@ import {
|
||||
type PresenceEntry,
|
||||
PresenceEntrySchema,
|
||||
ProtocolSchemas,
|
||||
type ProvidersLogoutParams,
|
||||
ProvidersLogoutParamsSchema,
|
||||
type ProvidersStatusParams,
|
||||
ProvidersStatusParamsSchema,
|
||||
type ProvidersStatusResult,
|
||||
ProvidersStatusResultSchema,
|
||||
type RequestFrame,
|
||||
RequestFrameSchema,
|
||||
type ResponseFrame,
|
||||
@@ -247,6 +251,9 @@ export const validateTalkModeParams =
|
||||
export const validateProvidersStatusParams = ajv.compile<ProvidersStatusParams>(
|
||||
ProvidersStatusParamsSchema,
|
||||
);
|
||||
export const validateProvidersLogoutParams = ajv.compile<ProvidersLogoutParams>(
|
||||
ProvidersLogoutParamsSchema,
|
||||
);
|
||||
export const validateModelsListParams = ajv.compile<ModelsListParams>(
|
||||
ModelsListParamsSchema,
|
||||
);
|
||||
@@ -344,6 +351,8 @@ export {
|
||||
WizardStartResultSchema,
|
||||
WizardStatusResultSchema,
|
||||
ProvidersStatusParamsSchema,
|
||||
ProvidersStatusResultSchema,
|
||||
ProvidersLogoutParamsSchema,
|
||||
WebLoginStartParamsSchema,
|
||||
WebLoginWaitParamsSchema,
|
||||
AgentSummarySchema,
|
||||
@@ -409,6 +418,8 @@ export type {
|
||||
WizardStatusResult,
|
||||
TalkModeParams,
|
||||
ProvidersStatusParams,
|
||||
ProvidersStatusResult,
|
||||
ProvidersLogoutParams,
|
||||
WebLoginStartParams,
|
||||
WebLoginWaitParams,
|
||||
AgentSummary,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { type Static, type TSchema, Type } from "@sinclair/typebox";
|
||||
import { SESSION_LABEL_MAX_LENGTH } from "../../sessions/session-label.js";
|
||||
import { GATEWAY_CLIENT_IDS, GATEWAY_CLIENT_MODES } from "./client-info.js";
|
||||
|
||||
const NonEmptyString = Type.String({ minLength: 1 });
|
||||
const SessionLabelString = Type.String({
|
||||
@@ -7,6 +8,13 @@ const SessionLabelString = Type.String({
|
||||
maxLength: SESSION_LABEL_MAX_LENGTH,
|
||||
});
|
||||
|
||||
const GatewayClientIdSchema = Type.Union(
|
||||
Object.values(GATEWAY_CLIENT_IDS).map((value) => Type.Literal(value)),
|
||||
);
|
||||
const GatewayClientModeSchema = Type.Union(
|
||||
Object.values(GATEWAY_CLIENT_MODES).map((value) => Type.Literal(value)),
|
||||
);
|
||||
|
||||
export const PresenceEntrySchema = Type.Object(
|
||||
{
|
||||
host: Type.Optional(NonEmptyString),
|
||||
@@ -69,12 +77,13 @@ export const ConnectParamsSchema = Type.Object(
|
||||
maxProtocol: Type.Integer({ minimum: 1 }),
|
||||
client: Type.Object(
|
||||
{
|
||||
name: NonEmptyString,
|
||||
id: GatewayClientIdSchema,
|
||||
displayName: Type.Optional(NonEmptyString),
|
||||
version: NonEmptyString,
|
||||
platform: NonEmptyString,
|
||||
deviceFamily: Type.Optional(NonEmptyString),
|
||||
modelIdentifier: Type.Optional(NonEmptyString),
|
||||
mode: NonEmptyString,
|
||||
mode: GatewayClientModeSchema,
|
||||
instanceId: Type.Optional(NonEmptyString),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
@@ -587,6 +596,68 @@ export const ProvidersStatusParamsSchema = Type.Object(
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
// Provider docking: providers.status is intentionally schema-light so new
|
||||
// providers can ship without protocol updates.
|
||||
export const ProviderAccountSnapshotSchema = Type.Object(
|
||||
{
|
||||
accountId: NonEmptyString,
|
||||
name: Type.Optional(Type.String()),
|
||||
enabled: Type.Optional(Type.Boolean()),
|
||||
configured: Type.Optional(Type.Boolean()),
|
||||
linked: Type.Optional(Type.Boolean()),
|
||||
running: Type.Optional(Type.Boolean()),
|
||||
connected: Type.Optional(Type.Boolean()),
|
||||
reconnectAttempts: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
lastConnectedAt: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
lastError: Type.Optional(Type.String()),
|
||||
lastStartAt: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
lastStopAt: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
lastInboundAt: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
lastOutboundAt: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
lastProbeAt: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
mode: Type.Optional(Type.String()),
|
||||
dmPolicy: Type.Optional(Type.String()),
|
||||
allowFrom: Type.Optional(Type.Array(Type.String())),
|
||||
tokenSource: Type.Optional(Type.String()),
|
||||
botTokenSource: Type.Optional(Type.String()),
|
||||
appTokenSource: Type.Optional(Type.String()),
|
||||
baseUrl: Type.Optional(Type.String()),
|
||||
allowUnmentionedGroups: Type.Optional(Type.Boolean()),
|
||||
cliPath: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
||||
dbPath: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
||||
port: Type.Optional(
|
||||
Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
|
||||
),
|
||||
probe: Type.Optional(Type.Unknown()),
|
||||
audit: Type.Optional(Type.Unknown()),
|
||||
application: Type.Optional(Type.Unknown()),
|
||||
},
|
||||
{ additionalProperties: true },
|
||||
);
|
||||
|
||||
export const ProvidersStatusResultSchema = Type.Object(
|
||||
{
|
||||
ts: Type.Integer({ minimum: 0 }),
|
||||
providerOrder: Type.Array(NonEmptyString),
|
||||
providerLabels: Type.Record(NonEmptyString, NonEmptyString),
|
||||
providers: Type.Record(NonEmptyString, Type.Unknown()),
|
||||
providerAccounts: Type.Record(
|
||||
NonEmptyString,
|
||||
Type.Array(ProviderAccountSnapshotSchema),
|
||||
),
|
||||
providerDefaultAccountId: Type.Record(NonEmptyString, NonEmptyString),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const ProvidersLogoutParamsSchema = Type.Object(
|
||||
{
|
||||
provider: NonEmptyString,
|
||||
accountId: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const WebLoginStartParamsSchema = Type.Object(
|
||||
{
|
||||
force: Type.Optional(Type.Boolean()),
|
||||
@@ -718,15 +789,7 @@ export const CronPayloadSchema = Type.Union([
|
||||
timeoutSeconds: Type.Optional(Type.Integer({ minimum: 1 })),
|
||||
deliver: Type.Optional(Type.Boolean()),
|
||||
provider: Type.Optional(
|
||||
Type.Union([
|
||||
Type.Literal("last"),
|
||||
Type.Literal("whatsapp"),
|
||||
Type.Literal("telegram"),
|
||||
Type.Literal("discord"),
|
||||
Type.Literal("slack"),
|
||||
Type.Literal("signal"),
|
||||
Type.Literal("imessage"),
|
||||
]),
|
||||
Type.Union([Type.Literal("last"), NonEmptyString]),
|
||||
),
|
||||
to: Type.Optional(Type.String()),
|
||||
bestEffortDeliver: Type.Optional(Type.Boolean()),
|
||||
@@ -975,6 +1038,8 @@ export const ProtocolSchemas: Record<string, TSchema> = {
|
||||
WizardStatusResult: WizardStatusResultSchema,
|
||||
TalkModeParams: TalkModeParamsSchema,
|
||||
ProvidersStatusParams: ProvidersStatusParamsSchema,
|
||||
ProvidersStatusResult: ProvidersStatusResultSchema,
|
||||
ProvidersLogoutParams: ProvidersLogoutParamsSchema,
|
||||
WebLoginStartParams: WebLoginStartParamsSchema,
|
||||
WebLoginWaitParams: WebLoginWaitParamsSchema,
|
||||
AgentSummary: AgentSummarySchema,
|
||||
@@ -1006,7 +1071,7 @@ export const ProtocolSchemas: Record<string, TSchema> = {
|
||||
ShutdownEvent: ShutdownEventSchema,
|
||||
};
|
||||
|
||||
export const PROTOCOL_VERSION = 2 as const;
|
||||
export const PROTOCOL_VERSION = 3 as const;
|
||||
|
||||
export type ConnectParams = Static<typeof ConnectParamsSchema>;
|
||||
export type HelloOk = Static<typeof HelloOkSchema>;
|
||||
@@ -1052,6 +1117,8 @@ export type WizardStartResult = Static<typeof WizardStartResultSchema>;
|
||||
export type WizardStatusResult = Static<typeof WizardStatusResultSchema>;
|
||||
export type TalkModeParams = Static<typeof TalkModeParamsSchema>;
|
||||
export type ProvidersStatusParams = Static<typeof ProvidersStatusParamsSchema>;
|
||||
export type ProvidersStatusResult = Static<typeof ProvidersStatusResultSchema>;
|
||||
export type ProvidersLogoutParams = Static<typeof ProvidersLogoutParamsSchema>;
|
||||
export type WebLoginStartParams = Static<typeof WebLoginStartParamsSchema>;
|
||||
export type WebLoginWaitParams = Static<typeof WebLoginWaitParamsSchema>;
|
||||
export type AgentSummary = Static<typeof AgentSummarySchema>;
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
setVoiceWakeTriggers,
|
||||
} from "../infra/voicewake.js";
|
||||
import { clearCommandLane } from "../process/command-queue.js";
|
||||
import { normalizeProviderId } from "../providers/plugins/index.js";
|
||||
import { normalizeMainKey } from "../routing/session-key.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
import {
|
||||
@@ -1100,14 +1101,7 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
||||
|
||||
const channelRaw =
|
||||
typeof link?.channel === "string" ? link.channel.trim() : "";
|
||||
const channel = channelRaw.toLowerCase();
|
||||
const provider =
|
||||
channel === "whatsapp" ||
|
||||
channel === "telegram" ||
|
||||
channel === "signal" ||
|
||||
channel === "imessage"
|
||||
? channel
|
||||
: undefined;
|
||||
const provider = normalizeProviderId(channelRaw) ?? undefined;
|
||||
const to =
|
||||
typeof link?.to === "string" && link.to.trim()
|
||||
? link.to.trim()
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
saveSessionStore,
|
||||
} from "../../config/sessions.js";
|
||||
import { registerAgentRunContext } from "../../infra/agent-events.js";
|
||||
import { resolveOutboundTarget } from "../../infra/outbound/targets.js";
|
||||
import { DEFAULT_CHAT_PROVIDER } from "../../providers/registry.js";
|
||||
import { normalizeMainKey } from "../../routing/session-key.js";
|
||||
import { defaultRuntime } from "../../runtime.js";
|
||||
import { resolveSendPolicy } from "../../sessions/send-policy.js";
|
||||
@@ -18,11 +20,6 @@ import {
|
||||
isGatewayMessageProvider,
|
||||
normalizeMessageProvider,
|
||||
} from "../../utils/message-provider.js";
|
||||
import { normalizeE164 } from "../../utils.js";
|
||||
import {
|
||||
isWhatsAppGroupJid,
|
||||
normalizeWhatsAppTarget,
|
||||
} from "../../whatsapp/normalize.js";
|
||||
import { parseMessageWithAttachments } from "../chat-attachments.js";
|
||||
import {
|
||||
type AgentWaitParams,
|
||||
@@ -238,7 +235,9 @@ export const agentHandlers: GatewayRequestHandlers = {
|
||||
if (lastProvider && lastProvider !== INTERNAL_MESSAGE_PROVIDER) {
|
||||
return lastProvider;
|
||||
}
|
||||
return wantsDelivery ? "whatsapp" : INTERNAL_MESSAGE_PROVIDER;
|
||||
return wantsDelivery
|
||||
? DEFAULT_CHAT_PROVIDER
|
||||
: INTERNAL_MESSAGE_PROVIDER;
|
||||
}
|
||||
|
||||
if (isGatewayMessageProvider(requestedProvider)) return requestedProvider;
|
||||
@@ -246,59 +245,35 @@ export const agentHandlers: GatewayRequestHandlers = {
|
||||
if (lastProvider && lastProvider !== INTERNAL_MESSAGE_PROVIDER) {
|
||||
return lastProvider;
|
||||
}
|
||||
return wantsDelivery ? "whatsapp" : INTERNAL_MESSAGE_PROVIDER;
|
||||
return wantsDelivery ? DEFAULT_CHAT_PROVIDER : INTERNAL_MESSAGE_PROVIDER;
|
||||
})();
|
||||
|
||||
const resolvedTo = (() => {
|
||||
const explicit =
|
||||
typeof request.to === "string" && request.to.trim()
|
||||
? request.to.trim()
|
||||
: undefined;
|
||||
if (explicit) return explicit;
|
||||
if (isDeliverableMessageProvider(resolvedProvider)) {
|
||||
return lastTo || undefined;
|
||||
}
|
||||
return undefined;
|
||||
})();
|
||||
|
||||
const sanitizedTo = (() => {
|
||||
// If we derived a WhatsApp recipient from session "lastTo", ensure it is still valid
|
||||
// for the configured allowlist. Otherwise, fall back to the first allowed number so
|
||||
// voice wake doesn't silently route to stale/test recipients.
|
||||
if (resolvedProvider !== "whatsapp") return resolvedTo;
|
||||
const explicit =
|
||||
typeof request.to === "string" && request.to.trim()
|
||||
? request.to.trim()
|
||||
: undefined;
|
||||
if (explicit) {
|
||||
if (!resolvedTo) return resolvedTo;
|
||||
return normalizeWhatsAppTarget(resolvedTo) ?? resolvedTo;
|
||||
}
|
||||
if (resolvedTo && isWhatsAppGroupJid(resolvedTo)) {
|
||||
return normalizeWhatsAppTarget(resolvedTo) ?? resolvedTo;
|
||||
}
|
||||
|
||||
const explicitTo =
|
||||
typeof request.to === "string" && request.to.trim()
|
||||
? request.to.trim()
|
||||
: undefined;
|
||||
const deliveryTargetMode = explicitTo
|
||||
? "explicit"
|
||||
: isDeliverableMessageProvider(resolvedProvider)
|
||||
? "implicit"
|
||||
: undefined;
|
||||
let resolvedTo =
|
||||
explicitTo ||
|
||||
(isDeliverableMessageProvider(resolvedProvider)
|
||||
? lastTo || undefined
|
||||
: undefined);
|
||||
if (!resolvedTo && isDeliverableMessageProvider(resolvedProvider)) {
|
||||
const cfg = cfgForAgent ?? loadConfig();
|
||||
const rawAllow = cfg.whatsapp?.allowFrom ?? [];
|
||||
if (rawAllow.includes("*")) {
|
||||
return resolvedTo
|
||||
? (normalizeWhatsAppTarget(resolvedTo) ?? resolvedTo)
|
||||
: resolvedTo;
|
||||
const fallback = resolveOutboundTarget({
|
||||
provider: resolvedProvider,
|
||||
cfg,
|
||||
accountId: sessionEntry?.lastAccountId ?? undefined,
|
||||
mode: "implicit",
|
||||
});
|
||||
if (fallback.ok) {
|
||||
resolvedTo = fallback.to;
|
||||
}
|
||||
const allowFrom = rawAllow
|
||||
.map((val) => normalizeE164(val))
|
||||
.filter((val) => val.length > 1);
|
||||
if (allowFrom.length === 0) return resolvedTo;
|
||||
|
||||
const normalizedLast =
|
||||
typeof resolvedTo === "string" && resolvedTo.trim()
|
||||
? normalizeWhatsAppTarget(resolvedTo)
|
||||
: undefined;
|
||||
if (normalizedLast && allowFrom.includes(normalizedLast)) {
|
||||
return normalizedLast;
|
||||
}
|
||||
return allowFrom[0];
|
||||
})();
|
||||
}
|
||||
|
||||
const deliver =
|
||||
request.deliver === true &&
|
||||
@@ -321,11 +296,12 @@ export const agentHandlers: GatewayRequestHandlers = {
|
||||
{
|
||||
message,
|
||||
images,
|
||||
to: sanitizedTo,
|
||||
to: resolvedTo,
|
||||
sessionId: resolvedSessionId,
|
||||
sessionKey: requestedSessionKey,
|
||||
thinking: request.thinking,
|
||||
deliver,
|
||||
deliveryTargetMode,
|
||||
provider: resolvedProvider,
|
||||
timeout: request.timeout?.toString(),
|
||||
bestEffortDeliver,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { mergeSessionEntry, saveSessionStore } from "../../config/sessions.js";
|
||||
import { registerAgentRunContext } from "../../infra/agent-events.js";
|
||||
import { defaultRuntime } from "../../runtime.js";
|
||||
import { resolveSendPolicy } from "../../sessions/send-policy.js";
|
||||
import { INTERNAL_MESSAGE_PROVIDER } from "../../utils/message-provider.js";
|
||||
import {
|
||||
abortChatRunById,
|
||||
abortChatRunsForSessionKey,
|
||||
@@ -328,7 +329,7 @@ export const chatHandlers: GatewayRequestHandlers = {
|
||||
thinking: p.thinking,
|
||||
deliver: p.deliver,
|
||||
timeout: Math.ceil(timeoutMs / 1000).toString(),
|
||||
messageProvider: "webchat",
|
||||
messageProvider: INTERNAL_MESSAGE_PROVIDER,
|
||||
abortSignal: abortController.signal,
|
||||
},
|
||||
defaultRuntime,
|
||||
|
||||
@@ -1,66 +1,80 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import {
|
||||
loadConfig,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
} from "../../config/config.js";
|
||||
import type { TelegramGroupConfig } from "../../config/types.js";
|
||||
import {
|
||||
listDiscordAccountIds,
|
||||
resolveDefaultDiscordAccountId,
|
||||
resolveDiscordAccount,
|
||||
} from "../../discord/accounts.js";
|
||||
import {
|
||||
auditDiscordChannelPermissions,
|
||||
collectDiscordAuditChannelIds,
|
||||
} from "../../discord/audit.js";
|
||||
import { type DiscordProbe, probeDiscord } from "../../discord/probe.js";
|
||||
import {
|
||||
listIMessageAccountIds,
|
||||
resolveDefaultIMessageAccountId,
|
||||
resolveIMessageAccount,
|
||||
} from "../../imessage/accounts.js";
|
||||
import { type IMessageProbe, probeIMessage } from "../../imessage/probe.js";
|
||||
import { loadConfig, readConfigFileSnapshot } from "../../config/config.js";
|
||||
import { getProviderActivity } from "../../infra/provider-activity.js";
|
||||
import { resolveProviderDefaultAccountId } from "../../providers/plugins/helpers.js";
|
||||
import {
|
||||
listSignalAccountIds,
|
||||
resolveDefaultSignalAccountId,
|
||||
resolveSignalAccount,
|
||||
} from "../../signal/accounts.js";
|
||||
import { probeSignal, type SignalProbe } from "../../signal/probe.js";
|
||||
import {
|
||||
listSlackAccountIds,
|
||||
resolveDefaultSlackAccountId,
|
||||
resolveSlackAccount,
|
||||
} from "../../slack/accounts.js";
|
||||
import { probeSlack, type SlackProbe } from "../../slack/probe.js";
|
||||
import {
|
||||
listTelegramAccountIds,
|
||||
resolveDefaultTelegramAccountId,
|
||||
resolveTelegramAccount,
|
||||
} from "../../telegram/accounts.js";
|
||||
import {
|
||||
auditTelegramGroupMembership,
|
||||
collectTelegramUnmentionedGroupIds,
|
||||
} from "../../telegram/audit.js";
|
||||
import { probeTelegram, type TelegramProbe } from "../../telegram/probe.js";
|
||||
import {
|
||||
listEnabledWhatsAppAccounts,
|
||||
resolveDefaultWhatsAppAccountId,
|
||||
} from "../../web/accounts.js";
|
||||
import {
|
||||
getWebAuthAgeMs,
|
||||
readWebSelfId,
|
||||
webAuthExists,
|
||||
} from "../../web/session.js";
|
||||
getProviderPlugin,
|
||||
listProviderPlugins,
|
||||
normalizeProviderId,
|
||||
type ProviderId,
|
||||
} from "../../providers/plugins/index.js";
|
||||
import { buildProviderAccountSnapshot } from "../../providers/plugins/status.js";
|
||||
import type {
|
||||
ProviderAccountSnapshot,
|
||||
ProviderPlugin,
|
||||
} from "../../providers/plugins/types.js";
|
||||
import { DEFAULT_ACCOUNT_ID } from "../../routing/session-key.js";
|
||||
import { defaultRuntime } from "../../runtime.js";
|
||||
import {
|
||||
ErrorCodes,
|
||||
errorShape,
|
||||
formatValidationErrors,
|
||||
validateProvidersLogoutParams,
|
||||
validateProvidersStatusParams,
|
||||
} from "../protocol/index.js";
|
||||
import { formatForLog } from "../ws-log.js";
|
||||
import type { GatewayRequestHandlers } from "./types.js";
|
||||
import type { GatewayRequestContext, GatewayRequestHandlers } from "./types.js";
|
||||
|
||||
type ProviderLogoutPayload = {
|
||||
provider: ProviderId;
|
||||
accountId: string;
|
||||
cleared: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export async function logoutProviderAccount(params: {
|
||||
providerId: ProviderId;
|
||||
accountId?: string | null;
|
||||
cfg: ClawdbotConfig;
|
||||
context: GatewayRequestContext;
|
||||
plugin: ProviderPlugin;
|
||||
}): Promise<ProviderLogoutPayload> {
|
||||
const resolvedAccountId =
|
||||
params.accountId?.trim() ||
|
||||
params.plugin.config.defaultAccountId?.(params.cfg) ||
|
||||
params.plugin.config.listAccountIds(params.cfg)[0] ||
|
||||
DEFAULT_ACCOUNT_ID;
|
||||
const account = params.plugin.config.resolveAccount(
|
||||
params.cfg,
|
||||
resolvedAccountId,
|
||||
);
|
||||
await params.context.stopProvider(params.providerId, resolvedAccountId);
|
||||
const result = await params.plugin.gateway?.logoutAccount?.({
|
||||
cfg: params.cfg,
|
||||
accountId: resolvedAccountId,
|
||||
account,
|
||||
runtime: defaultRuntime,
|
||||
});
|
||||
if (!result) {
|
||||
throw new Error(`Provider ${params.providerId} does not support logout`);
|
||||
}
|
||||
const cleared = Boolean(result.cleared);
|
||||
const loggedOut =
|
||||
typeof result.loggedOut === "boolean" ? result.loggedOut : cleared;
|
||||
if (loggedOut) {
|
||||
params.context.markProviderLoggedOut(
|
||||
params.providerId,
|
||||
true,
|
||||
resolvedAccountId,
|
||||
);
|
||||
}
|
||||
return {
|
||||
provider: params.providerId,
|
||||
accountId: resolvedAccountId,
|
||||
...result,
|
||||
cleared,
|
||||
};
|
||||
}
|
||||
|
||||
export const providersHandlers: GatewayRequestHandlers = {
|
||||
"providers.status": async ({ params, respond, context }) => {
|
||||
@@ -81,457 +95,222 @@ export const providersHandlers: GatewayRequestHandlers = {
|
||||
typeof timeoutMsRaw === "number" ? Math.max(1000, timeoutMsRaw) : 10_000;
|
||||
const cfg = loadConfig();
|
||||
const runtime = context.getRuntimeSnapshot();
|
||||
const plugins = listProviderPlugins();
|
||||
const pluginMap = new Map<ProviderId, ProviderPlugin>(
|
||||
plugins.map((plugin) => [plugin.id, plugin]),
|
||||
);
|
||||
|
||||
const defaultTelegramAccountId = resolveDefaultTelegramAccountId(cfg);
|
||||
const defaultDiscordAccountId = resolveDefaultDiscordAccountId(cfg);
|
||||
const defaultSlackAccountId = resolveDefaultSlackAccountId(cfg);
|
||||
const defaultSignalAccountId = resolveDefaultSignalAccountId(cfg);
|
||||
const defaultIMessageAccountId = resolveDefaultIMessageAccountId(cfg);
|
||||
const resolveRuntimeSnapshot = (
|
||||
providerId: ProviderId,
|
||||
accountId: string,
|
||||
defaultAccountId: string,
|
||||
): ProviderAccountSnapshot | undefined => {
|
||||
const accounts = runtime.providerAccounts[providerId];
|
||||
const defaultRuntime = runtime.providers[providerId];
|
||||
const raw =
|
||||
accounts?.[accountId] ??
|
||||
(accountId === defaultAccountId ? defaultRuntime : undefined);
|
||||
if (!raw) return undefined;
|
||||
return raw;
|
||||
};
|
||||
|
||||
const telegramAccounts = await Promise.all(
|
||||
listTelegramAccountIds(cfg).map(async (accountId) => {
|
||||
const account = resolveTelegramAccount({ cfg, accountId });
|
||||
const rt =
|
||||
runtime.telegramAccounts?.[account.accountId] ??
|
||||
(account.accountId === defaultTelegramAccountId
|
||||
? runtime.telegram
|
||||
: undefined);
|
||||
const configured = Boolean(account.token);
|
||||
let telegramProbe: TelegramProbe | undefined;
|
||||
const isAccountEnabled = (plugin: ProviderPlugin, account: unknown) =>
|
||||
plugin.config.isEnabled
|
||||
? plugin.config.isEnabled(account, cfg)
|
||||
: !account ||
|
||||
typeof account !== "object" ||
|
||||
(account as { enabled?: boolean }).enabled !== false;
|
||||
|
||||
const buildProviderAccounts = async (providerId: ProviderId) => {
|
||||
const plugin = pluginMap.get(providerId);
|
||||
if (!plugin) {
|
||||
return {
|
||||
accounts: [] as ProviderAccountSnapshot[],
|
||||
defaultAccountId: DEFAULT_ACCOUNT_ID,
|
||||
defaultAccount: undefined as ProviderAccountSnapshot | undefined,
|
||||
resolvedAccounts: {} as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
const accountIds = plugin.config.listAccountIds(cfg);
|
||||
const defaultAccountId = resolveProviderDefaultAccountId({
|
||||
plugin,
|
||||
cfg,
|
||||
accountIds,
|
||||
});
|
||||
const accounts: ProviderAccountSnapshot[] = [];
|
||||
const resolvedAccounts: Record<string, unknown> = {};
|
||||
for (const accountId of accountIds) {
|
||||
const account = plugin.config.resolveAccount(cfg, accountId);
|
||||
const enabled = isAccountEnabled(plugin, account);
|
||||
resolvedAccounts[accountId] = account;
|
||||
let probeResult: unknown;
|
||||
let lastProbeAt: number | null = null;
|
||||
const groups =
|
||||
cfg.telegram?.accounts?.[account.accountId]?.groups ??
|
||||
cfg.telegram?.groups;
|
||||
const { groupIds, unresolvedGroups, hasWildcardUnmentionedGroups } =
|
||||
collectTelegramUnmentionedGroupIds(
|
||||
groups as Record<string, TelegramGroupConfig> | undefined,
|
||||
);
|
||||
let audit:
|
||||
| Awaited<ReturnType<typeof auditTelegramGroupMembership>>
|
||||
| undefined;
|
||||
if (probe && configured && account.enabled) {
|
||||
telegramProbe = await probeTelegram(
|
||||
account.token,
|
||||
timeoutMs,
|
||||
account.config.proxy,
|
||||
);
|
||||
lastProbeAt = Date.now();
|
||||
const botId =
|
||||
telegramProbe.ok && telegramProbe.bot?.id != null
|
||||
? telegramProbe.bot.id
|
||||
: null;
|
||||
if (botId && (groupIds.length > 0 || unresolvedGroups > 0)) {
|
||||
const auditRes = await auditTelegramGroupMembership({
|
||||
token: account.token,
|
||||
botId,
|
||||
groupIds,
|
||||
proxyUrl: account.config.proxy,
|
||||
if (probe && enabled && plugin.status?.probeAccount) {
|
||||
let configured = true;
|
||||
if (plugin.config.isConfigured) {
|
||||
configured = await plugin.config.isConfigured(account, cfg);
|
||||
}
|
||||
if (configured) {
|
||||
probeResult = await plugin.status.probeAccount({
|
||||
account,
|
||||
timeoutMs,
|
||||
cfg,
|
||||
});
|
||||
audit = {
|
||||
...auditRes,
|
||||
unresolvedGroups,
|
||||
hasWildcardUnmentionedGroups,
|
||||
};
|
||||
} else if (unresolvedGroups > 0 || hasWildcardUnmentionedGroups) {
|
||||
audit = {
|
||||
ok: unresolvedGroups === 0 && !hasWildcardUnmentionedGroups,
|
||||
checkedGroups: 0,
|
||||
unresolvedGroups,
|
||||
hasWildcardUnmentionedGroups,
|
||||
groups: [],
|
||||
elapsedMs: 0,
|
||||
};
|
||||
lastProbeAt = Date.now();
|
||||
}
|
||||
}
|
||||
const allowUnmentionedGroups =
|
||||
Boolean(
|
||||
groups?.["*"] &&
|
||||
(groups["*"] as { requireMention?: boolean }).requireMention ===
|
||||
false,
|
||||
) ||
|
||||
Object.entries(groups ?? {}).some(
|
||||
([key, value]) =>
|
||||
key !== "*" &&
|
||||
Boolean(value) &&
|
||||
typeof value === "object" &&
|
||||
(value as { requireMention?: boolean }).requireMention === false,
|
||||
);
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
name: account.name,
|
||||
enabled: account.enabled,
|
||||
configured,
|
||||
tokenSource: account.tokenSource,
|
||||
running: rt?.running ?? false,
|
||||
mode: rt?.mode ?? (account.config.webhookUrl ? "webhook" : "polling"),
|
||||
lastStartAt: rt?.lastStartAt ?? null,
|
||||
lastStopAt: rt?.lastStopAt ?? null,
|
||||
lastError: rt?.lastError ?? null,
|
||||
probe: telegramProbe,
|
||||
lastProbeAt,
|
||||
audit,
|
||||
allowUnmentionedGroups,
|
||||
lastInboundAt: getProviderActivity({
|
||||
provider: "telegram",
|
||||
accountId: account.accountId,
|
||||
}).inboundAt,
|
||||
lastOutboundAt: getProviderActivity({
|
||||
provider: "telegram",
|
||||
accountId: account.accountId,
|
||||
}).outboundAt,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const defaultTelegramAccount =
|
||||
telegramAccounts.find(
|
||||
(account) => account.accountId === defaultTelegramAccountId,
|
||||
) ?? telegramAccounts[0];
|
||||
|
||||
const discordAccounts = await Promise.all(
|
||||
listDiscordAccountIds(cfg).map(async (accountId) => {
|
||||
const account = resolveDiscordAccount({ cfg, accountId });
|
||||
const rt =
|
||||
runtime.discordAccounts?.[account.accountId] ??
|
||||
(account.accountId === defaultDiscordAccountId
|
||||
? runtime.discord
|
||||
: undefined);
|
||||
const configured = Boolean(account.token);
|
||||
let discordProbe: DiscordProbe | undefined;
|
||||
let lastProbeAt: number | null = null;
|
||||
const { channelIds: auditChannelIds, unresolvedChannels } =
|
||||
collectDiscordAuditChannelIds({ cfg, accountId: account.accountId });
|
||||
let audit:
|
||||
| Awaited<ReturnType<typeof auditDiscordChannelPermissions>>
|
||||
| undefined;
|
||||
if (probe && configured && account.enabled) {
|
||||
discordProbe = await probeDiscord(account.token, timeoutMs, {
|
||||
includeApplication: true,
|
||||
});
|
||||
lastProbeAt = Date.now();
|
||||
if (auditChannelIds.length > 0 || unresolvedChannels > 0) {
|
||||
const auditRes = await auditDiscordChannelPermissions({
|
||||
token: account.token,
|
||||
accountId: account.accountId,
|
||||
channelIds: auditChannelIds,
|
||||
let auditResult: unknown;
|
||||
if (probe && enabled && plugin.status?.auditAccount) {
|
||||
let configured = true;
|
||||
if (plugin.config.isConfigured) {
|
||||
configured = await plugin.config.isConfigured(account, cfg);
|
||||
}
|
||||
if (configured) {
|
||||
auditResult = await plugin.status.auditAccount({
|
||||
account,
|
||||
timeoutMs,
|
||||
cfg,
|
||||
probe: probeResult,
|
||||
});
|
||||
audit = { ...auditRes, unresolvedChannels };
|
||||
}
|
||||
}
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
name: account.name,
|
||||
enabled: account.enabled,
|
||||
configured,
|
||||
tokenSource: account.tokenSource,
|
||||
bot: rt?.bot ?? null,
|
||||
application: rt?.application ?? null,
|
||||
running: rt?.running ?? false,
|
||||
lastStartAt: rt?.lastStartAt ?? null,
|
||||
lastStopAt: rt?.lastStopAt ?? null,
|
||||
lastError: rt?.lastError ?? null,
|
||||
probe: discordProbe,
|
||||
lastProbeAt,
|
||||
audit,
|
||||
lastInboundAt: getProviderActivity({
|
||||
provider: "discord",
|
||||
accountId: account.accountId,
|
||||
}).inboundAt,
|
||||
lastOutboundAt: getProviderActivity({
|
||||
provider: "discord",
|
||||
accountId: account.accountId,
|
||||
}).outboundAt,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const defaultDiscordAccount =
|
||||
discordAccounts.find(
|
||||
(account) => account.accountId === defaultDiscordAccountId,
|
||||
) ?? discordAccounts[0];
|
||||
|
||||
const slackAccounts = await Promise.all(
|
||||
listSlackAccountIds(cfg).map(async (accountId) => {
|
||||
const account = resolveSlackAccount({ cfg, accountId });
|
||||
const rt =
|
||||
runtime.slackAccounts?.[account.accountId] ??
|
||||
(account.accountId === defaultSlackAccountId
|
||||
? runtime.slack
|
||||
: undefined);
|
||||
const configured = Boolean(account.botToken && account.appToken);
|
||||
let slackProbe: SlackProbe | undefined;
|
||||
let lastProbeAt: number | null = null;
|
||||
if (probe && configured && account.enabled && account.botToken) {
|
||||
slackProbe = await probeSlack(account.botToken, timeoutMs);
|
||||
lastProbeAt = Date.now();
|
||||
}
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
name: account.name,
|
||||
enabled: account.enabled,
|
||||
configured,
|
||||
botTokenSource: account.botTokenSource,
|
||||
appTokenSource: account.appTokenSource,
|
||||
running: rt?.running ?? false,
|
||||
lastStartAt: rt?.lastStartAt ?? null,
|
||||
lastStopAt: rt?.lastStopAt ?? null,
|
||||
lastError: rt?.lastError ?? null,
|
||||
probe: slackProbe,
|
||||
lastProbeAt,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const defaultSlackAccount =
|
||||
slackAccounts.find(
|
||||
(account) => account.accountId === defaultSlackAccountId,
|
||||
) ?? slackAccounts[0];
|
||||
|
||||
const signalAccounts = await Promise.all(
|
||||
listSignalAccountIds(cfg).map(async (accountId) => {
|
||||
const account = resolveSignalAccount({ cfg, accountId });
|
||||
const rt =
|
||||
runtime.signalAccounts?.[account.accountId] ??
|
||||
(account.accountId === defaultSignalAccountId
|
||||
? runtime.signal
|
||||
: undefined);
|
||||
const configured = account.configured;
|
||||
let signalProbe: SignalProbe | undefined;
|
||||
let lastProbeAt: number | null = null;
|
||||
if (probe && configured && account.enabled) {
|
||||
signalProbe = await probeSignal(account.baseUrl, timeoutMs);
|
||||
lastProbeAt = Date.now();
|
||||
}
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
name: account.name,
|
||||
enabled: account.enabled,
|
||||
configured,
|
||||
baseUrl: account.baseUrl,
|
||||
running: rt?.running ?? false,
|
||||
lastStartAt: rt?.lastStartAt ?? null,
|
||||
lastStopAt: rt?.lastStopAt ?? null,
|
||||
lastError: rt?.lastError ?? null,
|
||||
probe: signalProbe,
|
||||
lastProbeAt,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const defaultSignalAccount =
|
||||
signalAccounts.find(
|
||||
(account) => account.accountId === defaultSignalAccountId,
|
||||
) ?? signalAccounts[0];
|
||||
|
||||
const imessageBaseConfigured = Boolean(cfg.imessage);
|
||||
let imessageProbe: IMessageProbe | undefined;
|
||||
let imessageLastProbeAt: number | null = null;
|
||||
if (probe && imessageBaseConfigured) {
|
||||
imessageProbe = await probeIMessage(timeoutMs);
|
||||
imessageLastProbeAt = Date.now();
|
||||
}
|
||||
const imessageAccounts = listIMessageAccountIds(cfg).map((accountId) => {
|
||||
const account = resolveIMessageAccount({ cfg, accountId });
|
||||
const rt =
|
||||
runtime.imessageAccounts?.[account.accountId] ??
|
||||
(account.accountId === defaultIMessageAccountId
|
||||
? runtime.imessage
|
||||
: undefined);
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
name: account.name,
|
||||
enabled: account.enabled,
|
||||
configured: imessageBaseConfigured,
|
||||
running: rt?.running ?? false,
|
||||
lastStartAt: rt?.lastStartAt ?? null,
|
||||
lastStopAt: rt?.lastStopAt ?? null,
|
||||
lastError: rt?.lastError ?? null,
|
||||
cliPath: rt?.cliPath ?? account.config.cliPath ?? null,
|
||||
dbPath: rt?.dbPath ?? account.config.dbPath ?? null,
|
||||
probe: imessageProbe,
|
||||
lastProbeAt: imessageLastProbeAt,
|
||||
};
|
||||
});
|
||||
const defaultIMessageAccount =
|
||||
imessageAccounts.find(
|
||||
(account) => account.accountId === defaultIMessageAccountId,
|
||||
) ?? imessageAccounts[0];
|
||||
const defaultWhatsAppAccountId = resolveDefaultWhatsAppAccountId(cfg);
|
||||
const enabledWhatsAppAccounts = listEnabledWhatsAppAccounts(cfg);
|
||||
const defaultWhatsAppAccount =
|
||||
enabledWhatsAppAccounts.find(
|
||||
(account) => account.accountId === defaultWhatsAppAccountId,
|
||||
) ?? enabledWhatsAppAccounts[0];
|
||||
const linked = defaultWhatsAppAccount
|
||||
? await webAuthExists(defaultWhatsAppAccount.authDir)
|
||||
: false;
|
||||
const authAgeMs = defaultWhatsAppAccount
|
||||
? getWebAuthAgeMs(defaultWhatsAppAccount.authDir)
|
||||
: null;
|
||||
const self = defaultWhatsAppAccount
|
||||
? readWebSelfId(defaultWhatsAppAccount.authDir)
|
||||
: { e164: null, jid: null };
|
||||
|
||||
const defaultWhatsAppStatus = {
|
||||
running: false,
|
||||
connected: false,
|
||||
reconnectAttempts: 0,
|
||||
lastConnectedAt: null,
|
||||
lastDisconnect: null,
|
||||
lastMessageAt: null,
|
||||
lastEventAt: null,
|
||||
lastError: null,
|
||||
} as const;
|
||||
const whatsappAccounts = await Promise.all(
|
||||
enabledWhatsAppAccounts.map(async (account) => {
|
||||
const rt =
|
||||
runtime.whatsappAccounts?.[account.accountId] ??
|
||||
defaultWhatsAppStatus;
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
enabled: account.enabled,
|
||||
linked: await webAuthExists(account.authDir),
|
||||
authAgeMs: getWebAuthAgeMs(account.authDir),
|
||||
self: readWebSelfId(account.authDir),
|
||||
running: rt.running,
|
||||
connected: rt.connected,
|
||||
lastConnectedAt: rt.lastConnectedAt ?? null,
|
||||
lastDisconnect: rt.lastDisconnect ?? null,
|
||||
reconnectAttempts: rt.reconnectAttempts,
|
||||
lastMessageAt: rt.lastMessageAt ?? null,
|
||||
lastEventAt: rt.lastEventAt ?? null,
|
||||
lastError: rt.lastError ?? null,
|
||||
lastInboundAt: getProviderActivity({
|
||||
provider: "whatsapp",
|
||||
accountId: account.accountId,
|
||||
}).inboundAt,
|
||||
lastOutboundAt: getProviderActivity({
|
||||
provider: "whatsapp",
|
||||
accountId: account.accountId,
|
||||
}).outboundAt,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
respond(
|
||||
true,
|
||||
{
|
||||
ts: Date.now(),
|
||||
whatsapp: {
|
||||
configured: linked,
|
||||
linked,
|
||||
authAgeMs,
|
||||
self,
|
||||
running: runtime.whatsapp.running,
|
||||
connected: runtime.whatsapp.connected,
|
||||
lastConnectedAt: runtime.whatsapp.lastConnectedAt ?? null,
|
||||
lastDisconnect: runtime.whatsapp.lastDisconnect ?? null,
|
||||
reconnectAttempts: runtime.whatsapp.reconnectAttempts,
|
||||
lastMessageAt: runtime.whatsapp.lastMessageAt ?? null,
|
||||
lastEventAt: runtime.whatsapp.lastEventAt ?? null,
|
||||
lastError: runtime.whatsapp.lastError ?? null,
|
||||
},
|
||||
whatsappAccounts,
|
||||
whatsappDefaultAccountId: defaultWhatsAppAccountId,
|
||||
telegram: {
|
||||
configured: defaultTelegramAccount?.configured ?? false,
|
||||
tokenSource: defaultTelegramAccount?.tokenSource ?? "none",
|
||||
running: defaultTelegramAccount?.running ?? false,
|
||||
mode: defaultTelegramAccount?.mode ?? null,
|
||||
lastStartAt: defaultTelegramAccount?.lastStartAt ?? null,
|
||||
lastStopAt: defaultTelegramAccount?.lastStopAt ?? null,
|
||||
lastError: defaultTelegramAccount?.lastError ?? null,
|
||||
probe: defaultTelegramAccount?.probe,
|
||||
lastProbeAt: defaultTelegramAccount?.lastProbeAt ?? null,
|
||||
},
|
||||
telegramAccounts,
|
||||
telegramDefaultAccountId: defaultTelegramAccountId,
|
||||
discord: {
|
||||
configured: defaultDiscordAccount?.configured ?? false,
|
||||
tokenSource: defaultDiscordAccount?.tokenSource ?? "none",
|
||||
running: defaultDiscordAccount?.running ?? false,
|
||||
lastStartAt: defaultDiscordAccount?.lastStartAt ?? null,
|
||||
lastStopAt: defaultDiscordAccount?.lastStopAt ?? null,
|
||||
lastError: defaultDiscordAccount?.lastError ?? null,
|
||||
probe: defaultDiscordAccount?.probe,
|
||||
lastProbeAt: defaultDiscordAccount?.lastProbeAt ?? null,
|
||||
},
|
||||
discordAccounts,
|
||||
discordDefaultAccountId: defaultDiscordAccountId,
|
||||
slack: {
|
||||
configured: defaultSlackAccount?.configured ?? false,
|
||||
botTokenSource: defaultSlackAccount?.botTokenSource ?? "none",
|
||||
appTokenSource: defaultSlackAccount?.appTokenSource ?? "none",
|
||||
running: defaultSlackAccount?.running ?? false,
|
||||
lastStartAt: defaultSlackAccount?.lastStartAt ?? null,
|
||||
lastStopAt: defaultSlackAccount?.lastStopAt ?? null,
|
||||
lastError: defaultSlackAccount?.lastError ?? null,
|
||||
probe: defaultSlackAccount?.probe,
|
||||
lastProbeAt: defaultSlackAccount?.lastProbeAt ?? null,
|
||||
},
|
||||
slackAccounts,
|
||||
slackDefaultAccountId: defaultSlackAccountId,
|
||||
signal: {
|
||||
configured: defaultSignalAccount?.configured ?? false,
|
||||
baseUrl: defaultSignalAccount?.baseUrl ?? null,
|
||||
running: defaultSignalAccount?.running ?? false,
|
||||
lastStartAt: defaultSignalAccount?.lastStartAt ?? null,
|
||||
lastStopAt: defaultSignalAccount?.lastStopAt ?? null,
|
||||
lastError: defaultSignalAccount?.lastError ?? null,
|
||||
probe: defaultSignalAccount?.probe,
|
||||
lastProbeAt: defaultSignalAccount?.lastProbeAt ?? null,
|
||||
},
|
||||
signalAccounts,
|
||||
signalDefaultAccountId: defaultSignalAccountId,
|
||||
imessage: {
|
||||
configured: defaultIMessageAccount?.configured ?? false,
|
||||
running: defaultIMessageAccount?.running ?? false,
|
||||
lastStartAt: defaultIMessageAccount?.lastStartAt ?? null,
|
||||
lastStopAt: defaultIMessageAccount?.lastStopAt ?? null,
|
||||
lastError: defaultIMessageAccount?.lastError ?? null,
|
||||
cliPath: defaultIMessageAccount?.cliPath ?? null,
|
||||
dbPath: defaultIMessageAccount?.dbPath ?? null,
|
||||
probe: defaultIMessageAccount?.probe,
|
||||
lastProbeAt: defaultIMessageAccount?.lastProbeAt ?? null,
|
||||
},
|
||||
imessageAccounts,
|
||||
imessageDefaultAccountId: defaultIMessageAccountId,
|
||||
},
|
||||
undefined,
|
||||
);
|
||||
},
|
||||
"telegram.logout": async ({ respond, context }) => {
|
||||
try {
|
||||
await context.stopTelegramProvider();
|
||||
const snapshot = await readConfigFileSnapshot();
|
||||
if (!snapshot.valid) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
"config invalid; fix it before logging out",
|
||||
),
|
||||
const runtimeSnapshot = resolveRuntimeSnapshot(
|
||||
providerId,
|
||||
accountId,
|
||||
defaultAccountId,
|
||||
);
|
||||
return;
|
||||
const snapshot = await buildProviderAccountSnapshot({
|
||||
plugin,
|
||||
cfg,
|
||||
accountId,
|
||||
runtime: runtimeSnapshot,
|
||||
probe: probeResult,
|
||||
audit: auditResult,
|
||||
});
|
||||
if (lastProbeAt) snapshot.lastProbeAt = lastProbeAt;
|
||||
const activity = getProviderActivity({
|
||||
provider: providerId as never,
|
||||
accountId,
|
||||
});
|
||||
if (snapshot.lastInboundAt == null) {
|
||||
snapshot.lastInboundAt = activity.inboundAt;
|
||||
}
|
||||
if (snapshot.lastOutboundAt == null) {
|
||||
snapshot.lastOutboundAt = activity.outboundAt;
|
||||
}
|
||||
accounts.push(snapshot);
|
||||
}
|
||||
const cfg = snapshot.config ?? {};
|
||||
const envToken = process.env.TELEGRAM_BOT_TOKEN?.trim() ?? "";
|
||||
const hadToken = Boolean(cfg.telegram?.botToken);
|
||||
const nextTelegram = cfg.telegram ? { ...cfg.telegram } : undefined;
|
||||
if (nextTelegram) {
|
||||
delete nextTelegram.botToken;
|
||||
}
|
||||
const nextCfg = { ...cfg } as ClawdbotConfig;
|
||||
if (nextTelegram && Object.keys(nextTelegram).length > 0) {
|
||||
nextCfg.telegram = nextTelegram;
|
||||
} else {
|
||||
delete nextCfg.telegram;
|
||||
}
|
||||
await writeConfigFile(nextCfg);
|
||||
const defaultAccount =
|
||||
accounts.find((entry) => entry.accountId === defaultAccountId) ??
|
||||
accounts[0];
|
||||
return { accounts, defaultAccountId, defaultAccount, resolvedAccounts };
|
||||
};
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
ts: Date.now(),
|
||||
providerOrder: plugins.map((plugin) => plugin.id),
|
||||
providerLabels: Object.fromEntries(
|
||||
plugins.map((plugin) => [plugin.id, plugin.meta.label]),
|
||||
),
|
||||
providers: {} as Record<string, unknown>,
|
||||
providerAccounts: {} as Record<string, unknown>,
|
||||
providerDefaultAccountId: {} as Record<string, unknown>,
|
||||
};
|
||||
const providersMap = payload.providers as Record<string, unknown>;
|
||||
const accountsMap = payload.providerAccounts as Record<string, unknown>;
|
||||
const defaultAccountIdMap = payload.providerDefaultAccountId as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
for (const plugin of plugins) {
|
||||
const { accounts, defaultAccountId, defaultAccount, resolvedAccounts } =
|
||||
await buildProviderAccounts(plugin.id);
|
||||
const fallbackAccount =
|
||||
resolvedAccounts[defaultAccountId] ??
|
||||
plugin.config.resolveAccount(cfg, defaultAccountId);
|
||||
const summary = plugin.status?.buildProviderSummary
|
||||
? await plugin.status.buildProviderSummary({
|
||||
account: fallbackAccount,
|
||||
cfg,
|
||||
defaultAccountId,
|
||||
snapshot:
|
||||
defaultAccount ??
|
||||
({
|
||||
accountId: defaultAccountId,
|
||||
} as ProviderAccountSnapshot),
|
||||
})
|
||||
: {
|
||||
configured: defaultAccount?.configured ?? false,
|
||||
};
|
||||
providersMap[plugin.id] = summary;
|
||||
accountsMap[plugin.id] = accounts;
|
||||
defaultAccountIdMap[plugin.id] = defaultAccountId;
|
||||
}
|
||||
|
||||
respond(true, payload, undefined);
|
||||
},
|
||||
"providers.logout": async ({ params, respond, context }) => {
|
||||
if (!validateProvidersLogoutParams(params)) {
|
||||
respond(
|
||||
true,
|
||||
{ cleared: hadToken, envToken: Boolean(envToken) },
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
`invalid providers.logout params: ${formatValidationErrors(validateProvidersLogoutParams.errors)}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const rawProvider = (params as { provider?: unknown }).provider;
|
||||
const providerId =
|
||||
typeof rawProvider === "string" ? normalizeProviderId(rawProvider) : null;
|
||||
if (!providerId) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
"invalid providers.logout provider",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const plugin = getProviderPlugin(providerId);
|
||||
if (!plugin?.gateway?.logoutAccount) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
`provider ${providerId} does not support logout`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const accountIdRaw = (params as { accountId?: unknown }).accountId;
|
||||
const accountId =
|
||||
typeof accountIdRaw === "string" ? accountIdRaw.trim() : undefined;
|
||||
const snapshot = await readConfigFileSnapshot();
|
||||
if (!snapshot.valid) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
"config invalid; fix it before logging out",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const payload = await logoutProviderAccount({
|
||||
providerId,
|
||||
accountId,
|
||||
cfg: snapshot.config ?? {},
|
||||
context,
|
||||
plugin,
|
||||
});
|
||||
respond(true, payload, undefined);
|
||||
} catch (err) {
|
||||
respond(
|
||||
false,
|
||||
|
||||
+143
-216
@@ -1,16 +1,14 @@
|
||||
import { loadConfig } from "../../config/config.js";
|
||||
import { sendMessageDiscord, sendPollDiscord } from "../../discord/index.js";
|
||||
import { shouldLogVerbose } from "../../globals.js";
|
||||
import { sendMessageIMessage } from "../../imessage/index.js";
|
||||
import { createMSTeamsPollStoreFs } from "../../msteams/polls.js";
|
||||
import { sendMessageMSTeams, sendPollMSTeams } from "../../msteams/send.js";
|
||||
import { deliverOutboundPayloads } from "../../infra/outbound/deliver.js";
|
||||
import type { OutboundProvider } from "../../infra/outbound/targets.js";
|
||||
import { resolveOutboundTarget } from "../../infra/outbound/targets.js";
|
||||
import { normalizePollInput } from "../../polls.js";
|
||||
import { sendMessageSignal } from "../../signal/index.js";
|
||||
import { sendMessageSlack } from "../../slack/send.js";
|
||||
import { sendMessageTelegram } from "../../telegram/send.js";
|
||||
import { normalizeMessageProvider } from "../../utils/message-provider.js";
|
||||
import { resolveDefaultWhatsAppAccountId } from "../../web/accounts.js";
|
||||
import { sendMessageWhatsApp, sendPollWhatsApp } from "../../web/outbound.js";
|
||||
import {
|
||||
getProviderPlugin,
|
||||
normalizeProviderId,
|
||||
} from "../../providers/plugins/index.js";
|
||||
import type { ProviderId } from "../../providers/plugins/types.js";
|
||||
import { DEFAULT_CHAT_PROVIDER } from "../../providers/registry.js";
|
||||
import {
|
||||
ErrorCodes,
|
||||
errorShape,
|
||||
@@ -54,139 +52,86 @@ export const sendHandlers: GatewayRequestHandlers = {
|
||||
}
|
||||
const to = request.to.trim();
|
||||
const message = request.message.trim();
|
||||
const provider = normalizeMessageProvider(request.provider) ?? "whatsapp";
|
||||
const providerInput =
|
||||
typeof request.provider === "string" ? request.provider : undefined;
|
||||
const normalizedProvider = providerInput
|
||||
? normalizeProviderId(providerInput)
|
||||
: null;
|
||||
if (providerInput && !normalizedProvider) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
`unsupported provider: ${providerInput}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const provider = normalizedProvider ?? DEFAULT_CHAT_PROVIDER;
|
||||
const accountId =
|
||||
typeof request.accountId === "string" && request.accountId.trim().length
|
||||
? request.accountId.trim()
|
||||
: undefined;
|
||||
try {
|
||||
if (provider === "telegram") {
|
||||
const result = await sendMessageTelegram(to, message, {
|
||||
mediaUrl: request.mediaUrl,
|
||||
verbose: shouldLogVerbose(),
|
||||
accountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
chatId: result.chatId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else if (provider === "discord") {
|
||||
const result = await sendMessageDiscord(to, message, {
|
||||
mediaUrl: request.mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
channelId: result.channelId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else if (provider === "slack") {
|
||||
const result = await sendMessageSlack(to, message, {
|
||||
mediaUrl: request.mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
channelId: result.channelId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else if (provider === "signal") {
|
||||
const result = await sendMessageSignal(to, message, {
|
||||
mediaUrl: request.mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else if (provider === "imessage") {
|
||||
const result = await sendMessageIMessage(to, message, {
|
||||
mediaUrl: request.mediaUrl,
|
||||
accountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else if (provider === "msteams") {
|
||||
const cfg = loadConfig();
|
||||
const result = await sendMessageMSTeams({
|
||||
cfg,
|
||||
to,
|
||||
text: message,
|
||||
mediaUrl: request.mediaUrl,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
conversationId: result.conversationId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else {
|
||||
const cfg = loadConfig();
|
||||
const targetAccountId =
|
||||
accountId ?? resolveDefaultWhatsAppAccountId(cfg);
|
||||
const result = await sendMessageWhatsApp(to, message, {
|
||||
mediaUrl: request.mediaUrl,
|
||||
verbose: shouldLogVerbose(),
|
||||
gifPlayback: request.gifPlayback,
|
||||
accountId: targetAccountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
toJid: result.toJid ?? `${to}@s.whatsapp.net`,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
const outboundProvider = provider as Exclude<OutboundProvider, "none">;
|
||||
const plugin = getProviderPlugin(provider as ProviderId);
|
||||
if (!plugin) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
`unsupported provider: ${provider}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const cfg = loadConfig();
|
||||
const resolved = resolveOutboundTarget({
|
||||
provider: outboundProvider,
|
||||
to,
|
||||
cfg,
|
||||
accountId,
|
||||
mode: "explicit",
|
||||
});
|
||||
if (!resolved.ok) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(ErrorCodes.INVALID_REQUEST, String(resolved.error)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const results = await deliverOutboundPayloads({
|
||||
cfg,
|
||||
provider: outboundProvider,
|
||||
to: resolved.to,
|
||||
accountId,
|
||||
payloads: [{ text: message, mediaUrl: request.mediaUrl }],
|
||||
gifPlayback: request.gifPlayback,
|
||||
});
|
||||
const result = results.at(-1);
|
||||
if (!result) {
|
||||
throw new Error("No delivery result");
|
||||
}
|
||||
const payload: Record<string, unknown> = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
provider,
|
||||
};
|
||||
if ("chatId" in result) payload.chatId = result.chatId;
|
||||
if ("channelId" in result) payload.channelId = result.channelId;
|
||||
if ("toJid" in result) payload.toJid = result.toJid;
|
||||
if ("conversationId" in result) {
|
||||
payload.conversationId = result.conversationId;
|
||||
}
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} catch (err) {
|
||||
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
||||
context.dedupe.set(`send:${idem}`, {
|
||||
@@ -232,22 +177,23 @@ export const sendHandlers: GatewayRequestHandlers = {
|
||||
return;
|
||||
}
|
||||
const to = request.to.trim();
|
||||
const provider = normalizeMessageProvider(request.provider) ?? "whatsapp";
|
||||
if (
|
||||
provider !== "whatsapp" &&
|
||||
provider !== "discord" &&
|
||||
provider !== "msteams"
|
||||
) {
|
||||
const providerInput =
|
||||
typeof request.provider === "string" ? request.provider : undefined;
|
||||
const normalizedProvider = providerInput
|
||||
? normalizeProviderId(providerInput)
|
||||
: null;
|
||||
if (providerInput && !normalizedProvider) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
`unsupported poll provider: ${provider}`,
|
||||
`unsupported poll provider: ${providerInput}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const provider = normalizedProvider ?? DEFAULT_CHAT_PROVIDER;
|
||||
const poll = {
|
||||
question: request.question,
|
||||
options: request.options,
|
||||
@@ -259,78 +205,59 @@ export const sendHandlers: GatewayRequestHandlers = {
|
||||
? request.accountId.trim()
|
||||
: undefined;
|
||||
try {
|
||||
if (provider === "discord") {
|
||||
const result = await sendPollDiscord(to, poll, { accountId });
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
channelId: result.channelId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`poll:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else if (provider === "msteams") {
|
||||
const cfg = loadConfig();
|
||||
const normalized = normalizePollInput(poll, { maxOptions: 12 });
|
||||
const result = await sendPollMSTeams({
|
||||
cfg,
|
||||
to,
|
||||
question: normalized.question,
|
||||
options: normalized.options,
|
||||
maxSelections: normalized.maxSelections,
|
||||
});
|
||||
const pollStore = createMSTeamsPollStoreFs();
|
||||
await pollStore.createPoll({
|
||||
id: result.pollId,
|
||||
question: normalized.question,
|
||||
options: normalized.options,
|
||||
maxSelections: normalized.maxSelections,
|
||||
createdAt: new Date().toISOString(),
|
||||
conversationId: result.conversationId,
|
||||
messageId: result.messageId,
|
||||
votes: {},
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
conversationId: result.conversationId,
|
||||
pollId: result.pollId,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`poll:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} else {
|
||||
const cfg = loadConfig();
|
||||
const accountId =
|
||||
typeof request.accountId === "string" &&
|
||||
request.accountId.trim().length > 0
|
||||
? request.accountId.trim()
|
||||
: resolveDefaultWhatsAppAccountId(cfg);
|
||||
const result = await sendPollWhatsApp(to, poll, {
|
||||
verbose: shouldLogVerbose(),
|
||||
accountId,
|
||||
});
|
||||
const payload = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
toJid: result.toJid ?? `${to}@s.whatsapp.net`,
|
||||
provider,
|
||||
};
|
||||
context.dedupe.set(`poll:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
const plugin = getProviderPlugin(provider as ProviderId);
|
||||
const outbound = plugin?.outbound;
|
||||
if (!outbound?.sendPoll) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(
|
||||
ErrorCodes.INVALID_REQUEST,
|
||||
`unsupported poll provider: ${provider}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const cfg = loadConfig();
|
||||
const resolved = resolveOutboundTarget({
|
||||
provider: provider as Exclude<OutboundProvider, "none">,
|
||||
to,
|
||||
cfg,
|
||||
accountId,
|
||||
mode: "explicit",
|
||||
});
|
||||
if (!resolved.ok) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(ErrorCodes.INVALID_REQUEST, String(resolved.error)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const normalized = outbound.pollMaxOptions
|
||||
? normalizePollInput(poll, { maxOptions: outbound.pollMaxOptions })
|
||||
: normalizePollInput(poll);
|
||||
const result = await outbound.sendPoll({
|
||||
cfg,
|
||||
to: resolved.to,
|
||||
poll: normalized,
|
||||
accountId,
|
||||
});
|
||||
const payload: Record<string, unknown> = {
|
||||
runId: idem,
|
||||
messageId: result.messageId,
|
||||
provider,
|
||||
};
|
||||
if (result.toJid) payload.toJid = result.toJid;
|
||||
if (result.channelId) payload.channelId = result.channelId;
|
||||
if (result.conversationId) payload.conversationId = result.conversationId;
|
||||
if (result.pollId) payload.pollId = result.pollId;
|
||||
context.dedupe.set(`poll:${idem}`, {
|
||||
ts: Date.now(),
|
||||
ok: true,
|
||||
payload,
|
||||
});
|
||||
respond(true, payload, undefined, { provider });
|
||||
} catch (err) {
|
||||
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
||||
context.dedupe.set(`poll:${idem}`, {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user