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: `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 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. - 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 ### Changes
- Onboarding/Models: add first-class Z.AI (GLM) auth choice (`zai-api-key`) + `--zai-api-key` flag. - 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. - 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. - 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. - 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) - 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. - 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) { private func openSettings(tab: SettingsTab) {
SettingsTabRouter.request(tab) SettingsTabRouter.request(tab)
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab) SettingsWindowOpener.shared.open()
NSApp.sendAction(#selector(NSApplication.showSettingsWindow), to: nil, from: nil) DispatchQueue.main.async {
NotificationCenter.default.post(name: .clawdbotSelectSettingsTab, object: tab)
}
} }
private static func appVersion() -> String? { private static func appVersion() -> String? {

View File

@@ -34,7 +34,7 @@ enum CLIInstaller {
self.installedLocation() != nil 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 expected = GatewayEnvironment.expectedGatewayVersion()?.description ?? "latest"
let prefix = Self.installPrefix() let prefix = Self.installPrefix()
await statusHandler("Installing clawdbot CLI…") await statusHandler("Installing clawdbot CLI…")

View File

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

View File

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

View File

@@ -121,12 +121,54 @@ struct ProvidersStatusSnapshot: Codable {
let lastProbeAt: Double? 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 ts: Double
let whatsapp: WhatsAppStatus let providerOrder: [String]
let telegram: TelegramStatus let providerLabels: [String: String]
let discord: DiscordStatus? let providers: [String: AnyCodable]
let signal: SignalStatus? let providerAccounts: [String: [ProviderAccountSnapshot]]
let imessage: IMessageStatus? 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 { struct ConfigSnapshot: Codable {

View File

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

View File

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

View File

@@ -226,7 +226,10 @@ actor GatewayEndpointStore {
} }
let config = try await self.ensureRemoteConfig(detail: Self.remoteConnectingDetail) let config = try await self.ensureRemoteConfig(detail: Self.remoteConnectingDetail)
guard let portInt = config.0.port, let port = UInt16(exactly: portInt) else { 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 return port
} }
@@ -290,7 +293,10 @@ actor GatewayEndpointStore {
let forwarded = try await ensure.task.value let forwarded = try await ensure.task.value
let stillRemote = await self.deps.mode() == .remote let stillRemote = await self.deps.mode() == .remote
guard stillRemote else { 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 { if self.remoteEnsure?.token == ensure.token {

View File

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

View File

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

View File

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

View File

@@ -461,10 +461,8 @@ struct GeneralSettings: View {
self.isInstallingCLI = true self.isInstallingCLI = true
defer { isInstallingCLI = false } defer { isInstallingCLI = false }
await CLIInstaller.install { status in await CLIInstaller.install { status in
await MainActor.run { self.cliStatus = status
self.cliStatus = status self.refreshCLIStatus()
self.refreshCLIStatus()
}
} }
} }
@@ -503,7 +501,19 @@ struct GeneralSettings: View {
} }
if let snap = snapshot { 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) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
Text("Session store: \(snap.sessions.path) (\(snap.sessions.count) entries)") Text("Session store: \(snap.sessions.path) (\(snap.sessions.count) entries)")

View File

@@ -4,35 +4,29 @@ import Observation
import SwiftUI import SwiftUI
struct HealthSnapshot: Codable, Sendable { struct HealthSnapshot: Codable, Sendable {
struct Telegram: Codable, Sendable { struct ProviderSummary: Codable, Sendable {
struct Probe: Codable, Sendable { struct Probe: Codable, Sendable {
struct Bot: Codable, Sendable { struct Bot: Codable, Sendable {
let id: Int?
let username: String? let username: String?
} }
let ok: Bool struct Webhook: Codable, Sendable {
let url: String?
}
let ok: Bool?
let status: Int? let status: Int?
let error: String? let error: String?
let elapsedMs: Double? let elapsedMs: Double?
let bot: Bot? let bot: Bot?
let webhook: Webhook?
} }
let configured: Bool let configured: Bool?
let probe: Probe? let linked: Bool?
}
struct Web: Codable, Sendable {
struct Connect: Codable, Sendable {
let ok: Bool
let status: Int?
let error: String?
let elapsedMs: Double?
}
let linked: Bool
let authAgeMs: Double? let authAgeMs: Double?
let connect: Connect? let probe: Probe?
let lastProbeAt: Double?
} }
struct SessionInfo: Codable, Sendable { struct SessionInfo: Codable, Sendable {
@@ -50,8 +44,9 @@ struct HealthSnapshot: Codable, Sendable {
let ok: Bool? let ok: Bool?
let ts: Double let ts: Double
let durationMs: Double let durationMs: Double
let web: Web let providers: [String: ProviderSummary]
let telegram: Telegram? let providerOrder: [String]?
let providerLabels: [String: String]?
let heartbeatSeconds: Int? let heartbeatSeconds: Int?
let sessions: Sessions 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() { func start() {
guard self.loopTask == nil else { return } guard self.loopTask == nil else { return }
self.loopTask = Task { [weak self] in self.loopTask = Task { [weak self] in
@@ -142,10 +144,49 @@ final class HealthStore {
} }
} }
private static func isTelegramHealthy(_ snap: HealthSnapshot) -> Bool { private static func isProviderHealthy(_ summary: HealthSnapshot.ProviderSummary) -> Bool {
guard let tg = snap.telegram, tg.configured else { return false } guard summary.configured == true else { return false }
// If probe is missing, treat it as "configured but unknown health" (not a hard fail). // 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 { var state: HealthState {
@@ -153,13 +194,15 @@ final class HealthStore {
return .degraded(error) return .degraded(error)
} }
guard let snap = self.snapshot else { return .unknown } guard let snap = self.snapshot else { return .unknown }
if !snap.web.linked { guard let link = self.resolveLinkProvider(snap) else { return .unknown }
// WhatsApp Web linking is optional if Telegram is healthy; don't paint the whole app red. if link.summary.linked != true {
return Self.isTelegramHealthy(snap) ? .degraded("Not linked") : .linkingNeeded // 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 { // A provider can be "linked" but still unhealthy (failed probe / cannot connect).
let reason = connect.error ?? "connect failed" if let probe = link.summary.probe, probe.ok == false {
return .degraded(reason) return .degraded(Self.describeProbeFailure(probe))
} }
return .ok return .ok
} }
@@ -168,19 +211,22 @@ final class HealthStore {
if self.isRefreshing { return "Health check running…" } if self.isRefreshing { return "Health check running…" }
if let error = self.lastError { return "Health check failed: \(error)" } if let error = self.lastError { return "Health check failed: \(error)" }
guard let snap = self.snapshot else { return "Health check pending" } guard let snap = self.snapshot else { return "Health check pending" }
if !snap.web.linked { guard let link = self.resolveLinkProvider(snap) else { return "Health check pending" }
if let tg = snap.telegram, tg.configured { if link.summary.linked != true {
let tgLabel = (tg.probe?.ok ?? true) ? "Telegram ok" : "Telegram degraded" if let fallback = self.resolveFallbackProvider(snap, excluding: link.id) {
return "\(tgLabel) · Not linked — run clawdbot login" 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" return "Not linked — run clawdbot login"
} }
let auth = snap.web.authAgeMs.map { msToAge($0) } ?? "unknown" let auth = link.summary.authAgeMs.map { msToAge($0) } ?? "unknown"
if let connect = snap.web.connect, !connect.ok { if let probe = link.summary.probe, probe.ok == false {
let code = connect.status.map(String.init) ?? "?" let status = probe.status.map(String.init) ?? "?"
return "Link stale? status \(code)" 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. /// 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 { 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" return "Not linked — run clawdbot login"
} }
if let connect = snap.web.connect, !connect.ok { if let link = self.resolveLinkProvider(snap), let probe = link.summary.probe, probe.ok == false {
let elapsed = connect.elapsedMs.map { "\(Int($0))ms" } ?? "unknown duration" return Self.describeProbeFailure(probe)
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 fallback, !fallback.isEmpty { if let fallback, !fallback.isEmpty {
return fallback return fallback

View File

@@ -242,6 +242,18 @@ final class InstancesStore {
do { do {
let data = try await ControlChannel.shared.health(timeout: 8) let data = try await ControlChannel.shared.health(timeout: 8)
guard let snap = decodeHealthSnapshot(from: data) else { return } 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( let entry = InstanceInfo(
id: "health-\(snap.ts)", id: "health-\(snap.ts)",
host: "gateway (health)", host: "gateway (health)",
@@ -253,7 +265,7 @@ final class InstancesStore {
lastInputSeconds: nil, lastInputSeconds: nil,
mode: "health", mode: "health",
reason: "health probe", reason: "health probe",
text: "Health ok · linked=\(snap.web.linked)", text: "Health ok · \(linkLabel) linked=\(linked)",
ts: snap.ts) ts: snap.ts)
if !self.instances.contains(where: { $0.id == entry.id }) { if !self.instances.contains(where: { $0.id == entry.id }) {
self.instances.insert(entry, at: 0) self.instances.insert(entry, at: 0)

View File

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

View File

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

View File

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

View File

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

View File

@@ -345,7 +345,10 @@ final class LocationPermissionRequester: NSObject, CLLocationManagerDelegate {
} }
// Legacy callback (still used on some macOS versions / configurations). // 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 Task { @MainActor in
self.finish(status: status) 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$"#, of: #"\s*-?\s*bridge$"#,
with: "", with: "",
options: .regularExpression) 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 // Generated by scripts/protocol-gen-swift.ts do not edit by hand
import Foundation import Foundation
public let GATEWAY_PROTOCOL_VERSION = 2 public let GATEWAY_PROTOCOL_VERSION = 3
public enum ErrorCode: String, Codable, Sendable { public enum ErrorCode: String, Codable, Sendable {
case notLinked = "NOT_LINKED" 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 struct WebLoginStartParams: Codable, Sendable {
public let force: Bool? public let force: Bool?
public let timeoutms: Int? public let timeoutms: Int?

View File

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

View File

@@ -5,14 +5,14 @@ import Testing
@Suite struct HealthDecodeTests { @Suite struct HealthDecodeTests {
private let sampleJSON: String = // minimal but complete payload 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 { @Test func decodesCleanJSON() async throws {
let data = Data(sampleJSON.utf8) let data = Data(sampleJSON.utf8)
let snap = decodeHealthSnapshot(from: data) let snap = decodeHealthSnapshot(from: data)
#expect(snap?.web.linked == true) #expect(snap?.providers["whatsapp"]?.linked == true)
#expect(snap?.sessions.count == 1) #expect(snap?.sessions.count == 1)
} }
@@ -20,7 +20,7 @@ import Testing
let noisy = "debug: something logged\n" + self.sampleJSON + "\ntrailer" let noisy = "debug: something logged\n" + self.sampleJSON + "\ntrailer"
let snap = decodeHealthSnapshot(from: Data(noisy.utf8)) 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 { @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 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 remove`: disable by default; pass `--delete` to remove config entries without prompts.
- `providers login`: interactive provider login (WhatsApp Web only). - `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: Common options:
- `--provider <name>`: `whatsapp|telegram|discord|slack|signal|imessage|msteams` - `--provider <name>`: `whatsapp|telegram|discord|slack|signal|imessage|msteams`
@@ -268,7 +268,7 @@ Common options:
- `--verbose` - `--verbose`
`providers logout` options: `providers logout` options:
- `--provider <provider>` (default `whatsapp`; supports `whatsapp`/`web`) - `--provider <provider>` (default `whatsapp`)
- `--account <id>` - `--account <id>`
`providers list` options: `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: read_when:
- Changing provider routing or inbox behavior - Changing provider routing or inbox behavior
--- ---

View File

@@ -91,10 +91,11 @@ Connect (first message):
"minProtocol": 2, "minProtocol": 2,
"maxProtocol": 2, "maxProtocol": 2,
"client": { "client": {
"name": "macos", "id": "clawdbot-macos",
"displayName": "macos",
"version": "1.0.0", "version": "1.0.0",
"platform": "macos 15.1", "platform": "macos 15.1",
"mode": "app", "mode": "ui",
"instanceId": "A1B2" "instanceId": "A1B2"
} }
} }
@@ -150,10 +151,11 @@ ws.on("open", () => {
id: "c1", id: "c1",
method: "connect", method: "connect",
params: { params: {
minProtocol: 2, minProtocol: 3,
maxProtocol: 2, maxProtocol: 3,
client: { client: {
name: "example", id: "cli",
displayName: "example",
version: "dev", version: "dev",
platform: "node", platform: "node",
mode: "cli" 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: read_when:
- Diagnosing web provider health - Diagnosing web provider health
--- ---
# Health Checks (CLI) # Health Checks (CLI)
Short guide to verify the WhatsApp Web / Baileys stack without guessing. Short guide to verify provider connectivity without guessing.
## Quick checks ## 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 --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). - `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. - 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`. - 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`). - 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 ## 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) ## 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). - Gateway replies `res {type:"res", id, ok:true, payload:hello-ok }` (or `ok:false` with an error, then closes).
- After handshake: - After handshake:
- Requests: `{type:"req", id, method, params}` → `{type:"res", id, ok, payload|error}` - 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 ## Operational checks
- Liveness: open WS and send `req:connect` → expect `res` with `payload.type="hello-ok"` (with snapshot). - 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. - Debug: subscribe to `tick` and `presence` events; ensure `status` shows linked/auth age; presence entries show Gateway host and connected clients.
## Safety guarantees ## Safety guarantees

View File

@@ -5,14 +5,14 @@ read_when:
--- ---
# Health Checks on macOS # 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 ## Menu bar
- Status dot now reflects Baileys health: - Status dot now reflects Baileys health:
- Green: linked + socket opened recently. - Green: linked + socket opened recently.
- Orange: connecting/retrying. - Orange: connecting/retrying.
- Red: logged out or probe failed. - 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. - "Run Health Check" menu item triggers an on-demand probe.
## Settings ## 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). - **Connections tab** surfaces provider status + controls for WhatsApp/Telegram (login QR, logout, probe, last disconnect/error).
## How the probe works ## 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. - Cache the last good snapshot and the last error separately to avoid flicker; show the timestamp of each.
## When in doubt ## 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): Text + native (when enabled):
- `/help` - `/help`
- `/commands` - `/commands`
- `/whoami` (alias: `/id`)
- `/status`
- `/status` (show current status; includes a short usage line when available) - `/status` (show current status; includes a short usage line when available)
- `/usage` (alias: `/status`) - `/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`) - `/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`) - `/debug show|set|unset|reset` (runtime overrides, owner-only; requires `commands.debug: true`)
- `/cost on|off` (toggle per-response usage line) - `/cost on|off` (toggle per-response usage line)

View File

@@ -89,7 +89,8 @@ ws.send(
minProtocol: PROTOCOL_VERSION, minProtocol: PROTOCOL_VERSION,
maxProtocol: PROTOCOL_VERSION, maxProtocol: PROTOCOL_VERSION,
client: { client: {
name: \"docker-net-e2e\", id: \"test\",
displayName: \"docker-net-e2e\",
version: \"dev\", version: \"dev\",
platform: process.platform, platform: process.platform,
mode: \"test\", mode: \"test\",
@@ -112,4 +113,3 @@ console.log(\"ok\");
NODE" NODE"
echo "OK" 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"; export { runClaudeCliAgent, runCliAgent } from "./cli-runner.js";

View File

@@ -1,3 +1,8 @@
import {
getProviderPlugin,
normalizeProviderId,
} from "../providers/plugins/index.js";
export type MessagingToolSend = { export type MessagingToolSend = {
tool: string; tool: string;
provider: string; provider: string;
@@ -5,101 +10,29 @@ export type MessagingToolSend = {
to?: string; to?: string;
}; };
const MESSAGING_TOOLS = new Set([ const CORE_MESSAGING_TOOLS = new Set(["sessions_send", "message"]);
"telegram",
"whatsapp",
"discord",
"slack",
"sessions_send",
"message",
]);
// Provider docking: any plugin with `actions` opts into messaging tool handling.
export function isMessagingTool(toolName: string): boolean { 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( export function isMessagingToolSendAction(
toolName: string, toolName: string,
actionRaw: string, args: Record<string, unknown>,
): boolean { ): boolean {
const action = actionRaw.trim(); const action = typeof args.action === "string" ? args.action.trim() : "";
if (toolName === "sessions_send") return true; if (toolName === "sessions_send") return true;
if (toolName === "message") { if (toolName === "message") {
return action === "send" || action === "thread-reply"; return action === "send" || action === "thread-reply";
} }
return action === "sendMessage" || action === "threadReply"; const providerId = normalizeProviderId(toolName);
} if (!providerId) return false;
const plugin = getProviderPlugin(providerId);
function normalizeSlackTarget(raw: string): string | undefined { if (!plugin?.actions?.extractToolSend) return false;
const trimmed = raw.trim(); return Boolean(plugin.actions.extractToolSend({ args })?.to);
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();
} }
export function normalizeTargetForProvider( export function normalizeTargetForProvider(
@@ -107,14 +40,10 @@ export function normalizeTargetForProvider(
raw?: string, raw?: string,
): string | undefined { ): string | undefined {
if (!raw) return undefined; if (!raw) return undefined;
switch (provider.trim().toLowerCase()) { const providerId = normalizeProviderId(provider);
case "slack": const plugin = providerId ? getProviderPlugin(providerId) : undefined;
return normalizeSlackTarget(raw); const normalized =
case "discord": plugin?.messaging?.normalizeTarget?.(raw) ??
return normalizeDiscordTarget(raw); (raw.trim().toLowerCase() || undefined);
case "telegram": return normalized || undefined;
return normalizeTelegramTarget(raw);
default:
return raw.trim().toLowerCase() || undefined;
}
} }

View File

@@ -117,6 +117,7 @@ import {
type SkillSnapshot, type SkillSnapshot,
} from "./skills.js"; } from "./skills.js";
import { buildAgentSystemPrompt } from "./system-prompt.js"; import { buildAgentSystemPrompt } from "./system-prompt.js";
import { buildToolSummaryMap } from "./tool-summaries.js";
import { normalizeUsage, type UsageLike } from "./usage.js"; import { normalizeUsage, type UsageLike } from "./usage.js";
import { import {
filterBootstrapFilesForSession, filterBootstrapFilesForSession,
@@ -644,6 +645,7 @@ function buildEmbeddedSystemPrompt(params: {
runtimeInfo: params.runtimeInfo, runtimeInfo: params.runtimeInfo,
sandboxInfo: params.sandboxInfo, sandboxInfo: params.sandboxInfo,
toolNames: params.tools.map((tool) => tool.name), toolNames: params.tools.map((tool) => tool.name),
toolSummaries: buildToolSummaryMap(params.tools),
modelAliasLines: params.modelAliasLines, modelAliasLines: params.modelAliasLines,
userTimezone: params.userTimezone, userTimezone: params.userTimezone,
userTime: params.userTime, userTime: params.userTime,

View File

@@ -9,6 +9,10 @@ import { formatToolAggregate } from "../auto-reply/tool-meta.js";
import { resolveStateDir } from "../config/paths.js"; import { resolveStateDir } from "../config/paths.js";
import { emitAgentEvent } from "../infra/agent-events.js"; import { emitAgentEvent } from "../infra/agent-events.js";
import { createSubsystemLogger } from "../logging.js"; import { createSubsystemLogger } from "../logging.js";
import {
getProviderPlugin,
normalizeProviderId,
} from "../providers/plugins/index.js";
import { truncateUtf16Safe } from "../utils.js"; import { truncateUtf16Safe } from "../utils.js";
import type { BlockReplyChunking } from "./pi-embedded-block-chunker.js"; import type { BlockReplyChunking } from "./pi-embedded-block-chunker.js";
import { EmbeddedBlockChunker } from "./pi-embedded-block-chunker.js"; import { EmbeddedBlockChunker } from "./pi-embedded-block-chunker.js";
@@ -142,59 +146,37 @@ function extractMessagingToolSend(
toolName: string, toolName: string,
args: Record<string, unknown>, args: Record<string, unknown>,
): MessagingToolSend | undefined { ): MessagingToolSend | undefined {
// Provider docking: new provider tools must implement plugin.actions.extractToolSend.
const action = typeof args.action === "string" ? args.action.trim() : ""; const action = typeof args.action === "string" ? args.action.trim() : "";
const accountIdRaw = const accountIdRaw =
typeof args.accountId === "string" ? args.accountId.trim() : undefined; typeof args.accountId === "string" ? args.accountId.trim() : undefined;
const accountId = accountIdRaw ? accountIdRaw : 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 (toolName === "message") {
if (action !== "send" && action !== "thread-reply") return undefined; if (action !== "send" && action !== "thread-reply") return undefined;
const toRaw = typeof args.to === "string" ? args.to : undefined; const toRaw = typeof args.to === "string" ? args.to : undefined;
if (!toRaw) return undefined; if (!toRaw) return undefined;
const providerRaw = const providerRaw =
typeof args.provider === "string" ? args.provider.trim() : ""; 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); const to = normalizeTargetForProvider(provider, toRaw);
return to ? { tool: toolName, provider, accountId, to } : undefined; 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: { export function subscribeEmbeddedPiSession(params: {
@@ -564,7 +546,10 @@ export function subscribeEmbeddedPiSession(params: {
typeof argsRecord.action === "string" typeof argsRecord.action === "string"
? argsRecord.action.trim() ? argsRecord.action.trim()
: ""; : "";
const isMessagingSend = isMessagingToolSendAction(toolName, action); const isMessagingSend = isMessagingToolSendAction(
toolName,
argsRecord,
);
if (isMessagingSend) { if (isMessagingSend) {
const sendTarget = extractMessagingToolSend(toolName, argsRecord); const sendTarget = extractMessagingToolSend(toolName, argsRecord);
if (sendTarget) { if (sendTarget) {

View File

@@ -6,12 +6,10 @@ import {
createWriteTool, createWriteTool,
readTool, readTool,
} from "@mariozechner/pi-coding-agent"; } from "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/typebox";
import type { ClawdbotConfig } from "../config/config.js"; import type { ClawdbotConfig } from "../config/config.js";
import { detectMime } from "../media/mime.js"; import { detectMime } from "../media/mime.js";
import { isSubagentSessionKey } from "../routing/session-key.js"; import { isSubagentSessionKey } from "../routing/session-key.js";
import { resolveGatewayMessageProvider } from "../utils/message-provider.js"; import { resolveGatewayMessageProvider } from "../utils/message-provider.js";
import { startWebLoginWithQr, waitForWebLogin } from "../web/login-qr.js";
import { import {
resolveAgentConfig, resolveAgentConfig,
resolveAgentIdFromSessionKey, resolveAgentIdFromSessionKey,
@@ -24,6 +22,7 @@ import {
} from "./bash-tools.js"; } from "./bash-tools.js";
import { createClawdbotTools } from "./clawdbot-tools.js"; import { createClawdbotTools } from "./clawdbot-tools.js";
import type { ModelAuthMode } from "./model-auth.js"; import type { ModelAuthMode } from "./model-auth.js";
import { listProviderAgentTools } from "./provider-tools.js";
import type { SandboxContext, SandboxToolPolicy } from "./sandbox.js"; import type { SandboxContext, SandboxToolPolicy } from "./sandbox.js";
import { assertSandboxPath } from "./sandbox-paths.js"; import { assertSandboxPath } from "./sandbox-paths.js";
import { cleanSchemaForGemini } from "./schema/clean-for-gemini.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); 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 { function createClawdbotReadTool(base: AnyAgentTool): AnyAgentTool {
return { return {
...base, ...base,
@@ -635,7 +565,8 @@ export function createClawdbotCodingTools(options?: {
: []), : []),
bashTool as unknown as AnyAgentTool, bashTool as unknown as AnyAgentTool,
processTool as unknown as AnyAgentTool, processTool as unknown as AnyAgentTool,
createWhatsAppLoginTool(), // Provider docking: include provider-defined agent tools (login, etc.).
...listProviderAgentTools({ cfg: options?.config }),
...createClawdbotTools({ ...createClawdbotTools({
browserControlUrl: sandbox?.browser?.controlUrl, browserControlUrl: sandbox?.browser?.controlUrl,
allowHostBrowserControl: sandbox ? sandbox.browserAllowHostControl : true, 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, loadConfig,
STATE_DIR_CLAWDBOT, STATE_DIR_CLAWDBOT,
} from "../config/config.js"; } from "../config/config.js";
import { PROVIDER_IDS } from "../providers/registry.js";
import { import {
buildAgentMainSessionKey, buildAgentMainSessionKey,
normalizeAgentId, normalizeAgentId,
@@ -176,13 +177,14 @@ const DEFAULT_TOOL_ALLOW = [
"sessions_spawn", "sessions_spawn",
"session_status", "session_status",
]; ];
// Provider docking: keep sandbox policy aligned with provider tool names.
const DEFAULT_TOOL_DENY = [ const DEFAULT_TOOL_DENY = [
"browser", "browser",
"canvas", "canvas",
"nodes", "nodes",
"cron", "cron",
"discord",
"gateway", "gateway",
...PROVIDER_IDS,
]; ];
export const DEFAULT_SANDBOX_BROWSER_IMAGE = export const DEFAULT_SANDBOX_BROWSER_IMAGE =
"clawdbot-sandbox-browser:bookworm-slim"; "clawdbot-sandbox-browser:bookworm-slim";

View File

@@ -1,7 +1,10 @@
import type { ReasoningLevel, ThinkLevel } from "../auto-reply/thinking.js"; import type { ReasoningLevel, ThinkLevel } from "../auto-reply/thinking.js";
import { SILENT_REPLY_TOKEN } from "../auto-reply/tokens.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"; import type { EmbeddedContextFile } from "./pi-embedded-helpers.js";
const MESSAGE_PROVIDER_OPTIONS = PROVIDER_IDS.join("|");
export function buildAgentSystemPrompt(params: { export function buildAgentSystemPrompt(params: {
workspaceDir: string; workspaceDir: string;
defaultThinkLevel?: ThinkLevel; defaultThinkLevel?: ThinkLevel;
@@ -10,6 +13,7 @@ export function buildAgentSystemPrompt(params: {
ownerNumbers?: string[]; ownerNumbers?: string[];
reasoningTagHint?: boolean; reasoningTagHint?: boolean;
toolNames?: string[]; toolNames?: string[];
toolSummaries?: Record<string, string>;
modelAliasLines?: string[]; modelAliasLines?: string[];
userTimezone?: string; userTimezone?: string;
userTime?: 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", read: "Read file contents",
write: "Create or overwrite files", write: "Create or overwrite files",
edit: "Make precise edits to files", edit: "Make precise edits to files",
@@ -51,7 +55,7 @@ export function buildAgentSystemPrompt(params: {
ls: "List directory contents", ls: "List directory contents",
bash: "Run shell commands", bash: "Run shell commands",
process: "Manage background bash sessions", 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", browser: "Control web browser",
canvas: "Present/eval/snapshot the Canvas", canvas: "Present/eval/snapshot the Canvas",
nodes: "List/describe/notify/camera/screen on paired nodes", nodes: "List/describe/notify/camera/screen on paired nodes",
@@ -78,7 +82,6 @@ export function buildAgentSystemPrompt(params: {
"ls", "ls",
"bash", "bash",
"process", "process",
"whatsapp_login",
"browser", "browser",
"canvas", "canvas",
"nodes", "nodes",
@@ -107,17 +110,25 @@ export function buildAgentSystemPrompt(params: {
const normalizedTools = canonicalToolNames.map((tool) => tool.toLowerCase()); const normalizedTools = canonicalToolNames.map((tool) => tool.toLowerCase());
const availableTools = new Set(normalizedTools); 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( const extraTools = Array.from(
new Set(normalizedTools.filter((tool) => !toolOrder.includes(tool))), new Set(normalizedTools.filter((tool) => !toolOrder.includes(tool))),
); );
const enabledTools = toolOrder.filter((tool) => availableTools.has(tool)); const enabledTools = toolOrder.filter((tool) => availableTools.has(tool));
const toolLines = enabledTools.map((tool) => { const toolLines = enabledTools.map((tool) => {
const summary = toolSummaries[tool]; const summary = coreToolSummaries[tool] ?? externalToolSummaries.get(tool);
const name = resolveToolName(tool); const name = resolveToolName(tool);
return summary ? `- ${name}: ${summary}` : `- ${name}`; return summary ? `- ${name}: ${summary}` : `- ${name}`;
}); });
for (const tool of extraTools.sort()) { 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"); const hasGateway = availableTools.has("gateway");
@@ -160,9 +171,7 @@ export function buildAgentSystemPrompt(params: {
const runtimeCapabilitiesLower = new Set( const runtimeCapabilitiesLower = new Set(
runtimeCapabilities.map((cap) => cap.toLowerCase()), runtimeCapabilities.map((cap) => cap.toLowerCase()),
); );
const telegramInlineButtonsEnabled = const inlineButtonsEnabled = runtimeCapabilitiesLower.has("inlinebuttons");
runtimeProvider === "telegram" &&
runtimeCapabilitiesLower.has("inlinebuttons");
const skillsLines = skillsPrompt ? [skillsPrompt, ""] : []; const skillsLines = skillsPrompt ? [skillsPrompt, ""] : [];
const skillsSection = skillsPrompt const skillsSection = skillsPrompt
? [ ? [
@@ -188,7 +197,6 @@ export function buildAgentSystemPrompt(params: {
"- ls: list directory contents", "- ls: list directory contents",
`- ${bashToolName}: run shell commands (supports background via yieldMs/background)`, `- ${bashToolName}: run shell commands (supports background via yieldMs/background)`,
`- ${processToolName}: manage background bash sessions`, `- ${processToolName}: manage background bash sessions`,
"- whatsapp_login: generate a WhatsApp QR code and wait for linking",
"- browser: control clawd's dedicated browser", "- browser: control clawd's dedicated browser",
"- canvas: present/eval/snapshot the Canvas", "- canvas: present/eval/snapshot the Canvas",
"- nodes: list/describe/notify/camera/screen on paired nodes", "- nodes: list/describe/notify/camera/screen on paired nodes",
@@ -314,11 +322,11 @@ export function buildAgentSystemPrompt(params: {
"### message tool", "### message tool",
"- Use `message` for proactive sends + provider actions (polls, reactions, etc.).", "- Use `message` for proactive sends + provider actions (polls, reactions, etc.).",
"- For `action=send`, include `to` and `message`.", "- For `action=send`, include `to` and `message`.",
"- If multiple providers are configured, pass `provider` (whatsapp|telegram|discord|slack|signal|imessage|msteams).", `- If multiple providers are configured, pass \`provider\` (${MESSAGE_PROVIDER_OPTIONS}).`,
telegramInlineButtonsEnabled inlineButtonsEnabled
? "- Telegram: inline buttons supported. Use `action=send` with `buttons=[[{text,callback_data}]]` (callback_data routes back as a user message)." ? "- Inline buttons supported. Use `action=send` with `buttons=[[{text,callback_data}]]` (callback_data routes back as a user message)."
: runtimeProvider === "telegram" : runtimeProvider
? '- Telegram: inline buttons NOT enabled. If you need them, ask to add "inlineButtons" to telegram.capabilities or telegram.accounts.<id>.capabilities.' ? `- Inline buttons not enabled for ${runtimeProvider}. If you need them, ask to add "inlineButtons" to ${runtimeProvider}.capabilities or ${runtimeProvider}.accounts.<id>.capabilities.`
: "", : "",
] ]
.filter(Boolean) .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 { 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"; export const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789";
@@ -39,7 +43,8 @@ export async function callGatewayTool<T = unknown>(
params, params,
timeoutMs: gateway.timeoutMs, timeoutMs: gateway.timeoutMs,
expectFinal: extra?.expectFinal, expectFinal: extra?.expectFinal,
clientName: "agent", clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
mode: "agent", 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 { callGateway } from "../../gateway/call.js";
import {
getProviderPlugin,
normalizeProviderId,
} from "../../providers/plugins/index.js";
import type { AnnounceTarget } from "./sessions-send-helpers.js"; import type { AnnounceTarget } from "./sessions-send-helpers.js";
import { resolveAnnounceTargetFromKey } 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 parsedDisplay = resolveAnnounceTargetFromKey(params.displayKey);
const fallback = parsed ?? parsedDisplay ?? null; const fallback = parsed ?? parsedDisplay ?? null;
// Most providers can derive (provider,to) from the session key directly. if (fallback) {
// WhatsApp is special: we may need lastAccountId from the session store. const normalized = normalizeProviderId(fallback.provider);
if (fallback && fallback.provider !== "whatsapp") return fallback; const plugin = normalized ? getProviderPlugin(normalized) : null;
if (!plugin?.meta?.preferSessionLookupForAnnounceTarget) {
return fallback;
}
}
try { try {
const list = (await callGateway({ const list = (await callGateway({

View File

@@ -1,4 +1,8 @@
import type { ClawdbotConfig } from "../../config/config.js"; import type { ClawdbotConfig } from "../../config/config.js";
import {
getProviderPlugin,
normalizeProviderId,
} from "../../providers/plugins/index.js";
const ANNOUNCE_SKIP_TOKEN = "ANNOUNCE_SKIP"; const ANNOUNCE_SKIP_TOKEN = "ANNOUNCE_SKIP";
const REPLY_SKIP_TOKEN = "REPLY_SKIP"; const REPLY_SKIP_TOKEN = "REPLY_SKIP";
@@ -25,14 +29,19 @@ export function resolveAnnounceTargetFromKey(
const id = rest.join(":").trim(); const id = rest.join(":").trim();
if (!id) return null; if (!id) return null;
if (!providerRaw) return null; if (!providerRaw) return null;
const provider = providerRaw.toLowerCase(); const normalizedProvider = normalizeProviderId(providerRaw);
if (provider === "discord") { const provider = normalizedProvider ?? providerRaw.toLowerCase();
return { provider, to: `channel:${id}` }; const kindTarget = normalizedProvider
} ? kind === "channel"
if (provider === "signal") { ? `channel:${id}`
return { provider, to: `group:${id}` }; : `group:${id}`
} : id;
return { provider, to: id }; const normalized = normalizedProvider
? getProviderPlugin(normalizedProvider)?.messaging?.normalizeTarget?.(
kindTarget,
)
: undefined;
return { provider, to: normalized ?? kindTarget };
} }
export function buildAgentToAgentMessageContext(params: { export function buildAgentToAgentMessageContext(params: {

View File

@@ -117,7 +117,12 @@ describe("resolveTextChunkLimit", () => {
expect(resolveTextChunkLimit(undefined, "slack")).toBe(4000); expect(resolveTextChunkLimit(undefined, "slack")).toBe(4000);
expect(resolveTextChunkLimit(undefined, "signal")).toBe(4000); expect(resolveTextChunkLimit(undefined, "signal")).toBe(4000);
expect(resolveTextChunkLimit(undefined, "imessage")).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", () => { it("supports provider overrides", () => {

View File

@@ -8,80 +8,63 @@ import {
isSafeFenceBreak, isSafeFenceBreak,
parseFenceSpans, parseFenceSpans,
} from "../markdown/fences.js"; } from "../markdown/fences.js";
import type { ProviderId } from "../providers/plugins/types.js";
import { normalizeAccountId } from "../routing/session-key.js"; import { normalizeAccountId } from "../routing/session-key.js";
import { INTERNAL_MESSAGE_PROVIDER } from "../utils/message-provider.js";
export type TextChunkProvider = export type TextChunkProvider = ProviderId | typeof INTERNAL_MESSAGE_PROVIDER;
| "whatsapp"
| "telegram"
| "discord"
| "slack"
| "signal"
| "imessage"
| "webchat"
| "msteams";
const DEFAULT_CHUNK_LIMIT_BY_PROVIDER: Record<TextChunkProvider, number> = { const DEFAULT_CHUNK_LIMIT = 4000;
whatsapp: 4000,
telegram: 4000, type ProviderChunkConfig = {
discord: 2000, textChunkLimit?: number;
slack: 4000, accounts?: Record<string, { textChunkLimit?: number }>;
signal: 4000,
imessage: 4000,
webchat: 4000,
msteams: 4000,
}; };
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( export function resolveTextChunkLimit(
cfg: ClawdbotConfig | undefined, cfg: ClawdbotConfig | undefined,
provider?: TextChunkProvider, provider?: TextChunkProvider,
accountId?: string | null, accountId?: string | null,
opts?: { fallbackLimit?: number },
): number { ): number {
const fallback =
typeof opts?.fallbackLimit === "number" && opts.fallbackLimit > 0
? opts.fallbackLimit
: DEFAULT_CHUNK_LIMIT;
const providerOverride = (() => { const providerOverride = (() => {
if (!provider) return undefined; if (!provider || provider === INTERNAL_MESSAGE_PROVIDER) return undefined;
const normalizedAccountId = normalizeAccountId(accountId); const providerConfig = (cfg as Record<string, unknown> | undefined)?.[
if (provider === "whatsapp") { provider
return cfg?.whatsapp?.textChunkLimit; ] as ProviderChunkConfig | undefined;
} return resolveChunkLimitForProvider(providerConfig, accountId);
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 (typeof providerOverride === "number" && providerOverride > 0) { if (typeof providerOverride === "number" && providerOverride > 0) {
return providerOverride; return providerOverride;
} }
if (provider) return DEFAULT_CHUNK_LIMIT_BY_PROVIDER[provider]; return fallback;
return 4000;
} }
export function chunkText(text: string, limit: number): string[] { export function chunkText(text: string, limit: number): string[] {

View File

@@ -1,72 +1,123 @@
import type { ClawdbotConfig } from "../config/config.js"; 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"; import type { MsgContext } from "./templating.js";
export type CommandAuthorization = { export type CommandAuthorization = {
isWhatsAppProvider: boolean; providerId?: ProviderId;
ownerList: string[]; ownerList: string[];
senderE164?: string; senderId?: string;
isAuthorizedSender: boolean; isAuthorizedSender: boolean;
from?: string; from?: string;
to?: 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: { export function resolveCommandAuthorization(params: {
ctx: MsgContext; ctx: MsgContext;
cfg: ClawdbotConfig; cfg: ClawdbotConfig;
commandAuthorized: boolean; commandAuthorized: boolean;
}): CommandAuthorization { }): CommandAuthorization {
const { ctx, cfg, commandAuthorized } = params; const { ctx, cfg, commandAuthorized } = params;
const provider = (ctx.Provider ?? "").trim().toLowerCase(); const providerId = resolveProviderFromContext(ctx, cfg);
const from = (ctx.From ?? "").replace(/^whatsapp:/, ""); const dock = providerId ? getProviderDock(providerId) : undefined;
const to = (ctx.To ?? "").replace(/^whatsapp:/, ""); const from = (ctx.From ?? "").trim();
const hasWhatsappPrefix = const to = (ctx.To ?? "").trim();
(ctx.From ?? "").startsWith("whatsapp:") || const allowFromRaw = dock?.config?.resolveAllowFrom
(ctx.To ?? "").startsWith("whatsapp:"); ? dock.config.resolveAllowFrom({ cfg, accountId: ctx.AccountId })
const looksLikeE164 = (value: string) => : [];
Boolean(value && /^\+?\d{3,}$/.test(value.replace(/[^\d+]/g, ""))); const allowFromList = formatAllowFromList({
const inferWhatsApp = dock,
!provider && cfg,
Boolean(cfg.whatsapp?.allowFrom?.length) && accountId: ctx.AccountId,
(looksLikeE164(from) || looksLikeE164(to)); allowFrom: Array.isArray(allowFromRaw) ? allowFromRaw : [],
const isWhatsAppProvider = });
provider === "whatsapp" || hasWhatsappPrefix || inferWhatsApp;
const configuredAllowFrom = isWhatsAppProvider
? cfg.whatsapp?.allowFrom
: undefined;
const allowFromList =
configuredAllowFrom?.filter((entry) => entry?.trim()) ?? [];
const allowAll = const allowAll =
!isWhatsAppProvider ||
allowFromList.length === 0 || allowFromList.length === 0 ||
allowFromList.some((entry) => entry.trim() === "*"); allowFromList.some((entry) => entry.trim() === "*");
const senderE164 = normalizeE164( const ownerCandidates = allowAll
ctx.SenderE164 ?? (isWhatsAppProvider ? from : ""), ? []
); : allowFromList.filter((entry) => entry !== "*");
const ownerCandidates = if (!allowAll && ownerCandidates.length === 0 && to) {
isWhatsAppProvider && !allowAll const normalizedTo = formatAllowFromList({
? allowFromList.filter((entry) => entry !== "*") dock,
: []; cfg,
if (isWhatsAppProvider && !allowAll && ownerCandidates.length === 0 && to) { accountId: ctx.AccountId,
ownerCandidates.push(to); allowFrom: [to],
})[0];
if (normalizedTo) ownerCandidates.push(normalizedTo);
} }
const ownerList = ownerCandidates const ownerList = ownerCandidates;
.map((entry) => normalizeE164(entry))
.filter((entry): entry is string => Boolean(entry));
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 = const isOwner =
!isWhatsAppProvider || !enforceOwner ||
allowAll || allowAll ||
ownerList.length === 0 || ownerList.length === 0 ||
(senderE164 ? ownerList.includes(senderE164) : false); (senderId ? ownerList.includes(senderId) : false);
const isAuthorizedSender = commandAuthorized && isOwner; const isAuthorizedSender = commandAuthorized && isOwner;
return { return {
isWhatsAppProvider, providerId,
ownerList, ownerList,
senderE164: senderE164 || undefined, senderId: senderId || undefined,
isAuthorizedSender, isAuthorizedSender,
from: from || undefined, from: from || undefined,
to: to || 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(true); expect(hasControlCommand("/commands:")).toBe(true);
expect(hasControlCommand("commands")).toBe(false); expect(hasControlCommand("commands")).toBe(false);
expect(hasControlCommand("/compact")).toBe(true); expect(hasControlCommand("/status")).toBe(true);
expect(hasControlCommand("/compact:")).toBe(true); expect(hasControlCommand("/status:")).toBe(true);
expect(hasControlCommand("compact")).toBe(false);
expect(hasControlCommand("status")).toBe(false); expect(hasControlCommand("status")).toBe(false);
expect(hasControlCommand("usage")).toBe(false); expect(hasControlCommand("usage")).toBe(false);
@@ -55,6 +54,9 @@ describe("control command parsing", () => {
expect(hasControlCommand(`${alias}:`)).toBe(true); 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", () => { it("respects disabled config/debug commands", () => {

View File

@@ -1,4 +1,5 @@
import type { ClawdbotConfig } from "../config/types.js"; import type { ClawdbotConfig } from "../config/types.js";
import { listProviderDocks } from "../providers/dock.js";
export type CommandScope = "text" | "native" | "both"; export type CommandScope = "text" | "native" | "both";
@@ -263,8 +264,18 @@ export const CHAT_COMMANDS: ChatCommandDefinition[] = (() => {
assertCommandRegistry(commands); assertCommandRegistry(commands);
return 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 TEXT_ALIAS_MAP: Map<string, TextAliasSpec> = (() => {
const map = new Map<string, TextAliasSpec>(); const map = new Map<string, TextAliasSpec>();
@@ -354,14 +365,18 @@ export function normalizeCommandBody(raw: string): string {
const trimmed = raw.trim(); const trimmed = raw.trim();
if (!trimmed.startsWith("/")) return trimmed; 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 normalized = colonMatch
? (() => { ? (() => {
const [, command, rest] = colonMatch; const [, command, rest] = colonMatch;
const normalizedRest = rest.trimStart(); const normalizedRest = rest.trimStart();
return normalizedRest ? `/${command} ${normalizedRest}` : `/${command}`; return normalizedRest ? `/${command} ${normalizedRest}` : `/${command}`;
})() })()
: trimmed; : singleLine;
const lowered = normalized.toLowerCase(); const lowered = normalized.toLowerCase();
const exact = TEXT_ALIAS_MAP.get(lowered); const exact = TEXT_ALIAS_MAP.get(lowered);
@@ -380,44 +395,86 @@ export function normalizeCommandBody(raw: string): string {
: tokenSpec.canonical; : 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; if (cachedDetection) return cachedDetection;
const exact = new Set<string>(); const exact = new Set<string>();
const patterns: string[] = []; const patterns: string[] = [];
for (const command of CHAT_COMMANDS) { for (const cmd of CHAT_COMMANDS) {
for (const alias of command.textAliases) { for (const alias of cmd.textAliases) {
const normalized = alias.trim().toLowerCase(); const normalized = alias.trim().toLowerCase();
if (!normalized) continue; if (!normalized) continue;
exact.add(normalized); exact.add(normalized);
const escaped = escapeRegExp(normalized); const escaped = escapeRegExp(normalized);
if (!escaped) continue; if (!escaped) continue;
if (command.acceptsArgs) { if (cmd.acceptsArgs) {
patterns.push(`${escaped}(?:\\s+.+|\\s*:\\s*.*)?`); patterns.push(`${escaped}(?:\\s+.+|\\s*:\\s*.*)?`);
} else { } else {
patterns.push(`${escaped}(?:\\s*:\\s*)?`); patterns.push(`${escaped}(?:\\s*:\\s*)?`);
} }
} }
} }
const regex = patterns.length cachedDetection = {
? new RegExp(`^(?:${patterns.join("|")})$`, "i") exact,
: /$^/; regex: patterns.length
cachedDetection = { exact, regex }; ? new RegExp(`^(?:${patterns.join("|")})$`, "i")
: /$^/,
};
return cachedDetection; 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; if (!surface) return false;
return NATIVE_COMMAND_SURFACES.has(surface.toLowerCase()); return getNativeCommandSurfaces().has(surface.toLowerCase());
} }
export function shouldHandleTextCommands(params: { export function shouldHandleTextCommands(params: {
cfg: ClawdbotConfig; cfg: ClawdbotConfig;
surface?: string; surface: string;
commandSource?: "text" | "native"; commandSource?: "text" | "native";
}): boolean { }): boolean {
const { cfg, surface, commandSource } = params; if (params.commandSource === "native") return true;
const textEnabled = cfg.commands?.text !== false; if (params.cfg.commands?.text !== false) return true;
if (commandSource === "native") return true; return !isNativeCommandSurface(params.surface);
if (textEnabled) return true;
return !supportsNativeCommands(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) => { await withTempHome(async (home) => {
const cfg = { const cfg = {
agents: { agents: {
@@ -809,11 +809,7 @@ describe("trigger handling", () => {
workspace: join(home, "clawd"), workspace: join(home, "clawd"),
}, },
}, },
discord: { tools: { elevated: { allowFrom: { discord: ["steipete"] } } },
dm: {
allowFrom: ["steipete"],
},
},
session: { store: join(home, "sessions.json") }, session: { store: join(home, "sessions.json") },
}; };
@@ -856,11 +852,6 @@ describe("trigger handling", () => {
allowFrom: { discord: [] }, allowFrom: { discord: [] },
}, },
}, },
discord: {
dm: {
allowFrom: ["steipete"],
},
},
session: { store: join(home, "sessions.json") }, session: { store: join(home, "sessions.json") },
}; };

View File

@@ -32,8 +32,14 @@ import {
import { resolveSessionFilePath } from "../config/sessions.js"; import { resolveSessionFilePath } from "../config/sessions.js";
import { logVerbose } from "../globals.js"; import { logVerbose } from "../globals.js";
import { clearCommandLane, getQueueSize } from "../process/command-queue.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 { normalizeMainKey } from "../routing/session-key.js";
import { defaultRuntime } from "../runtime.js"; import { defaultRuntime } from "../runtime.js";
import { INTERNAL_MESSAGE_PROVIDER } from "../utils/message-provider.js";
import { resolveCommandAuthorization } from "./command-auth.js"; import { resolveCommandAuthorization } from "./command-auth.js";
import { hasControlCommand } from "./command-detection.js"; import { hasControlCommand } from "./command-detection.js";
import { import {
@@ -127,53 +133,41 @@ function slugAllowToken(value?: string) {
return text.replace(/-{2,}/g, "-").replace(/^-+|-+$/g, ""); 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) { function stripSenderPrefix(value?: string) {
if (!value) return ""; if (!value) return "";
const trimmed = value.trim(); const trimmed = value.trim();
return trimmed.replace( return trimmed.replace(SENDER_PREFIX_RE, "");
/^(whatsapp|telegram|discord|signal|imessage|webchat|user|group|channel):/i,
"",
);
} }
function resolveElevatedAllowList( function resolveElevatedAllowList(
allowFrom: AgentElevatedAllowFromConfig | undefined, allowFrom: AgentElevatedAllowFromConfig | undefined,
provider: string, provider: string,
discordFallback?: Array<string | number>, fallbackAllowFrom?: Array<string | number>,
): Array<string | number> | undefined { ): Array<string | number> | undefined {
switch (provider) { if (!allowFrom) return fallbackAllowFrom;
case "whatsapp": const value = allowFrom[provider];
return allowFrom?.whatsapp; return Array.isArray(value) ? value : fallbackAllowFrom;
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;
}
} }
function isApprovedElevatedSender(params: { function isApprovedElevatedSender(params: {
provider: string; provider: string;
ctx: MsgContext; ctx: MsgContext;
allowFrom?: AgentElevatedAllowFromConfig; allowFrom?: AgentElevatedAllowFromConfig;
discordFallback?: Array<string | number>; fallbackAllowFrom?: Array<string | number>;
}): boolean { }): boolean {
const rawAllow = resolveElevatedAllowList( const rawAllow = resolveElevatedAllowList(
params.allowFrom, params.allowFrom,
params.provider, params.provider,
params.discordFallback, params.fallbackAllowFrom,
); );
if (!rawAllow || rawAllow.length === 0) return false; if (!rawAllow || rawAllow.length === 0) return false;
@@ -248,23 +242,24 @@ function resolveElevatedPermissions(params: {
return { enabled, allowed: false, failures }; return { enabled, allowed: false, failures };
} }
const discordFallback = const normalizedProvider = normalizeProviderId(params.provider);
params.provider === "discord" const dockFallbackAllowFrom = normalizedProvider
? params.cfg.discord?.dm?.allowFrom ? getProviderDock(normalizedProvider)?.elevated?.allowFromFallback?.({
: undefined; cfg: params.cfg,
accountId: params.ctx.AccountId,
})
: undefined;
const fallbackAllowFrom = dockFallbackAllowFrom;
const globalAllowed = isApprovedElevatedSender({ const globalAllowed = isApprovedElevatedSender({
provider: params.provider, provider: params.provider,
ctx: params.ctx, ctx: params.ctx,
allowFrom: globalConfig?.allowFrom, allowFrom: globalConfig?.allowFrom,
discordFallback, fallbackAllowFrom,
}); });
if (!globalAllowed) { if (!globalAllowed) {
failures.push({ failures.push({
gate: "allowFrom", gate: "allowFrom",
key: key: `tools.elevated.allowFrom.${params.provider}`,
params.provider === "discord" && discordFallback
? "tools.elevated.allowFrom.discord (or discord.dm.allowFrom fallback)"
: `tools.elevated.allowFrom.${params.provider}`,
}); });
return { enabled, allowed: false, failures }; return { enabled, allowed: false, failures };
} }
@@ -274,6 +269,7 @@ function resolveElevatedPermissions(params: {
provider: params.provider, provider: params.provider,
ctx: params.ctx, ctx: params.ctx,
allowFrom: agentConfig.allowFrom, allowFrom: agentConfig.allowFrom,
fallbackAllowFrom,
}) })
: true; : true;
if (!agentAllowed) { if (!agentAllowed) {
@@ -605,7 +601,8 @@ export async function getReplyFromConfig(
agentCfg?.blockStreamingBreak === "message_end" agentCfg?.blockStreamingBreak === "message_end"
? "message_end" ? "message_end"
: "text_end"; : "text_end";
const blockStreamingEnabled = resolvedBlockStreaming === "on"; const blockStreamingEnabled =
resolvedBlockStreaming === "on" && opts?.disableBlockStreaming !== true;
const blockReplyChunking = blockStreamingEnabled const blockReplyChunking = blockStreamingEnabled
? resolveBlockStreamingChunking( ? resolveBlockStreamingChunking(
cfg, cfg,
@@ -782,8 +779,13 @@ export async function getReplyFromConfig(
: undefined; : undefined;
const isEmptyConfig = Object.keys(cfg).length === 0; const isEmptyConfig = Object.keys(cfg).length === 0;
const skipWhenConfigEmpty = command.providerId
? Boolean(
getProviderDock(command.providerId)?.commands?.skipWhenConfigEmpty,
)
: false;
if ( if (
command.isWhatsAppProvider && skipWhenConfigEmpty &&
isEmptyConfig && isEmptyConfig &&
command.from && command.from &&
command.to && command.to &&
@@ -854,6 +856,7 @@ export async function getReplyFromConfig(
); );
const groupIntro = shouldInjectGroupIntro const groupIntro = shouldInjectGroupIntro
? buildGroupIntro({ ? buildGroupIntro({
cfg,
sessionCtx, sessionCtx,
sessionEntry, sessionEntry,
defaultActivation, defaultActivation,

View File

@@ -12,6 +12,7 @@ import {
runEmbeddedPiAgent, runEmbeddedPiAgent,
} from "../../agents/pi-embedded.js"; } from "../../agents/pi-embedded.js";
import { hasNonzeroUsage, type NormalizedUsage } from "../../agents/usage.js"; import { hasNonzeroUsage, type NormalizedUsage } from "../../agents/usage.js";
import type { ClawdbotConfig } from "../../config/config.js";
import { import {
loadSessionStore, loadSessionStore,
resolveSessionTranscriptPath, resolveSessionTranscriptPath,
@@ -26,6 +27,9 @@ import {
registerAgentRunContext, registerAgentRunContext,
} from "../../infra/agent-events.js"; } from "../../infra/agent-events.js";
import { isAudioFileName } from "../../media/mime.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 { defaultRuntime } from "../../runtime.js";
import { import {
estimateUsageCost, 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; const BLOCK_REPLY_SEND_TIMEOUT_MS = 15_000;
/** /**
* Build Slack-specific threading context for tool auto-injection. * Build provider-specific threading context for tool auto-injection.
* Returns undefined values for non-Slack providers.
*/ */
function buildSlackThreadingContext(params: { function buildThreadingToolContext(params: {
sessionCtx: TemplateContext; sessionCtx: TemplateContext;
config: { slack?: { replyToMode?: "off" | "first" | "all" } } | undefined; config: ClawdbotConfig | undefined;
hasRepliedRef: { value: boolean } | undefined; hasRepliedRef: { value: boolean } | undefined;
}): { }): ProviderThreadingToolContext {
currentChannelId: string | undefined;
currentThreadTs: string | undefined;
replyToMode: "off" | "first" | "all" | undefined;
hasRepliedRef: { value: boolean } | undefined;
} {
const { sessionCtx, config, hasRepliedRef } = params; const { sessionCtx, config, hasRepliedRef } = params;
const isSlack = sessionCtx.Provider?.toLowerCase() === "slack"; if (!config) return {};
if (!isSlack) { const provider = normalizeProviderId(sessionCtx.Provider);
return { if (!provider) return {};
currentChannelId: undefined, const dock = getProviderDock(provider);
currentThreadTs: undefined, if (!dock?.threading?.buildToolContext) return {};
replyToMode: undefined, return (
hasRepliedRef: undefined, dock.threading.buildToolContext({
}; cfg: config,
} accountId: sessionCtx.AccountId,
context: {
// If we're already inside a thread, never jump replies out of it (even in Provider: sessionCtx.Provider,
// replyToMode="off"/"first"). This keeps tool calls consistent with the To: sessionCtx.To,
// auto-reply path. ReplyToId: sessionCtx.ReplyToId,
const configuredReplyToMode = config?.slack?.replyToMode ?? "off"; ThreadLabel: sessionCtx.ThreadLabel,
const effectiveReplyToMode = sessionCtx.ThreadLabel },
? ("all" as const) hasRepliedRef,
: 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,
};
} }
const isBunFetchSocketError = (message?: string) => const isBunFetchSocketError = (message?: string) =>
@@ -282,6 +271,7 @@ export async function runReplyAgent(params: {
const replyToMode = resolveReplyToMode( const replyToMode = resolveReplyToMode(
followupRun.run.config, followupRun.run.config,
replyToChannel, replyToChannel,
sessionCtx.AccountId,
); );
const applyReplyToMode = createReplyToModeFilterForChannel( const applyReplyToMode = createReplyToModeFilterForChannel(
replyToMode, replyToMode,
@@ -437,8 +427,8 @@ export async function runReplyAgent(params: {
messageProvider: messageProvider:
sessionCtx.Provider?.trim().toLowerCase() || undefined, sessionCtx.Provider?.trim().toLowerCase() || undefined,
agentAccountId: sessionCtx.AccountId, agentAccountId: sessionCtx.AccountId,
// Slack threading context for tool auto-injection // Provider threading context for tool auto-injection
...buildSlackThreadingContext({ ...buildThreadingToolContext({
sessionCtx, sessionCtx,
config: followupRun.run.config, config: followupRun.run.config,
hasRepliedRef: opts?.hasRepliedRef, hasRepliedRef: opts?.hasRepliedRef,

View File

@@ -1,29 +1,17 @@
import type { ClawdbotConfig } from "../../config/config.js"; 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 { normalizeAccountId } from "../../routing/session-key.js";
import { INTERNAL_MESSAGE_PROVIDER } from "../../utils/message-provider.js";
import { resolveTextChunkLimit, type TextChunkProvider } from "../chunk.js"; import { resolveTextChunkLimit, type TextChunkProvider } from "../chunk.js";
const DEFAULT_BLOCK_STREAM_MIN = 800; const DEFAULT_BLOCK_STREAM_MIN = 800;
const DEFAULT_BLOCK_STREAM_MAX = 1200; const DEFAULT_BLOCK_STREAM_MAX = 1200;
const DEFAULT_BLOCK_STREAM_COALESCE_IDLE_MS = 1000; 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>([ const BLOCK_CHUNK_PROVIDERS = new Set<TextChunkProvider>([
"whatsapp", ...PROVIDER_IDS,
"telegram", INTERNAL_MESSAGE_PROVIDER,
"discord",
"slack",
"signal",
"imessage",
"webchat",
"msteams",
]); ]);
function normalizeChunkProvider( function normalizeChunkProvider(
@@ -36,6 +24,29 @@ function normalizeChunkProvider(
: undefined; : 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 = { export type BlockStreamingCoalescing = {
minChars: number; minChars: number;
maxChars: number; maxChars: number;
@@ -53,7 +64,13 @@ export function resolveBlockStreamingChunking(
breakPreference: "paragraph" | "newline" | "sentence"; breakPreference: "paragraph" | "newline" | "sentence";
} { } {
const providerKey = normalizeChunkProvider(provider); 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 chunkCfg = cfg?.agents?.defaults?.blockStreamingChunk;
const maxRequested = Math.max( const maxRequested = Math.max(
1, 1,
@@ -74,39 +91,6 @@ export function resolveBlockStreamingChunking(
return { minChars, maxChars, breakPreference }; 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( export function resolveBlockStreamingCoalescing(
cfg: ClawdbotConfig | undefined, cfg: ClawdbotConfig | undefined,
provider?: string, provider?: string,
@@ -118,54 +102,21 @@ export function resolveBlockStreamingCoalescing(
}, },
): BlockStreamingCoalescing | undefined { ): BlockStreamingCoalescing | undefined {
const providerKey = normalizeChunkProvider(provider); const providerKey = normalizeChunkProvider(provider);
const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId); const providerId = providerKey ? normalizeProviderId(providerKey) : null;
const normalizedAccountId = normalizeAccountId(accountId); const providerChunkLimit = providerId
const providerDefaults = providerKey ? getProviderDock(providerId)?.outbound?.textChunkLimit
? PROVIDER_COALESCE_DEFAULTS[providerKey]
: undefined; : undefined;
const providerCfg = (() => { const textLimit = resolveTextChunkLimit(cfg, providerKey, accountId, {
if (!cfg || !providerKey) return undefined; fallbackLimit: providerChunkLimit,
if (providerKey === "whatsapp") { });
return ( const providerDefaults = providerId
cfg.whatsapp?.accounts?.[normalizedAccountId]?.blockStreamingCoalesce ?? ? getProviderDock(providerId)?.streaming?.blockStreamingCoalesceDefaults
cfg.whatsapp?.blockStreamingCoalesce : undefined;
); const providerCfg = resolveProviderBlockStreamingCoalesce({
} cfg,
if (providerKey === "telegram") { providerKey,
return ( accountId,
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 coalesceCfg = const coalesceCfg =
providerCfg ?? cfg?.agents?.defaults?.blockStreamingCoalesce; providerCfg ?? cfg?.agents?.defaults?.blockStreamingCoalesce;
const minRequested = Math.max( const minRequested = Math.max(

View File

@@ -54,9 +54,9 @@ import {
triggerClawdbotRestart, triggerClawdbotRestart,
} from "../../infra/restart.js"; } from "../../infra/restart.js";
import { enqueueSystemEvent } from "../../infra/system-events.js"; import { enqueueSystemEvent } from "../../infra/system-events.js";
import type { ProviderId } from "../../providers/plugins/types.js";
import { parseAgentSessionKey } from "../../routing/session-key.js"; import { parseAgentSessionKey } from "../../routing/session-key.js";
import { resolveSendPolicy } from "../../sessions/send-policy.js"; import { resolveSendPolicy } from "../../sessions/send-policy.js";
import { normalizeE164 } from "../../utils.js";
import { resolveCommandAuthorization } from "../command-auth.js"; import { resolveCommandAuthorization } from "../command-auth.js";
import { import {
normalizeCommandBody, normalizeCommandBody,
@@ -108,10 +108,10 @@ function resolveSessionEntryForKey(
export type CommandContext = { export type CommandContext = {
surface: string; surface: string;
provider: string; provider: string;
isWhatsAppProvider: boolean; providerId?: ProviderId;
ownerList: string[]; ownerList: string[];
isAuthorizedSender: boolean; isAuthorizedSender: boolean;
senderE164?: string; senderId?: string;
abortKey?: string; abortKey?: string;
rawBodyNormalized: string; rawBodyNormalized: string;
commandBodyNormalized: string; commandBodyNormalized: string;
@@ -155,7 +155,7 @@ export async function buildStatusReply(params: {
} = params; } = params;
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /status from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /status from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return undefined; return undefined;
} }
@@ -359,10 +359,10 @@ export function buildCommandContext(params: {
return { return {
surface, surface,
provider, provider,
isWhatsAppProvider: auth.isWhatsAppProvider, providerId: auth.providerId,
ownerList: auth.ownerList, ownerList: auth.ownerList,
isAuthorizedSender: auth.isAuthorizedSender, isAuthorizedSender: auth.isAuthorizedSender,
senderE164: auth.senderE164, senderId: auth.senderId,
abortKey, abortKey,
rawBodyNormalized, rawBodyNormalized,
commandBodyNormalized, commandBodyNormalized,
@@ -448,7 +448,7 @@ export async function handleCommands(params: {
command.commandBodyNormalized === "/new"; command.commandBodyNormalized === "/new";
if (resetRequested && !command.isAuthorizedSender) { if (resetRequested && !command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /reset from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /reset from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -472,22 +472,9 @@ export async function handleCommands(params: {
reply: { text: "⚙️ Group activation only applies to group chats." }, reply: { text: "⚙️ Group activation only applies to group chats." },
}; };
} }
const activationOwnerList = command.ownerList; if (!command.isAuthorizedSender) {
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)
) {
logVerbose( logVerbose(
`Ignoring /activation from unauthorized sender in group: ${command.senderE164 || "<unknown>"}`, `Ignoring /activation from unauthorized sender in group: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -515,7 +502,7 @@ export async function handleCommands(params: {
if (allowTextCommands && sendPolicyCommand.hasCommand) { if (allowTextCommands && sendPolicyCommand.hasCommand) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /send from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /send from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -552,7 +539,7 @@ export async function handleCommands(params: {
if (allowTextCommands && command.commandBodyNormalized === "/restart") { if (allowTextCommands && command.commandBodyNormalized === "/restart") {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /restart from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /restart from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -598,7 +585,7 @@ export async function handleCommands(params: {
if (allowTextCommands && helpRequested) { if (allowTextCommands && helpRequested) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /help from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /help from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -609,7 +596,7 @@ export async function handleCommands(params: {
if (allowTextCommands && commandsRequested) { if (allowTextCommands && commandsRequested) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /commands from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /commands from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -673,7 +660,7 @@ export async function handleCommands(params: {
if (configCommand) { if (configCommand) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /config from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /config from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -805,7 +792,7 @@ export async function handleCommands(params: {
if (debugCommand) { if (debugCommand) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /debug from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /debug from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -832,13 +819,11 @@ export async function handleCommands(params: {
reply: { text: "⚙️ Debug overrides: (none)" }, reply: { text: "⚙️ Debug overrides: (none)" },
}; };
} }
const effectiveConfig = cfg ?? {};
const json = JSON.stringify(overrides, null, 2); const json = JSON.stringify(overrides, null, 2);
const effectiveJson = JSON.stringify(effectiveConfig, null, 2);
return { return {
shouldContinue: false, shouldContinue: false,
reply: { 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 (allowTextCommands && stopRequested) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /stop from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /stop from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }
@@ -927,7 +912,7 @@ export async function handleCommands(params: {
if (compactRequested) { if (compactRequested) {
if (!command.isAuthorizedSender) { if (!command.isAuthorizedSender) {
logVerbose( logVerbose(
`Ignoring /compact from unauthorized sender: ${command.senderE164 || "<unknown>"}`, `Ignoring /compact from unauthorized sender: ${command.senderId || "<unknown>"}`,
); );
return { shouldContinue: false }; return { shouldContinue: false };
} }

View File

@@ -198,7 +198,11 @@ export function createFollowupRunner(params: {
(queued.run.messageProvider?.toLowerCase() as (queued.run.messageProvider?.toLowerCase() as
| OriginatingChannelType | OriginatingChannelType
| undefined); | undefined);
const replyToMode = resolveReplyToMode(queued.run.config, replyToChannel); const replyToMode = resolveReplyToMode(
queued.run.config,
replyToChannel,
queued.originatingAccountId,
);
const replyTaggedPayloads: ReplyPayload[] = applyReplyThreading({ const replyTaggedPayloads: ReplyPayload[] = applyReplyThreading({
payloads: sanitizedPayloads, payloads: sanitizedPayloads,

View File

@@ -1,181 +1,39 @@
import type { ClawdbotConfig } from "../../config/config.js"; import type { ClawdbotConfig } from "../../config/config.js";
import { resolveProviderGroupRequireMention } from "../../config/group-policy.js";
import type { import type {
GroupKeyResolution, GroupKeyResolution,
SessionEntry, SessionEntry,
} from "../../config/sessions.js"; } 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 { normalizeGroupActivation } from "../group-activation.js";
import type { TemplateContext } from "../templating.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: { export function resolveGroupRequireMention(params: {
cfg: ClawdbotConfig; cfg: ClawdbotConfig;
ctx: TemplateContext; ctx: TemplateContext;
groupResolution?: GroupKeyResolution; groupResolution?: GroupKeyResolution;
}): boolean { }): boolean {
const { cfg, ctx, groupResolution } = params; const { cfg, ctx, groupResolution } = params;
const provider = const rawProvider = groupResolution?.provider ?? ctx.Provider?.trim();
groupResolution?.provider ?? ctx.Provider?.trim().toLowerCase(); const provider = normalizeProviderId(rawProvider);
if (!provider) return true;
const groupId = groupResolution?.id ?? ctx.From?.replace(/^group:/, ""); const groupId = groupResolution?.id ?? ctx.From?.replace(/^group:/, "");
const groupRoom = ctx.GroupRoom?.trim() ?? ctx.GroupSubject?.trim(); const groupRoom = ctx.GroupRoom?.trim() ?? ctx.GroupSubject?.trim();
const groupSpace = ctx.GroupSpace?.trim(); const groupSpace = ctx.GroupSpace?.trim();
if (provider === "telegram") { const requireMention = getProviderDock(
const { chatId, topicId } = parseTelegramGroupId(groupId); provider,
const requireMention = resolveTelegramRequireMention({ )?.groups?.resolveRequireMention?.({
cfg, cfg,
chatId, groupId,
topicId, groupRoom,
}); groupSpace,
if (typeof requireMention === "boolean") return requireMention; accountId: ctx.AccountId,
return resolveProviderGroupRequireMention({ });
cfg, if (typeof requireMention === "boolean") return requireMention;
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;
}
return true; return true;
} }
@@ -186,6 +44,7 @@ export function defaultGroupActivation(
} }
export function buildGroupIntro(params: { export function buildGroupIntro(params: {
cfg: ClawdbotConfig;
sessionCtx: TemplateContext; sessionCtx: TemplateContext;
sessionEntry?: SessionEntry; sessionEntry?: SessionEntry;
defaultActivation: "always" | "mention"; defaultActivation: "always" | "mention";
@@ -196,14 +55,14 @@ export function buildGroupIntro(params: {
params.defaultActivation; params.defaultActivation;
const subject = params.sessionCtx.GroupSubject?.trim(); const subject = params.sessionCtx.GroupSubject?.trim();
const members = params.sessionCtx.GroupMembers?.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 = (() => { const providerLabel = (() => {
if (!provider) return "chat"; if (!providerKey) return "chat";
if (provider === "whatsapp") return "WhatsApp"; if (isInternalMessageProvider(providerKey)) return "WebChat";
if (provider === "telegram") return "Telegram"; if (providerId) return getChatProviderMeta(providerId).label;
if (provider === "discord") return "Discord"; return `${providerKey.at(0)?.toUpperCase() ?? ""}${providerKey.slice(1)}`;
if (provider === "webchat") return "WebChat";
return `${provider.at(0)?.toUpperCase() ?? ""}${provider.slice(1)}`;
})(); })();
const subjectLine = subject const subjectLine = subject
? `You are replying inside the ${providerLabel} group "${subject}".` ? `You are replying inside the ${providerLabel} group "${subject}".`
@@ -213,10 +72,18 @@ export function buildGroupIntro(params: {
activation === "always" activation === "always"
? "Activation: always-on (you receive every group message)." ? "Activation: always-on (you receive every group message)."
: "Activation: trigger-only (you are invoked only when explicitly mentioned; recent context may be included)."; : "Activation: trigger-only (you are invoked only when explicitly mentioned; recent context may be included).";
const whatsappIdsLine = const groupId = params.sessionCtx.From?.replace(/^group:/, "");
provider === "whatsapp" const groupRoom = params.sessionCtx.GroupRoom?.trim() ?? subject;
? "WhatsApp IDs: SenderId is the participant JID; [message_id: ...] is the message id for reactions (use SenderId as participant)." const groupSpace = params.sessionCtx.GroupSpace?.trim();
: undefined; const providerIdsLine = providerId
? getProviderDock(providerId)?.groups?.resolveGroupIntroHint?.({
cfg: params.cfg,
groupId,
groupRoom,
groupSpace,
accountId: params.sessionCtx.AccountId,
})
: undefined;
const silenceLine = const silenceLine =
activation === "always" 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.` ? `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, subjectLine,
membersLine, membersLine,
activationLine, activationLine,
whatsappIdsLine, providerIdsLine,
silenceLine, silenceLine,
cautionLine, cautionLine,
lurkLine, lurkLine,

View File

@@ -1,5 +1,7 @@
import { resolveAgentConfig } from "../../agents/agent-scope.js"; import { resolveAgentConfig } from "../../agents/agent-scope.js";
import type { ClawdbotConfig } from "../../config/config.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"; import type { MsgContext } from "../templating.js";
function escapeRegExp(text: string): string { function escapeRegExp(text: string): string {
@@ -112,9 +114,14 @@ export function stripMentions(
agentId?: string, agentId?: string,
): string { ): string {
let result = text; let result = text;
const rawPatterns = resolveMentionPatterns(cfg, agentId); const providerId = ctx.Provider ? normalizeProviderId(ctx.Provider) : null;
const patterns = normalizeMentionPatterns(rawPatterns); const providerMentions = providerId
? getProviderDock(providerId)?.mentions
: undefined;
const patterns = normalizeMentionPatterns([
...resolveMentionPatterns(cfg, agentId),
...(providerMentions?.stripPatterns?.({ ctx, cfg, agentId }) ?? []),
]);
for (const p of patterns) { for (const p of patterns) {
try { try {
const re = new RegExp(p, "gi"); const re = new RegExp(p, "gi");
@@ -123,16 +130,15 @@ export function stripMentions(
// ignore invalid regex // ignore invalid regex
} }
} }
const selfE164 = (ctx.To ?? "").replace(/^whatsapp:/, ""); if (providerMentions?.stripMentions) {
if (selfE164) { result = providerMentions.stripMentions({
const esc = selfE164.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); text: result,
result = result ctx,
.replace(new RegExp(esc, "gi"), " ") cfg,
.replace(new RegExp(`@${esc}`, "gi"), " "); agentId,
});
} }
// Generic mention patterns like @123456789 or plain digits // Generic mention patterns like @123456789 or plain digits
result = result.replace(/@[0-9+]{5,}/g, " "); result = result.replace(/@[0-9+]{5,}/g, " ");
// Discord-style mentions (<@123> or <@!123>)
result = result.replace(/<@!?\d+>/g, " ");
return result.replace(/\s+/g, " ").trim(); return result.replace(/\s+/g, " ").trim();
} }

View File

@@ -568,14 +568,7 @@ export function scheduleFollowupDrain(
} }
})(); })();
} }
function defaultQueueModeForProvider(provider?: string): QueueMode { 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";
return "collect"; return "collect";
} }
export function resolveQueueSettings(params: { export function resolveQueueSettings(params: {

View File

@@ -1,22 +1,22 @@
import type { ClawdbotConfig } from "../../config/config.js"; import type { ClawdbotConfig } from "../../config/config.js";
import type { ReplyToMode } from "../../config/types.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 { OriginatingChannelType } from "../templating.js";
import type { ReplyPayload } from "../types.js"; import type { ReplyPayload } from "../types.js";
export function resolveReplyToMode( export function resolveReplyToMode(
cfg: ClawdbotConfig, cfg: ClawdbotConfig,
channel?: OriginatingChannelType, channel?: OriginatingChannelType,
accountId?: string | null,
): ReplyToMode { ): ReplyToMode {
switch (channel) { const provider = normalizeProviderId(channel);
case "telegram": if (!provider) return "all";
return cfg.telegram?.replyToMode ?? "first"; const resolved = getProviderDock(provider)?.threading?.resolveReplyToMode?.({
case "discord": cfg,
return cfg.discord?.replyToMode ?? "off"; accountId,
case "slack": });
return cfg.slack?.replyToMode ?? "off"; return resolved ?? "all";
default:
return "all";
}
} }
export function createReplyToModeFilter( export function createReplyToModeFilter(
@@ -43,7 +43,11 @@ export function createReplyToModeFilterForChannel(
mode: ReplyToMode, mode: ReplyToMode,
channel?: OriginatingChannelType, channel?: OriginatingChannelType,
) { ) {
const provider = normalizeProviderId(channel);
const allowTagsWhenOff = provider
? Boolean(getProviderDock(provider)?.threading?.allowTagsWhenOff)
: false;
return createReplyToModeFilter(mode, { return createReplyToModeFilter(mode, {
allowTagsWhenOff: channel === "slack", allowTagsWhenOff,
}); });
} }

View File

@@ -236,11 +236,12 @@ describe("routeReply", () => {
to: "conversation:19:abc@thread.tacv2", to: "conversation:19:abc@thread.tacv2",
cfg, cfg,
}); });
expect(mocks.sendMessageMSTeams).toHaveBeenCalledWith({ expect(mocks.sendMessageMSTeams).toHaveBeenCalledWith(
cfg, expect.objectContaining({
to: "conversation:19:abc@thread.tacv2", cfg,
text: "hi", to: "conversation:19:abc@thread.tacv2",
mediaUrl: undefined, text: "hi",
}); }),
);
}); });
}); });

View File

@@ -10,13 +10,8 @@
import { resolveSessionAgentId } from "../../agents/agent-scope.js"; import { resolveSessionAgentId } from "../../agents/agent-scope.js";
import { resolveEffectiveMessagesConfig } from "../../agents/identity.js"; import { resolveEffectiveMessagesConfig } from "../../agents/identity.js";
import type { ClawdbotConfig } from "../../config/config.js"; import type { ClawdbotConfig } from "../../config/config.js";
import { sendMessageDiscord } from "../../discord/send.js"; import { normalizeProviderId } from "../../providers/registry.js";
import { sendMessageIMessage } from "../../imessage/send.js"; import { INTERNAL_MESSAGE_PROVIDER } from "../../utils/message-provider.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 type { OriginatingChannelType } from "../templating.js"; import type { OriginatingChannelType } from "../templating.js";
import type { ReplyPayload } from "../types.js"; import type { ReplyPayload } from "../types.js";
import { normalizeReplyPayload } from "./normalize-reply.js"; import { normalizeReplyPayload } from "./normalize-reply.js";
@@ -93,118 +88,39 @@ export async function routeReply(
return { ok: true }; return { ok: true };
} }
const sendOne = async (params: { if (channel === INTERNAL_MESSAGE_PROVIDER) {
text: string; return {
mediaUrl?: string; ok: false,
}): Promise<RouteReplyResult> => { error: "Webchat routing not supported for queued replies",
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 };
}
case "slack": { const provider = normalizeProviderId(channel) ?? null;
const result = await sendMessageSlack(to, text, { if (!provider) {
mediaUrl, return { ok: false, error: `Unknown channel: ${String(channel)}` };
threadTs: replyToId, }
accountId, if (abortSignal?.aborted) {
}); return { ok: false, error: "Reply routing aborted" };
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)}` };
}
}
};
try { try {
if (abortSignal?.aborted) { // Provider docking: this is an execution boundary (we're about to send).
return { ok: false, error: "Reply routing aborted" }; // Keep the module cheap to import by loading outbound plumbing lazily.
} const { deliverOutboundPayloads } = await import(
if (mediaUrls.length === 0) { "../../infra/outbound/deliver.js"
return await sendOne({ text }); );
} const results = await deliverOutboundPayloads({
cfg,
let last: RouteReplyResult | undefined; provider,
for (let i = 0; i < mediaUrls.length; i++) { to,
if (abortSignal?.aborted) { accountId: accountId ?? undefined,
return { ok: false, error: "Reply routing aborted" }; payloads: [normalized],
} replyToId: replyToId ?? null,
const mediaUrl = mediaUrls[i]; threadId: threadId ?? null,
const caption = i === 0 ? text : ""; abortSignal,
last = await sendOne({ text: caption, mediaUrl }); });
if (!last.ok) return last; const last = results.at(-1);
} return { ok: true, messageId: last?.messageId };
return last ?? { ok: true };
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : String(err); const message = err instanceof Error ? err.message : String(err);
return { return {
@@ -222,22 +138,10 @@ export async function routeReply(
*/ */
export function isRoutableChannel( export function isRoutableChannel(
channel: OriginatingChannelType | undefined, channel: OriginatingChannelType | undefined,
): channel is ): channel is Exclude<
| "telegram" OriginatingChannelType,
| "slack" typeof INTERNAL_MESSAGE_PROVIDER
| "discord" > {
| "signal" if (!channel || channel === INTERNAL_MESSAGE_PROVIDER) return false;
| "imessage" return normalizeProviderId(channel) !== null;
| "whatsapp"
| "msteams" {
if (!channel) return false;
return [
"telegram",
"slack",
"discord",
"signal",
"imessage",
"whatsapp",
"msteams",
].includes(channel);
} }

View File

@@ -23,6 +23,8 @@ import {
type SessionScope, type SessionScope,
saveSessionStore, saveSessionStore,
} from "../../config/sessions.js"; } from "../../config/sessions.js";
import { getProviderDock } from "../../providers/dock.js";
import { normalizeProviderId } from "../../providers/registry.js";
import { normalizeMainKey } from "../../routing/session-key.js"; import { normalizeMainKey } from "../../routing/session-key.js";
import { resolveCommandAuthorization } from "../command-auth.js"; import { resolveCommandAuthorization } from "../command-auth.js";
import type { MsgContext, TemplateContext } from "../templating.js"; import type { MsgContext, TemplateContext } from "../templating.js";
@@ -236,7 +238,13 @@ export async function initSessionState(params: {
const subject = ctx.GroupSubject?.trim(); const subject = ctx.GroupSubject?.trim();
const space = ctx.GroupSpace?.trim(); const space = ctx.GroupSpace?.trim();
const explicitRoom = ctx.GroupRoom?.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 = const nextRoom =
explicitRoom ?? explicitRoom ??
(isRoomProvider && subject && subject.startsWith("#") (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. */ /** Valid provider channels for message routing. */
export type OriginatingChannelType = export type OriginatingChannelType = ProviderId | InternalMessageProvider;
| "telegram"
| "slack"
| "discord"
| "signal"
| "imessage"
| "whatsapp"
| "webchat"
| "msteams";
export type MsgContext = { export type MsgContext = {
Body?: string; Body?: string;
@@ -50,7 +45,7 @@ export type MsgContext = {
SenderUsername?: string; SenderUsername?: string;
SenderTag?: string; SenderTag?: string;
SenderE164?: string; SenderE164?: string;
/** Provider label (whatsapp|telegram|discord|imessage|...). */ /** Provider label (e.g. whatsapp, telegram). */
Provider?: string; Provider?: string;
/** Provider surface label (e.g. discord, slack). Prefer this over `Provider` when available. */ /** Provider surface label (e.g. discord, slack). Prefer this over `Provider` when available. */
Surface?: string; Surface?: string;

View File

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

View File

@@ -50,6 +50,10 @@ import { getResolvedLoggerSettings } from "../logging.js";
import { defaultRuntime } from "../runtime.js"; import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js"; import { formatDocsLink } from "../terminal/links.js";
import { colorize, isRich, theme } from "../terminal/theme.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 { createDefaultDeps } from "./deps.js";
import { withProgress } from "./progress.js"; import { withProgress } from "./progress.js";
@@ -236,8 +240,8 @@ async function probeGatewayStatus(opts: {
password: opts.password, password: opts.password,
method: "status", method: "status",
timeoutMs: opts.timeoutMs, timeoutMs: opts.timeoutMs,
clientName: "cli", clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: "cli", mode: GATEWAY_CLIENT_MODES.CLI,
...(opts.configPath ? { configPath: opts.configPath } : {}), ...(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 { sendMessageDiscord } from "../discord/send.js";
import { sendMessageIMessage } from "../imessage/send.js"; import { sendMessageIMessage } from "../imessage/send.js";
import type { OutboundSendDeps } from "../infra/outbound/deliver.js";
import { sendMessageMSTeams } from "../msteams/send.js"; import { sendMessageMSTeams } from "../msteams/send.js";
import { logWebSelfId, sendMessageWhatsApp } from "../providers/web/index.js"; import { logWebSelfId, sendMessageWhatsApp } from "../providers/web/index.js";
import { sendMessageSignal } from "../signal/send.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 }; export { logWebSelfId };

View File

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

View File

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

View File

@@ -1,5 +1,9 @@
import type { Command } from "commander"; import type { Command } from "commander";
import { callGateway } from "../gateway/call.js"; import { callGateway } from "../gateway/call.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { withProgress } from "./progress.js"; import { withProgress } from "./progress.js";
export type GatewayRpcOpts = { export type GatewayRpcOpts = {
@@ -41,8 +45,8 @@ export async function callGatewayFromCli(
params, params,
expectFinal: extra?.expectFinal ?? Boolean(opts.expectFinal), expectFinal: extra?.expectFinal ?? Boolean(opts.expectFinal),
timeoutMs: Number(opts.timeout ?? 10_000), timeoutMs: Number(opts.timeout ?? 10_000),
clientName: "cli", clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: "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 { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js"; import { formatDocsLink } from "../terminal/links.js";
import { theme } from "../terminal/theme.js"; import { theme } from "../terminal/theme.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
import { import {
type CameraFacing, type CameraFacing,
cameraTempPath, cameraTempPath,
@@ -152,8 +156,8 @@ const callGatewayCli = async (
method, method,
params, params,
timeoutMs: Number(opts.timeout ?? 10_000), timeoutMs: Number(opts.timeout ?? 10_000),
clientName: "cli", clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: "cli", mode: GATEWAY_CLIENT_MODES.CLI,
}), }),
); );

View File

@@ -3,40 +3,33 @@ import { describe, expect, it, vi } from "vitest";
const listProviderPairingRequests = vi.fn(); const listProviderPairingRequests = vi.fn();
const approveProviderPairingCode = 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", () => ({ vi.mock("../pairing/pairing-store.js", () => ({
listProviderPairingRequests, listProviderPairingRequests,
approveProviderPairingCode, approveProviderPairingCode,
})); }));
vi.mock("../telegram/send.js", () => ({ vi.mock("../providers/plugins/pairing.js", () => ({
sendMessageTelegram: vi.fn(), listPairingProviders,
})); resolvePairingProvider,
notifyPairingApproved,
vi.mock("../discord/send.js", () => ({ requirePairingAdapter,
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("../config/config.js", () => ({ vi.mock("../config/config.js", () => ({
loadConfig: vi.fn().mockReturnValue({}), loadConfig: vi.fn().mockReturnValue({}),
})); }));
vi.mock("../telegram/token.js", () => ({
resolveTelegramToken: vi.fn().mockReturnValue({ token: "t" }),
}));
describe("pairing cli", () => { describe("pairing cli", () => {
it("labels Telegram ids as telegramUserId", async () => { it("labels Telegram ids as telegramUserId", async () => {
const { registerPairingCli } = await import("./pairing-cli.js"); const { registerPairingCli } = await import("./pairing-cli.js");

View File

@@ -1,78 +1,27 @@
import type { Command } from "commander"; import type { Command } from "commander";
import { loadConfig } from "../config/config.js"; import { loadConfig } from "../config/config.js";
import { sendMessageDiscord } from "../discord/send.js"; import { resolvePairingIdLabel } from "../pairing/pairing-labels.js";
import { sendMessageIMessage } from "../imessage/send.js";
import { sendMessageMSTeams } from "../msteams/send.js";
import { PROVIDER_ID_LABELS } from "../pairing/pairing-labels.js";
import { import {
approveProviderPairingCode, approveProviderPairingCode,
listProviderPairingRequests, listProviderPairingRequests,
type PairingProvider, type PairingProvider,
} from "../pairing/pairing-store.js"; } from "../pairing/pairing-store.js";
import { sendMessageSignal } from "../signal/send.js"; import {
import { sendMessageSlack } from "../slack/send.js"; listPairingProviders,
import { sendMessageTelegram } from "../telegram/send.js"; notifyPairingApproved,
import { resolveTelegramToken } from "../telegram/token.js"; resolvePairingProvider,
} from "../providers/plugins/pairing.js";
const PROVIDERS: PairingProvider[] = [ const PROVIDERS: PairingProvider[] = listPairingProviders();
"telegram",
"signal",
"imessage",
"discord",
"slack",
"whatsapp",
"msteams",
];
function parseProvider(raw: unknown): PairingProvider { function parseProvider(raw: unknown): PairingProvider {
const value = ( return resolvePairingProvider(raw);
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(", ")})`,
);
} }
async function notifyApproved(provider: PairingProvider, id: string) { async function notifyApproved(provider: PairingProvider, id: string) {
const message = const cfg = loadConfig();
"✅ Clawdbot access approved. Send a message to start chatting."; await notifyPairingApproved({ providerId: provider, id, cfg });
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.
} }
export function registerPairingCli(program: Command) { export function registerPairingCli(program: Command) {
@@ -105,7 +54,7 @@ export function registerPairingCli(program: Command) {
} }
for (const r of requests) { for (const r of requests) {
const meta = r.meta ? JSON.stringify(r.meta) : ""; const meta = r.meta ? JSON.stringify(r.meta) : "";
const idLabel = PROVIDER_ID_LABELS[provider]; const idLabel = resolvePairingIdLabel(provider);
console.log( console.log(
`${r.code} ${idLabel}=${r.id}${meta ? ` meta=${meta}` : ""} ${r.createdAt}`, `${r.code} ${idLabel}=${r.id}${meta ? ` meta=${meta}` : ""} ${r.createdAt}`,
); );

View File

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

View File

@@ -1,8 +1,12 @@
import { loadConfig } from "../config/config.js"; import { loadConfig } from "../config/config.js";
import { setVerbose } from "../globals.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 { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import { resolveWhatsAppAccount } from "../web/accounts.js";
type ProviderAuthOptions = { type ProviderAuthOptions = {
provider?: string; provider?: string;
@@ -10,44 +14,55 @@ type ProviderAuthOptions = {
verbose?: boolean; 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( export async function runProviderLogin(
opts: ProviderAuthOptions, opts: ProviderAuthOptions,
runtime: RuntimeEnv = defaultRuntime, 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. // Auth-only flow: do not mutate provider config here.
setVerbose(Boolean(opts.verbose)); setVerbose(Boolean(opts.verbose));
await loginWeb( const cfg = loadConfig();
Boolean(opts.verbose), const accountId =
provider, opts.account?.trim() || resolveProviderDefaultAccountId({ plugin, cfg });
undefined, await plugin.auth.login({
cfg,
accountId,
runtime, runtime,
opts.account, verbose: Boolean(opts.verbose),
); providerInput,
});
} }
export async function runProviderLogout( export async function runProviderLogout(
opts: ProviderAuthOptions, opts: ProviderAuthOptions,
runtime: RuntimeEnv = defaultRuntime, 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. // Auth-only flow: resolve account + clear session state only.
const cfg = loadConfig(); 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, cfg,
accountId: opts.account, accountId,
}); account,
await logoutWeb({
runtime, runtime,
authDir: account.authDir,
isLegacyAuthDir: account.isLegacyAuthDir,
}); });
} }

View File

@@ -169,9 +169,9 @@ export function registerProvidersCli(program: Command) {
providers providers
.command("logout") .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("--provider <provider>", "Provider alias (default: whatsapp)")
.option("--account <id>", "WhatsApp account id (accountId)") .option("--account <id>", "Account id (accountId)")
.action(async (opts) => { .action(async (opts) => {
try { try {
await runProviderLogout( await runProviderLogout(

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -28,7 +28,15 @@ const probeGateway = vi.fn(async ({ url }: { url: string }) => {
error: null, error: null,
close: null, close: null,
health: { ok: true }, health: { ok: true },
status: { web: { linked: false }, sessions: { count: 0 } }, status: {
linkProvider: {
id: "whatsapp",
label: "WhatsApp",
linked: false,
authAgeMs: null,
},
sessions: { count: 0 },
},
presence: [ presence: [
{ mode: "gateway", reason: "self", host: "local", ip: "127.0.0.1" }, { 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, error: null,
close: null, close: null,
health: { ok: true }, 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: [ presence: [
{ mode: "gateway", reason: "self", host: "remote", ip: "100.64.0.2" }, { 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), callGateway: (...args: unknown[]) => callGatewayMock(...args),
})); }));
vi.mock("../web/session.js", () => ({ vi.mock("../web/auth-store.js", () => ({
webAuthExists: vi.fn(async () => true), webAuthExists: vi.fn(async () => true),
getWebAuthAgeMs: vi.fn(() => 0), getWebAuthAgeMs: vi.fn(() => 0),
logWebSelfId: (...args: unknown[]) => logWebSelfIdMock(...args), logWebSelfId: (...args: unknown[]) => logWebSelfIdMock(...args),
@@ -32,22 +32,29 @@ describe("healthCommand (coverage)", () => {
ok: true, ok: true,
ts: Date.now(), ts: Date.now(),
durationMs: 5, durationMs: 5,
web: { providers: {
linked: true, whatsapp: {
authAgeMs: 5 * 60_000, linked: true,
connect: { ok: true, status: 200, elapsedMs: 10 }, authAgeMs: 5 * 60_000,
}, },
telegram: { telegram: {
configured: true, configured: true,
probe: { probe: {
ok: true, ok: true,
elapsedMs: 7, elapsedMs: 7,
bot: { username: "bot" }, bot: { username: "bot" },
webhook: { url: "https://example.com/h" }, webhook: { url: "https://example.com/h" },
},
},
discord: {
configured: false,
}, },
}, },
discord: { providerOrder: ["whatsapp", "telegram", "discord"],
configured: false, providerLabels: {
whatsapp: "WhatsApp",
telegram: "Telegram",
discord: "Discord",
}, },
heartbeatSeconds: 60, heartbeatSeconds: 60,
sessions: { sessions: {
@@ -64,7 +71,7 @@ describe("healthCommand (coverage)", () => {
expect(runtime.exit).not.toHaveBeenCalled(); expect(runtime.exit).not.toHaveBeenCalled();
expect(runtime.log.mock.calls.map((c) => String(c[0])).join("\n")).toMatch( expect(runtime.log.mock.calls.map((c) => String(c[0])).join("\n")).toMatch(
/Web: linked/i, /WhatsApp: linked/i,
); );
expect(logWebSelfIdMock).toHaveBeenCalled(); expect(logWebSelfIdMock).toHaveBeenCalled();
}); });

View File

@@ -23,9 +23,10 @@ vi.mock("../config/sessions.js", () => ({
loadSessionStore: () => testStore, loadSessionStore: () => testStore,
})); }));
vi.mock("../web/session.js", () => ({ vi.mock("../web/auth-store.js", () => ({
webAuthExists: vi.fn(async () => true), webAuthExists: vi.fn(async () => true),
getWebAuthAgeMs: vi.fn(() => 1234), getWebAuthAgeMs: vi.fn(() => 1234),
readWebSelfId: vi.fn(() => ({ e164: null, jid: null })),
logWebSelfId: vi.fn(), logWebSelfId: vi.fn(),
})); }));
@@ -49,10 +50,16 @@ describe("getHealthSnapshot", () => {
}; };
vi.stubEnv("TELEGRAM_BOT_TOKEN", ""); vi.stubEnv("TELEGRAM_BOT_TOKEN", "");
vi.stubEnv("DISCORD_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.ok).toBe(true);
expect(snap.telegram.configured).toBe(false); const telegram = snap.providers.telegram as {
expect(snap.telegram.probe).toBeUndefined(); configured?: boolean;
probe?: unknown;
};
expect(telegram.configured).toBe(false);
expect(telegram.probe).toBeUndefined();
expect(snap.sessions.count).toBe(2); expect(snap.sessions.count).toBe(2);
expect(snap.sessions.recent[0]?.key).toBe("foo"); expect(snap.sessions.recent[0]?.key).toBe("foo");
}); });
@@ -98,11 +105,19 @@ describe("getHealthSnapshot", () => {
}), }),
); );
const snap = await getHealthSnapshot(25); const snap = await getHealthSnapshot({ timeoutMs: 25 });
expect(snap.telegram.configured).toBe(true); const telegram = snap.providers.telegram as {
expect(snap.telegram.probe?.ok).toBe(true); configured?: boolean;
expect(snap.telegram.probe?.bot?.username).toBe("bot"); probe?: {
expect(snap.telegram.probe?.webhook?.url).toMatch(/^https:/); 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("/getMe"))).toBe(true);
expect(calls.some((c) => c.includes("/getWebhookInfo"))).toBe(true); expect(calls.some((c) => c.includes("/getWebhookInfo"))).toBe(true);
}); });
@@ -151,9 +166,13 @@ describe("getHealthSnapshot", () => {
}), }),
); );
const snap = await getHealthSnapshot(25); const snap = await getHealthSnapshot({ timeoutMs: 25 });
expect(snap.telegram.configured).toBe(true); const telegram = snap.providers.telegram as {
expect(snap.telegram.probe?.ok).toBe(true); 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); expect(calls.some((c) => c.includes("bott-file/getMe"))).toBe(true);
fs.rmSync(tmpDir, { recursive: true, force: true }); fs.rmSync(tmpDir, { recursive: true, force: true });
@@ -178,11 +197,15 @@ describe("getHealthSnapshot", () => {
}), }),
); );
const snap = await getHealthSnapshot(25); const snap = await getHealthSnapshot({ timeoutMs: 25 });
expect(snap.telegram.configured).toBe(true); const telegram = snap.providers.telegram as {
expect(snap.telegram.probe?.ok).toBe(false); configured?: boolean;
expect(snap.telegram.probe?.status).toBe(401); probe?: { ok?: boolean; status?: number; error?: string };
expect(snap.telegram.probe?.error).toMatch(/unauthorized/i); };
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 () => { it("captures unexpected probe exceptions as errors", async () => {
@@ -197,9 +220,13 @@ describe("getHealthSnapshot", () => {
}), }),
); );
const snap = await getHealthSnapshot(25); const snap = await getHealthSnapshot({ timeoutMs: 25 });
expect(snap.telegram.configured).toBe(true); const telegram = snap.providers.telegram as {
expect(snap.telegram.probe?.ok).toBe(false); configured?: boolean;
expect(snap.telegram.probe?.error).toMatch(/network down/i); 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 () => { it("outputs JSON from gateway", async () => {
const snapshot: HealthSummary = { const snapshot: HealthSummary = {
ok: true,
ts: Date.now(), ts: Date.now(),
durationMs: 5, durationMs: 5,
web: { providers: {
linked: true, whatsapp: { linked: true, authAgeMs: 5000 },
authAgeMs: 5000, telegram: { configured: true, probe: { ok: true, elapsedMs: 1 } },
connect: { ok: true, elapsedMs: 10 }, 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, heartbeatSeconds: 60,
sessions: { sessions: {
path: "/tmp/sessions.json", path: "/tmp/sessions.json",
@@ -44,18 +49,27 @@ describe("healthCommand", () => {
expect(runtime.exit).not.toHaveBeenCalled(); expect(runtime.exit).not.toHaveBeenCalled();
const logged = runtime.log.mock.calls[0]?.[0] as string; const logged = runtime.log.mock.calls[0]?.[0] as string;
const parsed = JSON.parse(logged) as HealthSummary; const parsed = JSON.parse(logged) as HealthSummary;
expect(parsed.web.linked).toBe(true); expect(parsed.providers.whatsapp?.linked).toBe(true);
expect(parsed.telegram.configured).toBe(true); expect(parsed.providers.telegram?.configured).toBe(true);
expect(parsed.sessions.count).toBe(1); expect(parsed.sessions.count).toBe(1);
}); });
it("prints text summary when not json", async () => { it("prints text summary when not json", async () => {
callGatewayMock.mockResolvedValueOnce({ callGatewayMock.mockResolvedValueOnce({
ok: true,
ts: Date.now(), ts: Date.now(),
durationMs: 5, durationMs: 5,
web: { linked: false, authAgeMs: null }, providers: {
telegram: { configured: false }, whatsapp: { linked: false, authAgeMs: null },
discord: { configured: false }, telegram: { configured: false },
discord: { configured: false },
},
providerOrder: ["whatsapp", "telegram", "discord"],
providerLabels: {
whatsapp: "WhatsApp",
telegram: "Telegram",
discord: "Discord",
},
heartbeatSeconds: 60, heartbeatSeconds: 60,
sessions: { path: "/tmp/sessions.json", count: 0, recent: [] }, sessions: { path: "/tmp/sessions.json", count: 0, recent: [] },
} satisfies HealthSummary); } satisfies HealthSummary);

View File

@@ -1,19 +1,26 @@
import { withProgress } from "../cli/progress.js"; import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js"; import { loadConfig } from "../config/config.js";
import { loadSessionStore, resolveStorePath } from "../config/sessions.js"; import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
import { type DiscordProbe, probeDiscord } from "../discord/probe.js";
import { buildGatewayConnectionDetails, callGateway } from "../gateway/call.js"; import { buildGatewayConnectionDetails, callGateway } from "../gateway/call.js";
import { info } from "../globals.js"; import { info } from "../globals.js";
import type { RuntimeEnv } from "../runtime.js"; import { formatErrorMessage } from "../infra/errors.js";
import { probeTelegram, type TelegramProbe } from "../telegram/probe.js"; import { resolveProviderDefaultAccountId } from "../providers/plugins/helpers.js";
import { resolveTelegramToken } from "../telegram/token.js";
import { resolveWhatsAppAccount } from "../web/accounts.js";
import { resolveHeartbeatSeconds } from "../web/reconnect.js";
import { import {
getWebAuthAgeMs, getProviderPlugin,
logWebSelfId, listProviderPlugins,
webAuthExists, } from "../providers/plugins/index.js";
} from "../web/session.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 = { export type HealthSummary = {
/** /**
@@ -24,24 +31,9 @@ export type HealthSummary = {
ok: true; ok: true;
ts: number; ts: number;
durationMs: number; durationMs: number;
web: { providers: Record<string, ProviderHealthSummary>;
linked: boolean; providerOrder: string[];
authAgeMs: number | null; providerLabels: Record<string, string>;
connect?: {
ok: boolean;
status?: number | null;
error?: string | null;
elapsedMs?: number | null;
};
};
telegram: {
configured: boolean;
probe?: TelegramProbe;
};
discord: {
configured: boolean;
probe?: DiscordProbe;
};
heartbeatSeconds: number; heartbeatSeconds: number;
sessions: { sessions: {
path: string; path: string;
@@ -56,13 +48,110 @@ export type HealthSummary = {
const DEFAULT_TIMEOUT_MS = 10_000; const DEFAULT_TIMEOUT_MS = 10_000;
export async function getHealthSnapshot( const isAccountEnabled = (account: unknown): boolean => {
timeoutMs?: number, if (!account || typeof account !== "object") return true;
): Promise<HealthSummary> { 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 cfg = loadConfig();
const account = resolveWhatsAppAccount({ cfg });
const linked = await webAuthExists(account.authDir);
const authAgeMs = getWebAuthAgeMs(account.authDir);
const heartbeatSeconds = resolveHeartbeatSeconds(cfg, undefined); const heartbeatSeconds = resolveHeartbeatSeconds(cfg, undefined);
const storePath = resolveStorePath(cfg.session?.store); const storePath = resolveStorePath(cfg.session?.store);
const store = loadSessionStore(storePath); const store = loadSessionStore(storePath);
@@ -78,27 +167,81 @@ export async function getHealthSnapshot(
const start = Date.now(); const start = Date.now();
const cappedTimeout = Math.max(1000, timeoutMs ?? DEFAULT_TIMEOUT_MS); const cappedTimeout = Math.max(1000, timeoutMs ?? DEFAULT_TIMEOUT_MS);
const { token: telegramToken } = resolveTelegramToken(cfg); const doProbe = params?.probe !== false;
const telegramConfigured = telegramToken.trim().length > 0; const providers: Record<string, ProviderHealthSummary> = {};
const telegramProxy = cfg.telegram?.proxy; const providerOrder = listProviderPlugins().map((plugin) => plugin.id);
const telegramProbe = telegramConfigured const providerLabels: Record<string, string> = {};
? await probeTelegram(telegramToken.trim(), cappedTimeout, telegramProxy)
: undefined;
const discordToken = for (const plugin of listProviderPlugins()) {
process.env.DISCORD_BOT_TOKEN ?? cfg.discord?.token ?? ""; providerLabels[plugin.id] = plugin.meta.label ?? plugin.id;
const discordConfigured = discordToken.trim().length > 0; const accountIds = plugin.config.listAccountIds(cfg);
const discordProbe = discordConfigured const defaultAccountId = resolveProviderDefaultAccountId({
? await probeDiscord(discordToken.trim(), cappedTimeout) plugin,
: undefined; 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 = { const summary: HealthSummary = {
ok: true, ok: true,
ts: Date.now(), ts: Date.now(),
durationMs: Date.now() - start, durationMs: Date.now() - start,
web: { linked, authAgeMs }, providers,
telegram: { configured: telegramConfigured, probe: telegramProbe }, providerOrder,
discord: { configured: discordConfigured, probe: discordProbe }, providerLabels,
heartbeatSeconds, heartbeatSeconds,
sessions: { sessions: {
path: storePath, path: storePath,
@@ -140,47 +283,29 @@ export async function healthCommand(
runtime.log(` ${line}`); runtime.log(` ${line}`);
} }
} }
runtime.log( for (const line of formatHealthProviderLines(summary)) {
summary.web.linked runtime.log(line);
? `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);
} }
if (summary.web.connect) { const cfg = loadConfig();
const base = summary.web.connect.ok for (const plugin of listProviderPlugins()) {
? info(`Connect: ok (${summary.web.connect.elapsedMs}ms)`) const providerSummary = summary.providers?.[plugin.id];
: `Connect: failed (${summary.web.connect.status ?? "unknown"})`; if (!providerSummary || providerSummary.linked !== true) continue;
runtime.log( if (!plugin.status?.logSelfId) continue;
base + const accountIds = plugin.config.listAccountIds(cfg);
(summary.web.connect.error ? ` - ${summary.web.connect.error}` : ""), 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(`Heartbeat interval: ${summary.heartbeatSeconds}s`));
runtime.log( runtime.log(
info( info(

View File

@@ -1,8 +1,4 @@
import type { AgentToolResult } from "@mariozechner/pi-agent-core"; 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 type { CliDeps } from "../cli/deps.js";
import { withProgress } from "../cli/progress.js"; import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js"; import { loadConfig } from "../config/config.js";
@@ -24,7 +20,13 @@ import {
sendPoll, sendPoll,
} from "../infra/outbound/message.js"; } from "../infra/outbound/message.js";
import { resolveMessageProviderSelection } from "../infra/outbound/provider-selection.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 type { RuntimeEnv } from "../runtime.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
type MessageAction = type MessageAction =
| "send" | "send"
@@ -277,6 +279,8 @@ export async function messageCommand(
provider: opts.provider, provider: opts.provider,
}); });
const provider = providerSelection.provider; const provider = providerSelection.provider;
const accountId = optionalString(opts.account);
const actionParams = opts as Record<string, unknown>;
const outboundDeps: OutboundSendDeps = { const outboundDeps: OutboundSendDeps = {
sendWhatsApp: deps.sendMessageWhatsApp, sendWhatsApp: deps.sendMessageWhatsApp,
sendTelegram: deps.sendMessageTelegram, sendTelegram: deps.sendMessageTelegram,
@@ -304,7 +308,7 @@ export async function messageCommand(
dryRun: opts.dryRun, dryRun: opts.dryRun,
media: optionalString(opts.media), media: optionalString(opts.media),
gifPlayback: opts.gifPlayback, gifPlayback: opts.gifPlayback,
account: optionalString(opts.account), account: accountId,
}; };
if (opts.dryRun) { if (opts.dryRun) {
@@ -312,72 +316,20 @@ export async function messageCommand(
return; return;
} }
if (provider === "discord") { const handled = await dispatchProviderMessageAction({
const result = await handleDiscordAction( provider,
{ action: action as ProviderMessageActionName,
action: "sendMessage", cfg,
to, params: actionParams,
content: message, accountId,
mediaUrl: optionalString(opts.media), gateway: {
replyTo: optionalString(opts.replyTo), clientName: GATEWAY_CLIENT_NAMES.CLI,
}, mode: GATEWAY_CLIENT_MODES.CLI,
cfg, },
); dryRun: opts.dryRun,
const payload = extractToolPayload(result); });
if (opts.json) { if (handled) {
runtime.log(JSON.stringify(payload, null, 2)); const payload = extractToolPayload(handled);
} 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);
if (opts.json) { if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2)); runtime.log(JSON.stringify(payload, null, 2));
} else { } else {
@@ -400,10 +352,13 @@ export async function messageCommand(
provider, provider,
mediaUrl: optionalString(opts.media), mediaUrl: optionalString(opts.media),
gifPlayback: opts.gifPlayback, gifPlayback: opts.gifPlayback,
accountId: optionalString(opts.account), accountId,
dryRun: opts.dryRun, dryRun: opts.dryRun,
deps: outboundDeps, deps: outboundDeps,
gateway: { clientName: "cli", mode: "cli" }, gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}), }),
); );
logSendResult(result, sendOpts, runtime); logSendResult(result, sendOpts, runtime);
@@ -434,26 +389,29 @@ export async function messageCommand(
durationHours, durationHours,
provider, provider,
dryRun: true, dryRun: true,
gateway: { clientName: "cli", mode: "cli" }, gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}); });
logPollDryRun(result, runtime); logPollDryRun(result, runtime);
return; return;
} }
if (provider === "discord") { const handled = await dispatchProviderMessageAction({
const result = await handleDiscordAction( provider,
{ action: action as ProviderMessageActionName,
action: "poll", cfg,
to, params: actionParams,
question, accountId,
answers: options, gateway: {
allowMultiselect, clientName: GATEWAY_CLIENT_NAMES.CLI,
durationHours: durationHours ?? undefined, mode: GATEWAY_CLIENT_MODES.CLI,
content: optionalString(opts.message), },
}, dryRun: opts.dryRun,
cfg, });
); if (handled) {
const payload = extractToolPayload(result); const payload = extractToolPayload(handled);
if (opts.json) { if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2)); runtime.log(JSON.stringify(payload, null, 2));
} else { } else {
@@ -478,7 +436,10 @@ export async function messageCommand(
durationHours, durationHours,
provider, provider,
dryRun: opts.dryRun, 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; return;
} }
if (action === "react") { const handled = await dispatchProviderMessageAction({
const messageId = requireString(opts.messageId, "message-id"); provider,
const emoji = optionalString(opts.emoji) ?? ""; action: action as ProviderMessageActionName,
if (provider === "discord") { cfg,
const result = await handleDiscordAction( params: actionParams,
{ accountId,
action: "react", gateway: {
channelId: requireString(opts.channelId ?? opts.to, "to"), clientName: GATEWAY_CLIENT_NAMES.CLI,
messageId, mode: GATEWAY_CLIENT_MODES.CLI,
emoji, },
remove: opts.remove, dryRun: opts.dryRun,
}, });
cfg, if (handled) {
); runtime.log(JSON.stringify(extractToolPayload(handled), null, 2));
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));
return; return;
} }
if (action === "thread-create") { throw new Error(
if (provider !== "discord") { `Action ${action} is not supported for provider ${provider}.`,
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"}`);
} }

View File

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

View File

@@ -8,6 +8,10 @@ import { WebSocket } from "ws";
import { PROTOCOL_VERSION } from "../gateway/protocol/index.js"; import { PROTOCOL_VERSION } from "../gateway/protocol/index.js";
import { rawDataToString } from "../infra/ws.js"; import { rawDataToString } from "../infra/ws.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
async function getFreePort(): Promise<number> { async function getFreePort(): Promise<number> {
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
@@ -66,10 +70,11 @@ async function connectReq(params: { url: string; token?: string }) {
minProtocol: PROTOCOL_VERSION, minProtocol: PROTOCOL_VERSION,
maxProtocol: PROTOCOL_VERSION, maxProtocol: PROTOCOL_VERSION,
client: { client: {
name: "vitest", id: GATEWAY_CLIENT_NAMES.TEST,
displayName: "vitest",
version: "dev", version: "dev",
platform: process.platform, platform: process.platform,
mode: "test", mode: GATEWAY_CLIENT_MODES.TEST,
}, },
caps: [], caps: [],
auth: params.token ? { token: params.token } : undefined, 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 { PROTOCOL_VERSION } from "../gateway/protocol/index.js";
import { rawDataToString } from "../infra/ws.js"; import { rawDataToString } from "../infra/ws.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
async function getFreePort(): Promise<number> { async function getFreePort(): Promise<number> {
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
@@ -91,10 +95,11 @@ async function connectReq(params: { url: string; token?: string }) {
minProtocol: PROTOCOL_VERSION, minProtocol: PROTOCOL_VERSION,
maxProtocol: PROTOCOL_VERSION, maxProtocol: PROTOCOL_VERSION,
client: { client: {
name: "vitest", id: GATEWAY_CLIENT_NAMES.TEST,
displayName: "vitest",
version: "dev", version: "dev",
platform: process.platform, platform: process.platform,
mode: "test", mode: GATEWAY_CLIENT_MODES.TEST,
}, },
caps: [], caps: [],
auth: params.token ? { token: params.token } : undefined, 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", () => { it("formats gateway provider status lines in registry order", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
telegramAccounts: [{ accountId: "default", configured: true }], providerAccounts: {
whatsappAccounts: [{ accountId: "default", linked: true }], telegram: [{ accountId: "default", configured: true }],
whatsapp: [{ accountId: "default", linked: true }],
},
}); });
const telegramIndex = lines.findIndex((line) => const telegramIndex = lines.findIndex((line) =>
@@ -326,14 +328,16 @@ describe("providers command", () => {
it("surfaces Discord privileged intent issues in providers status output", () => { it("surfaces Discord privileged intent issues in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
discordAccounts: [ providerAccounts: {
{ discord: [
accountId: "default", {
enabled: true, accountId: "default",
configured: true, enabled: true,
application: { intents: { messageContent: "disabled" } }, configured: true,
}, application: { intents: { messageContent: "disabled" } },
], },
],
},
}); });
expect(lines.join("\n")).toMatch(/Warnings:/); expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/Message Content Intent is disabled/i); 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", () => { it("surfaces Discord permission audit issues in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
discordAccounts: [ providerAccounts: {
{ discord: [
accountId: "default", {
enabled: true, accountId: "default",
configured: true, enabled: true,
audit: { configured: true,
unresolvedChannels: 1, audit: {
channels: [ unresolvedChannels: 1,
{ channels: [
channelId: "111", {
ok: false, channelId: "111",
missing: ["ViewChannel", "SendMessages"], ok: false,
}, missing: ["ViewChannel", "SendMessages"],
], },
],
},
}, },
}, ],
], },
}); });
expect(lines.join("\n")).toMatch(/Warnings:/); expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/permission audit/i); 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", () => { it("surfaces Telegram privacy-mode hints when allowUnmentionedGroups is enabled", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
telegramAccounts: [ providerAccounts: {
{ telegram: [
accountId: "default", {
enabled: true, accountId: "default",
configured: true, enabled: true,
allowUnmentionedGroups: true, configured: true,
}, allowUnmentionedGroups: true,
], },
],
},
}); });
expect(lines.join("\n")).toMatch(/Warnings:/); expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/Telegram Bot API privacy mode/i); 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", () => { it("surfaces Telegram group membership audit issues in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
telegramAccounts: [ providerAccounts: {
{ telegram: [
accountId: "default", {
enabled: true, accountId: "default",
configured: true, enabled: true,
audit: { configured: true,
hasWildcardUnmentionedGroups: true, audit: {
unresolvedGroups: 1, hasWildcardUnmentionedGroups: true,
groups: [ unresolvedGroups: 1,
{ groups: [
chatId: "-1001", {
ok: false, chatId: "-1001",
status: "left", ok: false,
error: "not in group", status: "left",
}, error: "not in group",
], },
],
},
}, },
}, ],
], },
}); });
expect(lines.join("\n")).toMatch(/Warnings:/); expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/membership probing is not possible/i); 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", () => { it("surfaces WhatsApp auth/runtime hints when unlinked or disconnected", () => {
const unlinked = formatGatewayProvidersStatusLines({ const unlinked = formatGatewayProvidersStatusLines({
whatsappAccounts: [ providerAccounts: {
{ accountId: "default", enabled: true, linked: false }, whatsapp: [{ accountId: "default", enabled: true, linked: false }],
], },
}); });
expect(unlinked.join("\n")).toMatch(/WhatsApp/i); expect(unlinked.join("\n")).toMatch(/WhatsApp/i);
expect(unlinked.join("\n")).toMatch(/Not linked/i); expect(unlinked.join("\n")).toMatch(/Not linked/i);
const disconnected = formatGatewayProvidersStatusLines({ const disconnected = formatGatewayProvidersStatusLines({
whatsappAccounts: [ providerAccounts: {
{ whatsapp: [
accountId: "default", {
enabled: true, accountId: "default",
linked: true, enabled: true,
running: true, linked: true,
connected: false, running: true,
reconnectAttempts: 5, connected: false,
lastError: "connection closed", reconnectAttempts: 5,
}, lastError: "connection closed",
], },
],
},
}); });
expect(disconnected.join("\n")).toMatch(/disconnected/i); expect(disconnected.join("\n")).toMatch(/disconnected/i);
}); });
it("surfaces Signal runtime errors in providers status output", () => { it("surfaces Signal runtime errors in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
signalAccounts: [ providerAccounts: {
{ signal: [
accountId: "default", {
enabled: true, accountId: "default",
configured: true, enabled: true,
running: false, configured: true,
lastError: "signal-cli unreachable", running: false,
}, lastError: "signal-cli unreachable",
], },
],
},
}); });
expect(lines.join("\n")).toMatch(/Warnings:/); expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/signal/i); expect(lines.join("\n")).toMatch(/signal/i);
@@ -451,15 +465,17 @@ describe("providers command", () => {
it("surfaces iMessage runtime errors in providers status output", () => { it("surfaces iMessage runtime errors in providers status output", () => {
const lines = formatGatewayProvidersStatusLines({ const lines = formatGatewayProvidersStatusLines({
imessageAccounts: [ providerAccounts: {
{ imessage: [
accountId: "default", {
enabled: true, accountId: "default",
configured: true, enabled: true,
running: false, configured: true,
lastError: "imsg permission denied", running: false,
}, lastError: "imsg permission denied",
], },
],
},
}); });
expect(lines.join("\n")).toMatch(/Warnings:/); expect(lines.join("\n")).toMatch(/Warnings:/);
expect(lines.join("\n")).toMatch(/imessage/i); expect(lines.join("\n")).toMatch(/imessage/i);

View File

@@ -1,56 +1,12 @@
import type { ClawdbotConfig } from "../../config/config.js"; import type { ClawdbotConfig } from "../../config/config.js";
import type { ChatProviderId } from "../../providers/registry.js"; import { getProviderPlugin } from "../../providers/plugins/index.js";
import { import type {
DEFAULT_ACCOUNT_ID, ProviderId,
normalizeAccountId, ProviderSetupInput,
} from "../../routing/session-key.js"; } from "../../providers/plugins/types.js";
import { normalizeAccountId } from "../../routing/session-key.js";
type ChatProvider = ChatProviderId; type ChatProvider = ProviderId;
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;
}
export function applyAccountName(params: { export function applyAccountName(params: {
cfg: ClawdbotConfig; cfg: ClawdbotConfig;
@@ -58,65 +14,12 @@ export function applyAccountName(params: {
accountId: string; accountId: string;
name?: string; name?: string;
}): ClawdbotConfig { }): ClawdbotConfig {
const trimmed = params.name?.trim();
if (!trimmed) return params.cfg;
const accountId = normalizeAccountId(params.accountId); const accountId = normalizeAccountId(params.accountId);
if (params.provider === "whatsapp") { const plugin = getProviderPlugin(params.provider);
return { const apply = plugin?.setup?.applyAccountName;
...params.cfg, return apply
whatsapp: { ? apply({ cfg: params.cfg, accountId, name: params.name })
...params.cfg.whatsapp, : params.cfg;
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;
} }
export function applyProviderAccountConfig(params: { export function applyProviderAccountConfig(params: {
@@ -140,205 +43,25 @@ export function applyProviderAccountConfig(params: {
useEnv?: boolean; useEnv?: boolean;
}): ClawdbotConfig { }): ClawdbotConfig {
const accountId = normalizeAccountId(params.accountId); const accountId = normalizeAccountId(params.accountId);
const name = params.name?.trim() || undefined; const plugin = getProviderPlugin(params.provider);
const namedConfig = applyAccountName({ const apply = plugin?.setup?.applyAccountConfig;
cfg: params.cfg, if (!apply) return params.cfg;
provider: params.provider, const input: ProviderSetupInput = {
accountId, name: params.name,
name, token: params.token,
}); tokenFile: params.tokenFile,
const next = botToken: params.botToken,
accountId !== DEFAULT_ACCOUNT_ID appToken: params.appToken,
? migrateBaseNameToDefaultAccount(namedConfig, params.provider) signalNumber: params.signalNumber,
: namedConfig; cliPath: params.cliPath,
dbPath: params.dbPath,
if (params.provider === "whatsapp") { service: params.service,
const entry = { region: params.region,
...next.whatsapp?.accounts?.[accountId], authDir: params.authDir,
...(params.authDir ? { authDir: params.authDir } : {}), httpUrl: params.httpUrl,
enabled: true, httpHost: params.httpHost,
}; httpPort: params.httpPort,
return { useEnv: params.useEnv,
...next, };
whatsapp: { return apply({ cfg: params.cfg, accountId, input });
...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;
} }

View File

@@ -1,5 +1,9 @@
import { writeConfigFile } from "../../config/config.js"; 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 { import {
DEFAULT_ACCOUNT_ID, DEFAULT_ACCOUNT_ID,
normalizeAccountId, normalizeAccountId,
@@ -75,25 +79,12 @@ export async function providersAddCommand(
if (wantsNames) { if (wantsNames) {
for (const provider of selection) { for (const provider of selection) {
const accountId = accountIds[provider] ?? DEFAULT_ACCOUNT_ID; const accountId = accountIds[provider] ?? DEFAULT_ACCOUNT_ID;
const existingName = const plugin = getProviderPlugin(provider as ProviderId);
provider === "whatsapp" const account = plugin?.config.resolveAccount(nextConfig, accountId) as
? nextConfig.whatsapp?.accounts?.[accountId]?.name | { name?: string }
: provider === "telegram" | undefined;
? (nextConfig.telegram?.accounts?.[accountId]?.name ?? const snapshot = plugin?.config.describeAccount?.(account, nextConfig);
nextConfig.telegram?.name) const existingName = snapshot?.name ?? account?.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 name = await prompter.text({ const name = await prompter.text({
message: `${provider} account name (${accountId})`, message: `${provider} account name (${accountId})`,
initialValue: existingName, initialValue: existingName,
@@ -114,76 +105,48 @@ export async function providersAddCommand(
return; return;
} }
const provider = normalizeChatProviderId(opts.provider); const provider = normalizeProviderId(opts.provider);
if (!provider) { if (!provider) {
runtime.error(`Unknown provider: ${String(opts.provider ?? "")}`); runtime.error(`Unknown provider: ${String(opts.provider ?? "")}`);
runtime.exit(1); runtime.exit(1);
return; 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; const useEnv = opts.useEnv === true;
const validationError = plugin.setup.validateInput?.({
if (provider === "telegram") { cfg,
if (useEnv && accountId !== DEFAULT_ACCOUNT_ID) { accountId,
runtime.error( input: {
"TELEGRAM_BOT_TOKEN can only be used for the default account.", name: opts.name,
); token: opts.token,
runtime.exit(1); tokenFile: opts.tokenFile,
return; botToken: opts.botToken,
} appToken: opts.appToken,
if (!useEnv && !opts.token && !opts.tokenFile) { signalNumber: opts.signalNumber,
runtime.error( cliPath: opts.cliPath,
"Telegram requires --token or --token-file (or --use-env).", dbPath: opts.dbPath,
); service: opts.service,
runtime.exit(1); region: opts.region,
return; authDir: opts.authDir,
} httpUrl: opts.httpUrl,
} httpHost: opts.httpHost,
if (provider === "discord") { httpPort: opts.httpPort,
if (useEnv && accountId !== DEFAULT_ACCOUNT_ID) { useEnv,
runtime.error( },
"DISCORD_BOT_TOKEN can only be used for the default account.", });
); if (validationError) {
runtime.exit(1); runtime.error(validationError);
return; 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 nextConfig = applyProviderAccountConfig({ const nextConfig = applyProviderAccountConfig({

View File

@@ -4,44 +4,19 @@ import {
loadAuthProfileStore, loadAuthProfileStore,
} from "../../agents/auth-profiles.js"; } from "../../agents/auth-profiles.js";
import { withProgress } from "../../cli/progress.js"; import { withProgress } from "../../cli/progress.js";
import {
listDiscordAccountIds,
resolveDiscordAccount,
} from "../../discord/accounts.js";
import {
listIMessageAccountIds,
resolveIMessageAccount,
} from "../../imessage/accounts.js";
import { import {
formatUsageReportLines, formatUsageReportLines,
loadProviderUsageSummary, loadProviderUsageSummary,
} from "../../infra/provider-usage.js"; } from "../../infra/provider-usage.js";
import { resolveMSTeamsCredentials } from "../../msteams/token.js"; import { listProviderPlugins } from "../../providers/plugins/index.js";
import { import { buildProviderAccountSnapshot } from "../../providers/plugins/status.js";
type ChatProviderId, import type {
listChatProviders, ProviderAccountSnapshot,
} from "../../providers/registry.js"; ProviderPlugin,
import { DEFAULT_ACCOUNT_ID } from "../../routing/session-key.js"; } from "../../providers/plugins/types.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.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 { formatDocsLink } from "../../terminal/links.js";
import { theme } from "../../terminal/theme.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"; import { formatProviderAccountLabel, requireValidConfig } from "./shared.js";
export type ProvidersListOptions = { export type ProvidersListOptions = {
@@ -77,6 +52,49 @@ function formatLinked(value: boolean): string {
return value ? theme.success("linked") : theme.warn("not linked"); 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( async function loadUsageWithProgress(
runtime: RuntimeEnv, runtime: RuntimeEnv,
): Promise<Awaited<ReturnType<typeof loadProviderUsageSummary>> | null> { ): Promise<Awaited<ReturnType<typeof loadProviderUsageSummary>> | null> {
@@ -99,118 +117,7 @@ export async function providersListCommand(
if (!cfg) return; if (!cfg) return;
const includeUsage = opts.usage !== false; const includeUsage = opts.usage !== false;
const accountIdsByProvider: Record<ChatProviderId, string[]> = { const plugins = listProviderPlugins();
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 authStore = loadAuthProfileStore(); const authStore = loadAuthProfileStore();
const authProfiles = Object.entries(authStore.profiles).map( const authProfiles = Object.entries(authStore.profiles).map(
@@ -225,19 +132,11 @@ export async function providersListCommand(
); );
if (opts.json) { if (opts.json) {
const usage = includeUsage ? await loadProviderUsageSummary() : undefined; const usage = includeUsage ? await loadProviderUsageSummary() : undefined;
const payload = { const chat: Record<string, string[]> = {};
chat: { for (const plugin of plugins) {
whatsapp: accountIdsByProvider.whatsapp, chat[plugin.id] = plugin.config.listAccountIds(cfg);
telegram: accountIdsByProvider.telegram, }
discord: accountIdsByProvider.discord, const payload = { chat, auth: authProfiles, ...(usage ? { usage } : {}) };
slack: accountIdsByProvider.slack,
signal: accountIdsByProvider.signal,
imessage: accountIdsByProvider.imessage,
msteams: accountIdsByProvider.msteams,
},
auth: authProfiles,
...(usage ? { usage } : {}),
};
runtime.log(JSON.stringify(payload, null, 2)); runtime.log(JSON.stringify(payload, null, 2));
return; return;
} }
@@ -245,12 +144,21 @@ export async function providersListCommand(
const lines: string[] = []; const lines: string[] = [];
lines.push(theme.heading("Chat providers:")); lines.push(theme.heading("Chat providers:"));
for (const meta of listChatProviders()) { for (const plugin of plugins) {
const accounts = accountIdsByProvider[meta.id]; const accounts = plugin.config.listAccountIds(cfg);
if (!accounts || accounts.length === 0) continue; if (!accounts || accounts.length === 0) continue;
for (const accountId of accounts) { for (const accountId of accounts) {
const line = await lineBuilders[meta.id](accountId); const snapshot = await buildProviderAccountSnapshot({
lines.push(line); 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