Move provider to a plugin-architecture (#661)

* refactor: introduce provider plugin registry

* refactor: move provider CLI to plugins

* docs: add provider plugin implementation notes

* refactor: shift provider runtime logic into plugins

* refactor: add plugin defaults and summaries

* docs: update provider plugin notes

* feat(commands): add /commands slash list

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* Tests: align google shared expectations

* Auto-reply: tidy help message

* Auto-reply: fix status command lint

* refactor: move provider routing into plugins

* test: align agent routing expectations

* docs: update provider plugin notes

* refactor: route replies via provider plugins

* docs: note route-reply plugin hooks

* refactor: extend provider plugin contract

* refactor: derive provider status from plugins

* refactor: unify gateway provider control

* refactor: use plugin metadata in auto-reply

* fix: parenthesize cron target selection

* refactor: derive gateway methods from plugins

* refactor: generalize provider logout

* refactor: route provider logout through plugins

* refactor: move WhatsApp web login methods into plugin

* refactor: generalize provider log prefixes

* refactor: centralize default chat provider

* refactor: derive provider lists from registry

* refactor: move provider reload noops into plugins

* refactor: resolve web login provider via alias

* refactor: derive CLI provider options from plugins

* refactor: derive prompt provider list from plugins

* style: apply biome lint fixes

* fix: resolve provider routing edge cases

* docs: update provider plugin refactor notes

* fix(gateway): harden agent provider routing

* refactor: move provider routing into plugins

* refactor: move provider CLI to plugins

* refactor: derive provider lists from registry

* fix: restore slash command parsing

* refactor: align provider ids for schema

* refactor: unify outbound target resolution

* fix: keep outbound labels stable

* feat: add msteams to cron surfaces

* fix: clean up lint build issues

* refactor: localize chat provider alias normalization

* refactor: drive gateway provider lists from plugins

* docs: update provider plugin notes

* style: format message-provider

* fix: avoid provider registry init cycles

* style: sort message-provider imports

* fix: relax provider alias map typing

* refactor: move provider routing into plugins

* refactor: add plugin pairing/config adapters

* refactor: route pairing and provider removal via plugins

* refactor: align auto-reply provider typing

* test: stabilize telegram media mocks

* docs: update provider plugin refactor notes

* refactor: pluginize outbound targets

* refactor: pluginize provider selection

* refactor: generalize text chunk limits

* docs: update provider plugin notes

* refactor: generalize group session/config

* fix: normalize provider id for room detection

* fix: avoid provider init in system prompt

* style: formatting cleanup

* refactor: normalize agent delivery targets

* test: update outbound delivery labels

* chore: fix lint regressions

* refactor: extend provider plugin adapters

* refactor: move elevated/block streaming defaults to plugins

* refactor: defer outbound send deps to plugins

* docs: note plugin-driven streaming/elevated defaults

* refactor: centralize webchat provider constant

* refactor: add provider setup adapters

* refactor: delegate provider add config to plugins

* docs: document plugin-driven provider add

* refactor: add plugin state/binding metadata

* refactor: build agent provider status from plugins

* docs: note plugin-driven agent bindings

* refactor: centralize internal provider constant usage

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

* refactor: centralize default chat provider

* refactor: centralize WhatsApp target normalization

* refactor: move provider routing into plugins

* refactor: normalize agent delivery targets

* chore: fix lint regressions

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

* feat: expand provider plugin adapters

* refactor: route auto-reply via provider plugins

* fix: align WhatsApp target normalization

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

* refactor: centralize WhatsApp target normalization

* feat: add /config chat config updates

* docs: add /config get alias

* feat(commands): add /commands slash list

* refactor: centralize default chat provider

* style: apply biome lint fixes

* chore: fix lint regressions

* fix: clean up whatsapp allowlist typing

* style: format config command helpers

* refactor: pluginize tool threading context

* refactor: normalize session announce targets

* docs: note new plugin threading and announce hooks

* refactor: pluginize message actions

* docs: update provider plugin actions notes

* fix: align provider action adapters

* refactor: centralize webchat checks

* style: format message provider helpers

* refactor: move provider onboarding into adapters

* docs: note onboarding provider adapters

* feat: add msteams onboarding adapter

* style: organize onboarding imports

* fix: normalize msteams allowFrom types

* feat: add plugin text chunk limits

* refactor: use plugin chunk limit fallbacks

* feat: add provider mention stripping hooks

* style: organize provider plugin type imports

* refactor: generalize health snapshots

* refactor: update macOS health snapshot handling

* docs: refresh health snapshot notes

* style: format health snapshot updates

* refactor: drive security warnings via plugins

* docs: note provider security adapter

* style: format provider security adapters

* refactor: centralize provider account defaults

* refactor: type gateway client identity constants

* chore: regen gateway protocol swift

* fix: degrade health on failed provider probe

* refactor: centralize pairing approve hint

* docs: add plugin CLI command references

* refactor: route auth and tool sends through plugins

* docs: expand provider plugin hooks

* refactor: document provider docking touchpoints

* refactor: normalize internal provider defaults

* refactor: streamline outbound delivery wiring

* refactor: make provider onboarding plugin-owned

* refactor: support provider-owned agent tools

* refactor: move telegram draft chunking into telegram module

* refactor: infer provider tool sends via extractToolSend

* fix: repair plugin onboarding imports

* refactor: de-dup outbound target normalization

* style: tidy plugin and agent imports

* refactor: data-drive provider selection line

* fix: satisfy lint after provider plugin rebase

* test: deflake gateway-cli coverage

* style: format gateway-cli coverage test

* refactor(provider-plugins): simplify provider ids

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

* style(macos): swiftformat HealthStore

* refactor(sandbox): derive provider tool denylist

* fix(sandbox): avoid plugin init in defaults

* refactor(provider-plugins): centralize provider aliases

* style(test): satisfy biome

* refactor(protocol): v3 providers.status maps

* refactor(ui): adapt to protocol v3

* refactor(macos): adapt to protocol v3

* test: update providers.status v3 fixtures

* refactor(gateway): map provider runtime snapshot

* test(gateway): update reload runtime snapshot

* refactor(whatsapp): normalize heartbeat provider id

* docs(refactor): update provider plugin notes

* style: satisfy biome after rebase

* fix: describe sandboxed elevated in prompt

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

* refactor: derive CLI provider options from plugins

* fix(gateway): harden agent provider routing

* fix(gateway): harden agent provider routing

* refactor: align provider ids for schema

* fix(protocol): keep agent provider string

* fix(gateway): harden agent provider routing

* fix(protocol): keep agent provider string

* refactor: normalize agent delivery targets

* refactor: support provider-owned agent tools

* refactor(config): provider-keyed elevated allowFrom

* style: satisfy biome

* fix(gateway): appease provider narrowing

* style: satisfy biome

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

* fix(reply): avoid plugin registry init cycle

* refactor(providers): add lightweight provider dock

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

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

* refactor(providers): make media limit helper generic

* fix(providers): break plugin registry import cycles

* style: satisfy biome

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

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

* refactor(provider): drop web alias

* refactor(provider): lazy-load monitors

* style: satisfy lint/format

* style: format status-all providers table

* style: swiftformat gateway discovery model

* test: make reload plan plugin-driven

* fix: avoid token stringification in status-all

* refactor: make provider IDs explicit in status

* feat: warn on signal/imessage provider runtime errors

* test: cover gateway provider runtime warnings in status

* fix: add runtime kind to provider status issues

* test: cover health degradation on probe failure

* fix: keep routeReply lightweight

* style: organize routeReply imports

* refactor(web): extract auth-store helpers

* refactor(whatsapp): lazy login imports

* refactor(outbound): route replies via plugin outbound

* docs: update provider plugin notes

* style: format provider status issues

* fix: make sandbox scope warning wrap-safe

* refactor: load outbound adapters from provider plugins

* docs: update provider plugin outbound notes

* style(macos): fix swiftformat lint

* docs: changelog for provider plugins

* fix(macos): satisfy swiftformat

* fix(macos): open settings via menu action

* style: format after rebase

* fix(macos): open Settings via menu action

---------

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

View File

@@ -20,7 +20,7 @@
- CLI: `clawdbot status` now table-based + shows OS/update/gateway/daemon/agents/sessions; `status --all` adds a full read-only debug report (tables, log tails, Tailscale summary, and scan progress via OSC-9 + spinner).
- CLI Backends: add Codex CLI fallback with resume support (text output) and JSONL parsing for new runs, plus a live CLI resume probe.
- CLI: add `clawdbot update` (safe-ish git checkout update) + `--update` shorthand. (#673) — thanks @fm1randa.
- Gateway: add OpenAI-compatible `/v1/chat/completions` HTTP endpoint (auth, SSE streaming, per-agent routing). (#680) — thanks @steipete.
- Gateway: add OpenAI-compatible `/v1/chat/completions` HTTP endpoint (auth, SSE streaming, per-agent routing). (#680).
### Changes
- Onboarding/Models: add first-class Z.AI (GLM) auth choice (`zai-api-key`) + `--zai-api-key` flag.
@@ -30,7 +30,8 @@
- Onboarding/Models: add catalog-backed default model picker to onboarding + configure. (#611) — thanks @jonasjancarik.
- Agents/OpenCode Zen: update fallback models + defaults, keep legacy alias mappings. (#669) — thanks @magimetal.
- CLI: add `clawdbot reset` and `clawdbot uninstall` flows (interactive + non-interactive) plus docker cleanup smoke test.
- Providers: unify group history context wrappers across providers with per-provider/per-account `historyLimit` overrides (fallback to `messages.groupChat.historyLimit`). Set `0` to disable. (#672) — thanks @steipete.
- Providers: move provider wiring to a plugin architecture. (#661).
- Providers: unify group history context wrappers across providers with per-provider/per-account `historyLimit` overrides (fallback to `messages.groupChat.historyLimit`). Set `0` to disable. (#672).
- Gateway/Heartbeat: optionally deliver heartbeat `Reasoning:` output (`agents.defaults.heartbeat.includeReasoning`). (#690)
- Docker: allow optional home volume + extra bind mounts in `docker-setup.sh`. (#679) — thanks @gabriel-trigo.

View File

@@ -61,8 +61,10 @@ final class CLIInstallPrompter {
private func openSettings(tab: SettingsTab) {
SettingsTabRouter.request(tab)
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
NSApp.sendAction(#selector(NSApplication.showSettingsWindow), to: nil, from: nil)
SettingsWindowOpener.shared.open()
DispatchQueue.main.async {
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
}
}
private static func appVersion() -> String? {

View File

@@ -34,7 +34,7 @@ enum CLIInstaller {
self.installedLocation() != nil
}
static func install(statusHandler: @escaping @Sendable (String) async -> Void) async {
static func install(statusHandler: @escaping @MainActor @Sendable (String) async -> Void) async {
let expected = GatewayEnvironment.expectedGatewayVersion()?.description ?? "latest"
let prefix = Self.installPrefix()
await statusHandler("Installing clawdbot CLI…")

View File

@@ -1,8 +1,16 @@
import SwiftUI
extension ConnectionsSettings {
private func providerStatus<T: Decodable>(
_ id: String,
as type: T.Type) -> T?
{
self.store.snapshot?.decodeProvider(id, as: type)
}
var whatsAppTint: Color {
guard let status = self.store.snapshot?.whatsapp else { return .secondary }
guard let status = self.providerStatus("whatsapp", as: ProvidersStatusSnapshot.WhatsAppStatus.self)
else { return .secondary }
if !status.configured { return .secondary }
if !status.linked { return .red }
if status.lastError != nil { return .orange }
@@ -12,7 +20,8 @@ extension ConnectionsSettings {
}
var telegramTint: Color {
guard let status = self.store.snapshot?.telegram else { return .secondary }
guard let status = self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)
else { return .secondary }
if !status.configured { return .secondary }
if status.lastError != nil { return .orange }
if status.probe?.ok == false { return .orange }
@@ -21,7 +30,8 @@ extension ConnectionsSettings {
}
var discordTint: Color {
guard let status = self.store.snapshot?.discord else { return .secondary }
guard let status = self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)
else { return .secondary }
if !status.configured { return .secondary }
if status.lastError != nil { return .orange }
if status.probe?.ok == false { return .orange }
@@ -30,7 +40,8 @@ extension ConnectionsSettings {
}
var signalTint: Color {
guard let status = self.store.snapshot?.signal else { return .secondary }
guard let status = self.providerStatus("signal", as: ProvidersStatusSnapshot.SignalStatus.self)
else { return .secondary }
if !status.configured { return .secondary }
if status.lastError != nil { return .orange }
if status.probe?.ok == false { return .orange }
@@ -39,7 +50,8 @@ extension ConnectionsSettings {
}
var imessageTint: Color {
guard let status = self.store.snapshot?.imessage else { return .secondary }
guard let status = self.providerStatus("imessage", as: ProvidersStatusSnapshot.IMessageStatus.self)
else { return .secondary }
if !status.configured { return .secondary }
if status.lastError != nil { return .orange }
if status.probe?.ok == false { return .orange }
@@ -48,7 +60,8 @@ extension ConnectionsSettings {
}
var whatsAppSummary: String {
guard let status = self.store.snapshot?.whatsapp else { return "Checking…" }
guard let status = self.providerStatus("whatsapp", as: ProvidersStatusSnapshot.WhatsAppStatus.self)
else { return "Checking…" }
if !status.linked { return "Not linked" }
if status.connected { return "Connected" }
if status.running { return "Running" }
@@ -56,35 +69,40 @@ extension ConnectionsSettings {
}
var telegramSummary: String {
guard let status = self.store.snapshot?.telegram else { return "Checking…" }
guard let status = self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)
else { return "Checking…" }
if !status.configured { return "Not configured" }
if status.running { return "Running" }
return "Configured"
}
var discordSummary: String {
guard let status = self.store.snapshot?.discord else { return "Checking…" }
guard let status = self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)
else { return "Checking…" }
if !status.configured { return "Not configured" }
if status.running { return "Running" }
return "Configured"
}
var signalSummary: String {
guard let status = self.store.snapshot?.signal else { return "Checking…" }
guard let status = self.providerStatus("signal", as: ProvidersStatusSnapshot.SignalStatus.self)
else { return "Checking…" }
if !status.configured { return "Not configured" }
if status.running { return "Running" }
return "Configured"
}
var imessageSummary: String {
guard let status = self.store.snapshot?.imessage else { return "Checking…" }
guard let status = self.providerStatus("imessage", as: ProvidersStatusSnapshot.IMessageStatus.self)
else { return "Checking…" }
if !status.configured { return "Not configured" }
if status.running { return "Running" }
return "Configured"
}
var whatsAppDetails: String? {
guard let status = self.store.snapshot?.whatsapp else { return nil }
guard let status = self.providerStatus("whatsapp", as: ProvidersStatusSnapshot.WhatsAppStatus.self)
else { return nil }
var lines: [String] = []
if let e164 = status.`self`?.e164 ?? status.`self`?.jid {
lines.append("Linked as \(e164)")
@@ -114,7 +132,8 @@ extension ConnectionsSettings {
}
var telegramDetails: String? {
guard let status = self.store.snapshot?.telegram else { return nil }
guard let status = self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)
else { return nil }
var lines: [String] = []
if let source = status.tokenSource {
lines.append("Token source: \(source)")
@@ -145,7 +164,8 @@ extension ConnectionsSettings {
}
var discordDetails: String? {
guard let status = self.store.snapshot?.discord else { return nil }
guard let status = self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)
else { return nil }
var lines: [String] = []
if let source = status.tokenSource {
lines.append("Token source: \(source)")
@@ -173,7 +193,8 @@ extension ConnectionsSettings {
}
var signalDetails: String? {
guard let status = self.store.snapshot?.signal else { return nil }
guard let status = self.providerStatus("signal", as: ProvidersStatusSnapshot.SignalStatus.self)
else { return nil }
var lines: [String] = []
lines.append("Base URL: \(status.baseUrl)")
if let probe = status.probe {
@@ -199,7 +220,8 @@ extension ConnectionsSettings {
}
var imessageDetails: String? {
guard let status = self.store.snapshot?.imessage else { return nil }
guard let status = self.providerStatus("imessage", as: ProvidersStatusSnapshot.IMessageStatus.self)
else { return nil }
var lines: [String] = []
if let cliPath = status.cliPath, !cliPath.isEmpty {
lines.append("CLI: \(cliPath)")
@@ -221,11 +243,11 @@ extension ConnectionsSettings {
}
var isTelegramTokenLocked: Bool {
self.store.snapshot?.telegram.tokenSource == "env"
self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)?.tokenSource == "env"
}
var isDiscordTokenLocked: Bool {
self.store.snapshot?.discord?.tokenSource == "env"
self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)?.tokenSource == "env"
}
var orderedProviders: [ConnectionProvider] {
@@ -258,19 +280,24 @@ extension ConnectionsSettings {
func providerEnabled(_ provider: ConnectionProvider) -> Bool {
switch provider {
case .whatsapp:
guard let status = self.store.snapshot?.whatsapp else { return false }
guard let status = self.providerStatus("whatsapp", as: ProvidersStatusSnapshot.WhatsAppStatus.self)
else { return false }
return status.configured || status.linked || status.running
case .telegram:
guard let status = self.store.snapshot?.telegram else { return false }
guard let status = self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)
else { return false }
return status.configured || status.running
case .discord:
guard let status = self.store.snapshot?.discord else { return false }
guard let status = self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)
else { return false }
return status.configured || status.running
case .signal:
guard let status = self.store.snapshot?.signal else { return false }
guard let status = self.providerStatus("signal", as: ProvidersStatusSnapshot.SignalStatus.self)
else { return false }
return status.configured || status.running
case .imessage:
guard let status = self.store.snapshot?.imessage else { return false }
guard let status = self.providerStatus("imessage", as: ProvidersStatusSnapshot.IMessageStatus.self)
else { return false }
return status.configured || status.running
}
}
@@ -344,35 +371,48 @@ extension ConnectionsSettings {
func providerLastCheck(_ provider: ConnectionProvider) -> Date? {
switch provider {
case .whatsapp:
guard let status = self.store.snapshot?.whatsapp else { return nil }
guard let status = self.providerStatus("whatsapp", as: ProvidersStatusSnapshot.WhatsAppStatus.self)
else { return nil }
return self.date(fromMs: status.lastEventAt ?? status.lastMessageAt ?? status.lastConnectedAt)
case .telegram:
return self.date(fromMs: self.store.snapshot?.telegram.lastProbeAt)
return self
.date(fromMs: self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)?
.lastProbeAt)
case .discord:
return self.date(fromMs: self.store.snapshot?.discord?.lastProbeAt)
return self
.date(fromMs: self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)?
.lastProbeAt)
case .signal:
return self.date(fromMs: self.store.snapshot?.signal?.lastProbeAt)
return self
.date(fromMs: self.providerStatus("signal", as: ProvidersStatusSnapshot.SignalStatus.self)?.lastProbeAt)
case .imessage:
return self.date(fromMs: self.store.snapshot?.imessage?.lastProbeAt)
return self
.date(fromMs: self.providerStatus("imessage", as: ProvidersStatusSnapshot.IMessageStatus.self)?
.lastProbeAt)
}
}
func providerHasError(_ provider: ConnectionProvider) -> Bool {
switch provider {
case .whatsapp:
guard let status = self.store.snapshot?.whatsapp else { return false }
guard let status = self.providerStatus("whatsapp", as: ProvidersStatusSnapshot.WhatsAppStatus.self)
else { return false }
return status.lastError?.isEmpty == false || status.lastDisconnect?.loggedOut == true
case .telegram:
guard let status = self.store.snapshot?.telegram else { return false }
guard let status = self.providerStatus("telegram", as: ProvidersStatusSnapshot.TelegramStatus.self)
else { return false }
return status.lastError?.isEmpty == false || status.probe?.ok == false
case .discord:
guard let status = self.store.snapshot?.discord else { return false }
guard let status = self.providerStatus("discord", as: ProvidersStatusSnapshot.DiscordStatus.self)
else { return false }
return status.lastError?.isEmpty == false || status.probe?.ok == false
case .signal:
guard let status = self.store.snapshot?.signal else { return false }
guard let status = self.providerStatus("signal", as: ProvidersStatusSnapshot.SignalStatus.self)
else { return false }
return status.lastError?.isEmpty == false || status.probe?.ok == false
case .imessage:
guard let status = self.store.snapshot?.imessage else { return false }
guard let status = self.providerStatus("imessage", as: ProvidersStatusSnapshot.IMessageStatus.self)
else { return false }
return status.lastError?.isEmpty == false || status.probe?.ok == false
}
}

View File

@@ -100,9 +100,12 @@ extension ConnectionsStore {
self.whatsappBusy = true
defer { self.whatsappBusy = false }
do {
let result: WhatsAppLogoutResult = try await GatewayConnection.shared.requestDecoded(
method: .webLogout,
params: nil,
let params: [String: AnyCodable] = [
"provider": AnyCodable("whatsapp"),
]
let result: ProviderLogoutResult = try await GatewayConnection.shared.requestDecoded(
method: .providersLogout,
params: params,
timeoutMs: 15000)
self.whatsappLoginMessage = result.cleared
? "Logged out and cleared credentials."
@@ -119,9 +122,12 @@ extension ConnectionsStore {
self.telegramBusy = true
defer { self.telegramBusy = false }
do {
let result: TelegramLogoutResult = try await GatewayConnection.shared.requestDecoded(
method: .telegramLogout,
params: nil,
let params: [String: AnyCodable] = [
"provider": AnyCodable("telegram"),
]
let result: ProviderLogoutResult = try await GatewayConnection.shared.requestDecoded(
method: .providersLogout,
params: params,
timeoutMs: 15000)
if result.envToken == true {
self.configStatus = "Telegram token still set via env; config cleared."
@@ -148,11 +154,9 @@ private struct WhatsAppLoginWaitResult: Codable {
let message: String
}
private struct WhatsAppLogoutResult: Codable {
let cleared: Bool
}
private struct TelegramLogoutResult: Codable {
private struct ProviderLogoutResult: Codable {
let provider: String?
let accountId: String?
let cleared: Bool
let envToken: Bool?
}

View File

@@ -121,12 +121,54 @@ struct ProvidersStatusSnapshot: Codable {
let lastProbeAt: Double?
}
struct ProviderAccountSnapshot: Codable {
let accountId: String
let name: String?
let enabled: Bool?
let configured: Bool?
let linked: Bool?
let running: Bool?
let connected: Bool?
let reconnectAttempts: Int?
let lastConnectedAt: Double?
let lastError: String?
let lastStartAt: Double?
let lastStopAt: Double?
let lastInboundAt: Double?
let lastOutboundAt: Double?
let lastProbeAt: Double?
let mode: String?
let dmPolicy: String?
let allowFrom: [String]?
let tokenSource: String?
let botTokenSource: String?
let appTokenSource: String?
let baseUrl: String?
let allowUnmentionedGroups: Bool?
let cliPath: String?
let dbPath: String?
let port: Int?
let probe: AnyCodable?
let audit: AnyCodable?
let application: AnyCodable?
}
let ts: Double
let whatsapp: WhatsAppStatus
let telegram: TelegramStatus
let discord: DiscordStatus?
let signal: SignalStatus?
let imessage: IMessageStatus?
let providerOrder: [String]
let providerLabels: [String: String]
let providers: [String: AnyCodable]
let providerAccounts: [String: [ProviderAccountSnapshot]]
let providerDefaultAccountId: [String: String]
func decodeProvider<T: Decodable>(_ id: String, as type: T.Type) -> T? {
guard let value = self.providers[id] else { return nil }
do {
let data = try JSONEncoder().encode(value)
return try JSONDecoder().decode(type, from: data)
} catch {
return nil
}
}
}
struct ConfigSnapshot: Codable {

View File

@@ -192,15 +192,17 @@ actor GatewayChannelActor {
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
let platform = "macos \(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"
let primaryLocale = Locale.preferredLanguages.first ?? Locale.current.identifier
let clientName = InstanceIdentity.displayName
let clientDisplayName = InstanceIdentity.displayName
let clientId = "clawdbot-macos"
let reqId = UUID().uuidString
var client: [String: ProtoAnyCodable] = [
"name": ProtoAnyCodable(clientName),
"id": ProtoAnyCodable(clientId),
"displayName": ProtoAnyCodable(clientDisplayName),
"version": ProtoAnyCodable(
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"),
"platform": ProtoAnyCodable(platform),
"mode": ProtoAnyCodable("app"),
"mode": ProtoAnyCodable("ui"),
"instanceId": ProtoAnyCodable(InstanceIdentity.instanceId),
]
client["deviceFamily"] = ProtoAnyCodable("Mac")

View File

@@ -13,6 +13,7 @@ enum GatewayAgentProvider: String, Codable, CaseIterable, Sendable {
case slack
case signal
case imessage
case msteams
case webchat
init(raw: String?) {
@@ -61,8 +62,7 @@ actor GatewayConnection {
case talkMode = "talk.mode"
case webLoginStart = "web.login.start"
case webLoginWait = "web.login.wait"
case webLogout = "web.logout"
case telegramLogout = "telegram.logout"
case providersLogout = "providers.logout"
case modelsList = "models.list"
case chatHistory = "chat.history"
case chatSend = "chat.send"

View File

@@ -226,7 +226,10 @@ actor GatewayEndpointStore {
}
let config = try await self.ensureRemoteConfig(detail: Self.remoteConnectingDetail)
guard let portInt = config.0.port, let port = UInt16(exactly: portInt) else {
throw NSError(domain: "GatewayEndpoint", code: 1, userInfo: [NSLocalizedDescriptionKey: "Missing tunnel port"])
throw NSError(
domain: "GatewayEndpoint",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "Missing tunnel port"])
}
return port
}
@@ -290,7 +293,10 @@ actor GatewayEndpointStore {
let forwarded = try await ensure.task.value
let stillRemote = await self.deps.mode() == .remote
guard stillRemote else {
throw NSError(domain: "RemoteTunnel", code: 1, userInfo: [NSLocalizedDescriptionKey: "Remote mode is not enabled"])
throw NSError(
domain: "RemoteTunnel",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "Remote mode is not enabled"])
}
if self.remoteEnsure?.token == ensure.token {

View File

@@ -319,5 +319,4 @@ enum GatewayEnvironment {
else { return nil }
return Semver.parse(version)
}
}

View File

@@ -6,6 +6,17 @@ enum GatewayLaunchAgentManager {
private static let legacyGatewayLaunchdLabel = "com.steipete.clawdbot.gateway"
private static let disableLaunchAgentMarker = ".clawdbot/disable-launchagent"
private enum GatewayProgramArgumentsError: LocalizedError {
case cliNotFound
var errorDescription: String? {
switch self {
case .cliNotFound:
"clawdbot CLI not found in PATH; install the CLI."
}
}
}
private static var plistURL: URL {
FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/LaunchAgents/\(gatewayLaunchdLabel).plist")
@@ -16,21 +27,27 @@ enum GatewayLaunchAgentManager {
.appendingPathComponent("Library/LaunchAgents/\(legacyGatewayLaunchdLabel).plist")
}
private static func gatewayProgramArguments(port: Int, bind: String) -> Result<[String], String> {
private static func gatewayProgramArguments(
port: Int,
bind: String) -> Result<[String], GatewayProgramArgumentsError>
{
#if DEBUG
let projectRoot = CommandResolver.projectRoot()
if let localBin = CommandResolver.projectClawdbotExecutable(projectRoot: projectRoot) {
return .success([localBin, "gateway-daemon", "--port", "\(port)", "--bind", bind])
}
if let entry = CommandResolver.gatewayEntrypoint(in: projectRoot),
case let .success(runtime) = CommandResolver.runtimeResolution()
{
let cmd = CommandResolver.makeRuntimeCommand(
runtime: runtime,
entrypoint: entry,
subcommand: "gateway-daemon",
extraArgs: ["--port", "\(port)", "--bind", bind])
return .success(cmd)
if let entry = CommandResolver.gatewayEntrypoint(in: projectRoot) {
switch CommandResolver.runtimeResolution() {
case let .success(runtime):
let cmd = CommandResolver.makeRuntimeCommand(
runtime: runtime,
entrypoint: entry,
subcommand: "gateway-daemon",
extraArgs: ["--port", "\(port)", "--bind", bind])
return .success(cmd)
case .failure:
break
}
}
#endif
let searchPaths = CommandResolver.preferredPaths()
@@ -38,19 +55,22 @@ enum GatewayLaunchAgentManager {
return .success([gatewayBin, "gateway-daemon", "--port", "\(port)", "--bind", bind])
}
let projectRoot = CommandResolver.projectRoot()
if let entry = CommandResolver.gatewayEntrypoint(in: projectRoot),
case let .success(runtime) = CommandResolver.runtimeResolution(searchPaths: searchPaths)
{
let cmd = CommandResolver.makeRuntimeCommand(
runtime: runtime,
entrypoint: entry,
subcommand: "gateway-daemon",
extraArgs: ["--port", "\(port)", "--bind", bind])
return .success(cmd)
let fallbackProjectRoot = CommandResolver.projectRoot()
if let entry = CommandResolver.gatewayEntrypoint(in: fallbackProjectRoot) {
switch CommandResolver.runtimeResolution(searchPaths: searchPaths) {
case let .success(runtime):
let cmd = CommandResolver.makeRuntimeCommand(
runtime: runtime,
entrypoint: entry,
subcommand: "gateway-daemon",
extraArgs: ["--port", "\(port)", "--bind", bind])
return .success(cmd)
case .failure:
break
}
}
return .failure("clawdbot CLI not found in PATH; install the CLI.")
return .failure(.cliNotFound)
}
static func isLoaded() async -> Bool {
@@ -78,25 +98,26 @@ enum GatewayLaunchAgentManager {
token: desiredToken,
password: desiredPassword)
let programArgumentsResult = self.gatewayProgramArguments(port: port, bind: desiredBind)
guard case let .success(programArguments) = programArgumentsResult else {
if case let .failure(message) = programArgumentsResult {
self.logger.error("launchd enable failed: \(message)")
return message
}
return "Failed to resolve gateway command."
let programArguments: [String]
switch programArgumentsResult {
case let .success(args):
programArguments = args
case let .failure(error):
let message = error.errorDescription ?? "Failed to resolve gateway CLI"
self.logger.error("launchd enable failed: \(message)")
return message
}
// If launchd already loaded the job (common on login), avoid `bootout` unless we must
// change the config. `bootout` can kill a just-started gateway and cause attach loops.
let loaded = await self.isLoaded()
if loaded,
let existing = self.readPlistConfig(),
existing.matches(desiredConfig)
{
self.logger.info("launchd job already loaded with desired config; skipping bootout")
await self.ensureEnabled()
_ = await Launchctl.run(["kickstart", "gui/\(getuid())/\(gatewayLaunchdLabel)"])
return nil
if loaded {
if let existing = self.readPlistConfig(), existing.matches(desiredConfig) {
self.logger.info("launchd job already loaded with desired config; skipping bootout")
await self.ensureEnabled()
_ = await Launchctl.run(["kickstart", "gui/\(getuid())/\(gatewayLaunchdLabel)"])
return nil
}
}
self.logger.info("launchd enable requested port=\(port) bind=\(desiredBind)")
@@ -129,7 +150,6 @@ enum GatewayLaunchAgentManager {
_ = await Launchctl.run(["kickstart", "-k", "gui/\(getuid())/\(gatewayLaunchdLabel)"])
}
private static func writePlist(bundlePath: String, port: Int) {
private static func writePlist(programArguments: [String]) {
let preferredPath = CommandResolver.preferredPaths().joined(separator: ":")
let token = self.preferredGatewayToken()

View File

@@ -221,9 +221,21 @@ final class GatewayProcessManager {
private func describe(details instance: String?, port: Int, snap: HealthSnapshot?) -> String {
let instanceText = instance ?? "pid unknown"
if let snap {
let linked = snap.web.linked ? "linked" : "not linked"
let authAge = snap.web.authAgeMs.flatMap(msToAge) ?? "unknown age"
return "port \(port), \(linked), auth \(authAge), \(instanceText)"
let linkId = snap.providerOrder?.first(where: {
if let summary = snap.providers[$0] { return summary.linked != nil }
return false
}) ?? snap.providers.keys.first(where: {
if let summary = snap.providers[$0] { return summary.linked != nil }
return false
})
let linked = linkId.flatMap { snap.providers[$0]?.linked } ?? false
let authAge = linkId.flatMap { snap.providers[$0]?.authAgeMs }.flatMap(msToAge) ?? "unknown age"
let label =
linkId.flatMap { snap.providerLabels?[$0] } ??
linkId?.capitalized ??
"provider"
let linkText = linked ? "linked" : "not linked"
return "port \(port), \(label) \(linkText), auth \(authAge), \(instanceText)"
}
return "port \(port), health probe succeeded, \(instanceText)"
}

View File

@@ -461,10 +461,8 @@ struct GeneralSettings: View {
self.isInstallingCLI = true
defer { isInstallingCLI = false }
await CLIInstaller.install { status in
await MainActor.run {
self.cliStatus = status
self.refreshCLIStatus()
}
self.cliStatus = status
self.refreshCLIStatus()
}
}
@@ -503,7 +501,19 @@ struct GeneralSettings: View {
}
if let snap = snapshot {
Text("Linked auth age: \(healthAgeString(snap.web.authAgeMs))")
let linkId = snap.providerOrder?.first(where: {
if let summary = snap.providers[$0] { return summary.linked != nil }
return false
}) ?? snap.providers.keys.first(where: {
if let summary = snap.providers[$0] { return summary.linked != nil }
return false
})
let linkLabel =
linkId.flatMap { snap.providerLabels?[$0] } ??
linkId?.capitalized ??
"Link provider"
let linkAge = linkId.flatMap { snap.providers[$0]?.authAgeMs }
Text("\(linkLabel) auth age: \(healthAgeString(linkAge))")
.font(.caption)
.foregroundStyle(.secondary)
Text("Session store: \(snap.sessions.path) (\(snap.sessions.count) entries)")

View File

@@ -4,35 +4,29 @@ import Observation
import SwiftUI
struct HealthSnapshot: Codable, Sendable {
struct Telegram: Codable, Sendable {
struct ProviderSummary: Codable, Sendable {
struct Probe: Codable, Sendable {
struct Bot: Codable, Sendable {
let id: Int?
let username: String?
}
let ok: Bool
struct Webhook: Codable, Sendable {
let url: String?
}
let ok: Bool?
let status: Int?
let error: String?
let elapsedMs: Double?
let bot: Bot?
let webhook: Webhook?
}
let configured: Bool
let probe: Probe?
}
struct Web: Codable, Sendable {
struct Connect: Codable, Sendable {
let ok: Bool
let status: Int?
let error: String?
let elapsedMs: Double?
}
let linked: Bool
let configured: Bool?
let linked: Bool?
let authAgeMs: Double?
let connect: Connect?
let probe: Probe?
let lastProbeAt: Double?
}
struct SessionInfo: Codable, Sendable {
@@ -50,8 +44,9 @@ struct HealthSnapshot: Codable, Sendable {
let ok: Bool?
let ts: Double
let durationMs: Double
let web: Web
let telegram: Telegram?
let providers: [String: ProviderSummary]
let providerOrder: [String]?
let providerLabels: [String: String]?
let heartbeatSeconds: Int?
let sessions: Sessions
}
@@ -94,6 +89,13 @@ final class HealthStore {
}
}
// Test-only escape hatch: the HealthStore is a process-wide singleton but
// state derivation is pure from `snapshot` + `lastError`.
func __setSnapshotForTest(_ snapshot: HealthSnapshot?, lastError: String? = nil) {
self.snapshot = snapshot
self.lastError = lastError
}
func start() {
guard self.loopTask == nil else { return }
self.loopTask = Task { [weak self] in
@@ -142,10 +144,49 @@ final class HealthStore {
}
}
private static func isTelegramHealthy(_ snap: HealthSnapshot) -> Bool {
guard let tg = snap.telegram, tg.configured else { return false }
private static func isProviderHealthy(_ summary: HealthSnapshot.ProviderSummary) -> Bool {
guard summary.configured == true else { return false }
// If probe is missing, treat it as "configured but unknown health" (not a hard fail).
return tg.probe?.ok ?? true
return summary.probe?.ok ?? true
}
private static func describeProbeFailure(_ probe: HealthSnapshot.ProviderSummary.Probe) -> String {
let elapsed = probe.elapsedMs.map { "\(Int($0))ms" }
if let error = probe.error, error.lowercased().contains("timeout") || probe.status == nil {
if let elapsed { return "Health check timed out (\(elapsed))" }
return "Health check timed out"
}
let code = probe.status.map { "status \($0)" } ?? "status unknown"
let reason = probe.error?.isEmpty == false ? probe.error! : "health probe failed"
if let elapsed { return "\(reason) (\(code), \(elapsed))" }
return "\(reason) (\(code))"
}
private func resolveLinkProvider(
_ snap: HealthSnapshot) -> (id: String, summary: HealthSnapshot.ProviderSummary)?
{
let order = snap.providerOrder ?? Array(snap.providers.keys)
for id in order {
if let summary = snap.providers[id], summary.linked != nil {
return (id: id, summary: summary)
}
}
return nil
}
private func resolveFallbackProvider(
_ snap: HealthSnapshot,
excluding id: String?) -> (id: String, summary: HealthSnapshot.ProviderSummary)?
{
let order = snap.providerOrder ?? Array(snap.providers.keys)
for providerId in order {
if providerId == id { continue }
guard let summary = snap.providers[providerId] else { continue }
if Self.isProviderHealthy(summary) {
return (id: providerId, summary: summary)
}
}
return nil
}
var state: HealthState {
@@ -153,13 +194,15 @@ final class HealthStore {
return .degraded(error)
}
guard let snap = self.snapshot else { return .unknown }
if !snap.web.linked {
// WhatsApp Web linking is optional if Telegram is healthy; don't paint the whole app red.
return Self.isTelegramHealthy(snap) ? .degraded("Not linked") : .linkingNeeded
guard let link = self.resolveLinkProvider(snap) else { return .unknown }
if link.summary.linked != true {
// Linking is optional if any other provider is healthy; don't paint the whole app red.
let fallback = self.resolveFallbackProvider(snap, excluding: link.id)
return fallback != nil ? .degraded("Not linked") : .linkingNeeded
}
if let connect = snap.web.connect, !connect.ok {
let reason = connect.error ?? "connect failed"
return .degraded(reason)
// A provider can be "linked" but still unhealthy (failed probe / cannot connect).
if let probe = link.summary.probe, probe.ok == false {
return .degraded(Self.describeProbeFailure(probe))
}
return .ok
}
@@ -168,19 +211,22 @@ final class HealthStore {
if self.isRefreshing { return "Health check running…" }
if let error = self.lastError { return "Health check failed: \(error)" }
guard let snap = self.snapshot else { return "Health check pending" }
if !snap.web.linked {
if let tg = snap.telegram, tg.configured {
let tgLabel = (tg.probe?.ok ?? true) ? "Telegram ok" : "Telegram degraded"
return "\(tgLabel) · Not linked — run clawdbot login"
guard let link = self.resolveLinkProvider(snap) else { return "Health check pending" }
if link.summary.linked != true {
if let fallback = self.resolveFallbackProvider(snap, excluding: link.id) {
let fallbackLabel = snap.providerLabels?[fallback.id] ?? fallback.id.capitalized
let fallbackState = (fallback.summary.probe?.ok ?? true) ? "ok" : "degraded"
return "\(fallbackLabel) \(fallbackState) · Not linked — run clawdbot login"
}
return "Not linked — run clawdbot login"
}
let auth = snap.web.authAgeMs.map { msToAge($0) } ?? "unknown"
if let connect = snap.web.connect, !connect.ok {
let code = connect.status.map(String.init) ?? "?"
return "Link stale? status \(code)"
let auth = link.summary.authAgeMs.map { msToAge($0) } ?? "unknown"
if let probe = link.summary.probe, probe.ok == false {
let status = probe.status.map(String.init) ?? "?"
let suffix = probe.status == nil ? "probe degraded" : "probe degraded · status \(status)"
return "linked · auth \(auth) · \(suffix)"
}
return "linked · auth \(auth) · socket ok"
return "linked · auth \(auth)"
}
/// Short, human-friendly detail for the last failure, used in the UI.
@@ -201,17 +247,11 @@ final class HealthStore {
}
func describeFailure(from snap: HealthSnapshot, fallback: String?) -> String {
if !snap.web.linked {
if let link = self.resolveLinkProvider(snap), link.summary.linked != true {
return "Not linked — run clawdbot login"
}
if let connect = snap.web.connect, !connect.ok {
let elapsed = connect.elapsedMs.map { "\(Int($0))ms" } ?? "unknown duration"
if let err = connect.error, err.lowercased().contains("timeout") || connect.status == nil {
return "Health check timed out (\(elapsed))"
}
let code = connect.status.map { "status \($0)" } ?? "status unknown"
let reason = connect.error ?? "connect failed"
return "\(reason) (\(code), \(elapsed))"
if let link = self.resolveLinkProvider(snap), let probe = link.summary.probe, probe.ok == false {
return Self.describeProbeFailure(probe)
}
if let fallback, !fallback.isEmpty {
return fallback

View File

@@ -242,6 +242,18 @@ final class InstancesStore {
do {
let data = try await ControlChannel.shared.health(timeout: 8)
guard let snap = decodeHealthSnapshot(from: data) else { return }
let linkId = snap.providerOrder?.first(where: {
if let summary = snap.providers[$0] { return summary.linked != nil }
return false
}) ?? snap.providers.keys.first(where: {
if let summary = snap.providers[$0] { return summary.linked != nil }
return false
})
let linked = linkId.flatMap { snap.providers[$0]?.linked } ?? false
let linkLabel =
linkId.flatMap { snap.providerLabels?[$0] } ??
linkId?.capitalized ??
"provider"
let entry = InstanceInfo(
id: "health-\(snap.ts)",
host: "gateway (health)",
@@ -253,7 +265,7 @@ final class InstancesStore {
lastInputSeconds: nil,
mode: "health",
reason: "health probe",
text: "Health ok · linked=\(snap.web.linked)",
text: "Health ok · \(linkLabel) linked=\(linked)",
ts: snap.ts)
if !self.instances.contains(where: { $0.id == entry.id }) {
self.instances.insert(entry, at: 0)

View File

@@ -153,6 +153,9 @@ struct MenuContent: View {
self.micRefreshTask = nil
self.micObserver.stop()
}
.task { @MainActor in
SettingsWindowOpener.shared.register(openSettings: self.openSettings)
}
}
private var connectionLabel: String {
@@ -301,7 +304,9 @@ struct MenuContent: View {
SettingsTabRouter.request(tab)
NSApp.activate(ignoringOtherApps: true)
self.openSettings()
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
DispatchQueue.main.async {
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
}
}
@MainActor

View File

@@ -395,13 +395,13 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate {
private func controlChannelStatusText(for state: ControlChannel.ConnectionState) -> String {
switch state {
case .connected:
return "Loading sessions…"
"Loading sessions…"
case .connecting:
return "Connecting…"
"Connecting…"
case let .degraded(message):
return message.nonEmpty ?? "Gateway disconnected"
message.nonEmpty ?? "Gateway disconnected"
case .disconnected:
return "Gateway disconnected"
"Gateway disconnected"
}
}

View File

@@ -1,6 +1,7 @@
import AppKit
import ClawdbotDiscovery
import ClawdbotIPC
import Foundation
import SwiftUI
extension OnboardingView {
@@ -41,7 +42,9 @@ extension OnboardingView {
func openSettings(tab: SettingsTab) {
SettingsTabRouter.request(tab)
self.openSettings()
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
DispatchQueue.main.async {
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
}
}
func handleBack() {

View File

@@ -95,7 +95,7 @@ extension OnboardingView {
self.installingCLI = true
defer { installingCLI = false }
await CLIInstaller.install { message in
await MainActor.run { self.cliStatus = message }
self.cliStatus = message
}
self.refreshCLIStatus()
}

View File

@@ -345,7 +345,10 @@ final class LocationPermissionRequester: NSObject, CLLocationManagerDelegate {
}
// Legacy callback (still used on some macOS versions / configurations).
nonisolated func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
nonisolated func locationManager(
_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus)
{
Task { @MainActor in
self.finish(status: status)
}

View File

@@ -0,0 +1,36 @@
import AppKit
import SwiftUI
@objc
private protocol SettingsWindowMenuActions {
@objc(showSettingsWindow:)
optional func showSettingsWindow(_ sender: Any?)
@objc(showPreferencesWindow:)
optional func showPreferencesWindow(_ sender: Any?)
}
@MainActor
final class SettingsWindowOpener {
static let shared = SettingsWindowOpener()
private var openSettingsAction: OpenSettingsAction?
func register(openSettings: OpenSettingsAction) {
self.openSettingsAction = openSettings
}
func open() {
NSApp.activate(ignoringOtherApps: true)
if let openSettingsAction {
openSettingsAction()
return
}
// Fallback path: mimic the built-in Settings menu item action.
let didOpen = NSApp.sendAction(#selector(SettingsWindowMenuActions.showSettingsWindow(_:)), to: nil, from: nil)
if !didOpen {
_ = NSApp.sendAction(#selector(SettingsWindowMenuActions.showPreferencesWindow(_:)), to: nil, from: nil)
}
}
}

View File

@@ -602,7 +602,7 @@ public final class GatewayDiscoveryModel {
of: #"\s*-?\s*bridge$"#,
with: "",
options: .regularExpression)
return normalizeHostToken(strippedBridge)
return self.normalizeHostToken(strippedBridge)
}
}

View File

@@ -1,7 +1,7 @@
// Generated by scripts/protocol-gen-swift.ts do not edit by hand
import Foundation
public let GATEWAY_PROTOCOL_VERSION = 2
public let GATEWAY_PROTOCOL_VERSION = 3
public enum ErrorCode: String, Codable, Sendable {
case notLinked = "NOT_LINKED"
@@ -1119,6 +1119,56 @@ public struct ProvidersStatusParams: Codable, Sendable {
}
}
public struct ProvidersStatusResult: Codable, Sendable {
public let ts: Int
public let providerorder: [String]
public let providerlabels: [String: AnyCodable]
public let providers: [String: AnyCodable]
public let provideraccounts: [String: AnyCodable]
public let providerdefaultaccountid: [String: AnyCodable]
public init(
ts: Int,
providerorder: [String],
providerlabels: [String: AnyCodable],
providers: [String: AnyCodable],
provideraccounts: [String: AnyCodable],
providerdefaultaccountid: [String: AnyCodable]
) {
self.ts = ts
self.providerorder = providerorder
self.providerlabels = providerlabels
self.providers = providers
self.provideraccounts = provideraccounts
self.providerdefaultaccountid = providerdefaultaccountid
}
private enum CodingKeys: String, CodingKey {
case ts
case providerorder = "providerOrder"
case providerlabels = "providerLabels"
case providers
case provideraccounts = "providerAccounts"
case providerdefaultaccountid = "providerDefaultAccountId"
}
}
public struct ProvidersLogoutParams: Codable, Sendable {
public let provider: String
public let accountid: String?
public init(
provider: String,
accountid: String?
) {
self.provider = provider
self.accountid = accountid
}
private enum CodingKeys: String, CodingKey {
case provider
case accountid = "accountId"
}
}
public struct WebLoginStartParams: Codable, Sendable {
public let force: Bool?
public let timeoutms: Int?

View File

@@ -9,68 +9,76 @@ struct ConnectionsSettingsSmokeTests {
let store = ConnectionsStore(isPreview: true)
store.snapshot = ProvidersStatusSnapshot(
ts: 1_700_000_000_000,
whatsapp: ProvidersStatusSnapshot.WhatsAppStatus(
configured: true,
linked: true,
authAgeMs: 86_400_000,
self: ProvidersStatusSnapshot.WhatsAppSelf(
e164: "+15551234567",
jid: nil),
running: true,
connected: false,
lastConnectedAt: 1_700_000_000_000,
lastDisconnect: ProvidersStatusSnapshot.WhatsAppDisconnect(
at: 1_700_000_050_000,
status: 401,
error: "logged out",
loggedOut: true),
reconnectAttempts: 2,
lastMessageAt: 1_700_000_060_000,
lastEventAt: 1_700_000_060_000,
lastError: "needs login"),
telegram: ProvidersStatusSnapshot.TelegramStatus(
configured: true,
tokenSource: "env",
running: true,
mode: "polling",
lastStartAt: 1_700_000_000_000,
lastStopAt: nil,
lastError: nil,
probe: ProvidersStatusSnapshot.TelegramProbe(
ok: true,
status: 200,
error: nil,
elapsedMs: 120,
bot: ProvidersStatusSnapshot.TelegramBot(id: 123, username: "clawdbotbot"),
webhook: ProvidersStatusSnapshot.TelegramWebhook(
url: "https://example.com/hook",
hasCustomCert: false)),
lastProbeAt: 1_700_000_050_000),
discord: nil,
signal: ProvidersStatusSnapshot.SignalStatus(
configured: true,
baseUrl: "http://127.0.0.1:8080",
running: true,
lastStartAt: 1_700_000_000_000,
lastStopAt: nil,
lastError: nil,
probe: ProvidersStatusSnapshot.SignalProbe(
ok: true,
status: 200,
error: nil,
elapsedMs: 140,
version: "0.12.4"),
lastProbeAt: 1_700_000_050_000),
imessage: ProvidersStatusSnapshot.IMessageStatus(
configured: false,
running: false,
lastStartAt: nil,
lastStopAt: nil,
lastError: "not configured",
cliPath: nil,
dbPath: nil,
probe: ProvidersStatusSnapshot.IMessageProbe(ok: false, error: "imsg not found (imsg)"),
lastProbeAt: 1_700_000_050_000))
providerOrder: ["whatsapp", "telegram", "signal", "imessage"],
providerLabels: [
"whatsapp": "WhatsApp",
"telegram": "Telegram",
"signal": "Signal",
"imessage": "iMessage",
],
providers: [
"whatsapp": AnyCodable([
"configured": true,
"linked": true,
"authAgeMs": 86_400_000,
"self": ["e164": "+15551234567"],
"running": true,
"connected": false,
"lastConnectedAt": 1_700_000_000_000,
"lastDisconnect": [
"at": 1_700_000_050_000,
"status": 401,
"error": "logged out",
"loggedOut": true,
],
"reconnectAttempts": 2,
"lastMessageAt": 1_700_000_060_000,
"lastEventAt": 1_700_000_060_000,
"lastError": "needs login",
]),
"telegram": AnyCodable([
"configured": true,
"tokenSource": "env",
"running": true,
"mode": "polling",
"lastStartAt": 1_700_000_000_000,
"probe": [
"ok": true,
"status": 200,
"elapsedMs": 120,
"bot": ["id": 123, "username": "clawdbotbot"],
"webhook": ["url": "https://example.com/hook", "hasCustomCert": false],
],
"lastProbeAt": 1_700_000_050_000,
]),
"signal": AnyCodable([
"configured": true,
"baseUrl": "http://127.0.0.1:8080",
"running": true,
"lastStartAt": 1_700_000_000_000,
"probe": [
"ok": true,
"status": 200,
"elapsedMs": 140,
"version": "0.12.4",
],
"lastProbeAt": 1_700_000_050_000,
]),
"imessage": AnyCodable([
"configured": false,
"running": false,
"lastError": "not configured",
"probe": ["ok": false, "error": "imsg not found (imsg)"],
"lastProbeAt": 1_700_000_050_000,
]),
],
providerAccounts: [:],
providerDefaultAccountId: [
"whatsapp": "default",
"telegram": "default",
"signal": "default",
"imessage": "default",
])
store.whatsappLoginMessage = "Scan QR"
store.whatsappLoginQrDataUrl =
@@ -91,60 +99,62 @@ struct ConnectionsSettingsSmokeTests {
let store = ConnectionsStore(isPreview: true)
store.snapshot = ProvidersStatusSnapshot(
ts: 1_700_000_000_000,
whatsapp: ProvidersStatusSnapshot.WhatsAppStatus(
configured: false,
linked: false,
authAgeMs: nil,
self: nil,
running: false,
connected: false,
lastConnectedAt: nil,
lastDisconnect: nil,
reconnectAttempts: 0,
lastMessageAt: nil,
lastEventAt: nil,
lastError: nil),
telegram: ProvidersStatusSnapshot.TelegramStatus(
configured: false,
tokenSource: nil,
running: false,
mode: nil,
lastStartAt: nil,
lastStopAt: nil,
lastError: "bot missing",
probe: ProvidersStatusSnapshot.TelegramProbe(
ok: false,
status: 403,
error: "unauthorized",
elapsedMs: 120,
bot: nil,
webhook: nil),
lastProbeAt: 1_700_000_100_000),
discord: nil,
signal: ProvidersStatusSnapshot.SignalStatus(
configured: false,
baseUrl: "http://127.0.0.1:8080",
running: false,
lastStartAt: nil,
lastStopAt: nil,
lastError: "not configured",
probe: ProvidersStatusSnapshot.SignalProbe(
ok: false,
status: 404,
error: "unreachable",
elapsedMs: 200,
version: nil),
lastProbeAt: 1_700_000_200_000),
imessage: ProvidersStatusSnapshot.IMessageStatus(
configured: false,
running: false,
lastStartAt: nil,
lastStopAt: nil,
lastError: "not configured",
cliPath: "imsg",
dbPath: nil,
probe: ProvidersStatusSnapshot.IMessageProbe(ok: false, error: "imsg not found (imsg)"),
lastProbeAt: 1_700_000_200_000))
providerOrder: ["whatsapp", "telegram", "signal", "imessage"],
providerLabels: [
"whatsapp": "WhatsApp",
"telegram": "Telegram",
"signal": "Signal",
"imessage": "iMessage",
],
providers: [
"whatsapp": AnyCodable([
"configured": false,
"linked": false,
"running": false,
"connected": false,
"reconnectAttempts": 0,
]),
"telegram": AnyCodable([
"configured": false,
"running": false,
"lastError": "bot missing",
"probe": [
"ok": false,
"status": 403,
"error": "unauthorized",
"elapsedMs": 120,
],
"lastProbeAt": 1_700_000_100_000,
]),
"signal": AnyCodable([
"configured": false,
"baseUrl": "http://127.0.0.1:8080",
"running": false,
"lastError": "not configured",
"probe": [
"ok": false,
"status": 404,
"error": "unreachable",
"elapsedMs": 200,
],
"lastProbeAt": 1_700_000_200_000,
]),
"imessage": AnyCodable([
"configured": false,
"running": false,
"lastError": "not configured",
"cliPath": "imsg",
"probe": ["ok": false, "error": "imsg not found (imsg)"],
"lastProbeAt": 1_700_000_200_000,
]),
],
providerAccounts: [:],
providerDefaultAccountId: [
"whatsapp": "default",
"telegram": "default",
"signal": "default",
"imessage": "default",
])
let view = ConnectionsSettings(store: store)
_ = view.body

View File

@@ -5,14 +5,14 @@ import Testing
@Suite struct HealthDecodeTests {
private let sampleJSON: String = // minimal but complete payload
"""
{"ts":1733622000,"durationMs":420,"web":{"linked":true,"authAgeMs":120000,"connect":{"ok":true,"status":200,"error":null,"elapsedMs":800}},"heartbeatSeconds":60,"sessions":{"path":"/tmp/sessions.json","count":1,"recent":[{"key":"abc","updatedAt":1733621900,"age":120000}]}}
{"ts":1733622000,"durationMs":420,"providers":{"whatsapp":{"linked":true,"authAgeMs":120000},"telegram":{"configured":true,"probe":{"ok":true,"elapsedMs":800}}},"providerOrder":["whatsapp","telegram"],"heartbeatSeconds":60,"sessions":{"path":"/tmp/sessions.json","count":1,"recent":[{"key":"abc","updatedAt":1733621900,"age":120000}]}}
"""
@Test func decodesCleanJSON() async throws {
let data = Data(sampleJSON.utf8)
let snap = decodeHealthSnapshot(from: data)
#expect(snap?.web.linked == true)
#expect(snap?.providers["whatsapp"]?.linked == true)
#expect(snap?.sessions.count == 1)
}
@@ -20,7 +20,7 @@ import Testing
let noisy = "debug: something logged\n" + self.sampleJSON + "\ntrailer"
let snap = decodeHealthSnapshot(from: Data(noisy.utf8))
#expect(snap?.web.connect?.status == 200)
#expect(snap?.providers["telegram"]?.probe?.elapsedMs == 800)
}
@Test func failsWithoutBraces() async throws {

View File

@@ -0,0 +1,46 @@
import Foundation
import Testing
@testable import Clawdbot
@Suite struct HealthStoreStateTests {
@Test @MainActor func linkedProviderProbeFailureDegradesState() async throws {
let snap = HealthSnapshot(
ok: true,
ts: 0,
durationMs: 1,
providers: [
"whatsapp": .init(
configured: true,
linked: true,
authAgeMs: 1,
probe: .init(
ok: false,
status: 503,
error: "gateway connect failed",
elapsedMs: 12,
bot: nil,
webhook: nil
),
lastProbeAt: 0
),
],
providerOrder: ["whatsapp"],
providerLabels: ["whatsapp": "WhatsApp"],
heartbeatSeconds: 60,
sessions: .init(path: "/tmp/sessions.json", count: 0, recent: [])
)
let store = HealthStore.shared
store.__setSnapshotForTest(snap, lastError: nil)
switch store.state {
case .degraded(let message):
#expect(!message.isEmpty)
default:
Issue.record("Expected degraded state when probe fails for linked provider")
}
#expect(store.summaryLine.contains("probe degraded"))
}
}

View File

@@ -255,7 +255,7 @@ Subcommands:
- `providers add`: wizard-style setup when no flags are passed; flags switch to non-interactive mode.
- `providers remove`: disable by default; pass `--delete` to remove config entries without prompts.
- `providers login`: interactive provider login (WhatsApp Web only).
- `providers logout`: log out of a provider session (WhatsApp Web only).
- `providers logout`: log out of a provider session (if supported).
Common options:
- `--provider <name>`: `whatsapp|telegram|discord|slack|signal|imessage|msteams`
@@ -268,7 +268,7 @@ Common options:
- `--verbose`
`providers logout` options:
- `--provider <provider>` (default `whatsapp`; supports `whatsapp`/`web`)
- `--provider <provider>` (default `whatsapp`)
- `--account <id>`
`providers list` options:

View File

@@ -1,5 +1,5 @@
---
summary: "Routing rules per provider (WhatsApp, Telegram, Discord, web) and shared context"
summary: "Routing rules per provider (WhatsApp, Telegram, Discord, Slack) and shared context"
read_when:
- Changing provider routing or inbox behavior
---

View File

@@ -91,10 +91,11 @@ Connect (first message):
"minProtocol": 2,
"maxProtocol": 2,
"client": {
"name": "macos",
"id": "clawdbot-macos",
"displayName": "macos",
"version": "1.0.0",
"platform": "macos 15.1",
"mode": "app",
"mode": "ui",
"instanceId": "A1B2"
}
}
@@ -150,10 +151,11 @@ ws.on("open", () => {
id: "c1",
method: "connect",
params: {
minProtocol: 2,
maxProtocol: 2,
minProtocol: 3,
maxProtocol: 3,
client: {
name: "example",
id: "cli",
displayName: "example",
version: "dev",
platform: "node",
mode: "cli"

View File

@@ -1,16 +1,16 @@
---
summary: "Health check steps for Baileys/WhatsApp connectivity"
summary: "Health check steps for provider connectivity"
read_when:
- Diagnosing web provider health
---
# Health Checks (CLI)
Short guide to verify the WhatsApp Web / Baileys stack without guessing.
Short guide to verify provider connectivity without guessing.
## Quick checks
- `clawdbot status` — local summary: gateway reachability/mode, update hint, creds/auth age, sessions + recent activity.
- `clawdbot status` — local summary: gateway reachability/mode, update hint, link provider auth age, sessions + recent activity.
- `clawdbot status --all` — full local diagnosis (read-only, color, safe to paste for debugging).
- `clawdbot status --deep` — adds gateway health probes to status output (Telegram + Discord APIs; requires reachable gateway).
- `clawdbot status --deep` — also probes the running Gateway (per-provider probes when supported).
- `clawdbot health --json` — asks the running Gateway for a full health snapshot (WS-only; no direct Baileys socket).
- Send `/status` as a standalone message in WhatsApp/WebChat to get a status reply without invoking the agent.
- Logs: tail `/tmp/clawdbot/clawdbot-*.log` and filter for `web-heartbeat`, `web-reconnect`, `web-auto-reply`, `web-inbound`.
@@ -26,4 +26,4 @@ Short guide to verify the WhatsApp Web / Baileys stack without guessing.
- No inbound messages → confirm linked phone is online and the sender is allowed (`whatsapp.allowFrom`); for group chats, ensure allowlist + mention rules match (`whatsapp.groups`, `agents.list[].groupChat.mentionPatterns`).
## Dedicated "health" command
`clawdbot health --json` asks the running Gateway for its health snapshot (no direct Baileys socket from the CLI). It reports linked creds, auth age, Baileys connect result/status code, session-store summary, and a probe duration. It exits non-zero if the Gateway is unreachable or the probe fails/timeouts. Use `--timeout <ms>` to override the 10s default.
`clawdbot health --json` asks the running Gateway for its health snapshot (no direct provider sockets from the CLI). It reports linked creds/auth age when available, per-provider probe summaries, session-store summary, and a probe duration. It exits non-zero if the Gateway is unreachable or the probe fails/timeouts. Use `--timeout <ms>` to override the 10s default.

View File

@@ -103,7 +103,7 @@ CLAWDBOT_CONFIG_PATH=~/.clawdbot/b.json CLAWDBOT_STATE_DIR=~/.clawdbot-b clawdbo
```
## Protocol (operator view)
- Mandatory first frame from client: `req {type:"req", id, method:"connect", params:{minProtocol,maxProtocol,client:{name,version,platform,deviceFamily?,modelIdentifier?,mode,instanceId}, caps, auth?, locale?, userAgent? } }`.
- Mandatory first frame from client: `req {type:"req", id, method:"connect", params:{minProtocol,maxProtocol,client:{id,displayName?,version,platform,deviceFamily?,modelIdentifier?,mode,instanceId?}, caps, auth?, locale?, userAgent? } }`.
- Gateway replies `res {type:"res", id, ok:true, payload:hello-ok }` (or `ok:false` with an error, then closes).
- After handshake:
- Requests: `{type:"req", id, method, params}` → `{type:"res", id, ok, payload|error}`
@@ -259,7 +259,7 @@ Windows installs should use **WSL2** and follow the Linux systemd section above.
## Operational checks
- Liveness: open WS and send `req:connect` → expect `res` with `payload.type="hello-ok"` (with snapshot).
- Readiness: call `health` → expect `ok: true` and `web.linked=true`.
- Readiness: call `health` → expect `ok: true` and a linked provider in the `providers` payload (when applicable).
- Debug: subscribe to `tick` and `presence` events; ensure `status` shows linked/auth age; presence entries show Gateway host and connected clients.
## Safety guarantees

View File

@@ -5,14 +5,14 @@ read_when:
---
# Health Checks on macOS
How to see whether the WhatsApp Web/Baileys bridge is healthy from the menu bar app.
How to see whether the linked provider is healthy from the menu bar app.
## Menu bar
- Status dot now reflects Baileys health:
- Green: linked + socket opened recently.
- Orange: connecting/retrying.
- Red: logged out or probe failed.
- Secondary line reads "Web: linked · auth 12m · socket ok" or shows the failure reason.
- Secondary line reads "linked · auth 12m" or shows the failure reason.
- "Run Health Check" menu item triggers an on-demand probe.
## Settings
@@ -21,7 +21,7 @@ How to see whether the WhatsApp Web/Baileys bridge is healthy from the menu bar
- **Connections tab** surfaces provider status + controls for WhatsApp/Telegram (login QR, logout, probe, last disconnect/error).
## How the probe works
- App runs `clawdbot health --json` via `ShellExecutor` every ~60s and on demand. The probe loads creds, attempts a short Baileys connect, and reports status without sending messages.
- App runs `clawdbot health --json` via `ShellExecutor` every ~60s and on demand. The probe loads creds and reports status without sending messages.
- Cache the last good snapshot and the last error separately to avoid flicker; show the timestamp of each.
## When in doubt

View File

@@ -0,0 +1,113 @@
---
summary: "Provider plugin refactor implementation notes (registry, status, gateway/runtime)"
read_when:
- Adding or refactoring provider plugin wiring
- Moving provider-specific behavior into plugin hooks
---
# Provider Plugin Refactor — Implementation Notes
Goal: make providers (iMessage, Discord, etc.) pluggable with minimal wiring and shared UX/state paths.
## Architecture Overview
- Registry: `src/providers/plugins/index.ts` owns the plugin list.
- Provider dock: `src/providers/dock.ts` owns lightweight provider metadata used by shared flows (reply, command auth, block streaming) without importing full plugins.
- IDs/aliases: `src/providers/registry.ts` owns stable provider ids + input aliases.
- Shape: `src/providers/plugins/types.ts` defines the plugin contract.
- Gateway: `src/gateway/server-providers.ts` drives start/stop + runtime snapshots via plugins.
- Outbound: `src/infra/outbound/deliver.ts` routes through plugin outbound when present.
- Outbound delivery loads **outbound adapters** on-demand via `src/providers/plugins/outbound/load.ts` (avoid importing heavy provider plugins on hot paths).
- Reload: `src/gateway/config-reload.ts` uses plugin `reload.configPrefixes` lazily (avoid init cycles).
- CLI: `src/commands/providers/*` uses plugin list for add/remove/status/list.
- Protocol: `src/gateway/protocol/schema.ts` (v3) makes provider-shaped responses container-generic (maps keyed by provider id).
## Plugin Contract (high-level)
Each `ProviderPlugin` bundles:
- `meta`: id/labels/docs/sort order.
- `capabilities`: chatTypes + optional features (polls, media, nativeCommands, etc.).
- `config`: list/resolve/default/isConfigured/describeAccount + isEnabled + (un)configured reasons + `resolveAllowFrom` + `formatAllowFrom`.
- `outbound`: deliveryMode + chunker + resolveTarget (mode-aware) + sendText/sendMedia/sendPoll + pollMaxOptions.
- `status`: defaultRuntime + probe/audit/buildAccountSnapshot + buildProviderSummary + logSelfId + collectStatusIssues.
- `gateway`: startAccount/stopAccount with runtime context (`getStatus`/`setStatus`), plus optional `loginWithQrStart/loginWithQrWait` for gateway-owned QR login flows.
- `security`: dmPolicy + allowFrom hints used by `doctor security`.
- `heartbeat`: optional readiness checks + heartbeat recipient resolution when providers own targeting.
- `auth`: optional login hook used by `clawdbot providers login`.
- `reload`: `configPrefixes` that map to hot restarts.
- `onboarding`: optional CLI onboarding adapter (wizard UI hooks per provider).
- `agentTools`: optional provider-owned agent tools (ex: QR login).
## Key Integration Notes
- `listProviderPlugins()` is the runtime source of truth for provider UX and wiring.
- Avoid importing `src/providers/plugins/index.ts` from shared modules (reply flow, command auth, sandbox explain). Its intentionally “heavy” (providers may pull web login / monitor code). Use `getProviderDock()` + `normalizeProviderId()` for cheap metadata, and only `getProviderPlugin()` at execution boundaries (ex: `src/auto-reply/reply/route-reply.ts`).
- WhatsApp plugin keeps Baileys-heavy login bits behind lazy imports; cheap auth file checks live in `src/web/auth-store.ts` (so outbound routing doesnt pay Baileys import cost).
- `routeReply` delegates sending to plugin `outbound` adapters via a lazy import of `src/infra/outbound/deliver.ts` (so adding a provider is “just implement outbound adapter”, no router switches).
- Avoid static imports of provider monitors inside plugin modules. Monitors typically import the reply pipeline, which can create ESM cycles (and break Vite/Vitest SSR with TDZ errors). Prefer lazy imports inside `gateway.startAccount`.
- Debug cycle leaks quickly with: `npx -y madge --circular src/providers/plugins/index.ts`.
- Gateway protocol schema keeps provider selection as an open-ended string (no provider enum / static list) to avoid init cycles and so new plugins dont require protocol changes.
- Protocol v3: no more per-provider fields in `providers.status`; consumers must read map entries by provider id.
- `DEFAULT_CHAT_PROVIDER` lives in `src/providers/registry.ts` and is used anywhere we need a fallback delivery surface.
- Provider reload rules are computed lazily to avoid static init cycles in tests.
- Signal/iMessage media size limits are now resolved inside their plugins.
- `normalizeProviderId()` handles aliases (ex: `imsg`, `teams`) so CLI and API inputs stay stable.
- `ProviderId` is `ChatProviderId` (no extra special-cased provider IDs in shared code).
- Gateway runtime defaults (`status.defaultRuntime`) replace the old per-provider runtime map.
- Gateway runtime snapshot (`getRuntimeSnapshot`) is map-based: `{ providers, providerAccounts }` (no `${id}Accounts` keys).
- `providers.status` response keys (v3):
- `providerOrder: string[]`
- `providerLabels: Record<string, string>`
- `providers: Record<string, unknown>` (provider summary objects, plugin-defined)
- `providerAccounts: Record<string, ProviderAccountSnapshot[]>`
- `providerDefaultAccountId: Record<string, string>`
- `providers.status` summary objects come from `status.buildProviderSummary` (no per-provider branching in the handler).
- `providers.status` warnings now flow through `status.collectStatusIssues` per plugin.
- CLI list uses `meta.showConfigured` to decide whether to show configured state.
- CLI provider options and prompt provider lists are generated from `listProviderPlugins()` (avoid hardcoded arrays).
- Provider selection (`resolveMessageProviderSelection`) now inspects `config.isEnabled` + `config.isConfigured` per plugin instead of hardcoded provider checks.
- Pairing flows (CLI + store) now use `plugin.pairing` (`idLabel`, `normalizeAllowEntry`, `notifyApproval`) via `src/providers/plugins/pairing.ts`.
- CLI provider remove/disable delegates to `config.setAccountEnabled` + `config.deleteAccount` per plugin.
- CLI provider add now delegates to `plugin.setup` for account validation, naming, and config writes (no hardcoded provider checks).
- Agent provider status entries are now built from plugin config/status (`status.resolveAccountState` for custom state labels).
- Agent binding defaults use `meta.forceAccountBinding` to avoid hardcoded provider checks.
- Onboarding quickstart allowlist uses `meta.quickstartAllowFrom` to avoid hardcoded provider lists.
- `resolveProviderDefaultAccountId()` is the shared helper for picking default accounts from `accountIds` + plugin config.
- `routeReply` uses plugin outbound senders; `ProviderOutboundContext` supports `replyToId` + `threadId` and outbound delivery supports `abortSignal` for cooperative cancellation.
- Outbound target resolution (`resolveOutboundTarget`) now delegates to `plugin.outbound.resolveTarget` (mode-aware, uses config allowlists when present).
- Outbound delivery results accept `meta` for provider-specific fields to avoid core type churn in new plugins.
- Agent gateway routing sets `deliveryTargetMode` and uses `resolveOutboundTarget` for implicit fallback targets when `to` is missing.
- Elevated tool allowlists (`tools.elevated.allowFrom`) are a record keyed by provider id (no schema update needed when adding providers).
- Block streaming defaults live on the plugin (`capabilities.blockStreaming`, `streaming.blockStreamingCoalesceDefaults`) instead of hardcoded provider checks.
- Provider logout now routes through `providers.logout` using `gateway.logoutAccount` on each plugin (clients should call the generic method).
- Gateway message-provider normalization uses `src/providers/registry.ts` for cheap validation/normalization without plugin init cycles.
- Group mention gating now flows through `plugin.groups.resolveRequireMention` (Discord/Slack/Telegram/WhatsApp/iMessage) instead of branching in reply handlers.
- Command authorization uses `config.resolveAllowFrom` + `config.formatAllowFrom`, with `commands.enforceOwnerForCommands` and `commands.skipWhenConfigEmpty` driving provider-specific behavior.
- Security warnings (`doctor security`) use `plugin.security.resolveDmPolicy` + `plugin.security.collectWarnings`; supply `policyPath` + `allowFromPath` for accurate config hints.
- Reply threading uses `plugin.threading.resolveReplyToMode` and `plugin.threading.allowTagsWhenOff` rather than provider switches in reply helpers.
- Tool auto-threading context flows through `plugin.threading.buildToolContext` (e.g., Slack threadTs injection).
- Messaging tool dedupe now relies on `plugin.messaging.normalizeTarget` for provider-specific target normalization.
- Message tool + CLI action dispatch now use `plugin.actions.listActions` + `plugin.actions.handleAction`; use `plugin.actions.supportsAction` for dispatch-only gating when you still want fallback send/poll.
- Session announce targets can opt into `meta.preferSessionLookupForAnnounceTarget` when session keys are insufficient (e.g., WhatsApp).
- Onboarding provider setup is delegated to adapter modules under `src/providers/plugins/onboarding/*`, keeping `setupProviders` provider-agnostic.
- Onboarding registry now reads `plugin.onboarding` from each provider (no standalone onboarding map).
- Provider login flows (`clawdbot providers login`) route through `plugin.auth.login` when available.
- `clawdbot status` reports `linkProvider` (derived from `status.buildProviderSummary().linked`) instead of a hardcoded `web` provider field.
- Gateway `web.login.*` methods use `plugin.gatewayMethods` ownership to pick the provider (no hardcoded `normalizeProviderId("web")` in the handler).
## CLI Commands (inline references)
- Add/remove providers: `clawdbot providers add <provider>` / `clawdbot providers remove <provider>`.
- Inspect provider state: `clawdbot providers list`, `clawdbot providers status`.
- Link/unlink providers: `clawdbot providers login --provider <provider>` / `clawdbot providers logout --provider <provider>`.
- Pairing approvals: `clawdbot pairing list <provider>`, `clawdbot pairing approve <provider> <code>`.
## Adding a Provider (checklist)
1) Create `src/providers/plugins/<id>.ts` exporting `ProviderPlugin`.
2) Register in `src/providers/plugins/index.ts` and update `src/providers/registry.ts` (ids/aliases/meta) if needed.
3) Add a dock entry in `src/providers/dock.ts` for any shared behavior (capabilities, allowFrom format/resolve, mention stripping, threading, streaming chunk defaults).
4) Add `reload.configPrefixes` for hot reload when config changes.
5) Delegate to existing provider modules (send/probe/monitor) or create them.
6) If you changed the gateway protocol: run `pnpm protocol:check` (updates `dist/protocol.schema.json` + `apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift`).
7) Update docs/tests for any behavior changes.
## Cleanup Expectations
- Keep plugin files small; move heavy logic into provider modules.
- Prefer shared helpers over V2 copies.
- Update docs when behavior/inputs change.

View File

@@ -40,11 +40,9 @@ Directives (`/think`, `/verbose`, `/reasoning`, `/elevated`) are parsed even whe
Text + native (when enabled):
- `/help`
- `/commands`
- `/whoami` (alias: `/id`)
- `/status`
- `/status` (show current status; includes a short usage line when available)
- `/usage` (alias: `/status`)
- `/whoami` (alias: `/id`)
- `/whoami` (show your sender id; alias: `/id`)
- `/config show|get|set|unset` (persist config to disk, owner-only; requires `commands.config: true`)
- `/debug show|set|unset|reset` (runtime overrides, owner-only; requires `commands.debug: true`)
- `/cost on|off` (toggle per-response usage line)

View File

@@ -89,7 +89,8 @@ ws.send(
minProtocol: PROTOCOL_VERSION,
maxProtocol: PROTOCOL_VERSION,
client: {
name: \"docker-net-e2e\",
id: \"test\",
displayName: \"docker-net-e2e\",
version: \"dev\",
platform: process.platform,
mode: \"test\",
@@ -112,4 +113,3 @@ console.log(\"ok\");
NODE"
echo "OK"

View File

@@ -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";

View File

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

View File

@@ -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,

View File

@@ -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) {

View File

@@ -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:",
"",
`![whatsapp-qr](${result.qrDataUrl})`,
].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,

View File

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

View File

@@ -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";

View File

@@ -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)

View File

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

View File

@@ -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

View File

@@ -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({

View File

@@ -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: {

View File

@@ -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", () => {

View File

@@ -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[] {

View File

@@ -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,

View File

@@ -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", () => {

View File

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

View File

@@ -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") },
};

View File

@@ -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,

View File

@@ -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,

View File

@@ -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(

View File

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

View File

@@ -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,

View File

@@ -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,

View File

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

View File

@@ -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: {

View File

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

View File

@@ -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",
}),
);
});
});

View File

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

View File

@@ -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("#")

View File

@@ -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;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More