From e7d429305278e4de87c7e629ccf9b8f43f9d4cda Mon Sep 17 00:00:00 2001 From: loveuer Date: Thu, 12 Nov 2026 09:33:29 +0800 Subject: [PATCH] refactor: trim unused IM channels and dependencies Remove Slack, Slack Webhook, Teams Webhook, Matrix, Delta Chat, IRC and VK. Clean up channel configuration, migration support, examples and documentation. Drop unused SDKs and Matrix build tags while preserving the remaining channels. Validated with full Go tests, static checks, docs lint and a Linux amd64 build. --- .github/workflows/pr.yml | 6 +- .goreleaser.yaml | 1 - Makefile | 13 +- README.md | 5 - ROADMAP.md | 2 +- config/config.example.json | 57 - docs/architecture/routing-system.md | 6 +- docs/architecture/routing-system.zh.md | 6 +- docs/architecture/session-system.md | 2 +- docs/architecture/session-system.zh.md | 2 +- docs/channels/deltachat/README.md | 148 -- docs/channels/matrix/README.fr.md | 65 - docs/channels/matrix/README.ja.md | 65 - docs/channels/matrix/README.md | 77 - docs/channels/matrix/README.pt-br.md | 65 - docs/channels/matrix/README.vi.md | 65 - docs/channels/matrix/README.zh.md | 76 - docs/channels/slack/README.fr.md | 36 - docs/channels/slack/README.ja.md | 36 - docs/channels/slack/README.md | 36 - docs/channels/slack/README.pt-br.md | 36 - docs/channels/slack/README.vi.md | 36 - docs/channels/slack/README.zh.md | 36 - docs/channels/vk/README.md | 198 --- docs/design/steering-spec.md | 2 +- docs/guides/chat-apps.fr.md | 111 +- docs/guides/chat-apps.ja.md | 109 -- docs/guides/chat-apps.md | 111 +- docs/guides/chat-apps.ms.md | 40 +- docs/guides/chat-apps.pt-br.md | 111 +- docs/guides/chat-apps.vi.md | 111 +- docs/guides/chat-apps.zh.md | 111 +- docs/guides/routing-guide.md | 14 +- docs/guides/routing-guide.zh.md | 14 +- docs/guides/session-guide.md | 6 +- docs/guides/session-guide.zh.md | 6 +- docs/project/README.fr.md | 6 - docs/project/README.id.md | 3 - docs/project/README.it.md | 3 - docs/project/README.ja.md | 3 - docs/project/README.ko.md | 4 - docs/project/README.ms.md | 6 - docs/project/README.pt-br.md | 3 - docs/project/README.vi.md | 3 - docs/project/README.zh.md | 4 - docs/security/security_configuration.md | 9 - docs/security/sensitive_data_filtering.md | 2 +- docs/security/sensitive_data_filtering.zh.md | 2 +- go.mod | 8 - go.sum | 16 - integration/README.md | 8 +- integration/docker-compose.runner.yml | 2 +- pkg/agent/agent_test.go | 22 +- pkg/agent/dispatch_request_test.go | 12 +- pkg/agent/steering_test.go | 4 +- pkg/audio/asr/agent_test.go | 4 +- pkg/bus/bus_test.go | 16 +- pkg/bus/types.go | 2 +- pkg/channels/README.md | 142 +- pkg/channels/README.zh.md | 142 +- pkg/channels/deltachat/deltachat.go | 1330 --------------- pkg/channels/deltachat/deltachat_test.go | 1254 -------------- pkg/channels/deltachat/handler.go | 398 ----- pkg/channels/deltachat/init.go | 35 - pkg/channels/deltachat/rpc.go | 188 --- pkg/channels/irc/handler.go | 167 -- pkg/channels/irc/init.go | 35 - pkg/channels/irc/irc.go | 196 --- pkg/channels/irc/irc_test.go | 148 -- pkg/channels/manager.go | 15 - pkg/channels/manager_channel.go | 49 - pkg/channels/manager_channel_test.go | 25 - pkg/channels/matrix/init.go | 38 - pkg/channels/matrix/matrix.go | 1438 ----------------- pkg/channels/matrix/matrix_test.go | 506 ------ pkg/channels/slack/init.go | 25 - pkg/channels/slack/slack.go | 633 -------- pkg/channels/slack/slack_test.go | 264 --- pkg/channels/slack_webhook/convert.go | 263 --- pkg/channels/slack_webhook/convert_test.go | 187 --- pkg/channels/slack_webhook/init.go | 32 - pkg/channels/slack_webhook/slack_webhook.go | 316 ---- .../slack_webhook/slack_webhook_test.go | 281 ---- pkg/channels/teams_webhook/init.go | 32 - pkg/channels/teams_webhook/teams_webhook.go | 425 ----- .../teams_webhook/teams_webhook_test.go | 582 ------- pkg/channels/vk/init.go | 20 - pkg/channels/vk/vk.go | 295 ---- pkg/channels/vk/vk_test.go | 252 --- pkg/channels/voice_capabilities.go | 1 - pkg/commands/builtin_test.go | 6 +- pkg/config/config.go | 88 - pkg/config/config_channel.go | 14 - pkg/config/config_test.go | 75 +- pkg/config/defaults.go | 24 - pkg/config/example_security_usage.go | 11 - pkg/config/security_integration_test.go | 43 - pkg/gateway/channel_matrix.go | 24 - pkg/gateway/gateway.go | 6 - pkg/identity/identity_test.go | 4 +- pkg/memory/jsonl.go | 2 +- pkg/migrate/sources/openclaw/common.go | 2 - .../sources/openclaw/openclaw_config.go | 136 -- .../sources/openclaw/openclaw_config_test.go | 114 -- pkg/providers/ratelimiter_test.go | 2 +- pkg/routing/route_test.go | 6 +- pkg/session/allocator_test.go | 6 +- pkg/session/key_test.go | 6 +- pkg/session/manager_test.go | 2 +- pkg/tools/spawn_status_test.go | 4 +- pkg/utils/media.go | 2 +- scripts/test-irc.sh | 56 - 112 files changed, 243 insertions(+), 12067 deletions(-) delete mode 100644 docs/channels/deltachat/README.md delete mode 100644 docs/channels/matrix/README.fr.md delete mode 100644 docs/channels/matrix/README.ja.md delete mode 100644 docs/channels/matrix/README.md delete mode 100644 docs/channels/matrix/README.pt-br.md delete mode 100644 docs/channels/matrix/README.vi.md delete mode 100644 docs/channels/matrix/README.zh.md delete mode 100644 docs/channels/slack/README.fr.md delete mode 100644 docs/channels/slack/README.ja.md delete mode 100644 docs/channels/slack/README.md delete mode 100644 docs/channels/slack/README.pt-br.md delete mode 100644 docs/channels/slack/README.vi.md delete mode 100644 docs/channels/slack/README.zh.md delete mode 100644 docs/channels/vk/README.md delete mode 100644 pkg/channels/deltachat/deltachat.go delete mode 100644 pkg/channels/deltachat/deltachat_test.go delete mode 100644 pkg/channels/deltachat/handler.go delete mode 100644 pkg/channels/deltachat/init.go delete mode 100644 pkg/channels/deltachat/rpc.go delete mode 100644 pkg/channels/irc/handler.go delete mode 100644 pkg/channels/irc/init.go delete mode 100644 pkg/channels/irc/irc.go delete mode 100644 pkg/channels/irc/irc_test.go delete mode 100644 pkg/channels/matrix/init.go delete mode 100644 pkg/channels/matrix/matrix.go delete mode 100644 pkg/channels/matrix/matrix_test.go delete mode 100644 pkg/channels/slack/init.go delete mode 100644 pkg/channels/slack/slack.go delete mode 100644 pkg/channels/slack/slack_test.go delete mode 100644 pkg/channels/slack_webhook/convert.go delete mode 100644 pkg/channels/slack_webhook/convert_test.go delete mode 100644 pkg/channels/slack_webhook/init.go delete mode 100644 pkg/channels/slack_webhook/slack_webhook.go delete mode 100644 pkg/channels/slack_webhook/slack_webhook_test.go delete mode 100644 pkg/channels/teams_webhook/init.go delete mode 100644 pkg/channels/teams_webhook/teams_webhook.go delete mode 100644 pkg/channels/teams_webhook/teams_webhook_test.go delete mode 100644 pkg/channels/vk/init.go delete mode 100644 pkg/channels/vk/vk.go delete mode 100644 pkg/channels/vk/vk_test.go delete mode 100644 pkg/gateway/channel_matrix.go delete mode 100755 scripts/test-irc.sh diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index b497b0b7..3265b29c 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -23,13 +23,13 @@ jobs: uses: golangci/golangci-lint-action@v9 with: version: v2.10.1 - args: --build-tags=goolm,stdjson + args: --build-tags=stdjson vuln_check: name: Security Check runs-on: ubuntu-latest env: - GOFLAGS: -tags=goolm,stdjson + GOFLAGS: -tags=stdjson steps: - name: Checkout uses: actions/checkout@v7 @@ -63,7 +63,7 @@ jobs: run: go generate ./... - name: Run go test - run: go test -tags goolm,stdjson ./... + run: go test -tags stdjson ./... integration: name: Integration Tests diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 1df46d2b..57daf017 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -16,7 +16,6 @@ builds: env: - CGO_ENABLED=0 tags: - - goolm - stdjson ldflags: - -s -w diff --git a/Makefile b/Makefile index 6059486e..ba35b215 100644 --- a/Makefile +++ b/Makefile @@ -34,7 +34,7 @@ LDFLAGS=-X $(CONFIG_PKG).Version=$(VERSION) -X $(CONFIG_PKG).GitCommit=$(GIT_COM # Go variables GO?=go CGO_ENABLED?=0 -GO_BUILD_TAGS?=goolm,stdjson +GO_BUILD_TAGS?=stdjson GOFLAGS?=-v -tags $(GO_BUILD_TAGS) GOCACHE?=$(CURDIR)/.cache/go-build GOMODCACHE?=$(CURDIR)/.cache/go-mod @@ -43,11 +43,6 @@ export CGO_ENABLED export GOCACHE export GOMODCACHE export GOTOOLCHAIN -comma:=, -empty:= -space:=$(empty) $(empty) -GO_BUILD_TAGS_NO_GOOLM:=$(subst $(space),$(comma),$(strip $(filter-out goolm,$(subst $(comma),$(space),$(GO_BUILD_TAGS))))) -GOFLAGS_NO_GOOLM?=-v -tags $(GO_BUILD_TAGS_NO_GOOLM) # Patch MIPS LE ELF e_flags (offset 36) for NaN2008-only kernels (e.g. Ingenic X2600). # @@ -223,7 +218,7 @@ build-whatsapp-native: generate GOOS=linux GOARCH=arm64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 ./$(CMD_DIR) GOOS=linux GOARCH=loong64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-loong64 ./$(CMD_DIR) GOOS=linux GOARCH=riscv64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR) - GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build -tags $(GO_BUILD_TAGS_NO_GOOLM),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR) + GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR) $(call PATCH_MIPS_FLAGS,$(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle) GOOS=darwin GOARCH=arm64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR) GOOS=windows GOARCH=amd64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./$(CMD_DIR) @@ -249,7 +244,7 @@ build-linux-arm64: generate build-linux-mipsle: generate @echo "Building for linux/mipsle (softfloat)..." @mkdir -p $(BUILD_DIR) - GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS_NO_GOOLM) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR) + GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR) $(call PATCH_MIPS_FLAGS,$(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle) @echo "Build complete: $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle" @@ -274,7 +269,7 @@ build-all: generate @$(PTY_PATCH_LOONG64) GOOS=linux GOARCH=loong64 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-loong64 ./$(CMD_DIR) GOOS=linux GOARCH=riscv64 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR) - GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS_NO_GOOLM) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR) + GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR) $(call PATCH_MIPS_FLAGS,$(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle) GOOS=linux GOARCH=arm GOARM=7 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-armv7 ./$(CMD_DIR) GOOS=darwin GOARCH=arm64 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR) diff --git a/README.md b/README.md index 8f962bb8..b621d55a 100644 --- a/README.md +++ b/README.md @@ -385,15 +385,10 @@ Talk to your PicoClaw through 19+ messaging platforms: | **WhatsApp** | Easy (QR scan or bridge URL) | Native / Bridge | [Guide](docs/guides/chat-apps.md#whatsapp) | | **Weixin** | Easy (Native QR scan) | iLink API | [Guide](docs/guides/chat-apps.md#weixin) | | **QQ** | Easy (AppID + AppSecret) | WebSocket | [Guide](docs/channels/qq/README.md) | -| **Slack** | Easy (bot + app token) | Socket Mode | [Guide](docs/channels/slack/README.md) | -| **Matrix** | Medium (homeserver + token) | Sync API | [Guide](docs/channels/matrix/README.md) | -| **Delta Chat** | Easy (account script or email/password) | JSON-RPC (email/E2EE) | [Guide](docs/channels/deltachat/README.md) | | **DingTalk** | Medium (client credentials) | Stream | [Guide](docs/channels/dingtalk/README.md) | | **Feishu / Lark** | Medium (App ID + Secret) | WebSocket/SDK | [Guide](docs/channels/feishu/README.md) | | **LINE** | Medium (credentials + webhook) | Webhook | [Guide](docs/channels/line/README.md) | | **WeCom** | Easy (QR login or manual) | WebSocket | [Guide](docs/channels/wecom/README.md) | -| **VK** | Easy (group token) | Long Poll | [Guide](docs/channels/vk/README.md) | -| **IRC** | Medium (server + nick) | IRC protocol | [Guide](docs/guides/chat-apps.md#irc) | | **OneBot** | Medium (WebSocket URL) | OneBot v11 | [Guide](docs/channels/onebot/README.md) | | **MQTT** | Easy (broker + agent_id) | MQTT pub/sub | [Guide](docs/channels/mqtt/README.md) | diff --git a/ROADMAP.md b/ROADMAP.md index 8c5c0e25..e61060d0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -48,7 +48,7 @@ * **Channel** - * **IM Matrix**: QQ, WeChat (Work), DingTalk, Feishu (Lark), Telegram, Discord, WhatsApp, LINE, Slack, Email, KOOK, Signal, ... + * **IM Matrix**: QQ, WeChat (Work), DingTalk, Feishu (Lark), Telegram, Discord, WhatsApp, LINE, Email, KOOK, Signal, ... * **Standards**: Support for the **OneBot** protocol. * [**attachment**](https://github.com/sipeed/picoclaw/issues/348): Native handling of images, audio, and video attachments. diff --git a/config/config.example.json b/config/config.example.json index 6fbb362f..b0432316 100644 --- a/config/config.example.json +++ b/config/config.example.json @@ -184,38 +184,6 @@ "client_secret": "YOUR_CLIENT_SECRET" } }, - "slack": { - "enabled": false, - "type": "slack", - "allow_from": [], - "reasoning_channel_id": "", - "settings": { - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN" - } - }, - "matrix": { - "enabled": false, - "type": "matrix", - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": ["Thinking...", "Processing...", "Typing..."] - }, - "reasoning_channel_id": "", - "settings": { - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "crypto_database_path": "", - "crypto_passphrase": "YOUR_MATRIX_CRYPTO_PICKLE_KEY" - } - }, "line": { "enabled": false, "type": "line", @@ -253,31 +221,6 @@ "websocket_url": "wss://openws.work.weixin.qq.com", "send_thinking_message": true } - }, - "irc": { - "enabled": false, - "type": "irc", - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "typing": { - "enabled": false - }, - "reasoning_channel_id": "", - "settings": { - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "mybot", - "user": "", - "real_name": "", - "password": "", - "nickserv_password": "", - "sasl_user": "", - "sasl_password": "", - "channels": ["#mychannel"], - "request_caps": ["server-time", "message-tags"] - } } }, "tools": { diff --git a/docs/architecture/routing-system.md b/docs/architecture/routing-system.md index 6df97143..26b5b168 100644 --- a/docs/architecture/routing-system.md +++ b/docs/architecture/routing-system.md @@ -89,11 +89,11 @@ This means dispatch rules must match the normalized shape, for example: } }, { - "name": "slack-mentions", + "name": "discord-mentions", "agent": "support", "when": { - "channel": "slack", - "space": "workspace:t001", + "channel": "discord", + "space": "guild:t001", "mentioned": true } } diff --git a/docs/architecture/routing-system.zh.md b/docs/architecture/routing-system.zh.md index c0de0ee4..9fd4e9f7 100644 --- a/docs/architecture/routing-system.zh.md +++ b/docs/architecture/routing-system.zh.md @@ -88,11 +88,11 @@ type ResolvedRoute struct { } }, { - "name": "slack-mentions", + "name": "discord-mentions", "agent": "support", "when": { - "channel": "slack", - "space": "workspace:t001", + "channel": "discord", + "space": "guild:t001", "mentioned": true } } diff --git a/docs/architecture/session-system.md b/docs/architecture/session-system.md index 7ed2aed0..aa641f97 100644 --- a/docs/architecture/session-system.md +++ b/docs/architecture/session-system.md @@ -77,7 +77,7 @@ For compatibility, the allocator also emits legacy aliases such as: ```text agent:main:direct:user123 -agent:main:slack:channel:c001 +agent:main:discord:channel:c001 agent:main:pico:direct:pico:session-123 ``` diff --git a/docs/architecture/session-system.zh.md b/docs/architecture/session-system.zh.md index d87abf37..de65d5cf 100644 --- a/docs/architecture/session-system.zh.md +++ b/docs/architecture/session-system.zh.md @@ -77,7 +77,7 @@ sk_v1_ ```text agent:main:direct:user123 -agent:main:slack:channel:c001 +agent:main:discord:channel:c001 agent:main:pico:direct:pico:session-123 ``` diff --git a/docs/channels/deltachat/README.md b/docs/channels/deltachat/README.md deleted file mode 100644 index 4b941d14..00000000 --- a/docs/channels/deltachat/README.md +++ /dev/null @@ -1,148 +0,0 @@ -> Back to [README](../../../README.md) - -# Delta Chat Channel - -PicoClaw can run as a Delta Chat bot by launching a local -`deltachat-rpc-server` process and talking to it over JSON-RPC. The RPC server -handles the email account, IMAP/SMTP connection, message store, and encryption -keys. - -## Install - -Install the Delta Chat RPC server. If `deltachat-rpc-server` is on `PATH`, -PicoClaw can find it automatically; otherwise set `rpc_server_path` to the -exact binary path. - -```bash -pip install deltachat-rpc-server -which deltachat-rpc-server -``` - -Prebuilt binaries are also available from the -[Delta Chat core releases](https://github.com/deltachat/deltachat-core-rust/releases). - -## Configure - -The easiest setup is to let PicoClaw create a chatmail account in Delta -Chat's local account store. Put a relay marker in `email` using an empty local -part, for example `@nine.testrun.org`: - -```json -{ - "channel_list": { - "deltachat": { - "enabled": true, - "type": "deltachat", - "allow_from": ["friend@example.org"], - "group_trigger": { - "mention_only": true - }, - "settings": { - "email": "@nine.testrun.org", - "display_name": "PicoClaw Bot", - "avatar_image": "/home/me/bot-avatar.png" - } - } - } -} -``` - -On startup, PicoClaw creates the account through `deltachat-rpc-server`, then -stops with an error that contains the generated address. Replace the relay -marker with that full email address and run PicoClaw again: - -```json -{ - "email": "bot123@nine.testrun.org", - "display_name": "PicoClaw Bot", - "avatar_image": "/home/me/bot-avatar.png" -} -``` - -If `email` is missing, the startup error lists the built-in relay choices copied -from Parla. You can use one of those relay markers, or a custom chatmail relay -with the same `@server.name` form. - -`password` is not needed for PicoClaw-created chatmail accounts. Omit it when -`email` points to an already configured account in `data_dir`; the JSON-RPC -server owns the mailbox password. The legacy password-based path remains only -for classic email accounts that PicoClaw must configure itself. In that mode, -`password` is a secure field; on first config load it is moved to -`~/.picoclaw/.security.yml`, and it can also be set with -`PICOCLAW_CHANNELS_DELTACHAT_PASSWORD`. - -`display_name` and `avatar_image` are optional profile settings. When present, -PicoClaw applies them on every startup, so changing the avatar path in config is -enough to update the bot profile. - -| Field | Required | Description | -|-------|----------|-------------| -| `email` | Yes | Full bot mailbox address, or first-run relay marker such as `@nine.testrun.org` | -| `rpc_server_path` | No | Path to `deltachat-rpc-server`; only needed when it is not on `PATH` | -| `password` | No | Legacy only; required when PicoClaw must configure/reconfigure a classic mailbox itself | -| `display_name` | No | Startup-applied profile name shown to contacts and used for group mention detection | -| `avatar_image` | No | Startup-applied profile avatar image path; `~` is expanded. Missing files are warned and ignored | -| `data_dir` | No | Account database directory. Default: `~/.picoclaw/deltachat/` | -| `invite_link` | No | Delta Chat invite link to join on startup | -| `allow_crosspost` | No | Default `false`. When `true`, senders allowed by `allow_from` may use `message` tool targets outside the current chat, or resolve recipients by email/contact/chat name | -| `imap_server`, `imap_port` | No | Manual IMAP override for password-based configuration | -| `smtp_server`, `smtp_port` | No | Manual SMTP override for password-based configuration | - -Standard channel fields such as `allow_from`, `group_trigger`, and -`reasoning_channel_id` also apply. - -## First Run - -With `email` set to `@server`, PicoClaw creates the chatmail account, prints -the generated full email in the startup error, and exits. Update `email` to that -full address and run PicoClaw again. On later runs, PicoClaw selects the -configured account by `email`, applies optional profile settings, marks it as a -bot, and starts IO. - -With a new `data_dir` plus legacy `password`, PicoClaw can still configure a -classic email account and validate the mailbox credentials; after that, the -account is reused from the local data directory. - -Delta Chat requires peers to learn the bot's encryption key before messaging -it. On startup PicoClaw prints the bot invite link and QR code. Add the bot from -Delta Chat with that invite, not by typing the bare email address. - -## Behavior - -- Direct chats always respond after `allow_from` passes. -- Group chats follow `group_trigger`; without one, every group message is - handled. -- Messages from the bot itself, device chats, and info/system messages are - ignored. -- Accepted inbound messages are marked seen after the allow-list check. -- Incoming attachments (images, audio, video, documents) are registered with - the media store and handed to the agent, so it can view images or operate on - the files directly. If no media store is available, the path is appended - inline as `[attachment: /path]` instead. -- Outbound attachments are supported: when the agent emits media, each file is - sent as a Delta Chat message (with the caption as text). Delta Chat infers the - view type from the file, so images, GIFs, and videos render natively. -- Crosspost recipient lookup is disabled by default. The agent can always reply - to the current numeric chat ID, but sending to another numeric chat ID or - resolving an email/contact/chat name requires `allow_crosspost: true` - and the current sender must pass `allow_from`; `allow_from: ["*"]` allows this - for any sender. -- Voice is supported in both directions when voice providers are configured: - incoming voice notes are transcribed by the agent's ASR and the transcript is - passed to the model; the agent can reply with synthesized speech, which is - delivered as a native Delta Chat voice message (`send_tts`). This requires an - ASR and/or TTS provider under `voice` — it is not Delta Chat-specific config. - -## Troubleshooting - -| Symptom | Fix | -|---------|-----| -| `deltachat-rpc-server not found on PATH` or `rpc_server_path ... not found` | Install the RPC server on PATH, or set `rpc_server_path` to an absolute path | -| `email is required` | Choose one listed chatmail server, set `email` to a first-run marker such as `@nine.testrun.org`, run `picoclaw g`, then replace it with the generated full email | -| `created chatmail account ...` | Replace the `@server` marker in `email` with the generated full email and run PicoClaw again | -| `account ... is not configured in data_dir` | Point `data_dir` at the existing JSON-RPC account store, or use `email="@server"` to create one | -| `configure (check email/password/server)` | Check credentials, app password requirements, or IMAP/SMTP overrides | -| Bot does not answer in a group | Check `group_trigger`; mention `display_name` or use a configured prefix | -| Bot ignores a sender | Add the sender email to `allow_from`, or use `["*"]` for open access | -| Sender cannot message the bot | Re-add the bot with the startup QR/invite so Delta Chat can establish encryption | -| Agent cannot send to an email/name/other chat ID | Enable `settings.allow_crosspost` and allow the controlling sender in `allow_from`; this capability is disabled by default for privacy | diff --git a/docs/channels/matrix/README.fr.md b/docs/channels/matrix/README.fr.md deleted file mode 100644 index 5ff329a2..00000000 --- a/docs/channels/matrix/README.fr.md +++ /dev/null @@ -1,65 +0,0 @@ -> Retour au [README](../../project/README.fr.md) - -# Guide de configuration du canal Matrix - -## 1. Exemple de configuration - -Ajoutez ceci à `config.json` : - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": "Thinking..." - }, - "reasoning_channel_id": "", - "message_format": "richtext" - } - } -} -``` - -## 2. Référence des champs - -| Champ | Type | Requis | Description | -|----------------------|----------|--------|-------------| -| enabled | bool | Oui | Activer ou désactiver le canal Matrix | -| homeserver | string | Oui | URL du homeserver Matrix (par exemple `https://matrix.org`) | -| user_id | string | Oui | ID utilisateur Matrix du bot (par exemple `@bot:matrix.org`) | -| access_token | string | Oui | Jeton d'accès du bot | -| device_id | string | Non | ID d'appareil Matrix optionnel | -| join_on_invite | bool | Non | Rejoindre automatiquement les salons invités | -| allow_from | []string | Non | Liste blanche d'utilisateurs (IDs Matrix) | -| group_trigger | object | Non | Stratégie de déclenchement de groupe (`mention_only` / `prefixes`) | -| placeholder | object | Non | Configuration du message de remplacement | -| reasoning_channel_id | string | Non | Canal cible pour la sortie de raisonnement | -| message_format | string | Non | Format de sortie : `"richtext"` (défaut) rend le markdown en HTML ; `"plain"` envoie du texte brut uniquement | - -## 3. Fonctionnalités actuellement supportées - -- Envoi/réception de messages texte avec rendu markdown (gras, italique, titres, blocs de code, etc.) -- Format de message configurable (`richtext` / `plain`) -- Téléchargement d'images/audio/vidéo/fichiers entrants (MediaStore en priorité, chemin local en secours) -- Normalisation de l'audio entrant dans le flux de transcription existant (`[audio: ...]`) -- Upload et envoi d'images/audio/vidéo/fichiers sortants -- Règles de déclenchement de groupe (y compris le mode mention uniquement) -- État de frappe (`m.typing`) -- Message de remplacement + remplacement de la réponse finale -- Rejoindre automatiquement les salons invités (peut être désactivé) - -## 4. TODO - -- Améliorations des métadonnées des médias riches (par exemple taille et miniatures des images/vidéos) diff --git a/docs/channels/matrix/README.ja.md b/docs/channels/matrix/README.ja.md deleted file mode 100644 index adb14a1f..00000000 --- a/docs/channels/matrix/README.ja.md +++ /dev/null @@ -1,65 +0,0 @@ -> [README](../../project/README.ja.md) に戻る - -# Matrix チャンネル設定ガイド - -## 1. 設定例 - -`config.json` に以下を追加してください: - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": "Thinking..." - }, - "reasoning_channel_id": "", - "message_format": "richtext" - } - } -} -``` - -## 2. フィールドリファレンス - -| フィールド | 型 | 必須 | 説明 | -|----------------------|----------|------|------| -| enabled | bool | はい | Matrix チャンネルの有効/無効 | -| homeserver | string | はい | Matrix ホームサーバー URL(例:`https://matrix.org`) | -| user_id | string | はい | ボットの Matrix ユーザー ID(例:`@bot:matrix.org`) | -| access_token | string | はい | ボットのアクセストークン | -| device_id | string | いいえ | オプションの Matrix デバイス ID | -| join_on_invite | bool | いいえ | 招待されたルームに自動参加 | -| allow_from | []string | いいえ | ユーザーホワイトリスト(Matrix ユーザー ID) | -| group_trigger | object | いいえ | グループトリガー戦略(`mention_only` / `prefixes`) | -| placeholder | object | いいえ | プレースホルダーメッセージ設定 | -| reasoning_channel_id | string | いいえ | 推論出力のターゲットチャンネル | -| message_format | string | いいえ | 出力形式:`"richtext"`(デフォルト)は markdown を HTML としてレンダリング;`"plain"` はプレーンテキストのみ送信 | - -## 3. 現在サポートされている機能 - -- markdown レンダリング付きテキストメッセージ送受信(太字、斜体、見出し、コードブロックなど) -- 設定可能なメッセージ形式(`richtext` / `plain`) -- 受信画像/音声/動画/ファイルのダウンロード(MediaStore 優先、ローカルパスフォールバック) -- 受信音声の既存文字起こしフローへの正規化(`[audio: ...]`) -- 送信画像/音声/動画/ファイルのアップロードと送信 -- グループトリガールール(メンションのみモードを含む) -- タイピング状態(`m.typing`) -- プレースホルダーメッセージ + 最終返信の置き換え -- 招待されたルームへの自動参加(無効化可能) - -## 4. TODO - -- リッチメディアメタデータの改善(例:画像/動画のサイズとサムネイル) diff --git a/docs/channels/matrix/README.md b/docs/channels/matrix/README.md deleted file mode 100644 index 0239928b..00000000 --- a/docs/channels/matrix/README.md +++ /dev/null @@ -1,77 +0,0 @@ -> Back to [README](../../../README.md) - -# Matrix Channel Configuration Guide - -## 1. Example Configuration - -Add this to `config.json`: - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": ["Thinking...", "Processing...", "Typing..."] - }, - "reasoning_channel_id": "", - "message_format": "richtext", - "crypto_database_path": "", - "crypto_passphrase": "YOUR_MATRIX_CRYPTO_PICKLE_KEY" - } - } -} -``` - -## 2. Field Reference - -| Field | Type | Required | Description | -|----------------------|----------|----------|-------------| -| enabled | bool | Yes | Enable or disable the Matrix channel | -| homeserver | string | Yes | Matrix homeserver URL (for example `https://matrix.org`) | -| user_id | string | Yes | Bot Matrix user ID (for example `@bot:matrix.org`) | -| access_token | string | Yes | Bot access token | -| device_id | string | No | Optional Matrix device ID | -| join_on_invite | bool | No | Auto-join invited rooms | -| allow_from | []string | No | User whitelist (Matrix user IDs) | -| group_trigger | object | No | Group trigger strategy (`mention_only` / `prefixes`) | -| placeholder | object | No | Placeholder message config (see below) | -| reasoning_channel_id | string | No | Target channel for reasoning output | -| message_format | string | No | Output format: `"richtext"` (default) renders markdown as HTML; `"plain"` sends plain text only | -| crypto_database_path | string | No | Path to store the crypto database (uses workspace path `~/.picoclaw/workspace` if empty) | -| crypto_passphrase | string | No | Serialization key for encrypting session keys in the database; must remain unchanged once set | - -### Placeholder Config - -| Field | Type | Required | Description | -|---------|----------------|----------|-------------| -| enabled | bool | No | Enable placeholder messages (default: false) | -| text | string/[]string | No | Placeholder text(s). Can be a single string or array of strings. If multiple texts are provided, one is randomly selected at runtime. Default: "Thinking..." | - -## 3. Currently Supported - -- Text message send/receive with markdown rendering (bold, italic, headers, code blocks, etc.) -- Configurable message format (`richtext` / `plain`) -- Incoming image/audio/video/file download (MediaStore first, local path fallback) -- Incoming audio normalization into existing transcription flow (`[audio: ...]`) -- Outgoing image/audio/video/file upload and send -- Group trigger rules (including mention-only mode) -- Typing state (`m.typing`) -- Placeholder message + final reply replacement -- Auto-join invited rooms (can be disabled) -- End-to-end encryption (E2EE) support for encrypted messages - -## 4. TODO - -- Rich media metadata improvements (for example image/video size and thumbnails) diff --git a/docs/channels/matrix/README.pt-br.md b/docs/channels/matrix/README.pt-br.md deleted file mode 100644 index 4f606f3e..00000000 --- a/docs/channels/matrix/README.pt-br.md +++ /dev/null @@ -1,65 +0,0 @@ -> Voltar ao [README](../../project/README.pt-br.md) - -# Guia de Configuração do Canal Matrix - -## 1. Exemplo de Configuração - -Adicione isto ao `config.json`: - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": "Thinking..." - }, - "reasoning_channel_id": "", - "message_format": "richtext" - } - } -} -``` - -## 2. Referência de Campos - -| Campo | Tipo | Obrigatório | Descrição | -|----------------------|----------|-------------|-----------| -| enabled | bool | Sim | Habilitar ou desabilitar o canal Matrix | -| homeserver | string | Sim | URL do homeserver Matrix (por exemplo `https://matrix.org`) | -| user_id | string | Sim | ID de usuário Matrix do bot (por exemplo `@bot:matrix.org`) | -| access_token | string | Sim | Token de acesso do bot | -| device_id | string | Não | ID de dispositivo Matrix opcional | -| join_on_invite | bool | Não | Entrar automaticamente em salas convidadas | -| allow_from | []string | Não | Lista branca de usuários (IDs Matrix) | -| group_trigger | object | Não | Estratégia de gatilho de grupo (`mention_only` / `prefixes`) | -| placeholder | object | Não | Configuração de mensagem de espaço reservado | -| reasoning_channel_id | string | Não | Canal alvo para saída de raciocínio | -| message_format | string | Não | Formato de saída: `"richtext"` (padrão) renderiza markdown como HTML; `"plain"` envia apenas texto simples | - -## 3. Suporte Atual - -- Envio/recebimento de mensagens de texto com renderização markdown (negrito, itálico, cabeçalhos, blocos de código, etc.) -- Formato de mensagem configurável (`richtext` / `plain`) -- Download de imagens/áudio/vídeo/arquivos recebidos (MediaStore primeiro, fallback para caminho local) -- Normalização de áudio recebido no fluxo de transcrição existente (`[audio: ...]`) -- Upload e envio de imagens/áudio/vídeo/arquivos de saída -- Regras de gatilho de grupo (incluindo modo somente menção) -- Estado de digitação (`m.typing`) -- Mensagem de espaço reservado + substituição de resposta final -- Entrada automática em salas convidadas (pode ser desabilitado) - -## 4. TODO - -- Melhorias nos metadados de mídia rica (por exemplo tamanho e miniaturas de imagens/vídeos) diff --git a/docs/channels/matrix/README.vi.md b/docs/channels/matrix/README.vi.md deleted file mode 100644 index 27f2ce74..00000000 --- a/docs/channels/matrix/README.vi.md +++ /dev/null @@ -1,65 +0,0 @@ -> Quay lại [README](../../project/README.vi.md) - -# Hướng dẫn Cấu hình Kênh Matrix - -## 1. Cấu hình Mẫu - -Thêm vào `config.json`: - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": "Thinking..." - }, - "reasoning_channel_id": "", - "message_format": "richtext" - } - } -} -``` - -## 2. Tham chiếu Trường - -| Trường | Kiểu | Bắt buộc | Mô tả | -|----------------------|----------|----------|-------| -| enabled | bool | Có | Bật hoặc tắt kênh Matrix | -| homeserver | string | Có | URL homeserver Matrix (ví dụ `https://matrix.org`) | -| user_id | string | Có | ID người dùng Matrix của bot (ví dụ `@bot:matrix.org`) | -| access_token | string | Có | Token truy cập của bot | -| device_id | string | Không | ID thiết bị Matrix tùy chọn | -| join_on_invite | bool | Không | Tự động tham gia phòng được mời | -| allow_from | []string | Không | Danh sách trắng người dùng (ID Matrix) | -| group_trigger | object | Không | Chiến lược kích hoạt nhóm (`mention_only` / `prefixes`) | -| placeholder | object | Không | Cấu hình tin nhắn giữ chỗ | -| reasoning_channel_id | string | Không | Kênh đích cho đầu ra suy luận | -| message_format | string | Không | Định dạng đầu ra: `"richtext"` (mặc định) render markdown thành HTML; `"plain"` chỉ gửi văn bản thuần | - -## 3. Tính năng Hiện tại - -- Gửi/nhận tin nhắn văn bản với render markdown (đậm, nghiêng, tiêu đề, khối code, v.v.) -- Định dạng tin nhắn có thể cấu hình (`richtext` / `plain`) -- Tải xuống hình ảnh/âm thanh/video/tệp đến (MediaStore trước, fallback đường dẫn cục bộ) -- Chuẩn hóa âm thanh đến vào luồng phiên âm hiện có (`[audio: ...]`) -- Tải lên và gửi hình ảnh/âm thanh/video/tệp đi -- Quy tắc kích hoạt nhóm (bao gồm chế độ chỉ đề cập) -- Trạng thái đang gõ (`m.typing`) -- Tin nhắn giữ chỗ + thay thế phản hồi cuối cùng -- Tự động tham gia phòng được mời (có thể tắt) - -## 4. TODO - -- Cải thiện metadata phương tiện phong phú (ví dụ kích thước và hình thu nhỏ hình ảnh/video) diff --git a/docs/channels/matrix/README.zh.md b/docs/channels/matrix/README.zh.md deleted file mode 100644 index 97634e2e..00000000 --- a/docs/channels/matrix/README.zh.md +++ /dev/null @@ -1,76 +0,0 @@ -> 返回 [README](../../project/README.zh.md) - -# Matrix 通道配置指南 - -## 1. 配置示例 - -在 `config.json` 中添加: - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "device_id": "", - "join_on_invite": true, - "allow_from": [], - "group_trigger": { - "mention_only": true - }, - "placeholder": { - "enabled": true, - "text": ["Thinking...", "Processing...", "Typing..."] - }, - "reasoning_channel_id": "", - "message_format": "richtext", - "crypto_database_path": "", - "crypto_passphrase": "YOUR_MATRIX_CRYPTO_PICKLE_KEY" - } - } -} -``` - -## 2. 参数说明 - -| 字段 | 类型 | 必填 | 说明 | -|----------------------|----------|------|------| -| enabled | bool | 是 | 是否启用 Matrix 通道 | -| homeserver | string | 是 | Matrix 服务器地址(例如 `https://matrix.org`) | -| user_id | string | 是 | 机器人 Matrix 用户 ID(例如 `@bot:matrix.org`) | -| access_token | string | 是 | 机器人 access token | -| device_id | string | 否 | 设备 ID(可选) | -| join_on_invite | bool | 否 | 是否自动加入邀请房间 | -| allow_from | []string | 否 | 白名单用户(Matrix 用户 ID) | -| group_trigger | object | 否 | 群聊触发策略(支持 `mention_only` / `prefixes`) | -| placeholder | object | 否 | 占位消息配置 | -| reasoning_channel_id | string | 否 | 思维链输出目标通道 | -| message_format | string | 否 | 消息格式:`richtext`(富文本)或 `plain`(纯文本) | -| crypto_database_path | string | 否 | 加密数据库存储路径(为空时使用工作空间路径 `~/.picoclaw/workspace`) | -| crypto_passphrase | string | 否 | 加密数据库中 session key 的序列化密钥;设置后不能更改 | - -### 占位消息配置 (Placeholder) - -| 字段 | 类型 | 必填 | 说明 | -|---------|-----------------|------|------| -| enabled | bool | 否 | 是否启用占位消息(默认:false) | -| text | string/[]string | 否 | 占位文本。可以是单个字符串或字符串数组。如果提供多个文本,运行时会随机选择一个。默认:"Thinking..." | - -## 3. 当前支持 - -- 文本消息收发 -- 图片/音频/视频/文件消息入站下载(写入 MediaStore / 本地路径回退) -- 音频消息按统一标记进入现有转写流程(`[audio: ...]`) -- 图片/音频/视频/文件消息出站发送(上传到 Matrix 媒体库后发送) -- 群聊触发规则(支持仅 @ 提及时响应) -- Typing 状态(`m.typing`) -- 占位消息(`Thinking... 💭`)+ 最终回复替换 -- 自动加入邀请房间(可关闭) -- 端对端加密(E2EE)消息支持 - -## 4. TODO - -- 富媒体细节增强(如 image/video 的尺寸、缩略图等 metadata) diff --git a/docs/channels/slack/README.fr.md b/docs/channels/slack/README.fr.md deleted file mode 100644 index be533052..00000000 --- a/docs/channels/slack/README.fr.md +++ /dev/null @@ -1,36 +0,0 @@ -> Retour au [README](../../project/README.fr.md) - -# Slack - -Slack est l'une des principales plateformes de messagerie instantanée pour les entreprises. PicoClaw utilise le Socket Mode de Slack pour une communication bidirectionnelle en temps réel, sans nécessiter la configuration d'un endpoint webhook public. - -## Configuration - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-...", - "app_token": "xapp-...", - "allow_from": [] - } - } -} -``` - -| Champ | Type | Requis | Description | -| ---------- | ------ | ------ | ---------------------------------------------------------------------------- | -| enabled | bool | Oui | Activer ou non le canal Slack | -| bot_token | string | Oui | Bot User OAuth Token du bot Slack (commence par xoxb-) | -| app_token | string | Oui | App Level Token Socket Mode de l'application Slack (commence par xapp-) | -| allow_from | array | Non | Liste blanche d'ID utilisateurs ; vide signifie tous les utilisateurs | - -## Procédure de configuration - -1. Rendez-vous sur [Slack API](https://api.slack.com/) et créez une nouvelle application Slack -2. Activez le Socket Mode et obtenez l'App Level Token -3. Ajoutez des Bot Token Scopes (par exemple `chat:write`, `im:history`, etc.) -4. Installez l'application dans votre espace de travail et obtenez le Bot User OAuth Token -5. Renseignez le Bot Token et l'App Token dans le fichier de configuration diff --git a/docs/channels/slack/README.ja.md b/docs/channels/slack/README.ja.md deleted file mode 100644 index 38cfc013..00000000 --- a/docs/channels/slack/README.ja.md +++ /dev/null @@ -1,36 +0,0 @@ -> [README](../../project/README.ja.md) に戻る - -# Slack - -Slack は世界をリードする企業向けインスタントメッセージングプラットフォームです。PicoClaw は Slack の Socket Mode を使用してリアルタイムの双方向通信を実現しており、公開 Webhook エンドポイントの設定は不要です。 - -## 設定 - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-...", - "app_token": "xapp-...", - "allow_from": [] - } - } -} -``` - -| フィールド | 型 | 必須 | 説明 | -| ---------- | ------ | ------ | ------------------------------------------------------------------------ | -| enabled | bool | はい | Slack チャンネルを有効にするかどうか | -| bot_token | string | はい | Slack ボットの Bot User OAuth Token(xoxb- で始まる) | -| app_token | string | はい | Slack アプリの Socket Mode App Level Token(xapp- で始まる) | -| allow_from | array | いいえ | ユーザーIDのホワイトリスト。空の場合は全ユーザーを許可 | - -## セットアップ手順 - -1. [Slack API](https://api.slack.com/) にアクセスして新しい Slack アプリを作成する -2. Socket Mode を有効にして App Level Token を取得する -3. Bot Token Scopes を追加する(例: `chat:write`、`im:history` など) -4. アプリをワークスペースにインストールして Bot User OAuth Token を取得する -5. Bot Token と App Token を設定ファイルに入力する diff --git a/docs/channels/slack/README.md b/docs/channels/slack/README.md deleted file mode 100644 index 4f101451..00000000 --- a/docs/channels/slack/README.md +++ /dev/null @@ -1,36 +0,0 @@ -> Back to [README](../../../README.md) - -# Slack - -Slack is a leading enterprise instant messaging platform. PicoClaw uses Slack's Socket Mode for real-time bidirectional communication, with no need to configure a public webhook endpoint. - -## Configuration - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-...", - "app_token": "xapp-...", - "allow_from": [] - } - } -} -``` - -| Field | Type | Required | Description | -| ---------- | ------ | -------- | ------------------------------------------------------------------------ | -| enabled | bool | Yes | Whether to enable the Slack channel | -| bot_token | string | Yes | Bot User OAuth Token for the Slack bot (starts with xoxb-) | -| app_token | string | Yes | Socket Mode App Level Token for the Slack app (starts with xapp-) | -| allow_from | array | No | User ID whitelist; empty means all users are allowed | - -## Setup - -1. Go to [Slack API](https://api.slack.com/) and create a new Slack app -2. Enable Socket Mode and obtain the App Level Token -3. Add Bot Token Scopes (e.g. `chat:write`, `im:history`, etc.) -4. Install the app to your workspace and obtain the Bot User OAuth Token -5. Fill in the Bot Token and App Token in the configuration file diff --git a/docs/channels/slack/README.pt-br.md b/docs/channels/slack/README.pt-br.md deleted file mode 100644 index d2676d44..00000000 --- a/docs/channels/slack/README.pt-br.md +++ /dev/null @@ -1,36 +0,0 @@ -> Voltar ao [README](../../project/README.pt-br.md) - -# Slack - -O Slack é uma das principais plataformas de mensagens instantâneas para empresas. O PicoClaw usa o Socket Mode do Slack para comunicação bidirecional em tempo real, sem necessidade de configurar um endpoint de webhook público. - -## Configuração - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-...", - "app_token": "xapp-...", - "allow_from": [] - } - } -} -``` - -| Campo | Tipo | Obrigatório | Descrição | -| ---------- | ------ | ----------- | ---------------------------------------------------------------------------- | -| enabled | bool | Sim | Se o canal Slack deve ser habilitado | -| bot_token | string | Sim | Bot User OAuth Token do bot Slack (começa com xoxb-) | -| app_token | string | Sim | App Level Token do Socket Mode do aplicativo Slack (começa com xapp-) | -| allow_from | array | Não | Lista de permissão de IDs de usuário; vazio permite todos | - -## Configuração passo a passo - -1. Acesse o [Slack API](https://api.slack.com/) e crie um novo aplicativo Slack -2. Ative o Socket Mode e obtenha o App Level Token -3. Adicione Bot Token Scopes (ex.: `chat:write`, `im:history`, etc.) -4. Instale o aplicativo no seu workspace e obtenha o Bot User OAuth Token -5. Preencha o Bot Token e o App Token no arquivo de configuração diff --git a/docs/channels/slack/README.vi.md b/docs/channels/slack/README.vi.md deleted file mode 100644 index 3bbbe313..00000000 --- a/docs/channels/slack/README.vi.md +++ /dev/null @@ -1,36 +0,0 @@ -> Quay lại [README](../../project/README.vi.md) - -# Slack - -Slack là nền tảng nhắn tin tức thì hàng đầu dành cho doanh nghiệp. PicoClaw sử dụng Socket Mode của Slack để giao tiếp hai chiều theo thời gian thực, không cần cấu hình endpoint webhook công khai. - -## Cấu hình - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-...", - "app_token": "xapp-...", - "allow_from": [] - } - } -} -``` - -| Trường | Kiểu | Bắt buộc | Mô tả | -| ---------- | ------ | -------- | ---------------------------------------------------------------------------- | -| enabled | bool | Có | Có bật kênh Slack hay không | -| bot_token | string | Có | Bot User OAuth Token của Slack bot (bắt đầu bằng xoxb-) | -| app_token | string | Có | App Level Token Socket Mode của ứng dụng Slack (bắt đầu bằng xapp-) | -| allow_from | array | Không | Danh sách trắng ID người dùng; để trống cho phép tất cả | - -## Quy trình thiết lập - -1. Truy cập [Slack API](https://api.slack.com/) và tạo một ứng dụng Slack mới -2. Bật Socket Mode và lấy App Level Token -3. Thêm Bot Token Scopes (ví dụ: `chat:write`, `im:history`, v.v.) -4. Cài đặt ứng dụng vào workspace và lấy Bot User OAuth Token -5. Điền Bot Token và App Token vào file cấu hình diff --git a/docs/channels/slack/README.zh.md b/docs/channels/slack/README.zh.md deleted file mode 100644 index 8ecfe88b..00000000 --- a/docs/channels/slack/README.zh.md +++ /dev/null @@ -1,36 +0,0 @@ -> 返回 [README](../../project/README.zh.md) - -# Slack - -Slack 是全球领先的企业级即时通讯平台。PicoClaw 采用 Slack 的 Socket Mode 实现实时双向通信,无需配置公开的 Webhook 端点。 - -## 配置 - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-...", - "app_token": "xapp-...", - "allow_from": [] - } - } -} -``` - -| 字段 | 类型 | 必填 | 描述 | -| ---------- | ------ | ---- | -------------------------------------------------------- | -| enabled | bool | 是 | 是否启用 Slack 频道 | -| bot_token | string | 是 | Slack 机器人的 Bot User OAuth Token (以 xoxb- 开头) | -| app_token | string | 是 | Slack 应用的 Socket Mode App Level Token (以 xapp- 开头) | -| allow_from | array | 否 | 用户ID白名单,空表示允许所有用户 | - -## 设置流程 - -1. 前往 [Slack API](https://api.slack.com/) 创建一个新的 Slack 应用 -2. 启用 Socket Mode 并获取 App Level Token -3. 添加 Bot Token Scopes(例如`chat:write`、`im:history`等) -4. 安装应用到工作区并获取 Bot User OAuth Token -5. 将 Bot Token 和 App Token 填入配置文件中 diff --git a/docs/channels/vk/README.md b/docs/channels/vk/README.md deleted file mode 100644 index 5e0c72bc..00000000 --- a/docs/channels/vk/README.md +++ /dev/null @@ -1,198 +0,0 @@ -# VK (VKontakte) - -The VK channel uses Bots Long Poll API for bot-based communication with VK social network. It supports text messages, media attachments (photos, videos, audio, documents, stickers), and group chat interactions. - -## Configuration - -```json -{ - "channel_list": { - "vk": { - "enabled": true, - "type": "vk", - "token": "NOT_HERE", - "group_id": 123456789, - "allow_from": ["123456789"], - "group_trigger": { - "mention_only": false, - "prefixes": ["/bot", "!bot"] - } - } - } -} -``` - -| Field | Type | Required | Description | -| ---------------- | ------ | -------- | ------------------------------------------------------------------ | -| enabled | bool | Yes | Whether to enable the VK channel | -| token | string | Yes | Set to `NOT_HERE` - token is stored securely (see Token Storage) | -| group_id | int | Yes | VK Community ID (Group ID) | -| allow_from | array | No | Allowlist of user IDs; empty means all users are allowed | -| group_trigger | object | No | Configuration for group chat triggers | - -### Token Storage - -For security reasons, the VK access token should not be stored directly in the configuration file. Instead: - -1. Set `token` to `"NOT_HERE"` in the configuration -2. Store the actual token using one of these methods: - - **Environment variable**: Set `PICOCLAW_CHANNELS_VK_TOKEN` environment variable - - **Secure storage**: Use PicoClaw's secure token storage mechanism - -Example using environment variable: -```bash -export PICOCLAW_CHANNELS_VK_TOKEN="vk1.a.abc123..." -``` - -### Group Trigger Configuration - -| Field | Type | Description | -| ------------ | -------- | ------------------------------------------------------------------ | -| mention_only | bool | Only respond when bot is mentioned in group chats | -| prefixes | []string | List of prefixes that trigger bot response in group chats | - -## Setup - -### 1. Create a VK Community - -1. Go to [VK](https://vk.com) and log in -2. Create a new community or use an existing one -3. Note your Community ID (found in the community URL, e.g., `public123456789`) - -### 2. Enable Messages - -1. Go to your community page -2. Click "Manage" → "Messages" → "Community Messages" -3. Enable community messages - -### 3. Create Access Token - -1. Go to "Manage" → "API usage" → "Access tokens" -2. Click "Create token" -3. Select the following permissions: - - `messages` - Access to messages - - `photos` - Access to photos (optional) - - `docs` - Access to documents (optional) -4. Copy the generated access token -5. Store the token securely (see Token Storage section below) - -### 4. Configure PicoClaw - -1. Add the token to your PicoClaw configuration -2. Set the `group_id` to your community ID (numeric value) -3. (Optional) Configure `allow_from` to restrict which user IDs can interact - -## Features - -### Supported Message Types - -- **Text messages**: Full support for text messages -- **Photos**: Photos are displayed as `[photo]` placeholder -- **Videos**: Videos are displayed as `[video]` placeholder -- **Audio**: Audio files are displayed as `[audio]` placeholder -- **Voice messages**: Voice messages are displayed as `[voice]` placeholder and support transcription -- **Documents**: Documents are displayed as `[document: filename]` -- **Stickers**: Stickers are displayed as `[sticker]` placeholder - -### Voice Support - -The VK channel supports both voice message reception and text-to-speech capabilities: - -- **ASR (Automatic Speech Recognition)**: Voice messages can be transcribed to text using configured voice models -- **TTS (Text-to-Speech)**: Text responses can be converted to voice messages - -To enable voice transcription, configure a voice model in your providers setup. See [Voice Transcription](../../guides/providers.md#voice-transcription) for details. - -### Group Chat Support - -The VK channel supports group chats with configurable triggers: - -- **Mention-only mode**: Bot only responds when mentioned -- **Prefix mode**: Bot responds to messages starting with specified prefixes -- **Permissive mode**: Bot responds to all messages (default) - -### Message Length - -VK has a maximum message length of 4000 characters. PicoClaw automatically splits longer messages into multiple parts. - -## Example Configuration - -### Basic Configuration - -```json -{ - "channel_list": { - "vk": { - "enabled": true, - "type": "vk", - "token": "NOT_HERE", - "group_id": 123456789 - } - } -} -``` - -### With User Whitelist - -```json -{ - "channel_list": { - "vk": { - "enabled": true, - "type": "vk", - "token": "NOT_HERE", - "group_id": 123456789, - "allow_from": ["123456789", "987654321"] - } - } -} -``` - -### With Group Chat Triggers - -```json -{ - "channel_list": { - "vk": { - "enabled": true, - "type": "vk", - "token": "NOT_HERE", - "group_id": 123456789, - "group_trigger": { - "prefixes": ["/bot", "!bot"] - } - } - } -} -``` - -## Troubleshooting - -### Bot Not Responding - -1. Check that the access token is valid -2. Verify that the `group_id` is correct -3. Ensure the user ID is in `allow_from` if configured -4. Check PicoClaw logs for error messages - -### Permission Errors - -Make sure the access token has the necessary permissions: -- `messages` - Required for sending and receiving messages -- `photos` - Optional, for handling photo attachments -- `docs` - Optional, for handling document attachments - -### Group Chat Issues - -If the bot doesn't respond in group chats: -1. Check `group_trigger` configuration -2. Try using a prefix to trigger the bot -3. Check if the bot has permission to read group messages - -## API Reference - -The VK channel uses the [VK SDK for Go](https://github.com/SevereCloud/vksdk) library, which supports VK API version 5.199. - -For more information about VK API, see: -- [VK API Documentation](https://dev.vk.com/en) -- [VK Bots Long Poll API](https://dev.vk.com/en/api/bots-long-poll/getting-started) diff --git a/docs/design/steering-spec.md b/docs/design/steering-spec.md index 5fd8360b..32a05195 100644 --- a/docs/design/steering-spec.md +++ b/docs/design/steering-spec.md @@ -21,7 +21,7 @@ graph TD subgraph External Callers TG[Telegram] DC[Discord] - SL[Slack] + SL[Discord] end subgraph AgentLoop diff --git a/docs/guides/chat-apps.fr.md b/docs/guides/chat-apps.fr.md index 6c432cab..a57bd2d7 100644 --- a/docs/guides/chat-apps.fr.md +++ b/docs/guides/chat-apps.fr.md @@ -4,7 +4,7 @@ ## 💬 Applications de Chat -Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT. +Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT. > **Note** : Tous les canaux basés sur les webhooks (LINE, WeCom, etc.) sont servis sur un seul serveur HTTP Gateway partagé (`gateway.host`:`gateway.port`, par défaut `127.0.0.1:18790`). Il n'y a pas de ports par canal à configurer. Note : Feishu utilise le mode WebSocket/SDK et n'utilise pas le serveur HTTP webhook partagé. @@ -14,14 +14,11 @@ Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, Matrix, QQ, Din | **Discord** | ⭐ Facile | Socket Mode, groupes/DM, écosystème bot riche | [Documentation](../channels/discord/README.fr.md) | | **WhatsApp** | ⭐ Facile | Natif (scan QR) ou Bridge URL | [Documentation](#whatsapp) | | **Weixin** | ⭐ Facile | Scan QR natif (API Tencent iLink) | [Documentation](#weixin) | -| **Slack** | ⭐ Facile | **Socket Mode** (pas d'IP publique requise), entreprise | [Documentation](../channels/slack/README.fr.md) | -| **Matrix** | ⭐⭐ Moyen | Protocole fédéré, auto-hébergement possible | [Documentation](../channels/matrix/README.fr.md) | | **QQ** | ⭐⭐ Moyen | API bot officielle, communauté chinoise | [Documentation](../channels/qq/README.fr.md) | | **DingTalk** | ⭐⭐ Moyen | Mode Stream (pas d'IP publique requise), entreprise | [Documentation](../channels/dingtalk/README.fr.md) | | **LINE** | ⭐⭐⭐ Avancé | HTTPS Webhook requis | [Documentation](../channels/line/README.fr.md) | | **WeCom (企业微信)** | ⭐⭐⭐ Avancé | Bot groupe (Webhook), app personnalisée (API), AI Bot | [Guide](../channels/wecom/README.fr.md) | | **Feishu (飞书)** | ⭐⭐⭐ Avancé | Collaboration entreprise, fonctionnalités riches | [Documentation](../channels/feishu/README.fr.md) | -| **IRC** | ⭐⭐ Moyen | Serveur + configuration TLS | [Documentation](#irc) | | **OneBot** | ⭐⭐ Moyen | Compatible NapCat/Go-CQHTTP, écosystème communautaire | [Documentation](../channels/onebot/README.fr.md) | | **MQTT** | ⭐ Facile | N'importe quel client MQTT via broker pub/sub | [Documentation](../channels/mqtt/README.fr.md) | @@ -294,42 +291,6 @@ picoclaw gateway ``` - -
-Matrix - -**1. Préparer le compte bot** - -* Utilisez votre homeserver préféré (par ex. `https://matrix.org` ou auto-hébergé) -* Créez un utilisateur bot et obtenez son access token - -**2. Configurer** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Lancer** - -```bash -picoclaw gateway -``` - -Pour toutes les options (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), voir le [Guide de Configuration du Canal Matrix](../channels/matrix/README.md). - -
-
LINE @@ -539,76 +500,6 @@ Pour toutes les options, voir le [Guide de Configuration du Canal Feishu](../cha
- -
-Slack - -**1. Créer une application Slack** - -* Allez sur [Slack API](https://api.slack.com/apps) et créez une nouvelle application -* Sous **OAuth & Permissions**, ajoutez les scopes bot : `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write` -* Installez l'application dans votre workspace -* Copiez le **Bot Token** (`xoxb-...`) et l'**App-Level Token** (`xapp-...`, activez Socket Mode pour l'obtenir) - -**2. Configurer** - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Lancer** - -```bash -picoclaw gateway -``` - -
- - -
-IRC - -**1. Configurer** - -```json -{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "picoclaw-bot", - "channels": ["#your-channel"], - "password": "", - "allow_from": [] - } - } -} -``` - -Optionnel : `nickserv_password` pour l'authentification NickServ, `sasl_user`/`sasl_password` pour l'authentification SASL. - -**2. Lancer** - -```bash -picoclaw gateway -``` - -Le bot se connectera au serveur IRC et rejoindra les canaux spécifiés. - -
-
OneBot (QQ via protocole OneBot) diff --git a/docs/guides/chat-apps.ja.md b/docs/guides/chat-apps.ja.md index a386500f..fd40a7a0 100644 --- a/docs/guides/chat-apps.ja.md +++ b/docs/guides/chat-apps.ja.md @@ -16,14 +16,11 @@ PicoClaw は複数のチャットプラットフォームをサポートして | **Discord** | ⭐ 簡単 | Socket Mode、グループ/DM 対応、Bot エコシステム充実 | [ドキュメント](../channels/discord/README.ja.md) | | **WhatsApp** | ⭐ 簡単 | ネイティブ (QR スキャン) または Bridge URL | [ドキュメント](#whatsapp) | | **微信 (Weixin)** | ⭐ 簡単 | ネイティブ QR スキャン(Tencent iLink API)| [ドキュメント](#weixin) | -| **Slack** | ⭐ 簡単 | **Socket Mode** (公開 IP 不要)、エンタープライズ対応 | [ドキュメント](../channels/slack/README.ja.md) | -| **Matrix** | ⭐⭐ 中程度 | フェデレーションプロトコル、セルフホスト対応 | [ドキュメント](../channels/matrix/README.ja.md) | | **QQ** | ⭐⭐ 中程度 | 公式ボット API、中国コミュニティ向け | [ドキュメント](../channels/qq/README.ja.md) | | **DingTalk** | ⭐⭐ 中程度 | Stream モード(公開 IP 不要)、企業向け | [ドキュメント](../channels/dingtalk/README.ja.md) | | **LINE** | ⭐⭐⭐ やや難 | HTTPS Webhook が必要 | [ドキュメント](../channels/line/README.ja.md) | | **WeCom (企業微信)** | ⭐⭐⭐ やや難 | グループ Bot (Webhook)、カスタムアプリ (API)、AI Bot 対応 | [ガイド](../channels/wecom/README.ja.md) | | **Feishu (飛書)** | ⭐⭐⭐ やや難 | エンタープライズコラボレーション、機能豊富 | [ドキュメント](../channels/feishu/README.ja.md) | -| **IRC** | ⭐⭐ 中程度 | サーバー + TLS 設定 | [ドキュメント](#irc) | | **OneBot** | ⭐⭐ 中程度 | NapCat/Go-CQHTTP 互換、コミュニティエコシステム充実 | [ドキュメント](../channels/onebot/README.ja.md) | | **MQTT** | ⭐ 簡単 | ブローカー経由で任意の MQTT クライアントと通信 | [ドキュメント](../channels/mqtt/README.ja.md) | @@ -213,42 +210,6 @@ picoclaw gateway
- -
-Matrix - -**1. Bot アカウントを準備** - -* お好みの homeserver(例: `https://matrix.org` またはセルフホスト)を使用 -* Bot ユーザーを作成し、access token を取得 - -**2. 設定** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. 実行** - -```bash -picoclaw gateway -``` - -すべてのオプション(`device_id`、`join_on_invite`、`group_trigger`、`placeholder`、`reasoning_channel_id`)については [Matrix チャネル設定ガイド](../channels/matrix/README.md) を参照してください。 - -
-
QQ @@ -292,76 +253,6 @@ QQ 開放プラットフォームでは、OpenClaw 互換ボットのワンク
- -
-Slack - -**1. Slack App を作成** - -* [Slack API](https://api.slack.com/apps) にアクセスして新しいアプリを作成 -* **OAuth & Permissions** で Bot スコープを追加:`chat:write`、`app_mentions:read`、`im:history`、`im:read`、`im:write` -* アプリをワークスペースにインストール -* **Bot Token**(`xoxb-...`)と **App-Level Token**(`xapp-...`、Socket Mode を有効にして取得)をコピー - -**2. 設定** - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN", - "allow_from": [] - } - } -} -``` - -**3. 実行** - -```bash -picoclaw gateway -``` - -
- - -
-IRC - -**1. 設定** - -```json -{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "picoclaw-bot", - "channels": ["#your-channel"], - "password": "", - "allow_from": [] - } - } -} -``` - -オプション:NickServ 認証用の `nickserv_password`、SASL 認証用の `sasl_user`/`sasl_password`。 - -**2. 実行** - -```bash -picoclaw gateway -``` - -ボットは IRC サーバーに接続し、指定されたチャネルに参加します。 - -
-
DingTalk diff --git a/docs/guides/chat-apps.md b/docs/guides/chat-apps.md index 3198c11b..bb9c632c 100644 --- a/docs/guides/chat-apps.md +++ b/docs/guides/chat-apps.md @@ -4,7 +4,7 @@ ## 💬 Chat Apps -Talk to your picoclaw through Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT +Talk to your picoclaw through Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT > **Note**: Channels that rely on HTTP callbacks share a single Gateway HTTP server (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Socket/stream-based channels such as Feishu, DingTalk, and WeCom do not rely on the shared webhook server for inbound delivery. @@ -14,14 +14,11 @@ Talk to your picoclaw through Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, | **Discord** | ⭐ Easy | Socket Mode, group/DM support, rich bot ecosystem | [Docs](../channels/discord/README.md) | | **WhatsApp** | ⭐ Easy | Native (QR scan) or Bridge URL | [Docs](#whatsapp) | | **Weixin** | ⭐ Easy | Native QR scan (Tencent iLink API) | [Docs](#weixin) | -| **Slack** | ⭐ Easy | **Socket Mode** (no public IP needed), enterprise | [Docs](../channels/slack/README.md) | -| **Matrix** | ⭐⭐ Medium | Federated protocol, self-hosting supported | [Docs](../channels/matrix/README.md) | | **QQ** | ⭐⭐ Medium | Official bot API, Chinese community | [Docs](../channels/qq/README.md) | | **DingTalk** | ⭐⭐ Medium | Stream mode (no public IP needed), enterprise | [Docs](../channels/dingtalk/README.md) | | **LINE** | ⭐⭐⭐ Advanced | HTTPS Webhook required | [Docs](../channels/line/README.md) | | **WeCom (企业微信)** | ⭐⭐⭐ Advanced | Official AI Bot over WebSocket, streaming + media | [Docs](../channels/wecom/README.md) | | **Feishu (飞书)** | ⭐⭐⭐ Advanced | Enterprise collaboration, feature-rich | [Docs](../channels/feishu/README.md) | -| **IRC** | ⭐⭐ Medium | Server + TLS configuration | [Docs](#irc) | | **OneBot** | ⭐⭐ Medium | NapCat/Go-CQHTTP compatible, community ecosystem | [Docs](../channels/onebot/README.md) | | **MQTT** | ⭐ Easy | Any MQTT client via broker pub/sub | [Docs](../channels/mqtt/README.md) | @@ -300,42 +297,6 @@ picoclaw gateway ```
- -
-Matrix - -**1. Prepare bot account** - -* Use your preferred homeserver (e.g. `https://matrix.org` or self-hosted) -* Create a bot user and obtain its access token - -**2. Configure** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Run** - -```bash -picoclaw gateway -``` - -For full options (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), see [Matrix Channel Configuration Guide](../channels/matrix/README.md). - -
-
LINE @@ -477,76 +438,6 @@ For full options, see [Feishu Channel Configuration Guide](../channels/feishu/RE
- -
-Slack - -**1. Create a Slack app** - -* Go to [Slack API](https://api.slack.com/apps) and create a new app -* Under **OAuth & Permissions**, add bot scopes: `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write` -* Install the app to your workspace -* Copy the **Bot Token** (`xoxb-...`) and **App-Level Token** (`xapp-...`, enable Socket Mode to get this) - -**2. Configure** - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Run** - -```bash -picoclaw gateway -``` - -
- - -
-IRC - -**1. Configure** - -```json -{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "picoclaw-bot", - "channels": ["#your-channel"], - "password": "", - "allow_from": [] - } - } -} -``` - -Optional: `nickserv_password` for NickServ authentication, `sasl_user`/`sasl_password` for SASL auth. - -**2. Run** - -```bash -picoclaw gateway -``` - -The bot will connect to the IRC server and join the specified channels. - -
-
OneBot (QQ via OneBot protocol) diff --git a/docs/guides/chat-apps.ms.md b/docs/guides/chat-apps.ms.md index e4905f15..6af63bd5 100644 --- a/docs/guides/chat-apps.ms.md +++ b/docs/guides/chat-apps.ms.md @@ -4,7 +4,7 @@ ## 💬 Aplikasi Sembang -Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT +Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT > **Nota**: Semua saluran berasaskan webhook (LINE, WeCom, dan sebagainya) diservis pada satu pelayan HTTP Gateway yang dikongsi (`gateway.host`:`gateway.port`, lalai `127.0.0.1:18790`). Tiada port khusus per saluran untuk dikonfigurasikan. Nota: Feishu menggunakan mod WebSocket/SDK dan tidak menggunakan pelayan HTTP webhook yang dikongsi. @@ -13,14 +13,11 @@ Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, Matrix, QQ, Di | **Telegram** | Mudah (hanya token) | | **Discord** | Mudah (token bot + intents) | | **WhatsApp** | Mudah (asli: imbas QR; atau bridge URL) | -| **Matrix** | Sederhana (homeserver + access token bot) | | **QQ** | Mudah (AppID + AppSecret) | | **DingTalk** | Sederhana (kelayakan aplikasi) | | **LINE** | Sederhana (kelayakan + webhook URL) | | **WeCom AI Bot** | Sederhana (Token + kunci AES) | | **Feishu** | Sederhana (App ID + Secret, mod WebSocket) | -| **Slack** | Sederhana (Bot token + App token) | -| **IRC** | Sederhana (pelayan + konfigurasi TLS) | | **OneBot** | Sederhana (QQ melalui protokol OneBot) | | **MQTT** | Mudah (broker + agent_id) | @@ -247,41 +244,6 @@ picoclaw gateway ```
-
-Matrix - -**1. Sediakan akaun bot** - -* Gunakan homeserver pilihan anda (contohnya `https://matrix.org` atau self-hosted) -* Cipta pengguna bot dan dapatkan access tokennya - -**2. Konfigurasi** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Jalankan** - -```bash -picoclaw gateway -``` - -Untuk pilihan penuh (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), lihat [Panduan Konfigurasi Saluran Matrix](../channels/matrix/README.md). - -
-
LINE diff --git a/docs/guides/chat-apps.pt-br.md b/docs/guides/chat-apps.pt-br.md index 76c6af5a..8d8c75b9 100644 --- a/docs/guides/chat-apps.pt-br.md +++ b/docs/guides/chat-apps.pt-br.md @@ -4,7 +4,7 @@ ## 💬 Aplicativos de Chat -Converse com seu picoclaw através do Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT +Converse com seu picoclaw através do Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT > **Nota**: Todos os canais baseados em webhook (LINE, WeCom, etc.) são servidos em um único servidor HTTP Gateway compartilhado (`gateway.host`:`gateway.port`, padrão `127.0.0.1:18790`). Não há portas por canal para configurar. Nota: Feishu usa o modo WebSocket/SDK e não utiliza o servidor HTTP webhook compartilhado. @@ -14,14 +14,11 @@ Converse com seu picoclaw através do Telegram, Discord, WhatsApp, Matrix, QQ, D | **Discord** | ⭐ Fácil | Socket Mode, suporte a grupos/DM, ecossistema bot rico | [Documentação](../channels/discord/README.pt-br.md) | | **WhatsApp** | ⭐ Fácil | Nativo (scan QR) ou Bridge URL | [Documentação](#whatsapp) | | **Weixin** | ⭐ Fácil | Scan QR nativo (API Tencent iLink) | [Documentação](#weixin) | -| **Slack** | ⭐ Fácil | **Socket Mode** (sem IP público), empresarial | [Documentação](../channels/slack/README.pt-br.md) | -| **Matrix** | ⭐⭐ Médio | Protocolo federado, suporte a auto-hospedagem | [Documentação](../channels/matrix/README.pt-br.md) | | **QQ** | ⭐⭐ Médio | API bot oficial, comunidade chinesa | [Documentação](../channels/qq/README.pt-br.md) | | **DingTalk** | ⭐⭐ Médio | Modo Stream (sem IP público), empresarial | [Documentação](../channels/dingtalk/README.pt-br.md) | | **LINE** | ⭐⭐⭐ Avançado | HTTPS Webhook obrigatório | [Documentação](../channels/line/README.pt-br.md) | | **WeCom (企业微信)** | ⭐⭐⭐ Avançado | Bot de grupo (Webhook), app personalizado (API), AI Bot | [Guia](../channels/wecom/README.pt-br.md) | | **Feishu (飞书)** | ⭐⭐⭐ Avançado | Colaboração empresarial, rico em recursos | [Documentação](../channels/feishu/README.pt-br.md) | -| **IRC** | ⭐⭐ Médio | Servidor + configuração TLS | [Documentação](#irc) | | **OneBot** | ⭐⭐ Médio | Compatível com NapCat/Go-CQHTTP, ecossistema comunitário | [Documentação](../channels/onebot/README.pt-br.md) | | **MQTT** | ⭐ Fácil | Qualquer cliente MQTT via broker pub/sub | [Documentação](../channels/mqtt/README.pt-br.md) | @@ -295,42 +292,6 @@ picoclaw gateway
- -
-Matrix - -**1. Preparar conta do bot** - -* Use seu homeserver preferido (ex.: `https://matrix.org` ou auto-hospedado) -* Crie um usuário bot e obtenha seu access token - -**2. Configurar** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Executar** - -```bash -picoclaw gateway -``` - -Para opções completas (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), veja o [Guia de Configuração do Canal Matrix](../channels/matrix/README.md). - -
-
LINE @@ -539,76 +500,6 @@ Para opções completas, veja o [Guia de Configuração do Canal Feishu](../chan
- -
-Slack - -**1. Criar um aplicativo Slack** - -* Acesse a [Slack API](https://api.slack.com/apps) e crie um novo aplicativo -* Em **OAuth & Permissions**, adicione os escopos do bot: `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write` -* Instale o aplicativo no seu workspace -* Copie o **Bot Token** (`xoxb-...`) e o **App-Level Token** (`xapp-...`, habilite Socket Mode para obtê-lo) - -**2. Configurar** - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Executar** - -```bash -picoclaw gateway -``` - -
- - -
-IRC - -**1. Configurar** - -```json -{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "picoclaw-bot", - "channels": ["#your-channel"], - "password": "", - "allow_from": [] - } - } -} -``` - -Opcional: `nickserv_password` para autenticação NickServ, `sasl_user`/`sasl_password` para autenticação SASL. - -**2. Executar** - -```bash -picoclaw gateway -``` - -O bot se conectará ao servidor IRC e entrará nos canais especificados. - -
-
OneBot (QQ via protocolo OneBot) diff --git a/docs/guides/chat-apps.vi.md b/docs/guides/chat-apps.vi.md index 14f99049..d630a522 100644 --- a/docs/guides/chat-apps.vi.md +++ b/docs/guides/chat-apps.vi.md @@ -4,7 +4,7 @@ ## 💬 Ứng Dụng Chat -Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT +Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT > **Lưu ý**: Tất cả các kênh dựa trên webhook (LINE, WeCom, v.v.) được phục vụ trên một máy chủ HTTP Gateway chung (`gateway.host`:`gateway.port`, mặc định `127.0.0.1:18790`). Không có port riêng cho từng kênh. Lưu ý: Feishu sử dụng chế độ WebSocket/SDK và không sử dụng máy chủ HTTP webhook chung. @@ -14,14 +14,11 @@ Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, Matrix | **Discord** | ⭐ Dễ | Socket Mode, hỗ trợ nhóm/DM, hệ sinh thái bot phong phú | [Tài liệu](../channels/discord/README.vi.md) | | **WhatsApp** | ⭐ Dễ | Bản địa (quét QR) hoặc Bridge URL | [Tài liệu](#whatsapp) | | **Weixin** | ⭐ Dễ | Quét QR gốc (API Tencent iLink) | [Tài liệu](#weixin) | -| **Slack** | ⭐ Dễ | **Socket Mode** (không cần IP công khai), doanh nghiệp | [Tài liệu](../channels/slack/README.vi.md) | -| **Matrix** | ⭐⭐ Trung bình | Giao thức liên kết, hỗ trợ tự lưu trữ | [Tài liệu](../channels/matrix/README.vi.md) | | **QQ** | ⭐⭐ Trung bình | API bot chính thức, cộng đồng Trung Quốc | [Tài liệu](../channels/qq/README.vi.md) | | **DingTalk** | ⭐⭐ Trung bình | Chế độ Stream (không cần IP công khai), doanh nghiệp | [Tài liệu](../channels/dingtalk/README.vi.md) | | **LINE** | ⭐⭐⭐ Nâng cao | Yêu cầu HTTPS Webhook | [Tài liệu](../channels/line/README.vi.md) | | **WeCom (企业微信)** | ⭐⭐⭐ Nâng cao | Bot nhóm (Webhook), ứng dụng tùy chỉnh (API), AI Bot | [Hướng dẫn](../channels/wecom/README.vi.md) | | **Feishu (飞书)** | ⭐⭐⭐ Nâng cao | Cộng tác doanh nghiệp, nhiều tính năng | [Tài liệu](../channels/feishu/README.vi.md) | -| **IRC** | ⭐⭐ Trung bình | Máy chủ + cấu hình TLS | [Tài liệu](#irc) | | **OneBot** | ⭐⭐ Trung bình | Tương thích NapCat/Go-CQHTTP, hệ sinh thái cộng đồng | [Tài liệu](../channels/onebot/README.vi.md) | | **MQTT** | ⭐ Dễ | Bất kỳ client MQTT nào qua broker pub/sub | [Tài liệu](../channels/mqtt/README.vi.md) | @@ -295,42 +292,6 @@ picoclaw gateway
- -
-Matrix - -**1. Chuẩn bị tài khoản bot** - -* Sử dụng homeserver ưa thích (ví dụ: `https://matrix.org` hoặc tự host) -* Tạo user bot và lấy access token - -**2. Cấu hình** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Chạy** - -```bash -picoclaw gateway -``` - -Để xem đầy đủ các tùy chọn (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), xem [Hướng Dẫn Cấu Hình Kênh Matrix](../channels/matrix/README.md). - -
-
LINE @@ -540,76 +501,6 @@ Mở Feishu, tìm tên bot của bạn và bắt đầu trò chuyện. Bạn cũ
- -
-Slack - -**1. Tạo ứng dụng Slack** - -* Truy cập [Slack API](https://api.slack.com/apps) và tạo ứng dụng mới -* Trong **OAuth & Permissions**, thêm các scope bot: `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write` -* Cài đặt ứng dụng vào workspace của bạn -* Sao chép **Bot Token** (`xoxb-...`) và **App-Level Token** (`xapp-...`, bật Socket Mode để lấy token này) - -**2. Cấu hình** - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN", - "allow_from": [] - } - } -} -``` - -**3. Chạy** - -```bash -picoclaw gateway -``` - -
- - -
-IRC - -**1. Cấu hình** - -```json -{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "picoclaw-bot", - "channels": ["#your-channel"], - "password": "", - "allow_from": [] - } - } -} -``` - -Tùy chọn: `nickserv_password` để xác thực NickServ, `sasl_user`/`sasl_password` để xác thực SASL. - -**2. Chạy** - -```bash -picoclaw gateway -``` - -Bot sẽ kết nối đến máy chủ IRC và tham gia các kênh đã chỉ định. - -
-
OneBot (QQ qua giao thức OneBot) diff --git a/docs/guides/chat-apps.zh.md b/docs/guides/chat-apps.zh.md index b2b2c73a..f32a2410 100644 --- a/docs/guides/chat-apps.zh.md +++ b/docs/guides/chat-apps.zh.md @@ -4,7 +4,7 @@ ## 💬 聊天应用集成 (Chat Apps) -PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、Discord、WhatsApp、微信、QQ、钉钉、LINE、企业微信、飞书、Slack、IRC、OneBot、MQTT 等。 +PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、Discord、WhatsApp、微信、QQ、钉钉、LINE、企业微信、飞书、OneBot、MQTT 等。 > **注意**: 依赖 HTTP 回调的渠道共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`),无需为每个渠道单独配置端口。飞书、钉钉、企业微信这类 Socket/Stream 模式渠道不依赖共享 webhook 服务器来接收入站消息。 @@ -16,14 +16,11 @@ PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方 | **Discord** | ⭐ 简单 | Socket Mode,支持群组/私信,Bot 生态成熟 | [查看文档](../channels/discord/README.zh.md) | | **WhatsApp** | ⭐ 简单 | 原生 (QR 扫码) 或 Bridge URL | [查看文档](#whatsapp) | | **微信 (Weixin)** | ⭐ 简单 | 原生扫码(腾讯 iLink API) | [查看文档](#weixin) | -| **Slack** | ⭐ 简单 | **Socket Mode** (无需公网 IP),企业级支持 | [查看文档](../channels/slack/README.zh.md) | -| **Matrix** | ⭐⭐ 中等 | 联邦协议,支持自建 homeserver 与公开服务器 | [查看文档](../channels/matrix/README.zh.md) | | **QQ** | ⭐⭐ 中等 | 官方机器人 API,适合国内社群 | [查看文档](../channels/qq/README.zh.md) | | **钉钉 (DingTalk)** | ⭐⭐ 中等 | Stream 模式无需公网,企业办公首选 | [查看文档](../channels/dingtalk/README.zh.md) | | **LINE** | ⭐⭐⭐ 较难 | 需要 HTTPS Webhook | [查看文档](../channels/line/README.zh.md) | | **企业微信 (WeCom)** | ⭐⭐⭐ 较难 | 官方 AI Bot WebSocket 接入,支持流式回复和媒体消息 | [查看文档](../channels/wecom/README.zh.md) | | **飞书 (Feishu)** | ⭐⭐⭐ 较难 | 企业级协作,功能丰富 | [查看文档](../channels/feishu/README.zh.md) | -| **IRC** | ⭐⭐ 中等 | 服务器 + TLS 配置 | [查看文档](#irc) | | **OneBot** | ⭐⭐ 中等 | 兼容 NapCat/Go-CQHTTP,社区生态丰富 | [查看文档](../channels/onebot/README.zh.md) | | **MQTT** | ⭐ 简单 | 任意 MQTT 客户端通过 Broker 收发消息 | [查看文档](../channels/mqtt/README.zh.md) | @@ -221,42 +218,6 @@ picoclaw gateway
- -
-Matrix - -**1. 准备 Bot 账号** - -* 使用你的 homeserver(如 `https://matrix.org` 或自建) -* 创建 Bot 用户并获取 access token - -**2. 配置** - -```json -{ - "channel_list": { - "matrix": { - "enabled": true, - "type": "matrix", - "homeserver": "https://matrix.org", - "user_id": "@your-bot:matrix.org", - "access_token": "YOUR_MATRIX_ACCESS_TOKEN", - "allow_from": [] - } - } -} -``` - -**3. 运行** - -```bash -picoclaw gateway -``` - -完整选项(`device_id`、`join_on_invite`、`group_trigger`、`placeholder`、`reasoning_channel_id`)请参考 [Matrix 渠道配置指南](../channels/matrix/README.md)。 - -
-
QQ @@ -300,76 +261,6 @@ QQ 开放平台提供了一键创建 OpenClaw 兼容机器人的页面:
- -
-Slack - -**1. 创建 Slack App** - -* 前往 [Slack API](https://api.slack.com/apps) 创建新应用 -* 在 **OAuth & Permissions** 中添加 Bot 权限范围:`chat:write`、`app_mentions:read`、`im:history`、`im:read`、`im:write` -* 将应用安装到你的工作区 -* 复制 **Bot Token**(`xoxb-...`)和 **App-Level Token**(`xapp-...`,启用 Socket Mode 后获取) - -**2. 配置** - -```json -{ - "channel_list": { - "slack": { - "enabled": true, - "type": "slack", - "bot_token": "xoxb-YOUR-BOT-TOKEN", - "app_token": "xapp-YOUR-APP-TOKEN", - "allow_from": [] - } - } -} -``` - -**3. 运行** - -```bash -picoclaw gateway -``` - -
- - -
-IRC - -**1. 配置** - -```json -{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "server": "irc.libera.chat:6697", - "tls": true, - "nick": "picoclaw-bot", - "channels": ["#your-channel"], - "password": "", - "allow_from": [] - } - } -} -``` - -可选:`nickserv_password` 用于 NickServ 认证,`sasl_user`/`sasl_password` 用于 SASL 认证。 - -**2. 运行** - -```bash -picoclaw gateway -``` - -Bot 将连接到 IRC 服务器并加入指定的频道。 - -
-
钉钉 (DingTalk) diff --git a/docs/guides/routing-guide.md b/docs/guides/routing-guide.md index a4798432..6ed4df99 100644 --- a/docs/guides/routing-guide.md +++ b/docs/guides/routing-guide.md @@ -36,7 +36,7 @@ This guide explains how to configure both for real deployments. } ``` -### Route only Slack mentions in one workspace +### Route only Discord mentions in one workspace ```json { @@ -48,11 +48,11 @@ This guide explains how to configure both for real deployments. "dispatch": { "rules": [ { - "name": "slack mentions", + "name": "discord mentions", "agent": "support", "when": { - "channel": "slack", - "space": "workspace:t001", + "channel": "discord", + "space": "guild:t001", "mentioned": true } } @@ -109,9 +109,9 @@ If no rule matches, PicoClaw falls back to the default agent. | Field | Meaning | Example | | --- | --- | --- | -| `channel` | Channel name | `telegram`, `slack`, `discord` | +| `channel` | Channel name | `telegram`, `discord`, `feishu` | | `account` | Normalized account ID | `default`, `bot2` | -| `space` | Workspace, guild, or similar container | `workspace:t001`, `guild:123456` | +| `space` | Workspace, guild, or similar container | `guild:t001`, `guild:123456` | | `chat` | Direct chat, group, or channel | `direct:user123`, `group:-100123`, `channel:c123` | | `topic` | Thread or topic | `topic:42` | | `sender` | Normalized sender identity | `12345`, `john` | @@ -202,7 +202,7 @@ Example: { "session": { "identity_links": { - "john": ["slack:u123", "legacy-user-42"] + "john": ["discord:u123", "legacy-user-42"] } }, "agents": { diff --git a/docs/guides/routing-guide.zh.md b/docs/guides/routing-guide.zh.md index 713cbeb0..e93b5a96 100644 --- a/docs/guides/routing-guide.zh.md +++ b/docs/guides/routing-guide.zh.md @@ -36,7 +36,7 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分: } ``` -### 只处理某个 Slack workspace 里的 @提及 +### 只处理某个 Discord server 里的 @提及 ```json { @@ -48,11 +48,11 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分: "dispatch": { "rules": [ { - "name": "slack mentions", + "name": "discord mentions", "agent": "support", "when": { - "channel": "slack", - "space": "workspace:t001", + "channel": "discord", + "space": "guild:t001", "mentioned": true } } @@ -109,9 +109,9 @@ agents.dispatch.rules | 字段 | 含义 | 示例 | | --- | --- | --- | -| `channel` | Channel 名称 | `telegram`、`slack`、`discord` | +| `channel` | Channel 名称 | `telegram`、`discord`、`feishu` | | `account` | 归一化后的 account ID | `default`、`bot2` | -| `space` | workspace、guild 等上层容器 | `workspace:t001`、`guild:123456` | +| `space` | workspace、guild 等上层容器 | `guild:t001`、`guild:123456` | | `chat` | 私聊、群或频道 | `direct:user123`、`group:-100123`、`channel:c123` | | `topic` | 线程或话题 | `topic:42` | | `sender` | 归一化后的发送者身份 | `12345`、`john` | @@ -202,7 +202,7 @@ agents.dispatch.rules { "session": { "identity_links": { - "john": ["slack:u123", "legacy-user-42"] + "john": ["discord:u123", "legacy-user-42"] } }, "agents": { diff --git a/docs/guides/session-guide.md b/docs/guides/session-guide.md index 3f375926..70ee2a24 100644 --- a/docs/guides/session-guide.md +++ b/docs/guides/session-guide.md @@ -73,7 +73,7 @@ If your channel exposes a `space` value, you can route by workspace or guild ins Use this when: -- a Slack workspace assistant should share context across channels +- a Discord server assistant should share context across channels - a Discord guild assistant should share context across channels ### Split by thread or forum topic @@ -212,7 +212,7 @@ Example: "session": { "dimensions": ["chat", "sender"], "identity_links": { - "john": ["slack:u123", "u123", "legacy-user-42"] + "john": ["discord:u123", "u123", "legacy-user-42"] } } } @@ -244,7 +244,7 @@ Switch to: } ``` -### The same user does not share memory across Slack and Telegram +### The same user does not share memory across Discord and Telegram That is expected. PicoClaw still separates sessions by channel even if you use `sender`. diff --git a/docs/guides/session-guide.zh.md b/docs/guides/session-guide.zh.md index 679a7f68..6b4280d0 100644 --- a/docs/guides/session-guide.zh.md +++ b/docs/guides/session-guide.zh.md @@ -73,7 +73,7 @@ Session 数据保存在工作区目录下,通常是: 适用场景: -- Slack workspace 里的 assistant 想跨多个 channel 共享上下文 +- Discord server 里的 assistant 想跨多个 channel 共享上下文 - Discord guild 里的 assistant 想跨多个 channel 共享上下文 ### 按线程或论坛 topic 隔离 @@ -212,7 +212,7 @@ Telegram forum 消息在默认 `chat` 模式下就会保留 topic 隔离。 "session": { "dimensions": ["chat", "sender"], "identity_links": { - "john": ["slack:u123", "u123", "legacy-user-42"] + "john": ["discord:u123", "u123", "legacy-user-42"] } } } @@ -244,7 +244,7 @@ Telegram forum 消息在默认 `chat` 模式下就会保留 topic 隔离。 } ``` -### 同一个用户在 Slack 和 Telegram 之间没有共享记忆 +### 同一个用户在 Discord 和 Telegram 之间没有共享记忆 这是当前实现下的预期行为。 即使使用了 `sender`,PicoClaw 仍然会按 channel 做基础隔离。 diff --git a/docs/project/README.fr.md b/docs/project/README.fr.md index 6d1b09d1..221522f0 100644 --- a/docs/project/README.fr.md +++ b/docs/project/README.fr.md @@ -30,7 +30,6 @@ **Fonctionne sur du matériel à $10 avec <10 Mo de RAM** — c'est 99% de mémoire en moins qu'OpenClaw et 98% moins cher qu'un Mac mini ! -
@@ -84,7 +83,6 @@ - ## ✨ Fonctionnalités 🪶 **Ultra-léger** : Empreinte mémoire du cœur <10 Mo — 99% plus petit qu'OpenClaw.* @@ -157,7 +155,6 @@ PicoClaw peut être déployé sur pratiquement n'importe quel appareil Linux ! 🌟 D'autres cas de déploiement vous attendent ! - ## 📦 Installation ### Télécharger depuis picoclaw.io (Recommandé) @@ -372,13 +369,10 @@ Parlez à votre PicoClaw via plus de 17 plateformes de messagerie : | **WhatsApp** | Facile (scan QR ou URL bridge) | Natif / Bridge | [Guide](../guides/chat-apps.fr.md#whatsapp) | | **Weixin** | Facile (scan QR natif) | iLink API | [Guide](../guides/chat-apps.fr.md#weixin) | | **QQ** | Facile (AppID + AppSecret) | WebSocket | [Guide](../channels/qq/README.fr.md) | -| **Slack** | Facile (token bot + app) | Socket Mode | [Guide](../channels/slack/README.fr.md) | -| **Matrix** | Moyen (homeserver + token) | Sync API | [Guide](../channels/matrix/README.fr.md) | | **DingTalk** | Moyen (identifiants client) | Stream | [Guide](../channels/dingtalk/README.fr.md) | | **Feishu / Lark** | Moyen (App ID + Secret) | WebSocket/SDK | [Guide](../channels/feishu/README.fr.md) | | **LINE** | Moyen (identifiants + webhook) | Webhook | [Guide](../channels/line/README.fr.md) | | **WeCom** | Facile (QR login ou manuel) | WebSocket | [Guide](../channels/wecom/README.fr.md) | -| **IRC** | Moyen (serveur + pseudo) | Protocole IRC | [Guide](../guides/chat-apps.fr.md#irc) | | **OneBot** | Moyen (URL WebSocket) | OneBot v11 | [Guide](../channels/onebot/README.fr.md) | > Tous les channels basés sur webhook partagent un seul serveur HTTP Gateway (`gateway.host`:`gateway.port`, par défaut `127.0.0.1:18790`). Feishu utilise le mode WebSocket/SDK et n'utilise pas le serveur HTTP partagé. diff --git a/docs/project/README.id.md b/docs/project/README.id.md index 607f3582..0a004ffd 100644 --- a/docs/project/README.id.md +++ b/docs/project/README.id.md @@ -368,13 +368,10 @@ Bicara dengan PicoClaw Anda melalui 17+ platform pesan: | **WhatsApp** | Mudah (scan QR atau bridge URL) | Native / Bridge | [Panduan](../guides/chat-apps.md#whatsapp) | | **Weixin** | Mudah (scan QR native) | iLink API | [Panduan](../guides/chat-apps.md#weixin) | | **QQ** | Mudah (AppID + AppSecret) | WebSocket | [Panduan](../channels/qq/README.md) | -| **Slack** | Mudah (bot + app token) | Socket Mode | [Panduan](../channels/slack/README.md) | -| **Matrix** | Sedang (homeserver + token) | Sync API | [Panduan](../channels/matrix/README.md) | | **DingTalk** | Sedang (client credentials) | Stream | [Panduan](../channels/dingtalk/README.md) | | **Feishu / Lark** | Sedang (App ID + Secret) | WebSocket/SDK | [Panduan](../channels/feishu/README.md) | | **LINE** | Sedang (credentials + webhook) | Webhook | [Panduan](../channels/line/README.md) | | **WeCom** | Mudah (login QR atau manual) | WebSocket | [Panduan](../channels/wecom/README.md) | -| **IRC** | Sedang (server + nick) | IRC protocol | [Panduan](../guides/chat-apps.md#irc) | | **OneBot** | Sedang (WebSocket URL) | OneBot v11 | [Panduan](../channels/onebot/README.md) | > Semua channel berbasis webhook berbagi satu server HTTP Gateway (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Feishu menggunakan mode WebSocket/SDK dan tidak menggunakan server HTTP bersama. diff --git a/docs/project/README.it.md b/docs/project/README.it.md index 3d8dfab6..35f556a5 100644 --- a/docs/project/README.it.md +++ b/docs/project/README.it.md @@ -368,13 +368,10 @@ Parla con il tuo PicoClaw attraverso 17+ piattaforme di messaggistica: | **WhatsApp** | Facile (QR scan o bridge URL) | Nativo / Bridge | [Guida](../guides/chat-apps.md#whatsapp) | | **Weixin** | Facile (scan QR nativo) | iLink API | [Guida](../guides/chat-apps.md#weixin) | | **QQ** | Facile (AppID + AppSecret) | WebSocket | [Guida](../channels/qq/README.md) | -| **Slack** | Facile (bot + app token) | Socket Mode | [Guida](../channels/slack/README.md) | -| **Matrix** | Medio (homeserver + token) | Sync API | [Guida](../channels/matrix/README.md) | | **DingTalk** | Medio (credenziali client) | Stream | [Guida](../channels/dingtalk/README.md) | | **Feishu / Lark** | Medio (App ID + Secret) | WebSocket/SDK | [Guida](../channels/feishu/README.md) | | **LINE** | Medio (credenziali + webhook) | Webhook | [Guida](../channels/line/README.md) | | **WeCom** | Facile (login QR o manuale) | WebSocket | [Guida](../channels/wecom/README.md) | -| **IRC** | Medio (server + nick) | Protocollo IRC | [Guida](../guides/chat-apps.md#irc) | | **OneBot** | Medio (WebSocket URL) | OneBot v11 | [Guida](../channels/onebot/README.md) | > Tutti i channel basati su webhook condividono un singolo server HTTP Gateway (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Feishu usa la modalità WebSocket/SDK e non usa il server HTTP condiviso. diff --git a/docs/project/README.ja.md b/docs/project/README.ja.md index 53f07cb4..8eccdd1f 100644 --- a/docs/project/README.ja.md +++ b/docs/project/README.ja.md @@ -369,13 +369,10 @@ Provider の完全な設定詳細は [Provider とモデル](../guides/providers | **WhatsApp** | 簡単(QR スキャンまたは bridge URL) | Native / Bridge | [ガイド](../guides/chat-apps.ja.md#whatsapp) | | **微信 (Weixin)** | 簡単(QR スキャン) | iLink API | [ガイド](../guides/chat-apps.ja.md#weixin) | | **QQ** | 簡単(AppID + AppSecret) | WebSocket | [ガイド](../channels/qq/README.ja.md) | -| **Slack** | 簡単(bot + app トークン) | Socket Mode | [ガイド](../channels/slack/README.ja.md) | -| **Matrix** | 中級(homeserver + トークン) | Sync API | [ガイド](../channels/matrix/README.ja.md) | | **DingTalk** | 中級(クライアント認証情報) | Stream | [ガイド](../channels/dingtalk/README.ja.md) | | **Feishu / Lark** | 中級(App ID + Secret) | WebSocket/SDK | [ガイド](../channels/feishu/README.ja.md) | | **LINE** | 中級(認証情報 + webhook) | Webhook | [ガイド](../channels/line/README.ja.md) | | **WeCom** | 簡単(QR ログインまたは手動) | WebSocket | [ガイド](../channels/wecom/README.ja.md) | -| **IRC** | 中級(サーバー + nick) | IRC protocol | [ガイド](../guides/chat-apps.ja.md#irc) | | **OneBot** | 中級(WebSocket URL) | OneBot v11 | [ガイド](../channels/onebot/README.ja.md) | > webhook ベースのすべての Channel は単一の Gateway HTTP サーバー(`gateway.host`:`gateway.port`、デフォルト `127.0.0.1:18790`)を共有します。Feishu は WebSocket/SDK モードを使用し、共有 HTTP サーバーを使用しません。 diff --git a/docs/project/README.ko.md b/docs/project/README.ko.md index f3835018..644a0010 100644 --- a/docs/project/README.ko.md +++ b/docs/project/README.ko.md @@ -371,14 +371,10 @@ PicoClaw는 `model_list` 설정을 통해 30개 이상의 LLM 프로바이더를 | **WhatsApp** | 쉬움(QR 스캔 또는 브리지 URL) | Native / Bridge | [가이드](../guides/chat-apps.md#whatsapp) | | **Weixin** | 쉬움(네이티브 QR 스캔) | iLink API | [가이드](../guides/chat-apps.md#weixin) | | **QQ** | 쉬움(AppID + AppSecret) | WebSocket | [가이드](../channels/qq/README.md) | -| **Slack** | 쉬움(봇 + 앱 토큰) | Socket Mode | [가이드](../channels/slack/README.md) | -| **Matrix** | 중간(homeserver + 토큰) | Sync API | [가이드](../channels/matrix/README.md) | | **DingTalk** | 중간(클라이언트 자격 증명) | Stream | [가이드](../channels/dingtalk/README.md) | | **Feishu / Lark** | 중간(App ID + Secret) | WebSocket/SDK | [가이드](../channels/feishu/README.md) | | **LINE** | 중간(인증 정보 + webhook) | Webhook | [가이드](../channels/line/README.md) | | **WeCom** | 쉬움(QR 로그인 또는 수동 설정) | WebSocket | [가이드](../channels/wecom/README.md) | -| **VK** | 쉬움(그룹 토큰) | Long Poll | [가이드](../channels/vk/README.md) | -| **IRC** | 중간(서버 + 닉네임) | IRC protocol | [가이드](../guides/chat-apps.md#irc) | | **OneBot** | 중간(WebSocket URL) | OneBot v11 | [가이드](../channels/onebot/README.md) | > webhook 기반 채널은 모두 하나의 게이트웨이 HTTP 서버(`gateway.host`:`gateway.port`, 기본값 `127.0.0.1:18790`)를 공유합니다. Feishu는 WebSocket/SDK 모드를 사용하며 이 공용 HTTP 서버를 사용하지 않습니다. diff --git a/docs/project/README.ms.md b/docs/project/README.ms.md index 4e5b9a39..4d5d8c19 100644 --- a/docs/project/README.ms.md +++ b/docs/project/README.ms.md @@ -53,7 +53,6 @@ > * **BERHATI-HATI:** Banyak domain `.ai/.org/.com/.net/...` telah didaftarkan oleh pihak ketiga. Jangan percayai mereka. > * **NOTA:** PicoClaw dalam pembangunan pesat awal. Mungkin terdapat isu keselamatan yang belum diselesaikan. Jangan deploy ke pengeluaran sebelum v1.0. - ## 📢 Berita 2026-05-11 🛒 **LicheeRV-Claw tersedia di AliExpress!** Anda kini boleh membeli LicheeRV-Claw di [AliExpress](https://www.aliexpress.com/item/1005006519668532.html), menjadikannya lebih mudah untuk mencuba PicoClaw pada perkakasan RISC-V yang kompak. @@ -155,7 +154,6 @@ PicoClaw boleh digunakan pada hampir mana-mana peranti Linux! 🌟 Lebih Banyak Kes Deployment Menanti! - ## 📦 Pemasangan ### Muat turun dari picoclaw.io (Disyorkan) @@ -357,7 +355,6 @@ Untuk butiran konfigurasi penyedia penuh, lihat [Penyedia & Model](../guides/pro - ## 💬 Saluran (Aplikasi Sembang) Bercakap dengan PicoClaw anda melalui 17+ platform pemesejan: @@ -369,13 +366,10 @@ Bercakap dengan PicoClaw anda melalui 17+ platform pemesejan: | **WhatsApp** | Mudah (imbas QR atau URL jambatan) | Natif / Jambatan | [Panduan](../guides/chat-apps.ms.md#whatsapp) | | **Weixin** | Mudah (imbas QR natif) | iLink API | [Panduan](../guides/chat-apps.ms.md#weixin) | | **QQ** | Mudah (AppID + AppSecret) | WebSocket | [Panduan](../channels/qq/README.md) | -| **Slack** | Mudah (token bot + app) | Socket Mode | [Panduan](../channels/slack/README.md) | -| **Matrix** | Sederhana (homeserver + token) | Sync API | [Panduan](../channels/matrix/README.md) | | **DingTalk** | Sederhana (kelayakan klien) | Stream | [Panduan](../channels/dingtalk/README.md) | | **Feishu / Lark** | Sederhana (App ID + Secret) | WebSocket/SDK | [Panduan](../channels/feishu/README.md) | | **LINE** | Sederhana (kelayakan + webhook) | Webhook | [Panduan](../channels/line/README.md) | | **WeCom** | Mudah (log masuk QR atau manual) | WebSocket | [Panduan](../channels/wecom/README.md) | -| **IRC** | Sederhana (pelayan + nick) | Protokol IRC | [Panduan](../guides/chat-apps.ms.md#irc) | | **OneBot** | Sederhana (URL WebSocket) | OneBot v11 | [Panduan](../channels/onebot/README.md) | > Semua saluran berasaskan webhook berkongsi satu pelayan HTTP Gateway (`gateway.host`:`gateway.port`, lalai `127.0.0.1:18790`). Feishu menggunakan mod WebSocket/SDK dan tidak menggunakan pelayan HTTP yang dikongsi. diff --git a/docs/project/README.pt-br.md b/docs/project/README.pt-br.md index 15fa1375..7522a571 100644 --- a/docs/project/README.pt-br.md +++ b/docs/project/README.pt-br.md @@ -369,13 +369,10 @@ Converse com seu PicoClaw por meio de mais de 17 plataformas de mensagens: | **WhatsApp** | Fácil (QR scan ou bridge URL) | Nativo / Bridge | [Guia](../guides/chat-apps.pt-br.md#whatsapp) | | **Weixin** | Fácil (scan QR nativo) | iLink API | [Guia](../guides/chat-apps.pt-br.md#weixin) | | **QQ** | Fácil (AppID + AppSecret) | WebSocket | [Guia](../channels/qq/README.pt-br.md) | -| **Slack** | Fácil (bot + app token) | Socket Mode | [Guia](../channels/slack/README.pt-br.md) | -| **Matrix** | Médio (homeserver + token) | Sync API | [Guia](../channels/matrix/README.pt-br.md) | | **DingTalk** | Médio (credenciais do cliente) | Stream | [Guia](../channels/dingtalk/README.pt-br.md) | | **Feishu / Lark** | Médio (App ID + Secret) | WebSocket/SDK | [Guia](../channels/feishu/README.pt-br.md) | | **LINE** | Médio (credenciais + webhook) | Webhook | [Guia](../channels/line/README.pt-br.md) | | **WeCom** | Fácil (login QR ou manual) | WebSocket | [Guia](../channels/wecom/README.pt-br.md) | -| **IRC** | Médio (servidor + nick) | Protocolo IRC | [Guia](../guides/chat-apps.pt-br.md#irc) | | **OneBot** | Médio (WebSocket URL) | OneBot v11 | [Guia](../channels/onebot/README.pt-br.md) | > Todos os channels baseados em webhook compartilham um único servidor HTTP do Gateway (`gateway.host`:`gateway.port`, padrão `127.0.0.1:18790`). O Feishu usa modo WebSocket/SDK e não utiliza o servidor HTTP compartilhado. diff --git a/docs/project/README.vi.md b/docs/project/README.vi.md index 52d1fd8e..a4a04879 100644 --- a/docs/project/README.vi.md +++ b/docs/project/README.vi.md @@ -369,13 +369,10 @@ Trò chuyện với PicoClaw của bạn qua 17+ nền tảng nhắn tin: | **WhatsApp** | Dễ (quét QR hoặc bridge URL) | Native / Bridge | [Hướng dẫn](../guides/chat-apps.vi.md#whatsapp) | | **Weixin** | Dễ (quét QR gốc) | iLink API | [Hướng dẫn](../guides/chat-apps.vi.md#weixin) | | **QQ** | Dễ (AppID + AppSecret) | WebSocket | [Hướng dẫn](../channels/qq/README.vi.md) | -| **Slack** | Dễ (bot + app token) | Socket Mode | [Hướng dẫn](../channels/slack/README.vi.md) | -| **Matrix** | Trung bình (homeserver + token) | Sync API | [Hướng dẫn](../channels/matrix/README.vi.md) | | **DingTalk** | Trung bình (client credentials) | Stream | [Hướng dẫn](../channels/dingtalk/README.vi.md) | | **Feishu / Lark** | Trung bình (App ID + Secret) | WebSocket/SDK | [Hướng dẫn](../channels/feishu/README.vi.md) | | **LINE** | Trung bình (credentials + webhook) | Webhook | [Hướng dẫn](../channels/line/README.vi.md) | | **WeCom** | Dễ (đăng nhập QR hoặc thủ công) | WebSocket | [Hướng dẫn](../channels/wecom/README.vi.md) | -| **IRC** | Trung bình (server + nick) | IRC protocol | [Hướng dẫn](../guides/chat-apps.vi.md#irc) | | **OneBot** | Trung bình (WebSocket URL) | OneBot v11 | [Hướng dẫn](../channels/onebot/README.vi.md) | > Tất cả các Channel dựa trên webhook dùng chung một Gateway HTTP server (`gateway.host`:`gateway.port`, mặc định `127.0.0.1:18790`). Feishu sử dụng chế độ WebSocket/SDK và không dùng HTTP server chung. diff --git a/docs/project/README.zh.md b/docs/project/README.zh.md index d8c8526e..60ee518c 100644 --- a/docs/project/README.zh.md +++ b/docs/project/README.zh.md @@ -369,14 +369,10 @@ PicoClaw 通过 `model_list` 配置支持 30+ LLM Provider,使用 `协议/模 | **WhatsApp** | 简单(扫码或 bridge URL) | 原生 / Bridge | [指南](../guides/chat-apps.zh.md#whatsapp) | | **微信 (Weixin)** | 简单(扫码登录) | iLink API | [指南](../guides/chat-apps.zh.md#weixin) | | **QQ** | 简单(AppID + AppSecret) | WebSocket | [指南](../channels/qq/README.zh.md) | -| **Slack** | 简单(bot + app token) | Socket Mode | [指南](../channels/slack/README.zh.md) | -| **Matrix** | 中等(homeserver + token) | Sync API | [指南](../channels/matrix/README.zh.md) | | **钉钉** | 中等(client credentials) | Stream | [指南](../channels/dingtalk/README.zh.md) | | **飞书 / Lark** | 中等(App ID + Secret) | WebSocket/SDK | [指南](../channels/feishu/README.zh.md) | | **LINE** | 中等(credentials + webhook) | Webhook | [指南](../channels/line/README.zh.md) | | **企业微信** | 简单(扫码登录或手动配置) | WebSocket | [指南](../channels/wecom/README.zh.md) | -| **VK** | 简单(群组 token) | Long Poll | [指南](../channels/vk/README.md) | -| **IRC** | 中等(server + nick) | IRC 协议 | [指南](../guides/chat-apps.zh.md#irc) | | **OneBot** | 中等(WebSocket URL) | OneBot v11 | [指南](../channels/onebot/README.zh.md) | > 所有基于 Webhook 的 Channel 共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`)。飞书使用 WebSocket/SDK 模式,不使用共享 HTTP 服务器。 diff --git a/docs/security/security_configuration.md b/docs/security/security_configuration.md index 4b5e4fe6..95e42dea 100644 --- a/docs/security/security_configuration.md +++ b/docs/security/security_configuration.md @@ -61,11 +61,6 @@ channels: app_secret: "your-qq-app-secret" dingtalk: client_secret: "your-dingtalk-client-secret" - slack: - bot_token: "your-slack-bot-token" - app_token: "your-slack-app-token" - matrix: - access_token: "your-matrix-access-token" line: channel_secret: "your-line-channel-secret" channel_access_token: "your-line-channel-access-token" @@ -84,10 +79,6 @@ channels: encoding_aes_key: "your-wecom-aibot-encoding-aes-key" pico: token: "your-pico-token" - irc: - password: "your-irc-password" - nickserv_password: "your-irc-nickserv-password" - sasl_password: "your-irc-sasl-password" # Channel Settings (nested format for channels that use settings block) channel_list: diff --git a/docs/security/sensitive_data_filtering.md b/docs/security/sensitive_data_filtering.md index e2d9de42..d4ada4b3 100644 --- a/docs/security/sensitive_data_filtering.md +++ b/docs/security/sensitive_data_filtering.md @@ -11,7 +11,7 @@ When the LLM uses a tool that returns its own credentials (e.g., a tool that ech Sensitive values are collected from [`.security.yml`](./credential_encryption.md) — the centralized storage for all sensitive configuration (API keys, tokens, secrets stored alongside `config.json`). This includes: - Model API keys -- Channel tokens (Telegram, Discord, Slack, Matrix, etc.) +- Channel tokens (Telegram, Discord, etc.) - Web tool API keys (Brave, Tavily, Perplexity, etc.) - Skills tokens (GitHub, ClawHub) diff --git a/docs/security/sensitive_data_filtering.zh.md b/docs/security/sensitive_data_filtering.zh.md index 6ff1acc2..d8981ec3 100644 --- a/docs/security/sensitive_data_filtering.zh.md +++ b/docs/security/sensitive_data_filtering.zh.md @@ -11,7 +11,7 @@ PicoClaw 可以从工具调用结果中过滤敏感值(API 密钥、令牌、 敏感值从 `.security.yml` 中收集 —— 这是所有敏感配置的集中存储,包括: - 模型 API 密钥 -- 频道令牌(Telegram、Discord、Slack、Matrix 等) +- 频道令牌(Telegram、Discord 等) - Web 工具 API 密钥(Brave、Tavily、Perplexity 等) - 技能令牌(GitHub、ClawHub) diff --git a/go.mod b/go.mod index 29b7e81b..72fc7224 100644 --- a/go.mod +++ b/go.mod @@ -5,10 +5,8 @@ go 1.25.13 require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 - github.com/SevereCloud/vksdk/v3 v3.3.1 github.com/adhocore/gronx v1.20.0 github.com/anthropics/anthropic-sdk-go v1.55.1 - github.com/atc0005/go-teams-notify/v2 v2.14.0 github.com/aws/aws-sdk-go-v2 v1.42.0 github.com/aws/aws-sdk-go-v2/config v1.32.25 github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.53.3 @@ -17,7 +15,6 @@ require ( github.com/charmbracelet/lipgloss v1.1.0 github.com/creack/pty v1.1.24 github.com/eclipse/paho.mqtt.golang v1.5.1 - github.com/ergochat/irc-go v0.6.0 github.com/ergochat/readline v0.1.3 github.com/gomarkdown/markdown v0.0.0-20260411013819-759bbc3e3207 github.com/google/uuid v1.6.0 @@ -37,7 +34,6 @@ require ( github.com/pion/webrtc/v3 v3.3.6 github.com/pmezard/go-difflib v1.0.0 github.com/rs/zerolog v1.35.1 - github.com/slack-go/slack v0.23.1 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 @@ -49,7 +45,6 @@ require ( golang.org/x/time v0.15.0 google.golang.org/protobuf v1.36.11 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.27.0 modernc.org/sqlite v1.53.0 ) @@ -94,7 +89,6 @@ require ( github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/mattn/go-sqlite3 v1.14.42 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect @@ -106,8 +100,6 @@ require ( github.com/segmentio/encoding v0.5.4 // indirect github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect github.com/vektah/gqlparser/v2 v2.5.27 // indirect - github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect - github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.mau.fi/libsignal v0.2.1 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect diff --git a/go.sum b/go.sum index c252133e..fccacd07 100644 --- a/go.sum +++ b/go.sum @@ -17,8 +17,6 @@ github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMs github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= -github.com/SevereCloud/vksdk/v3 v3.3.1 h1:O86zsp5LQnHE+O5acvuXM/s6S1LyxzVTkF6+Lup0Jyg= -github.com/SevereCloud/vksdk/v3 v3.3.1/go.mod h1:c6WaA5aocUYsXfkcUbg2qy45V9M1VDcqHHmHIN14NAw= github.com/adhocore/gronx v1.20.0 h1:PD13Mo0wekkZ7ZZR9yb1TqeqTfybs7/K3ez9DmjQwEs= github.com/adhocore/gronx v1.20.0/go.mod h1:7oUY1WAU8rEJWmAxXR2DN0JaO4gi9khSgKjiRypqteg= github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM= @@ -29,8 +27,6 @@ github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eT github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/anthropics/anthropic-sdk-go v1.55.1 h1:GxukHUVou6AFIngxa/Aw1z79hmwg13Hmn++KE9werbM= github.com/anthropics/anthropic-sdk-go v1.55.1/go.mod h1:3EfIfmFqxH6rbiLcIP4tPFyXL/IHakx2wDG4OU+TIEI= -github.com/atc0005/go-teams-notify/v2 v2.14.0 h1:7N+xw+COnYANLREaAveQ65rsNQ12nIZJED9nMLyscCo= -github.com/atc0005/go-teams-notify/v2 v2.14.0/go.mod h1:EECsWM2b0Hvoz7O+QdlsvyN2KCUOFQCGj8bUBXv3A3Q= github.com/aws/aws-sdk-go-v2 v1.42.0 h1:XvXMJTkFQtpBKIWZnmr9ZEOc2InWM2yldjXEJ/bymhA= github.com/aws/aws-sdk-go-v2 v1.42.0/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.12 h1:oRtsqWgxbpeXrOlxOoQStx2M9WNbIkPq4C4Xn1or6bc= @@ -113,8 +109,6 @@ github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2I github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU= github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg= github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo= -github.com/ergochat/irc-go v0.6.0 h1:Y0AGV76aeihJfCtLaQh+OyJKFiKGrYC0VTkeMZ6XW28= -github.com/ergochat/irc-go v0.6.0/go.mod h1:2vi7KNpIPWnReB5hmLpl92eMywQvuIeIIGdt/FQCph0= github.com/ergochat/readline v0.1.3 h1:/DytGTmwdUJcLAe3k3VJgowh5vNnsdifYT6uVaf4pSo= github.com/ergochat/readline v0.1.3/go.mod h1:o3ux9QLHLm77bq7hDB21UTm6HlV2++IPDMfIfKDuOgY= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= @@ -131,8 +125,6 @@ github.com/go-resty/resty/v2 v2.6.0/go.mod h1:PwvJS6hvaPkjtjNg9ph+VrSD92bi5Zq73w github.com/go-resty/resty/v2 v2.17.1 h1:x3aMpHK1YM9e4va/TMDRlusDDoZiQ+ViDu/WpA6xTM4= github.com/go-resty/resty/v2 v2.17.1/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U= -github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= @@ -270,8 +262,6 @@ github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfv github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= -github.com/slack-go/slack v0.23.1 h1:ZS5B96wxxYQRwvJ3/vJFtqtUZi3tXhsZCyT44Nv7M80= -github.com/slack-go/slack v0.23.1/go.mod h1:H0yR/YBuRJ39RkE+JpV/d/oEsbanzTRowR82bCN0cEs= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -315,10 +305,6 @@ github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADT github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE= github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s= github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo= -github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= -github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= -github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= -github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= @@ -476,8 +462,6 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -maunium.net/go/mautrix v0.27.0 h1:yfEYwoIluVWkofUgbZl9gP4i5nQTF+QNsxtb+r5bKlM= -maunium.net/go/mautrix v0.27.0/go.mod h1:7QpEQiTy6p4LHkXXaZI+N46tGYy8HMhD0JjzZAFoFWs= modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c= modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws= diff --git a/integration/README.md b/integration/README.md index baa6794a..5a7bb44e 100644 --- a/integration/README.md +++ b/integration/README.md @@ -41,7 +41,7 @@ The runner auto-discovers every suite under `integration/suites/`, so adding a s - The shared runner is defined in [`integration/docker-compose.runner.yml`](docker-compose.runner.yml). - Each suite lives in `integration/suites//`. - The runner script loads `suite.env`, merges the shared compose file with the suite-specific compose files, starts dependency services, runs the suite command, and then tears everything down. -- The shared runner container sets `GOFLAGS=-tags=goolm,stdjson,integration`, so tests run with the same build tags used by CI. +- The shared runner container sets `GOFLAGS=-tags=stdjson,integration`, so tests run with the same build tags used by CI. In practice, each suite gives us: @@ -125,7 +125,7 @@ This is the fastest way to reproduce exactly what the CI integration job does fo For faster iteration while writing the test, you can run the Go test itself without Docker: ```bash -go test -tags=goolm,stdjson,integration ./pkg/mcp -run TestIntegration_StreamableHTTPCompatibility -v +go test -tags=stdjson,integration ./pkg/mcp -run TestIntegration_StreamableHTTPCompatibility -v ``` You can also run the real-server smoke test directly if you provide the same environment variables that the Docker suite would inject: @@ -135,7 +135,7 @@ PICOCLAW_MCP_REAL_SERVER_JSON='{"enabled":true,"type":"http","url":"http://127.0 PICOCLAW_MCP_REAL_TOOL_NAME=echo \ PICOCLAW_MCP_REAL_TOOL_ARGS_JSON='{"message":"hello"}' \ PICOCLAW_MCP_REAL_EXPECT_SUBSTRING=hello \ -go test -tags=goolm,stdjson,integration ./pkg/mcp -run TestIntegration_RealConfiguredServer -v +go test -tags=stdjson,integration ./pkg/mcp -run TestIntegration_RealConfiguredServer -v ``` Notes: @@ -235,7 +235,7 @@ Practical advice: At minimum: ```bash -go test -tags=goolm,stdjson,integration ./path/to/package -run TestIntegration_Name -v +go test -tags=stdjson,integration ./path/to/package -run TestIntegration_Name -v bash ./scripts/run-integration-tests.sh ``` diff --git a/integration/docker-compose.runner.yml b/integration/docker-compose.runner.yml index cb7592ca..b7e8fa03 100644 --- a/integration/docker-compose.runner.yml +++ b/integration/docker-compose.runner.yml @@ -12,7 +12,7 @@ services: GOMODCACHE: /go-mod-cache GOTOOLCHAIN: local CGO_ENABLED: "0" - GOFLAGS: -tags=goolm,stdjson,integration + GOFLAGS: -tags=stdjson,integration volumes: picoclaw-integration-gocache: diff --git a/pkg/agent/agent_test.go b/pkg/agent/agent_test.go index d79b0396..21dec3c3 100644 --- a/pkg/agent/agent_test.go +++ b/pkg/agent/agent_test.go @@ -2006,7 +2006,7 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) { appendEventContextFields(fields, &TurnContext{ Inbound: &bus.InboundContext{ - Channel: "slack", + Channel: "discord", Account: "workspace-a", ChatID: "C123", ChatType: "channel", @@ -2018,20 +2018,20 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) { }, Route: &routing.ResolvedRoute{ AgentID: "support", - Channel: "slack", + Channel: "discord", AccountID: "workspace-a", MatchedBy: "default", SessionPolicy: routing.SessionPolicy{ Dimensions: []string{"chat", "sender"}, IdentityLinks: map[string][]string{ - "canonical-user": {"slack:U123"}, + "canonical-user": {"discord:U123"}, }, }, }, Scope: &session.SessionScope{ Version: session.ScopeVersionV1, AgentID: "support", - Channel: "slack", + Channel: "discord", Account: "workspace-a", Dimensions: []string{"chat", "sender"}, Values: map[string]string{ @@ -2041,8 +2041,8 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) { }, }) - if fields["inbound_channel"] != "slack" { - t.Fatalf("inbound_channel = %v, want slack", fields["inbound_channel"]) + if fields["inbound_channel"] != "discord" { + t.Fatalf("inbound_channel = %v, want discord", fields["inbound_channel"]) } if fields["inbound_topic_id"] != "thread-42" { t.Fatalf("inbound_topic_id = %v, want thread-42", fields["inbound_topic_id"]) @@ -2090,7 +2090,7 @@ func TestResolveMessageRoute_UsesInboundContextAccount(t *testing.T) { route, _, err := al.resolveMessageRoute(testInboundMessage(bus.InboundMessage{ Context: bus.InboundContext{ - Channel: "slack", + Channel: "discord", Account: "workspace-a", ChatID: "C123", ChatType: "channel", @@ -5536,7 +5536,6 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) { "mqtt": "rid-mqtt", "qq": "rid-qq", "dingtalk": "rid-dingtalk", - "slack": "rid-slack", "line": "rid-line", "onebot": "rid-onebot", "wecom": "rid-wecom", @@ -5555,7 +5554,6 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) { {channel: "mqtt", wantID: "rid-mqtt"}, {channel: "qq", wantID: "rid-qq"}, {channel: "dingtalk", wantID: "rid-dingtalk"}, - {channel: "slack", wantID: "rid-slack"}, {channel: "line", wantID: "rid-line"}, {channel: "onebot", wantID: "rid-onebot"}, {channel: "wecom", wantID: "rid-wecom"}, @@ -5622,13 +5620,13 @@ func TestHandleReasoning(t *testing.T) { t.Run("publishes one message for non telegram", func(t *testing.T) { al, msgBus := newLoop(t) - al.handleReasoning(context.Background(), "hello reasoning", "slack", "channel-1") + al.handleReasoning(context.Background(), "hello reasoning", "discord", "channel-1") msg, ok := <-msgBus.OutboundChan() if !ok { t.Fatal("expected an outbound message") } - if msg.Channel != "slack" || msg.ChatID != "channel-1" || msg.Content != "hello reasoning" { + if msg.Channel != "discord" || msg.ChatID != "channel-1" || msg.Content != "hello reasoning" { t.Fatalf("unexpected outbound message: %+v", msg) } }) @@ -5711,7 +5709,7 @@ func TestHandleReasoning(t *testing.T) { defer cancel() start := time.Now() - al.handleReasoning(ctx, "should timeout", "slack", "channel-full") + al.handleReasoning(ctx, "should timeout", "discord", "channel-full") elapsed := time.Since(start) // handleReasoning uses a 5s internal timeout, but the parent ctx diff --git a/pkg/agent/dispatch_request_test.go b/pkg/agent/dispatch_request_test.go index ec5f7033..811c9b5c 100644 --- a/pkg/agent/dispatch_request_test.go +++ b/pkg/agent/dispatch_request_test.go @@ -50,7 +50,7 @@ func TestNormalizeProcessOptions_PopulatesDispatchFromLegacyFields(t *testing.T) func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) { inbound := &bus.InboundContext{ - Channel: "slack", + Channel: "discord", ChatID: "C123", ChatType: "channel", SenderID: "U123", @@ -59,7 +59,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) { } route := &routing.ResolvedRoute{ AgentID: "support", - Channel: "slack", + Channel: "discord", AccountID: "workspace-a", MatchedBy: "dispatch.rule:test", SessionPolicy: routing.SessionPolicy{ @@ -69,7 +69,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) { scope := &session.SessionScope{ Version: session.ScopeVersionV1, AgentID: "support", - Channel: "slack", + Channel: "discord", Account: "workspace-a", Dimensions: []string{"chat"}, Values: map[string]string{ @@ -80,7 +80,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) { opts := normalizeProcessOptions(processOptions{ Dispatch: DispatchRequest{ SessionKey: "sk_v1_example", - SessionAliases: []string{"agent:support:slack:channel:c123"}, + SessionAliases: []string{"agent:support:discord:channel:c123"}, InboundContext: inbound, RouteResult: route, SessionScope: scope, @@ -92,8 +92,8 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) { if opts.SessionKey != "sk_v1_example" { t.Fatalf("SessionKey = %q, want sk_v1_example", opts.SessionKey) } - if opts.Channel != "slack" || opts.ChatID != "C123" { - t.Fatalf("legacy mirrors = (%q,%q), want (slack,C123)", opts.Channel, opts.ChatID) + if opts.Channel != "discord" || opts.ChatID != "C123" { + t.Fatalf("legacy mirrors = (%q,%q), want (discord,C123)", opts.Channel, opts.ChatID) } if opts.SenderID != "U123" || opts.MessageID != "m-1" { t.Fatalf("legacy sender/message = (%q,%q)", opts.SenderID, opts.MessageID) diff --git a/pkg/agent/steering_test.go b/pkg/agent/steering_test.go index 569f2058..268af87a 100644 --- a/pkg/agent/steering_test.go +++ b/pkg/agent/steering_test.go @@ -1267,12 +1267,12 @@ func TestAgentLoop_AgentForSession_UsesStoredScopeMetadata(t *testing.T) { t.Fatal("support session store does not support metadata") } - alias := "agent:support:slack:channel:c001" + alias := "agent:support:discord:channel:c001" key := session.BuildOpaqueSessionKey(alias) scope := &session.SessionScope{ Version: session.ScopeVersionV1, AgentID: "support", - Channel: "slack", + Channel: "discord", Account: "default", Dimensions: []string{"chat"}, Values: map[string]string{ diff --git a/pkg/audio/asr/agent_test.go b/pkg/audio/asr/agent_test.go index 0f9bcb3b..84f1960d 100644 --- a/pkg/audio/asr/agent_test.go +++ b/pkg/audio/asr/agent_test.go @@ -168,7 +168,7 @@ func TestAgentCheckSilencePublishesInboundAndCleansUp(t *testing.T) { chatID: "chat", speakerID: "speaker", sessionID: "sess", - channel: "slack", + channel: "discord", } agent.mu.Lock() @@ -179,7 +179,7 @@ func TestAgentCheckSilencePublishesInboundAndCleansUp(t *testing.T) { select { case msg := <-mb.InboundChan(): - if msg.Channel != "slack" { + if msg.Channel != "discord" { t.Fatalf("unexpected inbound channel: %q", msg.Channel) } if !strings.Contains(msg.Content, "hello there") { diff --git a/pkg/bus/bus_test.go b/pkg/bus/bus_test.go index 02688356..276fedcc 100644 --- a/pkg/bus/bus_test.go +++ b/pkg/bus/bus_test.go @@ -57,7 +57,7 @@ func TestPublishInbound_NormalizesContext(t *testing.T) { msg := InboundMessage{ Context: InboundContext{ - Channel: "slack", + Channel: "discord", Account: "workspace-a", ChatID: "C456/1712", ChatType: "group", @@ -77,8 +77,8 @@ func TestPublishInbound_NormalizesContext(t *testing.T) { } got := <-mb.InboundChan() - if got.Context.Channel != "slack" { - t.Fatalf("expected context channel slack, got %q", got.Context.Channel) + if got.Context.Channel != "discord" { + t.Fatalf("expected context channel discord, got %q", got.Context.Channel) } if got.Context.Account != "workspace-a" { t.Fatalf("expected context account workspace-a, got %q", got.Context.Account) @@ -394,7 +394,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) { msg := OutboundMediaMessage{ Context: InboundContext{ - Channel: "slack", + Channel: "discord", ChatID: "C001", }, AgentID: "support", @@ -402,7 +402,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) { Scope: &OutboundScope{ Version: 1, AgentID: "support", - Channel: "slack", + Channel: "discord", Dimensions: []string{"chat"}, Values: map[string]string{ "chat": "channel:c001", @@ -416,8 +416,8 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) { } got := <-mb.OutboundMediaChan() - if got.Channel != "slack" { - t.Fatalf("expected legacy channel slack, got %q", got.Channel) + if got.Channel != "discord" { + t.Fatalf("expected legacy channel discord, got %q", got.Channel) } if got.ChatID != "C001" { t.Fatalf("expected legacy chat ID C001, got %q", got.ChatID) @@ -428,7 +428,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) { if got.Scope == nil || got.Scope.Values["chat"] != "channel:c001" { t.Fatalf("unexpected outbound media scope: %+v", got.Scope) } - if got.Context.Channel != "slack" || got.Context.ChatID != "C001" { + if got.Context.Channel != "discord" || got.Context.ChatID != "C001" { t.Fatalf("unexpected outbound media context: %+v", got.Context) } } diff --git a/pkg/bus/types.go b/pkg/bus/types.go index 0e23ea0f..987f6d78 100644 --- a/pkg/bus/types.go +++ b/pkg/bus/types.go @@ -2,7 +2,7 @@ package bus // SenderInfo provides structured sender identity information. type SenderInfo struct { - Platform string `json:"platform,omitempty"` // "telegram", "discord", "slack", ... + Platform string `json:"platform,omitempty"` // "telegram", "discord", ... PlatformID string `json:"platform_id,omitempty"` // raw platform ID, e.g. "123456" CanonicalID string `json:"canonical_id,omitempty"` // "platform:id" format Username string `json:"username,omitempty"` // username (e.g. @alice) diff --git a/pkg/channels/README.md b/pkg/channels/README.md index 87f97dc3..1224913c 100644 --- a/pkg/channels/README.md +++ b/pkg/channels/README.md @@ -25,7 +25,6 @@ pkg/channels/ ├── telegram.go # Each channel directly in the channels package ├── discord.go -├── slack.go ├── manager.go # Manager directly references each channel type ├── ... ``` @@ -60,7 +59,7 @@ pkg/channels/ ├── discord/ │ ├── init.go │ └── discord.go -├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/ +├── line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/ │ └── ... pkg/bus/ @@ -80,7 +79,7 @@ pkg/identity/ ┌────────────┐ InboundMessage ┌───────────┐ LLM + Tools ┌────────────┐ │ Telegram │──┐ │ │ │ │ │ Discord │──┤ PublishInbound() │ │ PublishOutbound() │ │ -│ Slack │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │ +│ Feishu │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │ │ LINE │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │ │ ... │──┘ │ │ │ │ └────────────┘ └─────┬─────┘ └────────────┘ @@ -409,21 +408,21 @@ Main changes to the Agent Loop: ### 3.1 Minimum Implementation Checklist -To add a new chat platform (e.g., `matrix`), you need to: +To add a new chat platform (e.g., `examplechat`), you need to: -1. ✅ Create sub-package directory `pkg/channels/matrix/` +1. ✅ Create sub-package directory `pkg/channels/examplechat/` 2. ✅ Create `init.go` — factory registration -3. ✅ Create `matrix.go` — channel implementation +3. ✅ Create `examplechat.go` — channel implementation 4. ✅ Add blank import in Gateway helpers 5. ✅ Add config check in Manager.initChannels() 6. ✅ Add config struct in `pkg/config/` ### 3.2 Complete Template -#### `pkg/channels/matrix/init.go` +#### `pkg/channels/examplechat/init.go` ```go -package matrix +package examplechat import ( "github.com/sipeed/picoclaw/pkg/bus" @@ -432,21 +431,21 @@ import ( ) func init() { - channels.RegisterFactory(config.ChannelMatrix, func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { + channels.RegisterFactory(config.ChannelExampleChat, func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { bc := cfg.Channels[channelName] decoded, err := bc.GetDecoded() if err != nil { return nil, err } - c, ok := decoded.(*config.MatrixSettings) + c, ok := decoded.(*config.ExampleChatSettings) if !ok { return nil, channels.ErrSendFailed } - return NewMatrixChannel(bc, c, b) + return NewExampleChatChannel(bc, c, b) }) } ``` -#### `pkg/channels/matrix/matrix.go` +#### `pkg/channels/examplechat/examplechat.go` ```go -package matrix +package examplechat import ( "context" @@ -459,29 +458,29 @@ import ( "github.com/sipeed/picoclaw/pkg/logger" ) -// MatrixChannel implements channels.Channel for the Matrix protocol. -type MatrixChannel struct { +// ExampleChatChannel implements channels.Channel for the ExampleChat protocol. +type ExampleChatChannel struct { *channels.BaseChannel // Must embed config *config.Config ctx context.Context cancel context.CancelFunc - // ... Matrix SDK client, etc. + // ... ExampleChat SDK client, etc. } -func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChannel, error) { - matrixCfg := cfg.Channels.Matrix // Assumes this field exists in config +func NewExampleChatChannel(cfg *config.Config, msgBus *bus.MessageBus) (*ExampleChatChannel, error) { + examplechatCfg := cfg.Channels.ExampleChat // Assumes this field exists in config base := channels.NewBaseChannel( - "matrix", // Channel name (globally unique) - matrixCfg, // Raw config + "examplechat", // Channel name (globally unique) + examplechatCfg, // Raw config msgBus, // Message bus - matrixCfg.AllowFrom, // Allow list - channels.WithMaxMessageLength(65536), // Matrix message length limit - channels.WithGroupTrigger(matrixCfg.GroupTrigger), - channels.WithReasoningChannelID(matrixCfg.ReasoningChannelID), // Reasoning chain routing (optional) + examplechatCfg.AllowFrom, // Allow list + channels.WithMaxMessageLength(65536), // ExampleChat message length limit + channels.WithGroupTrigger(examplechatCfg.GroupTrigger), + channels.WithReasoningChannelID(examplechatCfg.ReasoningChannelID), // Reasoning chain routing (optional) ) - return &MatrixChannel{ + return &ExampleChatChannel{ BaseChannel: base, config: cfg, }, nil @@ -489,37 +488,37 @@ func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChanne // ========== Required Channel Interface Methods ========== -func (c *MatrixChannel) Start(ctx context.Context) error { +func (c *ExampleChatChannel) Start(ctx context.Context) error { c.ctx, c.cancel = context.WithCancel(ctx) - // 1. Initialize Matrix client + // 1. Initialize ExampleChat client // 2. Start listening for messages // 3. Mark as running c.SetRunning(true) - logger.InfoC("matrix", "Matrix channel started") + logger.InfoC("examplechat", "ExampleChat channel started") return nil } -func (c *MatrixChannel) Stop(ctx context.Context) error { +func (c *ExampleChatChannel) Stop(ctx context.Context) error { c.SetRunning(false) if c.cancel != nil { c.cancel() } - logger.InfoC("matrix", "Matrix channel stopped") + logger.InfoC("examplechat", "ExampleChat channel stopped") return nil } -func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { +func (c *ExampleChatChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { // 1. Check running state if !c.IsRunning() { return nil, channels.ErrNotRunning } - // 2. Send message to Matrix - eventID, err := c.sendToMatrix(ctx, msg.ChatID, msg.Content) + // 2. Send message to ExampleChat + eventID, err := c.sendToExampleChat(ctx, msg.ChatID, msg.Content) if err != nil { // 3. Must use error classification wrapping // If you have an HTTP status code: @@ -535,12 +534,12 @@ func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]st // ========== Incoming Message Handling ========== -func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) { +func (c *ExampleChatChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) { // 1. Construct structured sender identity sender := bus.SenderInfo{ - Platform: "matrix", + Platform: "examplechat", PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID("matrix", senderID), + CanonicalID: identity.BuildCanonicalID("examplechat", senderID), Username: senderID, DisplayName: displayName, } @@ -590,8 +589,8 @@ func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content st // ========== Internal Methods ========== -func (c *MatrixChannel) sendToMatrix(ctx context.Context, roomID, content string) (string, error) { - // Actual Matrix SDK call +func (c *ExampleChatChannel) sendToExampleChat(ctx context.Context, roomID, content string) (string, error) { + // Actual ExampleChat SDK call return "event-id", nil } ``` @@ -604,7 +603,7 @@ Depending on platform capabilities, your channel can optionally implement the fo ```go // If the platform supports sending images/files/audio/video -func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { +func (c *ExampleChatChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { if !c.IsRunning() { return nil, channels.ErrNotRunning } @@ -618,7 +617,7 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess for _, part := range msg.Parts { localPath, err := store.Resolve(part.Ref) if err != nil { - logger.ErrorCF("matrix", "Failed to resolve media", map[string]any{ + logger.ErrorCF("examplechat", "Failed to resolve media", map[string]any{ "ref": part.Ref, "error": err.Error(), }) continue @@ -627,9 +626,9 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess // Call the appropriate API based on part.Type ("image"|"audio"|"video"|"file") switch part.Type { case "image": - // Upload image to Matrix + // Upload image to ExampleChat default: - // Upload file to Matrix + // Upload file to ExampleChat } // Append platform IDs here when the API returns them. // messageIDs = append(messageIDs, uploadedMessageID) @@ -642,14 +641,14 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess ```go // If the platform supports "typing..." indicators -func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) { - // Call Matrix API to send typing indicator +func (c *ExampleChatChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) { + // Call ExampleChat API to send typing indicator // The returned stop function must be idempotent stopped := false return func() { if !stopped { stopped = true - // Call Matrix API to stop typing + // Call ExampleChat API to stop typing } }, nil } @@ -658,9 +657,9 @@ func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop fu #### ReactionCapable — Message Reaction Indicator ```go -// If the platform supports adding emoji reactions to inbound messages (e.g., Slack's 👀, OneBot's emoji 289) -func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) { - // Call Matrix API to add reaction to message +// If the platform supports adding emoji reactions to inbound messages (e.g., OneBot's emoji 289) +func (c *ExampleChatChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) { + // Call ExampleChat API to add reaction to message // The returned undo function removes the reaction, must be idempotent err = c.addReaction(chatID, messageID, "eyes") if err != nil { @@ -676,8 +675,8 @@ func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID st ```go // If the platform supports editing sent messages (used for Placeholder replacement) -func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error { - // Call Matrix API to edit message +func (c *ExampleChatChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error { + // Call ExampleChat API to edit message return nil } ``` @@ -690,8 +689,8 @@ func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, cont // automatically edit the placeholder into the final response on outbound. // SendPlaceholder checks PlaceholderConfig.Enabled internally; // returning ("", nil) means skip. -func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) { - cfg := c.config.Channels.Matrix.Placeholder +func (c *ExampleChatChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) { + cfg := c.config.Channels.ExampleChat.Placeholder if !cfg.Enabled { return "", nil } @@ -699,7 +698,7 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str if text == "" { text = "Thinking... 💭" } - // Call Matrix API to send placeholder message + // Call ExampleChat API to send placeholder message msg, err := c.sendText(ctx, chatID, text) if err != nil { return "", err @@ -712,11 +711,11 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str ```go // If the channel receives messages via webhook (rather than long-polling/WebSocket) -func (c *MatrixChannel) WebhookPath() string { - return "/webhook/matrix" // Path will be registered on the shared HTTP server +func (c *ExampleChatChannel) WebhookPath() string { + return "/webhook/examplechat" // Path will be registered on the shared HTTP server } -func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (c *ExampleChatChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Handle webhook request } ``` @@ -724,11 +723,11 @@ func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { #### HealthChecker — Health Check Endpoint ```go -func (c *MatrixChannel) HealthPath() string { - return "/health/matrix" +func (c *ExampleChatChannel) HealthPath() string { + return "/health/examplechat" } -func (c *MatrixChannel) HealthHandler(w http.ResponseWriter, r *http.Request) { +func (c *ExampleChatChannel) HealthHandler(w http.ResponseWriter, r *http.Request) { if c.IsRunning() { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) @@ -768,7 +767,7 @@ if c.owner != nil && c.placeholderRecorder != nil { **This means**: - Channels implementing `TypingCapable` (Telegram, Discord, LINE) do not need to manually call `StartTyping` + `RecordTypingStop` in `handleMessage` -- Channels implementing `ReactionCapable` (Slack, OneBot) do not need to manually call `AddReaction` + `RecordTypingStop` in `handleMessage` +- Channels implementing `ReactionCapable` (OneBot) do not need to manually call `AddReaction` + `RecordTypingStop` in `handleMessage` - Channels implementing `PlaceholderCapable` (Telegram, Discord) do not need to manually send placeholder messages and call `RecordPlaceholder` in `handleMessage` - Channels only need to implement the corresponding interface; `HandleMessage` handles orchestration automatically - Channels that don't implement these interfaces are unaffected (type assertions will fail and be skipped) @@ -792,12 +791,12 @@ the top level, with channel-specific settings in the `settings` sub-key: ```json { "channel_list": { - "matrix": { + "examplechat": { "enabled": true, - "type": "matrix", + "type": "examplechat", "allow_from": ["@user:example.com"], "settings": { - "home_server": "https://matrix.org", + "home_server": "https://examplechat.org", "user_id": "@bot:example.com", "access_token": "enc://..." } @@ -810,8 +809,8 @@ Secure fields (tokens, passwords, API keys) go into `.security.yml`: ```yaml channels: - matrix: - access_token: "your-matrix-access-token" + examplechat: + access_token: "your-examplechat-access-token" ``` Channel types must be registered in `channelSettingsFactory` in @@ -820,7 +819,7 @@ Channel types must be registered in `channelSettingsFactory` in ```go var channelSettingsFactory = map[string]any{ // ... existing channels - ChannelMatrix: (MatrixSettings{}), + ChannelExampleChat: (ExampleChatSettings{}), } ``` @@ -843,7 +842,7 @@ just register the factory and the config entry. ```go // cmd/picoclaw/internal/gateway/helpers.go import ( - _ "github.com/sipeed/picoclaw/pkg/channels/matrix" + _ "github.com/sipeed/picoclaw/pkg/channels/examplechat" ) ``` @@ -1072,7 +1071,6 @@ type channelWorker struct { var channelRateConfig = map[string]float64{ "telegram": 20, // 20 msg/s "discord": 1, // 1 msg/s - "slack": 1, // 1 msg/s "line": 10, // 10 msg/s } // Default: 10 msg/s @@ -1267,7 +1265,7 @@ Existing test files: To add tests for a new channel: ```bash -go test ./pkg/channels/matrix/ -v # Sub-package tests +go test ./pkg/channels/examplechat/ -v # Sub-package tests go test ./pkg/channels/ -run TestSpecific -v # Framework tests make test # Full test suite ``` @@ -1300,7 +1298,6 @@ make test # Full test suite |-------------|----------------|-------------------| | `pkg/channels/telegram/` | `"telegram"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender | | `pkg/channels/discord/` | `"discord"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender | -| `pkg/channels/slack/` | `"slack"` | ReactionCapable, MediaSender | | `pkg/channels/line/` | `"line"` | TypingCapable, MediaSender, WebhookHandler | | `pkg/channels/onebot/` | `"onebot"` | ReactionCapable, MediaSender | | `pkg/channels/dingtalk/` | `"dingtalk"` | — | @@ -1409,7 +1406,6 @@ agentLoop.Stop() // Stop Agent |---------|-------------|-------| | telegram | 20 | 10 | | discord | 1 | 1 | -| slack | 1 | 1 | | line | 10 | 5 | | _others_ | 10 (default) | 5 | @@ -1425,6 +1421,6 @@ agentLoop.Stop() // Stop Agent 5. **DingTalk uses Stream mode**: DingTalk uses the SDK's Stream/WebSocket mode (not HTTP webhook), so it does not implement `WebhookHandler`. -6. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 5 channel configs (Telegram, Discord, Slack, LINE, OneBot), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram, Discord) can actually use placeholder message editing. The rest are reserved fields. +6. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 4 channel configs (Telegram, Discord, LINE, OneBot), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram, Discord) can actually use placeholder message editing. The rest are reserved fields. -7. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (WhatsApp, Telegram, Feishu, Discord, QQ, DingTalk, Slack, LINE, OneBot, WeCom). `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method. +7. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (WhatsApp, Telegram, Feishu, Discord, QQ, DingTalk, LINE, OneBot, WeCom). `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method. diff --git a/pkg/channels/README.zh.md b/pkg/channels/README.zh.md index bca465df..39ab5152 100644 --- a/pkg/channels/README.zh.md +++ b/pkg/channels/README.zh.md @@ -25,7 +25,6 @@ pkg/channels/ ├── telegram.go # 每个 channel 直接放在 channels 包内 ├── discord.go -├── slack.go ├── manager.go # Manager 直接引用各 channel 类型 ├── ... ``` @@ -60,7 +59,7 @@ pkg/channels/ ├── discord/ │ ├── init.go │ └── discord.go -├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/ +├── line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/ │ └── ... pkg/bus/ @@ -80,7 +79,7 @@ pkg/identity/ ┌────────────┐ InboundMessage ┌───────────┐ LLM + Tools ┌────────────┐ │ Telegram │──┐ │ │ │ │ │ Discord │──┤ PublishInbound() │ │ PublishOutbound() │ │ -│ Slack │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │ +│ Feishu │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │ │ LINE │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │ │ ... │──┘ │ │ │ │ └────────────┘ └─────┬─────┘ └────────────┘ @@ -409,21 +408,21 @@ Agent Loop 的主要变化: ### 3.1 最小实现清单 -要添加一个新的聊天平台(例如 `matrix`),你需要: +要添加一个新的聊天平台(例如 `examplechat`),你需要: -1. ✅ 创建子包目录 `pkg/channels/matrix/` +1. ✅ 创建子包目录 `pkg/channels/examplechat/` 2. ✅ 创建 `init.go` — 工厂注册 -3. ✅ 创建 `matrix.go` — Channel 实现 +3. ✅ 创建 `examplechat.go` — Channel 实现 4. ✅ 在 Gateway helpers 中添加 blank import 5. ✅ 在 Manager.initChannels() 中添加配置检查 6. ✅ 在 `pkg/config/` 中添加配置结构体 ### 3.2 完整模板 -#### `pkg/channels/matrix/init.go` +#### `pkg/channels/examplechat/init.go` ```go -package matrix +package examplechat import ( "github.com/sipeed/picoclaw/pkg/bus" @@ -432,21 +431,21 @@ import ( ) func init() { - channels.RegisterFactory(config.ChannelMatrix, func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { + channels.RegisterFactory(config.ChannelExampleChat, func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { bc := cfg.Channels[channelName] decoded, err := bc.GetDecoded() if err != nil { return nil, err } - c, ok := decoded.(*config.MatrixSettings) + c, ok := decoded.(*config.ExampleChatSettings) if !ok { return nil, channels.ErrSendFailed } - return NewMatrixChannel(bc, c, b) + return NewExampleChatChannel(bc, c, b) }) } ``` -#### `pkg/channels/matrix/matrix.go` +#### `pkg/channels/examplechat/examplechat.go` ```go -package matrix +package examplechat import ( "context" @@ -459,29 +458,29 @@ import ( "github.com/sipeed/picoclaw/pkg/logger" ) -// MatrixChannel implements channels.Channel for the Matrix protocol. -type MatrixChannel struct { +// ExampleChatChannel implements channels.Channel for the ExampleChat protocol. +type ExampleChatChannel struct { *channels.BaseChannel // 必须嵌入 config *config.Config ctx context.Context cancel context.CancelFunc - // ... Matrix SDK 客户端等 + // ... ExampleChat SDK 客户端等 } -func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChannel, error) { - matrixCfg := cfg.Channels.Matrix // 假设配置中有此字段 +func NewExampleChatChannel(cfg *config.Config, msgBus *bus.MessageBus) (*ExampleChatChannel, error) { + examplechatCfg := cfg.Channels.ExampleChat // 假设配置中有此字段 base := channels.NewBaseChannel( - "matrix", // channel 名称(全局唯一) - matrixCfg, // 原始配置 + "examplechat", // channel 名称(全局唯一) + examplechatCfg, // 原始配置 msgBus, // 消息总线 - matrixCfg.AllowFrom, // 允许列表 - channels.WithMaxMessageLength(65536), // Matrix 消息长度限制 - channels.WithGroupTrigger(matrixCfg.GroupTrigger), - channels.WithReasoningChannelID(matrixCfg.ReasoningChannelID), // 思维链路由(可选) + examplechatCfg.AllowFrom, // 允许列表 + channels.WithMaxMessageLength(65536), // ExampleChat 消息长度限制 + channels.WithGroupTrigger(examplechatCfg.GroupTrigger), + channels.WithReasoningChannelID(examplechatCfg.ReasoningChannelID), // 思维链路由(可选) ) - return &MatrixChannel{ + return &ExampleChatChannel{ BaseChannel: base, config: cfg, }, nil @@ -489,37 +488,37 @@ func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChanne // ========== 必须实现的 Channel 接口方法 ========== -func (c *MatrixChannel) Start(ctx context.Context) error { +func (c *ExampleChatChannel) Start(ctx context.Context) error { c.ctx, c.cancel = context.WithCancel(ctx) - // 1. 初始化 Matrix 客户端 + // 1. 初始化 ExampleChat 客户端 // 2. 开始监听消息 // 3. 标记为运行中 c.SetRunning(true) - logger.InfoC("matrix", "Matrix channel started") + logger.InfoC("examplechat", "ExampleChat channel started") return nil } -func (c *MatrixChannel) Stop(ctx context.Context) error { +func (c *ExampleChatChannel) Stop(ctx context.Context) error { c.SetRunning(false) if c.cancel != nil { c.cancel() } - logger.InfoC("matrix", "Matrix channel stopped") + logger.InfoC("examplechat", "ExampleChat channel stopped") return nil } -func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { +func (c *ExampleChatChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { // 1. 检查运行状态 if !c.IsRunning() { return nil, channels.ErrNotRunning } - // 2. 发送消息到 Matrix - eventID, err := c.sendToMatrix(ctx, msg.ChatID, msg.Content) + // 2. 发送消息到 ExampleChat + eventID, err := c.sendToExampleChat(ctx, msg.ChatID, msg.Content) if err != nil { // 3. 必须使用错误分类包装 // 如果你有 HTTP 状态码: @@ -535,12 +534,12 @@ func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]st // ========== 消息接收处理 ========== -func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) { +func (c *ExampleChatChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) { // 1. 构造结构化发送者身份 sender := bus.SenderInfo{ - Platform: "matrix", + Platform: "examplechat", PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID("matrix", senderID), + CanonicalID: identity.BuildCanonicalID("examplechat", senderID), Username: senderID, DisplayName: displayName, } @@ -590,8 +589,8 @@ func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content st // ========== 内部方法 ========== -func (c *MatrixChannel) sendToMatrix(ctx context.Context, roomID, content string) (string, error) { - // 实际的 Matrix SDK 调用 +func (c *ExampleChatChannel) sendToExampleChat(ctx context.Context, roomID, content string) (string, error) { + // 实际的 ExampleChat SDK 调用 return "event-id", nil } ``` @@ -604,7 +603,7 @@ func (c *MatrixChannel) sendToMatrix(ctx context.Context, roomID, content string ```go // 如果平台支持发送图片/文件/音频/视频 -func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { +func (c *ExampleChatChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { if !c.IsRunning() { return nil, channels.ErrNotRunning } @@ -618,7 +617,7 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess for _, part := range msg.Parts { localPath, err := store.Resolve(part.Ref) if err != nil { - logger.ErrorCF("matrix", "Failed to resolve media", map[string]any{ + logger.ErrorCF("examplechat", "Failed to resolve media", map[string]any{ "ref": part.Ref, "error": err.Error(), }) continue @@ -627,9 +626,9 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess // 根据 part.Type ("image"|"audio"|"video"|"file") 调用对应 API switch part.Type { case "image": - // 上传图片到 Matrix + // 上传图片到 ExampleChat default: - // 上传文件到 Matrix + // 上传文件到 ExampleChat } // 如果 API 能返回平台消息 ID,就在这里追加。 // messageIDs = append(messageIDs, uploadedMessageID) @@ -642,14 +641,14 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess ```go // 如果平台支持 "正在输入..." 提示 -func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) { - // 调用 Matrix API 发送 typing 指示器 +func (c *ExampleChatChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) { + // 调用 ExampleChat API 发送 typing 指示器 // 返回的 stop 函数必须是幂等的 stopped := false return func() { if !stopped { stopped = true - // 调用 Matrix API 停止 typing + // 调用 ExampleChat API 停止 typing } }, nil } @@ -658,9 +657,9 @@ func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop fu #### ReactionCapable — 消息反应指示器 ```go -// 如果平台支持对入站消息添加 emoji 反应(如 Slack 的 👀、OneBot 的表情 289) -func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) { - // 调用 Matrix API 添加反应到消息 +// 如果平台支持对入站消息添加 emoji 反应(如 OneBot 的表情 289) +func (c *ExampleChatChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) { + // 调用 ExampleChat API 添加反应到消息 // 返回的 undo 函数移除反应,必须是幂等的 err = c.addReaction(chatID, messageID, "eyes") if err != nil { @@ -676,8 +675,8 @@ func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID st ```go // 如果平台支持编辑已发送的消息(用于 Placeholder 替换) -func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error { - // 调用 Matrix API 编辑消息 +func (c *ExampleChatChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error { + // 调用 ExampleChat API 编辑消息 return nil } ``` @@ -689,8 +688,8 @@ func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, cont // 则 Manager 的 preSend 会在出站时自动将占位消息编辑为最终回复。 // SendPlaceholder 内部根据 PlaceholderConfig.Enabled 决定是否发送; // 返回 ("", nil) 表示跳过。 -func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) { - cfg := c.config.Channels.Matrix.Placeholder +func (c *ExampleChatChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) { + cfg := c.config.Channels.ExampleChat.Placeholder if !cfg.Enabled { return "", nil } @@ -698,7 +697,7 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str if text == "" { text = "Thinking... 💭" } - // 调用 Matrix API 发送占位消息 + // 调用 ExampleChat API 发送占位消息 msg, err := c.sendText(ctx, chatID, text) if err != nil { return "", err @@ -711,11 +710,11 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str ```go // 如果 channel 通过 webhook 接收消息(而非长轮询/WebSocket) -func (c *MatrixChannel) WebhookPath() string { - return "/webhook/matrix" // 路径会被注册到共享 HTTP 服务器 +func (c *ExampleChatChannel) WebhookPath() string { + return "/webhook/examplechat" // 路径会被注册到共享 HTTP 服务器 } -func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (c *ExampleChatChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { // 处理 webhook 请求 } ``` @@ -723,11 +722,11 @@ func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { #### HealthChecker — 健康检查端点 ```go -func (c *MatrixChannel) HealthPath() string { - return "/health/matrix" +func (c *ExampleChatChannel) HealthPath() string { + return "/health/examplechat" } -func (c *MatrixChannel) HealthHandler(w http.ResponseWriter, r *http.Request) { +func (c *ExampleChatChannel) HealthHandler(w http.ResponseWriter, r *http.Request) { if c.IsRunning() { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) @@ -767,7 +766,7 @@ if c.owner != nil && c.placeholderRecorder != nil { **这意味着**: - 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop` -- 实现 `ReactionCapable` 的 channel(Slack、OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop` +- 实现 `ReactionCapable` 的 channel(OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop` - 实现 `PlaceholderCapable` 的 channel(Telegram、Discord)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder` - Channel 只需实现对应接口,`HandleMessage` 会自动完成编排 - 不实现这些接口的 channel 不受影响(类型断言会失败,跳过) @@ -791,12 +790,12 @@ channel 特定的设置放在 `settings` 子键中: ```json { "channel_list": { - "matrix": { + "examplechat": { "enabled": true, - "type": "matrix", + "type": "examplechat", "allow_from": ["@user:example.com"], "settings": { - "home_server": "https://matrix.org", + "home_server": "https://examplechat.org", "user_id": "@bot:example.com", "access_token": "enc://..." } @@ -809,8 +808,8 @@ channel 特定的设置放在 `settings` 子键中: ```yaml channels: - matrix: - access_token: "your-matrix-access-token" + examplechat: + access_token: "your-examplechat-access-token" ``` Channel 类型必须在 `pkg/config/config_channel.go` 的 `channelSettingsFactory` 中注册: @@ -818,7 +817,7 @@ Channel 类型必须在 `pkg/config/config_channel.go` 的 `channelSettingsFacto ```go var channelSettingsFactory = map[string]any{ // ... 现有 channels - ChannelMatrix: (MatrixSettings{}), + ChannelExampleChat: (ExampleChatSettings{}), } ``` @@ -841,7 +840,7 @@ Manager 使用 `InitChannelList()` 来验证类型和解码设置, ```go // cmd/picoclaw/internal/gateway/helpers.go import ( - _ "github.com/sipeed/picoclaw/pkg/channels/matrix" + _ "github.com/sipeed/picoclaw/pkg/channels/examplechat" ) ``` @@ -1070,7 +1069,6 @@ type channelWorker struct { var channelRateConfig = map[string]float64{ "telegram": 20, // 20 msg/s "discord": 1, // 1 msg/s - "slack": 1, // 1 msg/s "line": 10, // 10 msg/s } // 默认: 10 msg/s @@ -1265,7 +1263,7 @@ Manager 创建单一 `http.Server`,自动发现和注册: 为新 channel 添加测试时: ```bash -go test ./pkg/channels/matrix/ -v # 子包测试 +go test ./pkg/channels/examplechat/ -v # 子包测试 go test ./pkg/channels/ -run TestSpecific -v # 框架测试 make test # 全量测试 ``` @@ -1298,7 +1296,6 @@ make test # 全量测试 |------|--------|----------| | `pkg/channels/telegram/` | `"telegram"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender | | `pkg/channels/discord/` | `"discord"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender | -| `pkg/channels/slack/` | `"slack"` | ReactionCapable, MediaSender | | `pkg/channels/line/` | `"line"` | TypingCapable, MediaSender, WebhookHandler | | `pkg/channels/onebot/` | `"onebot"` | ReactionCapable, MediaSender | | `pkg/channels/dingtalk/` | `"dingtalk"` | — | @@ -1407,7 +1404,6 @@ agentLoop.Stop() // 停止 Agent |---------|-------------|-------| | telegram | 20 | 10 | | discord | 1 | 1 | -| slack | 1 | 1 | | line | 10 | 5 | | _其他_ | 10 (默认) | 5 | @@ -1423,6 +1419,6 @@ agentLoop.Stop() // 停止 Agent 5. **DingTalk 使用 Stream 模式**:DingTalk 使用 SDK 的 Stream/WebSocket 模式(非 HTTP webhook),因此不实现 `WebhookHandler`。 -6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 5 个 channel config 中(Telegram、Discord、Slack、LINE、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。 +6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 4 个 channel config 中(Telegram、Discord、LINE、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。 -7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、Slack、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。 +7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。 diff --git a/pkg/channels/deltachat/deltachat.go b/pkg/channels/deltachat/deltachat.go deleted file mode 100644 index 6d925372..00000000 --- a/pkg/channels/deltachat/deltachat.go +++ /dev/null @@ -1,1330 +0,0 @@ -// Package deltachat implements a PicoClaw channel for Delta Chat, an -// email-based, end-to-end encrypted messenger. -// -// PicoClaw does not link the Delta Chat core directly. Instead it drives a -// local `deltachat-rpc-server` process (shipped with the `deltachat-rpc-server` -// pip package or the precompiled release binary) over newline-delimited -// JSON-RPC 2.0 on stdio. This keeps the Go binary free of CGO/native deps. -package deltachat - -import ( - "context" - "encoding/json" - "fmt" - "net/mail" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/mdp/qrterminal/v3" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/identity" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/media" -) - -// chatTypeSingle is Delta Chat's Chattype::Single — a 1:1 direct chat. -// The wire value is a string enum ("Single", "Group", "Mailinglist", -// "OutBroadcast", "InBroadcast"); anything other than Single is a group. -const chatTypeSingle = "Single" - -// configureTimeout bounds the (network-bound) account configuration step. -const configureTimeout = 90 * time.Second - -type chatmailRelay struct { - Domain string - Location string -} - -// Keep this list in sync with Parla's CHATMAIL_RELAYS in ../parla/src/relay_picker.vala. -var defaultChatmailRelays = []chatmailRelay{ - {"nine.testrun.org", "Default"}, - {"mehl.cloud", "German"}, - {"mailchat.pl", "Poland"}, - {"chatmail.woodpeckersnest.space", "Italy"}, - {"chatmail.culturanerd.it", "Italy"}, - {"chat.adminforge.de", "Falkenstein, Germany"}, - {"chika.aangat.lahat.computer", "Santa Clara, USA"}, - {"tarpit.fun", "Nuremberg, Germany"}, - {"d.gaufr.es", "Roubaix, France"}, - {"chtml.ca", "Quebec, Canada"}, - {"chatmail.au", "Melbourne, Australia"}, - {"e2ee.wang", "Johannesburg, South Africa"}, - {"chat.privittytech.com", "Bangalore, India"}, - {"e2ee.im", "Orastie, Romania"}, - {"chatmail.email", "Warsaw, Poland"}, - {"danneskjold.de", "Helsinki, Finland"}, - {"chat.in-the.eu", "Falkenstein, Germany"}, - {"chat.nuvon.app", "Prague, Czechia"}, - {"nibblehole.com", "Zug, Switzerland"}, - {"chat.zashm.org", "Lviv, Ukraine"}, - {"chat.sus.fr", "Iceland/Japan/Kenya/South Africa"}, - {"delta.thelab.uno", "Gravelines, France"}, - {"chat.vim.wtf", "Frankfurt, Germany"}, - {"uninterest.ing", "Elk Grove Village, USA"}, - {"sweetfern.net", "Ashburn, USA"}, - {"delta.disobey.net", "Roon, Netherlands"}, -} - -var managedAccountConfigKeys = []string{ - "addr", - "mail_server", - "mail_port", - "send_server", - "send_port", -} - -// dcAccount is one entry from get_all_accounts. -type dcAccount struct { - ID int64 `json:"id"` - Kind string `json:"kind"` - Addr string `json:"addr"` -} - -// dcContact is the subset of Delta Chat's ContactObject we consume. -// NOTE: Delta Chat serializes object fields in camelCase on the wire (method -// names and config keys are snake_case, but struct fields are camelCase). -type dcContact struct { - ID int64 `json:"id"` - Address string `json:"address"` - DisplayName string `json:"displayName"` - Name string `json:"name"` - NameAndAddr string `json:"nameAndAddr"` -} - -// dcMessage is the subset of Delta Chat's MessageObject we consume. -type dcMessage struct { - ID int64 `json:"id"` - ChatID int64 `json:"chatId"` - FromID int64 `json:"fromId"` - Text string `json:"text"` - File string `json:"file"` - FileName string `json:"fileName"` - FileMime string `json:"fileMime"` - Timestamp int64 `json:"timestamp"` - IsInfo bool `json:"isInfo"` - Sender *dcContact `json:"sender"` -} - -// dcChat is the subset of Delta Chat's FullChat we consume. -type dcChat struct { - ID int64 `json:"id"` - Name string `json:"name"` - ChatType string `json:"chatType"` - IsDeviceChat bool `json:"isDeviceChat"` - CanSend bool `json:"canSend"` -} - -// dcMessageData mirrors the fields of Delta Chat's MessageData (camelCase on the -// wire) that PicoClaw sets when calling send_msg. Viewtype is normally left empty -// so Delta Chat infers it from the file (image/gif/video/file…); it is set only -// for voice replies, which must be Viewtype::Voice to render as a voice bubble -// rather than a generic audio attachment. -type dcMessageData struct { - Text string `json:"text,omitempty"` - File string `json:"file,omitempty"` - Filename string `json:"filename,omitempty"` - Viewtype string `json:"viewtype,omitempty"` -} - -// Ensure DeltaChatChannel satisfies the optional capability interfaces so the -// Manager routes media to it and the gateway advertises voice support. -var ( - _ channels.MediaSender = (*DeltaChatChannel)(nil) - _ channels.VoiceCapabilityProvider = (*DeltaChatChannel)(nil) -) - -// DeltaChatChannel implements channels.Channel on top of deltachat-rpc-server. -type DeltaChatChannel struct { - *channels.BaseChannel - bc *config.Channel - config *config.DeltaChatSettings - - serverPath string - dataDir string - - rpc *rpcClient - accountID int64 - selfAddr string - - ctx context.Context - cancel context.CancelFunc -} - -func parseDeltaChatEmailSetting(value string) (string, bool, error) { - email := strings.TrimSpace(value) - if email == "" { - return "", false, fmt.Errorf( - "deltachat: email is required.\nNext step: choose one of the chatmail servers below and set channel_list.deltachat.settings.email to %q, or use the same @server form with another chatmail relay. Run `picoclaw g` again; PicoClaw will create the account, print the generated full email address, and stop so you can save that address in the config.\nAvailable chatmail servers:\n%s", - "@"+defaultChatmailRelays[0].Domain, - formatChatmailRelayList(), - ) - } - if !strings.HasPrefix(email, "@") { - return email, false, nil - } - domain := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(email, "@"))) - if domain == "" { - return "", false, fmt.Errorf("deltachat: email %q is missing a chatmail server. Use %q or one of:\n%s", - email, "@"+defaultChatmailRelays[0].Domain, formatChatmailRelayList()) - } - if strings.Contains(domain, "@") || strings.ContainsAny(domain, "/\\ \t\r\n") { - return "", false, fmt.Errorf("deltachat: invalid chatmail server marker %q; use settings.email like %q", - email, "@"+defaultChatmailRelays[0].Domain) - } - return domain, true, nil -} - -func formatChatmailRelayList() string { - var b strings.Builder - for _, relay := range defaultChatmailRelays { - fmt.Fprintf(&b, " @%-34s %s\n", relay.Domain, relay.Location) - } - return strings.TrimRight(b.String(), "\n") -} - -func buildChatmailAccountQR(domain string) string { - return fmt.Sprintf("DCACCOUNT:https://%s/new", domain) -} - -// NewDeltaChatChannel validates config and resolves the RPC server + data dir. -func NewDeltaChatChannel( - bc *config.Channel, - cfg *config.DeltaChatSettings, - messageBus *bus.MessageBus, -) (*DeltaChatChannel, error) { - if _, _, err := parseDeltaChatEmailSetting(cfg.Email); err != nil { - return nil, err - } - - serverPath, err := resolveServerPath(cfg.RPCServerPath) - if err != nil { - return nil, err - } - dataDir := resolveDataDir(cfg.DataDir, bc.Name()) - - base := channels.NewBaseChannel(config.ChannelDeltaChat, cfg, messageBus, bc.AllowFrom, - channels.WithMaxMessageLength(0), // email has no practical length limit - channels.WithGroupTrigger(bc.GroupTrigger), - channels.WithReasoningChannelID(bc.ReasoningChannelID), - ) - - ch := &DeltaChatChannel{ - BaseChannel: base, - bc: bc, - config: cfg, - serverPath: serverPath, - dataDir: dataDir, - } - base.SetOwner(ch) - return ch, nil -} - -// Start spawns the RPC server, ensures the account is configured, and begins -// listening for messages. -func (c *DeltaChatChannel) Start(ctx context.Context) error { - logger.InfoC("deltachat", "Starting Delta Chat channel") - c.ctx, c.cancel = context.WithCancel(ctx) - - if err := os.MkdirAll(c.dataDir, 0o700); err != nil { - return fmt.Errorf("deltachat: create data dir %s: %w", c.dataDir, err) - } - - rpc, err := startRPC(c.serverPath, c.dataDir) - if err != nil { - return err - } - c.rpc = rpc - - if err := c.waitReady(c.ctx); err != nil { - c.rpc.close() - return err - } - - if err := c.ensureAccount(c.ctx); err != nil { - c.rpc.close() - return err - } - - if err := c.joinInviteLink(c.ctx); err != nil { - logger.WarnCF("deltachat", "Failed to join invite link", map[string]any{"error": err.Error()}) - } - - c.SetRunning(true) - go c.listen() - - logger.InfoCF("deltachat", "Delta Chat channel started", map[string]any{ - "email": c.selfAddr, - "account_id": c.accountID, - }) - - // Print the bot's invite link + QR so users can add it. Delta Chat / chatmail - // require end-to-end encryption, so peers must obtain the bot's key via this - // invite (adding the bare email address will not work). - c.printInviteLink(c.ctx) - - return nil -} - -// printInviteLink fetches the account-level secure-join invite link and prints -// it (with a scannable QR) to the terminal and log. -func (c *DeltaChatChannel) printInviteLink(ctx context.Context) { - raw, err := c.rpc.call(ctx, "get_chat_securejoin_qr_code", c.accountID, nil) - if err != nil { - logger.WarnCF("deltachat", "Could not generate invite link", map[string]any{"error": err.Error()}) - return - } - var link string - if err := json.Unmarshal(raw, &link); err != nil || link == "" { - return - } - - logger.InfoCF("deltachat", "Invite link", map[string]any{"link": link}) - fmt.Printf("\n📨 Delta Chat invite for %s — scan with Delta Chat (➕ → Scan/Paste QR) to message the bot:\n %s\n\n", - c.config.Email, link) - qrterminal.GenerateWithConfig(link, qrterminal.Config{ - Level: qrterminal.L, - Writer: os.Stdout, - HalfBlocks: true, - }) - fmt.Println() -} - -// Stop stops IO and terminates the RPC server. -func (c *DeltaChatChannel) Stop(ctx context.Context) error { - logger.InfoC("deltachat", "Stopping Delta Chat channel") - c.SetRunning(false) - if c.cancel != nil { - c.cancel() - } - if c.rpc != nil && c.accountID > 0 { - stopCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - _, _ = c.rpc.call(stopCtx, "stop_io", c.accountID) - cancel() - } - if c.rpc != nil { - c.rpc.close() - } - logger.InfoC("deltachat", "Delta Chat channel stopped") - return nil -} - -// Send delivers an outbound message to a Delta Chat chat. ChatID can be the -// numeric Delta Chat chat id, an email address, or a known contact/chat name. -func (c *DeltaChatChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - if strings.TrimSpace(msg.Content) == "" { - return nil, nil - } - - chatID, err := c.resolveOutboundChatID(ctx, msg.ChatID, msg.Context, msg.Scope) - if err != nil { - return nil, err - } - - // misc_send_msg(account_id, chat_id, text, file, name, location, quoted_message_id) - raw, err := c.rpc.call(ctx, "misc_send_msg", c.accountID, chatID, msg.Content, nil, nil, nil, nil) - if err != nil { - return nil, fmt.Errorf("deltachat send: %w", err) - } - - // Result is [message_id, message_object]; we only need the id. - var result []json.RawMessage - if err := json.Unmarshal(raw, &result); err == nil && len(result) > 0 { - var messageID int64 - if err := json.Unmarshal(result[0], &messageID); err == nil { - return []string{strconv.FormatInt(messageID, 10)}, nil - } - } - return nil, nil -} - -// SendMedia implements channels.MediaSender. Each part is resolved to a local -// file and delivered as its own Delta Chat message, with the part caption as the -// message text. Delta Chat copies the file into its blob store and infers the -// view type from the file itself. -func (c *DeltaChatChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - chatID, err := c.resolveOutboundChatID(ctx, msg.ChatID, msg.Context, msg.Scope) - if err != nil { - return nil, err - } - - store := c.GetMediaStore() - if store == nil { - return nil, fmt.Errorf("deltachat: no media store available: %w", channels.ErrSendFailed) - } - - var messageIDs []string - for _, part := range msg.Parts { - localPath, meta, err := store.ResolveWithMeta(part.Ref) - if err != nil { - logger.ErrorCF("deltachat", "Failed to resolve media ref", map[string]any{ - "ref": part.Ref, - "error": err.Error(), - }) - continue - } - // Delta Chat needs a path it can open from its own working directory; - // absolutize defensively in case the store ever yields a relative one. - if abs, absErr := filepath.Abs(localPath); absErr == nil { - localPath = abs - } - - data := dcMessageData{ - Text: part.Caption, - File: localPath, - Filename: part.Filename, - Viewtype: deltaChatViewtype(part, meta), - } - raw, err := c.rpc.call(ctx, "send_msg", c.accountID, chatID, data) - if err != nil { - logger.ErrorCF("deltachat", "Failed to send media", map[string]any{ - "ref": part.Ref, - "error": err.Error(), - }) - return messageIDs, fmt.Errorf("deltachat send media: %w", channels.ErrTemporary) - } - - // send_msg returns the new message id as a bare integer. - var messageID int64 - if err := json.Unmarshal(raw, &messageID); err == nil && messageID > 0 { - messageIDs = append(messageIDs, strconv.FormatInt(messageID, 10)) - } - } - - return messageIDs, nil -} - -func (c *DeltaChatChannel) resolveOutboundChatID( - ctx context.Context, - target string, - outboundCtx bus.InboundContext, - outboundScope *bus.OutboundScope, -) (int64, error) { - target = strings.TrimSpace(target) - if target == "" { - return 0, fmt.Errorf("deltachat: empty chat target: %w", channels.ErrSendFailed) - } - - if chatID, ok := parsePositiveInt64(target); ok { - if err := c.requireOutboundNumericChatAllowed(outboundCtx, outboundScope, chatID); err != nil { - return 0, err - } - return chatID, nil - } - if chatID, ok := parsePrefixedChatID(target); ok { - if err := c.requireOutboundNumericChatAllowed(outboundCtx, outboundScope, chatID); err != nil { - return 0, err - } - return chatID, nil - } - - if err := c.requireOutboundRecipientResolution(outboundCtx, outboundScope); err != nil { - return 0, err - } - - if address, ok := emailAddressFromTarget(target); ok { - chatID, err := c.resolveEmailChatID(ctx, address) - if err != nil { - return 0, fmt.Errorf("deltachat: resolve %q: %w", target, err) - } - return chatID, nil - } - - chatID, err := c.resolveAliasChatID(ctx, target) - if err != nil { - return 0, fmt.Errorf("deltachat: resolve %q: %w", target, err) - } - if chatID <= 0 { - return 0, fmt.Errorf("deltachat: unknown chat target %q: %w", target, channels.ErrSendFailed) - } - return chatID, nil -} - -func (c *DeltaChatChannel) requireOutboundNumericChatAllowed( - outboundCtx bus.InboundContext, - outboundScope *bus.OutboundScope, - chatID int64, -) error { - callerChatID := outboundCallerChatID(outboundCtx, outboundScope) - if callerChatID == "" || callerChatID == strconv.FormatInt(chatID, 10) { - return nil - } - return c.requireOutboundRecipientResolution(outboundCtx, outboundScope) -} - -func outboundCallerChatID(outboundCtx bus.InboundContext, outboundScope *bus.OutboundScope) string { - if chatID := deltaChatChatIDFromScope(outboundScope); chatID != "" { - return chatID - } - return strings.TrimSpace(outboundCtx.ChatID) -} - -func deltaChatChatIDFromScope(scope *bus.OutboundScope) string { - if scope == nil || (scope.Channel != "" && !strings.EqualFold(scope.Channel, config.ChannelDeltaChat)) { - return "" - } - chat := strings.TrimSpace(scope.Values["chat"]) - if chat == "" { - return "" - } - if _, value, ok := strings.Cut(chat, ":"); ok { - chat = value - } - if value, _, ok := strings.Cut(chat, "/"); ok { - chat = value - } - return strings.TrimSpace(chat) -} - -func (c *DeltaChatChannel) requireOutboundRecipientResolution( - outboundCtx bus.InboundContext, - outboundScope *bus.OutboundScope, -) error { - senderID := outboundSenderID(outboundCtx, outboundScope) - if c.config != nil && c.config.AllowCrosspost && c.canCrosspost(senderID) { - return nil - } - return fmt.Errorf( - "deltachat: crosspost recipient resolution is disabled or caller %q is not allowed by allow_from; enable settings.allow_crosspost and allow the sender in allow_from: %w", - senderID, - channels.ErrSendFailed, - ) -} - -func outboundSenderID(outboundCtx bus.InboundContext, outboundScope *bus.OutboundScope) string { - if senderID := strings.TrimSpace(outboundCtx.SenderID); senderID != "" { - return senderID - } - if outboundScope == nil || - (outboundScope.Channel != "" && !strings.EqualFold(outboundScope.Channel, config.ChannelDeltaChat)) { - return "" - } - return strings.TrimSpace(outboundScope.Values["sender"]) -} - -func (c *DeltaChatChannel) canCrosspost(senderID string) bool { - if c.bc == nil { - return false - } - senderID = strings.TrimSpace(senderID) - localPart, _, _ := strings.Cut(senderID, "@") - sender := bus.SenderInfo{ - Platform: config.ChannelDeltaChat, - PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID(config.ChannelDeltaChat, senderID), - Username: localPart, - } - for _, allowed := range c.bc.AllowFrom { - entry := strings.TrimSpace(allowed) - if entry == "*" { - return true - } - if entry != "" && senderID != "" && - (identity.MatchAllowed(sender, entry) || strings.EqualFold(entry, senderID)) { - return true - } - } - return false -} - -func parsePositiveInt64(value string) (int64, bool) { - id, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64) - if err != nil || id <= 0 { - return 0, false - } - return id, true -} - -func parsePrefixedChatID(value string) (int64, bool) { - prefix, id, ok := strings.Cut(strings.TrimSpace(value), ":") - if !ok { - return 0, false - } - switch strings.ToLower(strings.TrimSpace(prefix)) { - case "chat", "chatid", "chat_id", config.ChannelDeltaChat: - return parsePositiveInt64(id) - default: - return 0, false - } -} - -func emailAddressFromTarget(target string) (string, bool) { - target = strings.TrimSpace(target) - if target == "" { - return "", false - } - if strings.HasPrefix(strings.ToLower(target), "mailto:") { - target = strings.TrimSpace(target[len("mailto:"):]) - if before, _, ok := strings.Cut(target, "?"); ok { - target = before - } - } - if !strings.Contains(target, "@") { - return "", false - } - if parsed, err := mail.ParseAddress(target); err == nil && parsed.Address != "" { - return strings.ToLower(parsed.Address), true - } - if strings.Count(target, "@") == 1 && !strings.ContainsAny(target, " \t\r\n<>") { - return strings.ToLower(target), true - } - return "", false -} - -func (c *DeltaChatChannel) resolveEmailChatID(ctx context.Context, address string) (int64, error) { - contactID, err := c.lookupContactIDByAddress(ctx, address) - if err != nil { - return 0, err - } - if contactID <= 0 { - contactID, err = c.createContact(ctx, address, "") - if err != nil { - return 0, err - } - } - return c.chatIDForContact(ctx, contactID) -} - -func (c *DeltaChatChannel) lookupContactIDByAddress(ctx context.Context, address string) (int64, error) { - raw, err := c.rpc.call(ctx, "lookup_contact_id_by_addr", c.accountID, address) - if err != nil { - return 0, fmt.Errorf("lookup contact by address: %w", err) - } - return decodeOptionalInt64(raw, "lookup contact by address") -} - -func (c *DeltaChatChannel) createContact(ctx context.Context, address, name string) (int64, error) { - var displayName any - if strings.TrimSpace(name) != "" { - displayName = strings.TrimSpace(name) - } - raw, err := c.rpc.call(ctx, "create_contact", c.accountID, address, displayName) - if err != nil { - return 0, fmt.Errorf("create contact: %w", err) - } - var contactID int64 - if err := json.Unmarshal(raw, &contactID); err != nil { - return 0, fmt.Errorf("create contact decode: %w", err) - } - if contactID <= 0 { - return 0, fmt.Errorf("create contact returned empty id: %w", channels.ErrSendFailed) - } - return contactID, nil -} - -func (c *DeltaChatChannel) chatIDForContact(ctx context.Context, contactID int64) (int64, error) { - raw, err := c.rpc.call(ctx, "get_chat_id_by_contact_id", c.accountID, contactID) - if err != nil { - return 0, fmt.Errorf("get chat by contact: %w", err) - } - chatID, err := decodeOptionalInt64(raw, "get chat by contact") - if err != nil { - return 0, err - } - if chatID > 0 { - return chatID, nil - } - - raw, err = c.rpc.call(ctx, "create_chat_by_contact_id", c.accountID, contactID) - if err != nil { - return 0, fmt.Errorf("create chat by contact: %w", err) - } - if err := json.Unmarshal(raw, &chatID); err != nil { - return 0, fmt.Errorf("create chat by contact decode: %w", err) - } - if chatID <= 0 { - return 0, fmt.Errorf("create chat by contact returned empty id: %w", channels.ErrSendFailed) - } - return chatID, nil -} - -func decodeOptionalInt64(raw json.RawMessage, label string) (int64, error) { - var id *int64 - if err := json.Unmarshal(raw, &id); err != nil { - return 0, fmt.Errorf("%s decode: %w", label, err) - } - if id == nil { - return 0, nil - } - return *id, nil -} - -func (c *DeltaChatChannel) resolveAliasChatID(ctx context.Context, target string) (int64, error) { - for _, query := range aliasQueries(target) { - contacts, err := c.findMatchingContacts(ctx, query) - if err != nil { - return 0, err - } - if len(contacts) == 1 { - return c.chatIDForContact(ctx, contacts[0].ID) - } - if len(contacts) > 1 { - return 0, ambiguousRecipientError(target, contactRecipientLabels(contacts)) - } - - chats, err := c.findMatchingChats(ctx, query) - if err != nil { - return 0, err - } - if len(chats) == 1 { - return chats[0].ID, nil - } - if len(chats) > 1 { - return 0, ambiguousRecipientError(target, chatRecipientLabels(chats)) - } - } - return 0, nil -} - -func aliasQueries(target string) []string { - target = strings.TrimSpace(target) - if target == "" { - return nil - } - queries := []string{target} - if unwrapped := strings.Trim(target, "<>"); unwrapped != "" && unwrapped != target { - queries = append(queries, unwrapped) - } - if unprefixed := strings.TrimPrefix(target, "@"); unprefixed != "" && unprefixed != target { - queries = append(queries, unprefixed) - } - return uniqueStrings(queries) -} - -func uniqueStrings(values []string) []string { - seen := make(map[string]struct{}, len(values)) - out := make([]string, 0, len(values)) - for _, value := range values { - value = strings.TrimSpace(value) - if value == "" { - continue - } - key := strings.ToLower(value) - if _, ok := seen[key]; ok { - continue - } - seen[key] = struct{}{} - out = append(out, value) - } - return out -} - -func (c *DeltaChatChannel) findMatchingContacts(ctx context.Context, query string) ([]dcContact, error) { - raw, err := c.rpc.call(ctx, "get_contacts", c.accountID, 0, query) - if err != nil { - return nil, fmt.Errorf("search contacts: %w", err) - } - var contacts []dcContact - if err := json.Unmarshal(raw, &contacts); err != nil { - return nil, fmt.Errorf("search contacts decode: %w", err) - } - contacts = uniqueContacts(contacts) - if exact := exactContactMatches(query, contacts); len(exact) > 0 { - return exact, nil - } - if len(contacts) == 1 { - return contacts, nil - } - return nil, nil -} - -func uniqueContacts(contacts []dcContact) []dcContact { - seen := make(map[int64]struct{}, len(contacts)) - out := make([]dcContact, 0, len(contacts)) - for _, contact := range contacts { - if contact.ID <= 0 { - continue - } - if _, ok := seen[contact.ID]; ok { - continue - } - seen[contact.ID] = struct{}{} - out = append(out, contact) - } - return out -} - -func exactContactMatches(query string, contacts []dcContact) []dcContact { - var matches []dcContact - for _, contact := range contacts { - if contactMatchesAlias(contact, query) { - matches = append(matches, contact) - } - } - return matches -} - -func contactMatchesAlias(contact dcContact, query string) bool { - query = strings.TrimSpace(query) - if query == "" { - return false - } - aliases := []string{ - contact.DisplayName, - contact.Name, - contact.Address, - contact.NameAndAddr, - } - if local, _, ok := strings.Cut(contact.Address, "@"); ok { - aliases = append(aliases, local, "@"+local) - } - for _, alias := range aliases { - if strings.EqualFold(strings.TrimSpace(alias), query) { - return true - } - } - return false -} - -func (c *DeltaChatChannel) findMatchingChats(ctx context.Context, query string) ([]dcChat, error) { - raw, err := c.rpc.call(ctx, "get_chatlist_entries", c.accountID, 0, query, nil) - if err != nil { - return nil, fmt.Errorf("search chats: %w", err) - } - var chatIDs []int64 - if err := json.Unmarshal(raw, &chatIDs); err != nil { - return nil, fmt.Errorf("search chats decode: %w", err) - } - var chats []dcChat - for _, chatID := range uniqueInt64s(chatIDs) { - if chatID <= 0 { - continue - } - chat, err := c.getFullChatByContext(ctx, chatID) - if err != nil { - return nil, err - } - if chat.IsDeviceChat { - continue - } - chats = append(chats, *chat) - } - if exact := exactChatMatches(query, chats); len(exact) > 0 { - return exact, nil - } - if len(chats) == 1 { - return chats, nil - } - return nil, nil -} - -func uniqueInt64s(values []int64) []int64 { - seen := make(map[int64]struct{}, len(values)) - out := make([]int64, 0, len(values)) - for _, value := range values { - if _, ok := seen[value]; ok { - continue - } - seen[value] = struct{}{} - out = append(out, value) - } - return out -} - -func exactChatMatches(query string, chats []dcChat) []dcChat { - var matches []dcChat - for _, chat := range chats { - if strings.EqualFold(strings.TrimSpace(chat.Name), strings.TrimSpace(query)) { - matches = append(matches, chat) - } - } - return matches -} - -func (c *DeltaChatChannel) getFullChatByContext(ctx context.Context, chatID int64) (*dcChat, error) { - raw, err := c.rpc.call(ctx, "get_full_chat_by_id", c.accountID, chatID) - if err != nil { - return nil, fmt.Errorf("get chat %d: %w", chatID, err) - } - var chat dcChat - if err := json.Unmarshal(raw, &chat); err != nil { - return nil, fmt.Errorf("get chat %d decode: %w", chatID, err) - } - return &chat, nil -} - -func ambiguousRecipientError(target string, labels []string) error { - return fmt.Errorf( - "ambiguous recipient %q matches %s: %w", - target, - strings.Join(labels, ", "), - channels.ErrSendFailed, - ) -} - -func contactRecipientLabels(contacts []dcContact) []string { - labels := make([]string, 0, len(contacts)) - for _, contact := range contacts { - name := strings.TrimSpace(contact.DisplayName) - if name == "" { - name = strings.TrimSpace(contact.Name) - } - if name != "" && contact.Address != "" { - labels = append(labels, fmt.Sprintf("%s <%s>", name, contact.Address)) - } else if contact.Address != "" { - labels = append(labels, contact.Address) - } else { - labels = append(labels, strconv.FormatInt(contact.ID, 10)) - } - } - return labels -} - -func chatRecipientLabels(chats []dcChat) []string { - labels := make([]string, 0, len(chats)) - for _, chat := range chats { - name := strings.TrimSpace(chat.Name) - if name == "" { - name = strconv.FormatInt(chat.ID, 10) - } - labels = append(labels, fmt.Sprintf("%s (chat %d)", name, chat.ID)) - } - return labels -} - -// deltaChatViewtype returns the explicit Delta Chat view type for an outbound -// media part, or "" to let Delta Chat infer it from the file. Only voice replies -// are forced (to Viewtype::Voice) so they render as playable voice bubbles; -// images, GIFs, and video keep Delta Chat's native auto-detection. A part is -// treated as voice when it is audio and either came from the send_tts tool or -// carries a "voice" filename hint (matching the convention other channels use). -func deltaChatViewtype(part bus.MediaPart, meta media.MediaMeta) string { - isAudio := part.Type == "audio" || - strings.HasPrefix(strings.ToLower(part.ContentType), "audio/") || - strings.HasPrefix(strings.ToLower(meta.ContentType), "audio/") - if !isAudio { - return "" - } - - name := strings.ToLower(part.Filename) - if name == "" { - name = strings.ToLower(meta.Filename) - } - if meta.Source == "tool:send_tts" || strings.Contains(name, "voice") { - return "Voice" - } - return "" -} - -// VoiceCapabilities implements channels.VoiceCapabilityProvider. Delta Chat can -// receive voice notes (which the agent's ASR transcribes) and deliver -// synthesized speech as voice messages, so it advertises both ASR and TTS. The -// gateway still gates actual availability on configured ASR/TTS providers. -func (c *DeltaChatChannel) VoiceCapabilities() channels.VoiceCapabilities { - return channels.VoiceCapabilities{ASR: true, TTS: true} -} - -// StartTyping implements channels.TypingCapable. Delta Chat has no typing -// indicator over email, so this is a no-op that satisfies the interface and -// lets the Manager skip the placeholder dance gracefully. -func (c *DeltaChatChannel) StartTyping(ctx context.Context, chatID string) (func(), error) { - return func() {}, nil -} - -// waitReady polls get_system_info until the RPC server responds. -func (c *DeltaChatChannel) waitReady(ctx context.Context) error { - for attempt := 0; attempt < 40; attempt++ { - if ctx.Err() != nil { - return ctx.Err() - } - callCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - _, err := c.rpc.call(callCtx, "get_system_info") - cancel() - if err == nil { - return nil - } - time.Sleep(250 * time.Millisecond) - } - return fmt.Errorf("deltachat: rpc server did not become ready") -} - -// ensureAccount finds or creates the configured account and starts its IO. -func (c *DeltaChatChannel) ensureAccount(ctx context.Context) error { - server, bootstrap, err := parseDeltaChatEmailSetting(c.config.Email) - if err != nil { - return err - } - if bootstrap { - return c.createChatmailBootstrapAccount(ctx, server) - } - - c.selfAddr = strings.ToLower(c.config.Email) - - accounts, err := c.listAccounts(ctx) - if err != nil { - return err - } - - var accountID int64 - for _, acc := range accounts { - if acc.Kind == "Configured" && strings.EqualFold(acc.Addr, c.config.Email) { - accountID = acc.ID - break - } - } - - if accountID == 0 { - if c.config.Password.String() == "" { - return c.passwordRequiredError("account not found") - } - - raw, callErr := c.rpc.call(ctx, "add_account") - if callErr != nil { - return fmt.Errorf("deltachat add_account: %w", callErr) - } - if decErr := json.Unmarshal(raw, &accountID); decErr != nil { - return fmt.Errorf("deltachat add_account decode: %w", decErr) - } - } - - configured, err := c.isConfigured(ctx, accountID) - if err != nil { - return err - } - if !configured { - if err := c.configureAccount(ctx, accountID); err != nil { - return err - } - } else if c.config.Password.String() != "" { - changed, err := c.accountConfigChanged(ctx, accountID) - if err != nil { - logger.WarnCF("deltachat", "Could not read account config; reconfiguring", map[string]any{ - "email": c.config.Email, - "error": err.Error(), - }) - changed = true - } - if changed { - if err := c.configureAccount(ctx, accountID); err != nil { - return err - } - } - } - - if _, err := c.rpc.call(ctx, "select_account", accountID); err != nil { - return fmt.Errorf("deltachat select_account: %w", err) - } - if err := c.applyProfileConfig(ctx, accountID); err != nil { - return err - } - // Mark this account as a bot so the core delivers all messages to us. - if _, err := c.rpc.call(ctx, "batch_set_config", accountID, map[string]string{"bot": "1"}); err != nil { - return fmt.Errorf("deltachat set bot config: %w", err) - } - if _, err := c.rpc.call(ctx, "start_io", accountID); err != nil { - return fmt.Errorf("deltachat start_io: %w", err) - } - - c.accountID = accountID - return nil -} - -func (c *DeltaChatChannel) createChatmailBootstrapAccount(ctx context.Context, server string) error { - raw, err := c.rpc.call(ctx, "add_account") - if err != nil { - return fmt.Errorf("deltachat add_account: %w", err) - } - var accountID int64 - if decodeErr := json.Unmarshal(raw, &accountID); decodeErr != nil { - return fmt.Errorf("deltachat add_account decode: %w", decodeErr) - } - - created := false - defer func() { - if !created { - c.cleanupPendingAccount(context.Background(), accountID) - } - }() - - confCtx, cancel := context.WithTimeout(ctx, configureTimeout) - defer cancel() - if _, callErr := c.rpc.call( - confCtx, - "add_transport_from_qr", - accountID, - buildChatmailAccountQR(server), - ); callErr != nil { - return fmt.Errorf("deltachat create chatmail account on %s: %w", server, callErr) - } - created = true - - if profileErr := c.applyProfileConfig(ctx, accountID); profileErr != nil { - logger.WarnCF( - "deltachat", - "Could not apply profile config to new account", - map[string]any{"error": profileErr.Error()}, - ) - } - - addr, err := c.getAccountConfigString(ctx, accountID, "addr") - if err != nil { - return fmt.Errorf("deltachat created account on %s, but could not read generated email: %w", server, err) - } - addr = strings.TrimSpace(addr) - if addr == "" { - return fmt.Errorf("deltachat created account on %s, but generated email is empty", server) - } - - return fmt.Errorf( - "deltachat: created chatmail account %q on %s. Update channel_list.deltachat.settings.email from %q to %q, remove the @server bootstrap marker, then run PicoClaw again to use the account", - addr, - server, - c.config.Email, - addr, - ) -} - -func (c *DeltaChatChannel) cleanupPendingAccount(ctx context.Context, accountID int64) { - if accountID <= 0 || c.rpc == nil { - return - } - stopCtx, cancel := context.WithTimeout(ctx, 10*time.Second) - _, _ = c.rpc.call(stopCtx, "stop_ongoing_process", accountID) - cancel() - - removeCtx, cancel := context.WithTimeout(ctx, 10*time.Second) - _, _ = c.rpc.call(removeCtx, "remove_account", accountID) - cancel() -} - -func (c *DeltaChatChannel) getAccountConfigString(ctx context.Context, accountID int64, key string) (string, error) { - raw, err := c.rpc.call(ctx, "get_config", accountID, key) - if err != nil { - return "", fmt.Errorf("get config %s: %w", key, err) - } - var value *string - if err := json.Unmarshal(raw, &value); err != nil { - return "", fmt.Errorf("decode config %s: %w", key, err) - } - if value == nil { - return "", nil - } - return *value, nil -} - -func (c *DeltaChatChannel) passwordRequiredError(reason string) error { - return fmt.Errorf("deltachat: account %s is not configured in data_dir %s (%s)", - c.config.Email, c.dataDir, reason) -} - -func (c *DeltaChatChannel) applyProfileConfig(ctx context.Context, accountID int64) error { - cfgMap := map[string]*string{} - if name := strings.TrimSpace(c.config.DisplayName); name != "" { - cfgMap["displayname"] = accountConfigString(name) - } - if avatar := strings.TrimSpace(c.config.AvatarImage); avatar != "" { - avatar = expandHome(avatar) - if !fileExists(avatar) { - logger.WarnCF("deltachat", "avatar_image not found; leaving current avatar unchanged", map[string]any{ - "avatar_image": avatar, - }) - } else { - cfgMap["selfavatar"] = accountConfigString(avatar) - } - } - if len(cfgMap) == 0 { - return nil - } - if _, err := c.rpc.call(ctx, "batch_set_config", accountID, cfgMap); err != nil { - return fmt.Errorf("deltachat set profile config: %w", err) - } - return nil -} - -// configureAccount writes the managed account settings and runs the (network-bound) -// provider auto-configuration. -func (c *DeltaChatChannel) configureAccount(ctx context.Context, accountID int64) error { - if c.config.Password.String() == "" { - return c.passwordRequiredError("account is not configured") - } - - cfgMap := accountConfigMap(c.config) - if _, err := c.rpc.call(ctx, "batch_set_config", accountID, cfgMap); err != nil { - return fmt.Errorf("deltachat set account config: %w", err) - } - - logger.InfoCF("deltachat", "Configuring account (validating credentials)", map[string]any{ - "email": c.config.Email, - }) - confCtx, cancel := context.WithTimeout(ctx, configureTimeout) - defer cancel() - if _, err := c.rpc.call(confCtx, "configure", accountID); err != nil { - return fmt.Errorf("deltachat configure (check email/password/server): %w", err) - } - return nil -} - -func (c *DeltaChatChannel) accountConfigChanged(ctx context.Context, accountID int64) (bool, error) { - want := accountConfigMap(c.config) - for _, key := range managedAccountConfigKeys { - raw, err := c.rpc.call(ctx, "get_config", accountID, key) - if err != nil { - return false, fmt.Errorf("deltachat get config %s: %w", key, err) - } - var got *string - if err := json.Unmarshal(raw, &got); err != nil { - return false, fmt.Errorf("deltachat get config %s decode: %w", key, err) - } - if !accountConfigValueEqual(got, want[key]) { - logger.InfoCF("deltachat", "Account config changed; reconfiguring", map[string]any{ - "email": c.config.Email, - "key": key, - }) - return true, nil - } - } - return false, nil -} - -func accountConfigValueEqual(got, want *string) bool { - if want == nil { - return got == nil || *got == "" - } - if got == nil { - return *want == "" - } - return *got == *want -} - -func accountConfigMap(cfg *config.DeltaChatSettings) map[string]*string { - cfgMap := map[string]*string{ - "addr": accountConfigString(cfg.Email), - "mail_server": accountConfigOptionalString(cfg.IMAPServer), - "mail_port": accountConfigOptionalInt(cfg.IMAPPort), - "send_server": accountConfigOptionalString(cfg.SMTPServer), - "send_port": accountConfigOptionalInt(cfg.SMTPPort), - } - if password := cfg.Password.String(); password != "" { - cfgMap["mail_pw"] = accountConfigString(password) - } - return cfgMap -} - -func accountConfigString(value string) *string { - return &value -} - -func accountConfigOptionalString(value string) *string { - if value == "" { - return nil - } - return accountConfigString(value) -} - -func accountConfigOptionalInt(value int) *string { - if value <= 0 { - return nil - } - return accountConfigString(strconv.Itoa(value)) -} - -func (c *DeltaChatChannel) listAccounts(ctx context.Context) ([]dcAccount, error) { - raw, err := c.rpc.call(ctx, "get_all_accounts") - if err != nil { - return nil, fmt.Errorf("deltachat get_all_accounts: %w", err) - } - var accounts []dcAccount - if err := json.Unmarshal(raw, &accounts); err != nil { - return nil, fmt.Errorf("deltachat get_all_accounts decode: %w", err) - } - return accounts, nil -} - -func (c *DeltaChatChannel) isConfigured(ctx context.Context, accountID int64) (bool, error) { - raw, err := c.rpc.call(ctx, "is_configured", accountID) - if err != nil { - return false, fmt.Errorf("deltachat is_configured: %w", err) - } - var ok bool - if err := json.Unmarshal(raw, &ok); err != nil { - return false, fmt.Errorf("deltachat is_configured decode: %w", err) - } - return ok, nil -} - -// joinInviteLink optionally joins a chat via a configured invite/QR link. -func (c *DeltaChatChannel) joinInviteLink(ctx context.Context) error { - link := strings.TrimSpace(c.config.InviteLink) - if link == "" { - return nil - } - chatRaw, err := c.rpc.call(ctx, "secure_join", c.accountID, link) - if err != nil { - return err - } - var chatID int64 - if err := json.Unmarshal(chatRaw, &chatID); err == nil && chatID > 0 { - _, _ = c.rpc.call(ctx, "accept_chat", c.accountID, chatID) - logger.InfoCF("deltachat", "Joined invite chat", map[string]any{"chat_id": chatID}) - } - return nil -} - -// resolveServerPath validates the configured deltachat-rpc-server path, or -// falls back to deltachat-rpc-server on PATH. -func resolveServerPath(configured string) (string, error) { - if configured == "" { - p, err := exec.LookPath("deltachat-rpc-server") - if err != nil { - return "", fmt.Errorf("deltachat: deltachat-rpc-server not found on PATH " + - "(set rpc_server_path to the binary path if it is installed elsewhere)") - } - return p, nil - } - p := expandHome(configured) - if !fileExists(p) { - return "", fmt.Errorf("deltachat: rpc_server_path %q not found", p) - } - return p, nil -} - -// resolveDataDir picks where the account database lives. -func resolveDataDir(configured, channelName string) string { - if configured != "" { - return expandHome(configured) - } - home, err := os.UserHomeDir() - if err != nil { - home = "." - } - name := channelName - if name == "" { - name = config.ChannelDeltaChat - } - return filepath.Join(home, ".picoclaw", "deltachat", name) -} - -func expandHome(path string) string { - if path == "" || path[0] != '~' { - return path - } - home, err := os.UserHomeDir() - if err != nil { - return path - } - if len(path) == 1 { - return home - } - if path[1] == '/' { - return filepath.Join(home, path[2:]) - } - return path -} - -func fileExists(p string) bool { - info, err := os.Stat(p) - return err == nil && !info.IsDir() -} diff --git a/pkg/channels/deltachat/deltachat_test.go b/pkg/channels/deltachat/deltachat_test.go deleted file mode 100644 index bc46d40f..00000000 --- a/pkg/channels/deltachat/deltachat_test.go +++ /dev/null @@ -1,1254 +0,0 @@ -package deltachat - -import ( - "bufio" - "context" - "encoding/json" - "io" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/media" -) - -func TestNewDeltaChatChannel(t *testing.T) { - msgBus := bus.NewMessageBus() - - // A fake rpc server so resolveServerPath succeeds regardless of host setup. - fakeServer := filepath.Join(t.TempDir(), "deltachat-rpc-server") - if err := os.WriteFile(fakeServer, []byte("#!/bin/sh\n"), 0o755); err != nil { - t.Fatal(err) - } - - t.Run("missing email", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelDeltaChat, Enabled: true} - cfg := &config.DeltaChatSettings{Password: *config.NewSecureString("pw"), RPCServerPath: fakeServer} - _, err := NewDeltaChatChannel(bc, cfg, msgBus) - if err == nil { - t.Fatal("expected error for missing email") - } - if !strings.Contains(err.Error(), "@nine.testrun.org") { - t.Fatalf("error = %v, want bootstrap server guidance", err) - } - if !strings.Contains(err.Error(), "Next step:") || !strings.Contains(err.Error(), "picoclaw g") { - t.Fatalf("error = %v, want next-step guidance", err) - } - }) - - t.Run("bootstrap server marker", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelDeltaChat, Enabled: true} - cfg := &config.DeltaChatSettings{Email: "@mehl.cloud", RPCServerPath: fakeServer} - if _, err := NewDeltaChatChannel(bc, cfg, msgBus); err != nil { - t.Fatalf("unexpected error for bootstrap marker: %v", err) - } - }) - - t.Run("password optional for existing account reference", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelDeltaChat, Enabled: true} - cfg := &config.DeltaChatSettings{Email: "bot@example.org", RPCServerPath: fakeServer} - if _, err := NewDeltaChatChannel(bc, cfg, msgBus); err != nil { - t.Fatalf("unexpected error without password: %v", err) - } - }) - - t.Run("missing rpc server", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelDeltaChat, Enabled: true} - cfg := &config.DeltaChatSettings{ - Email: "bot@example.org", - Password: *config.NewSecureString("pw"), - RPCServerPath: filepath.Join(t.TempDir(), "does-not-exist"), - } - if _, err := NewDeltaChatChannel(bc, cfg, msgBus); err == nil { - t.Error("expected error for missing rpc server path") - } - }) - - t.Run("valid config", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelDeltaChat, Enabled: true} - cfg := &config.DeltaChatSettings{ - Email: "bot@example.org", - Password: *config.NewSecureString("pw"), - RPCServerPath: fakeServer, - DataDir: t.TempDir(), - } - ch, err := NewDeltaChatChannel(bc, cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ch.Name() != config.ChannelDeltaChat { - t.Errorf("Name() = %q, want %q", ch.Name(), config.ChannelDeltaChat) - } - if ch.IsRunning() { - t.Error("new channel should not be running") - } - }) -} - -func TestResolveServerPathUsesPATH(t *testing.T) { - dir := t.TempDir() - fakeServer := filepath.Join(dir, "deltachat-rpc-server") - if err := os.WriteFile(fakeServer, []byte("#!/bin/sh\n"), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", dir) - - got, err := resolveServerPath("") - if err != nil { - t.Fatalf("resolveServerPath: %v", err) - } - if got != fakeServer { - t.Fatalf("resolveServerPath() = %q, want %q", got, fakeServer) - } -} - -func TestMentionsBot(t *testing.T) { - tests := []struct { - name string - content string - displayName string - email string - want bool - }{ - {"display name", "hey PicoBot can you help", "PicoBot", "bot@example.org", true}, - {"case insensitive name", "hey picobot", "PicoBot", "bot@example.org", true}, - {"short display name exact", "hey bot can you help", "bot", "bot@example.org", true}, - {"short display name with punctuation", "AI, summarize this", "ai", "bot@example.org", true}, - {"multi word display name", "hey PicoClaw Bot, can you help", "PicoClaw Bot", "bot@example.org", true}, - {"email local part", "@bot please summarize", "", "bot@example.org", true}, - {"email local part with punctuation", "please summarize, @bot.", "", "bot@example.org", true}, - {"no mention", "just chatting here", "PicoBot", "bot@example.org", false}, - {"local part without @", "the robot is cool", "", "bot@example.org", false}, - {"short display name inside word", "the robot is cool", "bot", "bot@example.org", false}, - {"short display name inside mail", "please email me later", "ai", "bot@example.org", false}, - {"display name with prefix word", "hey SuperPicoClaw Bot", "PicoClaw Bot", "bot@example.org", false}, - {"email local part inside handle", "hello @botanic", "", "bot@example.org", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := mentionsBot(tt.content, tt.displayName, tt.email); got != tt.want { - t.Errorf("mentionsBot(%q, %q, %q) = %v, want %v", tt.content, tt.displayName, tt.email, got, tt.want) - } - }) - } -} - -func TestExpandHome(t *testing.T) { - home, _ := os.UserHomeDir() - tests := []struct { - in string - want string - }{ - {"", ""}, - {"/abs/path", "/abs/path"}, - {"~", home}, - {"~/sub", filepath.Join(home, "sub")}, - {"relative", "relative"}, - } - for _, tt := range tests { - if got := expandHome(tt.in); got != tt.want { - t.Errorf("expandHome(%q) = %q, want %q", tt.in, got, tt.want) - } - } -} - -func TestResolveDataDir(t *testing.T) { - if got := resolveDataDir("/explicit/dir", "x"); got != "/explicit/dir" { - t.Errorf("explicit data dir = %q, want /explicit/dir", got) - } - home, _ := os.UserHomeDir() - want := filepath.Join(home, ".picoclaw", "deltachat", "mychan") - if got := resolveDataDir("", "mychan"); got != want { - t.Errorf("default data dir = %q, want %q", got, want) - } -} - -func TestHandleMessageMarksSeenOnlyAfterDispatch(t *testing.T) { - tests := []struct { - name string - chatType string - mentionOnly bool - closeBus bool - wantSeen bool - }{ - {name: "successful dispatch", chatType: chatTypeSingle, wantSeen: true}, - {name: "ignored group trigger", chatType: "Group", mentionOnly: true}, - {name: "failed local publish", chatType: chatTypeSingle, closeBus: true}, - } - - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - messageID := int64(42 + i) - chat := dcChat{ID: 99, Name: "chat", ChatType: tt.chatType} - msgBus := bus.NewMessageBus() - if tt.closeBus { - msgBus.Close() - } else { - defer msgBus.Close() - } - - ch := newTestChannelWithBus(t, msgBus, func(bc *config.Channel) { - bc.GroupTrigger.MentionOnly = tt.mentionOnly - }) - ch.ctx = context.Background() - ch.accountID = 7 - ch.selfAddr = "bot@example.org" - - markSeen := make(chan struct{}, 1) - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_message": - return rpcResult(req, dcMessage{ - ID: messageID, - ChatID: chat.ID, - Text: "hello", - Sender: &dcContact{Address: "alice@example.org", DisplayName: "Alice"}, - }) - case "get_full_chat_by_id": - return rpcResult(req, chat) - case "markseen_msgs": - markSeen <- struct{}{} - return rpcResult(req, nil) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - ch.handleMessage(messageID) - - gotSeen := false - select { - case <-markSeen: - gotSeen = true - default: - } - if gotSeen != tt.wantSeen { - t.Fatalf("markseen called = %v, want %v", gotSeen, tt.wantSeen) - } - }) - } -} - -func TestDeltaChatSettingsDecode(t *testing.T) { - raw := []byte(`{ - "enabled": true, - "type": "deltachat", - "allow_from": ["alice@example.org"], - "settings": { - "email": "bot@example.org", - "display_name": "PicoBot", - "avatar_image": "/tmp/picobot.png", - "allow_crosspost": true, - "imap_port": 993 - } - }`) - var bc config.Channel - if err := json.Unmarshal(raw, &bc); err != nil { - t.Fatalf("unmarshal: %v", err) - } - bc.Type = config.ChannelDeltaChat - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("decode: %v", err) - } - cfg, ok := decoded.(*config.DeltaChatSettings) - if !ok { - t.Fatalf("decoded type = %T, want *config.DeltaChatSettings", decoded) - } - if cfg.Email != "bot@example.org" { - t.Errorf("email = %q, want bot@example.org", cfg.Email) - } - if cfg.DisplayName != "PicoBot" { - t.Errorf("display_name = %q, want PicoBot", cfg.DisplayName) - } - if cfg.AvatarImage != "/tmp/picobot.png" { - t.Errorf("avatar_image = %q, want /tmp/picobot.png", cfg.AvatarImage) - } - if cfg.IMAPPort != 993 { - t.Errorf("imap_port = %d, want 993", cfg.IMAPPort) - } - if !cfg.AllowCrosspost { - t.Error("allow_crosspost = false, want true") - } -} - -func TestEnsureAccountReconfiguresConfiguredAccountWhenSettingsChange(t *testing.T) { - ch := newTestChannel(t) - ch.config.DisplayName = "New Bot" - ch.config.IMAPServer = "imap.example.org" - ch.config.IMAPPort = 993 - ch.config.SMTPServer = "smtp.example.org" - ch.config.SMTPPort = 587 - - configureCalls := 0 - accountConfigCalls := 0 - var capturedConfig map[string]any - - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_all_accounts": - return rpcResult(req, []dcAccount{{ID: 7, Kind: "Configured", Addr: "bot@example.org"}}) - case "is_configured": - return rpcResult(req, true) - case "get_config": - key, _ := req.Params[1].(string) - current := map[string]*string{ - "addr": strPtr("bot@example.org"), - "mail_pw": strPtr("old-pw"), - "displayname": strPtr("Old Bot"), - } - return rpcResult(req, current[key]) - case "batch_set_config": - if cfg, ok := req.Params[1].(map[string]any); ok { - if _, ok := cfg["mail_pw"]; ok { - accountConfigCalls++ - capturedConfig = cfg - } - } - return rpcResult(req, nil) - case "configure": - configureCalls++ - return rpcResult(req, nil) - case "select_account", "start_io": - return rpcResult(req, nil) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - if err := ch.ensureAccount(context.Background()); err != nil { - t.Fatalf("ensureAccount: %v", err) - } - if configureCalls != 1 { - t.Fatalf("configure calls = %d, want 1", configureCalls) - } - if accountConfigCalls != 1 { - t.Fatalf("account batch_set_config calls = %d, want 1", accountConfigCalls) - } - if capturedConfig["mail_pw"] != "pw" { - t.Errorf("mail_pw = %v, want pw", capturedConfig["mail_pw"]) - } - if capturedConfig["mail_server"] != "imap.example.org" { - t.Errorf("mail_server = %v, want imap.example.org", capturedConfig["mail_server"]) - } - if capturedConfig["mail_port"] != "993" { - t.Errorf("mail_port = %v, want 993", capturedConfig["mail_port"]) - } - if capturedConfig["send_server"] != "smtp.example.org" { - t.Errorf("send_server = %v, want smtp.example.org", capturedConfig["send_server"]) - } - if capturedConfig["send_port"] != "587" { - t.Errorf("send_port = %v, want 587", capturedConfig["send_port"]) - } -} - -func TestEnsureAccountSkipsConfiguredAccountWhenSettingsMatch(t *testing.T) { - ch := newTestChannel(t) - ch.config.DisplayName = "Pico Bot" - ch.config.IMAPServer = "imap.example.org" - ch.config.IMAPPort = 993 - ch.config.SMTPServer = "smtp.example.org" - ch.config.SMTPPort = 587 - - configureCalls := 0 - accountConfigCalls := 0 - - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_all_accounts": - return rpcResult(req, []dcAccount{{ID: 7, Kind: "Configured", Addr: "bot@example.org"}}) - case "is_configured": - return rpcResult(req, true) - case "get_config": - key, _ := req.Params[1].(string) - current := map[string]*string{ - "addr": strPtr("bot@example.org"), - "mail_pw": strPtr("pw"), - "displayname": strPtr("Pico Bot"), - "mail_server": strPtr("imap.example.org"), - "mail_port": strPtr("993"), - "send_server": strPtr("smtp.example.org"), - "send_port": strPtr("587"), - } - return rpcResult(req, current[key]) - case "batch_set_config": - if cfg, ok := req.Params[1].(map[string]any); ok { - if _, ok := cfg["mail_pw"]; ok { - accountConfigCalls++ - } - } - return rpcResult(req, nil) - case "configure": - configureCalls++ - return rpcResult(req, nil) - case "select_account", "start_io": - return rpcResult(req, nil) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - if err := ch.ensureAccount(context.Background()); err != nil { - t.Fatalf("ensureAccount: %v", err) - } - if configureCalls != 0 { - t.Fatalf("configure calls = %d, want 0", configureCalls) - } - if accountConfigCalls != 0 { - t.Fatalf("account batch_set_config calls = %d, want 0", accountConfigCalls) - } -} - -func TestEnsureAccountCreatesBootstrapAccountAndStops(t *testing.T) { - ch := newTestChannel(t) - ch.config.Password = config.SecureString{} - ch.config.Email = "@mehl.cloud" - - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "add_account": - return rpcResult(req, int64(9)) - case "add_transport_from_qr": - if req.Params[0] != float64(9) { - t.Fatalf("account id = %v, want 9", req.Params[0]) - } - if req.Params[1] != "DCACCOUNT:https://mehl.cloud/new" { - t.Fatalf("qr = %v", req.Params[1]) - } - return rpcResult(req, nil) - case "get_config": - if req.Params[1] != "addr" { - t.Fatalf("get_config key = %v, want addr", req.Params[1]) - } - return rpcResult(req, "bot123@mehl.cloud") - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - err := ch.ensureAccount(context.Background()) - if err == nil { - t.Fatal("expected created-account instruction error") - } - if !strings.Contains(err.Error(), "bot123@mehl.cloud") || !strings.Contains(err.Error(), "run PicoClaw again") { - t.Fatalf("error = %v, want generated email and rerun instruction", err) - } -} - -func TestEnsureAccountUsesConfiguredAccountWithoutPassword(t *testing.T) { - ch := newTestChannel(t) - ch.config.Password = config.SecureString{} - ch.config.DisplayName = "Local Bot" - avatar := filepath.Join(t.TempDir(), "avatar.png") - if err := os.WriteFile(avatar, []byte("png"), 0o644); err != nil { - t.Fatal(err) - } - ch.config.AvatarImage = avatar - - profileConfigCalls := 0 - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_all_accounts": - return rpcResult(req, []dcAccount{{ID: 7, Kind: "Configured", Addr: "bot@example.org"}}) - case "is_configured": - return rpcResult(req, true) - case "batch_set_config": - cfg, _ := req.Params[1].(map[string]any) - if _, ok := cfg["bot"]; ok { - return rpcResult(req, nil) - } - profileConfigCalls++ - if cfg["displayname"] != "Local Bot" { - t.Fatalf("displayname = %v, want Local Bot", cfg["displayname"]) - } - if cfg["selfavatar"] != avatar { - t.Fatalf("selfavatar = %v, want %s", cfg["selfavatar"], avatar) - } - return rpcResult(req, nil) - case "select_account", "start_io": - return rpcResult(req, nil) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - if err := ch.ensureAccount(context.Background()); err != nil { - t.Fatalf("ensureAccount: %v", err) - } - if profileConfigCalls != 1 { - t.Fatalf("profile config calls = %d, want 1", profileConfigCalls) - } - if ch.accountID != 7 { - t.Fatalf("accountID = %d, want 7", ch.accountID) - } -} - -func TestEnsureAccountSkipsMissingAvatarImage(t *testing.T) { - ch := newTestChannel(t) - ch.config.Password = config.SecureString{} - ch.config.AvatarImage = filepath.Join(t.TempDir(), "missing.png") - - profileConfigCalls := 0 - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_all_accounts": - return rpcResult(req, []dcAccount{{ID: 7, Kind: "Configured", Addr: "bot@example.org"}}) - case "is_configured": - return rpcResult(req, true) - case "batch_set_config": - cfg, _ := req.Params[1].(map[string]any) - if _, ok := cfg["bot"]; !ok { - profileConfigCalls++ - } - return rpcResult(req, nil) - case "select_account", "start_io": - return rpcResult(req, nil) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - if err := ch.ensureAccount(context.Background()); err != nil { - t.Fatalf("ensureAccount: %v", err) - } - if profileConfigCalls != 0 { - t.Fatalf("profile config calls = %d, want 0", profileConfigCalls) - } -} - -func TestEnsureAccountRequiresPasswordWhenAccountMissing(t *testing.T) { - ch := newTestChannel(t) - ch.config.Password = config.SecureString{} - - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_all_accounts": - return rpcResult(req, []dcAccount{}) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - err := ch.ensureAccount(context.Background()) - if err == nil { - t.Fatal("expected password-required error") - } - if !strings.Contains(err.Error(), "is not configured") { - t.Fatalf("error = %v, want not-configured error", err) - } -} - -func TestEnsureAccountClearsRemovedOptionalSettings(t *testing.T) { - ch := newTestChannel(t) - - var capturedConfig map[string]any - - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_all_accounts": - return rpcResult(req, []dcAccount{{ID: 7, Kind: "Configured", Addr: "bot@example.org"}}) - case "is_configured": - return rpcResult(req, true) - case "get_config": - key, _ := req.Params[1].(string) - current := map[string]*string{ - "addr": strPtr("bot@example.org"), - "mail_pw": strPtr("pw"), - "displayname": strPtr("Old Bot"), - "mail_server": strPtr("imap.example.org"), - "mail_port": strPtr("993"), - "send_server": strPtr("smtp.example.org"), - "send_port": strPtr("587"), - } - return rpcResult(req, current[key]) - case "batch_set_config": - if cfg, ok := req.Params[1].(map[string]any); ok { - if _, ok := cfg["mail_pw"]; ok { - capturedConfig = cfg - } - } - return rpcResult(req, nil) - case "configure", "select_account", "start_io": - return rpcResult(req, nil) - default: - return rpcUnexpectedMethod(req) - } - }) - defer cleanup() - ch.rpc = rpc - - if err := ch.ensureAccount(context.Background()); err != nil { - t.Fatalf("ensureAccount: %v", err) - } - if capturedConfig == nil { - t.Fatal("account batch_set_config was not called") - } - for _, key := range []string{"mail_server", "mail_port", "send_server", "send_port"} { - if value, ok := capturedConfig[key]; !ok || value != nil { - t.Errorf("%s = %v (present %v), want explicit null", key, value, ok) - } - } - if capturedConfig["addr"] != "bot@example.org" { - t.Errorf("addr = %v, want bot@example.org", capturedConfig["addr"]) - } - if capturedConfig["mail_pw"] != "pw" { - t.Errorf("mail_pw = %v, want pw", capturedConfig["mail_pw"]) - } -} - -// TestRPCClientRoundTrip drives the JSON-RPC client against an in-process mock -// server over pipes, verifying id correlation and error propagation. -func TestRPCClientRoundTrip(t *testing.T) { - reqR, reqW := io.Pipe() // client -> server - respR, respW := io.Pipe() // server -> client - - c := &rpcClient{ - stdin: reqW, - stdout: respR, - pending: make(map[uint64]chan rpcResponse), - } - go c.readLoop() - - // Mock server: echo method "ping" -> "pong", anything else -> error. - go func() { - scanner := bufio.NewScanner(reqR) - for scanner.Scan() { - var req rpcRequest - if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { - continue - } - var resp string - if req.Method == "ping" { - resp = `{"jsonrpc":"2.0","id":` + itoa(req.ID) + `,"result":"pong"}` - } else { - resp = `{"jsonrpc":"2.0","id":` + itoa(req.ID) + `,"error":{"code":-1,"message":"boom"}}` - } - _, _ = respW.Write([]byte(resp + "\n")) - } - }() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - raw, err := c.call(ctx, "ping") - if err != nil { - t.Fatalf("ping call: %v", err) - } - var result string - if err := json.Unmarshal(raw, &result); err != nil || result != "pong" { - t.Fatalf("ping result = %q (err %v), want pong", result, err) - } - - if _, err := c.call(ctx, "explode"); err == nil { - t.Fatal("expected error from explode call") - } -} - -func itoa(n uint64) string { - b, _ := json.Marshal(n) - return string(b) -} - -// newTestChannel builds a DeltaChatChannel with a valid config (backed by a fake -// rpc-server binary) but without starting any IO, for unit-testing methods in -// isolation. -func newTestChannel(t *testing.T) *DeltaChatChannel { - return newTestChannelWithBus(t, bus.NewMessageBus(), nil) -} - -func newTestChannelWithBus(t *testing.T, msgBus *bus.MessageBus, configure func(*config.Channel)) *DeltaChatChannel { - t.Helper() - fakeServer := filepath.Join(t.TempDir(), "deltachat-rpc-server") - if err := os.WriteFile(fakeServer, []byte("#!/bin/sh\n"), 0o755); err != nil { - t.Fatal(err) - } - bc := &config.Channel{Type: config.ChannelDeltaChat, Enabled: true} - if configure != nil { - configure(bc) - } - cfg := &config.DeltaChatSettings{ - Email: "bot@example.org", - Password: *config.NewSecureString("pw"), - RPCServerPath: fakeServer, - DataDir: t.TempDir(), - } - ch, err := NewDeltaChatChannel(bc, cfg, msgBus) - if err != nil { - t.Fatalf("new channel: %v", err) - } - return ch -} - -// newMockRPC wires an rpcClient to an in-process server that replies to every -// request with handler(req), so methods that call the rpc can be tested without -// a real deltachat-rpc-server. -func newMockRPC(t *testing.T, handler func(req rpcRequest) string) (*rpcClient, func()) { - t.Helper() - reqR, reqW := io.Pipe() - respR, respW := io.Pipe() - c := &rpcClient{ - stdin: reqW, - stdout: respR, - pending: make(map[uint64]chan rpcResponse), - } - go c.readLoop() - go func() { - scanner := bufio.NewScanner(reqR) - for scanner.Scan() { - var req rpcRequest - if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { - continue - } - _, _ = respW.Write([]byte(handler(req) + "\n")) - } - }() - return c, func() { _ = reqW.Close(); _ = respW.Close() } -} - -func rpcResult(req rpcRequest, result any) string { - raw, _ := json.Marshal(result) - return `{"jsonrpc":"2.0","id":` + itoa(req.ID) + `,"result":` + string(raw) + `}` -} - -func rpcUnexpectedMethod(req rpcRequest) string { - return `{"jsonrpc":"2.0","id":` + itoa(req.ID) + `,"error":{"code":-32601,"message":"unexpected method"}}` -} - -func strPtr(value string) *string { - return &value -} - -// TestMessageDataJSON pins the camelCase keys and omitempty behavior expected by -// Delta Chat's send_msg MessageData parameter. -func TestMessageDataJSON(t *testing.T) { - raw, err := json.Marshal(dcMessageData{File: "/tmp/x.png"}) - if err != nil { - t.Fatal(err) - } - if got := string(raw); got != `{"file":"/tmp/x.png"}` { - t.Errorf("json = %s, want only the file field", got) - } - - raw, _ = json.Marshal(dcMessageData{Text: "hi", File: "/f", Filename: "f.bin"}) - if got := string(raw); got != `{"text":"hi","file":"/f","filename":"f.bin"}` { - t.Errorf("json = %s, want text/file/filename in camelCase", got) - } -} - -// TestRegisterInboundFile checks that an inbound attachment is copied out of -// Delta Chat's account directory into the tool-readable media temp dir and -// registered with delete-on-cleanup, and that the absence of a store yields an -// empty ref for the annotation fallback. -func TestRegisterInboundFile(t *testing.T) { - ch := newTestChannel(t) - - tmp := filepath.Join(t.TempDir(), "doc.pdf") - if err := os.WriteFile(tmp, []byte("%PDF-1.4"), 0o644); err != nil { - t.Fatal(err) - } - msg := &dcMessage{File: tmp, FileName: "doc.pdf", FileMime: "application/pdf"} - - if ref := ch.registerInboundFile("scope", msg); ref != "" { - t.Errorf("ref without media store = %q, want empty", ref) - } - - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - ref := ch.registerInboundFile("scope", msg) - if !strings.HasPrefix(ref, "media://") { - t.Fatalf("ref = %q, want a media:// ref", ref) - } - path, meta, err := store.ResolveWithMeta(ref) - if err != nil { - t.Fatalf("resolve: %v", err) - } - t.Cleanup(func() { _ = os.Remove(path) }) - - // The registered path must be a copy in the media temp dir (tool-readable), - // not the original blob path, and must have the same contents. - if path == tmp { - t.Errorf("path = %q, want a copy in the media temp dir, not the blob path", path) - } - if !strings.HasPrefix(filepath.Clean(path), filepath.Clean(media.TempDir())) { - t.Errorf("path = %q, want it under media temp dir %q", path, media.TempDir()) - } - if data, rerr := os.ReadFile(path); rerr != nil || string(data) != "%PDF-1.4" { - t.Errorf("copied file contents = %q (err %v), want %q", string(data), rerr, "%PDF-1.4") - } - if meta.ContentType != "application/pdf" { - t.Errorf("content type = %q, want application/pdf", meta.ContentType) - } - if meta.CleanupPolicy != media.CleanupPolicyDeleteOnCleanup { - t.Errorf("cleanup policy = %q, want delete_on_cleanup", meta.CleanupPolicy) - } -} - -func TestSend_CurrentNumericChatIDAllowedWithoutRecipientResolution(t *testing.T) { - ch := newTestChannel(t) - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - if req.Method != "misc_send_msg" { - return rpcUnexpectedMethod(req) - } - if got, _ := req.Params[1].(float64); got != 42 { - t.Fatalf("chat id = %v, want 42", req.Params[1]) - } - return rpcResult(req, []any{int64(1001), map[string]any{}}) - }) - ch.accountID = 7 - ch.SetRunning(true) - - ids, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "42", - Content: "hello", - Context: bus.InboundContext{ChatID: "42", SenderID: "friend@example.org"}, - }) - if err != nil { - t.Fatalf("Send: %v", err) - } - if len(ids) != 1 || ids[0] != "1001" { - t.Fatalf("ids = %v, want [1001]", ids) - } -} - -func TestSend_CrossChatNumericDeniedByDefault(t *testing.T) { - ch := newTestChannel(t) - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - t.Fatalf("unexpected rpc call: %s", req.Method) - return rpcUnexpectedMethod(req) - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "99", - Content: "hello", - Context: bus.InboundContext{ChatID: "42", SenderID: "admin@example.org"}, - }) - if err == nil || !strings.Contains(err.Error(), "allow_crosspost") { - t.Fatalf("Send error = %v, want crosspost recipient gate", err) - } -} - -func TestSend_EmailRecipientDeniedByDefault(t *testing.T) { - ch := newTestChannel(t) - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - t.Fatalf("unexpected rpc call: %s", req.Method) - return rpcUnexpectedMethod(req) - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "friend@example.org", - Content: "hello", - Context: bus.InboundContext{ChatID: "42", SenderID: "admin@example.org"}, - }) - if err == nil || !strings.Contains(err.Error(), "allow_crosspost") { - t.Fatalf("Send error = %v, want crosspost recipient gate", err) - } -} - -func TestSend_EmailRecipientRequiresAllowFrom(t *testing.T) { - ch := newTestChannelWithBus(t, bus.NewMessageBus(), func(bc *config.Channel) { - bc.AllowFrom = config.FlexibleStringSlice{"admin@example.org"} - }) - ch.config.AllowCrosspost = true - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - t.Fatalf("unexpected rpc call: %s", req.Method) - return rpcUnexpectedMethod(req) - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "friend@example.org", - Content: "hello", - Context: bus.InboundContext{ChatID: "42", SenderID: "other@example.org"}, - }) - if err == nil || !strings.Contains(err.Error(), "allow_from") { - t.Fatalf("Send error = %v, want allow_from gate", err) - } -} - -func TestSend_EmailRecipientUsesSessionScopeSenderForAdmin(t *testing.T) { - ch := newTestChannelWithBus(t, bus.NewMessageBus(), func(bc *config.Channel) { - bc.AllowFrom = config.FlexibleStringSlice{"admin@example.org"} - }) - ch.config.AllowCrosspost = true - - var sentChatID float64 - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "lookup_contact_id_by_addr": - return rpcResult(req, int64(11)) - case "get_chat_id_by_contact_id": - return rpcResult(req, int64(99)) - case "misc_send_msg": - sentChatID, _ = req.Params[1].(float64) - return rpcResult(req, []any{int64(1233), map[string]any{}}) - default: - return rpcUnexpectedMethod(req) - } - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "friend@example.org", - Content: "hello", - Context: bus.InboundContext{ChatID: "friend@example.org"}, - Scope: &bus.OutboundScope{ - Channel: config.ChannelDeltaChat, - Values: map[string]string{ - "chat": "direct:42", - "sender": "admin@example.org", - }, - }, - }) - if err != nil { - t.Fatalf("Send: %v", err) - } - if sentChatID != 99 { - t.Fatalf("sent chat id = %v, want 99", sentChatID) - } -} - -func TestSend_EmailRecipientResolvesForAllowFromWildcard(t *testing.T) { - ch := newTestChannelWithBus(t, bus.NewMessageBus(), func(bc *config.Channel) { - bc.AllowFrom = config.FlexibleStringSlice{"*"} - }) - ch.config.AllowCrosspost = true - - var sentChatID float64 - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "lookup_contact_id_by_addr": - return rpcResult(req, int64(11)) - case "get_chat_id_by_contact_id": - return rpcResult(req, int64(99)) - case "misc_send_msg": - sentChatID, _ = req.Params[1].(float64) - return rpcResult(req, []any{int64(1236), map[string]any{}}) - default: - return rpcUnexpectedMethod(req) - } - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "friend@example.org", - Content: "hello", - }) - if err != nil { - t.Fatalf("Send: %v", err) - } - if sentChatID != 99 { - t.Fatalf("sent chat id = %v, want 99", sentChatID) - } -} - -func TestSend_CrossChatNumericUsesSessionScopeChatForGate(t *testing.T) { - ch := newTestChannel(t) - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - t.Fatalf("unexpected rpc call: %s", req.Method) - return rpcUnexpectedMethod(req) - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "99", - Content: "hello", - Context: bus.InboundContext{ChatID: "99", SenderID: "admin@example.org"}, - Scope: &bus.OutboundScope{ - Channel: config.ChannelDeltaChat, - Values: map[string]string{"chat": "direct:42"}, - }, - }) - if err == nil || !strings.Contains(err.Error(), "allow_crosspost") { - t.Fatalf("Send error = %v, want crosspost recipient gate", err) - } -} - -func TestSend_EmailRecipientResolvesForAdmin(t *testing.T) { - ch := newTestChannelWithBus(t, bus.NewMessageBus(), func(bc *config.Channel) { - bc.AllowFrom = config.FlexibleStringSlice{"admin@example.org"} - }) - ch.config.AllowCrosspost = true - - var sentChatID float64 - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "lookup_contact_id_by_addr": - if req.Params[1] != "friend@example.org" { - t.Fatalf("lookup addr = %v, want friend@example.org", req.Params[1]) - } - return rpcResult(req, int64(11)) - case "get_chat_id_by_contact_id": - return rpcResult(req, nil) - case "create_chat_by_contact_id": - return rpcResult(req, int64(99)) - case "misc_send_msg": - sentChatID, _ = req.Params[1].(float64) - return rpcResult(req, []any{int64(1234), map[string]any{}}) - default: - return rpcUnexpectedMethod(req) - } - }) - ch.accountID = 7 - ch.SetRunning(true) - - ids, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "Friend ", - Content: "hello", - Context: bus.InboundContext{ChatID: "42", SenderID: "admin@example.org"}, - }) - if err != nil { - t.Fatalf("Send: %v", err) - } - if sentChatID != 99 { - t.Fatalf("sent chat id = %v, want 99", sentChatID) - } - if len(ids) != 1 || ids[0] != "1234" { - t.Fatalf("ids = %v, want [1234]", ids) - } -} - -func TestSend_AliasRecipientResolvesForAdmin(t *testing.T) { - ch := newTestChannelWithBus(t, bus.NewMessageBus(), func(bc *config.Channel) { - bc.AllowFrom = config.FlexibleStringSlice{"admin@example.org"} - }) - ch.config.AllowCrosspost = true - - var sentChatID float64 - ch.rpc, _ = newMockRPC(t, func(req rpcRequest) string { - switch req.Method { - case "get_contacts": - if req.Params[2] != "Alice" { - t.Fatalf("contact query = %v, want Alice", req.Params[2]) - } - return rpcResult(req, []dcContact{{ID: 12, Address: "alice@example.org", DisplayName: "Alice"}}) - case "get_chat_id_by_contact_id": - return rpcResult(req, int64(88)) - case "misc_send_msg": - sentChatID, _ = req.Params[1].(float64) - return rpcResult(req, []any{int64(1235), map[string]any{}}) - default: - return rpcUnexpectedMethod(req) - } - }) - ch.accountID = 7 - ch.SetRunning(true) - - _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "Alice", - Content: "hello", - Context: bus.InboundContext{ChatID: "42", SenderID: "admin@example.org"}, - }) - if err != nil { - t.Fatalf("Send: %v", err) - } - if sentChatID != 88 { - t.Fatalf("sent chat id = %v, want 88", sentChatID) - } -} - -// TestSendMedia verifies SendMedia resolves a media ref to a local path and -// drives send_msg with the expected MessageData, returning the new message id. -func TestSendMedia(t *testing.T) { - ch := newTestChannel(t) - - tmp := filepath.Join(t.TempDir(), "photo.png") - if err := os.WriteFile(tmp, []byte("\x89PNGfake"), 0o644); err != nil { - t.Fatal(err) - } - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - ref, err := store.Store(tmp, media.MediaMeta{Filename: "photo.png"}, "scope") - if err != nil { - t.Fatal(err) - } - - captured := make(chan rpcRequest, 1) - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - captured <- req - return `{"jsonrpc":"2.0","id":` + itoa(req.ID) + `,"result":4242}` - }) - defer cleanup() - ch.rpc = rpc - ch.accountID = 7 - ch.SetRunning(true) - - ids, err := ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ - ChatID: "99", - Parts: []bus.MediaPart{{ - Type: "image", - Ref: ref, - Caption: "hello", - Filename: "photo.png", - }}, - }) - if err != nil { - t.Fatalf("SendMedia: %v", err) - } - if len(ids) != 1 || ids[0] != "4242" { - t.Fatalf("ids = %v, want [4242]", ids) - } - - select { - case req := <-captured: - if req.Method != "send_msg" { - t.Errorf("method = %q, want send_msg", req.Method) - } - if len(req.Params) != 3 { - t.Fatalf("params = %v, want [accountID, chatID, data]", req.Params) - } - if got, _ := req.Params[0].(float64); got != 7 { - t.Errorf("account id = %v, want 7", req.Params[0]) - } - if got, _ := req.Params[1].(float64); got != 99 { - t.Errorf("chat id = %v, want 99", req.Params[1]) - } - data, ok := req.Params[2].(map[string]any) - if !ok { - t.Fatalf("data param = %T, want object", req.Params[2]) - } - if data["file"] != tmp { - t.Errorf("file = %v, want %s", data["file"], tmp) - } - if data["text"] != "hello" { - t.Errorf("text = %v, want hello", data["text"]) - } - if data["filename"] != "photo.png" { - t.Errorf("filename = %v, want photo.png", data["filename"]) - } - if _, present := data["viewtype"]; present { - t.Errorf("viewtype should be omitted (Delta Chat infers it), got %v", data["viewtype"]) - } - case <-time.After(2 * time.Second): - t.Fatal("mock server never received the request") - } -} - -// TestSendMediaNoStore ensures SendMedia fails cleanly without a media store. -func TestSendMediaNoStore(t *testing.T) { - ch := newTestChannel(t) - ch.SetRunning(true) - if _, err := ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ChatID: "1"}); err == nil { - t.Error("expected error when no media store is configured") - } -} - -// TestSendMediaVoice verifies that a send_tts-sourced audio part is delivered -// with viewtype "Voice" so Delta Chat renders it as a voice bubble. -func TestSendMediaVoice(t *testing.T) { - ch := newTestChannel(t) - - tmp := filepath.Join(t.TempDir(), "tts-123.ogg") - if err := os.WriteFile(tmp, []byte("OggSfake"), 0o644); err != nil { - t.Fatal(err) - } - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - ref, err := store.Store(tmp, media.MediaMeta{ - Filename: "tts-123.ogg", - ContentType: "audio/ogg", - Source: "tool:send_tts", - }, "scope") - if err != nil { - t.Fatal(err) - } - - captured := make(chan rpcRequest, 1) - rpc, cleanup := newMockRPC(t, func(req rpcRequest) string { - captured <- req - return `{"jsonrpc":"2.0","id":` + itoa(req.ID) + `,"result":7}` - }) - defer cleanup() - ch.rpc = rpc - ch.accountID = 1 - ch.SetRunning(true) - - if _, err := ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ - ChatID: "5", - Parts: []bus.MediaPart{{Type: "audio", Ref: ref, ContentType: "audio/ogg"}}, - }); err != nil { - t.Fatalf("SendMedia: %v", err) - } - - select { - case req := <-captured: - data, ok := req.Params[2].(map[string]any) - if !ok { - t.Fatalf("data param = %T, want object", req.Params[2]) - } - if data["viewtype"] != "Voice" { - t.Errorf("viewtype = %v, want Voice", data["viewtype"]) - } - case <-time.After(2 * time.Second): - t.Fatal("mock server never received the request") - } -} - -// TestDeltaChatViewtype pins the rule that only voice audio is forced to a view -// type; everything else is left to Delta Chat's own detection. -func TestDeltaChatViewtype(t *testing.T) { - tests := []struct { - name string - part bus.MediaPart - meta media.MediaMeta - want string - }{ - { - "tts audio", - bus.MediaPart{Type: "audio"}, - media.MediaMeta{Source: "tool:send_tts", ContentType: "audio/ogg"}, - "Voice", - }, - {"voice filename", bus.MediaPart{Type: "audio", Filename: "my-voice.mp3"}, media.MediaMeta{}, "Voice"}, - { - "plain audio", - bus.MediaPart{Type: "audio", Filename: "song.mp3"}, - media.MediaMeta{ContentType: "audio/mpeg"}, - "", - }, - {"image", bus.MediaPart{Type: "image", Filename: "photo.png"}, media.MediaMeta{ContentType: "image/png"}, ""}, - {"file", bus.MediaPart{Type: "file", Filename: "doc.pdf"}, media.MediaMeta{}, ""}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := deltaChatViewtype(tt.part, tt.meta); got != tt.want { - t.Errorf("deltaChatViewtype() = %q, want %q", got, tt.want) - } - }) - } -} - -// TestVoiceCapabilities checks that Delta Chat advertises ASR and TTS so the -// gateway's startup capability log is accurate. -func TestVoiceCapabilities(t *testing.T) { - ch := newTestChannel(t) - caps := ch.VoiceCapabilities() - if !caps.ASR || !caps.TTS { - t.Errorf("VoiceCapabilities() = %+v, want both ASR and TTS true", caps) - } -} diff --git a/pkg/channels/deltachat/handler.go b/pkg/channels/deltachat/handler.go deleted file mode 100644 index 724b73ee..00000000 --- a/pkg/channels/deltachat/handler.go +++ /dev/null @@ -1,398 +0,0 @@ -package deltachat - -import ( - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "strconv" - "strings" - "time" - "unicode" - - "github.com/google/uuid" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/identity" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/media" - "github.com/sipeed/picoclaw/pkg/utils" -) - -// listen is the inbound message loop. It blocks on wait_next_msgs and feeds -// each new message into the PicoClaw inbound pipeline. -func (c *DeltaChatChannel) listen() { - logger.InfoCF("deltachat", "Listening for messages", map[string]any{ - "account_id": c.accountID, - "email": c.selfAddr, - }) - for c.IsRunning() && c.ctx.Err() == nil { - raw, err := c.rpc.call(c.ctx, "wait_next_msgs", c.accountID) - if err != nil { - if c.ctx.Err() != nil || !c.IsRunning() { - return - } - logger.ErrorCF("deltachat", "wait_next_msgs failed", map[string]any{"error": err.Error()}) - time.Sleep(time.Second) - continue - } - - var messageIDs []int64 - if err := json.Unmarshal(raw, &messageIDs); err != nil { - continue - } - - if len(messageIDs) > 0 { - logger.DebugCF("deltachat", "Received message batch", map[string]any{ - "count": len(messageIDs), - }) - } - for _, messageID := range messageIDs { - c.handleMessage(messageID) - } - } -} - -// handleMessage fetches one message, applies inbound filtering, and publishes it. -func (c *DeltaChatChannel) handleMessage(messageID int64) { - msg, err := c.getMessage(messageID) - if err != nil { - logger.DebugCF("deltachat", "get_message failed", map[string]any{ - "message_id": messageID, - "error": err.Error(), - }) - return - } - - if msg.IsInfo || (strings.TrimSpace(msg.Text) == "" && msg.File == "") { - return - } - - senderAddr := "" - if msg.Sender != nil { - senderAddr = msg.Sender.Address - } - if senderAddr != "" && strings.EqualFold(senderAddr, c.selfAddr) { - logger.DebugCF("deltachat", "Drop: own message", map[string]any{"message_id": messageID}) - return - } - - chat, err := c.getFullChat(msg.ChatID) - if err != nil { - logger.DebugCF("deltachat", "get_full_chat_by_id failed", map[string]any{ - "chat_id": msg.ChatID, - "error": err.Error(), - }) - return - } - // Device messages are core-generated notices, not real conversations. - if chat.IsDeviceChat { - logger.DebugCF("deltachat", "Drop: device message", map[string]any{"chat_id": msg.ChatID}) - return - } - isGroup := chat.ChatType != chatTypeSingle - - logger.DebugCF("deltachat", "Inbound message", map[string]any{ - "message_id": messageID, - "chat_id": msg.ChatID, - "from": senderAddr, - "is_group": isGroup, - "has_file": msg.File != "", - "text_len": len(strings.TrimSpace(msg.Text)), - }) - - senderName := senderAddr - if msg.Sender != nil { - if msg.Sender.DisplayName != "" { - senderName = msg.Sender.DisplayName - } else if msg.Sender.Name != "" { - senderName = msg.Sender.Name - } - } - if senderName == "" { - senderName = "unknown" - } - - chatID := strconv.FormatInt(msg.ChatID, 10) - messageIDStr := strconv.FormatInt(msg.ID, 10) - - content := strings.TrimSpace(msg.Text) - - // Register any attachment with the media store so the agent pipeline can - // view images and operate on files. The ref is scoped to the same key the - // BaseChannel derives for this message, so it is released with the turn. - var mediaRefs []string - if msg.File != "" { - scope := channels.BuildMediaScope(c.Name(), chatID, messageIDStr) - if ref := c.registerInboundFile(scope, msg); ref != "" { - mediaRefs = append(mediaRefs, ref) - } else { - // Fallback when no media store is available: surface the path inline - // so the attachment is not silently lost. - annotation := fmt.Sprintf("[attachment: %s]", msg.File) - if content == "" { - content = annotation - } else { - content = content + "\n" + annotation - } - } - } - - // A file with no caption still warrants a turn; give the agent a minimal - // placeholder so the message survives the empty-content guard below. Audio - // gets a "[voice]" tag specifically, so the agent's transcription step can - // substitute the transcript in place rather than appending it. - if content == "" && len(mediaRefs) > 0 { - if utils.IsAudioFile(msg.FileName, msg.FileMime) { - content = "[voice]" - } else { - content = "[media]" - } - } - - sender := bus.SenderInfo{ - Platform: config.ChannelDeltaChat, - PlatformID: senderAddr, - CanonicalID: identity.BuildCanonicalID(config.ChannelDeltaChat, senderAddr), - Username: senderAddr, - DisplayName: senderName, - } - - if !c.IsAllowedSender(sender) { - logger.DebugCF("deltachat", "Drop: sender not in allow_from", map[string]any{ - "from": senderAddr, - }) - return - } - - isMentioned := false - if isGroup { - botName := c.config.DisplayName - if botName == "" { - botName = c.selfAddr - } - isMentioned = mentionsBot(content, botName, c.selfAddr) - respond, cleaned := c.ShouldRespondInGroup(isMentioned, content) - if !respond { - logger.DebugCF("deltachat", "Drop: group trigger not satisfied", map[string]any{ - "chat_id": msg.ChatID, - "mentioned": isMentioned, - }) - return - } - content = cleaned - } - - if strings.TrimSpace(content) == "" { - return - } - - metadata := map[string]string{ - "platform": config.ChannelDeltaChat, - "chat_name": chat.Name, - } - if msg.File != "" { - metadata["file"] = msg.File - metadata["file_name"] = msg.FileName - metadata["file_mime"] = msg.FileMime - } - - inboundCtx := bus.InboundContext{ - Channel: config.ChannelDeltaChat, - ChatID: chatID, - SenderID: senderAddr, - MessageID: messageIDStr, - Mentioned: isMentioned, - Raw: metadata, - } - if isGroup { - inboundCtx.ChatType = "group" - } else { - inboundCtx.ChatType = "direct" - } - - logger.DebugCF("deltachat", "Dispatching to agent", map[string]any{ - "chat_id": chatID, - "chat_type": inboundCtx.ChatType, - "from": senderAddr, - }) - if err := c.HandleInboundContext(c.ctx, chatID, content, mediaRefs, inboundCtx, sender); err != nil { - logger.ErrorCF("deltachat", "Dispatch failed; leaving message unseen", map[string]any{ - "message_id": messageID, - "chat_id": chatID, - "error": err.Error(), - }) - return - } - if _, err := c.rpc.call(c.ctx, "markseen_msgs", c.accountID, []int64{messageID}); err != nil { - logger.WarnCF("deltachat", "Failed to mark message seen", map[string]any{ - "message_id": messageID, - "chat_id": chatID, - "error": err.Error(), - }) - } -} - -// registerInboundFile records an inbound attachment with the media store under -// the given scope and returns its media:// ref. Returns "" when there is no -// media store or registration fails, letting the caller fall back to an inline -// path annotation. -// -// Delta Chat stores attachments inside the account directory, next to the -// credential database — a location tools are intentionally NOT allowed to read. -// We therefore copy the single attachment out into the shared media temp dir -// (which read_file/load_image are permitted to access) and register that copy, -// so the agent can actually open the file. The copy is store-managed and deleted -// when the turn's scope is released. -func (c *DeltaChatChannel) registerInboundFile(scope string, msg *dcMessage) string { - store := c.GetMediaStore() - if store == nil { - return "" - } - filename := msg.FileName - if filename == "" { - filename = filepath.Base(msg.File) - } - - localPath, err := copyToMediaTemp(msg.File, filename) - if err != nil { - logger.WarnCF("deltachat", "Failed to copy attachment into media dir", map[string]any{ - "file": msg.File, - "error": err.Error(), - }) - return "" - } - - ref, err := store.Store(localPath, media.MediaMeta{ - Filename: filename, - ContentType: msg.FileMime, - Source: config.ChannelDeltaChat, - CleanupPolicy: media.CleanupPolicyDeleteOnCleanup, - }, scope) - if err != nil { - logger.WarnCF("deltachat", "Failed to register attachment with media store", map[string]any{ - "file": localPath, - "error": err.Error(), - }) - _ = os.Remove(localPath) - return "" - } - return ref -} - -// copyToMediaTemp copies srcPath into the shared media temp directory under a -// unique name and returns the destination path. The media temp dir is the -// location the read_file/load_image tools are permitted to read, so copying here -// makes the attachment readable without exposing Delta Chat's account directory. -func copyToMediaTemp(srcPath, filename string) (string, error) { - if err := os.MkdirAll(media.TempDir(), 0o700); err != nil { - return "", err - } - safe := utils.SanitizeFilename(filename) - if safe == "" { - safe = filepath.Base(srcPath) - } - dstPath := filepath.Join(media.TempDir(), uuid.NewString()[:8]+"_"+safe) - - src, err := os.Open(srcPath) - if err != nil { - return "", err - } - defer src.Close() - - dst, err := os.Create(dstPath) - if err != nil { - return "", err - } - if _, err := io.Copy(dst, src); err != nil { - dst.Close() - _ = os.Remove(dstPath) - return "", err - } - if err := dst.Close(); err != nil { - _ = os.Remove(dstPath) - return "", err - } - return dstPath, nil -} - -func (c *DeltaChatChannel) getMessage(messageID int64) (*dcMessage, error) { - raw, err := c.rpc.call(c.ctx, "get_message", c.accountID, messageID) - if err != nil { - return nil, err - } - var msg dcMessage - if err := json.Unmarshal(raw, &msg); err != nil { - return nil, err - } - return &msg, nil -} - -func (c *DeltaChatChannel) getFullChat(chatID int64) (*dcChat, error) { - raw, err := c.rpc.call(c.ctx, "get_full_chat_by_id", c.accountID, chatID) - if err != nil { - return nil, err - } - var chat dcChat - if err := json.Unmarshal(raw, &chat); err != nil { - return nil, err - } - return &chat, nil -} - -// mentionsBot reports whether the message references the bot by display name or -// the local-part of its email address (a common addressing convention). -func mentionsBot(content, displayName, email string) bool { - if containsMentionToken(content, displayName) { - return true - } - if local, _, ok := strings.Cut(email, "@"); ok && local != "" { - if containsMentionToken(content, "@"+local) { - return true - } - } - return false -} - -func containsMentionToken(content, token string) bool { - token = strings.TrimSpace(token) - if token == "" { - return false - } - contentRunes := []rune(strings.ToLower(content)) - tokenRunes := []rune(strings.ToLower(token)) - if len(tokenRunes) == 0 || len(tokenRunes) > len(contentRunes) { - return false - } - for i := 0; i <= len(contentRunes)-len(tokenRunes); i++ { - if !sameRunes(contentRunes[i:i+len(tokenRunes)], tokenRunes) { - continue - } - before := i == 0 || !isMentionWordRune(contentRunes[i-1]) - afterIdx := i + len(tokenRunes) - after := afterIdx >= len(contentRunes) || !isMentionWordRune(contentRunes[afterIdx]) - if before && after { - return true - } - } - return false -} - -func sameRunes(a, b []rune) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -func isMentionWordRune(r rune) bool { - return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' -} diff --git a/pkg/channels/deltachat/init.go b/pkg/channels/deltachat/init.go deleted file mode 100644 index 85fdee0c..00000000 --- a/pkg/channels/deltachat/init.go +++ /dev/null @@ -1,35 +0,0 @@ -package deltachat - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelDeltaChat, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - if bc == nil || !bc.Enabled { - return nil, nil - } - decoded, err := bc.GetDecoded() - if err != nil { - return nil, err - } - c, ok := decoded.(*config.DeltaChatSettings) - if !ok { - return nil, channels.ErrSendFailed - } - ch, err := NewDeltaChatChannel(bc, c, b) - if err != nil { - return nil, err - } - if channelName != config.ChannelDeltaChat { - ch.SetName(channelName) - } - return ch, nil - }, - ) -} diff --git a/pkg/channels/deltachat/rpc.go b/pkg/channels/deltachat/rpc.go deleted file mode 100644 index a88355db..00000000 --- a/pkg/channels/deltachat/rpc.go +++ /dev/null @@ -1,188 +0,0 @@ -package deltachat - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "io" - "os/exec" - "sync" - - "github.com/sipeed/picoclaw/pkg/logger" -) - -// rpcRequest is a single JSON-RPC 2.0 request. Delta Chat uses positional -// (array) parameters. -type rpcRequest struct { - JSONRPC string `json:"jsonrpc"` - ID uint64 `json:"id"` - Method string `json:"method"` - Params []any `json:"params,omitempty"` -} - -// rpcResponse is a single JSON-RPC 2.0 response. -type rpcResponse struct { - ID uint64 `json:"id"` - Result json.RawMessage `json:"result"` - Error *rpcError `json:"error"` -} - -type rpcError struct { - Code int `json:"code"` - Message string `json:"message"` -} - -func (e *rpcError) Error() string { - return fmt.Sprintf("deltachat rpc error %d: %s", e.Code, e.Message) -} - -// rpcClient drives a `deltachat-rpc-server` child process over stdio using -// newline-delimited JSON-RPC 2.0. The server answers requests asynchronously -// and out of order, so every call is correlated back to its caller by id. -type rpcClient struct { - cmd *exec.Cmd - stdin io.WriteCloser - stdout io.ReadCloser - - mu sync.Mutex - nextID uint64 - pending map[uint64]chan rpcResponse - closed bool -} - -// startRPC spawns the RPC server with DC_ACCOUNTS_PATH pointing at dataDir and -// begins the background read loop. -func startRPC(serverPath, dataDir string) (*rpcClient, error) { - cmd := exec.Command(serverPath) - cmd.Env = append(cmd.Environ(), "DC_ACCOUNTS_PATH="+dataDir) - - stdin, err := cmd.StdinPipe() - if err != nil { - return nil, fmt.Errorf("deltachat rpc stdin: %w", err) - } - stdout, err := cmd.StdoutPipe() - if err != nil { - return nil, fmt.Errorf("deltachat rpc stdout: %w", err) - } - // Let the server's logs flow to our stderr for easy diagnostics. - cmd.Stderr = logWriter{} - - if err := cmd.Start(); err != nil { - return nil, fmt.Errorf("start deltachat-rpc-server (%s): %w", serverPath, err) - } - - c := &rpcClient{ - cmd: cmd, - stdin: stdin, - stdout: stdout, - pending: make(map[uint64]chan rpcResponse), - } - go c.readLoop() - return c, nil -} - -// readLoop reads newline-delimited responses and dispatches them to waiters. -func (c *rpcClient) readLoop() { - reader := bufio.NewReader(c.stdout) - for { - line, err := reader.ReadBytes('\n') - if len(line) > 0 { - var resp rpcResponse - if jsonErr := json.Unmarshal(line, &resp); jsonErr == nil && resp.ID != 0 { - c.mu.Lock() - ch := c.pending[resp.ID] - delete(c.pending, resp.ID) - c.mu.Unlock() - if ch != nil { - ch <- resp - } - } - } - if err != nil { - c.failAll(err) - return - } - } -} - -// failAll wakes every pending caller with an error (used on EOF / shutdown). -func (c *rpcClient) failAll(err error) { - c.mu.Lock() - defer c.mu.Unlock() - c.closed = true - for id, ch := range c.pending { - ch <- rpcResponse{Error: &rpcError{Code: -1, Message: "rpc closed: " + err.Error()}} - delete(c.pending, id) - } -} - -// call issues one request and blocks until the matching response arrives, the -// context is canceled, or the server goes away. -func (c *rpcClient) call(ctx context.Context, method string, params ...any) (json.RawMessage, error) { - c.mu.Lock() - if c.closed { - c.mu.Unlock() - return nil, fmt.Errorf("deltachat rpc: connection closed") - } - c.nextID++ - id := c.nextID - ch := make(chan rpcResponse, 1) - c.pending[id] = ch - c.mu.Unlock() - - req := rpcRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params} - data, err := json.Marshal(req) - if err != nil { - c.clearPending(id) - return nil, err - } - data = append(data, '\n') - - c.mu.Lock() - _, err = c.stdin.Write(data) - c.mu.Unlock() - if err != nil { - c.clearPending(id) - return nil, fmt.Errorf("deltachat rpc write %s: %w", method, err) - } - - select { - case <-ctx.Done(): - c.clearPending(id) - return nil, ctx.Err() - case resp := <-ch: - if resp.Error != nil { - return nil, resp.Error - } - return resp.Result, nil - } -} - -func (c *rpcClient) clearPending(id uint64) { - c.mu.Lock() - delete(c.pending, id) - c.mu.Unlock() -} - -// close terminates the RPC server process. -func (c *rpcClient) close() { - c.mu.Lock() - c.closed = true - c.mu.Unlock() - if c.stdin != nil { - _ = c.stdin.Close() - } - if c.cmd != nil && c.cmd.Process != nil { - _ = c.cmd.Process.Kill() - _ = c.cmd.Wait() - } -} - -// logWriter forwards deltachat-rpc-server stderr lines into the logger. -type logWriter struct{} - -func (logWriter) Write(p []byte) (int, error) { - logger.DebugC("deltachat", string(p)) - return len(p), nil -} diff --git a/pkg/channels/irc/handler.go b/pkg/channels/irc/handler.go deleted file mode 100644 index 73df9c43..00000000 --- a/pkg/channels/irc/handler.go +++ /dev/null @@ -1,167 +0,0 @@ -package irc - -import ( - "fmt" - "strings" - "time" - "unicode" - - "github.com/ergochat/irc-go/ircevent" - "github.com/ergochat/irc-go/ircmsg" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/identity" - "github.com/sipeed/picoclaw/pkg/logger" -) - -// onConnect is called after a successful connection (and on reconnect). -func (c *IRCChannel) onConnect(conn *ircevent.Connection) { - // NickServ auth (only if SASL is not configured) - if c.config.NickServPassword.String() != "" && c.config.SASLUser == "" { - conn.Privmsg("NickServ", "IDENTIFY "+c.config.NickServPassword.String()) - } - - // Join configured channels - for _, ch := range c.config.Channels { - conn.Join(ch) - logger.InfoCF("irc", "Joined IRC channel", map[string]any{ - "channel": ch, - }) - } -} - -// onPrivmsg handles incoming PRIVMSG events. -func (c *IRCChannel) onPrivmsg(conn *ircevent.Connection, e ircmsg.Message) { - if len(e.Params) < 2 { - return - } - - nick := e.Nick() - currentNick := conn.CurrentNick() - - // Ignore own messages - if strings.EqualFold(nick, currentNick) { - return - } - - target := e.Params[0] // channel name or bot's nick - content := e.Params[1] // message text - - // Determine if this is a DM or channel message - isDM := !strings.HasPrefix(target, "#") && !strings.HasPrefix(target, "&") - - var chatID string - - if isDM { - chatID = nick - } else { - chatID = target - } - - sender := bus.SenderInfo{ - Platform: "irc", - PlatformID: nick, - CanonicalID: identity.BuildCanonicalID("irc", nick), - Username: nick, - DisplayName: nick, - } - - if !c.IsAllowedSender(sender) { - return - } - - isMentioned := false - - // For channel messages, check group trigger (mention detection) - if !isDM { - isMentioned = isBotMentioned(content, currentNick) - if isMentioned { - content = stripBotMention(content, currentNick) - } - respond, cleaned := c.ShouldRespondInGroup(isMentioned, content) - if !respond { - return - } - content = cleaned - } - - if strings.TrimSpace(content) == "" { - return - } - - messageID := fmt.Sprintf("%s-%d", nick, time.Now().UnixNano()) - - metadata := map[string]string{ - "platform": "irc", - "server": c.config.Server, - } - if !isDM { - metadata["channel"] = target - } - - inboundCtx := bus.InboundContext{ - Channel: "irc", - ChatID: chatID, - SenderID: nick, - MessageID: messageID, - Mentioned: isMentioned, - Raw: metadata, - } - if isDM { - inboundCtx.ChatType = "direct" - } else { - inboundCtx.ChatType = "group" - } - - c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, sender) -} - -// nickMentionedAt returns the byte index where botNick is mentioned in content -// with word-boundary checks, or -1 if not found. Also checks for "nick:" / -// "nick," prefix convention. -func nickMentionedAt(content, botNick string) int { - lower := strings.ToLower(content) - lowerNick := strings.ToLower(botNick) - - // "nick:" or "nick," at start (most common IRC convention) - if strings.HasPrefix(lower, lowerNick+":") || strings.HasPrefix(lower, lowerNick+",") { - return 0 - } - - // Word-boundary match anywhere in the message - idx := strings.Index(lower, lowerNick) - if idx < 0 { - return -1 - } - runes := []rune(lower) - nickRunes := []rune(lowerNick) - endIdx := idx + len(string(nickRunes)) - before := idx == 0 || !unicode.IsLetter(runes[idx-1]) && !unicode.IsDigit(runes[idx-1]) - after := endIdx >= len(lower) || !unicode.IsLetter(rune(lower[endIdx])) && !unicode.IsDigit(rune(lower[endIdx])) - if before && after { - return idx - } - return -1 -} - -// isBotMentioned checks if the bot's nick appears in the message. -func isBotMentioned(content, botNick string) bool { - return nickMentionedAt(content, botNick) >= 0 -} - -// stripBotMention removes "nick: " or "nick, " prefix from content. -func stripBotMention(content, botNick string) string { - idx := nickMentionedAt(content, botNick) - if idx != 0 { - return content - } - lowerNick := strings.ToLower(botNick) - lower := strings.ToLower(content) - for _, sep := range []string{":", ","} { - prefix := lowerNick + sep - if strings.HasPrefix(lower, prefix) { - return strings.TrimSpace(content[len(prefix):]) - } - } - return content -} diff --git a/pkg/channels/irc/init.go b/pkg/channels/irc/init.go deleted file mode 100644 index 3f206cbc..00000000 --- a/pkg/channels/irc/init.go +++ /dev/null @@ -1,35 +0,0 @@ -package irc - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelIRC, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - if bc == nil || !bc.Enabled { - return nil, nil - } - decoded, err := bc.GetDecoded() - if err != nil { - return nil, err - } - c, ok := decoded.(*config.IRCSettings) - if !ok { - return nil, channels.ErrSendFailed - } - ch, err := NewIRCChannel(bc, c, b) - if err != nil { - return nil, err - } - if channelName != config.ChannelIRC { - ch.SetName(channelName) - } - return ch, nil - }, - ) -} diff --git a/pkg/channels/irc/irc.go b/pkg/channels/irc/irc.go deleted file mode 100644 index fa60e9b6..00000000 --- a/pkg/channels/irc/irc.go +++ /dev/null @@ -1,196 +0,0 @@ -package irc - -import ( - "context" - "crypto/tls" - "fmt" - "strings" - - "github.com/ergochat/irc-go/ircevent" - "github.com/ergochat/irc-go/ircmsg" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -// IRCChannel implements the Channel interface for IRC servers. -type IRCChannel struct { - *channels.BaseChannel - bc *config.Channel - config *config.IRCSettings - conn *ircevent.Connection - ctx context.Context - cancel context.CancelFunc -} - -// NewIRCChannel creates a new IRC channel. -func NewIRCChannel(bc *config.Channel, cfg *config.IRCSettings, messageBus *bus.MessageBus) (*IRCChannel, error) { - if cfg.Server == "" { - return nil, fmt.Errorf("irc server is required") - } - if cfg.Nick == "" { - return nil, fmt.Errorf("irc nick is required") - } - - base := channels.NewBaseChannel("irc", cfg, messageBus, bc.AllowFrom, - channels.WithMaxMessageLength(400), - channels.WithGroupTrigger(bc.GroupTrigger), - channels.WithReasoningChannelID(bc.ReasoningChannelID), - ) - - return &IRCChannel{ - BaseChannel: base, - bc: bc, - config: cfg, - }, nil -} - -// Start connects to the IRC server and begins listening. -func (c *IRCChannel) Start(ctx context.Context) error { - logger.InfoC("irc", "Starting IRC channel") - c.ctx, c.cancel = context.WithCancel(ctx) - - user := c.config.User - if user == "" { - user = c.config.Nick - } - realName := c.config.RealName - if realName == "" { - realName = c.config.Nick - } - caps := []string(c.config.RequestCaps) - if len(caps) == 0 { - caps = []string{"server-time", "message-tags"} - } - - conn := &ircevent.Connection{ - Server: c.config.Server, - Nick: c.config.Nick, - User: user, - RealName: realName, - Password: c.config.Password.String(), - UseTLS: c.config.TLS, - RequestCaps: caps, - QuitMessage: "Goodbye", - Debug: false, - Log: nil, - } - - if c.config.TLS { - conn.TLSConfig = &tls.Config{ - ServerName: extractHost(c.config.Server), - } - } - - // SASL auth (takes priority over NickServ) - if c.config.SASLUser != "" && c.config.SASLPassword.String() != "" { - conn.SASLLogin = c.config.SASLUser - conn.SASLPassword = c.config.SASLPassword.String() - } - - // Register event handlers - conn.AddConnectCallback(func(e ircmsg.Message) { - c.onConnect(conn) - }) - conn.AddCallback("PRIVMSG", func(e ircmsg.Message) { - c.onPrivmsg(conn, e) - }) - - if err := conn.Connect(); err != nil { - return fmt.Errorf("irc connect failed: %w", err) - } - - c.conn = conn - - // ircevent.Connection.Loop() handles reconnection internally. - go conn.Loop() - - c.SetRunning(true) - logger.InfoCF("irc", "IRC channel started", map[string]any{ - "server": c.config.Server, - "nick": c.config.Nick, - }) - return nil -} - -// Stop disconnects from the IRC server. -func (c *IRCChannel) Stop(ctx context.Context) error { - logger.InfoC("irc", "Stopping IRC channel") - c.SetRunning(false) - - if c.conn != nil { - c.conn.Quit() - } - if c.cancel != nil { - c.cancel() - } - - logger.InfoC("irc", "IRC channel stopped") - return nil -} - -// Send sends a message to an IRC channel or user. -func (c *IRCChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - target := msg.ChatID - if target == "" { - return nil, fmt.Errorf("chat ID is empty: %w", channels.ErrSendFailed) - } - - if strings.TrimSpace(msg.Content) == "" { - return nil, nil - } - - // Send each line separately (IRC is line-oriented) - lines := strings.Split(msg.Content, "\n") - for _, line := range lines { - line = strings.TrimRight(line, "\r") - if line == "" { - continue - } - c.conn.Privmsg(target, line) - } - - logger.DebugCF("irc", "Message sent", map[string]any{ - "target": target, - "lines": len(lines), - }) - return nil, nil -} - -// StartTyping implements channels.TypingCapable using IRCv3 +typing client tag. -// Requires typing.enabled in config and server support for message-tags capability. -func (c *IRCChannel) StartTyping(ctx context.Context, chatID string) (func(), error) { - noop := func() {} - - if !c.bc.Typing.Enabled || !c.IsRunning() || c.conn == nil { - return noop, nil - } - - // Check if server supports message-tags (required for TAGMSG) - if _, ok := c.conn.AcknowledgedCaps()["message-tags"]; !ok { - return noop, nil - } - - c.conn.SendWithTags(map[string]string{"+typing": "active"}, "TAGMSG", chatID) - - return func() { - if c.IsRunning() && c.conn != nil { - c.conn.SendWithTags(map[string]string{"+typing": "done"}, "TAGMSG", chatID) - } - }, nil -} - -// extractHost returns the hostname portion of a host:port string. -func extractHost(server string) string { - host, _, found := strings.Cut(server, ":") - if found { - return host - } - return server -} diff --git a/pkg/channels/irc/irc_test.go b/pkg/channels/irc/irc_test.go deleted file mode 100644 index e459e71f..00000000 --- a/pkg/channels/irc/irc_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package irc - -import ( - "testing" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/config" -) - -func TestNewIRCChannel(t *testing.T) { - msgBus := bus.NewMessageBus() - - t.Run("missing server", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelIRC, Enabled: true} - cfg := &config.IRCSettings{Nick: "bot"} - _, err := NewIRCChannel(bc, cfg, msgBus) - if err == nil { - t.Error("expected error for missing server, got nil") - } - }) - - t.Run("missing nick", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelIRC, Enabled: true} - cfg := &config.IRCSettings{Server: "irc.example.com:6667"} - _, err := NewIRCChannel(bc, cfg, msgBus) - if err == nil { - t.Error("expected error for missing nick, got nil") - } - }) - - t.Run("valid config", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelIRC, Enabled: true} - cfg := &config.IRCSettings{ - Server: "irc.example.com:6667", - Nick: "testbot", - Channels: []string{"#test"}, - } - ch, err := NewIRCChannel(bc, cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ch.Name() != "irc" { - t.Errorf("Name() = %q, want %q", ch.Name(), "irc") - } - if ch.IsRunning() { - t.Error("new channel should not be running") - } - }) -} - -func TestExtractHost(t *testing.T) { - tests := []struct { - server string - want string - }{ - {"irc.libera.chat:6697", "irc.libera.chat"}, - {"localhost:6667", "localhost"}, - {"irc.example.com", "irc.example.com"}, - {"", ""}, - } - - for _, tt := range tests { - t.Run(tt.server, func(t *testing.T) { - got := extractHost(tt.server) - if got != tt.want { - t.Errorf("extractHost(%q) = %q, want %q", tt.server, got, tt.want) - } - }) - } -} - -func TestNickMentionedAt(t *testing.T) { - tests := []struct { - name string - content string - nick string - want int - }{ - {"colon prefix", "bot: hello", "bot", 0}, - {"comma prefix", "bot, hello", "bot", 0}, - {"case insensitive", "BOT: hello", "bot", 0}, - {"word boundary mid", "hey bot what's up", "bot", 4}, - {"no mention", "hello world", "bot", -1}, - {"substring mismatch", "robotics are cool", "bot", -1}, - {"nick at end", "hello bot", "bot", 6}, - {"empty content", "", "bot", -1}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := nickMentionedAt(tt.content, tt.nick) - if got != tt.want { - t.Errorf("nickMentionedAt(%q, %q) = %d, want %d", tt.content, tt.nick, got, tt.want) - } - }) - } -} - -func TestIsBotMentioned(t *testing.T) { - tests := []struct { - name string - content string - nick string - want bool - }{ - {"colon prefix", "bot: hello", "bot", true}, - {"comma prefix", "bot, hello", "bot", true}, - {"case insensitive", "BOT: hello", "bot", true}, - {"word boundary mid", "hey bot what's up", "bot", true}, - {"no mention", "hello world", "bot", false}, - {"substring mismatch", "robotics are cool", "bot", false}, - {"nick at end", "hello bot", "bot", true}, - {"empty content", "", "bot", false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isBotMentioned(tt.content, tt.nick) - if got != tt.want { - t.Errorf("isBotMentioned(%q, %q) = %v, want %v", tt.content, tt.nick, got, tt.want) - } - }) - } -} - -func TestStripBotMention(t *testing.T) { - tests := []struct { - name string - content string - nick string - want string - }{ - {"colon prefix", "bot: hello there", "bot", "hello there"}, - {"comma prefix", "bot, help me", "bot", "help me"}, - {"case insensitive", "BOT: hello", "bot", "hello"}, - {"no prefix match", "hello bot", "bot", "hello bot"}, - {"only prefix", "bot:", "bot", ""}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := stripBotMention(tt.content, tt.nick) - if got != tt.want { - t.Errorf("stripBotMention(%q, %q) = %q, want %q", tt.content, tt.nick, got, tt.want) - } - }) - } -} diff --git a/pkg/channels/manager.go b/pkg/channels/manager.go index 654ea379..73eea8d6 100644 --- a/pkg/channels/manager.go +++ b/pkg/channels/manager.go @@ -68,11 +68,8 @@ type placeholderEntry struct { var channelRateConfig = map[string]float64{ "telegram": 20, "discord": 1, - "slack": 1, - "matrix": 2, "line": 10, "qq": 5, - "irc": 2, } type channelWorker struct { @@ -1056,18 +1053,12 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe return bc, settings.BridgeURL != "" } return bc, channelType == config.ChannelWhatsAppNative && settings.UseNative - case *config.MatrixSettings: - return bc, settings.Homeserver != "" && settings.UserID != "" && settings.AccessToken.String() != "" case *config.WeComSettings: return bc, settings.BotID != "" && settings.Secret.String() != "" case *config.DingTalkSettings: return bc, settings.ClientID != "" - case *config.SlackSettings: - return bc, settings.BotToken.String() != "" case *config.WeixinSettings: return bc, settings.Token.String() != "" - case *config.IRCSettings: - return bc, settings.Server != "" case *config.LINESettings: return bc, settings.ChannelAccessToken.String() != "" case *config.OneBotSettings: @@ -1078,14 +1069,8 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe return bc, settings.Token.String() != "" case *config.FeishuSettings: return bc, settings.AppSecret.String() != "" - case *config.TeamsWebhookSettings: - return bc, true - case *config.SlackWebhookSettings: - return bc, true case *config.DiscordSettings: return bc, settings.Token.String() != "" - case *config.VKSettings: - return bc, settings.GroupID != 0 && settings.Token.String() != "" case *config.MQTTSettings: return bc, settings.Broker != "" && settings.AgentID != "" } diff --git a/pkg/channels/manager_channel.go b/pkg/channels/manager_channel.go index 7f0cb3b7..a065c798 100644 --- a/pkg/channels/manager_channel.go +++ b/pkg/channels/manager_channel.go @@ -54,15 +54,6 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) { if settings, ok := v.(*config.DiscordSettings); ok { value["token"] = settings.Token.String() } - case "slack": - if settings, ok := v.(*config.SlackSettings); ok { - value["bot_token"] = settings.BotToken.String() - value["app_token"] = settings.AppToken.String() - } - case "matrix": - if settings, ok := v.(*config.MatrixSettings); ok { - value["token"] = settings.AccessToken.String() - } case "onebot": if settings, ok := v.(*config.OneBotSettings); ok { value["token"] = settings.AccessToken.String() @@ -84,57 +75,17 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) { if settings, ok := v.(*config.QQSettings); ok { value["secret"] = settings.AppSecret.String() } - case "irc": - if settings, ok := v.(*config.IRCSettings); ok { - value["password"] = settings.Password.String() - value["serv_password"] = settings.NickServPassword.String() - value["sasl_password"] = settings.SASLPassword.String() - } case "feishu": if settings, ok := v.(*config.FeishuSettings); ok { value["app_secret"] = settings.AppSecret.String() value["encrypt_key"] = settings.EncryptKey.String() value["verification_token"] = settings.VerificationToken.String() } - case "teams_webhook": - // Expose webhook URLs for hash computation (they contain secrets) - vv := value["webhooks"] - webhooks := make(map[string]string) - if vv != nil { - if m, ok := vv.(map[string]string); ok { - webhooks = m - } else if m, ok := vv.(map[string]any); ok { - for k, w := range m { - if s, ok := w.(string); ok { - webhooks[k] = s - } - } - } - } - if settings, ok := v.(*config.TeamsWebhookSettings); ok { - for name, target := range settings.Webhooks { - webhooks[name] = target.WebhookURL.String() - } - } - value["webhooks"] = webhooks case "mqtt": if settings, ok := v.(*config.MQTTSettings); ok { value["username"] = settings.Username.String() value["password"] = settings.Password.String() } - case "slack_webhook": - // Expose webhook URLs for hash computation (they contain secrets) - if settings, ok := v.(*config.SlackWebhookSettings); ok { - webhooks := make(map[string]any) - for name, target := range settings.Webhooks { - webhooks[name] = map[string]any{ - "webhook_url": target.WebhookURL.String(), - "username": target.Username, - "icon_emoji": target.IconEmoji, - } - } - value["webhooks"] = webhooks - } } } diff --git a/pkg/channels/manager_channel_test.go b/pkg/channels/manager_channel_test.go index 9d037329..5e9b00f0 100644 --- a/pkg/channels/manager_channel_test.go +++ b/pkg/channels/manager_channel_test.go @@ -180,28 +180,3 @@ func TestToChannelHashes_EnabledNotBool(t *testing.T) { h := toChannelHashes(cfg) assert.Equal(t, 0, len(h), "string enabled not treated as true") } - -func TestToChannelHashes_TeamsWebhookWithWebhooks(t *testing.T) { - cfg := config.DefaultConfig() - // teams_webhook with configured webhooks — this is the real-world - // scenario where the map type from JSON unmarshal (map[string]any) - // would cause a panic on the old unchecked vv.(map[string]string) - settings, _ := json.Marshal(map[string]any{ - "enabled": true, - "webhooks": map[string]any{ - "hook1": "https://example.com/webhook", - }, - }) - cfg.Channels["teams_webhook"] = &config.Channel{ - Enabled: true, - Type: config.ChannelTeamsWebHook, - Settings: config.RawNode(settings), - } - - assert.NotPanics(t, func() { - _ = toChannelHashes(cfg) - }) - h := toChannelHashes(cfg) - assert.Equal(t, 1, len(h)) - assert.Contains(t, h, "teams_webhook") -} diff --git a/pkg/channels/matrix/init.go b/pkg/channels/matrix/init.go deleted file mode 100644 index f645a464..00000000 --- a/pkg/channels/matrix/init.go +++ /dev/null @@ -1,38 +0,0 @@ -package matrix - -import ( - "path/filepath" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelMatrix, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - decoded, err := bc.GetDecoded() - if err != nil { - return nil, err - } - c, ok := decoded.(*config.MatrixSettings) - if !ok { - return nil, channels.ErrSendFailed - } - cryptoDatabasePath := c.CryptoDatabasePath - if cryptoDatabasePath == "" { - cryptoDatabasePath = filepath.Join(cfg.WorkspacePath(), "matrix") - } - ch, err := NewMatrixChannel(bc, c, b, cryptoDatabasePath) - if err != nil { - return nil, err - } - if channelName != config.ChannelMatrix { - ch.SetName(channelName) - } - return ch, nil - }, - ) -} diff --git a/pkg/channels/matrix/matrix.go b/pkg/channels/matrix/matrix.go deleted file mode 100644 index e8cd2b43..00000000 --- a/pkg/channels/matrix/matrix.go +++ /dev/null @@ -1,1438 +0,0 @@ -package matrix - -import ( - "context" - "database/sql" - "fmt" - "html" - "io" - "mime" - "net/url" - "os" - "path/filepath" - "regexp" - "strings" - "sync" - "time" - - "github.com/gomarkdown/markdown" - mdhtml "github.com/gomarkdown/markdown/html" - "github.com/gomarkdown/markdown/parser" - "go.mau.fi/util/dbutil" - "maunium.net/go/mautrix" - "maunium.net/go/mautrix/crypto/cryptohelper" - "maunium.net/go/mautrix/event" - "maunium.net/go/mautrix/id" - _ "modernc.org/sqlite" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/identity" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/media" -) - -const ( - sqliteDriver = "sqlite" - dbName = "store.db" - - typingRefreshInterval = 20 * time.Second - typingServerTTL = 30 * time.Second - roomKindCacheTTL = 5 * time.Minute - roomKindCacheCleanupPeriod = 1 * time.Minute - roomKindCacheMaxEntries = 2048 -) - -var matrixMentionHrefRegexp = regexp.MustCompile(`(?i)]+href=["']([^"']+)["']`) - -func outboundMessageIsToolFeedback(msg bus.OutboundMessage) bool { - if len(msg.Context.Raw) == 0 { - return false - } - return strings.EqualFold(strings.TrimSpace(msg.Context.Raw["message_kind"]), "tool_feedback") -} - -type roomKindCacheEntry struct { - isGroup bool - expiresAt time.Time - touchedAt time.Time -} - -type roomKindCache struct { - mu sync.Mutex - entries map[string]roomKindCacheEntry - maxEntries int - ttl time.Duration -} - -func newRoomKindCache(maxEntries int, ttl time.Duration) *roomKindCache { - if maxEntries <= 0 { - maxEntries = roomKindCacheMaxEntries - } - if ttl <= 0 { - ttl = roomKindCacheTTL - } - - return &roomKindCache{ - entries: make(map[string]roomKindCacheEntry), - maxEntries: maxEntries, - ttl: ttl, - } -} - -func (c *roomKindCache) get(roomID string, now time.Time) (bool, bool) { - c.mu.Lock() - defer c.mu.Unlock() - - entry, ok := c.entries[roomID] - if !ok { - return false, false - } - if !entry.expiresAt.After(now) { - delete(c.entries, roomID) - return false, false - } - - return entry.isGroup, true -} - -func (c *roomKindCache) set(roomID string, isGroup bool, now time.Time) { - c.mu.Lock() - defer c.mu.Unlock() - - if entry, ok := c.entries[roomID]; ok { - entry.isGroup = isGroup - entry.expiresAt = now.Add(c.ttl) - entry.touchedAt = now - c.entries[roomID] = entry - return - } - - c.cleanupExpiredLocked(now) - for len(c.entries) >= c.maxEntries { - if !c.evictOldestLocked() { - break - } - } - - c.entries[roomID] = roomKindCacheEntry{ - isGroup: isGroup, - expiresAt: now.Add(c.ttl), - touchedAt: now, - } -} - -func (c *roomKindCache) cleanupExpired(now time.Time) int { - c.mu.Lock() - defer c.mu.Unlock() - return c.cleanupExpiredLocked(now) -} - -func (c *roomKindCache) cleanupExpiredLocked(now time.Time) int { - removed := 0 - for roomID, entry := range c.entries { - if !entry.expiresAt.After(now) { - delete(c.entries, roomID) - removed++ - } - } - return removed -} - -func (c *roomKindCache) evictOldestLocked() bool { - if len(c.entries) == 0 { - return false - } - - var ( - oldestRoomID string - oldestAt time.Time - ) - - for roomID, entry := range c.entries { - if oldestRoomID == "" || entry.touchedAt.Before(oldestAt) { - oldestRoomID = roomID - oldestAt = entry.touchedAt - } - } - - delete(c.entries, oldestRoomID) - return true -} - -type typingSession struct { - stopCh chan struct{} - once sync.Once -} - -func newTypingSession() *typingSession { - return &typingSession{ - stopCh: make(chan struct{}), - } -} - -func (s *typingSession) stop() { - s.once.Do(func() { - close(s.stopCh) - }) -} - -// MatrixChannel implements the Channel interface for Matrix. -type MatrixChannel struct { - *channels.BaseChannel - bc *config.Channel - - client *mautrix.Client - config *config.MatrixSettings - syncer *mautrix.DefaultSyncer - - ctx context.Context - cancel context.CancelFunc - startTime time.Time - - typingMu sync.Mutex - typingSessions map[string]*typingSession // roomID -> session - - roomKindCache *roomKindCache - localpartMentionR *regexp.Regexp - - cryptoHelper *cryptohelper.CryptoHelper - cryptoDbPath string - progress *channels.ToolFeedbackAnimator -} - -func NewMatrixChannel( - bc *config.Channel, - cfg *config.MatrixSettings, - messageBus *bus.MessageBus, - cryptoDatabasePath string, -) (*MatrixChannel, error) { - homeserver := strings.TrimSpace(cfg.Homeserver) - userID := strings.TrimSpace(cfg.UserID) - accessToken := strings.TrimSpace(cfg.AccessToken.String()) - if homeserver == "" { - return nil, fmt.Errorf("matrix homeserver is required") - } - if userID == "" { - return nil, fmt.Errorf("matrix user_id is required") - } - if accessToken == "" { - return nil, fmt.Errorf("matrix access_token is required") - } - - client, err := mautrix.NewClient(homeserver, id.UserID(userID), accessToken) - if err != nil { - return nil, fmt.Errorf("create matrix client: %w", err) - } - if cfg.DeviceID != "" { - client.DeviceID = id.DeviceID(cfg.DeviceID) - } - - syncer, ok := client.Syncer.(*mautrix.DefaultSyncer) - if !ok { - return nil, fmt.Errorf("matrix syncer is not *mautrix.DefaultSyncer") - } - - base := channels.NewBaseChannel( - "matrix", - cfg, - messageBus, - bc.AllowFrom, - channels.WithMaxMessageLength(65536), - channels.WithGroupTrigger(bc.GroupTrigger), - channels.WithReasoningChannelID(bc.ReasoningChannelID), - ) - - ch := &MatrixChannel{ - BaseChannel: base, - bc: bc, - client: client, - config: cfg, - syncer: syncer, - typingSessions: make(map[string]*typingSession), - startTime: time.Now(), - roomKindCache: newRoomKindCache(roomKindCacheMaxEntries, roomKindCacheTTL), - localpartMentionR: localpartMentionRegexp(matrixLocalpart(client.UserID)), - typingMu: sync.Mutex{}, - cryptoDbPath: cryptoDatabasePath, - } - ch.progress = channels.NewToolFeedbackAnimator(ch.EditMessage) - return ch, nil -} - -func (c *MatrixChannel) Start(ctx context.Context) error { - logger.InfoC("matrix", "Starting Matrix channel") - - c.ctx, c.cancel = context.WithCancel(ctx) - c.startTime = time.Now() - - // Initialize crypto helper if database and passphrase are configured - if c.cryptoDbPath != "" && c.config.CryptoPassphrase != "" { - if err := c.initCrypto(ctx); err != nil { - logger.WarnCF( - "matrix", - "Failed to initialize crypto, continuing without encryption support", - map[string]any{ - "error": err.Error(), - }, - ) - } - } - - c.syncer.OnEventType(event.EventMessage, c.handleMessageEvent) - c.syncer.OnEventType(event.EventEncrypted, c.handleMessageEvent) - c.syncer.OnEventType(event.StateMember, c.handleMemberEvent) - - c.SetRunning(true) - go c.runRoomKindCacheJanitor(c.ctx) - - go func() { - if err := c.client.SyncWithContext(c.ctx); err != nil && c.ctx.Err() == nil { - logger.ErrorCF("matrix", "Matrix sync stopped unexpectedly", map[string]any{ - "error": err.Error(), - }) - } - }() - - logger.InfoC("matrix", "Matrix channel started") - return nil -} - -func (c *MatrixChannel) Stop(ctx context.Context) error { - logger.InfoC("matrix", "Stopping Matrix channel") - c.SetRunning(false) - - if c.cancel != nil { - c.cancel() - } - c.stopTypingSessions(ctx) - if c.progress != nil { - c.progress.StopAll() - } - - // Close crypto helper if initialized - if c.cryptoHelper != nil { - c.cryptoHelper.Close() - c.cryptoHelper = nil - c.client.Crypto = nil - } - - logger.InfoC("matrix", "Matrix channel stopped") - return nil -} - -func (c *MatrixChannel) initCrypto(ctx context.Context) error { - logger.InfoC("matrix", "Initializing crypto helper") - - // Ensure the crypto database directory exists - if err := os.MkdirAll(c.cryptoDbPath, 0o700); err != nil { - return fmt.Errorf("create crypto database directory: %w", err) - } - - // Create database with sqlite driver (modernc.org/sqlite) - dbPath := filepath.Join(c.cryptoDbPath, dbName) - connStr := "file:" + dbPath + "?_foreign_keys=on" - - db, err := sql.Open(sqliteDriver, connStr) - if err != nil { - return fmt.Errorf("open crypto database: %w", err) - } - db.SetMaxOpenConns(1) - db.SetMaxIdleConns(1) - - // Execute PRAGMA statements - // This is equivalent to the "sqlite3-fk-wal" dialect used by cryptohelper - pragmaStmts := []string{ - "PRAGMA foreign_keys = ON", - "PRAGMA journal_mode = WAL", - "PRAGMA synchronous = NORMAL", - "PRAGMA busy_timeout = 5000", - } - for _, pragma := range pragmaStmts { - if _, err = db.ExecContext(ctx, pragma); err != nil { - _ = db.Close() - return fmt.Errorf("execute %s: %w", pragma, err) - } - } - - // Wrap with dbutil for dialect support - wrappedDB, err := dbutil.NewWithDB(db, sqliteDriver) - if err != nil { - _ = db.Close() - return fmt.Errorf("wrap database: %w", err) - } - - cryptoHelper, err := cryptohelper.NewCryptoHelper(c.client, []byte(c.config.CryptoPassphrase), wrappedDB) - if err != nil { - return fmt.Errorf("create crypto helper: %w", err) - } - - if c.client.DeviceID == "" { - resp, whoamiErr := c.client.Whoami(ctx) - if whoamiErr != nil { - _ = db.Close() - return fmt.Errorf("get device ID via whoami: %w", whoamiErr) - } - c.client.DeviceID = resp.DeviceID - } - - if err = cryptoHelper.Init(ctx); err != nil { - cryptoHelper.Close() - return fmt.Errorf("init crypto helper: %w", err) - } - - c.client.Crypto = cryptoHelper - c.cryptoHelper = cryptoHelper - - logger.InfoC("matrix", "Crypto helper initialized successfully") - return nil -} - -func markdownToHTML(md string) string { - extensions := (parser.CommonExtensions | parser.NoEmptyLineBeforeBlock) &^ parser.DefinitionLists - p := parser.NewWithExtensions(extensions) - renderer := mdhtml.NewRenderer(mdhtml.RendererOptions{Flags: mdhtml.UseXHTML}) - return strings.TrimSpace(string(markdown.ToHTML([]byte(md), p, renderer))) -} - -func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - roomID := id.RoomID(strings.TrimSpace(msg.ChatID)) - if roomID == "" { - return nil, fmt.Errorf("matrix room ID is empty: %w", channels.ErrSendFailed) - } - - content := strings.TrimSpace(msg.Content) - if content == "" { - return nil, nil - } - - isToolFeedback := outboundMessageIsToolFeedback(msg) - if isToolFeedback { - if msgID, handled, err := c.progress.Update(ctx, msg.ChatID, content); handled { - if err != nil { - return nil, err - } - return []string{msgID}, nil - } - } - trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(msg.ChatID) - hasTrackedMsg = hasTrackedMsg && !channels.IsCommandReply(msg) - if !isToolFeedback { - if msgIDs, handled := c.FinalizeToolFeedbackMessage(ctx, msg); handled { - return msgIDs, nil - } - } - if isToolFeedback { - content = channels.InitialAnimatedToolFeedbackContent(content) - } - - resp, err := c.client.SendMessageEvent(ctx, roomID, event.EventMessage, c.messageContent(content)) - if err != nil { - return nil, fmt.Errorf("matrix send: %w", channels.ErrTemporary) - } - msgID := resp.EventID.String() - if isToolFeedback { - c.RecordToolFeedbackMessage(msg.ChatID, msgID, msg.Content) - } else if hasTrackedMsg { - c.dismissTrackedToolFeedbackMessage(ctx, msg.ChatID, trackedMsgID) - } - return []string{msgID}, nil -} - -func (c *MatrixChannel) messageContent(text string) *event.MessageEventContent { - mc := &event.MessageEventContent{MsgType: event.MsgText, Body: text} - if c.config.MessageFormat != "plain" { - mc.Format = event.FormatHTML - mc.FormattedBody = markdownToHTML(text) - } - return mc -} - -// SendMedia implements channels.MediaSender. -func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(msg.ChatID) - - sendCtx := ctx - if sendCtx == nil { - sendCtx = context.Background() - } - - roomID := id.RoomID(strings.TrimSpace(msg.ChatID)) - if roomID == "" { - return nil, fmt.Errorf("matrix room ID is empty: %w", channels.ErrSendFailed) - } - - store := c.GetMediaStore() - if store == nil { - return nil, fmt.Errorf("no media store available: %w", channels.ErrSendFailed) - } - - var eventIDs []string - for _, part := range msg.Parts { - if err := sendCtx.Err(); err != nil { - return nil, err - } - - localPath, meta, err := store.ResolveWithMeta(part.Ref) - if err != nil { - logger.ErrorCF("matrix", "Failed to resolve media ref", map[string]any{ - "ref": part.Ref, - "error": err.Error(), - }) - continue - } - - fileInfo, err := os.Stat(localPath) - if err != nil { - logger.ErrorCF("matrix", "Failed to stat media file", map[string]any{ - "path": localPath, - "error": err.Error(), - }) - continue - } - - file, err := os.Open(localPath) - if err != nil { - logger.ErrorCF("matrix", "Failed to open media file", map[string]any{ - "path": localPath, - "error": err.Error(), - }) - continue - } - - filename := strings.TrimSpace(part.Filename) - if filename == "" { - filename = strings.TrimSpace(meta.Filename) - } - if filename == "" { - filename = filepath.Base(localPath) - } - if filename == "" { - filename = "file" - } - - contentType := strings.TrimSpace(part.ContentType) - if contentType == "" { - contentType = strings.TrimSpace(meta.ContentType) - } - if contentType == "" { - contentType = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename))) - } - if contentType == "" { - contentType = "application/octet-stream" - } - - uploadResp, err := c.client.UploadMedia(sendCtx, mautrix.ReqUploadMedia{ - Content: file, - ContentLength: fileInfo.Size(), - ContentType: contentType, - FileName: filename, - }) - file.Close() - if err != nil { - logger.ErrorCF("matrix", "Failed to upload media", map[string]any{ - "path": localPath, - "type": part.Type, - "error": err.Error(), - }) - return nil, fmt.Errorf("matrix upload media: %w", channels.ErrTemporary) - } - - msgType := matrixOutboundMsgType(part.Type, filename, contentType) - content := matrixOutboundContent( - part.Caption, - filename, - msgType, - contentType, - fileInfo.Size(), - uploadResp.ContentURI.CUString(), - ) - - sendResp, err := c.client.SendMessageEvent(sendCtx, roomID, event.EventMessage, content) - if err != nil { - logger.ErrorCF("matrix", "Failed to send media message", map[string]any{ - "room_id": roomID.String(), - "type": msgType, - "error": err.Error(), - }) - return nil, fmt.Errorf("matrix send media: %w", channels.ErrTemporary) - } - if sendResp != nil { - eventIDs = append(eventIDs, sendResp.EventID.String()) - } - } - - if hasTrackedMsg { - c.dismissTrackedToolFeedbackMessage(ctx, msg.ChatID, trackedMsgID) - } - - return eventIDs, nil -} - -// StartTyping implements channels.TypingCapable. -func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (func(), error) { - if !c.IsRunning() { - return func() {}, nil - } - - roomID := id.RoomID(strings.TrimSpace(chatID)) - if roomID == "" { - return func() {}, fmt.Errorf("matrix room ID is empty") - } - - session := newTypingSession() - - c.typingMu.Lock() - if prev := c.typingSessions[chatID]; prev != nil { - prev.stop() - } - c.typingSessions[chatID] = session - c.typingMu.Unlock() - - parent := c.baseContext() - go c.typingLoop(parent, roomID, session) - - var once sync.Once - stop := func() { - once.Do(func() { - session.stop() - c.typingMu.Lock() - if current := c.typingSessions[chatID]; current == session { - delete(c.typingSessions, chatID) - } - c.typingMu.Unlock() - _, _ = c.client.UserTyping(context.Background(), roomID, false, 0) - }) - } - - return stop, nil -} - -// SendPlaceholder implements channels.PlaceholderCapable. -func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) { - if !c.bc.Placeholder.Enabled { - return "", nil - } - - roomID := id.RoomID(strings.TrimSpace(chatID)) - if roomID == "" { - return "", fmt.Errorf("matrix room ID is empty") - } - - text := c.bc.Placeholder.GetRandomText() - - resp, err := c.client.SendMessageEvent(ctx, roomID, event.EventMessage, &event.MessageEventContent{ - MsgType: event.MsgNotice, - Body: text, - }) - if err != nil { - return "", err - } - - return resp.EventID.String(), nil -} - -// EditMessage implements channels.MessageEditor. -func (c *MatrixChannel) EditMessage(ctx context.Context, chatID string, messageID string, content string) error { - roomID := id.RoomID(strings.TrimSpace(chatID)) - if roomID == "" { - return fmt.Errorf("matrix room ID is empty") - } - if strings.TrimSpace(messageID) == "" { - return fmt.Errorf("matrix message ID is empty") - } - - editContent := c.messageContent(content) - editContent.SetEdit(id.EventID(messageID)) - - _, err := c.client.SendMessageEvent(ctx, roomID, event.EventMessage, editContent) - return err -} - -// DeleteMessage implements channels.MessageDeleter. -func (c *MatrixChannel) DeleteMessage(ctx context.Context, chatID string, messageID string) error { - roomID := id.RoomID(strings.TrimSpace(chatID)) - if roomID == "" { - return fmt.Errorf("matrix room ID is empty") - } - eventID := id.EventID(strings.TrimSpace(messageID)) - if eventID == "" { - return fmt.Errorf("matrix message ID is empty") - } - - _, err := c.client.RedactEvent(ctx, roomID, eventID) - return err -} - -func (c *MatrixChannel) currentToolFeedbackMessage(chatID string) (string, bool) { - if c.progress == nil { - return "", false - } - return c.progress.Current(chatID) -} - -func (c *MatrixChannel) takeToolFeedbackMessage(chatID string) (string, string, bool) { - if c.progress == nil { - return "", "", false - } - return c.progress.Take(chatID) -} - -func (c *MatrixChannel) RecordToolFeedbackMessage(chatID, messageID, content string) { - if c.progress == nil { - return - } - c.progress.Record(chatID, messageID, content) -} - -func (c *MatrixChannel) ClearToolFeedbackMessage(chatID string) { - if c.progress == nil { - return - } - c.progress.Clear(chatID) -} - -func (c *MatrixChannel) DismissToolFeedbackMessage(ctx context.Context, chatID string) { - msgID, ok := c.currentToolFeedbackMessage(chatID) - if !ok { - return - } - c.dismissTrackedToolFeedbackMessage(ctx, chatID, msgID) -} - -func (c *MatrixChannel) dismissTrackedToolFeedbackMessage(ctx context.Context, chatID, messageID string) { - if strings.TrimSpace(chatID) == "" || strings.TrimSpace(messageID) == "" { - return - } - c.ClearToolFeedbackMessage(chatID) - _ = c.DeleteMessage(ctx, chatID, messageID) -} - -func (c *MatrixChannel) finalizeTrackedToolFeedbackMessage( - ctx context.Context, - chatID string, - content string, - editFn func(context.Context, string, string, string) error, -) ([]string, bool) { - msgID, baseContent, ok := c.takeToolFeedbackMessage(chatID) - if !ok || editFn == nil { - return nil, false - } - if err := editFn(ctx, chatID, msgID, content); err != nil { - c.RecordToolFeedbackMessage(chatID, msgID, baseContent) - return nil, false - } - return []string{msgID}, true -} - -func (c *MatrixChannel) FinalizeToolFeedbackMessage(ctx context.Context, msg bus.OutboundMessage) ([]string, bool) { - if outboundMessageIsToolFeedback(msg) || channels.IsCommandReply(msg) { - return nil, false - } - return c.finalizeTrackedToolFeedbackMessage(ctx, msg.ChatID, msg.Content, c.EditMessage) -} - -func (c *MatrixChannel) handleMemberEvent(ctx context.Context, evt *event.Event) { - if !c.config.JoinOnInvite { - return - } - if evt == nil { - return - } - - member := evt.Content.AsMember() - if member.Membership != event.MembershipInvite { - return - } - if evt.GetStateKey() != c.client.UserID.String() { - return - } - - _, err := c.client.JoinRoomByID(c.baseContext(), evt.RoomID) - if err != nil { - logger.WarnCF("matrix", "Failed to auto-join invited room", map[string]any{ - "room_id": evt.RoomID.String(), - "error": err.Error(), - }) - return - } - - logger.InfoCF("matrix", "Joined room after invite", map[string]any{ - "room_id": evt.RoomID.String(), - }) -} - -func (c *MatrixChannel) handleMessageEvent(ctx context.Context, evt *event.Event) { - if evt == nil { - return - } - - // Ignore our own messages. - if evt.Sender == c.client.UserID { - return - } - - // Ignore historical events on first sync. - if time.UnixMilli(evt.Timestamp).Before(c.startTime) { - return - } - - var msgEvt *event.MessageEventContent - switch evt.Type { - case event.EventMessage: - // When crypto is enabled, events marked WasEncrypted=true are - // re-dispatched by c.cryptoHelper after decryption and will be - // processed again in the EventEncrypted branch. Skip to avoid duplication. - if c.client.Crypto != nil && evt.Mautrix.WasEncrypted { - return - } - - msgEvt = evt.Content.AsMessage() - if msgEvt == nil || msgEvt.MsgType == "" { - return - } - case event.EventEncrypted: - var ok bool - msgEvt, ok = c.decryptEvent(ctx, evt) - if !ok { - return - } - } - - // Ignore edits. - if msgEvt.RelatesTo != nil && msgEvt.RelatesTo.GetReplaceID() != "" { - return - } - - roomID := evt.RoomID.String() - scope := channels.BuildMediaScope("matrix", roomID, evt.ID.String()) - - content, mediaPaths, ok := c.extractInboundContent(ctx, msgEvt, scope) - if !ok { - return - } - content = strings.TrimSpace(content) - if content == "" && len(mediaPaths) == 0 { - return - } - - senderID := evt.Sender.String() - sender := bus.SenderInfo{ - Platform: "matrix", - PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID("matrix", senderID), - Username: senderID, - DisplayName: senderID, - } - - if !c.IsAllowedSender(sender) { - logger.DebugCF("matrix", "Message rejected by allowlist", map[string]any{ - "sender_id": senderID, - }) - return - } - - isGroup := c.isGroupRoom(ctx, evt.RoomID) - if isGroup { - isMentioned := c.isBotMentioned(msgEvt) - if isMentioned { - content = c.stripSelfMention(content) - } - respond, cleaned := c.ShouldRespondInGroup(isMentioned, content) - if !respond { - logger.DebugCF("matrix", "Ignoring group message by trigger rules", map[string]any{ - "room_id": roomID, - "is_mentioned": isMentioned, - "mention_only": c.bc.GroupTrigger.MentionOnly, - "prefixes": c.bc.GroupTrigger.Prefixes, - }) - return - } - content = cleaned - } else { - content = c.stripSelfMention(content) - } - - content = strings.TrimSpace(content) - if content == "" { - return - } - - peerKind := "direct" - if isGroup { - peerKind = "group" - } - - metadata := map[string]string{ - "room_id": roomID, - "timestamp": fmt.Sprintf("%d", evt.Timestamp), - "is_group": fmt.Sprintf("%t", isGroup), - "sender_raw": senderID, - } - if replyTo := msgEvt.GetRelatesTo().GetReplyTo(); replyTo != "" { - metadata["reply_to_msg_id"] = replyTo.String() - } - - inboundCtx := bus.InboundContext{ - Channel: "matrix", - ChatID: roomID, - ChatType: peerKind, - SenderID: senderID, - MessageID: evt.ID.String(), - Raw: metadata, - } - if replyTo := msgEvt.GetRelatesTo().GetReplyTo(); replyTo != "" { - inboundCtx.ReplyToMessageID = replyTo.String() - } - - c.HandleInboundContext(c.baseContext(), roomID, content, mediaPaths, inboundCtx, sender) -} - -// decryptEvent decrypts an encrypted event and returns the decrypted message event content. -// It returns the decrypted content and a boolean indicating whether decryption was successful. -func (c *MatrixChannel) decryptEvent(ctx context.Context, evt *event.Event) (*event.MessageEventContent, bool) { - if c.client.Crypto == nil { - logger.DebugCF("matrix", "Received encrypted message but crypto is not enabled", map[string]any{ - "room_id": evt.RoomID.String(), - }) - return nil, false - } - - decrypted, err := c.client.Crypto.Decrypt(ctx, evt) - if err != nil { - logger.WarnCF("matrix", "Failed to decrypt message", map[string]any{ - "room_id": evt.RoomID.String(), - "error": err.Error(), - }) - return nil, false - } - - if decrypted.Type != event.EventMessage { - logger.DebugCF("matrix", "Decrypted event is not a message event", map[string]any{ - "room_id": evt.RoomID.String(), - "type": decrypted.Type.String(), - }) - return nil, false - } - - return decrypted.Content.AsMessage(), true -} - -func (c *MatrixChannel) extractInboundContent( - ctx context.Context, - msgEvt *event.MessageEventContent, - scope string, -) (string, []string, bool) { - switch msgEvt.MsgType { - case event.MsgText, event.MsgNotice: - return msgEvt.Body, nil, true - case event.MsgImage, event.MsgAudio, event.MsgVideo, event.MsgFile: - return c.extractInboundMedia(ctx, msgEvt, scope) - default: - logger.DebugCF("matrix", "Ignoring unsupported matrix msgtype", map[string]any{ - "msgtype": msgEvt.MsgType, - }) - return "", nil, false - } -} - -func (c *MatrixChannel) extractInboundMedia( - ctx context.Context, - msgEvt *event.MessageEventContent, - scope string, -) (string, []string, bool) { - mediaKind := matrixMediaKind(msgEvt.MsgType) - label := matrixMediaLabel(msgEvt, mediaKind) - content := fmt.Sprintf("[%s: %s]", mediaKind, label) - if caption := strings.TrimSpace(msgEvt.GetCaption()); caption != "" { - content = caption + "\n" + content - } - - localPath, err := c.downloadMedia(ctx, msgEvt, mediaKind) - if err != nil { - logger.WarnCF("matrix", "Failed to download media; forwarding as text-only marker", map[string]any{ - "msgtype": msgEvt.MsgType, - "error": err.Error(), - }) - return content, nil, true - } - - filename := matrixMediaFilename(label, mediaKind, matrixContentType(msgEvt)) - ref := c.storeMedia(localPath, media.MediaMeta{ - Filename: filename, - ContentType: matrixContentType(msgEvt), - Source: "matrix", - }, scope) - return content, []string{ref}, true -} - -func (c *MatrixChannel) storeMedia(localPath string, meta media.MediaMeta, scope string) string { - if store := c.GetMediaStore(); store != nil { - if meta.CleanupPolicy == "" { - meta.CleanupPolicy = media.CleanupPolicyDeleteOnCleanup - } - ref, err := store.Store(localPath, meta, scope) - if err == nil { - return ref - } - logger.WarnCF("matrix", "Failed to store media in MediaStore, falling back to local path", map[string]any{ - "path": localPath, - "error": err.Error(), - }) - } - return localPath -} - -func (c *MatrixChannel) downloadMedia( - ctx context.Context, - msgEvt *event.MessageEventContent, - mediaKind string, -) (string, error) { - uri := matrixMediaURI(msgEvt) - if uri == "" { - return "", fmt.Errorf("empty matrix media URL") - } - parsed := uri.ParseOrIgnore() - if parsed.IsEmpty() { - return "", fmt.Errorf("invalid matrix media URL: %s", uri) - } - - dlCtx := c.baseContext() - if ctx != nil { - dlCtx = ctx - } - reqCtx, cancel := context.WithTimeout(dlCtx, 20*time.Second) - defer cancel() - - resp, err := c.client.Download(reqCtx, parsed) - if err != nil { - return "", err - } - defer resp.Body.Close() - - reader := resp.Body - readerClose := func() error { return nil } - - // Encrypted attachments put URL in msgEvt.File and require client-side decryption. - if msgEvt != nil && msgEvt.File != nil && msgEvt.URL == "" { - if err = msgEvt.File.PrepareForDecryption(); err != nil { - return "", fmt.Errorf("decrypt matrix media: %w", err) - } - decryptReader := msgEvt.File.DecryptStream(resp.Body) - reader = decryptReader - readerClose = decryptReader.Close - } - - label := matrixMediaLabel(msgEvt, mediaKind) - ext := matrixMediaExt(label, matrixContentType(msgEvt), mediaKind) - mediaDir, err := matrixMediaTempDir() - if err != nil { - return "", fmt.Errorf("create matrix media directory: %w", err) - } - tmp, err := os.CreateTemp(mediaDir, "matrix-media-*"+ext) - if err != nil { - return "", err - } - tmpPath := tmp.Name() - cleanup := true - defer func() { - _ = tmp.Close() - if cleanup { - _ = os.Remove(tmpPath) - } - }() - - _, err = io.Copy(tmp, reader) - if err != nil { - return "", err - } - if err = readerClose(); err != nil { - return "", fmt.Errorf("decrypt matrix media: %w", err) - } - if err = tmp.Close(); err != nil { - return "", err - } - - cleanup = false - return tmpPath, nil -} - -func matrixContentType(msgEvt *event.MessageEventContent) string { - if msgEvt != nil && msgEvt.Info != nil { - return strings.TrimSpace(msgEvt.Info.MimeType) - } - return "" -} - -func matrixMediaURI(msgEvt *event.MessageEventContent) id.ContentURIString { - if msgEvt == nil { - return "" - } - if msgEvt.URL != "" { - return msgEvt.URL - } - if msgEvt.File != nil { - return msgEvt.File.URL - } - return "" -} - -func matrixMediaKind(msgType event.MessageType) string { - switch msgType { - case event.MsgAudio: - return "audio" - case event.MsgVideo: - return "video" - case event.MsgFile: - return "file" - default: - return "image" - } -} - -func matrixOutboundMsgType(partType, filename, contentType string) event.MessageType { - switch strings.ToLower(strings.TrimSpace(partType)) { - case "image": - return event.MsgImage - case "audio", "voice": - return event.MsgAudio - case "video": - return event.MsgVideo - case "file", "document": - return event.MsgFile - } - - ct := strings.ToLower(strings.TrimSpace(contentType)) - switch { - case strings.HasPrefix(ct, "image/"): - return event.MsgImage - case strings.HasPrefix(ct, "audio/"), ct == "application/ogg", ct == "application/x-ogg": - return event.MsgAudio - case strings.HasPrefix(ct, "video/"): - return event.MsgVideo - } - - switch strings.ToLower(strings.TrimSpace(filepath.Ext(filename))) { - case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg": - return event.MsgImage - case ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac", ".wma", ".opus": - return event.MsgAudio - case ".mp4", ".avi", ".mov", ".webm", ".mkv": - return event.MsgVideo - default: - return event.MsgFile - } -} - -func matrixOutboundContent( - caption, filename string, - msgType event.MessageType, - contentType string, - size int64, - uri id.ContentURIString, -) *event.MessageEventContent { - body := strings.TrimSpace(caption) - if body == "" { - body = filename - } - if body == "" { - body = matrixMediaKind(msgType) - } - - info := &event.FileInfo{MimeType: strings.TrimSpace(contentType)} - if size > 0 && size <= int64(int(^uint(0)>>1)) { - info.Size = int(size) - } - - content := &event.MessageEventContent{ - MsgType: msgType, - Body: body, - URL: uri, - FileName: filename, - Info: info, - } - return content -} - -func matrixMediaLabel(msgEvt *event.MessageEventContent, fallback string) string { - if msgEvt == nil { - return fallback - } - if v := strings.TrimSpace(msgEvt.FileName); v != "" { - return v - } - if v := strings.TrimSpace(msgEvt.Body); v != "" { - return v - } - return fallback -} - -func matrixMediaFilename(label, mediaKind, contentType string) string { - filename := strings.TrimSpace(label) - if filename == "" { - filename = mediaKind - } - if filepath.Ext(filename) == "" { - filename += matrixMediaExt("", contentType, mediaKind) - } - return filename -} - -func matrixMediaExt(filename, contentType, mediaKind string) string { - if ext := strings.TrimSpace(filepath.Ext(filename)); ext != "" { - return ext - } - if contentType != "" { - if exts, err := mime.ExtensionsByType(contentType); err == nil && len(exts) > 0 { - return exts[0] - } - } - switch mediaKind { - case "audio": - return ".ogg" - case "video": - return ".mp4" - case "file": - return ".bin" - default: - return ".jpg" - } -} - -func (c *MatrixChannel) isGroupRoom(ctx context.Context, roomID id.RoomID) bool { - now := time.Now() - if isGroup, ok := c.roomKindCache.get(roomID.String(), now); ok { - return isGroup - } - - qctx := c.baseContext() - if ctx != nil { - qctx = ctx - } - reqCtx, cancel := context.WithTimeout(qctx, 5*time.Second) - defer cancel() - - resp, err := c.client.JoinedMembers(reqCtx, roomID) - if err != nil { - logger.DebugCF("matrix", "Failed to query room members; assume direct", map[string]any{ - "room_id": roomID.String(), - "error": err.Error(), - }) - return false - } - - isGroup := len(resp.Joined) > 2 - c.roomKindCache.set(roomID.String(), isGroup, now) - return isGroup -} - -func (c *MatrixChannel) isBotMentioned(msgEvt *event.MessageEventContent) bool { - if msgEvt == nil { - return false - } - - if msgEvt.Mentions != nil && msgEvt.Mentions.Has(c.client.UserID) { - return true - } - - userID := c.client.UserID.String() - if userID != "" && strings.Contains(msgEvt.Body, userID) { - return true - } - if mentionsUserInFormattedBody(msgEvt.FormattedBody, c.client.UserID) { - return true - } - - mentionR := c.localpartMentionR - if mentionR == nil { - mentionR = localpartMentionRegexp(matrixLocalpart(c.client.UserID)) - } - if mentionR == nil { - return false - } - - // Matrix users are addressed as MXID "@localpart:server", but many clients - // emit plain-text mentions as "@localpart". Both forms are handled here. - return mentionR.MatchString(msgEvt.Body) || mentionR.MatchString(msgEvt.FormattedBody) -} - -func mentionsUserInFormattedBody(formattedBody string, userID id.UserID) bool { - target := strings.ToLower(strings.TrimSpace(userID.String())) - if target == "" { - return false - } - - formattedBody = strings.TrimSpace(formattedBody) - if formattedBody == "" { - return false - } - - if strings.Contains(strings.ToLower(formattedBody), target) { - return true - } - - matches := matrixMentionHrefRegexp.FindAllStringSubmatch(formattedBody, -1) - for _, match := range matches { - if len(match) < 2 { - continue - } - decoded := decodeMatrixMentionHref(match[1]) - if strings.Contains(strings.ToLower(decoded), target) { - return true - } - - u, err := url.Parse(decoded) - if err != nil { - continue - } - - if strings.Contains(strings.ToLower(u.Path), target) || strings.Contains(strings.ToLower(u.Fragment), target) { - return true - } - if strings.Contains(strings.ToLower(decodeMatrixMentionHref(u.Fragment)), target) { - return true - } - } - - return false -} - -func decodeMatrixMentionHref(v string) string { - decoded := html.UnescapeString(strings.TrimSpace(v)) - if decoded == "" { - return "" - } - - for i := 0; i < 2; i++ { - next, err := url.QueryUnescape(decoded) - if err != nil || next == decoded { - break - } - decoded = next - } - return decoded -} - -func (c *MatrixChannel) typingLoop(ctx context.Context, roomID id.RoomID, session *typingSession) { - sendTyping := func() { - _, err := c.client.UserTyping(ctx, roomID, true, typingServerTTL) - if err != nil { - logger.DebugCF("matrix", "Failed to send typing status", map[string]any{ - "room_id": roomID.String(), - "error": err.Error(), - }) - } - } - - sendTyping() - ticker := time.NewTicker(typingRefreshInterval) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return - case <-session.stopCh: - return - case <-ticker.C: - sendTyping() - } - } -} - -func (c *MatrixChannel) stopTypingSessions(ctx context.Context) { - c.typingMu.Lock() - sessions := c.typingSessions - c.typingSessions = make(map[string]*typingSession) - c.typingMu.Unlock() - - stopCtx := ctx - if stopCtx == nil { - stopCtx = context.Background() - } - for roomID, session := range sessions { - session.stop() - _, _ = c.client.UserTyping(stopCtx, id.RoomID(roomID), false, 0) - } -} - -func (c *MatrixChannel) baseContext() context.Context { - if c.ctx != nil { - return c.ctx - } - return context.Background() -} - -func (c *MatrixChannel) runRoomKindCacheJanitor(ctx context.Context) { - ticker := time.NewTicker(roomKindCacheCleanupPeriod) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return - case now := <-ticker.C: - c.roomKindCache.cleanupExpired(now) - } - } -} - -func (c *MatrixChannel) stripSelfMention(text string) string { - return stripUserMentionWithRegexp(text, c.client.UserID, c.localpartMentionR) -} - -func matrixMediaTempDir() (string, error) { - mediaDir := media.TempDir() - if err := os.MkdirAll(mediaDir, 0o700); err != nil { - return "", err - } - return mediaDir, nil -} - -func matrixLocalpart(userID id.UserID) string { - s := strings.TrimPrefix(userID.String(), "@") - localpart, _, _ := strings.Cut(s, ":") - return strings.TrimSpace(localpart) -} - -func localpartMentionRegexp(localpart string) *regexp.Regexp { - localpart = strings.TrimSpace(localpart) - if localpart == "" { - return nil - } - - // Match Matrix mentions in plain text while avoiding false positives: - // "@picoclaw" and "@picoclaw:matrix.org" should match, - // "test@example.com" and "hellopicoclawworld" should not. - pattern := `(?i)(^|[^[:alnum:]_])@` + regexp.QuoteMeta(localpart) + `(?::[A-Za-z0-9._:-]+)?([^[:alnum:]_]|$)` - return regexp.MustCompile(pattern) -} - -func stripUserMention(text string, userID id.UserID) string { - return stripUserMentionWithRegexp(text, userID, localpartMentionRegexp(matrixLocalpart(userID))) -} - -func stripUserMentionWithRegexp(text string, userID id.UserID, mentionR *regexp.Regexp) string { - cleaned := strings.ReplaceAll(text, userID.String(), "") - - if mentionR != nil { - cleaned = mentionR.ReplaceAllString(cleaned, "$1$2") - } - - cleaned = strings.TrimSpace(cleaned) - cleaned = strings.TrimLeft(cleaned, ",:; ") - return strings.TrimSpace(cleaned) -} - -// VoiceCapabilities returns the voice capabilities of the channel. -func (c *MatrixChannel) VoiceCapabilities() channels.VoiceCapabilities { - return channels.VoiceCapabilities{ASR: true, TTS: true} -} diff --git a/pkg/channels/matrix/matrix_test.go b/pkg/channels/matrix/matrix_test.go deleted file mode 100644 index 965396e2..00000000 --- a/pkg/channels/matrix/matrix_test.go +++ /dev/null @@ -1,506 +0,0 @@ -package matrix - -import ( - "context" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "maunium.net/go/mautrix" - "maunium.net/go/mautrix/event" - "maunium.net/go/mautrix/id" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/media" -) - -func TestMatrixLocalpartMentionRegexp(t *testing.T) { - re := localpartMentionRegexp("picoclaw") - - cases := []struct { - text string - want bool - }{ - {text: "@picoclaw hello", want: true}, - {text: "hi @picoclaw:matrix.org", want: true}, - { - text: "\u6b22\u8fce\u4e00\u4e0bpicoclaw\u5c0f\u9f99\u867e", - want: false, // historical false-positive case in PR #356 - }, - {text: "mail test@example.com", want: false}, - } - - for _, tc := range cases { - if got := re.MatchString(tc.text); got != tc.want { - t.Fatalf("text=%q match=%v want=%v", tc.text, got, tc.want) - } - } -} - -func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T) { - ch := &MatrixChannel{ - progress: channels.NewToolFeedbackAnimator(nil), - } - ch.RecordToolFeedbackMessage("!room:matrix.org", "$event1", "🔧 `read_file`") - - msgIDs, handled := ch.finalizeTrackedToolFeedbackMessage( - context.Background(), - "!room:matrix.org", - "final reply", - func(_ context.Context, chatID, messageID, content string) error { - if _, ok := ch.currentToolFeedbackMessage(chatID); ok { - t.Fatal("expected tracked tool feedback to be stopped before edit") - } - if chatID != "!room:matrix.org" || messageID != "$event1" || content != "final reply" { - t.Fatalf("unexpected edit args: %s %s %s", chatID, messageID, content) - } - return nil - }, - ) - if !handled { - t.Fatal("expected finalizeTrackedToolFeedbackMessage to handle tracked message") - } - if len(msgIDs) != 1 || msgIDs[0] != "$event1" { - t.Fatalf("finalizeTrackedToolFeedbackMessage() ids = %v, want [$event1]", msgIDs) - } -} - -func TestFinalizeToolFeedbackMessage_CommandReplyPreservesProgress(t *testing.T) { - ch := &MatrixChannel{progress: channels.NewToolFeedbackAnimator(nil)} - ch.RecordToolFeedbackMessage("!room:matrix.org", "$progress", "Working") - _, handled := ch.FinalizeToolFeedbackMessage(t.Context(), bus.OutboundMessage{ - ChatID: "!room:matrix.org", Content: "请待会再试", - Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}}, - }) - if handled { - t.Fatal("command reply finalized task progress") - } - if id, ok := ch.currentToolFeedbackMessage("!room:matrix.org"); !ok || id != "$progress" { - t.Fatal("task progress was removed") - } -} - -func TestStripUserMention(t *testing.T) { - userID := id.UserID("@picoclaw:matrix.org") - - cases := []struct { - in string - want string - }{ - {in: "@picoclaw:matrix.org hello", want: "hello"}, - {in: "@picoclaw, hello", want: "hello"}, - {in: "no mention here", want: "no mention here"}, - } - - for _, tc := range cases { - if got := stripUserMention(tc.in, userID); got != tc.want { - t.Fatalf("stripUserMention(%q)=%q want=%q", tc.in, got, tc.want) - } - } -} - -func TestIsBotMentioned(t *testing.T) { - ch := &MatrixChannel{ - client: &mautrix.Client{ - UserID: id.UserID("@picoclaw:matrix.org"), - }, - } - - cases := []struct { - name string - msg event.MessageEventContent - want bool - }{ - { - name: "mentions field", - msg: event.MessageEventContent{ - Body: "hello", - Mentions: &event.Mentions{ - UserIDs: []id.UserID{id.UserID("@picoclaw:matrix.org")}, - }, - }, - want: true, - }, - { - name: "full user id in body", - msg: event.MessageEventContent{ - Body: "@picoclaw:matrix.org hello", - }, - want: true, - }, - { - name: "localpart with at sign", - msg: event.MessageEventContent{ - Body: "@picoclaw hello", - }, - want: true, - }, - { - name: "localpart without at sign should not match", - msg: event.MessageEventContent{ - Body: "\u6b22\u8fce\u4e00\u4e0bpicoclaw\u5c0f\u9f99\u867e", - }, - want: false, - }, - { - name: "formatted mention href matrix.to plain", - msg: event.MessageEventContent{ - Body: "hello bot", - FormattedBody: `PicoClaw hello`, - }, - want: true, - }, - { - name: "formatted mention href matrix.to encoded", - msg: event.MessageEventContent{ - Body: "hello bot", - FormattedBody: `PicoClaw hello`, - }, - want: true, - }, - } - - for _, tc := range cases { - if got := ch.isBotMentioned(&tc.msg); got != tc.want { - t.Fatalf("%s: got=%v want=%v", tc.name, got, tc.want) - } - } -} - -func TestRoomKindCache_ExpiresEntries(t *testing.T) { - cache := newRoomKindCache(4, 5*time.Second) - now := time.Unix(100, 0) - cache.set("!room:matrix.org", true, now) - - if got, ok := cache.get("!room:matrix.org", now.Add(2*time.Second)); !ok || !got { - t.Fatalf("expected cached group room before ttl, got ok=%v group=%v", ok, got) - } - - if _, ok := cache.get("!room:matrix.org", now.Add(6*time.Second)); ok { - t.Fatal("expected cache miss after ttl expiry") - } -} - -func TestRoomKindCache_EvictsOldestWhenFull(t *testing.T) { - cache := newRoomKindCache(2, time.Minute) - now := time.Unix(200, 0) - - cache.set("!room1:matrix.org", false, now) - cache.set("!room2:matrix.org", false, now.Add(1*time.Second)) - cache.set("!room3:matrix.org", true, now.Add(2*time.Second)) - - if _, ok := cache.get("!room1:matrix.org", now.Add(2*time.Second)); ok { - t.Fatal("expected oldest cache entry to be evicted") - } - if got, ok := cache.get("!room2:matrix.org", now.Add(2*time.Second)); !ok || got { - t.Fatalf("expected room2 to remain and be direct, got ok=%v group=%v", ok, got) - } - if got, ok := cache.get("!room3:matrix.org", now.Add(2*time.Second)); !ok || !got { - t.Fatalf("expected room3 to remain and be group, got ok=%v group=%v", ok, got) - } -} - -func TestMatrixMediaTempDir(t *testing.T) { - dir, err := matrixMediaTempDir() - if err != nil { - t.Fatalf("matrixMediaTempDir failed: %v", err) - } - if filepath.Base(dir) != media.TempDirName { - t.Fatalf("unexpected media dir base: %q", filepath.Base(dir)) - } - - info, err := os.Stat(dir) - if err != nil { - t.Fatalf("media dir not created: %v", err) - } - if !info.IsDir() { - t.Fatalf("expected directory, got mode=%v", info.Mode()) - } -} - -func TestMatrixMediaExt(t *testing.T) { - if got := matrixMediaExt("photo.png", "", "image"); got != ".png" { - t.Fatalf("filename extension mismatch: got=%q", got) - } - if got := matrixMediaExt("", "image/webp", "image"); got != ".webp" { - t.Fatalf("content-type extension mismatch: got=%q", got) - } - if got := matrixMediaExt("", "", "image"); got != ".jpg" { - t.Fatalf("default image extension mismatch: got=%q", got) - } - if got := matrixMediaExt("", "", "audio"); got != ".ogg" { - t.Fatalf("default audio extension mismatch: got=%q", got) - } - if got := matrixMediaExt("", "", "video"); got != ".mp4" { - t.Fatalf("default video extension mismatch: got=%q", got) - } - if got := matrixMediaExt("", "", "file"); got != ".bin" { - t.Fatalf("default file extension mismatch: got=%q", got) - } -} - -func TestDownloadMedia_WritesResponseToTempFile(t *testing.T) { - const wantBody = "matrix-media-payload" - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !strings.HasSuffix(r.URL.Path, "/_matrix/client/v1/media/download/matrix.test/abc123") { - t.Fatalf("unexpected download path: %s", r.URL.Path) - } - w.Header().Set("Content-Type", "image/png") - _, _ = w.Write([]byte(wantBody)) - })) - defer server.Close() - - client, err := mautrix.NewClient(server.URL, id.UserID("@picoclaw:matrix.test"), "") - if err != nil { - t.Fatalf("NewClient: %v", err) - } - - ch := &MatrixChannel{client: client} - msg := &event.MessageEventContent{ - MsgType: event.MsgImage, - Body: "image.png", - URL: id.ContentURIString("mxc://matrix.test/abc123"), - Info: &event.FileInfo{MimeType: "image/png"}, - } - - path, err := ch.downloadMedia(context.Background(), msg, "image") - if err != nil { - t.Fatalf("downloadMedia: %v", err) - } - defer os.Remove(path) - - if ext := filepath.Ext(path); ext != ".png" { - t.Fatalf("temp file extension=%q want=.png", ext) - } - - got, err := os.ReadFile(path) - if err != nil { - t.Fatalf("ReadFile: %v", err) - } - if string(got) != wantBody { - t.Fatalf("file contents=%q want=%q", string(got), wantBody) - } -} - -func TestExtractInboundContent_ImageNoURLFallback(t *testing.T) { - ch := &MatrixChannel{} - msg := &event.MessageEventContent{ - MsgType: event.MsgImage, - Body: "test.png", - } - - content, mediaRefs, ok := ch.extractInboundContent(context.Background(), msg, "matrix:room:event") - if !ok { - t.Fatal("expected ok for image fallback") - } - if content != "[image: test.png]" { - t.Fatalf("unexpected content: %q", content) - } - if len(mediaRefs) != 0 { - t.Fatalf("expected no media refs, got %d", len(mediaRefs)) - } -} - -func TestExtractInboundContent_AudioNoURLFallback(t *testing.T) { - ch := &MatrixChannel{} - msg := &event.MessageEventContent{ - MsgType: event.MsgAudio, - FileName: "voice.ogg", - Body: "please transcribe", - } - - content, mediaRefs, ok := ch.extractInboundContent(context.Background(), msg, "matrix:room:event") - if !ok { - t.Fatal("expected ok for audio fallback") - } - if content != "please transcribe\n[audio: voice.ogg]" { - t.Fatalf("unexpected content: %q", content) - } - if len(mediaRefs) != 0 { - t.Fatalf("expected no media refs, got %d", len(mediaRefs)) - } -} - -func TestMatrixOutboundMsgType(t *testing.T) { - cases := []struct { - name string - partType string - filename string - contentType string - want event.MessageType - }{ - {name: "explicit image", partType: "image", want: event.MsgImage}, - {name: "explicit audio", partType: "audio", want: event.MsgAudio}, - {name: "mime fallback video", contentType: "video/mp4", want: event.MsgVideo}, - {name: "extension fallback audio", filename: "voice.ogg", want: event.MsgAudio}, - {name: "unknown defaults file", filename: "report.txt", want: event.MsgFile}, - } - - for _, tc := range cases { - if got := matrixOutboundMsgType(tc.partType, tc.filename, tc.contentType); got != tc.want { - t.Fatalf("%s: got=%q want=%q", tc.name, got, tc.want) - } - } -} - -func TestMatrixOutboundContent(t *testing.T) { - content := matrixOutboundContent( - "please review", - "voice.ogg", - event.MsgAudio, - "audio/ogg", - 1234, - id.ContentURIString("mxc://matrix.org/abc"), - ) - if content.Body != "please review" { - t.Fatalf("unexpected body: %q", content.Body) - } - if content.FileName != "voice.ogg" { - t.Fatalf("unexpected filename: %q", content.FileName) - } - if content.Info == nil || content.Info.MimeType != "audio/ogg" { - t.Fatalf("unexpected content type: %+v", content.Info) - } - if content.Info == nil || content.Info.Size != 1234 { - t.Fatalf("unexpected size: %+v", content.Info) - } - - noCaption := matrixOutboundContent( - "", - "image.png", - event.MsgImage, - "image/png", - 0, - id.ContentURIString("mxc://matrix.org/def"), - ) - if noCaption.Body != "image.png" { - t.Fatalf("unexpected fallback body: %q", noCaption.Body) - } -} - -func TestMarkdownToHTML(t *testing.T) { - cases := []struct { - name string - md string - rendered string - }{ - { - name: "paragraph", - md: "just **some** text with _custom_ formatting and `inline` code", - rendered: "

just some text with custom formatting and inline code

", - }, - { - name: "heading", - md: "### Title", - rendered: `

Title

`, - }, - { - name: "fenced code block", - md: "```\nfoo()\n```", - rendered: "
foo()\n
", - }, - { - name: "loose list", - md: "- Item one\n\n- Item two\n", - rendered: `
    -
  • Item one

  • - -
  • Item two

  • -
`, - }, - { - name: "tight list", - md: "- Alpha\n- Beta\n", - rendered: `
    -
  • Alpha
  • -
  • Beta
  • -
`, - }, - { - name: "list item with nested sublist", - md: "1. Steps overview:\n\n - Step A\n - Step B\n", - rendered: `
    -
  1. Steps overview:

    - -
      -
    • Step A
    • -
    • Step B
    • -
  2. -
`, - }, - { - // Definition list syntax is not enabled; the term and definition are - // rendered as a plain paragraph rather than
/
/
elements. - name: "definition list syntax renders as plain paragraph", - md: "Term\n: Definition of the term.\n", - rendered: "

Term\n: Definition of the term.

", - }, - { - name: "comprehensive document with headings, paragraphs, list, and code block", - md: "# Overview\n\nThis is a sample document designed to demonstrate various Markdown elements in a single block of text.\n\nThe first paragraph introduces the concept of structured data.\n\n## Details\n\nThe following is a list:\n\n* First\n* Second\n* Third\n\nThe second paragraph focuses on details. Below is a generic code snippet:\n\n```python\ndef calculate_area(radius):\n import math\n return math.pi * (radius ** 2)\n```\n\nThis concludes the generic sample text.\n", - rendered: `

Overview

- -

This is a sample document designed to demonstrate various Markdown elements in a single block of text.

- -

The first paragraph introduces the concept of structured data.

- -

Details

- -

The following is a list:

- -
    -
  • First
  • -
  • Second
  • -
  • Third
  • -
- -

The second paragraph focuses on details. Below is a generic code snippet:

- -
def calculate_area(radius):
-    import math
-    return math.pi * (radius ** 2)
-
- -

This concludes the generic sample text.

`, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := markdownToHTML(tc.md); got != tc.rendered { - t.Fatalf("markdownToHTML(%q)\n got: %q\nwant: %q", tc.md, got, tc.rendered) - } - }) - } -} - -func TestMessageContent(t *testing.T) { - richtext := &MatrixChannel{config: &config.MatrixSettings{MessageFormat: "richtext"}} - plain := &MatrixChannel{config: &config.MatrixSettings{MessageFormat: "plain"}} - defaultt := &MatrixChannel{config: &config.MatrixSettings{}} - - for _, c := range []*MatrixChannel{richtext, defaultt} { - mc := c.messageContent("**hi**") - if mc.Format != event.FormatHTML { - t.Errorf("format %q: expected FormatHTML, got %q", c.config.MessageFormat, mc.Format) - } - if !strings.Contains(mc.FormattedBody, "hi") { - t.Errorf("format %q: FormattedBody %q missing ", c.config.MessageFormat, mc.FormattedBody) - } - if mc.Body != "**hi**" { - t.Errorf("format %q: Body should remain plain, got %q", c.config.MessageFormat, mc.Body) - } - } - - mc := plain.messageContent("**hi**") - if mc.Format != "" || mc.FormattedBody != "" { - t.Errorf("plain: expected no formatting, got format=%q formattedBody=%q", mc.Format, mc.FormattedBody) - } -} diff --git a/pkg/channels/slack/init.go b/pkg/channels/slack/init.go deleted file mode 100644 index f1dbf6dd..00000000 --- a/pkg/channels/slack/init.go +++ /dev/null @@ -1,25 +0,0 @@ -package slack - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelSlack, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - decoded, err := bc.GetDecoded() - if err != nil { - return nil, err - } - c, ok := decoded.(*config.SlackSettings) - if !ok { - return nil, channels.ErrSendFailed - } - return NewSlackChannel(bc, c, b) - }, - ) -} diff --git a/pkg/channels/slack/slack.go b/pkg/channels/slack/slack.go deleted file mode 100644 index c8655b3d..00000000 --- a/pkg/channels/slack/slack.go +++ /dev/null @@ -1,633 +0,0 @@ -package slack - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/slack-go/slack" - "github.com/slack-go/slack/slackevents" - "github.com/slack-go/slack/socketmode" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/identity" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/media" - "github.com/sipeed/picoclaw/pkg/utils" -) - -type SlackChannel struct { - *channels.BaseChannel - config *config.SlackSettings - api *slack.Client - socketClient *socketmode.Client - botUserID string - teamID string - ctx context.Context - cancel context.CancelFunc - pendingAcks sync.Map - uploadFileFn func(context.Context, slack.UploadFileParameters) error - postTextFn func(context.Context, string, string, string) error -} - -type slackMessageRef struct { - ChannelID string - Timestamp string -} - -func NewSlackChannel( - bc *config.Channel, - cfg *config.SlackSettings, - messageBus *bus.MessageBus, -) (*SlackChannel, error) { - if cfg.BotToken.String() == "" || cfg.AppToken.String() == "" { - return nil, fmt.Errorf("slack bot_token and app_token are required") - } - - api := slack.New( - cfg.BotToken.String(), - slack.OptionAppLevelToken(cfg.AppToken.String()), - ) - - socketClient := socketmode.New(api) - - base := channels.NewBaseChannel("slack", cfg, messageBus, bc.AllowFrom, - channels.WithMaxMessageLength(40000), - channels.WithGroupTrigger(bc.GroupTrigger), - channels.WithReasoningChannelID(bc.ReasoningChannelID), - ) - - return &SlackChannel{ - BaseChannel: base, - config: cfg, - api: api, - socketClient: socketClient, - uploadFileFn: func(ctx context.Context, params slack.UploadFileParameters) error { - _, err := api.UploadFileContext(ctx, params) - return err - }, - postTextFn: func(ctx context.Context, channelID, threadTS, text string) error { - opts := []slack.MsgOption{slack.MsgOptionText(text, false)} - if threadTS != "" { - opts = append(opts, slack.MsgOptionTS(threadTS)) - } - _, _, err := api.PostMessageContext(ctx, channelID, opts...) - return err - }, - }, nil -} - -func (c *SlackChannel) Start(ctx context.Context) error { - logger.InfoC("slack", "Starting Slack channel (Socket Mode)") - - c.ctx, c.cancel = context.WithCancel(ctx) - - authResp, err := c.api.AuthTest() - if err != nil { - return fmt.Errorf("slack auth test failed: %w", err) - } - c.botUserID = authResp.UserID - c.teamID = authResp.TeamID - - logger.InfoCF("slack", "Slack bot connected", map[string]any{ - "bot_user_id": c.botUserID, - "team": authResp.Team, - }) - - go c.eventLoop() - - go func() { - if err := c.socketClient.RunContext(c.ctx); err != nil { - if c.ctx.Err() == nil { - logger.ErrorCF("slack", "Socket Mode connection error", map[string]any{ - "error": err.Error(), - }) - } - } - }() - - c.SetRunning(true) - logger.InfoC("slack", "Slack channel started (Socket Mode)") - return nil -} - -func (c *SlackChannel) Stop(ctx context.Context) error { - logger.InfoC("slack", "Stopping Slack channel") - - if c.cancel != nil { - c.cancel() - } - - c.SetRunning(false) - logger.InfoC("slack", "Slack channel stopped") - return nil -} - -func (c *SlackChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - deliveryChatID, channelID, threadTS := resolveSlackOutboundTarget(msg.ChatID, &msg.Context) - if channelID == "" { - return nil, fmt.Errorf("invalid slack chat ID: %s", msg.ChatID) - } - - opts := []slack.MsgOption{ - slack.MsgOptionText(msg.Content, false), - } - - if msg.ReplyToMessageID != "" && threadTS == "" { - // Answer to the message by creating a Thread under it - opts = append(opts, slack.MsgOptionTS(msg.ReplyToMessageID)) - } else if threadTS != "" { - // If we are already in a thread, continue in the thread - opts = append(opts, slack.MsgOptionTS(threadTS)) - } - - _, ts, err := c.api.PostMessageContext(ctx, channelID, opts...) - if err != nil { - return nil, fmt.Errorf("slack send: %w", channels.ErrTemporary) - } - - if ref, ok := c.pendingAcks.LoadAndDelete(deliveryChatID); ok { - msgRef, ok := ref.(slackMessageRef) - if !ok { - return []string{ts}, nil - } - c.api.AddReaction("white_check_mark", slack.ItemRef{ - Channel: msgRef.ChannelID, - Timestamp: msgRef.Timestamp, - }) - } - - logger.DebugCF("slack", "Message sent", map[string]any{ - "channel_id": channelID, - "thread_ts": threadTS, - }) - - return []string{ts}, nil -} - -// SendMedia implements the channels.MediaSender interface. -func (c *SlackChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - _, channelID, threadTS := resolveSlackMediaOutboundTarget(msg.ChatID, &msg.Context) - if channelID == "" { - return nil, fmt.Errorf("invalid slack chat ID: %s", msg.ChatID) - } - - store := c.GetMediaStore() - if store == nil { - return nil, fmt.Errorf("no media store available: %w", channels.ErrSendFailed) - } - - caption := slackFirstMediaCaption(msg.Parts) - sentAny := false - for _, part := range msg.Parts { - localPath, err := store.Resolve(part.Ref) - if err != nil { - logger.ErrorCF("slack", "Failed to resolve media ref", map[string]any{ - "ref": part.Ref, - "error": err.Error(), - }) - continue - } - - filename := part.Filename - if filename == "" { - filename = "file" - } - - title := part.Caption - if title == "" { - title = filename - } - - err = c.uploadFileFn(ctx, slack.UploadFileParameters{ - Channel: channelID, - ThreadTimestamp: threadTS, - File: localPath, - Filename: filename, - Title: title, - }) - if err != nil { - logger.ErrorCF("slack", "Failed to upload media", map[string]any{ - "filename": filename, - "error": err.Error(), - }) - return nil, fmt.Errorf("slack send media: %w", channels.ErrTemporary) - } - sentAny = true - } - - if sentAny && caption != "" { - if err := c.postTextFn(ctx, channelID, threadTS, caption); err != nil { - return nil, fmt.Errorf("slack send media caption fallback: %w", channels.ErrTemporary) - } - } - - // UploadFile does not expose the posted message timestamp in its - // response; returning nil avoids conflating file IDs with message IDs. - return nil, nil -} - -func slackFirstMediaCaption(parts []bus.MediaPart) string { - for _, part := range parts { - if caption := strings.TrimSpace(part.Caption); caption != "" { - return caption - } - } - return "" -} - -// ReactToMessage implements channels.ReactionCapable. -// It adds an "eyes" (👀) reaction to the inbound message and returns an undo function -// that removes the reaction. -func (c *SlackChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (func(), error) { - channelID, _ := parseSlackChatID(chatID) - if channelID == "" { - return func() {}, nil - } - - c.api.AddReaction("eyes", slack.ItemRef{ - Channel: channelID, - Timestamp: messageID, - }) - - return func() { - c.api.RemoveReaction("eyes", slack.ItemRef{ - Channel: channelID, - Timestamp: messageID, - }) - }, nil -} - -func (c *SlackChannel) eventLoop() { - for { - select { - case <-c.ctx.Done(): - return - case event, ok := <-c.socketClient.Events: - if !ok { - return - } - switch event.Type { - case socketmode.EventTypeEventsAPI: - c.handleEventsAPI(event) - case socketmode.EventTypeSlashCommand: - c.handleSlashCommand(event) - case socketmode.EventTypeInteractive: - if event.Request != nil { - c.socketClient.Ack(*event.Request) - } - } - } - } -} - -func (c *SlackChannel) handleEventsAPI(event socketmode.Event) { - if event.Request != nil { - c.socketClient.Ack(*event.Request) - } - - eventsAPIEvent, ok := event.Data.(slackevents.EventsAPIEvent) - if !ok { - return - } - - switch ev := eventsAPIEvent.InnerEvent.Data.(type) { - case *slackevents.MessageEvent: - c.handleMessageEvent(ev) - case *slackevents.AppMentionEvent: - c.handleAppMention(ev) - } -} - -func (c *SlackChannel) handleMessageEvent(ev *slackevents.MessageEvent) { - if ev.User == c.botUserID || ev.User == "" { - return - } - if ev.BotID != "" { - return - } - if ev.SubType != "" && ev.SubType != "file_share" { - return - } - - // check allowlist to avoid downloading attachments for rejected users - sender := bus.SenderInfo{ - Platform: "slack", - PlatformID: ev.User, - CanonicalID: identity.BuildCanonicalID("slack", ev.User), - } - if !c.IsAllowedSender(sender) { - logger.DebugCF("slack", "Message rejected by allowlist", map[string]any{ - "user_id": ev.User, - }) - return - } - - senderID := ev.User - channelID := ev.Channel - threadTS := ev.ThreadTimeStamp - messageTS := ev.TimeStamp - - chatID := channelID - if threadTS != "" { - chatID = channelID + "/" + threadTS - } - - c.pendingAcks.Store(chatID, slackMessageRef{ - ChannelID: channelID, - Timestamp: messageTS, - }) - - content := ev.Text - content = c.stripBotMention(content) - - // In non-DM channels, apply group trigger filtering - if !strings.HasPrefix(channelID, "D") { - respond, cleaned := c.ShouldRespondInGroup(false, content) - if !respond { - return - } - content = cleaned - } - - var mediaPaths []string - - scope := channels.BuildMediaScope("slack", chatID, messageTS) - - // Helper to register a local file with the media store - storeMedia := func(localPath, filename string) string { - if store := c.GetMediaStore(); store != nil { - ref, err := store.Store(localPath, media.MediaMeta{ - Filename: filename, - Source: "slack", - CleanupPolicy: media.CleanupPolicyDeleteOnCleanup, - }, scope) - if err == nil { - return ref - } - } - return localPath // fallback - } - - if ev.Message != nil && len(ev.Message.Files) > 0 { - for _, file := range ev.Message.Files { - localPath := c.downloadSlackFile(file) - if localPath == "" { - continue - } - mediaPaths = append(mediaPaths, storeMedia(localPath, file.Name)) - content += fmt.Sprintf("\n[file: %s]", file.Name) - } - } - - if strings.TrimSpace(content) == "" { - return - } - - peerKind := "channel" - if strings.HasPrefix(channelID, "D") { - peerKind = "direct" - } - - metadata := map[string]string{ - "message_ts": messageTS, - "channel_id": channelID, - "thread_ts": threadTS, - "platform": "slack", - "team_id": c.teamID, - } - - logger.DebugCF("slack", "Received message", map[string]any{ - "sender_id": senderID, - "chat_id": chatID, - "preview": utils.Truncate(content, 50), - "has_thread": threadTS != "", - }) - - inboundCtx := bus.InboundContext{ - Channel: c.Name(), - Account: c.teamID, - ChatID: channelID, - ChatType: peerKind, - SenderID: senderID, - MessageID: messageTS, - SpaceID: c.teamID, - SpaceType: "workspace", - Raw: metadata, - } - if threadTS != "" { - inboundCtx.TopicID = threadTS - } - - c.HandleInboundContext(c.ctx, chatID, content, mediaPaths, inboundCtx, sender) -} - -func (c *SlackChannel) handleAppMention(ev *slackevents.AppMentionEvent) { - if ev.User == c.botUserID { - return - } - - if !c.IsAllowedSender(bus.SenderInfo{ - Platform: "slack", - PlatformID: ev.User, - CanonicalID: identity.BuildCanonicalID("slack", ev.User), - }) { - logger.DebugCF("slack", "Mention rejected by allowlist", map[string]any{ - "user_id": ev.User, - }) - return - } - - senderID := ev.User - mentionSender := bus.SenderInfo{ - Platform: "slack", - PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID("slack", senderID), - } - channelID := ev.Channel - threadTS := ev.ThreadTimeStamp - messageTS := ev.TimeStamp - - var chatID string - if threadTS != "" { - chatID = channelID + "/" + threadTS - } else { - chatID = channelID + "/" + messageTS - } - - c.pendingAcks.Store(chatID, slackMessageRef{ - ChannelID: channelID, - Timestamp: messageTS, - }) - - content := c.stripBotMention(ev.Text) - - if strings.TrimSpace(content) == "" { - return - } - - mentionPeerKind := "channel" - if strings.HasPrefix(channelID, "D") { - mentionPeerKind = "direct" - } - - metadata := map[string]string{ - "message_ts": messageTS, - "channel_id": channelID, - "thread_ts": threadTS, - "platform": "slack", - "is_mention": "true", - "team_id": c.teamID, - } - inboundCtx := bus.InboundContext{ - Channel: c.Name(), - Account: c.teamID, - ChatID: channelID, - ChatType: mentionPeerKind, - TopicID: threadTS, - SenderID: senderID, - MessageID: messageTS, - SpaceID: c.teamID, - SpaceType: "workspace", - Mentioned: true, - Raw: metadata, - } - - c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, mentionSender) -} - -func (c *SlackChannel) handleSlashCommand(event socketmode.Event) { - cmd, ok := event.Data.(slack.SlashCommand) - if !ok { - return - } - - if event.Request != nil { - c.socketClient.Ack(*event.Request) - } - - cmdSender := bus.SenderInfo{ - Platform: "slack", - PlatformID: cmd.UserID, - CanonicalID: identity.BuildCanonicalID("slack", cmd.UserID), - } - if !c.IsAllowedSender(cmdSender) { - logger.DebugCF("slack", "Slash command rejected by allowlist", map[string]any{ - "user_id": cmd.UserID, - }) - return - } - - senderID := cmd.UserID - channelID := cmd.ChannelID - chatID := channelID - content := cmd.Text - - if strings.TrimSpace(content) == "" { - content = "help" - } - - metadata := map[string]string{ - "channel_id": channelID, - "platform": "slack", - "is_command": "true", - "trigger_id": cmd.TriggerID, - "team_id": c.teamID, - } - - logger.DebugCF("slack", "Slash command received", map[string]any{ - "sender_id": senderID, - "command": cmd.Command, - "text": utils.Truncate(content, 50), - }) - peerKind := "channel" - if strings.HasPrefix(channelID, "D") { - peerKind = "direct" - } - inboundCtx := bus.InboundContext{ - Channel: c.Name(), - Account: c.teamID, - ChatID: channelID, - ChatType: peerKind, - SenderID: senderID, - SpaceID: c.teamID, - SpaceType: "workspace", - Raw: metadata, - } - - c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, cmdSender) -} - -func (c *SlackChannel) downloadSlackFile(file slack.File) string { - downloadURL := file.URLPrivateDownload - if downloadURL == "" { - downloadURL = file.URLPrivate - } - if downloadURL == "" { - logger.ErrorCF("slack", "No download URL for file", map[string]any{"file_id": file.ID}) - return "" - } - - return utils.DownloadFile(downloadURL, file.Name, utils.DownloadOptions{ - LoggerPrefix: "slack", - ExtraHeaders: map[string]string{ - "Authorization": "Bearer " + c.config.BotToken.String(), - }, - }) -} - -func (c *SlackChannel) stripBotMention(text string) string { - mention := fmt.Sprintf("<@%s>", c.botUserID) - text = strings.ReplaceAll(text, mention, "") - return strings.TrimSpace(text) -} - -func parseSlackChatID(chatID string) (channelID, threadTS string) { - parts := strings.SplitN(chatID, "/", 2) - channelID = parts[0] - if len(parts) > 1 { - threadTS = parts[1] - } - return channelID, threadTS -} - -func resolveSlackOutboundTarget(chatID string, outboundCtx *bus.InboundContext) (string, string, string) { - deliveryChatID := strings.TrimSpace(chatID) - if deliveryChatID == "" && outboundCtx != nil { - deliveryChatID = strings.TrimSpace(outboundCtx.ChatID) - } - channelID, threadTS := parseSlackChatID(deliveryChatID) - if threadTS == "" && outboundCtx != nil { - threadTS = strings.TrimSpace(outboundCtx.TopicID) - if threadTS != "" && channelID != "" { - deliveryChatID = channelID + "/" + threadTS - } - } - return deliveryChatID, channelID, threadTS -} - -func resolveSlackMediaOutboundTarget(chatID string, outboundCtx *bus.InboundContext) (string, string, string) { - deliveryChatID := strings.TrimSpace(chatID) - if deliveryChatID == "" && outboundCtx != nil { - deliveryChatID = strings.TrimSpace(outboundCtx.ChatID) - } - channelID, threadTS := parseSlackChatID(deliveryChatID) - if threadTS == "" && outboundCtx != nil { - threadTS = strings.TrimSpace(outboundCtx.TopicID) - if threadTS != "" && channelID != "" { - deliveryChatID = channelID + "/" + threadTS - } - } - return deliveryChatID, channelID, threadTS -} diff --git a/pkg/channels/slack/slack_test.go b/pkg/channels/slack/slack_test.go deleted file mode 100644 index b85f3f02..00000000 --- a/pkg/channels/slack/slack_test.go +++ /dev/null @@ -1,264 +0,0 @@ -package slack - -import ( - "context" - "os" - "path/filepath" - "testing" - - slacksdk "github.com/slack-go/slack" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/media" -) - -func TestParseSlackChatID(t *testing.T) { - tests := []struct { - name string - chatID string - wantChanID string - wantThread string - }{ - { - name: "channel only", - chatID: "C123456", - wantChanID: "C123456", - wantThread: "", - }, - { - name: "channel with thread", - chatID: "C123456/1234567890.123456", - wantChanID: "C123456", - wantThread: "1234567890.123456", - }, - { - name: "DM channel", - chatID: "D987654", - wantChanID: "D987654", - wantThread: "", - }, - { - name: "empty string", - chatID: "", - wantChanID: "", - wantThread: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - chanID, threadTS := parseSlackChatID(tt.chatID) - if chanID != tt.wantChanID { - t.Errorf("parseSlackChatID(%q) channelID = %q, want %q", tt.chatID, chanID, tt.wantChanID) - } - if threadTS != tt.wantThread { - t.Errorf("parseSlackChatID(%q) threadTS = %q, want %q", tt.chatID, threadTS, tt.wantThread) - } - }) - } -} - -func TestResolveSlackOutboundTarget_PrefersContextTopicID(t *testing.T) { - deliveryChatID, channelID, threadTS := resolveSlackOutboundTarget("C123456", &bus.InboundContext{ - Channel: "slack", - ChatID: "C123456", - TopicID: "1234567890.123456", - }) - - if deliveryChatID != "C123456/1234567890.123456" { - t.Fatalf("deliveryChatID = %q, want %q", deliveryChatID, "C123456/1234567890.123456") - } - if channelID != "C123456" { - t.Fatalf("channelID = %q, want %q", channelID, "C123456") - } - if threadTS != "1234567890.123456" { - t.Fatalf("threadTS = %q, want %q", threadTS, "1234567890.123456") - } -} - -func TestStripBotMention(t *testing.T) { - ch := &SlackChannel{botUserID: "U12345BOT"} - - tests := []struct { - name string - input string - want string - }{ - { - name: "mention at start", - input: "<@U12345BOT> hello there", - want: "hello there", - }, - { - name: "mention in middle", - input: "hey <@U12345BOT> can you help", - want: "hey can you help", - }, - { - name: "no mention", - input: "hello world", - want: "hello world", - }, - { - name: "empty string", - input: "", - want: "", - }, - { - name: "only mention", - input: "<@U12345BOT>", - want: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := ch.stripBotMention(tt.input) - if got != tt.want { - t.Errorf("stripBotMention(%q) = %q, want %q", tt.input, got, tt.want) - } - }) - } -} - -func TestNewSlackChannel(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: "slack", Enabled: true} - - t.Run("missing bot token", func(t *testing.T) { - cfg := &config.SlackSettings{} - cfg.AppToken = *config.NewSecureString("xapp-test") - _, err := NewSlackChannel(bc, cfg, msgBus) - if err == nil { - t.Error("expected error for missing bot_token, got nil") - } - }) - - t.Run("missing app token", func(t *testing.T) { - cfg := &config.SlackSettings{} - cfg.BotToken = *config.NewSecureString("xoxb-test") - _, err := NewSlackChannel(bc, cfg, msgBus) - if err == nil { - t.Error("expected error for missing app_token, got nil") - } - }) - - t.Run("valid config", func(t *testing.T) { - cfg := &config.SlackSettings{} - cfg.BotToken = *config.NewSecureString("xoxb-test") - cfg.AppToken = *config.NewSecureString("xapp-test") - bc := &config.Channel{Type: "slack", Enabled: true, AllowFrom: []string{"U123"}} - ch, err := NewSlackChannel(bc, cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ch.Name() != "slack" { - t.Errorf("Name() = %q, want %q", ch.Name(), "slack") - } - if ch.IsRunning() { - t.Error("new channel should not be running") - } - }) -} - -func TestSlackChannelIsAllowed(t *testing.T) { - msgBus := bus.NewMessageBus() - - t.Run("empty allowlist allows all", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelSlack, Enabled: true, AllowFrom: []string{}} - cfg := &config.SlackSettings{} - cfg.BotToken = *config.NewSecureString("xoxb-test") - cfg.AppToken = *config.NewSecureString("xapp-test") - ch, _ := NewSlackChannel(bc, cfg, msgBus) - if !ch.IsAllowed("U_ANYONE") { - t.Error("empty allowlist should allow all users") - } - }) - - t.Run("allowlist restricts users", func(t *testing.T) { - bc := &config.Channel{Type: config.ChannelSlack, Enabled: true, AllowFrom: []string{"U_ALLOWED"}} - cfg := &config.SlackSettings{} - cfg.BotToken = *config.NewSecureString("xoxb-test") - cfg.AppToken = *config.NewSecureString("xapp-test") - ch, _ := NewSlackChannel(bc, cfg, msgBus) - if !ch.IsAllowed("U_ALLOWED") { - t.Error("allowed user should pass allowlist check") - } - if ch.IsAllowed("U_BLOCKED") { - t.Error("non-allowed user should be blocked") - } - }) -} - -func TestSendMedia_SendsCaptionFallbackAfterUploads(t *testing.T) { - ch := &SlackChannel{ - BaseChannel: channels.NewBaseChannel("slack", nil, nil, nil), - } - ch.SetRunning(true) - - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - - tmpDir := t.TempDir() - localPath := filepath.Join(tmpDir, "report.txt") - if err := os.WriteFile(localPath, []byte("attachment body"), 0o600); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - ref, err := store.Store(localPath, media.MediaMeta{ - Filename: "report.txt", - ContentType: "text/plain", - }, "test-scope") - if err != nil { - t.Fatalf("Store() error = %v", err) - } - - var uploaded []slackUploadRecord - var posted []string - ch.uploadFileFn = func(ctx context.Context, params slacksdk.UploadFileParameters) error { - uploaded = append(uploaded, slackUploadRecord{ - Channel: params.Channel, - Thread: params.ThreadTimestamp, - File: params.File, - Name: params.Filename, - Title: params.Title, - }) - return nil - } - ch.postTextFn = func(ctx context.Context, channelID, threadTS, text string) error { - posted = append(posted, channelID+"|"+threadTS+"|"+text) - return nil - } - - _, err = ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ - ChatID: "C123456/1234567890.123456", - Parts: []bus.MediaPart{{ - Ref: ref, - Type: "file", - Filename: "report.txt", - ContentType: "text/plain", - Caption: "shared caption", - }}, - }) - if err != nil { - t.Fatalf("SendMedia() error = %v", err) - } - if len(uploaded) != 1 { - t.Fatalf("uploads = %v, want 1 upload", uploaded) - } - if uploaded[0].Title != "shared caption" { - t.Fatalf("upload title = %q, want shared caption", uploaded[0].Title) - } - if len(posted) != 1 || posted[0] != "C123456|1234567890.123456|shared caption" { - t.Fatalf("posted = %v, want fallback text in same thread", posted) - } -} - -type slackUploadRecord struct { - Channel string - Thread string - File string - Name string - Title string -} diff --git a/pkg/channels/slack_webhook/convert.go b/pkg/channels/slack_webhook/convert.go deleted file mode 100644 index 6ee2be2f..00000000 --- a/pkg/channels/slack_webhook/convert.go +++ /dev/null @@ -1,263 +0,0 @@ -package slackwebhook - -import ( - "fmt" - "regexp" - "strings" -) - -const maxTableRowWidth = 60 - -var ( - boldRe = regexp.MustCompile(`\*\*([^*]+)\*\*`) - strikeRe = regexp.MustCompile(`~~([^~]+)~~`) - linkRe = regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`) - headerRe = regexp.MustCompile(`(?m)^#{1,6}\s+(.+)$`) - bulletRe = regexp.MustCompile(`(?m)^- (.+)$`) - markdownTableRe = regexp.MustCompile(`(?m)^(\|[^\n]+\|)\n(\|[-:\|\s]+\|)\n((?:\|[^\n]+\|\n?)+)`) - codeBlockRe = regexp.MustCompile("(?s)```.*?```") - inlineCodeRe = regexp.MustCompile("`[^`]+`") - italicRe = regexp.MustCompile(`(?:^|[^*])\*([^*]+)\*(?:[^*]|$)`) -) - -type contentSegment struct { - content string - isTable bool -} - -func convertMarkdownToMrkdwn(text string) string { - // Protect code blocks from conversion - var codeBlocks []string - text = codeBlockRe.ReplaceAllStringFunc(text, func(match string) string { - codeBlocks = append(codeBlocks, match) - return "\x00CODEBLOCK\x00" - }) - - // Protect inline code - var inlineCode []string - text = inlineCodeRe.ReplaceAllStringFunc(text, func(match string) string { - inlineCode = append(inlineCode, match) - return "\x00INLINE\x00" - }) - - // Convert italic *text* → _text_ BEFORE bold conversion - text = italicRe.ReplaceAllStringFunc(text, func(match string) string { - // Find the asterisk positions - firstAsterisk := strings.Index(match, "*") - lastAsterisk := strings.LastIndex(match, "*") - if firstAsterisk == lastAsterisk { - return match // Only one asterisk, not italic - } - - // Extract content between asterisks - content := match[firstAsterisk+1 : lastAsterisk] - - // Replace with underscores, preserving any prefix/suffix - return match[:firstAsterisk] + "_" + content + "_" + match[lastAsterisk+1:] - }) - - // Convert bold **text** → *text* - text = boldRe.ReplaceAllString(text, "*$1*") - - // Convert strikethrough ~~text~~ → ~text~ - text = strikeRe.ReplaceAllString(text, "~$1~") - - // Convert links [text](url) → - text = linkRe.ReplaceAllString(text, "<$2|$1>") - - // Convert headers # text → *text* - text = headerRe.ReplaceAllString(text, "*$1*") - - // Convert bullet lists - item → • item - text = bulletRe.ReplaceAllString(text, "• $1") - - // Restore inline code - for _, code := range inlineCode { - text = strings.Replace(text, "\x00INLINE\x00", code, 1) - } - - // Restore code blocks - for _, block := range codeBlocks { - text = strings.Replace(text, "\x00CODEBLOCK\x00", block, 1) - } - - return text -} - -func splitContentWithTables(content string) []contentSegment { - var segments []contentSegment - - // Protect code blocks from table detection using unique placeholders - var codeBlocks []string - blockIdx := 0 - protected := codeBlockRe.ReplaceAllStringFunc(content, func(match string) string { - codeBlocks = append(codeBlocks, match) - placeholder := fmt.Sprintf("\x00CODEBLOCK_%d\x00", blockIdx) - blockIdx++ - return placeholder - }) - - matches := markdownTableRe.FindAllStringSubmatchIndex(protected, -1) - if len(matches) == 0 { - return []contentSegment{{content: content, isTable: false}} - } - - // Restore code blocks using indexed placeholders - restoreCodeBlocks := func(s string) string { - result := s - for i, block := range codeBlocks { - placeholder := fmt.Sprintf("\x00CODEBLOCK_%d\x00", i) - result = strings.Replace(result, placeholder, block, 1) - } - return result - } - - lastEnd := 0 - for _, match := range matches { - if match[0] > lastEnd { - segments = append(segments, contentSegment{ - content: restoreCodeBlocks(protected[lastEnd:match[0]]), - isTable: false, - }) - } - segments = append(segments, contentSegment{ - content: restoreCodeBlocks(protected[match[0]:match[1]]), - isTable: true, - }) - lastEnd = match[1] - } - - if lastEnd < len(protected) { - segments = append(segments, contentSegment{ - content: restoreCodeBlocks(protected[lastEnd:]), - isTable: false, - }) - } - - return segments -} - -func renderTable(tableStr string) string { - lines := strings.Split(strings.TrimSpace(tableStr), "\n") - if len(lines) < 2 { - return "```\n" + tableStr + "\n```" - } - - // Parse all rows to get column widths - var allRows [][]string - maxCols := 0 - for i, line := range lines { - if i == 1 && isSeparatorRow(line) { - continue - } - cells := parseTableRow(line) - if len(cells) > 0 { - allRows = append(allRows, cells) - if len(cells) > maxCols { - maxCols = len(cells) - } - } - } - - if len(allRows) == 0 { - return "```\n" + tableStr + "\n```" - } - - // Calculate max width for each column using rune count - colWidths := make([]int, maxCols) - for _, row := range allRows { - for i, cell := range row { - runeLen := len([]rune(cell)) - if runeLen > colWidths[i] { - colWidths[i] = runeLen - } - } - } - - // Check if table is narrow enough for mrkdwn format - totalWidth := 0 - for _, w := range colWidths { - totalWidth += w - } - if len(colWidths) > 1 { - totalWidth += 3 * (len(colWidths) - 1) // " | " separators between columns - } - if totalWidth <= maxTableRowWidth { - // Render as formatted text with bold headers - var result strings.Builder - for i, row := range allRows { - if i == 0 { - var boldCells []string - for _, cell := range row { - boldCells = append(boldCells, "*"+cell+"*") - } - result.WriteString(strings.Join(boldCells, " | ")) - } else { - result.WriteString(strings.Join(row, " | ")) - } - result.WriteString("\n") - } - return strings.TrimSuffix(result.String(), "\n") - } - - // Render as aligned code block - var result strings.Builder - result.WriteString("```\n") - for i, row := range allRows { - var paddedCells []string - for j, cell := range row { - if j < len(colWidths) { - paddedCells = append(paddedCells, padRight(cell, colWidths[j])) - } else { - paddedCells = append(paddedCells, cell) - } - } - result.WriteString("| ") - result.WriteString(strings.Join(paddedCells, " | ")) - result.WriteString(" |\n") - - // Add separator after header - if i == 0 { - var sepParts []string - for _, w := range colWidths { - sepParts = append(sepParts, strings.Repeat("-", w)) - } - result.WriteString("|-") - result.WriteString(strings.Join(sepParts, "-|-")) - result.WriteString("-|\n") - } - } - result.WriteString("```") - return result.String() -} - -func padRight(s string, width int) string { - runeLen := len([]rune(s)) - if runeLen >= width { - return s - } - return s + strings.Repeat(" ", width-runeLen) -} - -func isSeparatorRow(line string) bool { - cleaned := strings.ReplaceAll(line, "|", "") - cleaned = strings.ReplaceAll(cleaned, " ", "") - cleaned = strings.ReplaceAll(cleaned, "-", "") - cleaned = strings.ReplaceAll(cleaned, ":", "") - return cleaned == "" -} - -func parseTableRow(line string) []string { - line = strings.TrimSpace(line) - line = strings.TrimPrefix(line, "|") - line = strings.TrimSuffix(line, "|") - if line == "" { - return nil - } - parts := strings.Split(line, "|") - var cells []string - for _, p := range parts { - cells = append(cells, strings.TrimSpace(p)) - } - return cells -} diff --git a/pkg/channels/slack_webhook/convert_test.go b/pkg/channels/slack_webhook/convert_test.go deleted file mode 100644 index 39ff4ac0..00000000 --- a/pkg/channels/slack_webhook/convert_test.go +++ /dev/null @@ -1,187 +0,0 @@ -package slackwebhook - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestConvertMarkdownToMrkdwn(t *testing.T) { - tests := []struct { - name string - input string - expected string - }{ - { - name: "bold double asterisk", - input: "This is **bold** text", - expected: "This is *bold* text", - }, - { - name: "italic single asterisk", - input: "This is *italic* text", - expected: "This is _italic_ text", - }, - { - name: "italic underscore", - input: "This is _italic_ text", - expected: "This is _italic_ text", - }, - { - name: "strikethrough", - input: "This is ~~struck~~ text", - expected: "This is ~struck~ text", - }, - { - name: "inline code unchanged", - input: "Use `code` here", - expected: "Use `code` here", - }, - { - name: "link conversion", - input: "Click [here](https://example.com) now", - expected: "Click now", - }, - { - name: "header to bold", - input: "# Header One", - expected: "*Header One*", - }, - { - name: "header level 2", - input: "## Header Two", - expected: "*Header Two*", - }, - { - name: "bullet list", - input: "- item one\n- item two", - expected: "• item one\n• item two", - }, - { - name: "mixed formatting", - input: "**bold** and *italic* and [link](http://x.com)", - expected: "*bold* and _italic_ and ", - }, - { - name: "code block unchanged", - input: "```\ncode here\n```", - expected: "```\ncode here\n```", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := convertMarkdownToMrkdwn(tt.input) - assert.Equal(t, tt.expected, result) - }) - } -} - -func TestSplitContentWithTables(t *testing.T) { - tests := []struct { - name string - input string - expectedCount int - expectedTables int - }{ - { - name: "no table", - input: "Just some text", - expectedCount: 1, - expectedTables: 0, - }, - { - name: "simple table", - input: "| A | B |\n|---|---|\n| 1 | 2 |", - expectedCount: 1, - expectedTables: 1, - }, - { - name: "text before table", - input: "Intro text\n\n| A | B |\n|---|---|\n| 1 | 2 |", - expectedCount: 2, - expectedTables: 1, - }, - { - name: "text before and after table", - input: "Before\n\n| A | B |\n|---|---|\n| 1 | 2 |\n\nAfter", - expectedCount: 3, - expectedTables: 1, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - segments := splitContentWithTables(tt.input) - assert.Equal(t, tt.expectedCount, len(segments)) - tableCount := 0 - for _, seg := range segments { - if seg.isTable { - tableCount++ - } - } - assert.Equal(t, tt.expectedTables, tableCount) - }) - } -} - -func TestRenderTable(t *testing.T) { - tests := []struct { - name string - input string - expectCode bool - }{ - { - name: "narrow table renders as text", - input: "| A | B |\n|---|---|\n| 1 | 2 |", - expectCode: false, - }, - { - name: "wide table renders as code block", - input: "| This is a very long column header | Another extremely long column header here |\n|---|---|\n| Some long value content here | More long value content |", - expectCode: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := renderTable(tt.input) - if tt.expectCode { - assert.Contains(t, result, "```") - } else { - assert.NotContains(t, result, "```") - assert.Contains(t, result, "*") // Bold headers - } - }) - } -} - -func TestRenderTable_Alignment(t *testing.T) { - input := "| Name | Status | Count |\n|---|---|---|\n| foo | OK | 1 |\n| barbaz | PENDING | 123 |" - result := renderTable(input) - - // Should be mrkdwn (narrow table) - assert.NotContains(t, result, "```") - assert.Contains(t, result, "*Name*") - - // Test wide table alignment - wideInput := "| This is a very long column header | Another extremely long column header here |\n|---|---|\n| Short | Longer value here |" - wideResult := renderTable(wideInput) - - assert.Contains(t, wideResult, "```") - // Check that columns are padded - header and value should have same column width - lines := strings.Split(wideResult, "\n") - // Find the header line and a data line - var headerLine, dataLine string - for _, line := range lines { - if strings.Contains(line, "This is a very long") { - headerLine = line - } - if strings.Contains(line, "Short") { - dataLine = line - } - } - // Both lines should have same length (aligned columns) - assert.Equal(t, len(headerLine), len(dataLine), "columns should be aligned") -} diff --git a/pkg/channels/slack_webhook/init.go b/pkg/channels/slack_webhook/init.go deleted file mode 100644 index eed3ae08..00000000 --- a/pkg/channels/slack_webhook/init.go +++ /dev/null @@ -1,32 +0,0 @@ -package slackwebhook - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelSlackWebHook, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - decoded, err := bc.GetDecoded() - if err != nil { - return nil, err - } - c, ok := decoded.(*config.SlackWebhookSettings) - if !ok { - return nil, channels.ErrSendFailed - } - ch, err := NewSlackWebhookChannel(bc, c, b) - if err != nil { - return nil, err - } - if channelName != config.ChannelSlackWebHook { - ch.SetName(channelName) - } - return ch, nil - }, - ) -} diff --git a/pkg/channels/slack_webhook/slack_webhook.go b/pkg/channels/slack_webhook/slack_webhook.go deleted file mode 100644 index 95951de6..00000000 --- a/pkg/channels/slack_webhook/slack_webhook.go +++ /dev/null @@ -1,316 +0,0 @@ -package slackwebhook - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "sort" - "strings" - "time" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -const maxTextBlockLength = 3000 - -// SlackWebhookChannel is an output-only channel that sends messages -// to Slack via Incoming Webhooks using Block Kit formatting. -type SlackWebhookChannel struct { - *channels.BaseChannel - bc *config.Channel - config *config.SlackWebhookSettings - client *http.Client -} - -// NewSlackWebhookChannel creates a new Slack webhook channel. -func NewSlackWebhookChannel( - bc *config.Channel, - cfg *config.SlackWebhookSettings, - bus *bus.MessageBus, -) (*SlackWebhookChannel, error) { - if len(cfg.Webhooks) == 0 { - return nil, fmt.Errorf("slack_webhook: at least one webhook target is required") - } - - if _, hasDefault := cfg.Webhooks["default"]; !hasDefault { - return nil, fmt.Errorf("slack_webhook: a 'default' webhook target is required") - } - - for name, target := range cfg.Webhooks { - webhookURL := target.WebhookURL.String() - if webhookURL == "" { - return nil, fmt.Errorf("slack_webhook: webhook %q has empty webhook_url", name) - } - parsed, err := url.Parse(webhookURL) - if err != nil { - return nil, fmt.Errorf("slack_webhook: webhook %q has invalid URL format: %w", name, err) - } - if !strings.EqualFold(parsed.Scheme, "https") { - return nil, fmt.Errorf("slack_webhook: webhook %q must use HTTPS (got %q)", name, parsed.Scheme) - } - } - - base := channels.NewBaseChannel( - "slack_webhook", - cfg, - bus, - []string{"*"}, - channels.WithMaxMessageLength(40000), - ) - - return &SlackWebhookChannel{ - BaseChannel: base, - bc: bc, - config: cfg, - client: &http.Client{ - Timeout: 30 * time.Second, - }, - }, nil -} - -// Start initializes the channel. For output-only channels, this is a no-op. -func (c *SlackWebhookChannel) Start(ctx context.Context) error { - targets := make([]string, 0, len(c.config.Webhooks)) - for name := range c.config.Webhooks { - targets = append(targets, name) - } - sort.Strings(targets) - logger.InfoCF("slack_webhook", "Starting Slack webhook channel (output-only)", map[string]any{ - "targets": targets, - }) - c.SetRunning(true) - return nil -} - -// Stop shuts down the channel. -func (c *SlackWebhookChannel) Stop(ctx context.Context) error { - logger.InfoC("slack_webhook", "Stopping Slack webhook channel") - c.SetRunning(false) - return nil -} - -// Send delivers a message to the specified Slack webhook target. -func (c *SlackWebhookChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - targetName := msg.ChatID - if targetName == "" { - targetName = "default" - } - - target, ok := c.config.Webhooks[targetName] - if !ok { - logger.WarnCF("slack_webhook", "Unknown target, falling back to default", map[string]any{ - "requested": msg.ChatID, - "using": "default", - }) - target = c.config.Webhooks["default"] - targetName = "default" - } - - payload := c.buildPayload(msg, target) - - jsonData, err := json.Marshal(payload) - if err != nil { - return nil, fmt.Errorf("slack_webhook: failed to marshal payload: %w", err) - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, target.WebhookURL.String(), bytes.NewReader(jsonData)) - if err != nil { - return nil, fmt.Errorf("slack_webhook: failed to create request: %w", err) - } - req.Header.Set("Content-Type", "application/json") - - resp, err := c.client.Do(req) - if err != nil { - logger.ErrorCF("slack_webhook", "Failed to send message", map[string]any{ - "target": targetName, - }) - // Don't expose raw error - it may contain webhook URL secrets - return nil, fmt.Errorf("slack_webhook: network error: %w", channels.ErrTemporary) - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) - respText := strings.TrimSpace(string(respBody)) - if respText == "" { - respText = http.StatusText(resp.StatusCode) - if respText == "" { - respText = "unknown error" - } - } - logger.ErrorCF("slack_webhook", "Slack API error", map[string]any{ - "target": targetName, - "status": resp.StatusCode, - "response": respText, - }) - sendErr := fmt.Errorf("status %d: %s", resp.StatusCode, respText) - return nil, fmt.Errorf("slack_webhook: %w", channels.ClassifySendError(resp.StatusCode, sendErr)) - } - - logger.DebugCF("slack_webhook", "Message sent successfully", map[string]any{ - "target": targetName, - }) - - return nil, nil -} - -func (c *SlackWebhookChannel) buildPayload(msg bus.OutboundMessage, target config.SlackWebhookTarget) map[string]any { - payload := make(map[string]any) - - if target.Username != "" { - payload["username"] = target.Username - } - if target.IconEmoji != "" { - payload["icon_emoji"] = target.IconEmoji - } - - content := msg.Content - if content == "" { - content = "(empty message)" - } - - blocks := c.buildBlocks(content) - payload["blocks"] = blocks - - return payload -} - -func (c *SlackWebhookChannel) buildBlocks(content string) []map[string]any { - var blocks []map[string]any - - segments := splitContentWithTables(content) - - for _, seg := range segments { - if seg.isTable { - tableText := renderTable(seg.content) - for _, chunk := range splitText(tableText, maxTextBlockLength) { - blocks = append(blocks, c.textSection(chunk)) - } - } else { - text := strings.TrimSpace(seg.content) - if text == "" { - continue - } - converted := convertMarkdownToMrkdwn(text) - for _, chunk := range splitText(converted, maxTextBlockLength) { - blocks = append(blocks, c.textSection(chunk)) - } - } - } - - if len(blocks) == 0 { - blocks = append(blocks, c.textSection("(empty message)")) - } - - return blocks -} - -func (c *SlackWebhookChannel) textSection(text string) map[string]any { - return map[string]any{ - "type": "section", - "text": map[string]any{ - "type": "mrkdwn", - "text": text, - }, - } -} - -func splitText(text string, maxLen int) []string { - runes := []rune(text) - if len(runes) <= maxLen { - return []string{text} - } - - const fencePrefix = "```\n" - const fenceSuffix = "\n```" - fencePrefixLen := len([]rune(fencePrefix)) - fenceSuffixLen := len([]rune(fenceSuffix)) - - var chunks []string - inFence := false - - for len(runes) > 0 { - // Calculate content budget reserving space for fence markers - prefixLen := 0 - if inFence { - prefixLen = fencePrefixLen - } - contentBudget := maxLen - prefixLen - fenceSuffixLen - if contentBudget <= 0 { - contentBudget = maxLen - } - - splitAt := len(runes) - if splitAt > contentBudget { - splitAt = findSplitPoint(runes, contentBudget) - if splitAt <= 0 || splitAt > contentBudget { - splitAt = contentBudget - } - } - - chunkBody := string(runes[:splitAt]) - chunkEndsInFence := endsInsideFence(chunkBody, inFence) - chunk := wrapFenceChunk(chunkBody, inFence, chunkEndsInFence) - - chunks = append(chunks, chunk) - inFence = chunkEndsInFence - runes = runes[splitAt:] - } - - return chunks -} - -func wrapFenceChunk(text string, wasInFence bool, endsInFence bool) string { - if wasInFence && !strings.HasPrefix(strings.TrimSpace(text), "```") { - text = "```\n" + text - } - if endsInFence { - text = strings.TrimSuffix(text, "\n") + "\n```" - } - return text -} - -func findSplitPoint(runes []rune, maxLen int) int { - if len(runes) <= maxLen { - return len(runes) - } - window := string(runes[:maxLen]) - - // Try splitting on newline - if idx := strings.LastIndex(window, "\n"); idx > 0 { - return len([]rune(window[:idx])) + 1 - } - - // Try splitting on space - if idx := strings.LastIndex(window, " "); idx > 0 { - return len([]rune(window[:idx])) + 1 - } - - // Try to split before a fence marker - if idx := strings.LastIndex(window, "```"); idx > 0 { - return len([]rune(window[:idx])) - } - - return maxLen -} - -func endsInsideFence(text string, wasInFence bool) bool { - return wasInFence != (strings.Count(text, "```")%2 == 1) -} diff --git a/pkg/channels/slack_webhook/slack_webhook_test.go b/pkg/channels/slack_webhook/slack_webhook_test.go deleted file mode 100644 index 83a4c052..00000000 --- a/pkg/channels/slack_webhook/slack_webhook_test.go +++ /dev/null @@ -1,281 +0,0 @@ -package slackwebhook - -import ( - "context" - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func TestNewSlackWebhookChannel_Validation(t *testing.T) { - tests := []struct { - name string - webhooks map[string]config.SlackWebhookTarget - expectErr string - }{ - { - name: "empty webhooks", - webhooks: map[string]config.SlackWebhookTarget{}, - expectErr: "at least one webhook target is required", - }, - { - name: "missing default", - webhooks: map[string]config.SlackWebhookTarget{ - "alerts": { - WebhookURL: *config.NewSecureString("https://hooks.slack.com/services/T/B/x"), - }, - }, - expectErr: "a 'default' webhook target is required", - }, - { - name: "empty webhook URL", - webhooks: map[string]config.SlackWebhookTarget{ - "default": {WebhookURL: *config.NewSecureString("")}, - }, - expectErr: "has empty webhook_url", - }, - { - name: "non-HTTPS URL", - webhooks: map[string]config.SlackWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("http://hooks.slack.com/services/T/B/x"), - }, - }, - expectErr: "must use HTTPS", - }, - { - name: "valid config", - webhooks: map[string]config.SlackWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://hooks.slack.com/services/T/B/x"), - Username: "TestBot", - IconEmoji: ":robot_face:", - }, - }, - expectErr: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.SlackWebhookSettings{Webhooks: tt.webhooks} - bc := &config.Channel{Enabled: true} - mb := bus.NewMessageBus() - - ch, err := NewSlackWebhookChannel(bc, cfg, mb) - if tt.expectErr != "" { - require.Error(t, err) - assert.Contains(t, err.Error(), tt.expectErr) - } else { - require.NoError(t, err) - assert.NotNil(t, ch) - } - }) - } -} - -func TestSlackWebhookChannel_Send(t *testing.T) { - payloadCh := make(chan map[string]any, 1) - server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - var payload map[string]any - json.Unmarshal(body, &payload) - payloadCh <- payload - w.WriteHeader(http.StatusOK) - })) - defer server.Close() - - cfg := &config.SlackWebhookSettings{ - Webhooks: map[string]config.SlackWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString(server.URL), - Username: "TestBot", - IconEmoji: ":test:", - }, - }, - } - bc := &config.Channel{Enabled: true} - mb := bus.NewMessageBus() - - ch, err := NewSlackWebhookChannel(bc, cfg, mb) - require.NoError(t, err) - - // Use the test server's client to skip TLS verification - ch.client = server.Client() - - err = ch.Start(context.Background()) - require.NoError(t, err) - - _, err = ch.Send(context.Background(), bus.OutboundMessage{ - Content: "Hello **world**", - ChatID: "default", - }) - require.NoError(t, err) - - // Verify payload structure - receivedPayload := <-payloadCh - assert.Equal(t, "TestBot", receivedPayload["username"]) - assert.Equal(t, ":test:", receivedPayload["icon_emoji"]) - blocks, ok := receivedPayload["blocks"].([]any) - require.True(t, ok) - require.Len(t, blocks, 1) -} - -func TestSlackWebhookChannel_FallbackToDefault(t *testing.T) { - var requestCount atomic.Int32 - server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - w.WriteHeader(http.StatusOK) - })) - defer server.Close() - - cfg := &config.SlackWebhookSettings{ - Webhooks: map[string]config.SlackWebhookTarget{ - "default": {WebhookURL: *config.NewSecureString(server.URL)}, - }, - } - bc := &config.Channel{Enabled: true} - mb := bus.NewMessageBus() - - ch, err := NewSlackWebhookChannel(bc, cfg, mb) - require.NoError(t, err) - ch.client = server.Client() - err = ch.Start(context.Background()) - require.NoError(t, err) - - // Send to unknown target - should fall back to default - _, err = ch.Send(context.Background(), bus.OutboundMessage{ - Content: "Test", - ChatID: "unknown_target", - }) - require.NoError(t, err) - assert.Equal(t, int32(1), requestCount.Load()) -} - -func TestSlackWebhookChannel_ErrorClassification(t *testing.T) { - tests := []struct { - name string - statusCode int - expectTemp bool - }{ - {"400 Bad Request", 400, false}, - {"401 Unauthorized", 401, false}, - {"403 Forbidden", 403, false}, - {"404 Not Found", 404, false}, - {"500 Internal Error", 500, true}, - {"502 Bad Gateway", 502, true}, - {"503 Service Unavailable", 503, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - server := httptest.NewTLSServer( - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(tt.statusCode) - }), - ) - defer server.Close() - - cfg := &config.SlackWebhookSettings{ - Webhooks: map[string]config.SlackWebhookTarget{ - "default": {WebhookURL: *config.NewSecureString(server.URL)}, - }, - } - bc := &config.Channel{Enabled: true} - mb := bus.NewMessageBus() - - ch, err := NewSlackWebhookChannel(bc, cfg, mb) - require.NoError(t, err) - ch.client = server.Client() - err = ch.Start(context.Background()) - require.NoError(t, err) - - _, err = ch.Send(context.Background(), bus.OutboundMessage{Content: "Test"}) - require.Error(t, err) - - if tt.expectTemp { - assert.True( - t, - errors.Is(err, channels.ErrTemporary), - "expected temporary error for %d", - tt.statusCode, - ) - } else { - assert.True(t, errors.Is(err, channels.ErrSendFailed), "expected permanent error for %d", tt.statusCode) - } - }) - } -} - -func TestSplitText_ChunkSizeLimit(t *testing.T) { - tests := []struct { - name string - input string - maxLen int - }{ - { - name: "plain text", - input: strings.Repeat("a", 5000), - maxLen: 3000, - }, - { - name: "text with code block", - input: "```\n" + strings.Repeat("x", 5000) + "\n```", - maxLen: 3000, - }, - { - name: "multiple code blocks", - input: "text\n```\n" + strings.Repeat( - "code ", - 800, - ) + "\n```\nmore text\n```\n" + strings.Repeat( - "more ", - 800, - ) + "\n```", - maxLen: 3000, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - chunks := splitText(tt.input, tt.maxLen) - for i, chunk := range chunks { - runeLen := len([]rune(chunk)) - assert.LessOrEqual(t, runeLen, tt.maxLen, - "chunk %d has %d runes, exceeds max %d", i, runeLen, tt.maxLen) - } - }) - } -} - -func TestSplitText_FenceIntegrity(t *testing.T) { - input := "```\n" + strings.Repeat("line of code\n", 300) + "```" - - chunks := splitText(input, 3000) - require.Greater(t, len(chunks), 1, "expected multiple chunks") - - for i, chunk := range chunks { - openCount := strings.Count(chunk, "```") - assert.Equal(t, 0, openCount%2, - "chunk %d has unbalanced fence markers (count=%d)", i, openCount) - } -} - -func TestSplitText_ShortText(t *testing.T) { - input := "short text" - chunks := splitText(input, 3000) - require.Len(t, chunks, 1) - assert.Equal(t, input, chunks[0]) -} diff --git a/pkg/channels/teams_webhook/init.go b/pkg/channels/teams_webhook/init.go deleted file mode 100644 index 6f05b661..00000000 --- a/pkg/channels/teams_webhook/init.go +++ /dev/null @@ -1,32 +0,0 @@ -package teamswebhook - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelTeamsWebHook, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - decoded, err := bc.GetDecoded() - if err != nil { - return nil, err - } - c, ok := decoded.(*config.TeamsWebhookSettings) - if !ok { - return nil, channels.ErrSendFailed - } - ch, err := NewTeamsWebhookChannel(bc, c, b) - if err != nil { - return nil, err - } - if channelName != config.ChannelTeamsWebHook { - ch.SetName(channelName) - } - return ch, nil - }, - ) -} diff --git a/pkg/channels/teams_webhook/teams_webhook.go b/pkg/channels/teams_webhook/teams_webhook.go deleted file mode 100644 index 83756345..00000000 --- a/pkg/channels/teams_webhook/teams_webhook.go +++ /dev/null @@ -1,425 +0,0 @@ -package teamswebhook - -import ( - "context" - "fmt" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - - goteamsnotify "github.com/atc0005/go-teams-notify/v2" - "github.com/atc0005/go-teams-notify/v2/adaptivecard" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -// statusCodeRe extracts HTTP status codes from error messages like "401 Unauthorized". -var statusCodeRe = regexp.MustCompile(`\b([45]\d{2})\b`) - -// markdownTableRe matches a markdown table block (header + separator + rows). -// It captures the entire table including all rows. -var markdownTableRe = regexp.MustCompile(`(?m)^(\|[^\n]+\|)\n(\|[-:\|\s]+\|)\n((?:\|[^\n]+\|\n?)+)`) - -// teamsMessageSender abstracts the Teams client for testability. -type teamsMessageSender interface { - SendWithContext(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error -} - -// classifyTeamsError extracts HTTP status code from error message and classifies it. -// The go-teams-notify library returns errors like "error on notification: 401 Unauthorized, ...". -// This allows proper retry behavior: 4xx errors are permanent, 5xx are temporary. -func classifyTeamsError(err error) error { - if err == nil { - return nil - } - errMsg := err.Error() - if matches := statusCodeRe.FindStringSubmatch(errMsg); len(matches) > 1 { - if statusCode, parseErr := strconv.Atoi(matches[1]); parseErr == nil { - return channels.ClassifySendError(statusCode, err) - } - } - // Fallback: treat as temporary network error (retryable) - return channels.ClassifyNetError(err) -} - -// TeamsWebhookChannel is an output-only channel that sends messages -// to Microsoft Teams via Power Automate workflow webhooks. -// Multiple webhook targets can be configured and selected via ChatID. -type TeamsWebhookChannel struct { - *channels.BaseChannel - bc *config.Channel - config *config.TeamsWebhookSettings - client teamsMessageSender -} - -// NewTeamsWebhookChannel creates a new Teams webhook channel. -func NewTeamsWebhookChannel( - bc *config.Channel, - cfg *config.TeamsWebhookSettings, - bus *bus.MessageBus, -) (*TeamsWebhookChannel, error) { - if len(cfg.Webhooks) == 0 { - return nil, fmt.Errorf("teams_webhook: at least one webhook target is required") - } - - // Require "default" webhook target - if _, hasDefault := cfg.Webhooks["default"]; !hasDefault { - return nil, fmt.Errorf("teams_webhook: a 'default' webhook target is required") - } - - // Validate all webhook targets have valid HTTPS URLs - for name, target := range cfg.Webhooks { - webhookURL := target.WebhookURL.String() - if webhookURL == "" { - return nil, fmt.Errorf("teams_webhook: webhook %q has empty webhook_url", name) - } - parsed, err := url.Parse(webhookURL) - if err != nil { - return nil, fmt.Errorf("teams_webhook: webhook %q has invalid URL: %w", name, err) - } - if !strings.EqualFold(parsed.Scheme, "https") { - return nil, fmt.Errorf("teams_webhook: webhook %q must use HTTPS (got %q)", name, parsed.Scheme) - } - } - - base := channels.NewBaseChannel( - "teams_webhook", - cfg, - bus, - []string{ - "*", - }, // Output-only channel; "*" suppresses misleading "allows EVERYONE" audit warning - channels.WithMaxMessageLength(24000), // Power Automate webhook payload limit is 28KB - ) - - client := goteamsnotify.NewTeamsClient() - - return &TeamsWebhookChannel{ - BaseChannel: base, - bc: bc, - config: cfg, - client: client, - }, nil -} - -// Start initializes the channel. For output-only channels, this is a no-op. -func (c *TeamsWebhookChannel) Start(ctx context.Context) error { - targets := make([]string, 0, len(c.config.Webhooks)) - for name := range c.config.Webhooks { - targets = append(targets, name) - } - sort.Strings(targets) - logger.InfoCF("teams_webhook", "Starting Teams webhook channel (output-only)", map[string]any{ - "targets": targets, - }) - c.SetRunning(true) - return nil -} - -// Stop shuts down the channel. -func (c *TeamsWebhookChannel) Stop(ctx context.Context) error { - logger.InfoC("teams_webhook", "Stopping Teams webhook channel") - c.SetRunning(false) - return nil -} - -// Send delivers a message to the specified Teams webhook target. -// The target is selected by msg.ChatID which must match a key in the webhooks map. -func (c *TeamsWebhookChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - // Look up webhook target by ChatID, fall back to "default" if empty or unknown - targetName := msg.ChatID - if targetName == "" { - targetName = "default" - } - - target, ok := c.config.Webhooks[targetName] - if !ok { - // Log warning and fall back to default target - logger.WarnCF("teams_webhook", "Unknown target, falling back to default", map[string]any{ - "requested": msg.ChatID, - "using": "default", - }) - target = c.config.Webhooks["default"] - } - - // Build an Adaptive Card for rich formatting - card, err := c.buildAdaptiveCard(msg, target) - if err != nil { - return nil, fmt.Errorf("teams_webhook: failed to build card: %w", err) - } - - // Create the message with the card - teamsMsg, err := adaptivecard.NewMessageFromCard(card) - if err != nil { - return nil, fmt.Errorf("teams_webhook: failed to create message: %w", err) - } - - // Send to Teams - if err := c.client.SendWithContext(ctx, target.WebhookURL.String(), teamsMsg); err != nil { - // Log without raw error to avoid leaking webhook URL (embedded in net/http errors) - logger.ErrorCF("teams_webhook", "Failed to send message to Teams webhook", map[string]any{ - "target": msg.ChatID, - }) - // Classify error based on status code extracted from error message. - // The go-teams-notify library includes status in errors like "401 Unauthorized". - // Use ClassifySendError for proper retry behavior (4xx = permanent, 5xx = temporary). - classifiedErr := classifyTeamsError(err) - return nil, fmt.Errorf("teams_webhook: send failed: %w", classifiedErr) - } - - logger.DebugCF("teams_webhook", "Message sent successfully", map[string]any{ - "target": msg.ChatID, - }) - - return nil, nil -} - -// buildAdaptiveCard creates a formatted Adaptive Card from the outbound message. -// It detects markdown tables and converts them to native Adaptive Card Table elements, -// since TextBlocks only support a limited markdown subset (no tables). -func (c *TeamsWebhookChannel) buildAdaptiveCard( - msg bus.OutboundMessage, - target config.TeamsWebhookTarget, -) (adaptivecard.Card, error) { - card := adaptivecard.NewCard() - card.Type = adaptivecard.TypeAdaptiveCard - - // Set full width for Teams rendering - card.MSTeams.Width = "Full" - - // Add title if configured on the target - title := target.Title - if title == "" { - title = "PicoClaw Notification" - } - - titleBlock := adaptivecard.NewTextBlock(title, true) - titleBlock.Size = adaptivecard.SizeLarge - titleBlock.Weight = adaptivecard.WeightBolder - titleBlock.Style = adaptivecard.TextBlockStyleHeading - - if err := card.AddElement(false, titleBlock); err != nil { - return card, err - } - - content := msg.Content - if content == "" { - content = "(empty message)" - } - - // Split content into text segments and tables - // TextBlocks support: bold, italic, bullet/numbered lists, links - // TextBlocks do NOT support: headers, tables, images - segments := splitContentWithTables(content) - - for _, seg := range segments { - if seg.isTable { - // Convert markdown table to Adaptive Card Table element - tableElement, err := parseMarkdownTable(seg.content) - if err != nil { - // Fallback: render as preformatted text if parsing fails - logger.WarnCF("teams_webhook", "Failed to parse markdown table, using fallback", map[string]any{ - "error": err.Error(), - }) - block := adaptivecard.NewTextBlock("```\n"+seg.content+"\n```", true) - block.Wrap = true - if err := card.AddElement(false, block); err != nil { - return card, err - } - continue - } - if err := card.AddElement(false, tableElement); err != nil { - return card, err - } - } else { - // Regular text content - text := strings.TrimSpace(seg.content) - if text == "" { - continue - } - block := adaptivecard.NewTextBlock(text, true) - block.Wrap = true - if err := card.AddElement(false, block); err != nil { - return card, err - } - } - } - - return card, nil -} - -// contentSegment represents either a text block or a table in the message content. -type contentSegment struct { - content string - isTable bool -} - -// splitContentWithTables splits content into alternating text and table segments. -func splitContentWithTables(content string) []contentSegment { - var segments []contentSegment - - matches := markdownTableRe.FindAllStringSubmatchIndex(content, -1) - if len(matches) == 0 { - // No tables found, return entire content as text - return []contentSegment{{content: content, isTable: false}} - } - - lastEnd := 0 - for _, match := range matches { - // Text before this table - if match[0] > lastEnd { - segments = append(segments, contentSegment{ - content: content[lastEnd:match[0]], - isTable: false, - }) - } - // The table itself - segments = append(segments, contentSegment{ - content: content[match[0]:match[1]], - isTable: true, - }) - lastEnd = match[1] - } - - // Text after the last table - if lastEnd < len(content) { - segments = append(segments, contentSegment{ - content: content[lastEnd:], - isTable: false, - }) - } - - return segments -} - -// parseMarkdownTable converts a markdown table string to an Adaptive Card Table element. -func parseMarkdownTable(tableStr string) (adaptivecard.Element, error) { - lines := strings.Split(strings.TrimSpace(tableStr), "\n") - if len(lines) < 2 { - return adaptivecard.Element{}, fmt.Errorf("table must have at least header and separator rows") - } - - // Track header content length per column for width calculation - var headerLengths []int - - // Parse all rows (header + data rows, skip separator) - var allRows [][]adaptivecard.TableCell - for i, line := range lines { - // Skip separator row (contains only |, -, :, and spaces) - if i == 1 && isSeparatorRow(line) { - continue - } - - cells := parseTableRow(line) - if len(cells) == 0 { - continue - } - - var tableCells []adaptivecard.TableCell - for _, cellText := range cells { - trimmedText := strings.TrimSpace(cellText) - - // Use header row (first row) to determine column widths - if i == 0 { - headerLengths = append(headerLengths, len(trimmedText)) - } - - textBlock := adaptivecard.Element{ - Type: adaptivecard.TypeElementTextBlock, - Text: trimmedText, - Wrap: true, - } - cell := adaptivecard.TableCell{ - Type: adaptivecard.TypeTableCell, - Items: []*adaptivecard.Element{&textBlock}, - } - tableCells = append(tableCells, cell) - } - allRows = append(allRows, tableCells) - } - - if len(allRows) == 0 { - return adaptivecard.Element{}, fmt.Errorf("no valid rows found in table") - } - - // Create table with first row as headers - firstRowAsHeaders := true - showGridLines := true - - table, err := adaptivecard.NewTableFromTableCells(allRows, 0, firstRowAsHeaders, showGridLines) - if err != nil { - return adaptivecard.Element{}, fmt.Errorf("failed to create table: %w", err) - } - - // Set column widths based on header content length - table.Columns = calculateColumnWidths(headerLengths) - - return table, nil -} - -// calculateColumnWidths creates TableColumnDefinition entries with widths -// proportional to the max content length of each column. -func calculateColumnWidths(maxLengths []int) []adaptivecard.Column { - if len(maxLengths) == 0 { - return nil - } - - // Use content length as relative weight, with a minimum of 1 - columns := make([]adaptivecard.Column, len(maxLengths)) - for i, length := range maxLengths { - weight := length - if weight < 1 { - weight = 1 - } - columns[i] = adaptivecard.Column{ - Type: "TableColumnDefinition", - Width: weight, - } - } - - return columns -} - -// isSeparatorRow checks if a line is a markdown table separator (e.g., |---|---|). -func isSeparatorRow(line string) bool { - // Remove pipes and spaces, check if only dashes and colons remain - cleaned := strings.ReplaceAll(line, "|", "") - cleaned = strings.ReplaceAll(cleaned, " ", "") - cleaned = strings.ReplaceAll(cleaned, "-", "") - cleaned = strings.ReplaceAll(cleaned, ":", "") - return cleaned == "" -} - -// parseTableRow extracts cell values from a markdown table row. -func parseTableRow(line string) []string { - // Trim leading/trailing pipes and split by | - line = strings.TrimSpace(line) - line = strings.TrimPrefix(line, "|") - line = strings.TrimSuffix(line, "|") - - if line == "" { - return nil - } - - parts := strings.Split(line, "|") - var cells []string - for _, p := range parts { - cells = append(cells, strings.TrimSpace(p)) - } - return cells -} diff --git a/pkg/channels/teams_webhook/teams_webhook_test.go b/pkg/channels/teams_webhook/teams_webhook_test.go deleted file mode 100644 index cc157003..00000000 --- a/pkg/channels/teams_webhook/teams_webhook_test.go +++ /dev/null @@ -1,582 +0,0 @@ -package teamswebhook - -import ( - "context" - "errors" - "testing" - - goteamsnotify "github.com/atc0005/go-teams-notify/v2" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/config" -) - -// mockTeamsClient implements teamsMessageSender for testing. -type mockTeamsClient struct { - sendFunc func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error -} - -func (m *mockTeamsClient) SendWithContext( - ctx context.Context, - webhookURL string, - message goteamsnotify.TeamsMessage, -) error { - if m.sendFunc != nil { - return m.sendFunc(ctx, webhookURL, message) - } - return nil -} - -func TestNewTeamsWebhookChannel(t *testing.T) { - msgBus := bus.NewMessageBus() - - // Test missing webhooks - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: nil, - } - _, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err == nil { - t.Error("expected error for missing webhooks") - } - - // Test missing "default" webhook - cfg.Webhooks = map[string]config.TeamsWebhookTarget{ - "alerts": { - WebhookURL: *config.NewSecureString("https://example.com/webhook"), - Title: "Alerts", - }, - } - _, err = NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err == nil { - t.Error("expected error for missing 'default' webhook") - } - - // Test empty webhook URL - cfg.Webhooks = map[string]config.TeamsWebhookTarget{ - "default": {Title: "Default"}, - } - _, err = NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err == nil { - t.Error("expected error for empty webhook_url") - } - - // Test HTTP URL (should fail, must be HTTPS) - cfg.Webhooks = map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("http://example.com/webhook"), - Title: "Default", - }, - } - _, err = NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err == nil { - t.Error("expected error for HTTP webhook URL (must be HTTPS)") - } - - // Test valid config with HTTPS (must include "default") - cfg.Webhooks = map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-default"), - Title: "Default", - }, - "alerts": { - WebhookURL: *config.NewSecureString("https://example.com/webhook1"), - Title: "Alerts", - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if ch.Name() != "teams_webhook" { - t.Errorf("expected name 'teams_webhook', got %q", ch.Name()) - } -} - -func TestTeamsWebhookChannel_StartStop(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook"), - }, - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - ctx := context.Background() - - if ch.IsRunning() { - t.Error("channel should not be running before Start") - } - - if err := ch.Start(ctx); err != nil { - t.Fatalf("Start failed: %v", err) - } - - if !ch.IsRunning() { - t.Error("channel should be running after Start") - } - - if err := ch.Stop(ctx); err != nil { - t.Fatalf("Stop failed: %v", err) - } - - if ch.IsRunning() { - t.Error("channel should not be running after Stop") - } -} - -func TestTeamsWebhookChannel_BuildAdaptiveCard(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-default"), - Title: "Default", - }, - "alerts": { - WebhookURL: *config.NewSecureString("https://example.com/webhook"), - Title: "Custom Title", - }, - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - target := ch.config.Webhooks["alerts"] - msg := bus.OutboundMessage{ - Content: "Test message content", - ChatID: "alerts", - } - - card, err := ch.buildAdaptiveCard(msg, target) - if err != nil { - t.Fatalf("buildAdaptiveCard failed: %v", err) - } - - if card.Type != "AdaptiveCard" { - t.Errorf("expected card type 'AdaptiveCard', got %q", card.Type) - } -} - -func TestTeamsWebhookChannel_SendNotRunning(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook"), - }, - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - ctx := context.Background() - msg := bus.OutboundMessage{Content: "test", ChatID: "default"} - - _, err = ch.Send(ctx, msg) - if err == nil { - t.Error("expected error when sending while not running") - } -} - -func TestTeamsWebhookChannel_SendDefaultTargetFallback(t *testing.T) { - tests := []struct { - name string - chatID string - }{ - {"unknown target falls back to default", "unknown"}, - {"empty ChatID uses default", ""}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-default"), - }, - "alerts": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-alerts"), - }, - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - var sentURL string - ch.client = &mockTeamsClient{ - sendFunc: func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error { - sentURL = webhookURL - return nil - }, - } - - ctx := context.Background() - _ = ch.Start(ctx) - defer ch.Stop(ctx) - - msg := bus.OutboundMessage{Content: "test", ChatID: tt.chatID} - _, err = ch.Send(ctx, msg) - if err != nil { - t.Fatalf("expected success, got error: %v", err) - } - - if sentURL != "https://example.com/webhook-default" { - t.Errorf("expected default webhook URL, got %q", sentURL) - } - }) - } -} - -func TestTeamsWebhookChannel_SendSuccess(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-default"), - Title: "Default", - }, - "alerts": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-alerts"), - Title: "Test Alerts", - }, - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // Inject mock client - var sentURL string - ch.client = &mockTeamsClient{ - sendFunc: func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error { - sentURL = webhookURL - return nil - }, - } - - ctx := context.Background() - _ = ch.Start(ctx) - defer ch.Stop(ctx) - - msg := bus.OutboundMessage{Content: "Hello Teams!", ChatID: "alerts"} - - _, err = ch.Send(ctx, msg) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if sentURL != "https://example.com/webhook-alerts" { - t.Errorf("expected webhook URL 'https://example.com/webhook-alerts', got %q", sentURL) - } -} - -func TestTeamsWebhookChannel_SendError(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true} - cfg := config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-default"), - }, - "alerts": { - WebhookURL: *config.NewSecureString("https://example.com/webhook-alerts"), - }, - }, - } - ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // Inject mock client that returns an error - ch.client = &mockTeamsClient{ - sendFunc: func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error { - return errors.New("error on notification: 401 Unauthorized, forbidden") - }, - } - - ctx := context.Background() - _ = ch.Start(ctx) - defer ch.Stop(ctx) - - msg := bus.OutboundMessage{Content: "test", ChatID: "alerts"} - - _, err = ch.Send(ctx, msg) - if err == nil { - t.Error("expected error from failed send") - } -} - -func TestSplitContentWithTables(t *testing.T) { - tests := []struct { - name string - content string - wantSegs int - wantTbl int // number of table segments - }{ - { - name: "no tables", - content: "Just some text\nwith multiple lines", - wantSegs: 1, - wantTbl: 0, - }, - { - name: "single table", - content: `| Col1 | Col2 | -|------|------| -| A | B | -| C | D |`, - wantSegs: 1, - wantTbl: 1, - }, - { - name: "text before table", - content: `Here is some text. - -| Col1 | Col2 | -|------|------| -| A | B |`, - wantSegs: 2, - wantTbl: 1, - }, - { - name: "text before and after table", - content: `Before table. - -| Col1 | Col2 | -|------|------| -| A | B | - -After table.`, - wantSegs: 3, - wantTbl: 1, - }, - { - name: "multiple tables", - content: `First table: - -| A | B | -|---|---| -| 1 | 2 | - -Second table: - -| X | Y | -|---|---| -| 3 | 4 |`, - wantSegs: 4, - wantTbl: 2, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - segs := splitContentWithTables(tt.content) - if len(segs) != tt.wantSegs { - t.Errorf("got %d segments, want %d", len(segs), tt.wantSegs) - } - tableCount := 0 - for _, s := range segs { - if s.isTable { - tableCount++ - } - } - if tableCount != tt.wantTbl { - t.Errorf("got %d tables, want %d", tableCount, tt.wantTbl) - } - }) - } -} - -func TestParseMarkdownTable(t *testing.T) { - tableStr := `| Name | Value | -|------|-------| -| foo | 123 | -| bar | 456 |` - - elem, err := parseMarkdownTable(tableStr) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if elem.Type != "Table" { - t.Errorf("expected type 'Table', got %q", elem.Type) - } - - // Should have 3 rows (header + 2 data rows) - if len(elem.Rows) != 3 { - t.Errorf("expected 3 rows, got %d", len(elem.Rows)) - } - - // Should have 2 columns with widths based on content length - if len(elem.Columns) != 2 { - t.Errorf("expected 2 columns, got %d", len(elem.Columns)) - } -} - -func TestParseMarkdownTableColumnWidths(t *testing.T) { - // Column widths are based on HEADER row only: - // Col1: "Description" (11 chars) - // Col2: "X" (1 char) - // Col3: "Amount" (6 chars) - tableStr := `| Description | X | Amount | -|-------------|---|--------| -| Short | Y | 100 | -| Longer text | Z | 50 |` - - elem, err := parseMarkdownTable(tableStr) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if len(elem.Columns) != 3 { - t.Fatalf("expected 3 columns, got %d", len(elem.Columns)) - } - - // Verify column widths are based on header content length - w1, ok1 := elem.Columns[0].Width.(int) - w2, ok2 := elem.Columns[1].Width.(int) - w3, ok3 := elem.Columns[2].Width.(int) - - if !ok1 || !ok2 || !ok3 { - t.Fatalf("expected int widths, got types: %T, %T, %T", - elem.Columns[0].Width, elem.Columns[1].Width, elem.Columns[2].Width) - } - - // Header lengths: "Description" = 11, "X" = 1, "Amount" = 6 - if w1 != 11 { - t.Errorf("expected col1 width 11 (from 'Description'), got %d", w1) - } - if w2 != 1 { - t.Errorf("expected col2 width 1 (from 'X'), got %d", w2) - } - if w3 != 6 { - t.Errorf("expected col3 width 6 (from 'Amount'), got %d", w3) - } -} - -func TestCalculateColumnWidths(t *testing.T) { - tests := []struct { - name string - maxLengths []int - wantWidths []int - }{ - { - name: "equal lengths", - maxLengths: []int{10, 10, 10}, - wantWidths: []int{10, 10, 10}, - }, - { - name: "varying lengths", - maxLengths: []int{5, 20, 10}, - wantWidths: []int{5, 20, 10}, - }, - { - name: "zero length gets minimum of 1", - maxLengths: []int{0, 5, 0}, - wantWidths: []int{1, 5, 1}, - }, - { - name: "empty input", - maxLengths: []int{}, - wantWidths: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cols := calculateColumnWidths(tt.maxLengths) - - if tt.wantWidths == nil { - if cols != nil { - t.Errorf("expected nil, got %v", cols) - } - return - } - - if len(cols) != len(tt.wantWidths) { - t.Fatalf("expected %d columns, got %d", len(tt.wantWidths), len(cols)) - } - - for i, col := range cols { - width, ok := col.Width.(int) - if !ok { - t.Errorf("column %d: expected int width, got %T", i, col.Width) - continue - } - if width != tt.wantWidths[i] { - t.Errorf("column %d: expected width %d, got %d", i, tt.wantWidths[i], width) - } - if col.Type != "TableColumnDefinition" { - t.Errorf("column %d: expected type 'TableColumnDefinition', got %q", i, col.Type) - } - } - }) - } -} - -func TestParseTableRow(t *testing.T) { - tests := []struct { - line string - want []string - }{ - {"| A | B | C |", []string{"A", "B", "C"}}, - {"|A|B|C|", []string{"A", "B", "C"}}, - {"| foo | bar |", []string{"foo", "bar"}}, - {"", nil}, - } - - for _, tt := range tests { - got := parseTableRow(tt.line) - if len(got) != len(tt.want) { - t.Errorf("parseTableRow(%q): got %v, want %v", tt.line, got, tt.want) - continue - } - for i := range got { - if got[i] != tt.want[i] { - t.Errorf("parseTableRow(%q)[%d]: got %q, want %q", tt.line, i, got[i], tt.want[i]) - } - } - } -} - -func TestIsSeparatorRow(t *testing.T) { - tests := []struct { - line string - want bool - }{ - {"|---|---|", true}, - {"| --- | --- |", true}, - {"|:---|---:|", true}, - {"| :---: | :---: |", true}, - {"| A | B |", false}, - {"| foo | bar |", false}, - } - - for _, tt := range tests { - got := isSeparatorRow(tt.line) - if got != tt.want { - t.Errorf("isSeparatorRow(%q): got %v, want %v", tt.line, got, tt.want) - } - } -} diff --git a/pkg/channels/vk/init.go b/pkg/channels/vk/init.go deleted file mode 100644 index deca297d..00000000 --- a/pkg/channels/vk/init.go +++ /dev/null @@ -1,20 +0,0 @@ -package vk - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelVK, - func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) { - bc := cfg.Channels[channelName] - if bc == nil { - return nil, channels.ErrSendFailed - } - return NewVKChannel(channelName, bc, b) - }, - ) -} diff --git a/pkg/channels/vk/vk.go b/pkg/channels/vk/vk.go deleted file mode 100644 index b27431ba..00000000 --- a/pkg/channels/vk/vk.go +++ /dev/null @@ -1,295 +0,0 @@ -package vk - -import ( - "context" - "fmt" - "strconv" - "strings" - - "github.com/SevereCloud/vksdk/v3/api" - "github.com/SevereCloud/vksdk/v3/api/params" - "github.com/SevereCloud/vksdk/v3/events" - "github.com/SevereCloud/vksdk/v3/longpoll-bot" - "github.com/SevereCloud/vksdk/v3/object" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/identity" - "github.com/sipeed/picoclaw/pkg/logger" -) - -type VKChannel struct { - *channels.BaseChannel - vk *api.VK - lp *longpoll.LongPoll - channelName string - bc *config.Channel - ctx context.Context - cancel context.CancelFunc -} - -func NewVKChannel(channelName string, bc *config.Channel, bus *bus.MessageBus) (*VKChannel, error) { - var vkCfg config.VKSettings - if err := bc.Decode(&vkCfg); err != nil { - return nil, err - } - - vk := api.NewVK(vkCfg.Token.String()) - - base := channels.NewBaseChannel( - channelName, - &vkCfg, - bus, - bc.AllowFrom, - channels.WithMaxMessageLength(4000), - channels.WithGroupTrigger(bc.GroupTrigger), - channels.WithReasoningChannelID(bc.ReasoningChannelID), - ) - - return &VKChannel{ - BaseChannel: base, - vk: vk, - channelName: channelName, - bc: bc, - }, nil -} - -func (c *VKChannel) getVKCfg() *config.VKSettings { - var v config.VKSettings - if err := c.bc.Decode(&v); err != nil { - return nil - } - return &v -} - -func (c *VKChannel) Start(ctx context.Context) error { - logger.InfoC("vk", "Starting VK bot (Long Poll mode)...") - - c.ctx, c.cancel = context.WithCancel(ctx) - - groupID := c.getVKCfg().GroupID - if groupID == 0 { - c.cancel() - return fmt.Errorf("group_id is required for VK bot") - } - - lp, err := longpoll.NewLongPoll(c.vk, groupID) - if err != nil { - c.cancel() - return fmt.Errorf("failed to create long poll: %w", err) - } - c.lp = lp - - lp.MessageNew(func(_ context.Context, obj events.MessageNewObject) { - c.handleMessage(obj.Message) - }) - - c.SetRunning(true) - - logger.InfoCF("vk", "VK bot connected", map[string]any{ - "group_id": groupID, - }) - - go func() { - if err := lp.Run(); err != nil { - logger.ErrorCF("vk", "Long poll failed", map[string]any{ - "error": err.Error(), - }) - } - }() - - return nil -} - -func (c *VKChannel) Stop(ctx context.Context) error { - logger.InfoC("vk", "Stopping VK bot...") - c.SetRunning(false) - - if c.lp != nil { - c.lp.Shutdown() - } - - if c.cancel != nil { - c.cancel() - } - - return nil -} - -func (c *VKChannel) handleMessage(msg object.MessagesMessage) { - if msg.Action.Type != "" { - return - } - - if bool(msg.Out) { - return - } - - peerID := msg.PeerID - chatID := strconv.Itoa(peerID) - - fromID := msg.FromID - userID := strconv.Itoa(fromID) - - platformID := userID - sender := bus.SenderInfo{ - Platform: "vk", - PlatformID: platformID, - CanonicalID: identity.BuildCanonicalID("vk", platformID), - DisplayName: c.getUserName(fromID), - } - - if !c.IsAllowedSender(sender) { - logger.DebugCF("vk", "Message from unauthorized user", map[string]any{ - "peer_id": peerID, - }) - return - } - - text := msg.Text - if text == "" && len(msg.Attachments) > 0 { - text = c.processAttachments(msg.Attachments) - } - - if text == "" { - return - } - - groupTrigger := c.bc.GroupTrigger - isGroupChat := peerID != fromID - - if isGroupChat { - isMentioned := c.isMentioned(msg) - if isMentioned { - text = c.stripBotMention(text) - } - respond, cleaned := c.ShouldRespondInGroup(isMentioned, text) - if !respond { - return - } - text = cleaned - _ = groupTrigger - } - - chatType := "direct" - if isGroupChat { - chatType = "group" - } - - messageID := strconv.Itoa(msg.ConversationMessageID) - - metadata := map[string]string{ - "user_id": userID, - "is_group": fmt.Sprintf("%t", isGroupChat), - } - - c.HandleInboundContext(c.ctx, chatID, text, nil, bus.InboundContext{ - Channel: "vk", - ChatID: chatID, - ChatType: chatType, - SenderID: userID, - MessageID: messageID, - Mentioned: isGroupChat && c.isMentioned(msg), - Raw: metadata, - }, sender) -} - -func (c *VKChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - peerID, err := strconv.Atoi(msg.ChatID) - if err != nil { - return nil, fmt.Errorf("invalid chat ID %s: %w", msg.ChatID, channels.ErrSendFailed) - } - - if msg.Content == "" { - return nil, nil - } - - var messageIDs []string - chunks := channels.SplitMessage(msg.Content, 4000) - - for _, chunk := range chunks { - if chunk == "" { - continue - } - - b := params.NewMessagesSendBuilder() - b.Message(chunk) - b.RandomID(0) - b.PeerID(peerID) - - if msg.ReplyToMessageID != "" { - if replyID, err := strconv.Atoi(msg.ReplyToMessageID); err == nil { - b.ReplyTo(replyID) - } - } - - resp, err := c.vk.MessagesSend(b.Params) - if err != nil { - logger.ErrorCF("vk", "Failed to send message", map[string]any{ - "error": err.Error(), - "peer_id": peerID, - }) - return messageIDs, fmt.Errorf("failed to send message: %w", err) - } - - messageIDs = append(messageIDs, strconv.Itoa(resp)) - } - - return messageIDs, nil -} - -func (c *VKChannel) isMentioned(msg object.MessagesMessage) bool { - return false -} - -func (c *VKChannel) stripBotMention(text string) string { - return strings.TrimSpace(text) -} - -func (c *VKChannel) getUserName(userID int) string { - users, err := c.vk.UsersGet(api.Params{ - "user_ids": userID, - }) - if err != nil || len(users) == 0 { - return strconv.Itoa(userID) - } - - user := users[0] - return fmt.Sprintf("%s %s", user.FirstName, user.LastName) -} - -func (c *VKChannel) processAttachments(attachments []object.MessagesMessageAttachment) string { - var parts []string - - for _, att := range attachments { - switch att.Type { - case "photo": - parts = append(parts, "[photo]") - case "video": - parts = append(parts, "[video]") - case "audio": - parts = append(parts, "[audio]") - case "doc": - if att.Doc.Title != "" { - parts = append(parts, fmt.Sprintf("[document: %s]", att.Doc.Title)) - } else { - parts = append(parts, "[document]") - } - case "audio_message": - parts = append(parts, "[voice]") - case "sticker": - parts = append(parts, "[sticker]") - } - } - - return strings.Join(parts, " ") -} - -func (c *VKChannel) VoiceCapabilities() channels.VoiceCapabilities { - return channels.VoiceCapabilities{ASR: true, TTS: true} -} diff --git a/pkg/channels/vk/vk_test.go b/pkg/channels/vk/vk_test.go deleted file mode 100644 index 9583cbf4..00000000 --- a/pkg/channels/vk/vk_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package vk - -import ( - "encoding/json" - "testing" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func makeVKTestBaseChannel(vkCfg config.VKSettings) *config.Channel { - settings, _ := json.Marshal(vkCfg) - return &config.Channel{ - Enabled: true, - Type: config.ChannelVK, - Settings: settings, - } -} - -func TestNewVKChannel(t *testing.T) { - msgBus := bus.NewMessageBus() - - t.Run("missing group_id", func(t *testing.T) { - bc := makeVKTestBaseChannel(config.VKSettings{ - Token: *config.NewSecureString("test_token"), - }) - ch, err := NewVKChannel("vk", bc, msgBus) - if err != nil { - t.Fatalf("unexpected error during creation: %v", err) - } - if ch.Name() != "vk" { - t.Errorf("Name() = %q, want %q", ch.Name(), "vk") - } - if ch.IsRunning() { - t.Error("new channel should not be running") - } - }) - - t.Run("valid config with group_id", func(t *testing.T) { - bc := makeVKTestBaseChannel(config.VKSettings{ - Token: *config.NewSecureString("test_token"), - GroupID: 123456789, - }) - ch, err := NewVKChannel("vk", bc, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ch.Name() != "vk" { - t.Errorf("Name() = %q, want %q", ch.Name(), "vk") - } - if ch.IsRunning() { - t.Error("new channel should not be running") - } - }) - - t.Run("with allow_from", func(t *testing.T) { - vkCfg := config.VKSettings{ - Token: *config.NewSecureString("test_token"), - GroupID: 123456789, - } - settings, _ := json.Marshal(vkCfg) - bc := &config.Channel{ - Enabled: true, - Type: "vk", - AllowFrom: []string{"123456789"}, - Settings: settings, - } - ch, err := NewVKChannel("vk", bc, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !ch.IsAllowedSender(bus.SenderInfo{PlatformID: "123456789"}) { - t.Error("user 123456789 should be allowed") - } - if ch.IsAllowedSender(bus.SenderInfo{PlatformID: "999999999"}) { - t.Error("user 999999999 should not be allowed") - } - }) - - t.Run("with group_trigger", func(t *testing.T) { - vkCfg := config.VKSettings{ - Token: *config.NewSecureString("test_token"), - GroupID: 123456789, - } - settings, _ := json.Marshal(vkCfg) - bc := &config.Channel{ - Enabled: true, - Type: "vk", - GroupTrigger: config.GroupTriggerConfig{ - MentionOnly: false, - Prefixes: []string{"/bot", "!bot"}, - }, - Settings: settings, - } - ch, err := NewVKChannel("vk", bc, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ch.Name() != "vk" { - t.Errorf("Name() = %q, want %q", ch.Name(), "vk") - } - }) -} - -func TestVKChannel_MaxMessageLength(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := makeVKTestBaseChannel(config.VKSettings{ - Token: *config.NewSecureString("test_token"), - GroupID: 123456789, - }) - ch, err := NewVKChannel("vk", bc, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - maxLen := ch.MaxMessageLength() - if maxLen != 4000 { - t.Errorf("MaxMessageLength() = %d, want 4000", maxLen) - } -} - -func TestVKChannel_SplitMessage(t *testing.T) { - tests := []struct { - name string - content string - maxLen int - want int - }{ - { - name: "short message", - content: "hello", - maxLen: 4000, - want: 1, - }, - { - name: "exact length", - content: string(make([]byte, 4000)), - maxLen: 4000, - want: 1, - }, - { - name: "needs split", - content: string(make([]byte, 5000)), - maxLen: 4000, - want: 2, - }, - { - name: "empty message", - content: "", - maxLen: 4000, - want: 0, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := channels.SplitMessage(tt.content, tt.maxLen) - if len(got) != tt.want { - t.Errorf("SplitMessage() got %d parts, want %d parts", len(got), tt.want) - } - }) - } -} - -func TestVKChannel_ProcessAttachments(t *testing.T) { - tests := []struct { - name string - attachments []string - want string - }{ - { - name: "empty attachments", - attachments: []string{}, - want: "", - }, - { - name: "photo attachment", - attachments: []string{"photo"}, - want: "[photo]", - }, - { - name: "video attachment", - attachments: []string{"video"}, - want: "[video]", - }, - { - name: "audio attachment", - attachments: []string{"audio"}, - want: "[audio]", - }, - { - name: "document attachment", - attachments: []string{"doc"}, - want: "[doc]", - }, - { - name: "sticker attachment", - attachments: []string{"sticker"}, - want: "[sticker]", - }, - { - name: "audio_message attachment", - attachments: []string{"audio_message"}, - want: "[voice]", - }, - { - name: "multiple attachments", - attachments: []string{"photo", "video", "audio"}, - want: "[photo] [video] [audio]", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var result string - for i, att := range tt.attachments { - if i > 0 { - result += " " - } - if att == "audio_message" { - result += "[voice]" - } else { - result += "[" + att + "]" - } - } - if result != tt.want { - t.Errorf("processAttachments() = %q, want %q", result, tt.want) - } - }) - } -} - -func TestVKChannel_VoiceCapabilities(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := makeVKTestBaseChannel(config.VKSettings{ - Token: *config.NewSecureString("test_token"), - GroupID: 123456789, - }) - ch, err := NewVKChannel("vk", bc, msgBus) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - caps := ch.VoiceCapabilities() - if !caps.ASR { - t.Error("VoiceCapabilities().ASR should be true") - } - if !caps.TTS { - t.Error("VoiceCapabilities().TTS should be true") - } -} diff --git a/pkg/channels/voice_capabilities.go b/pkg/channels/voice_capabilities.go index 34fd2426..9ce398cd 100644 --- a/pkg/channels/voice_capabilities.go +++ b/pkg/channels/voice_capabilities.go @@ -18,7 +18,6 @@ type VoiceCapabilityProvider interface { var asrCapableChannels = map[string]bool{ "discord": true, "telegram": true, - "matrix": true, "qq": true, "weixin": true, "line": true, diff --git a/pkg/commands/builtin_test.go b/pkg/commands/builtin_test.go index bb9abe36..eb8236ad 100644 --- a/pkg/commands/builtin_test.go +++ b/pkg/commands/builtin_test.go @@ -133,7 +133,7 @@ func TestBuiltinShowChannel_PreservesUserVisibleBehavior(t *testing.T) { func TestBuiltinListChannels_UsesGetEnabledChannels(t *testing.T) { rt := &Runtime{ GetEnabledChannels: func() []string { - return []string{"telegram", "slack"} + return []string{"telegram", "discord"} }, } defs := BuiltinDefinitions() @@ -150,8 +150,8 @@ func TestBuiltinListChannels_UsesGetEnabledChannels(t *testing.T) { if res.Outcome != OutcomeHandled { t.Fatalf("/list channels: outcome=%v, want=%v", res.Outcome, OutcomeHandled) } - if !strings.Contains(reply, "telegram") || !strings.Contains(reply, "slack") { - t.Fatalf("/list channels reply=%q, want telegram and slack", reply) + if !strings.Contains(reply, "telegram") || !strings.Contains(reply, "discord") { + t.Fatalf("/list channels reply=%q, want telegram and discord", reply) } } diff --git a/pkg/config/config.go b/pkg/config/config.go index c409705a..9027f1f7 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -574,47 +574,6 @@ type DingTalkSettings struct { ClientSecret SecureString `json:"client_secret,omitzero" yaml:"client_secret,omitempty" env:"PICOCLAW_CHANNELS_DINGTALK_CLIENT_SECRET"` } -type SlackSettings struct { - BotToken SecureString `json:"bot_token,omitzero" yaml:"bot_token,omitempty" env:"PICOCLAW_CHANNELS_SLACK_BOT_TOKEN"` - AppToken SecureString `json:"app_token,omitzero" yaml:"app_token,omitempty" env:"PICOCLAW_CHANNELS_SLACK_APP_TOKEN"` -} - -type MatrixSettings struct { - Homeserver string `json:"homeserver" yaml:"-" env:"PICOCLAW_CHANNELS_MATRIX_HOMESERVER"` - UserID string `json:"user_id" yaml:"-" env:"PICOCLAW_CHANNELS_MATRIX_USER_ID"` - AccessToken SecureString `json:"access_token,omitzero" yaml:"access_token,omitempty" env:"PICOCLAW_CHANNELS_MATRIX_ACCESS_TOKEN"` - DeviceID string `json:"device_id,omitempty" yaml:"-"` - JoinOnInvite bool `json:"join_on_invite" yaml:"-"` - MessageFormat string `json:"message_format,omitempty" yaml:"-"` - CryptoDatabasePath string `json:"crypto_database_path,omitempty" yaml:"-"` - CryptoPassphrase string `json:"crypto_passphrase,omitempty" yaml:"-"` -} - -// DeltaChatSettings configures the Delta Chat channel. Delta Chat is an -// email-based, end-to-end encrypted messenger; PicoClaw talks to a local -// `deltachat-rpc-server` process over JSON-RPC (stdio). -// -// Email is the only required setting. A full address selects an already -// configured account in DataDir; a first-run marker such as "@nine.testrun.org" -// creates a chatmail account and tells the user which full email to save. -// Mailbox credentials stay in the Delta Chat account store. DisplayName and -// AvatarImage are optional profile settings applied on startup. Password remains -// only for legacy PicoClaw-managed email configuration. -type DeltaChatSettings struct { - Email string `json:"email" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_EMAIL"` - Password SecureString `json:"password,omitzero" yaml:"password,omitempty" env:"PICOCLAW_CHANNELS_DELTACHAT_PASSWORD"` - DisplayName string `json:"display_name,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_DISPLAY_NAME"` - AvatarImage string `json:"avatar_image,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_AVATAR_IMAGE"` - DataDir string `json:"data_dir,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_DATA_DIR"` - RPCServerPath string `json:"rpc_server_path,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_RPC_SERVER_PATH"` - InviteLink string `json:"invite_link,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_INVITE_LINK"` - AllowCrosspost bool `json:"allow_crosspost,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_ALLOW_CROSSPOST"` - IMAPServer string `json:"imap_server,omitempty" yaml:"-"` - IMAPPort int `json:"imap_port,omitempty" yaml:"-"` - SMTPServer string `json:"smtp_server,omitempty" yaml:"-"` - SMTPPort int `json:"smtp_port,omitempty" yaml:"-"` -} - type LINESettings struct { ChannelSecret SecureString `json:"channel_secret,omitzero" yaml:"channel_secret,omitempty" env:"PICOCLAW_CHANNELS_LINE_CHANNEL_SECRET"` ChannelAccessToken SecureString `json:"channel_access_token,omitzero" yaml:"channel_access_token,omitempty" env:"PICOCLAW_CHANNELS_LINE_CHANNEL_ACCESS_TOKEN"` @@ -659,41 +618,6 @@ func (c *WeixinSettings) SetToken(token string) { c.Token = *NewSecureString(token) } -type IRCSettings struct { - Server string `json:"server" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_SERVER"` - TLS bool `json:"tls" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_TLS"` - Nick string `json:"nick" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_NICK"` - User string `json:"user,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_USER"` - RealName string `json:"real_name,omitempty" yaml:"-"` - Password SecureString `json:"password,omitzero" yaml:"password,omitempty" env:"PICOCLAW_CHANNELS_IRC_PASSWORD"` - NickServPassword SecureString `json:"nickserv_password,omitzero" yaml:"nickserv_password,omitempty" env:"PICOCLAW_CHANNELS_IRC_NICKSERV_PASSWORD"` - SASLUser string `json:"sasl_user" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_SASL_USER"` - SASLPassword SecureString `json:"sasl_password,omitzero" yaml:"sasl_password,omitempty" env:"PICOCLAW_CHANNELS_IRC_SASL_PASSWORD"` - Channels FlexibleStringSlice `json:"channels" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_CHANNELS"` - RequestCaps FlexibleStringSlice `json:"request_caps,omitempty" yaml:"-"` -} - -type VKSettings struct { - Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"PICOCLAW_CHANNELS_VK_TOKEN"` - GroupID int `json:"group_id" yaml:"-" env:"PICOCLAW_CHANNELS_VK_GROUP_ID"` -} - -func (c *VKSettings) SetToken(token string) { - c.Token = *NewSecureString(token) -} - -// TeamsWebhookSettings configures the output-only Microsoft Teams webhook channel. -// Multiple webhook targets can be configured and selected via ChatID at send time. -type TeamsWebhookSettings struct { - Webhooks map[string]TeamsWebhookTarget `json:"webhooks" yaml:"webhooks,omitempty"` -} - -// TeamsWebhookTarget represents a single Teams webhook destination. -type TeamsWebhookTarget struct { - WebhookURL SecureString `json:"webhook_url,omitzero" yaml:"webhook_url,omitempty"` - Title string `json:"title,omitempty" yaml:"-"` -} - type MQTTSettings struct { Broker string `json:"broker" yaml:"-" env:"PICOCLAW_CHANNELS_MQTT_BROKER"` AgentID string `json:"agent_id" yaml:"-" env:"PICOCLAW_CHANNELS_MQTT_AGENT_ID"` @@ -705,18 +629,6 @@ type MQTTSettings struct { QoS int `json:"qos,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_MQTT_QOS"` } -// SlackWebhookSettings configures the output-only Slack webhook channel. -type SlackWebhookSettings struct { - Webhooks map[string]SlackWebhookTarget `json:"webhooks" yaml:"webhooks,omitempty"` -} - -// SlackWebhookTarget represents a single Slack Incoming Webhook destination. -type SlackWebhookTarget struct { - WebhookURL SecureString `json:"webhook_url,omitzero" yaml:"webhook_url,omitempty"` - Username string `json:"username,omitempty" yaml:"-"` - IconEmoji string `json:"icon_emoji,omitempty" yaml:"-"` -} - type HeartbeatConfig struct { Enabled bool `json:"enabled" env:"PICOCLAW_HEARTBEAT_ENABLED"` Interval int `json:"interval" env:"PICOCLAW_HEARTBEAT_INTERVAL"` // minutes, min 5 diff --git a/pkg/config/config_channel.go b/pkg/config/config_channel.go index 7dc5c46a..578e558d 100644 --- a/pkg/config/config_channel.go +++ b/pkg/config/config_channel.go @@ -23,19 +23,12 @@ const ( ChannelWeixin = "weixin" ChannelWeCom = "wecom" ChannelDingTalk = "dingtalk" - ChannelSlack = "slack" - ChannelMatrix = "matrix" - ChannelDeltaChat = "deltachat" ChannelLINE = "line" ChannelOneBot = "onebot" ChannelQQ = "qq" - ChannelIRC = "irc" - ChannelVK = "vk" ChannelWhatsApp = "whatsapp" ChannelWhatsAppNative = "whatsapp_native" - ChannelTeamsWebHook = "teams_webhook" ChannelMQTT = "mqtt" - ChannelSlackWebHook = "slack_webhook" ) // RawNode stores raw configuration data as JSON bytes, supporting both JSON and YAML. @@ -611,19 +604,12 @@ var channelSettingsFactory = map[string]any{ ChannelWeixin: (WeixinSettings{}), ChannelWeCom: (WeComSettings{}), ChannelDingTalk: (DingTalkSettings{}), - ChannelSlack: (SlackSettings{}), - ChannelMatrix: (MatrixSettings{}), - ChannelDeltaChat: (DeltaChatSettings{}), ChannelLINE: (LINESettings{}), ChannelOneBot: (OneBotSettings{}), ChannelQQ: (QQSettings{}), - ChannelIRC: (IRCSettings{}), - ChannelVK: (VKSettings{}), ChannelWhatsApp: (WhatsAppSettings{}), ChannelWhatsAppNative: (WhatsAppSettings{}), - ChannelTeamsWebHook: (TeamsWebhookSettings{}), ChannelMQTT: (MQTTSettings{}), - ChannelSlackWebHook: (SlackWebhookSettings{}), } // RegisterChannelSettings registers a settings struct prototype for a custom diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index a91199e5..5046564c 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -720,7 +720,7 @@ func TestLoadConfig_MigratesLegacyBindingsToDispatchRules(t *testing.T) { { "id": "main", "default": true }, { "id": "support" }, { "id": "ops" }, - { "id": "slack" } + { "id": "discord" } ] }, "bindings": [ @@ -739,9 +739,9 @@ func TestLoadConfig_MigratesLegacyBindingsToDispatchRules(t *testing.T) { } }, { - "agent_id": "slack", + "agent_id": "discord", "match": { - "channel": "slack", + "channel": "discord", "account_id": "*" } } @@ -779,10 +779,10 @@ func TestLoadConfig_MigratesLegacyBindingsToDispatchRules(t *testing.T) { } third := cfg.Agents.Dispatch.Rules[2] - if third.Agent != "slack" { - t.Fatalf("third.Agent = %q, want %q", third.Agent, "slack") + if third.Agent != "discord" { + t.Fatalf("third.Agent = %q, want %q", third.Agent, "discord") } - if third.When.Channel != "slack" || third.When.Account != "" { + if third.When.Channel != "discord" || third.When.Account != "" { t.Fatalf("third.When = %+v", third.When) } } @@ -1004,38 +1004,6 @@ func TestDefaultConfig_ChannelStreamingDisabled(t *testing.T) { } -func TestDefaultConfig_DeltaChatExample(t *testing.T) { - cfg := DefaultConfig() - - deltachat := cfg.Channels.Get(ChannelDeltaChat) - if deltachat == nil { - t.Fatal("DefaultConfig() missing deltachat channel") - } - if deltachat.Enabled { - t.Fatal("DefaultConfig().deltachat should be disabled") - } - if !deltachat.GroupTrigger.MentionOnly { - t.Fatal("DefaultConfig().deltachat should use mention-only group trigger") - } - decoded, err := deltachat.GetDecoded() - if err != nil { - t.Fatalf("deltachat GetDecoded() error = %v", err) - } - settings, ok := decoded.(*DeltaChatSettings) - if !ok { - t.Fatalf("deltachat settings type = %T, want *DeltaChatSettings", decoded) - } - if settings.Email != "@nine.testrun.org" { - t.Fatalf("DefaultConfig().deltachat.settings.email = %q, want @nine.testrun.org", settings.Email) - } - if settings.Password.String() != "" { - t.Fatal("DefaultConfig().deltachat.settings.password should be empty") - } - if settings.DisplayName == "" { - t.Fatal("DefaultConfig().deltachat.settings.display_name should be populated") - } -} - // TestDefaultConfig_WebTools verifies web tools config func TestDefaultConfig_WebTools(t *testing.T) { cfg := DefaultConfig() @@ -2909,16 +2877,6 @@ func TestFilterSensitiveData_AllTokenTypes(t *testing.T) { content: "Discord token: discord-bot-token-xyz789", want: "Discord token: [FILTERED]", }, - { - name: "slack_tokens", - content: "Slack bot: xoxb-slack-bot-token, app: xapp-slack-app-token", - want: "Slack bot: [FILTERED], app: [FILTERED]", - }, - { - name: "matrix_token", - content: "Matrix access token: matrix-access-token-abc", - want: "Matrix access token: [FILTERED]", - }, { name: "brave_api_key", content: "Brave key: brave-api-key", @@ -2934,11 +2892,6 @@ func TestFilterSensitiveData_AllTokenTypes(t *testing.T) { content: "GitHub token: github-token-xyz", want: "GitHub token: [FILTERED]", }, - { - name: "irc_passwords", - content: "IRC password: irc-password, nickserv: nickserv-pass", - want: "IRC password: [FILTERED], nickserv: [FILTERED]", - }, { name: "mixed_content", content: "Model key sk-model-key-12345 and Telegram token telegram-bot-token-abcdef", @@ -3129,14 +3082,6 @@ func testChannelsConfigWithTokens() ChannelsConfig { defs := []chDef{ {"telegram", TelegramSettings{Token: *NewSecureString("telegram-bot-token-abcdef")}}, {"discord", DiscordSettings{Token: *NewSecureString("discord-bot-token-xyz789")}}, - { - "slack", - SlackSettings{ - BotToken: *NewSecureString("xoxb-slack-bot-token"), - AppToken: *NewSecureString("xapp-slack-app-token"), - }, - }, - {"matrix", MatrixSettings{AccessToken: *NewSecureString("matrix-access-token-abc")}}, { "feishu", FeishuSettings{ @@ -3147,14 +3092,6 @@ func testChannelsConfigWithTokens() ChannelsConfig { {"dingtalk", DingTalkSettings{ClientSecret: *NewSecureString("dingtalk-client-secret")}}, {"onebot", OneBotSettings{AccessToken: *NewSecureString("onebot-access-token")}}, {"wecom", WeComSettings{Secret: *NewSecureString("wecom-secret")}}, - { - "irc", - IRCSettings{ - Password: *NewSecureString("irc-password"), - NickServPassword: *NewSecureString("nickserv-pass"), - SASLPassword: *NewSecureString("sasl-pass"), - }, - }, } for _, def := range defs { // Create Channel directly with settings to preserve SecureString values diff --git a/pkg/config/defaults.go b/pkg/config/defaults.go index de6d3320..63bf6c3c 100644 --- a/pkg/config/defaults.go +++ b/pkg/config/defaults.go @@ -537,22 +537,6 @@ func defaultChannels() ChannelsConfig { "settings": map[string]any{"max_message_length": 2000}, }, "dingtalk": map[string]any{}, - "slack": map[string]any{}, - "matrix": map[string]any{ - "group_trigger": map[string]any{"mention_only": true}, - "placeholder": map[string]any{"enabled": true, "text": []string{"Thinking... 💭"}}, - "settings": map[string]any{ - "homeserver": "https://matrix.org", - "join_on_invite": true, - }, - }, - "deltachat": map[string]any{ - "group_trigger": map[string]any{"mention_only": true}, - "settings": map[string]any{ - "email": "@nine.testrun.org", - "display_name": "PicoClaw Bot", - }, - }, "line": map[string]any{ "group_trigger": map[string]any{"mention_only": true}, "settings": map[string]any{ @@ -579,14 +563,6 @@ func defaultChannels() ChannelsConfig { "cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c", }, }, - "irc": map[string]any{ - "settings": map[string]any{ - "server": "", - "tls": true, - "nick": "picoclaw", - "channels": []string{}, - }, - }, } channels := make(ChannelsConfig, len(defs)) diff --git a/pkg/config/example_security_usage.go b/pkg/config/example_security_usage.go index de80f541..812128a5 100644 --- a/pkg/config/example_security_usage.go +++ b/pkg/config/example_security_usage.go @@ -212,11 +212,6 @@ channels: app_secret: "value" dingtalk: client_secret: "value" - slack: - bot_token: "value" - app_token: "value" - matrix: - access_token: "value" line: channel_secret: "value" channel_access_token: "value" @@ -233,12 +228,6 @@ channels: secret: "value" token: "value" encoding_aes_key: "value" - pico: - token: "value" - irc: - password: "value" - nickserv_password: "value" - sasl_password: "value" ## Web Tool API Keys diff --git a/pkg/config/security_integration_test.go b/pkg/config/security_integration_test.go index c7959cb1..1e4f8a37 100644 --- a/pkg/config/security_integration_test.go +++ b/pkg/config/security_integration_test.go @@ -228,14 +228,6 @@ func TestAllSecurityKeysAccessible(t *testing.T) { "enabled": true, "client_id": "test_client_id" }, - "slack": { - "enabled": true - }, - "matrix": { - "enabled": true, - "homeserver": "https://matrix.org", - "user_id": "@test:matrix.org" - }, "line": { "enabled": true, "webhook_host": "localhost", @@ -250,11 +242,6 @@ func TestAllSecurityKeysAccessible(t *testing.T) { "enabled": true, "bot_id": "test_wecom_bot_id" }, - "irc": { - "enabled": true, - "server": "irc.example.com", - "nick": "testbot" - }, "qq": { "enabled": true, "app_id": "test_qq_app_id" @@ -304,11 +291,6 @@ channels: token: "discord_test_bot_token_xyz" dingtalk: client_secret: "dingtalk_test_client_secret" - slack: - bot_token: "xoxb-slack-bot-token-123" - app_token: "xapp-slack-app-token-456" - matrix: - access_token: "matrix_test_access_token" line: channel_secret: "line_test_channel_secret" channel_access_token: "line_test_channel_access_token" @@ -316,10 +298,6 @@ channels: access_token: "onebot_test_access_token" wecom: secret: "wecom_test_secret" - irc: - password: "irc_test_password" - nickserv_password: "irc_test_nickserv_password" - sasl_password: "irc_test_sasl_password" qq: app_secret: "qq_test_app_secret" @@ -401,18 +379,6 @@ skills: assert.Equal(t, "dingtalk_test_client_secret", secureStr(dtSec.(*DingTalkSettings).ClientSecret)) t.Logf("DingTalk ClientSecret(): %s", secureStr(dtSec.(*DingTalkSettings).ClientSecret)) - // Slack - slSec := decodeChannel("slack") - assert.Equal(t, "xoxb-slack-bot-token-123", secureStr(slSec.(*SlackSettings).BotToken)) - assert.Equal(t, "xapp-slack-app-token-456", secureStr(slSec.(*SlackSettings).AppToken)) - t.Logf("Slack BotToken(): %s", secureStr(slSec.(*SlackSettings).BotToken)) - t.Logf("Slack AppToken(): %s", secureStr(slSec.(*SlackSettings).AppToken)) - - // Matrix - matSec := decodeChannel("matrix") - assert.Equal(t, "matrix_test_access_token", secureStr(matSec.(*MatrixSettings).AccessToken)) - t.Logf("Matrix AccessToken(): %s", secureStr(matSec.(*MatrixSettings).AccessToken)) - // LINE lineSec := decodeChannel("line") assert.Equal(t, "line_test_channel_secret", secureStr(lineSec.(*LINESettings).ChannelSecret)) @@ -432,15 +398,6 @@ skills: t.Logf("WeCom BotID: %s", wcSec.(*WeComSettings).BotID) t.Logf("WeCom Secret(): %s", secureStr(wcSec.(*WeComSettings).Secret)) - // IRC - ircSec := decodeChannel("irc") - assert.Equal(t, "irc_test_password", secureStr(ircSec.(*IRCSettings).Password)) - assert.Equal(t, "irc_test_nickserv_password", secureStr(ircSec.(*IRCSettings).NickServPassword)) - assert.Equal(t, "irc_test_sasl_password", secureStr(ircSec.(*IRCSettings).SASLPassword)) - t.Logf("IRC Password(): %s", secureStr(ircSec.(*IRCSettings).Password)) - t.Logf("IRC NickServPassword(): %s", secureStr(ircSec.(*IRCSettings).NickServPassword)) - t.Logf("IRC SASLPassword(): %s", secureStr(ircSec.(*IRCSettings).SASLPassword)) - // QQ qqSec := decodeChannel("qq") assert.Equal(t, "qq_test_app_secret", secureStr(qqSec.(*QQSettings).AppSecret)) diff --git a/pkg/gateway/channel_matrix.go b/pkg/gateway/channel_matrix.go deleted file mode 100644 index b6adbe49..00000000 --- a/pkg/gateway/channel_matrix.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !mipsle && !netbsd && !(freebsd && arm) && !android - -package gateway - -import ( - // Matrix currently pulls in mautrix crypto and modernc sqlite transitively. - // - // We exclude it on: - // - linux/mipsle: mautrix crypto falls back to libolm when the `goolm` build - // tag is unavailable, and modernc.org/sqlite/modernc.org/libc also lacks a - // working build path for our mipsle + softfloat target. - // - netbsd/*: modernc.org/sqlite v1.46.1 fails to compile due to broken - // generated mutex code on NetBSD (for example sqlite_netbsd_amd64.go calls - // mu.enter/mu.leave, but the generated mutex type does not define them). - // - freebsd/arm: modernc.org/libc v1.67.6 fails to compile due to broken - // generated 32-bit FreeBSD code (size_t/uint64 and int32/int64 mismatches - // in libc_freebsd.go). - // - // This means Matrix is currently unavailable on those targets. The proper - // long-term fix is to split Matrix basic support from its E2EE/sqlite-backed - // crypto path, or to upgrade/replace the upstream sqlite dependency once the - // affected targets are supported. - _ "github.com/sipeed/picoclaw/pkg/channels/matrix" -) diff --git a/pkg/gateway/gateway.go b/pkg/gateway/gateway.go index 042ce9ec..e929cd1c 100644 --- a/pkg/gateway/gateway.go +++ b/pkg/gateway/gateway.go @@ -19,20 +19,14 @@ import ( "github.com/sipeed/picoclaw/pkg/audio/tts" "github.com/sipeed/picoclaw/pkg/bus" "github.com/sipeed/picoclaw/pkg/channels" - _ "github.com/sipeed/picoclaw/pkg/channels/deltachat" _ "github.com/sipeed/picoclaw/pkg/channels/dingtalk" _ "github.com/sipeed/picoclaw/pkg/channels/discord" _ "github.com/sipeed/picoclaw/pkg/channels/feishu" - _ "github.com/sipeed/picoclaw/pkg/channels/irc" _ "github.com/sipeed/picoclaw/pkg/channels/line" _ "github.com/sipeed/picoclaw/pkg/channels/mqtt" _ "github.com/sipeed/picoclaw/pkg/channels/onebot" _ "github.com/sipeed/picoclaw/pkg/channels/qq" - _ "github.com/sipeed/picoclaw/pkg/channels/slack" - _ "github.com/sipeed/picoclaw/pkg/channels/slack_webhook" - _ "github.com/sipeed/picoclaw/pkg/channels/teams_webhook" _ "github.com/sipeed/picoclaw/pkg/channels/telegram" - _ "github.com/sipeed/picoclaw/pkg/channels/vk" _ "github.com/sipeed/picoclaw/pkg/channels/wecom" _ "github.com/sipeed/picoclaw/pkg/channels/weixin" _ "github.com/sipeed/picoclaw/pkg/channels/whatsapp" diff --git a/pkg/identity/identity_test.go b/pkg/identity/identity_test.go index c60402d1..2c6774a4 100644 --- a/pkg/identity/identity_test.go +++ b/pkg/identity/identity_test.go @@ -14,7 +14,7 @@ func TestBuildCanonicalID(t *testing.T) { }{ {"telegram", "123456", "telegram:123456"}, {"Discord", "98765432", "discord:98765432"}, - {"SLACK", "U123ABC", "slack:U123ABC"}, + {"DISCORD", "U123ABC", "discord:U123ABC"}, {"", "123", ""}, {"telegram", "", ""}, {" telegram ", " 123 ", "telegram:123"}, @@ -38,7 +38,7 @@ func TestParseCanonicalID(t *testing.T) { }{ {"telegram:123456", "telegram", "123456", true}, {"discord:98765432", "discord", "98765432", true}, - {"slack:U123ABC", "slack", "U123ABC", true}, + {"discord:U123ABC", "discord", "U123ABC", true}, {"nocolon", "", "", false}, {"", "", "", false}, {":missing", "", "", false}, diff --git a/pkg/memory/jsonl.go b/pkg/memory/jsonl.go index ef34d3bc..8addc26d 100644 --- a/pkg/memory/jsonl.go +++ b/pkg/memory/jsonl.go @@ -96,7 +96,7 @@ func (s *JSONLStore) metaPath(key string) string { // sanitizeKey converts a session key to a safe filename component. // Mirrors pkg/session.sanitizeFilename so that migration paths match. // Replaces ':' with '_' (session key separator) and '/' and '\' with '_' -// so composite IDs (e.g. Telegram forum "chatID/threadID", Slack "channel/thread_ts") +// so composite IDs (e.g. Telegram forum "chatID/threadID") // do not create subdirectories or break on Windows. func sanitizeKey(key string) string { s := strings.ReplaceAll(key, ":", "_") diff --git a/pkg/migrate/sources/openclaw/common.go b/pkg/migrate/sources/openclaw/common.go index 536e5c3e..a222577c 100644 --- a/pkg/migrate/sources/openclaw/common.go +++ b/pkg/migrate/sources/openclaw/common.go @@ -19,8 +19,6 @@ var supportedChannels = map[string]bool{ "discord": true, "qq": true, "dingtalk": true, - "slack": true, - "matrix": true, "line": true, "onebot": true, "wecom": true, diff --git a/pkg/migrate/sources/openclaw/openclaw_config.go b/pkg/migrate/sources/openclaw/openclaw_config.go index c9f28dd4..3c1eeef4 100644 --- a/pkg/migrate/sources/openclaw/openclaw_config.go +++ b/pkg/migrate/sources/openclaw/openclaw_config.go @@ -115,13 +115,9 @@ type OpenClawAgentTools struct { type OpenClawChannels struct { Telegram *OpenClawTelegramConfig `json:"telegram"` Discord *OpenClawDiscordConfig `json:"discord"` - Slack *OpenClawSlackConfig `json:"slack"` WhatsApp *OpenClawWhatsAppConfig `json:"whatsapp"` Signal *OpenClawSignalConfig `json:"signal"` - Matrix *OpenClawMatrixConfig `json:"matrix"` GoogleChat *OpenClawGoogleChatConfig `json:"googlechat"` - Teams *OpenClawTeamsConfig `json:"msteams"` - IRC *OpenClawIrcConfig `json:"irc"` Mattermost *OpenClawMattermostConfig `json:"mattermost"` Feishu *OpenClawFeishuConfig `json:"feishu"` IMessage *OpenClawIMessageConfig `json:"imessage"` @@ -148,15 +144,6 @@ type OpenClawDiscordConfig struct { Enabled *bool `json:"enabled"` } -type OpenClawSlackConfig struct { - BotToken *string `json:"botToken"` - AppToken *string `json:"appToken"` - DmPolicy *string `json:"dmPolicy"` - GroupPolicy *string `json:"groupPolicy"` - AllowFrom []string `json:"allowFrom"` - Enabled *bool `json:"enabled"` -} - type OpenClawWhatsAppConfig struct { AuthDir *string `json:"authDir"` DmPolicy *string `json:"dmPolicy"` @@ -176,16 +163,6 @@ type OpenClawSignalConfig struct { Enabled *bool `json:"enabled"` } -type OpenClawMatrixConfig struct { - Homeserver *string `json:"homeserver"` - UserID *string `json:"userId"` - AccessToken *string `json:"accessToken"` - Rooms []string `json:"rooms"` - DmPolicy *string `json:"dmPolicy"` - AllowFrom []string `json:"allowFrom"` - Enabled *bool `json:"enabled"` -} - type OpenClawGoogleChatConfig struct { ServiceAccountFile *string `json:"serviceAccountFile"` WebhookPath *string `json:"webhookPath"` @@ -194,27 +171,6 @@ type OpenClawGoogleChatConfig struct { Enabled *bool `json:"enabled"` } -type OpenClawTeamsConfig struct { - AppID *string `json:"appId"` - AppPassword *string `json:"appPassword"` - TenantID *string `json:"tenantId"` - DmPolicy *string `json:"dmPolicy"` - AllowFrom []string `json:"allowFrom"` - Enabled *bool `json:"enabled"` -} - -type OpenClawIrcConfig struct { - Host *string `json:"host"` - Port *int `json:"port"` - TLS *bool `json:"tls"` - Nick *string `json:"nick"` - Password *string `json:"password"` - Channels []string `json:"channels"` - DmPolicy *string `json:"dmPolicy"` - AllowFrom []string `json:"allowFrom"` - Enabled *bool `json:"enabled"` -} - type OpenClawMattermostConfig struct { BotToken *string `json:"botToken"` BaseURL *string `json:"baseUrl"` @@ -361,10 +317,6 @@ func (c *OpenClawConfig) IsChannelEnabled(name string) bool { return c.Channels.Telegram == nil || c.Channels.Telegram.Enabled == nil || *c.Channels.Telegram.Enabled case "discord": return c.Channels.Discord == nil || c.Channels.Discord.Enabled == nil || *c.Channels.Discord.Enabled - case "slack": - return c.Channels.Slack == nil || c.Channels.Slack.Enabled == nil || *c.Channels.Slack.Enabled - case "matrix": - return c.Channels.Matrix == nil || c.Channels.Matrix.Enabled == nil || *c.Channels.Matrix.Enabled case "whatsapp": return c.Channels.WhatsApp == nil || c.Channels.WhatsApp.Enabled == nil || *c.Channels.WhatsApp.Enabled case "feishu": @@ -386,16 +338,6 @@ func GetChannelAllowFrom(ch any) []string { return nil } return c.AllowFrom - case *OpenClawSlackConfig: - if c == nil { - return nil - } - return c.AllowFrom - case *OpenClawMatrixConfig: - if c == nil { - return nil - } - return c.AllowFrom case *OpenClawWhatsAppConfig: if c == nil { return nil @@ -624,8 +566,6 @@ type ChannelsConfig struct { Discord DiscordConfig `json:"discord"` QQ QQConfig `json:"qq"` DingTalk DingTalkConfig `json:"dingtalk"` - Slack SlackConfig `json:"slack"` - Matrix MatrixConfig `json:"matrix"` LINE LINEConfig `json:"line"` } @@ -673,21 +613,6 @@ type DingTalkConfig struct { AllowFrom []string `json:"allow_from"` } -type SlackConfig struct { - Enabled bool `json:"enabled"` - BotToken string `json:"bot_token"` - AppToken string `json:"app_token"` - AllowFrom []string `json:"allow_from"` -} - -type MatrixConfig struct { - Enabled bool `json:"enabled"` - Homeserver string `json:"homeserver"` - UserID string `json:"user_id"` - AccessToken string `json:"access_token"` - AllowFrom []string `json:"allow_from"` -} - type LINEConfig struct { Enabled bool `json:"enabled"` ChannelSecret string `json:"channel_secret"` @@ -784,20 +709,6 @@ func (c *OpenClawConfig) convertChannels(warnings *[]string) ChannelsConfig { } } - if c.Channels.Slack != nil { - enabled := c.Channels.Slack.Enabled == nil || *c.Channels.Slack.Enabled - channels.Slack = SlackConfig{ - Enabled: enabled, - AllowFrom: c.Channels.Slack.AllowFrom, - } - if c.Channels.Slack.BotToken != nil { - channels.Slack.BotToken = *c.Channels.Slack.BotToken - } - if c.Channels.Slack.AppToken != nil { - channels.Slack.AppToken = *c.Channels.Slack.AppToken - } - } - if c.Channels.WhatsApp != nil { enabled := c.Channels.WhatsApp.Enabled == nil || *c.Channels.WhatsApp.Enabled channels.WhatsApp = WhatsAppConfig{ @@ -855,29 +766,9 @@ func (c *OpenClawConfig) convertChannels(warnings *[]string) ChannelsConfig { } } - if c.Channels.Matrix != nil && supportedChannels["matrix"] { - enabled := c.Channels.Matrix.Enabled == nil || *c.Channels.Matrix.Enabled - channels.Matrix = MatrixConfig{ - Enabled: enabled, - AllowFrom: c.Channels.Matrix.AllowFrom, - } - if c.Channels.Matrix.Homeserver != nil { - channels.Matrix.Homeserver = *c.Channels.Matrix.Homeserver - } - if c.Channels.Matrix.UserID != nil { - channels.Matrix.UserID = *c.Channels.Matrix.UserID - } - if c.Channels.Matrix.AccessToken != nil { - channels.Matrix.AccessToken = *c.Channels.Matrix.AccessToken - } - } - if c.Channels.Signal != nil { *warnings = append(*warnings, "Channel 'signal': No PicoClaw adapter available") } - if c.Channels.IRC != nil { - *warnings = append(*warnings, "Channel 'irc': No PicoClaw adapter available") - } if c.Channels.Mattermost != nil { *warnings = append(*warnings, "Channel 'mattermost': No PicoClaw adapter available") } @@ -1056,33 +947,6 @@ func (c ChannelsConfig) ToStandardChannels() config.ChannelsConfig { return m }()) - setChannel(channels, "slack", func() map[string]any { - m := map[string]any{ - "enabled": c.Slack.Enabled, - } - if c.Slack.BotToken != "" { - m["bot_token"] = config.NewSecureString(c.Slack.BotToken) - } - if c.Slack.AppToken != "" { - m["app_token"] = config.NewSecureString(c.Slack.AppToken) - } - return m - }()) - - setChannel(channels, "matrix", func() map[string]any { - m := map[string]any{ - "enabled": c.Matrix.Enabled, - "homeserver": c.Matrix.Homeserver, - "user_id": c.Matrix.UserID, - "allow_from": c.Matrix.AllowFrom, - "join_on_invite": true, - } - if c.Matrix.AccessToken != "" { - m["access_token"] = config.NewSecureString(c.Matrix.AccessToken) - } - return m - }()) - setChannel(channels, "line", func() map[string]any { m := map[string]any{ "enabled": c.LINE.Enabled, diff --git a/pkg/migrate/sources/openclaw/openclaw_config_test.go b/pkg/migrate/sources/openclaw/openclaw_config_test.go index 74590b0f..dd80f89a 100644 --- a/pkg/migrate/sources/openclaw/openclaw_config_test.go +++ b/pkg/migrate/sources/openclaw/openclaw_config_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "os" "path/filepath" - "strings" "testing" "github.com/sipeed/picoclaw/pkg/config" @@ -328,11 +327,6 @@ func TestConvertToPicoClawWithQQAndDingTalk(t *testing.T) { "enabled": true, "appId": "ding-app-id", "appSecret": "ding-app-secret" - }, - "slack": { - "enabled": true, - "botToken": "xoxb-test", - "appToken": "xapp-test" } } }` @@ -366,105 +360,6 @@ func TestConvertToPicoClawWithQQAndDingTalk(t *testing.T) { t.Errorf("expected dingtalk client ID 'ding-app-id', got '%s'", picoCfg.Channels.DingTalk.ClientID) } - if !picoCfg.Channels.Slack.Enabled { - t.Error("slack should be enabled") - } - if picoCfg.Channels.Slack.BotToken != "xoxb-test" { - t.Errorf("expected slack bot token 'xoxb-test', got '%s'", picoCfg.Channels.Slack.BotToken) - } - if picoCfg.Channels.Slack.AppToken != "xapp-test" { - t.Errorf("expected slack app token 'xapp-test', got '%s'", picoCfg.Channels.Slack.AppToken) - } -} - -func TestConvertToPicoClawWithMatrix(t *testing.T) { - tmpDir := t.TempDir() - configPath := filepath.Join(tmpDir, "openclaw.json") - - testConfig := `{ - "channels": { - "matrix": { - "enabled": true, - "homeserver": "https://matrix.example.com", - "userId": "@bot:matrix.example.com", - "accessToken": "syt_test_token", - "allowFrom": ["@alice:matrix.example.com"] - } - } - }` - - err := os.WriteFile(configPath, []byte(testConfig), 0o644) - if err != nil { - t.Fatalf("failed to write test config: %v", err) - } - - cfg, err := LoadOpenClawConfig(configPath) - if err != nil { - t.Fatalf("failed to load config: %v", err) - } - - picoCfg, warnings, err := cfg.ConvertToPicoClaw("") - if err != nil { - t.Fatalf("failed to convert config: %v", err) - } - - if !picoCfg.Channels.Matrix.Enabled { - t.Error("matrix should be enabled") - } - if picoCfg.Channels.Matrix.Homeserver != "https://matrix.example.com" { - t.Errorf("expected matrix homeserver, got %q", picoCfg.Channels.Matrix.Homeserver) - } - if picoCfg.Channels.Matrix.UserID != "@bot:matrix.example.com" { - t.Errorf("expected matrix user_id, got %q", picoCfg.Channels.Matrix.UserID) - } - if picoCfg.Channels.Matrix.AccessToken != "syt_test_token" { - t.Errorf("expected matrix access_token, got %q", picoCfg.Channels.Matrix.AccessToken) - } - if len(picoCfg.Channels.Matrix.AllowFrom) != 1 || - picoCfg.Channels.Matrix.AllowFrom[0] != "@alice:matrix.example.com" { - t.Errorf("unexpected matrix allow_from: %#v", picoCfg.Channels.Matrix.AllowFrom) - } - - for _, w := range warnings { - if strings.Contains(w, "Channel 'matrix'") { - t.Fatalf("matrix should no longer be reported as unsupported, warning=%q", w) - } - } -} - -func TestConvertToPicoClawWithMatrixDisabled(t *testing.T) { - tmpDir := t.TempDir() - configPath := filepath.Join(tmpDir, "openclaw.json") - - testConfig := `{ - "channels": { - "matrix": { - "enabled": false, - "homeserver": "https://matrix.example.com", - "userId": "@bot:matrix.example.com", - "accessToken": "syt_test_token" - } - } - }` - - err := os.WriteFile(configPath, []byte(testConfig), 0o644) - if err != nil { - t.Fatalf("failed to write test config: %v", err) - } - - cfg, err := LoadOpenClawConfig(configPath) - if err != nil { - t.Fatalf("failed to load config: %v", err) - } - - picoCfg, _, err := cfg.ConvertToPicoClaw("") - if err != nil { - t.Fatalf("failed to convert config: %v", err) - } - - if picoCfg.Channels.Matrix.Enabled { - t.Error("matrix should respect enabled=false from source config") - } } func TestOpenClawAgentModel(t *testing.T) { @@ -502,9 +397,6 @@ func TestChannelEnabled(t *testing.T) { Discord: &OpenClawDiscordConfig{ Enabled: boolPtr(false), }, - Slack: &OpenClawSlackConfig{ - Enabled: boolPtr(true), - }, }, } @@ -514,12 +406,6 @@ func TestChannelEnabled(t *testing.T) { if cfg.IsChannelEnabled("discord") { t.Error("discord should be disabled") } - if !cfg.IsChannelEnabled("slack") { - t.Error("slack should be enabled (explicitly set)") - } - if !cfg.IsChannelEnabled("matrix") { - t.Error("matrix should be enabled (nil config defaults to enabled)") - } if cfg.IsChannelEnabled("line") { t.Error("line should return false (not in switch cases)") } diff --git a/pkg/providers/ratelimiter_test.go b/pkg/providers/ratelimiter_test.go index 9972616e..9634a6df 100644 --- a/pkg/providers/ratelimiter_test.go +++ b/pkg/providers/ratelimiter_test.go @@ -202,7 +202,7 @@ func TestRateLimiter_Concurrency(t *testing.T) { wg.Wait() got := passed.Load() - // Allow small timing slack: between rpm-2 and rpm+2. + // Allow small timing discord: between rpm-2 and rpm+2. if got < int64(rpm-2) || got > int64(rpm+2) { t.Fatalf("expected ~%d immediate passes, got %d", rpm, got) } diff --git a/pkg/routing/route_test.go b/pkg/routing/route_test.go index 729e880f..424672d9 100644 --- a/pkg/routing/route_test.go +++ b/pkg/routing/route_test.go @@ -160,10 +160,10 @@ func TestResolveRoute_DispatchMentionedRule(t *testing.T) { cfg.Agents.Dispatch = &config.DispatchConfig{ Rules: []config.DispatchRule{ { - Name: "slack-mentions", + Name: "discord-mentions", Agent: "support", When: config.DispatchSelector{ - Channel: "slack", + Channel: "discord", Space: "workspace:t001", Mentioned: &mentioned, }, @@ -173,7 +173,7 @@ func TestResolveRoute_DispatchMentionedRule(t *testing.T) { r := NewRouteResolver(cfg) route := r.ResolveRoute(bus.InboundContext{ - Channel: "slack", + Channel: "discord", ChatID: "C123", ChatType: "channel", SpaceID: "T001", diff --git a/pkg/session/allocator_test.go b/pkg/session/allocator_test.go index 3f8557fc..23239b61 100644 --- a/pkg/session/allocator_test.go +++ b/pkg/session/allocator_test.go @@ -49,7 +49,7 @@ func TestAllocateRouteSession_GroupPeer(t *testing.T) { allocation := AllocateRouteSession(AllocationInput{ AgentID: "main", Context: bus.InboundContext{ - Channel: "slack", + Channel: "discord", Account: "workspace-a", ChatID: "C001", ChatType: "channel", @@ -63,8 +63,8 @@ func TestAllocateRouteSession_GroupPeer(t *testing.T) { if allocation.SessionKey == "" || !IsOpaqueSessionKey(allocation.SessionKey) { t.Fatalf("SessionKey = %q, want opaque session key", allocation.SessionKey) } - if !containsAlias(allocation.SessionAliases, "agent:main:slack:channel:c001") { - t.Fatalf("SessionAliases = %v, want to contain agent:main:slack:channel:c001", allocation.SessionAliases) + if !containsAlias(allocation.SessionAliases, "agent:main:discord:channel:c001") { + t.Fatalf("SessionAliases = %v, want to contain agent:main:discord:channel:c001", allocation.SessionAliases) } if allocation.MainSessionKey == "" || !IsOpaqueSessionKey(allocation.MainSessionKey) { t.Fatalf("MainSessionKey = %q, want opaque session key", allocation.MainSessionKey) diff --git a/pkg/session/key_test.go b/pkg/session/key_test.go index 6cdf397e..4bdf7e11 100644 --- a/pkg/session/key_test.go +++ b/pkg/session/key_test.go @@ -63,8 +63,8 @@ func TestBuildLegacyDirectAliases(t *testing.T) { } func TestBuildLegacyPeerAlias(t *testing.T) { - got := BuildLegacyPeerAlias("Main", "Slack", "channel", "C001") - if got != "agent:main:slack:channel:c001" { + got := BuildLegacyPeerAlias("Main", "Discord", "channel", "C001") + if got != "agent:main:discord:channel:c001" { t.Fatalf("BuildLegacyPeerAlias() = %q", got) } } @@ -84,7 +84,7 @@ func TestResolveAgentID_PrefersSessionScope(t *testing.T) { scope: &SessionScope{ Version: ScopeVersionV1, AgentID: "Support", - Channel: "slack", + Channel: "discord", }, } diff --git a/pkg/session/manager_test.go b/pkg/session/manager_test.go index e167941e..fb6c29be 100644 --- a/pkg/session/manager_test.go +++ b/pkg/session/manager_test.go @@ -14,7 +14,7 @@ func TestSanitizeFilename(t *testing.T) { {"simple", "simple"}, {"telegram:123456", "telegram_123456"}, {"discord:987654321", "discord_987654321"}, - {"slack:C01234", "slack_C01234"}, + {"discord:C01234", "discord_C01234"}, {"no-colons-here", "no-colons-here"}, {"multiple:colons:here", "multiple_colons_here"}, {"agent:main:telegram:group:-1003822706455/12", "agent_main_telegram_group_-1003822706455_12"}, diff --git a/pkg/tools/spawn_status_test.go b/pkg/tools/spawn_status_test.go index 9c772d61..b6df453c 100644 --- a/pkg/tools/spawn_status_test.go +++ b/pkg/tools/spawn_status_test.go @@ -362,14 +362,14 @@ func TestSpawnStatusTool_ChannelFiltering_GetByID(t *testing.T) { manager.mu.Lock() manager.tasks["subagent-99"] = &SubagentTask{ ID: "subagent-99", Task: "secret", Status: "completed", Result: "private data", - OriginChannel: "slack", OriginChatID: "room-Z", + OriginChannel: "discord", OriginChatID: "room-Z", } manager.mu.Unlock() tool := NewSpawnStatusTool(manager) // Different chat trying to look up subagent-99 by ID. - ctx := WithToolContext(context.Background(), "slack", "room-OTHER") + ctx := WithToolContext(context.Background(), "discord", "room-OTHER") result := tool.Execute(ctx, map[string]any{"task_id": "subagent-99"}) if !result.IsError { diff --git a/pkg/utils/media.go b/pkg/utils/media.go index 51d4b81e..8d20e2b5 100644 --- a/pkg/utils/media.go +++ b/pkg/utils/media.go @@ -141,7 +141,7 @@ func DownloadFile(urlStr, filename string, opts DownloadOptions) string { return "" } - // Add extra headers (e.g., Authorization for Slack) + // Add extra headers (e.g., Authorization) for key, value := range opts.ExtraHeaders { req.Header.Set(key, value) } diff --git a/scripts/test-irc.sh b/scripts/test-irc.sh deleted file mode 100755 index 40db0175..00000000 --- a/scripts/test-irc.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/sh -# Starts a local Ergo IRC server for testing the IRC channel. -# -# Requirements: docker -# Usage: ./scripts/test-irc.sh - -set -e - -CONTAINER_NAME="picoclaw-test-ergo" -IRC_PORT=6667 - -# Clean up any previous instance -docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true - -echo "Starting Ergo IRC server on port $IRC_PORT..." -docker run -d \ - --name "$CONTAINER_NAME" \ - -p "$IRC_PORT:6667" \ - ghcr.io/ergochat/ergo:stable - -for i in $(seq 1 10); do - if nc -z localhost "$IRC_PORT" 2>/dev/null; then - break - fi - if [ "$i" -eq 10 ]; then - echo "ERROR: Server did not start within 10s" - exit 1 - fi - sleep 1 -done - -echo "" -echo "IRC server ready on localhost:$IRC_PORT" -echo "" -echo "Add this to your ~/.picoclaw/config.json under \"channels\":" -echo "" -echo ' "irc": {' -echo ' "enabled": true,' -echo ' "server": "localhost:6667",' -echo ' "tls": false,' -echo ' "nick": "picobot",' -echo ' "channels": ["#test"],' -echo ' "allow_from": [],' -echo ' "group_trigger": { "mention_only": true }' -echo ' }' -echo "" -echo "Then run picoclaw:" -echo " cd packages/picoclaw && go run ./cmd/picoclaw gateway" -echo "" -echo "Connect with an IRC client:" -echo " irssi: /connect localhost $IRC_PORT" -echo " weechat: /server add test localhost/$IRC_PORT && /connect test" -echo " Join #test, then: picobot: hello" -echo "" -echo "To stop the IRC server:" -echo " docker rm -f $CONTAINER_NAME"