From 996dfefffe1733d4076c830c80dbbad27601f4e8 Mon Sep 17 00:00:00 2001 From: loveuer Date: Wed, 11 Nov 2026 19:02:03 +0800 Subject: [PATCH] refactor: remove Pico and MaixCAM channels Remove pico, pico_client and maixcam adapters, configuration and migration support. Drop Pico-specific agent publishing while preserving shared IM streaming and MQTT. Clean up channel examples and localized documentation; move shared tests to Telegram. Validated with full Go tests, vet, lint, docs checks and a Linux amd64 build. --- README.md | 4 - config/config.example.json | 35 - docs/channels/maixcam/README.fr.md | 36 - docs/channels/maixcam/README.ja.md | 36 - docs/channels/maixcam/README.md | 36 - docs/channels/maixcam/README.pt-br.md | 36 - docs/channels/maixcam/README.vi.md | 36 - docs/channels/maixcam/README.zh.md | 36 - docs/guides/chat-apps.fr.md | 36 +- docs/guides/chat-apps.ja.md | 25 - docs/guides/chat-apps.md | 4 +- docs/guides/chat-apps.ms.md | 4 +- docs/guides/chat-apps.pt-br.md | 50 +- docs/guides/chat-apps.vi.md | 50 +- docs/guides/chat-apps.zh.md | 27 +- docs/guides/configuration.fr.md | 14 +- docs/guides/configuration.it.md | 14 +- docs/guides/configuration.ja.md | 14 +- docs/guides/configuration.md | 14 +- docs/guides/configuration.ms.md | 14 +- docs/guides/configuration.pt-br.md | 14 +- docs/guides/configuration.vi.md | 14 +- docs/guides/configuration.zh.md | 14 +- docs/guides/docker.md | 2 +- docs/project/README.fr.md | 4 - docs/project/README.id.md | 4 - docs/project/README.it.md | 4 - docs/project/README.ja.md | 4 - docs/project/README.ko.md | 4 - docs/project/README.ms.md | 4 - docs/project/README.pt-br.md | 4 - docs/project/README.vi.md | 4 - docs/project/README.zh.md | 4 - examples/pico-echo-server/README.md | 47 - examples/pico-echo-server/main.go | 160 -- pkg/agent/agent.go | 5 +- pkg/agent/agent_message.go | 12 +- pkg/agent/agent_outbound.go | 152 -- pkg/agent/agent_test.go | 414 +---- pkg/agent/context_cache_test.go | 2 +- pkg/agent/pipeline_execute.go | 4 +- pkg/agent/pipeline_finalize.go | 4 +- pkg/agent/pipeline_llm.go | 45 +- pkg/agent/pipeline_streaming.go | 36 +- pkg/agent/pipeline_streaming_test.go | 86 +- pkg/agent/turn_profile_test.go | 16 +- pkg/bus/bus_test.go | 4 +- pkg/channels/README.md | 20 +- pkg/channels/README.zh.md | 20 +- pkg/channels/maixcam/init.go | 25 - pkg/channels/maixcam/maixcam.go | 291 ---- pkg/channels/manager.go | 6 - pkg/channels/manager_channel.go | 4 - pkg/channels/pico/client.go | 343 ---- pkg/channels/pico/client_test.go | 625 ------- pkg/channels/pico/init.go | 54 - pkg/channels/pico/pico.go | 1492 ----------------- pkg/channels/pico/pico_test.go | 1072 ------------ pkg/channels/pico/pico_usage_test.go | 69 - pkg/channels/pico/protocol.go | 81 - pkg/config/config.go | 33 - pkg/config/config_channel.go | 74 +- pkg/config/config_channel_test.go | 62 +- pkg/config/config_test.go | 148 +- pkg/config/defaults.go | 12 - pkg/config/security_integration_test.go | 10 - pkg/config/security_test.go | 6 - pkg/gateway/gateway.go | 2 - pkg/heartbeat/service.go | 2 +- pkg/migrate/sources/openclaw/common.go | 1 - .../sources/openclaw/openclaw_config.go | 36 - .../sources/openclaw/openclaw_config_test.go | 15 - pkg/session/allocator_test.go | 6 +- pkg/session/jsonl_backend_test.go | 8 +- 74 files changed, 243 insertions(+), 5862 deletions(-) delete mode 100644 docs/channels/maixcam/README.fr.md delete mode 100644 docs/channels/maixcam/README.ja.md delete mode 100644 docs/channels/maixcam/README.md delete mode 100644 docs/channels/maixcam/README.pt-br.md delete mode 100644 docs/channels/maixcam/README.vi.md delete mode 100644 docs/channels/maixcam/README.zh.md delete mode 100644 examples/pico-echo-server/README.md delete mode 100644 examples/pico-echo-server/main.go delete mode 100644 pkg/channels/maixcam/init.go delete mode 100644 pkg/channels/maixcam/maixcam.go delete mode 100644 pkg/channels/pico/client.go delete mode 100644 pkg/channels/pico/client_test.go delete mode 100644 pkg/channels/pico/init.go delete mode 100644 pkg/channels/pico/pico.go delete mode 100644 pkg/channels/pico/pico_test.go delete mode 100644 pkg/channels/pico/pico_usage_test.go delete mode 100644 pkg/channels/pico/protocol.go diff --git a/README.md b/README.md index dba7057e..8f962bb8 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,6 @@ PicoClaw can be deployed on virtually any Linux device! - $9.9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) E(Ethernet) or W(WiFi6) edition, for a minimal home assistant - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), or $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), for automated server operations -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) or $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), for smart surveillance @@ -397,9 +396,6 @@ Talk to your PicoClaw through 19+ messaging platforms: | **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) | -| **MaixCam** | Easy (enable) | TCP socket | [Guide](docs/channels/maixcam/README.md) | -| **Pico** | Easy (enable) | Native protocol | Built-in | -| **Pico Client** | Easy (WebSocket URL) | WebSocket | Built-in | > All webhook-based channels share a single Gateway HTTP server (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Feishu uses WebSocket/SDK mode and does not use the shared HTTP server. diff --git a/config/config.example.json b/config/config.example.json index de12d84c..6fbb362f 100644 --- a/config/config.example.json +++ b/config/config.example.json @@ -145,16 +145,6 @@ "app_secret": "YOUR_QQ_APP_SECRET" } }, - "maixcam": { - "enabled": false, - "type": "maixcam", - "allow_from": [], - "reasoning_channel_id": "", - "settings": { - "host": "0.0.0.0", - "port": 18790 - } - }, "whatsapp": { "enabled": false, "type": "whatsapp", @@ -264,31 +254,6 @@ "send_thinking_message": true } }, - "pico": { - "enabled": false, - "type": "pico", - "allow_from": [], - "settings": { - "token": "YOUR_PICO_TOKEN", - "allow_token_query": false, - "allow_origins": [], - "ping_interval": 30, - "read_timeout": 60, - "max_connections": 100 - } - }, - "pico_client": { - "enabled": false, - "type": "pico_client", - "allow_from": [], - "settings": { - "url": "wss://remote-pico-server/pico/ws", - "token": "YOUR_PICO_TOKEN", - "session_id": "", - "ping_interval": 30, - "read_timeout": 60 - } - }, "irc": { "enabled": false, "type": "irc", diff --git a/docs/channels/maixcam/README.fr.md b/docs/channels/maixcam/README.fr.md deleted file mode 100644 index 23f8c11c..00000000 --- a/docs/channels/maixcam/README.fr.md +++ /dev/null @@ -1,36 +0,0 @@ -> Retour au [README](../../project/README.fr.md) - -# MaixCam - -MaixCam est un canal dédié à la connexion aux caméras AI Sipeed MaixCAM et MaixCAM2. Il utilise des sockets TCP pour une communication bidirectionnelle et prend en charge les scénarios de déploiement d'IA en périphérie. - -## Configuration - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "host": "0.0.0.0", - "port": 18790, - "allow_from": [] - } - } -} -``` - -| Champ | Type | Requis | Description | -| ---------- | ------ | ------ | --------------------------------------------------------------------------- | -| enabled | bool | Oui | Activer ou non le canal MaixCam | -| host | string | Oui | Adresse d'écoute du serveur TCP | -| port | int | Oui | Port d'écoute du serveur TCP | -| allow_from | array | Non | Liste blanche d'identifiants d'appareils ; vide signifie tous les appareils | - -## Cas d'utilisation - -Le canal MaixCam permet à PicoClaw de fonctionner comme backend IA pour les appareils en périphérie : - -- **Surveillance intelligente** : MaixCAM envoie des images ; PicoClaw les analyse via des modèles de vision -- **Contrôle IoT** : Les appareils envoient des données de capteurs ; PicoClaw coordonne les réponses -- **IA hors ligne** : Déployer PicoClaw sur un réseau local pour une inférence à faible latence diff --git a/docs/channels/maixcam/README.ja.md b/docs/channels/maixcam/README.ja.md deleted file mode 100644 index adec1944..00000000 --- a/docs/channels/maixcam/README.ja.md +++ /dev/null @@ -1,36 +0,0 @@ -> [README](../../project/README.ja.md) に戻る - -# MaixCam - -MaixCam は、Sipeed MaixCAM および MaixCAM2 AI カメラデバイスへの接続専用チャンネルです。TCP ソケットを使用した双方向通信を実装し、エッジ AI デプロイメントシナリオをサポートします。 - -## 設定 - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "host": "0.0.0.0", - "port": 18790, - "allow_from": [] - } - } -} -``` - -| フィールド | 型 | 必須 | 説明 | -| ---------- | ------ | ------ | ------------------------------------------------------------- | -| enabled | bool | はい | MaixCam チャンネルを有効にするかどうか | -| host | string | はい | TCP サーバーのリッスンアドレス | -| port | int | はい | TCP サーバーのリッスンポート | -| allow_from | array | いいえ | 許可するデバイスIDのリスト。空の場合はすべてのデバイスを許可 | - -## ユースケース - -MaixCam チャンネルにより、PicoClaw はエッジデバイスの AI バックエンドとして機能できます: - -- **スマート監視**:MaixCAM が画像フレームを送信し、PicoClaw がビジョンモデルで分析する -- **IoT 制御**:デバイスがセンサーデータを送信し、PicoClaw がレスポンスを調整する -- **オフライン AI**:ローカルネットワークに PicoClaw をデプロイして低遅延推論を実現する diff --git a/docs/channels/maixcam/README.md b/docs/channels/maixcam/README.md deleted file mode 100644 index f5efe53a..00000000 --- a/docs/channels/maixcam/README.md +++ /dev/null @@ -1,36 +0,0 @@ -> Back to [README](../../../README.md) - -# MaixCam - -MaixCam is a dedicated channel for connecting to Sipeed MaixCAM and MaixCAM2 AI camera devices. It uses TCP sockets for bidirectional communication and supports edge AI deployment scenarios. - -## Configuration - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "host": "0.0.0.0", - "port": 18790, - "allow_from": [] - } - } -} -``` - -| Field | Type | Required | Description | -| ---------- | ------ | -------- | ---------------------------------------------------------------- | -| enabled | bool | Yes | Whether to enable the MaixCam channel | -| host | string | Yes | TCP server listening address | -| port | int | Yes | TCP server listening port | -| allow_from | array | No | Allowlist of device IDs; empty means all devices are allowed | - -## Use Cases - -The MaixCam channel enables PicoClaw to act as an AI backend for edge devices: - -- **Smart Surveillance**: MaixCAM sends image frames; PicoClaw analyzes them using vision models -- **IoT Control**: Devices send sensor data; PicoClaw coordinates responses -- **Offline AI**: Deploy PicoClaw on a local network for low-latency inference diff --git a/docs/channels/maixcam/README.pt-br.md b/docs/channels/maixcam/README.pt-br.md deleted file mode 100644 index dd606ff5..00000000 --- a/docs/channels/maixcam/README.pt-br.md +++ /dev/null @@ -1,36 +0,0 @@ -> Voltar ao [README](../../project/README.pt-br.md) - -# MaixCam - -MaixCam é um canal dedicado para conectar dispositivos de câmera AI Sipeed MaixCAM e MaixCAM2. Utiliza sockets TCP para comunicação bidirecional e suporta cenários de implantação de IA na borda. - -## Configuração - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "host": "0.0.0.0", - "port": 18790, - "allow_from": [] - } - } -} -``` - -| Campo | Tipo | Obrigatório | Descrição | -| ---------- | ------ | ----------- | -------------------------------------------------------------------------- | -| enabled | bool | Sim | Se o canal MaixCam deve ser habilitado | -| host | string | Sim | Endereço de escuta do servidor TCP | -| port | int | Sim | Porta de escuta do servidor TCP | -| allow_from | array | Não | Lista de IDs de dispositivos permitidos; vazio significa todos os dispositivos | - -## Casos de uso - -O canal MaixCam permite que o PicoClaw atue como backend de IA para dispositivos de borda: - -- **Vigilância inteligente**: MaixCAM envia quadros de imagem; PicoClaw os analisa usando modelos de visão -- **Controle IoT**: Dispositivos enviam dados de sensores; PicoClaw coordena as respostas -- **IA offline**: Implante o PicoClaw em uma rede local para inferência de baixa latência diff --git a/docs/channels/maixcam/README.vi.md b/docs/channels/maixcam/README.vi.md deleted file mode 100644 index 09aba354..00000000 --- a/docs/channels/maixcam/README.vi.md +++ /dev/null @@ -1,36 +0,0 @@ -> Quay lại [README](../../project/README.vi.md) - -# MaixCam - -MaixCam là kênh chuyên dụng để kết nối với các thiết bị camera AI Sipeed MaixCAM và MaixCAM2. Sử dụng TCP socket để giao tiếp hai chiều và hỗ trợ các kịch bản triển khai AI tại biên. - -## Cấu hình - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "host": "0.0.0.0", - "port": 18790, - "allow_from": [] - } - } -} -``` - -| Trường | Kiểu | Bắt buộc | Mô tả | -| ---------- | ------ | -------- | ------------------------------------------------------------------------ | -| enabled | bool | Có | Có bật kênh MaixCam hay không | -| host | string | Có | Địa chỉ lắng nghe của máy chủ TCP | -| port | int | Có | Cổng lắng nghe của máy chủ TCP | -| allow_from | array | Không | Danh sách trắng ID thiết bị; để trống nghĩa là cho phép tất cả thiết bị | - -## Trường hợp sử dụng - -Kênh MaixCam cho phép PicoClaw hoạt động như backend AI cho các thiết bị biên: - -- **Giám sát thông minh**: MaixCAM gửi khung hình ảnh; PicoClaw phân tích bằng mô hình thị giác -- **Điều khiển IoT**: Thiết bị gửi dữ liệu cảm biến; PicoClaw điều phối phản hồi -- **AI ngoại tuyến**: Triển khai PicoClaw trên mạng nội bộ để suy luận độ trễ thấp diff --git a/docs/channels/maixcam/README.zh.md b/docs/channels/maixcam/README.zh.md deleted file mode 100644 index 2b4fdb87..00000000 --- a/docs/channels/maixcam/README.zh.md +++ /dev/null @@ -1,36 +0,0 @@ -> 返回 [README](../../project/README.zh.md) - -# MaixCam - -MaixCam 是专用于连接矽速科技 MaixCAM 与 MaixCAM2 AI 摄像设备的通道。它采用 TCP 套接字实现双向通信,支持边缘 AI 部署场景。 - -## 配置 - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "host": "0.0.0.0", - "port": 18790, - "allow_from": [] - } - } -} -``` - -| 字段 | 类型 | 必填 | 描述 | -| ---------- | ------ | ---- | -------------------------------- | -| enabled | bool | 是 | 是否启用 MaixCam 频道 | -| host | string | 是 | TCP 服务器监听地址 | -| port | int | 是 | TCP 服务器监听端口 | -| allow_from | array | 否 | 设备ID白名单,空表示允许所有设备 | - -## 使用场景 - -MaixCam 通道使 PicoClaw 能够作为边缘设备的 AI 后端运行: - -- **智能监控** :MaixCAM 发送图像帧,PicoClaw 通过视觉模型进行分析 -- **物联网控制** :设备发送传感器数据,PicoClaw 协调响应 -- **离线AI** :在本地网络部署 PicoClaw 实现低延迟推理 diff --git a/docs/guides/chat-apps.fr.md b/docs/guides/chat-apps.fr.md index a03141e5..6c432cab 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 ou MaixCam. +Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, 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é. @@ -24,8 +24,6 @@ Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, Matrix, QQ, Din | **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) | -| **MaixCam** | ⭐ Facile | Canal d'intégration matérielle pour caméras AI Sipeed | [Documentation](../channels/maixcam/README.fr.md) | -| **Pico** | ⭐ Facile | Canal protocole natif PicoClaw | |
@@ -651,38 +649,6 @@ picoclaw gateway
- -
-MaixCam - -**1. Préparer le matériel** - -* Obtenez un appareil [Sipeed MaixCam](https://wiki.sipeed.com/maixcam) - -**2. Configurer** - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam", - "allow_from": [] - } - } -} -``` - -> MaixCam est une intégration matérielle Sipeed pour l'interaction IA embarquée. - -**3. Lancer** - -```bash -picoclaw gateway -``` - -
-
MQTT diff --git a/docs/guides/chat-apps.ja.md b/docs/guides/chat-apps.ja.md index cc9671bd..a386500f 100644 --- a/docs/guides/chat-apps.ja.md +++ b/docs/guides/chat-apps.ja.md @@ -26,8 +26,6 @@ PicoClaw は複数のチャットプラットフォームをサポートして | **IRC** | ⭐⭐ 中程度 | サーバー + TLS 設定 | [ドキュメント](#irc) | | **OneBot** | ⭐⭐ 中程度 | NapCat/Go-CQHTTP 互換、コミュニティエコシステム充実 | [ドキュメント](../channels/onebot/README.ja.md) | | **MQTT** | ⭐ 簡単 | ブローカー経由で任意の MQTT クライアントと通信 | [ドキュメント](../channels/mqtt/README.ja.md) | -| **MaixCam** | ⭐ 簡単 | Sipeed AI カメラハードウェア統合チャネル | [ドキュメント](../channels/maixcam/README.ja.md) | -| **Pico** | ⭐ 簡単 | PicoClaw ネイティブプロトコルチャネル | | --- @@ -649,29 +647,6 @@ picoclaw gateway
- -
-MaixCam - -Sipeed AI カメラハードウェア向けの統合チャネルです。 - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam" - } - } -} -``` - -```bash -picoclaw gateway -``` - -
-
MQTT diff --git a/docs/guides/chat-apps.md b/docs/guides/chat-apps.md index 4fcf1265..3198c11b 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, MaixCam, or Pico (native protocol) +Talk to your picoclaw through Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, 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. @@ -24,8 +24,6 @@ Talk to your picoclaw through Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, | **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) | -| **MaixCam** | ⭐ Easy | Hardware integration channel for Sipeed AI cameras | [Docs](../channels/maixcam/README.md) | -| **Pico** | ⭐ Easy | Native PicoClaw protocol channel | |
diff --git a/docs/guides/chat-apps.ms.md b/docs/guides/chat-apps.ms.md index 03e8d36c..e4905f15 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, MaixCam, atau Pico (protokol asli) +Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, 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. @@ -23,8 +23,6 @@ Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, Matrix, QQ, Di | **IRC** | Sederhana (pelayan + konfigurasi TLS) | | **OneBot** | Sederhana (QQ melalui protokol OneBot) | | **MQTT** | Mudah (broker + agent_id) | -| **MaixCam** | Mudah (integrasi perkakasan Sipeed) | -| **Pico** | Protokol PicoClaw asli |
Telegram (Disyorkan) diff --git a/docs/guides/chat-apps.pt-br.md b/docs/guides/chat-apps.pt-br.md index f6b89ca3..76c6af5a 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 ou MaixCam +Converse com seu picoclaw através do Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, 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. @@ -24,8 +24,6 @@ Converse com seu picoclaw através do Telegram, Discord, WhatsApp, Matrix, QQ, D | **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) | -| **MaixCam** | ⭐ Fácil | Canal de integração de hardware para câmeras AI Sipeed | [Documentação](../channels/maixcam/README.pt-br.md) | -| **Pico** | ⭐ Fácil | Canal de protocolo nativo PicoClaw | |
@@ -297,30 +295,6 @@ picoclaw gateway
- -
-MaixCam - -Canal de integração projetado especificamente para hardware de câmera AI Sipeed. - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam" - } - } -} -``` - -```bash -picoclaw gateway -``` - -
- -
Matrix @@ -675,28 +649,6 @@ picoclaw gateway
-
-MaixCam - -Canal de integração projetado especificamente para hardware de câmera AI Sipeed. - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam" - } - } -} -``` - -```bash -picoclaw gateway -``` - -
-
MQTT diff --git a/docs/guides/chat-apps.vi.md b/docs/guides/chat-apps.vi.md index 8071c9d3..14f99049 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 hoặc MaixCam +Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, 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. @@ -24,8 +24,6 @@ Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, Matrix | **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) | -| **MaixCam** | ⭐ Dễ | Kênh tích hợp phần cứng cho camera AI Sipeed | [Tài liệu](../channels/maixcam/README.vi.md) | -| **Pico** | ⭐ Dễ | Kênh giao thức bản địa PicoClaw | |
@@ -297,30 +295,6 @@ picoclaw gateway
- -
-MaixCam - -Kênh tích hợp được thiết kế đặc biệt cho phần cứng camera AI Sipeed. - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam" - } - } -} -``` - -```bash -picoclaw gateway -``` - -
- -
Matrix @@ -676,28 +650,6 @@ picoclaw gateway
-
-MaixCam - -Kênh tích hợp được thiết kế đặc biệt cho phần cứng camera AI Sipeed. - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam" - } - } -} -``` - -```bash -picoclaw gateway -``` - -
-
MQTT diff --git a/docs/guides/chat-apps.zh.md b/docs/guides/chat-apps.zh.md index d7400cd8..b2b2c73a 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、MaixCam 等。 +PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、Discord、WhatsApp、微信、QQ、钉钉、LINE、企业微信、飞书、Slack、IRC、OneBot、MQTT 等。 > **注意**: 依赖 HTTP 回调的渠道共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`),无需为每个渠道单独配置端口。飞书、钉钉、企业微信这类 Socket/Stream 模式渠道不依赖共享 webhook 服务器来接收入站消息。 @@ -26,8 +26,6 @@ PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方 | **IRC** | ⭐⭐ 中等 | 服务器 + TLS 配置 | [查看文档](#irc) | | **OneBot** | ⭐⭐ 中等 | 兼容 NapCat/Go-CQHTTP,社区生态丰富 | [查看文档](../channels/onebot/README.zh.md) | | **MQTT** | ⭐ 简单 | 任意 MQTT 客户端通过 Broker 收发消息 | [查看文档](../channels/mqtt/README.zh.md) | -| **MaixCam** | ⭐ 简单 | 专为 AI 摄像头设计的硬件集成通道 | [查看文档](../channels/maixcam/README.zh.md) | -| **Pico** | ⭐ 简单 | PicoClaw 原生协议通道 | | --- @@ -589,29 +587,6 @@ picoclaw gateway
- -
-MaixCam - -专为 Sipeed AI 摄像头硬件设计的集成通道。 - -```json -{ - "channel_list": { - "maixcam": { - "enabled": true, - "type": "maixcam" - } - } -} -``` - -```bash -picoclaw gateway -``` - -
-
MQTT diff --git a/docs/guides/configuration.fr.md b/docs/guides/configuration.fr.md index 64812ddc..aff3e78a 100644 --- a/docs/guides/configuration.fr.md +++ b/docs/guides/configuration.fr.md @@ -412,8 +412,6 @@ L'ancienne configuration `providers` est **dépréciée** et a été supprimée Le streaming provider utilise un double opt-in et est désactivé par défaut. L'agent ne tente le streaming que lorsque le channel courant a `settings.streaming.enabled: true`, que l'entrée de modèle active a `streaming.enabled: true`, et que le provider comme le channel prennent en charge le streaming. Si une condition manque, PicoClaw utilise le chemin de requête non-streaming normal. -Pico est le premier channel entièrement câblé. Pico crée le premier message assistant avec le message wire existant `message.create`, puis met à jour ce même message avec `message.update`; aucun nouveau type de message Pico n'est introduit. - Laissez `streaming` absent si vous ne voulez pas de streaming. Un bloc `streaming` omis signifie désactivé; il n'est pas nécessaire d'écrire `"streaming": {"enabled": false}`. Exemple d'activation : @@ -432,11 +430,11 @@ Exemple d'activation : } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -449,11 +447,11 @@ Exemple d'activation : | Champ | Type | Défaut | Description | | ----- | ---- | ------ | ----------- | | `channel_list..settings.streaming.enabled` | bool | `false` | Autorise ce channel à afficher la sortie streaming du provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Défaut Pico après activation : `0` | Intervalle minimal entre les mises à jour intermédiaires; le contenu final est toujours envoyé | -| `channel_list..settings.streaming.min_growth_chars` | int | Défaut Pico après activation : `1` | Croissance minimale du texte avant une mise à jour intermédiaire; le contenu final est toujours envoyé | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Intervalle minimal entre les mises à jour intermédiaires; le contenu final est toujours envoyé | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Croissance minimale du texte avant une mise à jour intermédiaire; le contenu final est toujours envoyé | | `model_list[].streaming.enabled` | bool | `false` | Autorise cette entrée de modèle à tenter des requêtes provider en streaming | -Les anciennes variables d'environnement Telegram restent compatibles : `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` et `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Elles s'appliquent uniquement aux settings Telegram et n'activent ni ne modifient `settings.streaming` de Pico. +Les anciennes variables d'environnement Telegram restent compatibles : `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` et `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Le comportement d'échec est volontairement conservateur : si le streaming échoue avant l'envoi d'un chunk visible, PicoClaw réessaie une fois via le chemin `Chat()` normal. Si un chunk a déjà été affiché à l'utilisateur, PicoClaw n'envoie pas une deuxième réponse non-streaming, afin d'éviter une sortie dupliquée. diff --git a/docs/guides/configuration.it.md b/docs/guides/configuration.it.md index 1fcb3cbb..b004b38c 100644 --- a/docs/guides/configuration.it.md +++ b/docs/guides/configuration.it.md @@ -35,8 +35,6 @@ PICOCLAW_HOME=/srv/picoclaw PICOCLAW_CONFIG=/srv/picoclaw/main.json picoclaw gat Lo streaming del provider usa un double opt-in ed è disattivato per impostazione predefinita. L'agent prova lo streaming solo quando il canale corrente ha `settings.streaming.enabled: true`, l'entry del modello attivo ha `streaming.enabled: true`, e sia il provider sia il canale supportano lo streaming. Se manca una qualsiasi condizione, PicoClaw usa il normale percorso di richiesta non streaming. -Pico è il primo canale completamente collegato. Pico crea il primo messaggio assistant con il wire message esistente `message.create`, poi aggiorna lo stesso messaggio con `message.update`; non viene introdotto alcun nuovo tipo di wire message Pico. - Lascia `streaming` assente quando non vuoi usare lo streaming. Un blocco `streaming` omesso significa disattivato; non è necessario scrivere `"streaming": {"enabled": false}`. Esempio di attivazione: @@ -55,11 +53,11 @@ Esempio di attivazione: } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -72,11 +70,11 @@ Esempio di attivazione: | Campo | Tipo | Predefinito | Descrizione | | ----- | ---- | ----------- | ----------- | | `channel_list..settings.streaming.enabled` | bool | `false` | Permette a questo canale di mostrare l'output streaming del provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Predefinito Pico dopo l'attivazione: `0` | Intervallo minimo tra aggiornamenti intermedi; il contenuto finale viene sempre inviato | -| `channel_list..settings.streaming.min_growth_chars` | int | Predefinito Pico dopo l'attivazione: `1` | Crescita minima del testo prima di inviare un aggiornamento intermedio; il contenuto finale viene sempre inviato | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Intervallo minimo tra aggiornamenti intermedi; il contenuto finale viene sempre inviato | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Crescita minima del testo prima di inviare un aggiornamento intermedio; il contenuto finale viene sempre inviato | | `model_list[].streaming.enabled` | bool | `false` | Permette a questa entry di modello di provare richieste provider streaming | -Le variabili d'ambiente legacy di Telegram restano compatibili: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` e `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Si applicano solo alle settings Telegram e non attivano né modificano `settings.streaming` di Pico. +Le variabili d'ambiente legacy di Telegram restano compatibili: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` e `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Il comportamento in caso di errore è intenzionalmente conservativo: se lo streaming fallisce prima che venga inviato un chunk visibile, PicoClaw riprova una volta tramite il normale percorso `Chat()`. Se un chunk è già stato mostrato all'utente, PicoClaw non invia una seconda risposta non streaming, evitando output duplicato. diff --git a/docs/guides/configuration.ja.md b/docs/guides/configuration.ja.md index 27fe7c07..38f254ae 100644 --- a/docs/guides/configuration.ja.md +++ b/docs/guides/configuration.ja.md @@ -413,8 +413,6 @@ HEARTBEAT_OK を返信 ユーザーが直接結果を受信 Provider ストリーミングは二重の opt-in 方式で、デフォルトでは無効です。現在の channel に `settings.streaming.enabled: true` があり、アクティブなモデルエントリに `streaming.enabled: true` があり、さらに provider と channel の両方がストリーミングをサポートしている場合にのみ、agent はストリーミングリクエストを試行します。いずれかの条件が欠ける場合、PicoClaw は通常の非ストリーミングリクエスト経路を使います。 -Pico が最初に完全対応した channel です。Pico は既存の `message.create` wire message で最初の assistant メッセージを作成し、その後 `message.update` で同じメッセージを更新します。新しい Pico wire message type は追加されません。 - ストリーミングを使わない場合は `streaming` を省略してください。`streaming` ブロックの省略は無効を意味するため、`"streaming": {"enabled": false}` を書く必要はありません。 有効化例: @@ -433,11 +431,11 @@ Pico が最初に完全対応した channel です。Pico は既存の `message. } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -450,11 +448,11 @@ Pico が最初に完全対応した channel です。Pico は既存の `message. | フィールド | 型 | デフォルト | 説明 | | ---------- | -- | ---------- | ---- | | `channel_list..settings.streaming.enabled` | bool | `false` | この channel で provider のストリーミング出力を表示できるようにします | -| `channel_list..settings.streaming.throttle_seconds` | int | Pico で有効化後のデフォルト:`0` | 中間更新の最小間隔。最終内容は常に flush されます | -| `channel_list..settings.streaming.min_growth_chars` | int | Pico で有効化後のデフォルト:`1` | 次の中間更新を送るために必要な最小文字増加数。最終内容は常に flush されます | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | 中間更新の最小間隔。最終内容は常に flush されます | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | 次の中間更新を送るために必要な最小文字増加数。最終内容は常に flush されます | | `model_list[].streaming.enabled` | bool | `false` | このモデルエントリで provider ストリーミングリクエストを試行できるようにします | -既存の Telegram 環境変数 `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS` は互換性のため引き続き使えます。これらは Telegram settings にのみ適用され、Pico の `settings.streaming` を有効化または変更しません。 +既存の Telegram 環境変数 `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. 失敗時の動作は保守的です。可視 chunk が送信される前にストリーミングが失敗した場合、PicoClaw は通常の `Chat()` 経路で一度だけ再試行します。すでに chunk がユーザーに表示されている場合は、表示済み出力の重複を避けるため、二つ目の非ストリーミング回答は送信しません。 diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 5065fb84..81141e1f 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -782,8 +782,6 @@ Resolution rules: Provider streaming uses a double opt-in and is disabled by default. The agent only tries streaming when the current channel has `settings.streaming.enabled: true`, the active model entry has `streaming.enabled: true`, and both the provider and channel support streaming. If any condition is missing, PicoClaw uses the normal non-streaming request path. -Pico is the first fully wired channel. Pico creates the first assistant message with the existing `message.create` wire message, then updates that same message with `message.update`; no new Pico wire message type is introduced. - Leave `streaming` unset when you do not want streaming. An omitted `streaming` block means disabled; you do not need to write `"streaming": {"enabled": false}`. Opt-in example: @@ -802,11 +800,11 @@ Opt-in example: } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -819,11 +817,11 @@ Opt-in example: | Field | Type | Default | Description | | ----- | ---- | ------- | ----------- | | `channel_list..settings.streaming.enabled` | bool | `false` | Allows this channel to display provider streaming output | -| `channel_list..settings.streaming.throttle_seconds` | int | Pico default after enabling: `0` | Minimum interval for intermediate updates; final content is always flushed | -| `channel_list..settings.streaming.min_growth_chars` | int | Pico default after enabling: `1` | Minimum character growth before sending an intermediate update; final content is always flushed | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Minimum interval for intermediate updates; final content is always flushed | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Minimum character growth before sending an intermediate update; final content is always flushed | | `model_list[].streaming.enabled` | bool | `false` | Allows this model entry to try provider streaming requests | -Legacy Telegram environment variables remain compatible: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, and `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. They only apply to Telegram settings and do not enable or modify Pico `settings.streaming`. +Legacy Telegram environment variables remain compatible: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, and `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Failure behavior is intentionally conservative: if streaming fails before any visible chunk is sent, PicoClaw retries once through the normal `Chat()` path. If a chunk has already been shown to the user, PicoClaw does not send a second non-streaming answer, because that would duplicate visible output. diff --git a/docs/guides/configuration.ms.md b/docs/guides/configuration.ms.md index ad4c184f..bec5898a 100644 --- a/docs/guides/configuration.ms.md +++ b/docs/guides/configuration.ms.md @@ -35,8 +35,6 @@ PICOCLAW_HOME=/srv/picoclaw PICOCLAW_CONFIG=/srv/picoclaw/main.json picoclaw gat Provider streaming menggunakan double opt-in dan dimatikan secara lalai. Agent hanya mencuba streaming apabila saluran semasa mempunyai `settings.streaming.enabled: true`, entry model aktif mempunyai `streaming.enabled: true`, dan kedua-dua provider serta saluran menyokong streaming. Jika mana-mana syarat tiada, PicoClaw menggunakan laluan permintaan bukan streaming biasa. -Pico ialah saluran pertama yang disambungkan sepenuhnya. Pico mencipta mesej assistant pertama dengan wire message sedia ada `message.create`, kemudian mengemas kini mesej yang sama dengan `message.update`; tiada jenis wire message Pico baharu ditambah. - Biarkan `streaming` tidak ditetapkan jika anda tidak mahu streaming. Blok `streaming` yang tiada bermaksud dimatikan; anda tidak perlu menulis `"streaming": {"enabled": false}`. Contoh mengaktifkan streaming: @@ -55,11 +53,11 @@ Contoh mengaktifkan streaming: } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -72,11 +70,11 @@ Contoh mengaktifkan streaming: | Kunci | Jenis | Lalai | Penerangan | | ----- | ----- | ----- | ---------- | | `channel_list..settings.streaming.enabled` | bool | `false` | Membenarkan saluran ini memaparkan output streaming provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Lalai Pico selepas diaktifkan: `0` | Jarak masa minimum antara kemas kini pertengahan; kandungan akhir sentiasa dihantar | -| `channel_list..settings.streaming.min_growth_chars` | int | Lalai Pico selepas diaktifkan: `1` | Pertambahan aksara minimum sebelum menghantar kemas kini pertengahan; kandungan akhir sentiasa dihantar | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Jarak masa minimum antara kemas kini pertengahan; kandungan akhir sentiasa dihantar | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Pertambahan aksara minimum sebelum menghantar kemas kini pertengahan; kandungan akhir sentiasa dihantar | | `model_list[].streaming.enabled` | bool | `false` | Membenarkan entry model ini mencuba permintaan provider streaming | -Pemboleh ubah persekitaran Telegram lama masih serasi: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, dan `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Ia hanya digunakan untuk settings Telegram dan tidak mengaktifkan atau mengubah `settings.streaming` Pico. +Pemboleh ubah persekitaran Telegram lama masih serasi: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, dan `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Tingkah laku kegagalan adalah konservatif: jika streaming gagal sebelum mana-mana chunk kelihatan dihantar, PicoClaw mencuba semula sekali melalui laluan `Chat()` biasa. Jika chunk sudah dipaparkan kepada pengguna, PicoClaw tidak menghantar jawapan bukan streaming kedua untuk mengelakkan output berganda. diff --git a/docs/guides/configuration.pt-br.md b/docs/guides/configuration.pt-br.md index 41d34b22..549b9ddd 100644 --- a/docs/guides/configuration.pt-br.md +++ b/docs/guides/configuration.pt-br.md @@ -413,8 +413,6 @@ A configuração antiga `providers` está **depreciada** e foi removida no V2. C O streaming do provider usa double opt-in e fica desativado por padrão. O agent só tenta streaming quando o canal atual tem `settings.streaming.enabled: true`, a entrada de modelo ativa tem `streaming.enabled: true`, e tanto o provider quanto o canal suportam streaming. Se qualquer condição estiver ausente, o PicoClaw usa o caminho normal de requisição sem streaming. -O Pico é o primeiro canal totalmente integrado. O Pico cria a primeira mensagem assistant com o wire message existente `message.create` e depois atualiza a mesma mensagem com `message.update`; nenhum novo tipo de wire message do Pico é introduzido. - Deixe `streaming` ausente quando não quiser streaming. Um bloco `streaming` omitido significa desativado; você não precisa escrever `"streaming": {"enabled": false}`. Exemplo de ativação: @@ -433,11 +431,11 @@ Exemplo de ativação: } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -450,11 +448,11 @@ Exemplo de ativação: | Campo | Tipo | Padrão | Descrição | | ----- | ---- | ------ | --------- | | `channel_list..settings.streaming.enabled` | bool | `false` | Permite que este canal exiba output streaming do provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Padrão do Pico após ativar: `0` | Intervalo mínimo entre atualizações intermediárias; o conteúdo final sempre é enviado | -| `channel_list..settings.streaming.min_growth_chars` | int | Padrão do Pico após ativar: `1` | Crescimento mínimo de texto antes de enviar outra atualização intermediária; o conteúdo final sempre é enviado | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Intervalo mínimo entre atualizações intermediárias; o conteúdo final sempre é enviado | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Crescimento mínimo de texto antes de enviar outra atualização intermediária; o conteúdo final sempre é enviado | | `model_list[].streaming.enabled` | bool | `false` | Permite que esta entrada de modelo tente requisições de provider streaming | -As variáveis de ambiente legadas do Telegram continuam compatíveis: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` e `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Elas se aplicam apenas às settings do Telegram e não ativam nem modificam `settings.streaming` do Pico. +As variáveis de ambiente legadas do Telegram continuam compatíveis: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` e `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. O comportamento de falha é intencionalmente conservador: se o streaming falhar antes de qualquer chunk visível ser enviado, o PicoClaw tenta novamente uma vez pelo caminho normal `Chat()`. Se um chunk já foi mostrado ao usuário, o PicoClaw não envia uma segunda resposta sem streaming, evitando output duplicado. diff --git a/docs/guides/configuration.vi.md b/docs/guides/configuration.vi.md index 82880302..38b4be42 100644 --- a/docs/guides/configuration.vi.md +++ b/docs/guides/configuration.vi.md @@ -413,8 +413,6 @@ Cấu hình `providers` cũ đã **bị deprecated** và đã được loại b Provider streaming dùng cơ chế double opt-in và bị tắt theo mặc định. Agent chỉ thử streaming khi channel hiện tại có `settings.streaming.enabled: true`, entry model đang dùng có `streaming.enabled: true`, và cả provider lẫn channel đều hỗ trợ streaming. Nếu thiếu bất kỳ điều kiện nào, PicoClaw dùng đường dẫn yêu cầu không streaming thông thường. -Pico là channel đầu tiên được nối đầy đủ. Pico tạo message assistant đầu tiên bằng wire message hiện có `message.create`, sau đó cập nhật chính message đó bằng `message.update`; không thêm loại wire message Pico mới. - Hãy để trống `streaming` khi bạn không muốn dùng streaming. Bỏ qua block `streaming` nghĩa là đã tắt; bạn không cần viết `"streaming": {"enabled": false}`. Ví dụ bật streaming: @@ -433,11 +431,11 @@ Ví dụ bật streaming: } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -450,11 +448,11 @@ Ví dụ bật streaming: | Trường | Kiểu | Mặc định | Mô tả | | ------ | ---- | -------- | ----- | | `channel_list..settings.streaming.enabled` | bool | `false` | Cho phép channel này hiển thị output streaming từ provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Mặc định Pico sau khi bật: `0` | Khoảng cách tối thiểu giữa các cập nhật trung gian; nội dung cuối luôn được flush | -| `channel_list..settings.streaming.min_growth_chars` | int | Mặc định Pico sau khi bật: `1` | Số ký tự tăng tối thiểu trước khi gửi cập nhật trung gian; nội dung cuối luôn được flush | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Khoảng cách tối thiểu giữa các cập nhật trung gian; nội dung cuối luôn được flush | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Số ký tự tăng tối thiểu trước khi gửi cập nhật trung gian; nội dung cuối luôn được flush | | `model_list[].streaming.enabled` | bool | `false` | Cho phép entry model này thử yêu cầu provider streaming | -Các biến môi trường Telegram cũ vẫn tương thích: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, và `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Chúng chỉ áp dụng cho Telegram settings và không bật hoặc thay đổi `settings.streaming` của Pico. +Các biến môi trường Telegram cũ vẫn tương thích: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, và `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. Hành vi lỗi được giữ thận trọng: nếu streaming lỗi trước khi gửi bất kỳ chunk hiển thị nào, PicoClaw thử lại một lần qua đường dẫn `Chat()` thông thường. Nếu đã có chunk hiển thị cho người dùng, PicoClaw không gửi thêm một câu trả lời non-streaming thứ hai để tránh lặp output. diff --git a/docs/guides/configuration.zh.md b/docs/guides/configuration.zh.md index cd5774b9..90e5e60f 100644 --- a/docs/guides/configuration.zh.md +++ b/docs/guides/configuration.zh.md @@ -574,8 +574,6 @@ Agent 读取 HEARTBEAT.md Provider 流式输出采用双开关,默认关闭。只有当前 channel 的 `settings.streaming.enabled` 和当前模型条目的 `streaming.enabled` 都为 `true`,并且 provider 与 channel 都支持流式能力时,Agent 才会尝试流式请求;任一条件不满足时仍使用普通非流式请求。 -当前完整落地的是 Pico。Pico 使用已有的 `message.create` 创建第一条 assistant 消息,随后用 `message.update` 更新同一条消息,不新增协议消息类型。 - 不需要流式时请省略 `streaming` 配置块。省略表示关闭,不需要写 `"streaming": {"enabled": false}`。 开启示例: @@ -594,11 +592,11 @@ Provider 流式输出采用双开关,默认关闭。只有当前 channel 的 ` } ], "channel_list": { - "pico": { + "telegram": { "enabled": true, - "type": "pico", + "type": "telegram", "settings": { - "token": "YOUR_PICO_TOKEN", + "token": "YOUR_TELEGRAM_TOKEN", "streaming": { "enabled": true } @@ -611,11 +609,11 @@ Provider 流式输出采用双开关,默认关闭。只有当前 channel 的 ` | 字段 | 类型 | 默认值 | 说明 | |------|------|--------|------| | `channel_list..settings.streaming.enabled` | bool | `false` | 是否允许该 channel 尝试展示 provider 流式输出 | -| `channel_list..settings.streaming.throttle_seconds` | int | Pico 开启后默认 `0` | 中间更新的最小时间间隔,最终内容不受此限制 | -| `channel_list..settings.streaming.min_growth_chars` | int | Pico 开启后默认 `1` | 中间更新相比上次发送至少增长的字符数,最终内容不受此限制 | +| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | 中间更新的最小时间间隔,最终内容不受此限制 | +| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | 中间更新相比上次发送至少增长的字符数,最终内容不受此限制 | | `model_list[].streaming.enabled` | bool | `false` | 是否允许该模型条目尝试 provider 流式请求 | -Telegram 旧环境变量仍兼容:`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`。这些环境变量只作用于 Telegram settings,不会开启或修改 Pico 的 `settings.streaming`。 +Telegram 旧环境变量仍兼容:`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. 失败处理保持保守:如果还没有任何可见 chunk 就失败,PicoClaw 会回退到普通 `Chat()` 路径重试一次;如果已经有 chunk 展示给用户,则不会再发送一条非流式最终答案,避免界面重复输出。 diff --git a/docs/guides/docker.md b/docs/guides/docker.md index d19637a1..d6200e46 100644 --- a/docs/guides/docker.md +++ b/docs/guides/docker.md @@ -27,7 +27,7 @@ docker compose -f docker/docker-compose.yml --profile gateway up -d > **Docker Users**: By default, the Gateway listens on `127.0.0.1` which is not accessible from the host. If you need to access the health endpoints or expose ports, set `PICOCLAW_GATEWAY_HOST=0.0.0.0` in your environment or update `config.json`. > [!NOTE] -> The `gateway` profile only serves the webhook handlers (including Pico when enabled) and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. The `/pico/ws` endpoint is available directly on the gateway whenever the Pico channel is enabled. +> The `gateway` profile only serves the webhook handlers and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. ```bash # 5. Check logs diff --git a/docs/project/README.fr.md b/docs/project/README.fr.md index 8d90e004..6d1b09d1 100644 --- a/docs/project/README.fr.md +++ b/docs/project/README.fr.md @@ -152,7 +152,6 @@ PicoClaw peut être déployé sur pratiquement n'importe quel appareil Linux ! - $9,9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) édition E(Ethernet) ou W(WiFi6), pour un assistant domestique minimal - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), ou $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), pour des opérations serveur automatisées -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) ou $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), pour la surveillance intelligente @@ -381,9 +380,6 @@ Parlez à votre PicoClaw via plus de 17 plateformes de messagerie : | **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) | -| **MaixCam** | Facile (activer) | Socket TCP | [Guide](../channels/maixcam/README.fr.md) | -| **Pico** | Facile (activer) | Protocole natif | Intégré | -| **Pico Client** | Facile (URL WebSocket) | WebSocket | Intégré | > 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 0435f74b..607f3582 100644 --- a/docs/project/README.id.md +++ b/docs/project/README.id.md @@ -150,7 +150,6 @@ PicoClaw dapat di-deploy di hampir semua perangkat Linux! - $9,9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) versi E(Ethernet) atau W(WiFi6), untuk home assistant minimal - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), atau $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), untuk operasi server otomatis -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) atau $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), untuk pengawasan cerdas @@ -377,9 +376,6 @@ Bicara dengan PicoClaw Anda melalui 17+ platform pesan: | **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) | -| **MaixCam** | Mudah (aktifkan) | TCP socket | [Panduan](../channels/maixcam/README.md) | -| **Pico** | Mudah (aktifkan) | Native protocol | Bawaan | -| **Pico Client** | Mudah (WebSocket URL) | WebSocket | Bawaan | > 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 1e28afc3..3d8dfab6 100644 --- a/docs/project/README.it.md +++ b/docs/project/README.it.md @@ -150,7 +150,6 @@ PicoClaw può essere distribuito su quasi qualsiasi dispositivo Linux! - $9,9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) versione E (Ethernet) o W (WiFi6), per un assistente domotico minimale - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), o $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), per la manutenzione automatizzata dei server -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) o $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), per la sorveglianza intelligente @@ -377,9 +376,6 @@ Parla con il tuo PicoClaw attraverso 17+ piattaforme di messaggistica: | **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) | -| **MaixCam** | Facile (abilita) | TCP socket | [Guida](../channels/maixcam/README.md) | -| **Pico** | Facile (abilita) | Protocollo nativo | Integrato | -| **Pico Client** | Facile (WebSocket URL) | WebSocket | Integrato | > 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 6fe6b354..53f07cb4 100644 --- a/docs/project/README.ja.md +++ b/docs/project/README.ja.md @@ -150,7 +150,6 @@ PicoClaw はほぼすべての Linux デバイスにデプロイできます! - $9.9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) E(Ethernet) または W(WiFi6) バージョン、最小ホームアシスタントに - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html) または $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html) サーバー自動メンテナンスに -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) または $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera) スマート監視に @@ -378,9 +377,6 @@ Provider の完全な設定詳細は [Provider とモデル](../guides/providers | **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) | -| **MaixCam** | 簡単(有効化) | TCP socket | [ガイド](../channels/maixcam/README.ja.md) | -| **Pico** | 簡単(有効化) | Native protocol | 内蔵 | -| **Pico Client** | 簡単(WebSocket URL) | WebSocket | 内蔵 | > 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 484acb74..f3835018 100644 --- a/docs/project/README.ko.md +++ b/docs/project/README.ko.md @@ -150,7 +150,6 @@ PicoClaw는 사실상 거의 모든 Linux 장치에 배포할 수 있습니다! - 최소형 홈 어시스턴트를 위해 $9.9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) E(이더넷) 또는 W(WiFi6) 에디션 - 서버 자동 운영을 위해 $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html) 또는 $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html) -- 스마트 감시를 위해 $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) 또는 $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera) @@ -381,9 +380,6 @@ PicoClaw는 `model_list` 설정을 통해 30개 이상의 LLM 프로바이더를 | **VK** | 쉬움(그룹 토큰) | Long Poll | [가이드](../channels/vk/README.md) | | **IRC** | 중간(서버 + 닉네임) | IRC protocol | [가이드](../guides/chat-apps.md#irc) | | **OneBot** | 중간(WebSocket URL) | OneBot v11 | [가이드](../channels/onebot/README.md) | -| **MaixCam** | 쉬움(활성화) | TCP socket | [가이드](../channels/maixcam/README.md) | -| **Pico** | 쉬움(활성화) | 네이티브 프로토콜 | 내장 | -| **Pico Client** | 쉬움(WebSocket URL) | WebSocket | 내장 | > 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 3edbd4dd..4e5b9a39 100644 --- a/docs/project/README.ms.md +++ b/docs/project/README.ms.md @@ -150,7 +150,6 @@ PicoClaw boleh digunakan pada hampir mana-mana peranti Linux! - $9.9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) untuk pembantu rumah minimal - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html) untuk operasi pelayan automatik -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) untuk pengawasan pintar @@ -378,9 +377,6 @@ Bercakap dengan PicoClaw anda melalui 17+ platform pemesejan: | **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) | -| **MaixCam** | Mudah (aktifkan) | TCP socket | [Panduan](../channels/maixcam/README.md) | -| **Pico** | Mudah (aktifkan) | Protokol natif | Terbina dalam | -| **Pico Client** | Mudah (URL WebSocket) | WebSocket | Terbina dalam | > 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 914e0feb..15fa1375 100644 --- a/docs/project/README.pt-br.md +++ b/docs/project/README.pt-br.md @@ -150,7 +150,6 @@ O PicoClaw pode ser implantado em praticamente qualquer dispositivo Linux! - $9,9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) edição E(Ethernet) ou W(WiFi6), para um assistente doméstico mínimo - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), ou $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), para operações automatizadas de servidor -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) ou $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), para vigilância inteligente @@ -378,9 +377,6 @@ Converse com seu PicoClaw por meio de mais de 17 plataformas de mensagens: | **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) | -| **MaixCam** | Fácil (habilitar) | TCP socket | [Guia](../channels/maixcam/README.pt-br.md) | -| **Pico** | Fácil (habilitar) | Protocolo nativo | Integrado | -| **Pico Client** | Fácil (WebSocket URL) | WebSocket | Integrado | > 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 15aceea1..52d1fd8e 100644 --- a/docs/project/README.vi.md +++ b/docs/project/README.vi.md @@ -150,7 +150,6 @@ PicoClaw có thể được triển khai trên hầu hết mọi thiết bị Li - $9.9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) phiên bản E(Ethernet) hoặc W(WiFi6), cho trợ lý gia đình tối giản - $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), hoặc $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), cho vận hành máy chủ tự động -- $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) hoặc $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), cho giám sát thông minh @@ -378,9 +377,6 @@ Trò chuyện với PicoClaw của bạn qua 17+ nền tảng nhắn tin: | **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) | -| **MaixCam** | Dễ (bật) | TCP socket | [Hướng dẫn](../channels/maixcam/README.vi.md) | -| **Pico** | Dễ (bật) | Native protocol | Tích hợp sẵn | -| **Pico Client** | Dễ (WebSocket URL) | WebSocket | Tích hợp sẵn | > 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 bf9fbe08..d8c8526e 100644 --- a/docs/project/README.zh.md +++ b/docs/project/README.zh.md @@ -150,7 +150,6 @@ PicoClaw 几乎可以部署在任何 Linux 设备上! - $9.9 [LicheeRV-Nano](https://item.taobao.com/item.htm?id=764939520376) E(网口) 或 W(WiFi6) 版本,用于极简家庭助手 - $30~50 [NanoKVM](https://item.taobao.com/item.htm?id=811206560480),或 $100 [NanoKVM-Pro](https://item.taobao.com/item.htm?id=994419942411),用于自动化服务器运维 -- $50 [MaixCAM](https://item.taobao.com/item.htm?id=784724795837) 或 $100 [MaixCAM2](https://item.taobao.com/item.htm?id=1050380368975),用于智能监控 @@ -379,9 +378,6 @@ PicoClaw 通过 `model_list` 配置支持 30+ LLM Provider,使用 `协议/模 | **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) | -| **MaixCam** | 简单(启用即可) | TCP socket | [指南](../channels/maixcam/README.zh.md) | -| **Pico** | 简单(启用即可) | 原生协议 | 内置 | -| **Pico Client** | 简单(WebSocket URL) | WebSocket | 内置 | > 所有基于 Webhook 的 Channel 共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`)。飞书使用 WebSocket/SDK 模式,不使用共享 HTTP 服务器。 diff --git a/examples/pico-echo-server/README.md b/examples/pico-echo-server/README.md deleted file mode 100644 index bca27ec8..00000000 --- a/examples/pico-echo-server/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# pico-echo-server - -Minimal Pico Protocol WebSocket server for testing the `pico_client` channel. - -## Usage - -```bash -go run ./examples/pico-echo-server -addr :9090 -token secret -``` - -### Flags - -| Flag | Default | Description | -|----------|---------|------------------------------------| -| `-addr` | `:9090` | Listen address | -| `-token` | (none) | Auth token; empty disables auth | - -## How it works - -- Listens for WebSocket connections at `/ws` -- Authenticates via `Authorization: Bearer ` header or `?token=` query param -- Prints received `message.send` content to stdout -- Responds to `ping` with `pong` -- Lines typed into stdin are broadcast as `message.create` to all connected clients - -## Testing with pico_client - -1. Start the server: - ```bash - go run ./examples/pico-echo-server -token mytoken - ``` - -2. Configure `pico_client` in your `config.json`: - ```json - { - "channel_list": { - "pico_client": { - "enabled": true, - "url": "ws://localhost:9090/ws", - "token": "mytoken", - "session_id": "test-session" - } - } - } - ``` - -3. Start picoclaw — the client connects and you can exchange messages interactively via stdin/stdout. diff --git a/examples/pico-echo-server/main.go b/examples/pico-echo-server/main.go deleted file mode 100644 index 46970fb3..00000000 --- a/examples/pico-echo-server/main.go +++ /dev/null @@ -1,160 +0,0 @@ -// pico-echo-server is a minimal Pico Protocol WebSocket server for testing -// the pico_client channel. It accepts connections, prints received messages -// to stdout, and forwards stdin lines as message.create to all connected clients. -// -// Usage: -// -// go run ./examples/pico-echo-server -addr :9090 -token secret -// -// Then configure pico_client with url=ws://localhost:9090/ws&token=secret. -package main - -import ( - "bufio" - "encoding/json" - "flag" - "fmt" - "log" - "net/http" - "os" - "strings" - "sync" - "time" - - "github.com/gorilla/websocket" -) - -type picoMessage struct { - Type string `json:"type"` - ID string `json:"id,omitempty"` - SessionID string `json:"session_id,omitempty"` - Timestamp int64 `json:"timestamp,omitempty"` - Payload map[string]any `json:"payload,omitempty"` -} - -var upgrader = websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} - -type server struct { - token string - mu sync.Mutex - conns map[*websocket.Conn]string // conn → sessionID -} - -func (s *server) handleWS(w http.ResponseWriter, r *http.Request) { - if s.token != "" { - auth := r.Header.Get("Authorization") - if auth != "Bearer "+s.token { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - } - - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - log.Printf("upgrade: %v", err) - return - } - - sessionID := r.URL.Query().Get("session_id") - if sessionID == "" { - sessionID = fmt.Sprintf("sess-%d", time.Now().UnixMilli()) - } - - s.mu.Lock() - s.conns[conn] = sessionID - s.mu.Unlock() - - log.Printf("[+] client connected (session=%s)", sessionID) - - defer func() { - s.mu.Lock() - delete(s.conns, conn) - s.mu.Unlock() - conn.Close() - log.Printf("[-] client disconnected (session=%s)", sessionID) - }() - - for { - _, raw, err := conn.ReadMessage() - if err != nil { - if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) { - log.Printf("read error: %v", err) - } - return - } - - var msg picoMessage - if err := json.Unmarshal(raw, &msg); err != nil { - log.Printf("bad json: %v", err) - continue - } - - switch msg.Type { - case "ping": - pong := picoMessage{Type: "pong", ID: msg.ID, Timestamp: time.Now().UnixMilli()} - conn.WriteJSON(pong) - - case "message.send": - content, _ := msg.Payload["content"].(string) - fmt.Printf("[%s] %s\n", sessionID, content) - - case "typing.start": - log.Printf("[%s] typing...", sessionID) - - case "typing.stop": - log.Printf("[%s] stopped typing", sessionID) - - default: - log.Printf("[%s] unknown type: %s", sessionID, msg.Type) - } - } -} - -func (s *server) broadcast(content string) { - msg := picoMessage{ - Type: "message.create", - Timestamp: time.Now().UnixMilli(), - Payload: map[string]any{"content": content}, - } - - s.mu.Lock() - defer s.mu.Unlock() - - for conn, sid := range s.conns { - msg.SessionID = sid - if err := conn.WriteJSON(msg); err != nil { - log.Printf("write to %s failed: %v", sid, err) - } - } -} - -func main() { - addr := flag.String("addr", ":9090", "listen address") - token := flag.String("token", "", "auth token (empty = no auth)") - flag.Parse() - - s := &server{ - token: *token, - conns: make(map[*websocket.Conn]string), - } - - http.HandleFunc("/ws", s.handleWS) - - log.Printf("listening on %s", *addr) - log.Printf("connect with: ws://localhost%s/ws", *addr) - fmt.Println("Type messages to send to connected clients (Ctrl+C to quit):") - - go func() { - scanner := bufio.NewScanner(os.Stdin) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if line == "" { - continue - } - s.broadcast(line) - log.Printf("[server] sent: %s", line) - } - }() - - log.Fatal(http.ListenAndServe(*addr, nil)) -} diff --git a/pkg/agent/agent.go b/pkg/agent/agent.go index 69ad09d0..5dc0621b 100644 --- a/pkg/agent/agent.go +++ b/pkg/agent/agent.go @@ -103,7 +103,7 @@ type processOptions struct { DefaultResponse string // Response when LLM returns empty EnableSummary bool // Whether to trigger summarization SendResponse bool // Whether to send response via bus - AllowInterimPicoPublish bool // Whether pico tool-call interim text can be published when SendResponse is false + AllowStreaming bool // Whether streaming output is allowed when SendResponse is false SuppressToolFeedback bool // Whether to suppress inline tool feedback messages NoHistory bool // If true, don't load session history (for heartbeat) SkipInitialSteeringPoll bool // If true, skip the steering poll at loop start (used by Continue) @@ -126,11 +126,8 @@ const ( pendingTurnPrefix = "pending-" providerReloadGracePeriod = 30 * time.Second metadataKeyMessageKind = "message_kind" - metadataKeyToolCalls = "tool_calls" metadataKeyOutboundKind = "outbound_kind" - messageKindThought = "thought" messageKindToolFeedback = "tool_feedback" - messageKindToolCalls = "tool_calls" outboundKindFinal = "final" outboundKindCommandReply = "command_reply" metadataKeyAccountID = "account_id" diff --git a/pkg/agent/agent_message.go b/pkg/agent/agent_message.go index c445f5fb..284f4637 100644 --- a/pkg/agent/agent_message.go +++ b/pkg/agent/agent_message.go @@ -186,12 +186,12 @@ func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage) UserMessage: msg.Content, Media: append([]string(nil), msg.Media...), }, - SenderID: msg.SenderID, - SenderDisplayName: msg.Sender.DisplayName, - DefaultResponse: defaultResponse, - EnableSummary: true, - SendResponse: false, - AllowInterimPicoPublish: true, + SenderID: msg.SenderID, + SenderDisplayName: msg.Sender.DisplayName, + DefaultResponse: defaultResponse, + EnableSummary: true, + SendResponse: false, + AllowStreaming: true, } var err error opts, err = resolveTurnProfileOptions(al.GetConfig(), opts) diff --git a/pkg/agent/agent_outbound.go b/pkg/agent/agent_outbound.go index b19ea75a..749ab655 100644 --- a/pkg/agent/agent_outbound.go +++ b/pkg/agent/agent_outbound.go @@ -4,16 +4,12 @@ package agent import ( "context" - "encoding/json" "errors" - "strings" "time" "github.com/sipeed/picoclaw/pkg/bus" "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/providers" "github.com/sipeed/picoclaw/pkg/tools" - "github.com/sipeed/picoclaw/pkg/utils" ) func (al *AgentLoop) maybePublishError(ctx context.Context, channel, chatID, sessionKey string, err error) bool { @@ -101,154 +97,6 @@ func (al *AgentLoop) targetReasoningChannelID(channelName string) (chatID string return "" } -func (al *AgentLoop) publishPicoReasoning( - ctx context.Context, - reasoningContent, chatID, sessionKey, modelName string, -) { - if reasoningContent == "" || chatID == "" { - return - } - - if ctx.Err() != nil { - return - } - - pubCtx, pubCancel := context.WithTimeout(ctx, 5*time.Second) - defer pubCancel() - - raw := map[string]string{metadataKeyMessageKind: messageKindThought} - if trimmedModelName := strings.TrimSpace(modelName); trimmedModelName != "" { - raw["model_name"] = trimmedModelName - } - - if err := al.bus.PublishOutbound(pubCtx, bus.OutboundMessage{ - Context: bus.InboundContext{ - Channel: "pico", - ChatID: chatID, - Raw: raw, - }, - SessionKey: sessionKey, - Content: reasoningContent, - }); err != nil { - if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || - errors.Is(err, bus.ErrBusClosed) { - logger.DebugCF("agent", "Pico reasoning publish skipped (timeout/cancel)", map[string]any{ - "channel": "pico", - "error": err.Error(), - }) - } else { - logger.WarnCF("agent", "Failed to publish pico reasoning (best-effort)", map[string]any{ - "channel": "pico", - "error": err.Error(), - }) - } - } -} - -func (al *AgentLoop) publishPicoToolCallInterim( - ctx context.Context, - ts *turnState, - modelName string, - reasoningContent string, - content string, - toolCalls []providers.ToolCall, -) { - if ts == nil || ts.chatID == "" || al == nil || al.bus == nil { - return - } - - if strings.TrimSpace(reasoningContent) != "" { - pubCtx, pubCancel := context.WithTimeout(ctx, 3*time.Second) - err := al.bus.PublishOutbound( - pubCtx, - outboundMessageForTurnWithOptions( - ts, - reasoningContent, - outboundTurnMessageOptions{ - kind: messageKindThought, - modelName: modelName, - }, - ), - ) - pubCancel() - if err != nil && !errors.Is(err, context.DeadlineExceeded) && - !errors.Is(err, context.Canceled) && - !errors.Is(err, bus.ErrBusClosed) { - logger.WarnCF("agent", "Failed to publish pico reasoning", map[string]any{ - "channel": ts.channel, - "chat_id": ts.chatID, - "error": err.Error(), - }) - } - } - - if !ts.opts.AllowInterimPicoPublish { - return - } - - visibleToolCalls := utils.BuildVisibleToolCalls( - toolCalls, - al.cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength(), - ) - duplicateToolCallContent := len(visibleToolCalls) > 0 && - utils.ToolCallExplanationDuplicatesContent(content, toolCalls) - - if strings.TrimSpace(content) != "" && !duplicateToolCallContent { - pubCtx, pubCancel := context.WithTimeout(ctx, 3*time.Second) - err := al.bus.PublishOutbound( - pubCtx, - outboundMessageForTurnWithOptions(ts, content, outboundTurnMessageOptions{ - modelName: modelName, - }), - ) - pubCancel() - if err != nil && !errors.Is(err, context.DeadlineExceeded) && - !errors.Is(err, context.Canceled) && - !errors.Is(err, bus.ErrBusClosed) { - logger.WarnCF("agent", "Failed to publish pico interim assistant content", map[string]any{ - "channel": ts.channel, - "chat_id": ts.chatID, - "error": err.Error(), - }) - } - } - - if len(visibleToolCalls) == 0 { - return - } - - rawToolCalls, err := json.Marshal(visibleToolCalls) - if err != nil { - logger.WarnCF("agent", "Failed to serialize pico tool calls", map[string]any{ - "channel": ts.channel, - "chat_id": ts.chatID, - "error": err.Error(), - }) - return - } - - msg := outboundMessageForTurnWithOptions(ts, "", outboundTurnMessageOptions{ - kind: messageKindToolCalls, - modelName: modelName, - raw: map[string]string{ - metadataKeyToolCalls: string(rawToolCalls), - }, - }) - - pubCtx, pubCancel := context.WithTimeout(ctx, 3*time.Second) - err = al.bus.PublishOutbound(pubCtx, msg) - pubCancel() - if err != nil && !errors.Is(err, context.DeadlineExceeded) && - !errors.Is(err, context.Canceled) && - !errors.Is(err, bus.ErrBusClosed) { - logger.WarnCF("agent", "Failed to publish pico tool calls", map[string]any{ - "channel": ts.channel, - "chat_id": ts.chatID, - "error": err.Error(), - }) - } -} - func (al *AgentLoop) handleReasoning( ctx context.Context, reasoningContent, channelName, channelID string, diff --git a/pkg/agent/agent_test.go b/pkg/agent/agent_test.go index f96077e5..d79b0396 100644 --- a/pkg/agent/agent_test.go +++ b/pkg/agent/agent_test.go @@ -453,7 +453,7 @@ func TestPublishResponseIfNeeded_MarksFinalOutbound(t *testing.T) { defer cleanup() _ = provider - al.PublishResponseIfNeeded(context.Background(), "pico", "pico:session-1", "session-1", "final reply") + al.PublishResponseIfNeeded(context.Background(), "telegram", "telegram:session-1", "session-1", "final reply") select { case outbound := <-msgBus.OutboundChan(): @@ -471,32 +471,6 @@ func TestPublishResponseIfNeeded_MarksFinalOutbound(t *testing.T) { } } -func TestPublishPicoReasoningIncludesSessionKey(t *testing.T) { - al, _, msgBus, provider, cleanup := newTestAgentLoop(t) - defer cleanup() - _ = provider - - al.publishPicoReasoning(context.Background(), "reasoning", "pico-chat", "session-1", "") - - select { - case outbound := <-msgBus.OutboundChan(): - if outbound.Channel != "pico" || outbound.ChatID != "pico-chat" { - t.Fatalf("unexpected outbound target: %+v", outbound) - } - if outbound.Content != "reasoning" { - t.Fatalf("outbound content = %q, want reasoning", outbound.Content) - } - if outbound.SessionKey != "session-1" { - t.Fatalf("outbound session key = %q, want session-1", outbound.SessionKey) - } - if outbound.Context.Raw[metadataKeyMessageKind] != messageKindThought { - t.Fatalf("message kind = %q, want %q", outbound.Context.Raw[metadataKeyMessageKind], messageKindThought) - } - case <-time.After(time.Second): - t.Fatal("expected pico reasoning outbound") - } -} - func TestProcessMessage_IncludesCurrentSenderInDynamicContext(t *testing.T) { tmpDir, err := os.MkdirTemp("", "agent-test-*") if err != nil { @@ -566,7 +540,7 @@ func TestProcessMessage_DoesNotPassImplicitThinkingOffToCapableProvider(t *testi al := NewAgentLoop(cfg, bus.NewMessageBus(), provider) response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", ChatID: "chat-1", Content: "hello", })) @@ -602,7 +576,7 @@ func TestProcessMessage_PassesExplicitThinkingOffToCapableProvider(t *testing.T) al := NewAgentLoop(cfg, bus.NewMessageBus(), provider) response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", ChatID: "chat-1", Content: "hello", })) @@ -638,7 +612,7 @@ func TestProcessMessage_PassesExplicitThinkingOffToProviderWithoutThinkingCapabi al := NewAgentLoop(cfg, bus.NewMessageBus(), provider) response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", ChatID: "chat-1", Content: "hello", })) @@ -675,7 +649,7 @@ func TestProcessMessage_PassesDeepSeekThinkingLevelToThinkingCapableProvider(t * al := NewAgentLoop(cfg, bus.NewMessageBus(), provider) response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", ChatID: "chat-1", Content: "hello", })) @@ -714,8 +688,8 @@ func TestProcessMessage_SuppressesReasoningWhenThinkingOff(t *testing.T) { context.Background(), al.GetRegistry().GetDefaultAgent(), processOptions{ - SessionKey: "agent:main:pico:chat-1", - Channel: "pico", + SessionKey: "agent:main:telegram:chat-1", + Channel: "telegram", ChatID: "chat-1", UserMessage: "hello", SendResponse: false, @@ -767,9 +741,9 @@ func TestProcessMessage_BeforeLLMModelRewriteReevaluatesThinkingOff(t *testing.T } response, err := al.processMessage(context.Background(), bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", SenderID: "user1", - ChatID: "pico:test-session", + ChatID: "telegram:test-session", Content: "hello", }) if err != nil { @@ -814,14 +788,21 @@ func TestProcessMessage_BeforeLLMModelRewriteDoesNotLeakThinkingOff(t *testing.T msgBus := bus.NewMessageBus() provider := &reasoningOptionRecordingProvider{} al := NewAgentLoop(cfg, msgBus, provider) + + chManager, err := channels.NewManager(&config.Config{}, msgBus, nil) + if err != nil { + t.Fatalf("Failed to create channel manager: %v", err) + } + chManager.RegisterChannel("telegram", &fakeChannel{id: "reason-chat"}) + al.SetChannelManager(chManager) if err := al.MountHook(NamedHook("rewrite-model", modelRewriteHook{model: "plain-model"})); err != nil { t.Fatalf("MountHook failed: %v", err) } response, err := al.processMessage(context.Background(), bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", SenderID: "user1", - ChatID: "pico:test-session", + ChatID: "telegram:test-session", Content: "hello", }) if err != nil { @@ -2835,77 +2816,6 @@ func TestToolFeedbackArgsPreview_UsesJSONAndTruncates(t *testing.T) { } } -type picoInterleavedContentProvider struct { - calls int -} - -func (m *picoInterleavedContentProvider) Chat( - ctx context.Context, - messages []providers.Message, - tools []providers.ToolDefinition, - model string, - opts map[string]any, -) (*providers.LLMResponse, error) { - m.calls++ - if m.calls == 1 { - return &providers.LLMResponse{ - Content: "intermediate model text", - ToolCalls: []providers.ToolCall{{ - ID: "call_tool_limit_test", - Type: "function", - Name: "tool_limit_test_tool", - Arguments: map[string]any{"value": "x"}, - }}, - }, nil - } - - return &providers.LLMResponse{ - Content: "final model text", - ToolCalls: []providers.ToolCall{}, - }, nil -} - -func (m *picoInterleavedContentProvider) GetDefaultModel() string { - return "pico-interleaved-content-model" -} - -type picoDistinctToolCallContentProvider struct { - calls int -} - -func (m *picoDistinctToolCallContentProvider) Chat( - ctx context.Context, - messages []providers.Message, - tools []providers.ToolDefinition, - model string, - opts map[string]any, -) (*providers.LLMResponse, error) { - m.calls++ - if m.calls == 1 { - return &providers.LLMResponse{ - Content: "intermediate model text", - ToolCalls: []providers.ToolCall{{ - ID: "call_tool_limit_test", - Type: "function", - Name: "tool_limit_test_tool", - Arguments: map[string]any{"value": "x"}, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: "Read the file before replying.", - }, - }}, - }, nil - } - - return &providers.LLMResponse{ - Content: "final model text", - ToolCalls: []providers.ToolCall{}, - }, nil -} - -func (m *picoDistinctToolCallContentProvider) GetDefaultModel() string { - return "pico-distinct-tool-call-content-model" -} - type toolLimitOnlyProvider struct{} func (m *toolLimitOnlyProvider) Chat( @@ -5623,7 +5533,7 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) { "telegram": "rid-telegram", "feishu": "rid-feishu", "discord": "rid-discord", - "maixcam": "rid-maixcam", + "mqtt": "rid-mqtt", "qq": "rid-qq", "dingtalk": "rid-dingtalk", "slack": "rid-slack", @@ -5642,7 +5552,7 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) { {channel: "telegram", wantID: "rid-telegram"}, {channel: "feishu", wantID: "rid-feishu"}, {channel: "discord", wantID: "rid-discord"}, - {channel: "maixcam", wantID: "rid-maixcam"}, + {channel: "mqtt", wantID: "rid-mqtt"}, {channel: "qq", wantID: "rid-qq"}, {channel: "dingtalk", wantID: "rid-dingtalk"}, {channel: "slack", wantID: "rid-slack"}, @@ -5892,66 +5802,6 @@ func TestProcessMessage_PublishesReasoningContentToReasoningChannel(t *testing.T } } -func TestProcessMessage_PicoPublishesReasoningAsThoughtMessage(t *testing.T) { - tmpDir := t.TempDir() - cfg := &config.Config{ - Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{ - Workspace: tmpDir, - ModelName: "test-model", - MaxTokens: 4096, - MaxToolIterations: 10, - }, - }, - } - - msgBus := bus.NewMessageBus() - provider := &reasoningContentProvider{ - response: "final answer", - reasoningContent: "thinking trace", - } - al := NewAgentLoop(cfg, msgBus, provider) - - response, err := al.processMessage(context.Background(), bus.InboundMessage{ - Channel: "pico", - SenderID: "user1", - ChatID: "pico:test-session", - Content: "hello", - }) - if err != nil { - t.Fatalf("processMessage() error = %v", err) - } - if response != "final answer" { - t.Fatalf("processMessage() response = %q, want %q", response, "final answer") - } - - var thoughtMsg *bus.OutboundMessage - deadline := time.After(3 * time.Second) - - for thoughtMsg == nil { - select { - case outbound := <-msgBus.OutboundChan(): - msg := outbound - if msg.Content == "thinking trace" { - thoughtMsg = &msg - } - case <-deadline: - t.Fatal("expected thought outbound message for pico") - } - } - - if thoughtMsg.Channel != "pico" || thoughtMsg.ChatID != "pico:test-session" { - t.Fatalf("thought message route = %s/%s, want pico/pico:test-session", thoughtMsg.Channel, thoughtMsg.ChatID) - } - if thoughtMsg.Context.Raw[metadataKeyMessageKind] != messageKindThought { - t.Fatalf( - "thought metadata kind = %q, want %q", - thoughtMsg.Context.Raw[metadataKeyMessageKind], - messageKindThought, - ) - } -} - func TestProcessHeartbeat_DoesNotPublishToolFeedback(t *testing.T) { tmpDir := t.TempDir() heartbeatFile := filepath.Join(tmpDir, "heartbeat-task.txt") @@ -6107,9 +5957,9 @@ func TestProcessMessage_PersistsReasoningContentInSessionHistory(t *testing.T) { al := NewAgentLoop(cfg, msgBus, provider) response, err := al.processMessage(context.Background(), bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", SenderID: "user1", - ChatID: "pico:test-session", + ChatID: "telegram:test-session", Content: "hello", }) if err != nil { @@ -6440,224 +6290,6 @@ func TestProcessMessage_MessageToolPublishesOutboundWithTurnMetadata(t *testing. } } -func TestRun_PicoPublishesAssistantContentDuringToolCallsWithoutFinalDuplicate(t *testing.T) { - tmpDir := t.TempDir() - - cfg := &config.Config{ - Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{ - Workspace: tmpDir, - ModelName: "test-model", - MaxTokens: 4096, - MaxToolIterations: 10, - }, - }, - } - - msgBus := bus.NewMessageBus() - provider := &picoDistinctToolCallContentProvider{} - al := NewAgentLoop(cfg, msgBus, provider) - - agent := al.GetRegistry().GetDefaultAgent() - if agent == nil { - t.Fatal("expected default agent") - } - agent.Tools.Register(&toolLimitTestTool{}) - - runCtx, runCancel := context.WithCancel(context.Background()) - defer runCancel() - - runDone := make(chan error, 1) - go func() { - runDone <- al.Run(runCtx) - }() - - if err := msgBus.PublishInbound(context.Background(), bus.InboundMessage{ - Channel: "pico", - SenderID: "user-1", - ChatID: "session-1", - Content: "run with tools", - }); err != nil { - t.Fatalf("PublishInbound() error = %v", err) - } - - outputs := make([]bus.OutboundMessage, 0, 3) - deadline := time.After(2 * time.Second) - for len(outputs) < 3 { - select { - case outbound := <-msgBus.OutboundChan(): - outputs = append(outputs, outbound) - case <-deadline: - t.Fatalf("timed out waiting for pico outputs, got %v", outputs) - } - } - - if outputs[0].Content != "intermediate model text" { - t.Fatalf("first outbound content = %q, want %q", outputs[0].Content, "intermediate model text") - } - if outputs[1].Context.Raw[metadataKeyMessageKind] != messageKindToolCalls { - t.Fatalf("second outbound = %+v, want tool_calls message", outputs[1]) - } - if !strings.Contains(outputs[1].Context.Raw[metadataKeyToolCalls], "tool_limit_test_tool") { - t.Fatalf("second outbound tool_calls = %q, want tool name", outputs[1].Context.Raw[metadataKeyToolCalls]) - } - if outputs[2].Content != "final model text" { - t.Fatalf("third outbound content = %q, want %q", outputs[2].Content, "final model text") - } - - runCancel() - select { - case err := <-runDone: - if err != nil { - t.Fatalf("Run() error = %v", err) - } - case <-time.After(2 * time.Second): - t.Fatal("timed out waiting for Run() to exit") - } - - select { - case outbound := <-msgBus.OutboundChan(): - if outbound.Content == "final model text" { - t.Fatalf("unexpected duplicate final pico output: %+v", outbound) - } - case <-time.After(200 * time.Millisecond): - } -} - -func TestRunAgentLoop_PicoSkipsInterimPublishWhenNotAllowed(t *testing.T) { - tmpDir := t.TempDir() - - cfg := &config.Config{ - Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{ - Workspace: tmpDir, - ModelName: "test-model", - MaxTokens: 4096, - MaxToolIterations: 10, - }, - }, - } - - msgBus := bus.NewMessageBus() - provider := &picoInterleavedContentProvider{} - al := NewAgentLoop(cfg, msgBus, provider) - - agent := al.GetRegistry().GetDefaultAgent() - if agent == nil { - t.Fatal("expected default agent") - } - agent.Tools.Register(&toolLimitTestTool{}) - - response, err := al.runAgentLoop(context.Background(), agent, processOptions{ - SessionKey: "agent:main:pico:session-1", - Channel: "pico", - ChatID: "session-1", - UserMessage: "run with tools", - DefaultResponse: defaultResponse, - EnableSummary: false, - SendResponse: false, - AllowInterimPicoPublish: false, - SuppressToolFeedback: true, - }) - if err != nil { - t.Fatalf("runAgentLoop() error = %v", err) - } - if response != "final model text" { - t.Fatalf("runAgentLoop() response = %q, want %q", response, "final model text") - } - - select { - case outbound := <-msgBus.OutboundChan(): - t.Fatalf("unexpected outbound message when interim publish disabled: %+v", outbound) - case <-time.After(200 * time.Millisecond): - } -} - -func TestRun_PicoToolFeedbackSuppressesDuplicateInterimAssistantContent(t *testing.T) { - tmpDir := t.TempDir() - - cfg := &config.Config{ - Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{ - Workspace: tmpDir, - ModelName: "test-model", - MaxTokens: 4096, - MaxToolIterations: 10, - ToolFeedback: config.ToolFeedbackConfig{ - Enabled: true, - }, - }, - }, - } - - msgBus := bus.NewMessageBus() - provider := &picoInterleavedContentProvider{} - al := NewAgentLoop(cfg, msgBus, provider) - - agent := al.GetRegistry().GetDefaultAgent() - if agent == nil { - t.Fatal("expected default agent") - } - agent.Tools.Register(&toolLimitTestTool{}) - - runCtx, runCancel := context.WithCancel(context.Background()) - defer runCancel() - - runDone := make(chan error, 1) - go func() { - runDone <- al.Run(runCtx) - }() - - if err := msgBus.PublishInbound(context.Background(), bus.InboundMessage{ - Channel: "pico", - SenderID: "user-1", - ChatID: "session-1", - Content: "run with tools", - }); err != nil { - t.Fatalf("PublishInbound() error = %v", err) - } - - outputs := make([]bus.OutboundMessage, 0, 3) - deadline := time.After(2 * time.Second) - for len(outputs) < 2 { - select { - case outbound := <-msgBus.OutboundChan(): - outputs = append(outputs, outbound) - case <-deadline: - t.Fatalf("timed out waiting for pico outputs, got %v", outputs) - } - } - - if outputs[0].Context.Raw[metadataKeyMessageKind] != messageKindToolCalls { - t.Fatalf("first outbound = %+v, want tool_calls message", outputs[0]) - } - if outputs[0].Content != "" { - t.Fatalf("first outbound content = %q, want empty tool_calls content", outputs[0].Content) - } - if !strings.Contains(outputs[0].Context.Raw[metadataKeyToolCalls], "tool_limit_test_tool") { - t.Fatalf("first outbound tool_calls = %q, want tool name", outputs[0].Context.Raw[metadataKeyToolCalls]) - } - if outputs[1].Content != "final model text" { - t.Fatalf("second outbound content = %q, want %q", outputs[1].Content, "final model text") - } - - runCancel() - select { - case err := <-runDone: - if err != nil { - t.Fatalf("Run() error = %v", err) - } - case <-time.After(2 * time.Second): - t.Fatal("timed out waiting for Run() to exit") - } - - select { - case outbound := <-msgBus.OutboundChan(): - t.Fatalf("unexpected extra pico output after tool feedback + final reply: %+v", outbound) - case <-time.After(200 * time.Millisecond): - } -} - func TestResolveMediaRefs_ImageInjectsPathTag(t *testing.T) { store := media.NewFileMediaStore() dir := t.TempDir() @@ -7330,7 +6962,7 @@ func TestProcessMessage_NativeSearchHandlesHookClearingOptions(t *testing.T) { } response, err := al.processMessage(context.Background(), bus.InboundMessage{ - Channel: "pico", + Channel: "telegram", ChatID: "native-search-hook", Content: "search", }) diff --git a/pkg/agent/context_cache_test.go b/pkg/agent/context_cache_test.go index ef5e6c5d..20805912 100644 --- a/pkg/agent/context_cache_test.go +++ b/pkg/agent/context_cache_test.go @@ -717,7 +717,7 @@ func TestBuildMessages_IncludesMediaOnlyCurrentMessage(t *testing.T) { "", "", []string{"data:image/png;base64,abc123"}, - "pico", + "telegram", "chat-1", "", "", diff --git a/pkg/agent/pipeline_execute.go b/pkg/agent/pipeline_execute.go index 59e33317..1c3c3ffa 100644 --- a/pkg/agent/pipeline_execute.go +++ b/pkg/agent/pipeline_execute.go @@ -197,7 +197,7 @@ toolLoop: }, ) - if shouldPublishToolFeedback(al.cfg, ts) && ts.channel != "pico" { + if shouldPublishToolFeedback(al.cfg, ts) { toolFeedbackMaxLen := al.cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength() toolFeedbackExplanation := toolFeedbackExplanationForToolCall( exec.response, @@ -489,7 +489,7 @@ toolLoop: }, ) - if shouldPublishToolFeedback(al.cfg, ts) && ts.channel != "pico" { + if shouldPublishToolFeedback(al.cfg, ts) { toolFeedbackMaxLen := al.cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength() toolFeedbackExplanation := toolFeedbackExplanationForToolCall( exec.response, diff --git a/pkg/agent/pipeline_finalize.go b/pkg/agent/pipeline_finalize.go index d42f1091..50821ad7 100644 --- a/pkg/agent/pipeline_finalize.go +++ b/pkg/agent/pipeline_finalize.go @@ -78,10 +78,10 @@ func (p *Pipeline) Finalize( contextUsage := computeContextUsage(ts.agent, ts.sessionKey) streamErr := finalizeConfiguredStreamingLLM(turnCtx, ts, exec, finalContent, contextUsage) - // If streaming never became visible, keep the legacy Pico interim publish path + // If streaming never became visible, publish the fallback answer // so the final answer is still delivered outside normal SendResponse. if ((streamErr != nil && !isConfiguredStreamingVisibleError(streamErr)) || exec.streamingFallback) && - !ts.opts.SendResponse && ts.opts.AllowInterimPicoPublish && finalContent != "" { + !ts.opts.SendResponse && ts.opts.AllowStreaming && finalContent != "" { msg := outboundMessageForTurnWithOptions(ts, finalContent, outboundTurnMessageOptions{ modelName: exec.llmModelName, }) diff --git a/pkg/agent/pipeline_llm.go b/pkg/agent/pipeline_llm.go index acea5e23..c760a70b 100644 --- a/pkg/agent/pipeline_llm.go +++ b/pkg/agent/pipeline_llm.go @@ -551,33 +551,12 @@ func (p *Pipeline) CallLLM( exec.response.ReasoningDetails = nil } reasoningContent := responseReasoningContent(exec.response) - shouldPublishPicoToolCallInterim := ts.channel == "pico" && len(exec.response.ToolCalls) > 0 - if shouldPublishPicoToolCallInterim { - // Pico tool-call turns publish their reasoning/content/tool summary as a - // structured sequence after the tool-call payload is normalized below. - } else if ts.channel == "pico" { - if exec.streamingPublisher != nil && exec.streamingPublisher.ReasoningPublished() { - if err := exec.streamingPublisher.FinalizeReasoning(turnCtx, reasoningContent); err != nil { - logger.WarnCF("agent", "Failed to finalize streamed pico reasoning", map[string]any{ - "channel": ts.channel, - "chat_id": ts.chatID, - "error": err.Error(), - }) - } - } else { - // Publish pico thoughts before the turn context is canceled at return time. - // The async variant can race with turn teardown and intermittently drop the - // thought message in CI even though the LLM produced reasoning content. - al.publishPicoReasoning(turnCtx, reasoningContent, ts.chatID, ts.sessionKey, exec.llmModelName) - } - } else { - go al.handleReasoning( - turnCtx, - reasoningContent, - ts.channel, - al.targetReasoningChannelID(ts.channel), - ) - } + go al.handleReasoning( + turnCtx, + reasoningContent, + ts.channel, + al.targetReasoningChannelID(ts.channel), + ) al.emitEvent( runtimeevents.KindAgentLLMResponse, ts.eventMeta("runTurn", "turn.llm.response"), @@ -607,7 +586,7 @@ func (p *Pipeline) CallLLM( // No-tool-call path: steering check and direct response if len(exec.response.ToolCalls) == 0 || exec.gracefulTerminal { responseContent := exec.response.Content - if responseContent == "" && exec.response.ReasoningContent != "" && ts.channel != "pico" { + if responseContent == "" && exec.response.ReasoningContent != "" { responseContent = exec.response.ReasoningContent } if steerMsgs := al.dequeueSteeringMessagesForScope(ts.sessionKey); len(steerMsgs) > 0 { @@ -695,16 +674,6 @@ func (p *Pipeline) CallLLM( ts.recordPersistedMessage(assistantMsg) ts.ingestMessage(turnCtx, al, assistantMsg) } - if shouldPublishPicoToolCallInterim { - al.publishPicoToolCallInterim( - turnCtx, - ts, - exec.llmModelName, - reasoningContent, - exec.response.Content, - assistantMsg.ToolCalls, - ) - } return ControlToolLoop, nil } diff --git a/pkg/agent/pipeline_streaming.go b/pkg/agent/pipeline_streaming.go index 5457e472..f5f853a5 100644 --- a/pkg/agent/pipeline_streaming.go +++ b/pkg/agent/pipeline_streaming.go @@ -274,7 +274,7 @@ func (p *Pipeline) configuredStreamingEligible(ts *turnState, exec *turnExecutio }) return false } - if !ts.opts.SendResponse && !ts.opts.AllowInterimPicoPublish { + if !ts.opts.SendResponse && !ts.opts.AllowStreaming { logger.DebugCF("agent", "configured streaming not used", map[string]any{ "agent_id": ts.agent.ID, "channel": ts.channel, @@ -370,14 +370,13 @@ func streamingConfigFromDecodedSettings(decoded any) (config.StreamingConfig, bo } type streamingChunkPublisher struct { - streamer bus.Streamer - channel string - chatID string - modelName string - published bool - reasoningPublished bool - err error - ts *turnState + streamer bus.Streamer + channel string + chatID string + modelName string + published bool + err error + ts *turnState } func (p *streamingChunkPublisher) Update(ctx context.Context, accumulated string) { @@ -419,17 +418,12 @@ func (p *streamingChunkPublisher) UpdateReasoning(ctx context.Context, accumulat }) return } - p.reasoningPublished = true } func (p *streamingChunkPublisher) Published() bool { return p != nil && p.published } -func (p *streamingChunkPublisher) ReasoningPublished() bool { - return p != nil && p.reasoningPublished -} - func (p *streamingChunkPublisher) Err() error { if p == nil { return nil @@ -465,20 +459,6 @@ func (p *streamingChunkPublisher) Finalize(ctx context.Context, content string, return nil } -func (p *streamingChunkPublisher) FinalizeReasoning(ctx context.Context, content string) error { - if p == nil || p.streamer == nil || !p.reasoningPublished || strings.TrimSpace(content) == "" { - return nil - } - reasoningStreamer, ok := p.streamer.(bus.ReasoningStreamer) - if !ok { - return nil - } - if err := reasoningStreamer.FinalizeReasoning(ctx, content); err != nil { - return fmt.Errorf("stream reasoning finalize: %w", err) - } - return nil -} - func (p *streamingChunkPublisher) ClearFinalizedStreamMarker() { if p == nil || p.streamer == nil { return diff --git a/pkg/agent/pipeline_streaming_test.go b/pkg/agent/pipeline_streaming_test.go index 9bba1b90..e4eeca75 100644 --- a/pkg/agent/pipeline_streaming_test.go +++ b/pkg/agent/pipeline_streaming_test.go @@ -288,7 +288,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }{ { name: "channel and model enabled streams", - channel: "pico", + channel: "telegram", channelStreaming: true, modelStreaming: true, streamingProvider: true, @@ -306,7 +306,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }, { name: "channel disabled uses chat", - channel: "pico", + channel: "telegram", modelStreaming: true, streamingProvider: true, streamDelegate: true, @@ -314,7 +314,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }, { name: "model disabled uses chat", - channel: "pico", + channel: "telegram", channelStreaming: true, streamingProvider: true, streamDelegate: true, @@ -322,7 +322,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }, { name: "provider without streaming uses chat", - channel: "pico", + channel: "telegram", channelStreaming: true, modelStreaming: true, streamDelegate: true, @@ -330,7 +330,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }, { name: "multi candidate fallback uses chat", - channel: "pico", + channel: "telegram", channelStreaming: true, modelStreaming: true, fallbacks: []string{"fallback-model"}, @@ -340,7 +340,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }, { name: "missing streamer uses chat", - channel: "pico", + channel: "telegram", channelStreaming: true, modelStreaming: true, streamingProvider: true, @@ -348,7 +348,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) { }, { name: "omitted fields use chat", - channel: "pico", + channel: "telegram", streamingProvider: true, streamDelegate: true, wantChatCalls: 1, @@ -398,7 +398,7 @@ func TestConfiguredStreamingPreChunkFailureFallsBackToChat(t *testing.T) { } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "chat after stream failure" { t.Fatalf("response = %q, want chat fallback response", got) @@ -429,9 +429,9 @@ func TestConfiguredStreamingDisabledForInternalTurnWithoutUserVisibleOutput(t *t chatResponse: &providers.LLMResponse{Content: "chat response"}, } al := NewAgentLoop(cfg, msgBus, provider) - opts := configuredStreamingProcessOptions("pico") + opts := configuredStreamingProcessOptions("telegram") opts.SendResponse = false - opts.AllowInterimPicoPublish = false + opts.AllowStreaming = false got, err := al.runAgentLoop(context.Background(), al.GetRegistry().GetDefaultAgent(), opts) if err != nil { @@ -461,7 +461,7 @@ func TestConfiguredStreamingVisibleSendResponseFalseRetainsFinalizedStreamMarker } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "stream response" { t.Fatalf("response = %q, want stream response", got) @@ -471,7 +471,7 @@ func TestConfiguredStreamingVisibleSendResponseFalseRetainsFinalizedStreamMarker } } -func TestConfiguredStreamingStreamsPicoReasoningBeforeAnswerContent(t *testing.T) { +func TestConfiguredStreamingStreamsReasoningBeforeAnswerContent(t *testing.T) { cfg := newConfiguredStreamingTestConfig(t, true, true, nil) streamer := &recordingStreamer{} msgBus := bus.NewMessageBus() @@ -491,7 +491,7 @@ func TestConfiguredStreamingStreamsPicoReasoningBeforeAnswerContent(t *testing.T } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "answer" { t.Fatalf("response = %q, want answer", got) } @@ -517,7 +517,7 @@ func TestConfiguredStreamingStreamsPicoReasoningBeforeAnswerContent(t *testing.T } } -func TestConfiguredStreamingSuppressesPicoReasoningWhenThinkingOff(t *testing.T) { +func TestConfiguredStreamingSuppressesReasoningWhenThinkingOff(t *testing.T) { cfg := newConfiguredStreamingTestConfig(t, true, true, nil) cfg.ModelList[0].ThinkingLevel = "off" streamer := &recordingStreamer{} @@ -537,7 +537,7 @@ func TestConfiguredStreamingSuppressesPicoReasoningWhenThinkingOff(t *testing.T) } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "answer" { t.Fatalf("response = %q, want answer", got) } @@ -573,7 +573,7 @@ func TestConfiguredStreamingFinalFlushFailureAfterVisibleOutputReturnsErrorWitho _, err := al.runAgentLoop( context.Background(), al.GetRegistry().GetDefaultAgent(), - configuredStreamingProcessOptions("pico"), + configuredStreamingProcessOptions("telegram"), ) if err == nil { t.Fatal("expected final flush failure after visible output to return an error") @@ -600,7 +600,7 @@ func TestConfiguredStreamingFinalFlushFailureBeforeVisibleOutputPublishesFallbac } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "stream response" { t.Fatalf("response = %q, want stream response", got) @@ -632,7 +632,7 @@ func TestConfiguredStreamingFinalFlushFailureBeforeVisibleOutputKeepsNormalOutbo }}, } al := NewAgentLoop(cfg, msgBus, provider) - opts := configuredStreamingProcessOptions("pico") + opts := configuredStreamingProcessOptions("telegram") opts.SendResponse = true got, err := al.runAgentLoop(context.Background(), al.GetRegistry().GetDefaultAgent(), opts) @@ -669,7 +669,7 @@ func TestConfiguredStreamingUpdateFailureThenStreamErrorFallsBackToChat(t *testi } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "chat fallback after invisible update" { t.Fatalf("response = %q, want chat fallback", got) @@ -704,7 +704,7 @@ func TestConfiguredStreamingUpdateFailureThenStreamSuccessFallsBackToChat(t *tes } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "chat fallback after invisible update" { t.Fatalf("response = %q, want chat fallback", got) @@ -742,7 +742,7 @@ func TestConfiguredStreamingLaterUpdateFailureThenStreamSuccessReturnsVisibleErr _, err := al.runAgentLoop( context.Background(), al.GetRegistry().GetDefaultAgent(), - configuredStreamingProcessOptions("pico"), + configuredStreamingProcessOptions("telegram"), ) if err == nil { t.Fatal("expected post-visible update failure to return an error") @@ -815,7 +815,7 @@ func TestConfiguredStreamingBeforeLLMModelRewriteReevaluatesModelStreaming(t *te t.Fatalf("MountHook() error = %v", err) } - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if provider.streamCalls != tt.wantStreamCalls { t.Fatalf("ChatStream calls = %d, want %d", provider.streamCalls, tt.wantStreamCalls) @@ -860,7 +860,7 @@ func TestConfiguredStreamingPostChunkFailureDoesNotFallBackToChat(t *testing.T) _, err := al.runAgentLoop( context.Background(), al.GetRegistry().GetDefaultAgent(), - configuredStreamingProcessOptions("pico"), + configuredStreamingProcessOptions("telegram"), ) if err == nil { t.Fatal("expected post-chunk stream failure to return an error") @@ -893,7 +893,7 @@ func TestConfiguredStreamingPostChunkEOFDoesNotRetryOrCancelVisibleOutput(t *tes _, err := al.runAgentLoop( context.Background(), al.GetRegistry().GetDefaultAgent(), - configuredStreamingProcessOptions("pico"), + configuredStreamingProcessOptions("telegram"), ) if err == nil { t.Fatal("expected post-chunk EOF to return an error") @@ -927,7 +927,7 @@ func TestConfiguredStreamingFinalizesAfterAfterLLMHookMutation(t *testing.T) { t.Fatalf("MountHook() error = %v", err) } - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "hooked final response" { t.Fatalf("response = %q, want hook-modified response", got) @@ -968,7 +968,7 @@ func TestConfiguredStreamingAfterLLMAbortCancelsPublishedStream(t *testing.T) { _, _ = al.runAgentLoop( context.Background(), al.GetRegistry().GetDefaultAgent(), - configuredStreamingProcessOptions("pico"), + configuredStreamingProcessOptions("telegram"), ) if streamer.canceled != 1 { @@ -994,7 +994,7 @@ func TestConfiguredStreamingFinalizesWithDefaultResponseWhenContentEmpty(t *test } al := NewAgentLoop(cfg, msgBus, provider) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != defaultResponse { t.Fatalf("response = %q, want default response", got) @@ -1032,7 +1032,7 @@ func TestConfiguredStreamingToolCallsUseCompleteStreamResponse(t *testing.T) { agent := al.GetRegistry().GetDefaultAgent() agent.Tools.Register(&toolLimitTestTool{}) - got := runConfiguredStreamingTurn(t, al, "pico") + got := runConfiguredStreamingTurn(t, al, "telegram") if got != "tool call handled" { t.Fatalf("response = %q, want tool call handled", got) @@ -1075,8 +1075,8 @@ func newConfiguredStreamingTestConfig( }, }, Channels: config.ChannelsConfig{ - "pico": newConfiguredStreamingPicoChannel(t, channelStreaming), - "wecom": newConfiguredStreamingWeComChannel(t, channelStreaming), + "telegram": newConfiguredStreamingTelegramChannel(t, channelStreaming), + "wecom": newConfiguredStreamingWeComChannel(t, channelStreaming), }, ModelList: []*config.ModelConfig{{ ModelName: "test-model", @@ -1120,22 +1120,22 @@ func newConfiguredStreamingWeComChannel(t *testing.T, enabled bool) *config.Chan } } -func newConfiguredStreamingPicoChannel(t *testing.T, enabled bool) *config.Channel { +func newConfiguredStreamingTelegramChannel(t *testing.T, enabled bool) *config.Channel { t.Helper() - settings := config.PicoSettings{ + settings := config.TelegramSettings{ Streaming: config.StreamingConfig{ Enabled: enabled, ThrottleSeconds: 1, MinGrowthChars: 40, }, } - settings.SetToken("test-token") + settings.Token = *config.NewSecureString("test-token") raw, err := json.Marshal(settings) if err != nil { t.Fatalf("Marshal settings error = %v", err) } return &config.Channel{ - Type: config.ChannelPico, + Type: config.ChannelTelegram, Enabled: true, Settings: config.RawNode(raw), } @@ -1143,15 +1143,15 @@ func newConfiguredStreamingPicoChannel(t *testing.T, enabled bool) *config.Chann func configuredStreamingProcessOptions(channel string) processOptions { return processOptions{ - SessionKey: "agent:main:" + channel + ":session-1", - Channel: channel, - ChatID: "session-1", - UserMessage: "hello", - DefaultResponse: defaultResponse, - EnableSummary: false, - SendResponse: false, - AllowInterimPicoPublish: true, - NoHistory: true, + SessionKey: "agent:main:" + channel + ":session-1", + Channel: channel, + ChatID: "session-1", + UserMessage: "hello", + DefaultResponse: defaultResponse, + EnableSummary: false, + SendResponse: false, + AllowStreaming: true, + NoHistory: true, } } diff --git a/pkg/agent/turn_profile_test.go b/pkg/agent/turn_profile_test.go index eb79d523..e26857b7 100644 --- a/pkg/agent/turn_profile_test.go +++ b/pkg/agent/turn_profile_test.go @@ -203,8 +203,8 @@ func TestTurnProfile_ProcessMessageUsesEnabledTurnProfile(t *testing.T) { _, err := al.processMessage(context.Background(), bus.InboundMessage{ Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:sess-1", + Channel: "telegram", + ChatID: "telegram:sess-1", ChatType: "direct", SenderID: "pico-user", }, @@ -251,8 +251,8 @@ func TestTurnProfile_BtwCommandUsesEnabledTurnProfile(t *testing.T) { _, err := al.processMessage(context.Background(), bus.InboundMessage{ Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:btw", + Channel: "telegram", + ChatID: "telegram:btw", ChatType: "direct", SenderID: "pico-user", }, @@ -313,8 +313,8 @@ func TestTurnProfile_BtwCommandDoesNotAddToolFallbackWhenSystemPromptOff(t *test _, err := al.processMessage(context.Background(), bus.InboundMessage{ Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:btw-system-off", + Channel: "telegram", + ChatID: "telegram:btw-system-off", ChatType: "direct", SenderID: "pico-user", }, @@ -361,8 +361,8 @@ func TestTurnProfile_BtwHookCannotReenableNativeSearchWhenToolsOff(t *testing.T) _, err := al.processMessage(context.Background(), bus.InboundMessage{ Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:btw-native-search", + Channel: "telegram", + ChatID: "telegram:btw-native-search", ChatType: "direct", SenderID: "pico-user", }, diff --git a/pkg/bus/bus_test.go b/pkg/bus/bus_test.go index 786d97fc..02688356 100644 --- a/pkg/bus/bus_test.go +++ b/pkg/bus/bus_test.go @@ -148,7 +148,7 @@ func TestPublishInbound_BackfillsContextFromLegacyFields(t *testing.T) { defer mb.Close() msg := InboundMessage{ - Channel: "pico", + Channel: "telegram", ChatID: "session-1", SenderID: "user-1", MessageID: "msg-1", @@ -160,7 +160,7 @@ func TestPublishInbound_BackfillsContextFromLegacyFields(t *testing.T) { } got := <-mb.InboundChan() - if got.Context.Channel != "pico" { + if got.Context.Channel != "telegram" { t.Fatalf("expected context channel pico, got %q", got.Context.Channel) } if got.Context.ChatID != "session-1" { diff --git a/pkg/channels/README.md b/pkg/channels/README.md index eef31a61..87f97dc3 100644 --- a/pkg/channels/README.md +++ b/pkg/channels/README.md @@ -60,7 +60,7 @@ pkg/channels/ ├── discord/ │ ├── init.go │ └── discord.go -├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ maixcam/ pico/ +├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/ │ └── ... pkg/bus/ @@ -767,9 +767,9 @@ if c.owner != nil && c.placeholderRecorder != nil { ``` **This means**: -- Channels implementing `TypingCapable` (Telegram, Discord, LINE, Pico) do not need to manually call `StartTyping` + `RecordTypingStop` in `handleMessage` +- 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 `PlaceholderCapable` (Telegram, Discord, Pico) do not need to manually send placeholder messages and call `RecordPlaceholder` 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) - `PlaceholderCapable`'s `SendPlaceholder` method internally decides whether to send based on the configured `PlaceholderConfig.Enabled`; returning `("", nil)` skips registration @@ -1234,7 +1234,7 @@ Timeout configuration: ReadTimeout = 30s, WriteTimeout = 30s 5. **Typing/Reaction/Placeholder is handled by BaseChannel + Manager automatically**: A channel's `Send` method does not need to manage Typing stop, Reaction undo, or Placeholder editing. `BaseChannel.HandleMessage` auto-triggers `TypingCapable`, `ReactionCapable`, and `PlaceholderCapable` on the inbound side (via `owner` type assertions); Manager's `preSend` auto-stops Typing, undoes Reaction, and edits Placeholder on the outbound side. Channels only need to implement the corresponding interfaces. -6. **Factory registration belongs in init()**: Each sub-package must have an `init.go` file calling `channels.RegisterFactory`. Gateway must trigger registration via blank imports (`_ "pkg/channels/xxx"`). +5. **Factory registration belongs in init()**: Each sub-package must have an `init.go` file calling `channels.RegisterFactory`. Gateway must trigger registration via blank imports (`_ "pkg/channels/xxx"`). ### 5.2 Metadata Field Usage Conventions @@ -1309,9 +1309,7 @@ make test # Full test suite | `pkg/channels/qq/` | `"qq"` | — | | `pkg/channels/whatsapp/` | `"whatsapp"` | — (Bridge mode) | | `pkg/channels/whatsapp_native/` | `"whatsapp_native"` | — (Native whatsmeow mode) | -| `pkg/channels/maixcam/` | `"maixcam"` | — | | `pkg/channels/mqtt/` | `"mqtt"` | — | -| `pkg/channels/pico/` | `"pico"` | TypingCapable, PlaceholderCapable, MessageEditor, WebhookHandler | ### A.3 Interface Quick Reference @@ -1423,12 +1421,10 @@ agentLoop.Stop() // Stop Agent 3. **WeCom is now a single channel**: `"wecom"` is implemented as a WebSocket-based AI Bot channel with route persistence. Access control uses the shared channel allowlist mechanism. It no longer exposes the legacy webhook/app split. -4. **Pico Protocol**: `pkg/channels/pico/` implements a custom PicoClaw native protocol channel that receives messages via WebSocket webhook (`/pico/ws`). +4. **WhatsApp has two modes**: `"whatsapp"` (Bridge mode, communicates via external bridge URL) and `"whatsapp_native"` (native whatsmeow mode, connects directly to WhatsApp). Manager selects which to initialize based on `WhatsAppConfig.UseNative`. -5. **WhatsApp has two modes**: `"whatsapp"` (Bridge mode, communicates via external bridge URL) and `"whatsapp_native"` (native whatsmeow mode, connects directly to WhatsApp). Manager selects which to initialize based on `WhatsAppConfig.UseNative`. +5. **DingTalk uses Stream mode**: DingTalk uses the SDK's Stream/WebSocket mode (not HTTP webhook), so it does not implement `WebhookHandler`. -6. **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. -7. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 6 channel configs (Telegram, Discord, Slack, LINE, OneBot, Pico), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram, Discord, Pico) can actually use placeholder message editing. The rest are reserved fields. - -8. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (WhatsApp, Telegram, Feishu, Discord, MaixCam, QQ, DingTalk, Slack, LINE, OneBot, WeCom). Note: `PicoConfig` does not currently expose this field. `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, Slack, 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 b9add6ff..bca465df 100644 --- a/pkg/channels/README.zh.md +++ b/pkg/channels/README.zh.md @@ -60,7 +60,7 @@ pkg/channels/ ├── discord/ │ ├── init.go │ └── discord.go -├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ maixcam/ pico/ +├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/ │ └── ... pkg/bus/ @@ -766,9 +766,9 @@ if c.owner != nil && c.placeholderRecorder != nil { ``` **这意味着**: -- 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE、Pico)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop` +- 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop` - 实现 `ReactionCapable` 的 channel(Slack、OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop` -- 实现 `PlaceholderCapable` 的 channel(Telegram、Discord、Pico)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder` +- 实现 `PlaceholderCapable` 的 channel(Telegram、Discord)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder` - Channel 只需实现对应接口,`HandleMessage` 会自动完成编排 - 不实现这些接口的 channel 不受影响(类型断言会失败,跳过) - `PlaceholderCapable` 的 `SendPlaceholder` 方法内部根据配置的 `PlaceholderConfig.Enabled` 决定是否发送;返回 `("", nil)` 时跳过注册 @@ -1232,7 +1232,7 @@ Manager 创建单一 `http.Server`,自动发现和注册: 5. **Typing/Reaction/Placeholder 由 BaseChannel + Manager 自动处理**:Channel 的 `Send` 方法不需要管理 Typing 停止、Reaction 撤销或 Placeholder 编辑。`BaseChannel.HandleMessage` 在入站侧自动触发 `TypingCapable`、`ReactionCapable` 和 `PlaceholderCapable`(通过 `owner` 类型断言);Manager 的 `preSend` 在出站侧自动停止 Typing、撤销 Reaction、编辑 Placeholder。Channel 只需实现对应接口即可。 -6. **工厂注册在 init() 中**:每个子包必须有 `init.go` 文件调用 `channels.RegisterFactory`。Gateway 必须通过 blank import(`_ "pkg/channels/xxx"`)触发注册。 +5. **工厂注册在 init() 中**:每个子包必须有 `init.go` 文件调用 `channels.RegisterFactory`。Gateway 必须通过 blank import(`_ "pkg/channels/xxx"`)触发注册。 ### 5.2 Metadata 字段使用约定 @@ -1307,9 +1307,7 @@ make test # 全量测试 | `pkg/channels/qq/` | `"qq"` | — | | `pkg/channels/whatsapp/` | `"whatsapp"` | — (Bridge 模式) | | `pkg/channels/whatsapp_native/` | `"whatsapp_native"` | — (原生 whatsmeow 模式) | -| `pkg/channels/maixcam/` | `"maixcam"` | — | | `pkg/channels/mqtt/` | `"mqtt"` | — | -| `pkg/channels/pico/` | `"pico"` | TypingCapable, PlaceholderCapable, MessageEditor, WebhookHandler | ### A.3 接口速查表 @@ -1421,12 +1419,10 @@ agentLoop.Stop() // 停止 Agent 3. **WeCom 现在只有一个 channel**:`"wecom"` 采用 WebSocket AI Bot 实现,带路由持久化;访问控制走统一的 channel 白名单机制,不再保留旧的 webhook/app 双分支。 -4. **Pico Protocol**:`pkg/channels/pico/` 实现了一个自定义的 PicoClaw 原生协议 channel,通过 WebSocket webhook (`/pico/ws`) 接收消息。 +4. **WhatsApp 有两种模式**:`"whatsapp"`(Bridge 模式,通过外部 bridge URL 通信)和 `"whatsapp_native"`(原生 whatsmeow 模式,直接连接 WhatsApp)。Manager 根据 `WhatsAppConfig.UseNative` 决定初始化哪个。 -5. **WhatsApp 有两种模式**:`"whatsapp"`(Bridge 模式,通过外部 bridge URL 通信)和 `"whatsapp_native"`(原生 whatsmeow 模式,直接连接 WhatsApp)。Manager 根据 `WhatsAppConfig.UseNative` 决定初始化哪个。 +5. **DingTalk 使用 Stream 模式**:DingTalk 使用 SDK 的 Stream/WebSocket 模式(非 HTTP webhook),因此不实现 `WebhookHandler`。 -6. **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` 为预留字段。 -7. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 6 个 channel config 中(Telegram、Discord、Slack、LINE、OneBot、Pico),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord、Pico)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。 - -8. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、MaixCam、QQ、DingTalk、Slack、LINE、OneBot、WeCom)。注意:`PicoConfig` 目前不包含该字段。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。 +7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、Slack、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。 diff --git a/pkg/channels/maixcam/init.go b/pkg/channels/maixcam/init.go deleted file mode 100644 index f2f7b910..00000000 --- a/pkg/channels/maixcam/init.go +++ /dev/null @@ -1,25 +0,0 @@ -package maixcam - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelMaixCam, - 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.MaixCamSettings) - if !ok { - return nil, channels.ErrSendFailed - } - return NewMaixCamChannel(bc, c, b) - }, - ) -} diff --git a/pkg/channels/maixcam/maixcam.go b/pkg/channels/maixcam/maixcam.go deleted file mode 100644 index b81206c5..00000000 --- a/pkg/channels/maixcam/maixcam.go +++ /dev/null @@ -1,291 +0,0 @@ -package maixcam - -import ( - "context" - "encoding/json" - "fmt" - "net" - "sync" - "time" - - "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 MaixCamChannel struct { - *channels.BaseChannel - config *config.MaixCamSettings - listener net.Listener - ctx context.Context - cancel context.CancelFunc - clients map[net.Conn]bool - clientsMux sync.RWMutex -} - -type MaixCamMessage struct { - Type string `json:"type"` - Tips string `json:"tips"` - Timestamp float64 `json:"timestamp"` - Data map[string]any `json:"data"` -} - -func NewMaixCamChannel( - bc *config.Channel, - cfg *config.MaixCamSettings, - bus *bus.MessageBus, -) (*MaixCamChannel, error) { - base := channels.NewBaseChannel( - "maixcam", - cfg, - bus, - bc.AllowFrom, - channels.WithReasoningChannelID(bc.ReasoningChannelID), - ) - - return &MaixCamChannel{ - BaseChannel: base, - config: cfg, - clients: make(map[net.Conn]bool), - }, nil -} - -func (c *MaixCamChannel) Start(ctx context.Context) error { - logger.InfoC("maixcam", "Starting MaixCam channel server") - - c.ctx, c.cancel = context.WithCancel(ctx) - - addr := fmt.Sprintf("%s:%d", c.config.Host, c.config.Port) - listener, err := net.Listen("tcp", addr) - if err != nil { - c.cancel() - return fmt.Errorf("failed to listen on %s: %w", addr, err) - } - - c.listener = listener - c.SetRunning(true) - - logger.InfoCF("maixcam", "MaixCam server listening", map[string]any{ - "host": c.config.Host, - "port": c.config.Port, - }) - - go c.acceptConnections() - - return nil -} - -func (c *MaixCamChannel) acceptConnections() { - logger.DebugC("maixcam", "Starting connection acceptor") - - for { - select { - case <-c.ctx.Done(): - logger.InfoC("maixcam", "Stopping connection acceptor") - return - default: - conn, err := c.listener.Accept() - if err != nil { - if c.IsRunning() { - logger.ErrorCF("maixcam", "Failed to accept connection", map[string]any{ - "error": err.Error(), - }) - } - return - } - - logger.InfoCF("maixcam", "New connection from MaixCam device", map[string]any{ - "remote_addr": conn.RemoteAddr().String(), - }) - - c.clientsMux.Lock() - c.clients[conn] = true - c.clientsMux.Unlock() - - go c.handleConnection(conn) - } - } -} - -func (c *MaixCamChannel) handleConnection(conn net.Conn) { - logger.DebugC("maixcam", "Handling MaixCam connection") - - defer func() { - conn.Close() - c.clientsMux.Lock() - delete(c.clients, conn) - c.clientsMux.Unlock() - logger.DebugC("maixcam", "Connection closed") - }() - - decoder := json.NewDecoder(conn) - - for { - select { - case <-c.ctx.Done(): - return - default: - var msg MaixCamMessage - if err := decoder.Decode(&msg); err != nil { - if err.Error() != "EOF" { - logger.ErrorCF("maixcam", "Failed to decode message", map[string]any{ - "error": err.Error(), - }) - } - return - } - - c.processMessage(msg, conn) - } - } -} - -func (c *MaixCamChannel) processMessage(msg MaixCamMessage, conn net.Conn) { - switch msg.Type { - case "person_detected": - c.handlePersonDetection(msg) - case "heartbeat": - logger.DebugC("maixcam", "Received heartbeat") - case "status": - c.handleStatusUpdate(msg) - default: - logger.WarnCF("maixcam", "Unknown message type", map[string]any{ - "type": msg.Type, - }) - } -} - -func (c *MaixCamChannel) handlePersonDetection(msg MaixCamMessage) { - logger.InfoCF("maixcam", "", map[string]any{ - "timestamp": msg.Timestamp, - "data": msg.Data, - }) - - senderID := "maixcam" - chatID := "default" - - classInfo, ok := msg.Data["class_name"].(string) - if !ok { - classInfo = "person" - } - - score, _ := msg.Data["score"].(float64) - x, _ := msg.Data["x"].(float64) - y, _ := msg.Data["y"].(float64) - w, _ := msg.Data["w"].(float64) - h, _ := msg.Data["h"].(float64) - - content := fmt.Sprintf("📷 Person detected!\nClass: %s\nConfidence: %.2f%%\nPosition: (%.0f, %.0f)\nSize: %.0fx%.0f", - classInfo, score*100, x, y, w, h) - - metadata := map[string]string{ - "timestamp": fmt.Sprintf("%.0f", msg.Timestamp), - "class_id": fmt.Sprintf("%.0f", msg.Data["class_id"]), - "score": fmt.Sprintf("%.2f", score), - "x": fmt.Sprintf("%.0f", x), - "y": fmt.Sprintf("%.0f", y), - "w": fmt.Sprintf("%.0f", w), - "h": fmt.Sprintf("%.0f", h), - } - - sender := bus.SenderInfo{ - Platform: "maixcam", - PlatformID: "maixcam", - CanonicalID: identity.BuildCanonicalID("maixcam", "maixcam"), - } - - if !c.IsAllowedSender(sender) { - return - } - - inboundCtx := bus.InboundContext{ - Channel: "maixcam", - ChatID: chatID, - ChatType: "channel", - SenderID: senderID, - Raw: metadata, - } - - c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, sender) -} - -func (c *MaixCamChannel) handleStatusUpdate(msg MaixCamMessage) { - logger.InfoCF("maixcam", "Status update from MaixCam", map[string]any{ - "status": msg.Data, - }) -} - -func (c *MaixCamChannel) Stop(ctx context.Context) error { - logger.InfoC("maixcam", "Stopping MaixCam channel") - c.SetRunning(false) - - // Cancel context first to signal goroutines to exit - if c.cancel != nil { - c.cancel() - } - - if c.listener != nil { - c.listener.Close() - } - - c.clientsMux.Lock() - defer c.clientsMux.Unlock() - - for conn := range c.clients { - conn.Close() - } - c.clients = make(map[net.Conn]bool) - - logger.InfoC("maixcam", "MaixCam channel stopped") - return nil -} - -func (c *MaixCamChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - - // Check ctx before entering write path - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - c.clientsMux.RLock() - defer c.clientsMux.RUnlock() - - if len(c.clients) == 0 { - logger.WarnC("maixcam", "No MaixCam devices connected") - return nil, fmt.Errorf("no connected MaixCam devices") - } - - response := map[string]any{ - "type": "command", - "timestamp": float64(0), - "message": msg.Content, - "chat_id": msg.ChatID, - } - - data, err := json.Marshal(response) - if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) - } - - var sendErr error - for conn := range c.clients { - _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) - if _, err := conn.Write(data); err != nil { - logger.ErrorCF("maixcam", "Failed to send to client", map[string]any{ - "client": conn.RemoteAddr().String(), - "error": err.Error(), - }) - sendErr = fmt.Errorf("maixcam send: %w", channels.ErrTemporary) - } - _ = conn.SetWriteDeadline(time.Time{}) - } - - return nil, sendErr -} diff --git a/pkg/channels/manager.go b/pkg/channels/manager.go index 339f740e..654ea379 100644 --- a/pkg/channels/manager.go +++ b/pkg/channels/manager.go @@ -1060,16 +1060,12 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe return bc, settings.Homeserver != "" && settings.UserID != "" && settings.AccessToken.String() != "" case *config.WeComSettings: return bc, settings.BotID != "" && settings.Secret.String() != "" - case *config.PicoClientSettings: - return bc, settings.URL != "" 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.PicoSettings: - return bc, settings.Token.String() != "" case *config.IRCSettings: return bc, settings.Server != "" case *config.LINESettings: @@ -1082,8 +1078,6 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe return bc, settings.Token.String() != "" case *config.FeishuSettings: return bc, settings.AppSecret.String() != "" - case *config.MaixCamSettings: - return bc, true case *config.TeamsWebhookSettings: return bc, true case *config.SlackWebhookSettings: diff --git a/pkg/channels/manager_channel.go b/pkg/channels/manager_channel.go index fb3d76e0..7f0cb3b7 100644 --- a/pkg/channels/manager_channel.go +++ b/pkg/channels/manager_channel.go @@ -46,10 +46,6 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) { return } switch key { - case "pico": - if settings, ok := v.(*config.PicoSettings); ok { - value["token"] = settings.Token.String() - } case "telegram": if settings, ok := v.(*config.TelegramSettings); ok { value["token"] = settings.Token.String() diff --git a/pkg/channels/pico/client.go b/pkg/channels/pico/client.go deleted file mode 100644 index 3551632e..00000000 --- a/pkg/channels/pico/client.go +++ /dev/null @@ -1,343 +0,0 @@ -package pico - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/google/uuid" - "github.com/gorilla/websocket" - - "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" -) - -// PicoClientChannel connects to a remote Pico Protocol WebSocket server. -type PicoClientChannel struct { - *channels.BaseChannel - config *config.PicoClientSettings - conn *picoConn - mu sync.Mutex - ctx context.Context - cancel context.CancelFunc -} - -// NewPicoClientChannel creates a new Pico Protocol client channel. -func NewPicoClientChannel( - bc *config.Channel, - cfg *config.PicoClientSettings, - messageBus *bus.MessageBus, -) (*PicoClientChannel, error) { - if cfg.URL == "" { - return nil, fmt.Errorf("pico_client url is required") - } - - base := channels.NewBaseChannel("pico_client", cfg, messageBus, bc.AllowFrom) - - return &PicoClientChannel{ - BaseChannel: base, - config: cfg, - }, nil -} - -// Start dials the remote server and begins reading. -func (c *PicoClientChannel) Start(ctx context.Context) error { - logger.InfoC("pico_client", "Starting Pico Client channel") - c.ctx, c.cancel = context.WithCancel(ctx) - - if err := c.dial(); err != nil { - c.cancel() - return fmt.Errorf("pico_client initial connect: %w", err) - } - - c.SetRunning(true) - go c.reconnectLoop() - - logger.InfoCF("pico_client", "Connected", map[string]any{"url": c.config.URL}) - return nil -} - -// Stop closes the connection. -func (c *PicoClientChannel) Stop(ctx context.Context) error { - logger.InfoC("pico_client", "Stopping Pico Client channel") - c.SetRunning(false) - if c.cancel != nil { - c.cancel() - } - c.mu.Lock() - if c.conn != nil { - c.conn.close() - } - c.mu.Unlock() - logger.InfoC("pico_client", "Pico Client channel stopped") - return nil -} - -func (c *PicoClientChannel) dial() error { - header := http.Header{} - if c.config.Token.String() != "" { - header.Set("Authorization", "Bearer "+c.config.Token.String()) - } - - ws, resp, err := websocket.DefaultDialer.DialContext(c.ctx, c.config.URL, header) - if resp != nil && resp.Body != nil { - _ = resp.Body.Close() - } - if err != nil { - return err - } - - connCtx, connCancel := context.WithCancel(c.ctx) - - pc := &picoConn{ - id: uuid.New().String(), - conn: ws, - sessionID: c.config.SessionID, - cancel: connCancel, - } - if pc.sessionID == "" { - pc.sessionID = uuid.New().String() - } - - c.mu.Lock() - c.conn = pc - c.mu.Unlock() - - go c.readLoop(connCtx, pc) - return nil -} - -// reconnectLoop re-dials when the connection drops. -func (c *PicoClientChannel) reconnectLoop() { - for { - select { - case <-c.ctx.Done(): - return - default: - } - - c.mu.Lock() - pc := c.conn - c.mu.Unlock() - - if pc == nil || pc.closed.Load() { - backoff := 5 * time.Second - logger.InfoC("pico_client", "Reconnecting...") - if err := c.dial(); err != nil { - logger.WarnCF("pico_client", "Reconnect failed", map[string]any{ - "error": err.Error(), - }) - select { - case <-c.ctx.Done(): - return - case <-time.After(backoff): - } - continue - } - logger.InfoC("pico_client", "Reconnected") - } - - select { - case <-c.ctx.Done(): - return - case <-time.After(1 * time.Second): - } - } -} - -func (c *PicoClientChannel) readLoop(connCtx context.Context, pc *picoConn) { - defer pc.close() - - readTimeout := time.Duration(c.config.ReadTimeout) * time.Second - if readTimeout <= 0 { - readTimeout = 60 * time.Second - } - - _ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout)) - pc.conn.SetPongHandler(func(string) error { - return pc.conn.SetReadDeadline(time.Now().Add(readTimeout)) - }) - - pingInterval := time.Duration(c.config.PingInterval) * time.Second - if pingInterval <= 0 { - pingInterval = 30 * time.Second - } - go c.pingLoop(connCtx, pc, pingInterval) - - for { - select { - case <-connCtx.Done(): - return - default: - } - - _, raw, err := pc.conn.ReadMessage() - if err != nil { - if websocket.IsUnexpectedCloseError( - err, - websocket.CloseGoingAway, - websocket.CloseNormalClosure, - ) { - logger.DebugCF("pico_client", "Read error", map[string]any{ - "error": err.Error(), - }) - } - return - } - - _ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout)) - - var msg PicoMessage - if err := json.Unmarshal(raw, &msg); err != nil { - continue - } - - c.handleInbound(pc, msg) - } -} - -func (c *PicoClientChannel) pingLoop(connCtx context.Context, pc *picoConn, interval time.Duration) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-connCtx.Done(): - return - case <-ticker.C: - if pc.closed.Load() { - return - } - pc.writeMu.Lock() - err := pc.conn.WriteMessage(websocket.PingMessage, nil) - pc.writeMu.Unlock() - if err != nil { - return - } - } - } -} - -// handleInbound processes messages from the remote server. -// In client mode the server sends message.create (responses) and the client -// sends message.send (user input). We treat message.create from the server -// as inbound user messages to feed into the agent loop. -func (c *PicoClientChannel) handleInbound(pc *picoConn, msg PicoMessage) { - switch msg.Type { - case TypePong: - // response to our ping, ignore - case TypeMessageCreate: - // Server sent us a message — treat as inbound - c.handleServerMessage(pc, msg) - case TypeMediaCreate: - c.handleServerMessage(pc, msg) - default: - logger.DebugCF("pico_client", "Ignoring message type", map[string]any{ - "type": msg.Type, - }) - } -} - -func (c *PicoClientChannel) handleServerMessage(pc *picoConn, msg PicoMessage) { - if isThoughtPayload(msg.Payload) { - return - } - - content, _ := msg.Payload[PayloadKeyContent].(string) - media, err := parseInlineImageMedia(msg.Payload) - if err != nil { - logger.WarnCF("pico_client", "Ignoring invalid media payload", map[string]any{ - "error": err.Error(), - }) - if strings.TrimSpace(content) == "" { - return - } - media = nil - } - if strings.TrimSpace(content) == "" && len(media) == 0 { - return - } - - sessionID := msg.SessionID - if sessionID == "" { - sessionID = pc.sessionID - } - - chatID := "pico_client:" + sessionID - senderID := "pico-remote" - sender := bus.SenderInfo{ - Platform: "pico_client", - PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID("pico_client", senderID), - } - - if !c.IsAllowedSender(sender) { - return - } - - inboundCtx := bus.InboundContext{ - Channel: "pico_client", - ChatID: chatID, - ChatType: "direct", - SenderID: senderID, - MessageID: msg.ID, - Raw: map[string]string{ - "platform": "pico_client", - "session_id": sessionID, - }, - } - - c.HandleInboundContext(c.ctx, chatID, content, media, inboundCtx, sender) -} - -// Send sends a message to the remote server. -func (c *PicoClientChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - c.mu.Lock() - pc := c.conn - c.mu.Unlock() - if pc == nil || pc.closed.Load() { - return nil, channels.ErrSendFailed - } - - outMsg := newMessage(TypeMessageSend, map[string]any{ - PayloadKeyContent: msg.Content, - }) - outMsg.SessionID = strings.TrimPrefix(msg.ChatID, "pico_client:") - return nil, pc.writeJSON(outMsg) -} - -// StartTyping implements channels.TypingCapable. -func (c *PicoClientChannel) StartTyping(ctx context.Context, chatID string) (func(), error) { - c.mu.Lock() - pc := c.conn - c.mu.Unlock() - if pc == nil || pc.closed.Load() { - return func() {}, nil - } - - startMsg := newMessage(TypeTypingStart, nil) - startMsg.SessionID = strings.TrimPrefix(chatID, "pico_client:") - if err := pc.writeJSON(startMsg); err != nil { - return func() {}, err - } - return func() { - c.mu.Lock() - currentPC := c.conn - c.mu.Unlock() - if currentPC == nil { - return - } - stopMsg := newMessage(TypeTypingStop, nil) - stopMsg.SessionID = strings.TrimPrefix(chatID, "pico_client:") - currentPC.writeJSON(stopMsg) - }, nil -} diff --git a/pkg/channels/pico/client_test.go b/pkg/channels/pico/client_test.go deleted file mode 100644 index ae604a75..00000000 --- a/pkg/channels/pico/client_test.go +++ /dev/null @@ -1,625 +0,0 @@ -package pico - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/gorilla/websocket" - - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func TestNewPicoClientChannel_MissingURL(t *testing.T) { - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - _, err := NewPicoClientChannel(bc, &config.PicoClientSettings{}, bus.NewMessageBus()) - if err == nil { - t.Fatal("expected error for missing URL") - } - if !strings.Contains(err.Error(), "url is required") { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestNewPicoClientChannel_OK(t *testing.T) { - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:9999/ws", - }, bus.NewMessageBus()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ch.Name() != "pico_client" { - t.Fatalf("name = %q, want pico_client", ch.Name()) - } -} - -func TestSend_NotRunning(t *testing.T) { - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:9999/ws", - }, bus.NewMessageBus()) - if err != nil { - t.Fatal(err) - } - _, err = ch.Send(context.Background(), bus.OutboundMessage{Content: "hi"}) - if !errors.Is(err, channels.ErrNotRunning) { - t.Fatalf("expected ErrNotRunning, got %v", err) - } -} - -// testServer starts a WS server that echoes message.send back as message.create. -func testServer(t *testing.T, token string) *httptest.Server { - t.Helper() - upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} - - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if token != "" { - auth := r.Header.Get("Authorization") - if auth != "Bearer "+token { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - } - - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("upgrade error: %v", err) - return - } - defer conn.Close() - - for { - _, raw, err := conn.ReadMessage() - if err != nil { - return - } - - var msg PicoMessage - if err := json.Unmarshal(raw, &msg); err != nil { - continue - } - - if msg.Type == TypeMessageSend { - reply := newMessage(TypeMessageCreate, msg.Payload) - reply.SessionID = msg.SessionID - if err := conn.WriteJSON(reply); err != nil { - return - } - } - } - })) -} - -func wsURL(httpURL string) string { - return "ws" + strings.TrimPrefix(httpURL, "http") -} - -func TestClientChannel_ConnectAndSend(t *testing.T) { - srv := testServer(t, "test-token") - defer srv.Close() - - mb := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: wsURL(srv.URL), - Token: *config.NewSecureString("test-token"), - SessionID: "sess-1", - PingInterval: 60, - ReadTimeout: 10, - }, mb) - if err != nil { - t.Fatal(err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - if err = ch.Start(ctx); err != nil { - t.Fatalf("Start: %v", err) - } - defer ch.Stop(ctx) - - // Send a message - _, err = ch.Send(ctx, bus.OutboundMessage{ - ChatID: "pico_client:sess-1", - Content: "hello", - }) - if err != nil { - t.Fatalf("Send: %v", err) - } -} - -func TestClientChannel_AuthFailure(t *testing.T) { - srv := testServer(t, "correct-token") - defer srv.Close() - - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: wsURL(srv.URL), - Token: *config.NewSecureString("wrong-token"), - }, bus.NewMessageBus()) - if err != nil { - t.Fatal(err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - err = ch.Start(ctx) - if err == nil { - ch.Stop(ctx) - t.Fatal("expected auth failure") - } -} - -func TestClientChannel_ReceivesServerMessage(t *testing.T) { - srv := testServer(t, "") - defer srv.Close() - - mb := bus.NewMessageBus() - - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: wsURL(srv.URL), - SessionID: "sess-echo", - ReadTimeout: 10, - }, mb) - if err != nil { - t.Fatal(err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - if err = ch.Start(ctx); err != nil { - t.Fatalf("Start: %v", err) - } - defer ch.Stop(ctx) - - // Send a message; the echo server replies with message.create - _, err = ch.Send(ctx, bus.OutboundMessage{ - ChatID: "pico_client:sess-echo", - Content: "ping", - }) - if err != nil { - t.Fatalf("Send: %v", err) - } - - // The echoed message.create is processed by handleServerMessage which - // calls HandleMessage → PublishInbound. Consume it from the bus. - select { - case msg := <-mb.InboundChan(): - if msg.Content != "ping" { - t.Fatalf("received = %q, want %q", msg.Content, "ping") - } - case <-ctx.Done(): - t.Fatal("timed out waiting for echoed message") - } -} - -func TestClientChannel_StartTyping(t *testing.T) { - srv := testServer(t, "") - defer srv.Close() - - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: wsURL(srv.URL), - SessionID: "sess-type", - ReadTimeout: 10, - }, bus.NewMessageBus()) - if err != nil { - t.Fatal(err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - if err = ch.Start(ctx); err != nil { - t.Fatalf("Start: %v", err) - } - defer ch.Stop(ctx) - - stop, err := ch.StartTyping(ctx, "pico_client:sess-type") - if err != nil { - t.Fatalf("StartTyping: %v", err) - } - stop() // should not panic -} - -func TestSend_ClosedConnection(t *testing.T) { - srv := testServer(t, "") - defer srv.Close() - - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: wsURL(srv.URL), - SessionID: "sess-close", - ReadTimeout: 10, - }, bus.NewMessageBus()) - if err != nil { - t.Fatal(err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - if err = ch.Start(ctx); err != nil { - t.Fatalf("Start: %v", err) - } - - // Force close the underlying connection - ch.mu.Lock() - ch.conn.close() - ch.mu.Unlock() - - _, err = ch.Send(ctx, bus.OutboundMessage{ - ChatID: "pico_client:sess-close", - Content: "should fail", - }) - if !errors.Is(err, channels.ErrSendFailed) { - t.Fatalf("expected ErrSendFailed, got %v", err) - } - - ch.Stop(ctx) -} - -func TestParseInlineImageMedia_Valid(t *testing.T) { - media, err := parseInlineImageMedia(map[string]any{ - "media": []any{ - "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=", - }, - }) - if err != nil { - t.Fatalf("parseInlineImageMedia() error = %v", err) - } - if len(media) != 1 { - t.Fatalf("len(media) = %d, want 1", len(media)) - } -} - -func TestParseInlineImageMedia_Attachments(t *testing.T) { - imageURL := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=" - media, err := parseInlineImageMedia(map[string]any{ - "attachments": []any{ - map[string]any{ - "type": "image", - "url": imageURL, - }, - }, - }) - if err != nil { - t.Fatalf("parseInlineImageMedia() error = %v", err) - } - if len(media) != 1 || media[0] != imageURL { - t.Fatalf("media = %#v, want attachment image payload", media) - } -} - -func TestPicoChannel_HandleMessageSend_AllowsMediaOnly(t *testing.T) { - mb := bus.NewMessageBus() - bc := &config.Channel{Type: "pico", Enabled: true} - ch, err := NewPicoChannel(bc, &config.PicoSettings{ - Token: *config.NewSecureString("test-token"), - }, mb) - if err != nil { - t.Fatalf("NewPicoChannel() error = %v", err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - if err := ch.Start(ctx); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(ctx) - - pc := &picoConn{id: "conn-1", sessionID: "sess-1"} - ch.handleMessageSend(pc, PicoMessage{ - ID: "msg-1", - Payload: map[string]any{ - "media": []any{ - "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=", - }, - }, - }) - - select { - case msg := <-mb.InboundChan(): - if msg.Content != "" { - t.Fatalf("msg.Content = %q, want empty", msg.Content) - } - if len(msg.Media) != 1 || !strings.HasPrefix(msg.Media[0], "data:image/png;base64,") { - t.Fatalf("msg.Media = %#v, want inline image payload", msg.Media) - } - case <-ctx.Done(): - t.Fatal("timed out waiting for inbound media message") - } -} - -func newTestPicoClientChannel(t *testing.T) (*PicoClientChannel, *bus.MessageBus) { - t.Helper() - - mb := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:8080/ws", - }, mb) - if err != nil { - t.Fatalf("NewPicoClientChannel() error = %v", err) - } - ch.ctx = context.Background() - - return ch, mb -} - -func assertInboundMessage( - t *testing.T, - mb *bus.MessageBus, - wantContent string, - wantMedia []string, - timeoutMessage string, -) { - t.Helper() - - select { - case msg := <-mb.InboundChan(): - if msg.Content != wantContent { - t.Fatalf("msg.Content = %q, want %s", msg.Content, wantContent) - } - if len(msg.Media) != len(wantMedia) { - t.Fatalf("msg.Media = %#v, want %#v", msg.Media, wantMedia) - } - for i := range wantMedia { - if msg.Media[i] != wantMedia[i] { - t.Fatalf("msg.Media = %#v, want %#v", msg.Media, wantMedia) - } - } - case <-time.After(time.Second): - t.Fatal(timeoutMessage) - } -} - -func TestPicoClientChannel_HandleServerMessage_ForwardsMedia(t *testing.T) { - ch, mb := newTestPicoClientChannel(t) - pc := &picoConn{sessionID: "sess-media"} - imageURL := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=" - - ch.handleServerMessage(pc, PicoMessage{ - Type: TypeMessageCreate, - Payload: map[string]any{ - PayloadKeyContent: "describe this", - "attachments": []any{ - map[string]any{ - "type": "image", - "url": imageURL, - }, - }, - }, - }) - - assertInboundMessage( - t, - mb, - "describe this", - []string{imageURL}, - "timed out waiting for forwarded media message", - ) -} - -func TestPicoClientChannel_HandleInbound_ForwardsMediaCreate(t *testing.T) { - ch, mb := newTestPicoClientChannel(t) - pc := &picoConn{sessionID: "sess-media-create"} - imageURL := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=" - - ch.handleInbound(pc, PicoMessage{ - Type: TypeMediaCreate, - Payload: map[string]any{ - PayloadKeyContent: "describe media.create", - "attachments": []any{ - map[string]any{ - "type": "image", - "url": imageURL, - }, - }, - }, - }) - - assertInboundMessage( - t, - mb, - "describe media.create", - []string{imageURL}, - "timed out waiting for media.create message", - ) -} - -func TestPicoClientChannel_HandleServerMessage_ForwardsTextWithDownloadAttachment(t *testing.T) { - mb := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:8080/ws", - }, mb) - if err != nil { - t.Fatalf("NewPicoClientChannel() error = %v", err) - } - - ch.ctx = context.Background() - pc := &picoConn{sessionID: "sess-download-attachment"} - - ch.handleServerMessage(pc, PicoMessage{ - Type: TypeMessageCreate, - Payload: map[string]any{ - PayloadKeyContent: "see attached", - "attachments": []any{ - map[string]any{ - "type": "image", - "url": "/pico/media/abc", - "filename": "image.png", - "content_type": "image/png", - }, - }, - }, - }) - - select { - case msg := <-mb.InboundChan(): - if msg.Content != "see attached" { - t.Fatalf("msg.Content = %q, want see attached", msg.Content) - } - if len(msg.Media) != 0 { - t.Fatalf("msg.Media = %#v, want no inline media", msg.Media) - } - case <-time.After(time.Second): - t.Fatal("timed out waiting for text message with download attachment") - } -} - -func TestPicoClientChannel_HandleServerMessage_ForwardsTextWithInvalidMediaPayload(t *testing.T) { - mb := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:8080/ws", - }, mb) - if err != nil { - t.Fatalf("NewPicoClientChannel() error = %v", err) - } - - ch.ctx = context.Background() - pc := &picoConn{sessionID: "sess-invalid-media"} - - ch.handleServerMessage(pc, PicoMessage{ - Type: TypeMessageCreate, - Payload: map[string]any{ - PayloadKeyContent: "hello despite invalid media", - "attachments": "not-an-array", - }, - }) - - select { - case msg := <-mb.InboundChan(): - if msg.Content != "hello despite invalid media" { - t.Fatalf("msg.Content = %q, want hello despite invalid media", msg.Content) - } - if len(msg.Media) != 0 { - t.Fatalf("msg.Media = %#v, want no inline media", msg.Media) - } - case <-time.After(time.Second): - t.Fatal("timed out waiting for text message with invalid media payload") - } -} - -func TestIsThoughtPayload(t *testing.T) { - tests := []struct { - name string - payload map[string]any - want bool - }{ - { - name: "explicit thought kind", - payload: map[string]any{PayloadKeyKind: MessageKindThought}, - want: true, - }, - { - name: "thought kind ignores case and whitespace", - payload: map[string]any{PayloadKeyKind: " ThOuGhT "}, - want: true, - }, - { - name: "legacy thought bool remains supported for inbound compatibility", - payload: map[string]any{PayloadKeyThought: true}, - want: true, - }, - { - name: "legacy thought false", - payload: map[string]any{PayloadKeyThought: false}, - want: false, - }, - { - name: "tool calls kind", - payload: map[string]any{PayloadKeyKind: MessageKindToolCalls}, - want: false, - }, - { - name: "non-string kind ignored", - payload: map[string]any{PayloadKeyKind: true}, - want: false, - }, - { - name: "default normal", - payload: map[string]any{PayloadKeyContent: "hello"}, - want: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := isThoughtPayload(tt.payload); got != tt.want { - t.Fatalf("isThoughtPayload() = %v, want %v", got, tt.want) - } - }) - } -} - -func TestPicoClientChannel_HandleServerMessage_IgnoresThought(t *testing.T) { - mb := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:8080/ws", - }, mb) - if err != nil { - t.Fatalf("NewPicoClientChannel() error = %v", err) - } - - ch.ctx = context.Background() - pc := &picoConn{sessionID: "sess-thought"} - - ch.handleServerMessage(pc, PicoMessage{ - Type: TypeMessageCreate, - Payload: map[string]any{ - PayloadKeyContent: "internal reasoning", - PayloadKeyKind: MessageKindThought, - }, - }) - - select { - case msg := <-mb.InboundChan(): - t.Fatalf("expected no inbound publish for thought payload, got %+v", msg) - case <-time.After(150 * time.Millisecond): - } -} - -func TestPicoClientChannel_HandleServerMessage_IgnoresLegacyThoughtBool(t *testing.T) { - mb := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true} - ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{ - URL: "ws://localhost:8080/ws", - }, mb) - if err != nil { - t.Fatalf("NewPicoClientChannel() error = %v", err) - } - - ch.ctx = context.Background() - pc := &picoConn{sessionID: "sess-thought-legacy"} - - ch.handleServerMessage(pc, PicoMessage{ - Type: TypeMessageCreate, - Payload: map[string]any{ - PayloadKeyContent: "legacy internal reasoning", - PayloadKeyThought: true, - }, - }) - - select { - case msg := <-mb.InboundChan(): - t.Fatalf("expected no inbound publish for legacy thought payload, got %+v", msg) - case <-time.After(150 * time.Millisecond): - } -} diff --git a/pkg/channels/pico/init.go b/pkg/channels/pico/init.go deleted file mode 100644 index 54596fab..00000000 --- a/pkg/channels/pico/init.go +++ /dev/null @@ -1,54 +0,0 @@ -package pico - -import ( - "github.com/sipeed/picoclaw/pkg/bus" - "github.com/sipeed/picoclaw/pkg/channels" - "github.com/sipeed/picoclaw/pkg/config" -) - -func init() { - channels.RegisterFactory( - config.ChannelPico, - 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.PicoSettings) - if !ok { - return nil, channels.ErrSendFailed - } - ch, err := NewPicoChannel(bc, c, b) - if err != nil { - return nil, err - } - if channelName != config.ChannelPico { - ch.SetName(channelName) - } - return ch, nil - }, - ) - channels.RegisterFactory( - config.ChannelPicoClient, - 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.PicoClientSettings) - if !ok { - return nil, channels.ErrSendFailed - } - ch, err := NewPicoClientChannel(bc, c, b) - if err != nil { - return nil, err - } - if channelName != config.ChannelPicoClient { - ch.SetName(channelName) - } - return ch, nil - }, - ) -} diff --git a/pkg/channels/pico/pico.go b/pkg/channels/pico/pico.go deleted file mode 100644 index 363692dc..00000000 --- a/pkg/channels/pico/pico.go +++ /dev/null @@ -1,1492 +0,0 @@ -package pico - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "mime" - "net/http" - "net/url" - "os" - "path/filepath" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/google/uuid" - "github.com/gorilla/websocket" - - "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/utils" -) - -// picoConn represents a single WebSocket connection. -type picoConn struct { - id string - conn *websocket.Conn - sessionID string - writeMu sync.Mutex - closed atomic.Bool - cancel context.CancelFunc // cancels per-connection goroutines (e.g. pingLoop) -} - -var allowedInlineImageMIMETypes = map[string]struct{}{ - "image/jpeg": {}, - "image/png": {}, - "image/gif": {}, - "image/webp": {}, - "image/bmp": {}, -} - -func outboundMessageIsThought(msg bus.OutboundMessage) bool { - if len(msg.Context.Raw) == 0 { - return false - } - return strings.EqualFold(strings.TrimSpace(msg.Context.Raw["message_kind"]), MessageKindThought) -} - -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") -} - -func outboundMessageIsToolCalls(msg bus.OutboundMessage) bool { - if len(msg.Context.Raw) == 0 { - return false - } - return strings.EqualFold(strings.TrimSpace(msg.Context.Raw["message_kind"]), MessageKindToolCalls) -} - -func outboundMessageFinalizesTrackedToolFeedback(msg bus.OutboundMessage) bool { - return !channels.IsCommandReply(msg) && - !outboundMessageIsToolFeedback(msg) && - !outboundMessageIsThought(msg) && - !outboundMessageIsToolCalls(msg) -} - -// writeJSON sends a JSON message to the connection with write locking. -func (pc *picoConn) writeJSON(v any) error { - if pc.closed.Load() { - return fmt.Errorf("connection closed") - } - pc.writeMu.Lock() - defer pc.writeMu.Unlock() - return pc.conn.WriteJSON(v) -} - -// close closes the connection. -func (pc *picoConn) close() { - if pc.closed.CompareAndSwap(false, true) { - if pc.cancel != nil { - pc.cancel() - } - pc.conn.Close() - } -} - -// PicoChannel implements the native Pico Protocol WebSocket channel. -// It serves as the reference implementation for all optional capability interfaces. -type PicoChannel struct { - *channels.BaseChannel - bc *config.Channel - config *config.PicoSettings - upgrader websocket.Upgrader - connections map[string]*picoConn // connID -> *picoConn - sessionConnections map[string]map[string]*picoConn // sessionID -> connID -> *picoConn - connsMu sync.RWMutex - ctx context.Context - cancel context.CancelFunc - progress *channels.ToolFeedbackAnimator - deleteMessageFn func(context.Context, string, string) error - // broadcastFn lets tests intercept outbound broadcasts. nil → broadcastToSession. - broadcastFn func(chatID string, msg PicoMessage) error -} - -// NewPicoChannel creates a new Pico Protocol channel. -func NewPicoChannel( - bc *config.Channel, - cfg *config.PicoSettings, - messageBus *bus.MessageBus, -) (*PicoChannel, error) { - if cfg.Token.String() == "" { - return nil, fmt.Errorf("pico token is required") - } - - base := channels.NewBaseChannel("pico", cfg, messageBus, bc.AllowFrom) - - allowOrigins := cfg.AllowOrigins - checkOrigin := func(r *http.Request) bool { - if len(allowOrigins) == 0 { - return true // allow all if not configured - } - origin := r.Header.Get("Origin") - for _, allowed := range allowOrigins { - if allowed == "*" || allowed == origin { - return true - } - } - return false - } - - ch := &PicoChannel{ - BaseChannel: base, - bc: bc, - config: cfg, - upgrader: websocket.Upgrader{ - CheckOrigin: checkOrigin, - ReadBufferSize: 1024, - WriteBufferSize: 1024, - }, - connections: make(map[string]*picoConn), - sessionConnections: make(map[string]map[string]*picoConn), - } - ch.progress = channels.NewToolFeedbackAnimator(ch.EditMessage) - ch.deleteMessageFn = ch.DeleteMessage - return ch, nil -} - -// createAndAddConnection checks MaxConnections and registers a connection atomically. -func (c *PicoChannel) createAndAddConnection(conn *websocket.Conn, sessionID string, maxConns int) (*picoConn, error) { - c.connsMu.Lock() - defer c.connsMu.Unlock() - if len(c.connections) >= maxConns { - return nil, channels.ErrTemporary - } - - var connID string - for { - connID = uuid.New().String() - if _, exists := c.connections[connID]; !exists { - break - } - } - - pc := &picoConn{ - id: connID, - conn: conn, - sessionID: sessionID, - } - - c.connections[pc.id] = pc - bySession, ok := c.sessionConnections[pc.sessionID] - if !ok { - bySession = make(map[string]*picoConn) - c.sessionConnections[pc.sessionID] = bySession - } - bySession[pc.id] = pc - - return pc, nil -} - -// removeConnection deletes a connection from indexes and returns it when found. -func (c *PicoChannel) removeConnection(connID string) *picoConn { - c.connsMu.Lock() - defer c.connsMu.Unlock() - - pc, ok := c.connections[connID] - if !ok { - return nil - } - - delete(c.connections, connID) - if bySession, ok := c.sessionConnections[pc.sessionID]; ok { - delete(bySession, connID) - if len(bySession) == 0 { - delete(c.sessionConnections, pc.sessionID) - } - } - - return pc -} - -// takeAllConnections snapshots and clears all connection indexes. -func (c *PicoChannel) takeAllConnections() []*picoConn { - c.connsMu.Lock() - defer c.connsMu.Unlock() - - all := make([]*picoConn, 0, len(c.connections)) - for _, pc := range c.connections { - all = append(all, pc) - } - clear(c.connections) - clear(c.sessionConnections) - - return all -} - -// sessionConnectionsSnapshot returns all active connections for a session. -func (c *PicoChannel) sessionConnectionsSnapshot(sessionID string) []*picoConn { - c.connsMu.RLock() - defer c.connsMu.RUnlock() - - bySession, ok := c.sessionConnections[sessionID] - if !ok || len(bySession) == 0 { - return nil - } - - conns := make([]*picoConn, 0, len(bySession)) - for _, pc := range bySession { - conns = append(conns, pc) - } - return conns -} - -// currentConnCount returns a lock-protected snapshot of active connection count. -func (c *PicoChannel) currentConnCount() int { - c.connsMu.RLock() - defer c.connsMu.RUnlock() - return len(c.connections) -} - -// Start implements Channel. -func (c *PicoChannel) Start(ctx context.Context) error { - logger.InfoC("pico", "Starting Pico Protocol channel") - c.ctx, c.cancel = context.WithCancel(ctx) - c.SetRunning(true) - logger.InfoC("pico", "Pico Protocol channel started") - return nil -} - -// Stop implements Channel. -func (c *PicoChannel) Stop(ctx context.Context) error { - logger.InfoC("pico", "Stopping Pico Protocol channel") - c.SetRunning(false) - - // Close all connections - for _, pc := range c.takeAllConnections() { - pc.close() - } - - if c.cancel != nil { - c.cancel() - } - if c.progress != nil { - c.progress.StopAll() - } - - logger.InfoC("pico", "Pico Protocol channel stopped") - return nil -} - -// WebhookPath implements channels.WebhookHandler. -func (c *PicoChannel) WebhookPath() string { return "/pico/" } - -// ServeHTTP implements http.Handler for the shared HTTP server. -func (c *PicoChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) { - path := strings.TrimPrefix(r.URL.Path, "/pico") - - switch path { - case "/ws", "/ws/": - c.handleWebSocket(w, r) - default: - if strings.HasPrefix(path, "/media/") { - c.handleMediaDownload(w, r) - return - } - http.NotFound(w, r) - } -} - -// Send implements Channel — sends a message to the appropriate WebSocket connection. -func (c *PicoChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - isThought := outboundMessageIsThought(msg) - isToolFeedback := outboundMessageIsToolFeedback(msg) - isToolCalls := outboundMessageIsToolCalls(msg) - if isToolFeedback { - if msgID, handled, err := c.progress.Update(ctx, msg.ChatID, msg.Content); handled { - if err != nil { - return nil, err - } - return []string{msgID}, nil - } - } - trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(msg.ChatID) - if outboundMessageFinalizesTrackedToolFeedback(msg) { - if msgIDs, handled := c.FinalizeToolFeedbackMessage(ctx, msg); handled { - return msgIDs, nil - } - } - - content := msg.Content - if isToolFeedback { - content = channels.InitialAnimatedToolFeedbackContent(msg.Content) - } - msgID := uuid.New().String() - - payload := map[string]any{ - PayloadKeyContent: content, - "message_id": msgID, - } - if modelName := strings.TrimSpace(msg.Context.Raw[PayloadKeyModelName]); modelName != "" { - payload[PayloadKeyModelName] = modelName - } - switch { - case isThought: - payload[PayloadKeyKind] = MessageKindThought - - // This field is kept solely for compatibility with legacy pico clients that - // do not yet support the newer "kind" field. - // DO NOT use it for any purpose other than legacy client compatibility. - payload[PayloadKeyThought] = true - - case isToolCalls: - payload[PayloadKeyKind] = MessageKindToolCalls - if toolCalls, ok := picoToolCallsPayload(msg); ok { - payload[PayloadKeyToolCalls] = toolCalls - } - } - setContextUsagePayload(payload, msg.ContextUsage) - outMsg := newMessage(TypeMessageCreate, payload) - - if err := c.broadcastToSession(msg.ChatID, outMsg); err != nil { - return nil, err - } - if isToolFeedback { - c.RecordToolFeedbackMessage(msg.ChatID, msgID, msg.Content) - } else if hasTrackedMsg && outboundMessageFinalizesTrackedToolFeedback(msg) { - c.dismissTrackedToolFeedbackMessage(ctx, msg.ChatID, trackedMsgID) - } - return []string{msgID}, nil -} - -// EditMessage implements channels.MessageEditor. -func (c *PicoChannel) EditMessage(ctx context.Context, chatID string, messageID string, content string) error { - return c.editMessage(ctx, chatID, messageID, content, nil) -} - -func (c *PicoChannel) EditMessageWithPayload( - ctx context.Context, - chatID string, - messageID string, - payload map[string]any, -) error { - return c.editMessagePayload(ctx, chatID, messageID, payload, nil) -} - -// DeleteMessage implements channels.MessageDeleter. -func (c *PicoChannel) DeleteMessage(ctx context.Context, chatID string, messageID string) error { - outMsg := newMessage(TypeMessageDelete, map[string]any{ - "message_id": messageID, - }) - return c.broadcastToSession(chatID, outMsg) -} - -func (c *PicoChannel) currentToolFeedbackMessage(chatID string) (string, bool) { - if c.progress == nil { - return "", false - } - return c.progress.Current(chatID) -} - -func (c *PicoChannel) takeToolFeedbackMessage(chatID string) (string, string, bool) { - if c.progress == nil { - return "", "", false - } - return c.progress.Take(chatID) -} - -func (c *PicoChannel) RecordToolFeedbackMessage(chatID, messageID, content string) { - if c.progress == nil { - return - } - c.progress.Record(chatID, messageID, content) -} - -func (c *PicoChannel) ClearToolFeedbackMessage(chatID string) { - if c.progress == nil { - return - } - c.progress.Clear(chatID) -} - -func (c *PicoChannel) DismissToolFeedbackMessage(ctx context.Context, chatID string) { - msgID, ok := c.currentToolFeedbackMessage(chatID) - if !ok { - return - } - c.dismissTrackedToolFeedbackMessage(ctx, chatID, msgID) -} - -func (c *PicoChannel) dismissTrackedToolFeedbackMessage(ctx context.Context, chatID, messageID string) { - if strings.TrimSpace(chatID) == "" || strings.TrimSpace(messageID) == "" { - return - } - c.ClearToolFeedbackMessage(chatID) - deleteFn := c.deleteMessageFn - if deleteFn == nil { - deleteFn = c.DeleteMessage - } - _ = deleteFn(ctx, chatID, messageID) -} - -func (c *PicoChannel) finalizeTrackedToolFeedbackMessage( - ctx context.Context, - chatID string, - content string, - editFn func(context.Context, string, string, map[string]any, *bus.ContextUsage) error, - payload map[string]any, - contextUsage *bus.ContextUsage, -) ([]string, bool) { - msgID, baseContent, ok := c.takeToolFeedbackMessage(chatID) - if !ok || editFn == nil { - return nil, false - } - if payload == nil { - payload = map[string]any{ - PayloadKeyContent: content, - } - } - if _, ok := payload[PayloadKeyContent]; !ok { - payload[PayloadKeyContent] = content - } - if err := editFn(ctx, chatID, msgID, payload, contextUsage); err != nil { - c.RecordToolFeedbackMessage(chatID, msgID, baseContent) - return nil, false - } - return []string{msgID}, true -} - -func (c *PicoChannel) FinalizeToolFeedbackMessage(ctx context.Context, msg bus.OutboundMessage) ([]string, bool) { - if !outboundMessageFinalizesTrackedToolFeedback(msg) { - return nil, false - } - payload := map[string]any{ - PayloadKeyContent: msg.Content, - } - if modelName := strings.TrimSpace(msg.Context.Raw[PayloadKeyModelName]); modelName != "" { - payload[PayloadKeyModelName] = modelName - } - return c.finalizeTrackedToolFeedbackMessage( - ctx, - msg.ChatID, - msg.Content, - c.editMessagePayload, - payload, - msg.ContextUsage, - ) -} - -// StartTyping implements channels.TypingCapable. -func (c *PicoChannel) StartTyping(ctx context.Context, chatID string) (func(), error) { - startMsg := newMessage(TypeTypingStart, nil) - if err := c.broadcastToSession(chatID, startMsg); err != nil { - return func() {}, err - } - return func() { - stopMsg := newMessage(TypeTypingStop, nil) - c.broadcastToSession(chatID, stopMsg) - }, nil -} - -// SendPlaceholder implements channels.PlaceholderCapable. -// It sends a placeholder message via the Pico Protocol that will later be -// edited to the actual response via EditMessage (channels.MessageEditor). -func (c *PicoChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) { - if !c.bc.Placeholder.Enabled { - return "", nil - } - - text := c.bc.Placeholder.GetRandomText() - - msgID := uuid.New().String() - outMsg := newMessage(TypeMessageCreate, map[string]any{ - PayloadKeyContent: text, - PayloadKeyPlaceholder: true, - "message_id": msgID, - }) - - if err := c.broadcastToSession(chatID, outMsg); err != nil { - return "", err - } - - return msgID, nil -} - -// BeginStream implements channels.StreamingCapable for the Pico protocol. -func (c *PicoChannel) BeginStream(ctx context.Context, chatID string) (channels.Streamer, error) { - if c == nil || c.config == nil || !c.config.Streaming.Enabled { - return nil, fmt.Errorf("streaming disabled in config") - } - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - streamCfg := c.config.Streaming.WithDefaults(0, 1) - return &picoStreamer{ - channel: c, - chatID: chatID, - throttleInterval: time.Duration(streamCfg.ThrottleSeconds) * time.Second, - minGrowth: streamCfg.MinGrowthChars, - }, nil -} - -type picoStreamer struct { - channel *PicoChannel - chatID string - modelName string - turnInputTokens int - turnOutputTokens int - messageID string - reasoningID string - throttleInterval time.Duration - minGrowth int - lastLen int - lastAt time.Time - lastContent string - reasoningLastLen int - reasoningLastAt time.Time - reasoningContent string - mu sync.Mutex -} - -func (s *picoStreamer) SetModelName(modelName string) { - if s == nil { - return - } - s.mu.Lock() - defer s.mu.Unlock() - s.modelName = strings.TrimSpace(modelName) -} - -// SetTurnUsage records the real per-turn LLM token usage to emit on finalize. -func (s *picoStreamer) SetTurnUsage(inputTokens, outputTokens int) { - if s == nil { - return - } - s.mu.Lock() - defer s.mu.Unlock() - s.turnInputTokens = inputTokens - s.turnOutputTokens = outputTokens -} - -func (s *picoStreamer) Update(ctx context.Context, content string) error { - s.mu.Lock() - defer s.mu.Unlock() - return s.updateLocked(ctx, content, false, nil) -} - -func (s *picoStreamer) Finalize(ctx context.Context, content string) error { - return s.FinalizeWithContext(ctx, content, nil) -} - -func (s *picoStreamer) FinalizeWithContext(ctx context.Context, content string, contextUsage *bus.ContextUsage) error { - s.mu.Lock() - defer s.mu.Unlock() - return s.updateLocked(ctx, content, true, contextUsage) -} - -func (s *picoStreamer) UpdateReasoning(ctx context.Context, content string) error { - s.mu.Lock() - defer s.mu.Unlock() - return s.updateReasoningLocked(ctx, content, false) -} - -func (s *picoStreamer) FinalizeReasoning(ctx context.Context, content string) error { - s.mu.Lock() - defer s.mu.Unlock() - return s.updateReasoningLocked(ctx, content, true) -} - -func (s *picoStreamer) Cancel(ctx context.Context) { - if s == nil { - return - } - s.mu.Lock() - defer s.mu.Unlock() - if s.channel == nil || s.messageID == "" { - if s.channel != nil && s.reasoningID != "" { - _ = s.channel.DeleteMessage(ctx, s.chatID, s.reasoningID) - s.reasoningID = "" - } - return - } - _ = s.channel.DeleteMessage(ctx, s.chatID, s.messageID) - s.messageID = "" - if s.reasoningID != "" { - _ = s.channel.DeleteMessage(ctx, s.chatID, s.reasoningID) - s.reasoningID = "" - } -} - -func (s *picoStreamer) updateLocked( - ctx context.Context, - content string, - force bool, - contextUsage *bus.ContextUsage, -) error { - if s == nil || s.channel == nil { - return fmt.Errorf("streamer is not initialized") - } - if strings.TrimSpace(content) == "" && s.messageID == "" { - return nil - } - - now := time.Now() - contentLen := len([]rune(content)) - if s.messageID != "" && !force { - growth := contentLen - s.lastLen - if now.Sub(s.lastAt) < s.throttleInterval || growth < s.minGrowth { - return nil - } - } - - return s.sendLocked(ctx, content, contextUsage) -} - -func (s *picoStreamer) updateReasoningLocked(ctx context.Context, content string, force bool) error { - if s == nil || s.channel == nil { - return fmt.Errorf("streamer is not initialized") - } - if strings.TrimSpace(content) == "" && s.reasoningID == "" { - return nil - } - - now := time.Now() - contentLen := len([]rune(content)) - if s.reasoningID != "" && !force { - growth := contentLen - s.reasoningLastLen - if now.Sub(s.reasoningLastAt) < s.throttleInterval || growth < s.minGrowth { - return nil - } - } - - return s.sendReasoningLocked(ctx, content) -} - -func (s *picoStreamer) sendLocked(ctx context.Context, content string, contextUsage *bus.ContextUsage) error { - now := time.Now() - contentLen := len([]rune(content)) - - if s.messageID == "" { - s.messageID = uuid.New().String() - payload := map[string]any{ - PayloadKeyContent: content, - "message_id": s.messageID, - } - if s.modelName != "" { - payload[PayloadKeyModelName] = s.modelName - } - setContextUsagePayload(payload, contextUsage) - setTurnUsagePayload(payload, s.turnInputTokens, s.turnOutputTokens) - outMsg := newMessage(TypeMessageCreate, payload) - if err := s.channel.broadcast(s.chatID, outMsg); err != nil { - return err - } - } else if content != s.lastContent || contextUsage != nil { - payload := map[string]any{ - PayloadKeyContent: content, - "message_id": s.messageID, - } - if s.modelName != "" { - payload[PayloadKeyModelName] = s.modelName - } - setTurnUsagePayload(payload, s.turnInputTokens, s.turnOutputTokens) - if err := s.channel.editMessagePayload(ctx, s.chatID, s.messageID, payload, contextUsage); err != nil { - return err - } - } - - s.lastContent = content - s.lastLen = contentLen - s.lastAt = now - return nil -} - -func (s *picoStreamer) sendReasoningLocked(ctx context.Context, content string) error { - now := time.Now() - contentLen := len([]rune(content)) - - if s.reasoningID == "" { - s.reasoningID = uuid.New().String() - payload := map[string]any{ - PayloadKeyContent: content, - "message_id": s.reasoningID, - PayloadKeyKind: MessageKindThought, - PayloadKeyThought: true, - } - if s.modelName != "" { - payload[PayloadKeyModelName] = s.modelName - } - outMsg := newMessage(TypeMessageCreate, payload) - if err := s.channel.broadcastToSession(s.chatID, outMsg); err != nil { - return err - } - } else if content != s.reasoningContent { - payload := map[string]any{ - PayloadKeyContent: content, - "message_id": s.reasoningID, - PayloadKeyKind: MessageKindThought, - PayloadKeyThought: true, - } - if s.modelName != "" { - payload[PayloadKeyModelName] = s.modelName - } - outMsg := newMessage(TypeMessageUpdate, payload) - if err := s.channel.broadcastToSession(s.chatID, outMsg); err != nil { - return err - } - } - - s.reasoningContent = content - s.reasoningLastLen = contentLen - s.reasoningLastAt = now - return nil -} - -// SendMedia implements channels.MediaSender for the Pico protocol. -// Media is delivered as a normal assistant message carrying structured -// attachments plus an authenticated same-origin download URL. -func (c *PicoChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) { - if !c.IsRunning() { - return nil, channels.ErrNotRunning - } - trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(msg.ChatID) - - store := c.GetMediaStore() - if store == nil { - return nil, fmt.Errorf("no media store available: %w", channels.ErrSendFailed) - } - - attachments := make([]map[string]any, 0, len(msg.Parts)) - caption := "" - - for _, part := range msg.Parts { - localPath, meta, err := store.ResolveWithMeta(part.Ref) - if err != nil { - logger.ErrorCF("pico", "Failed to resolve media ref", map[string]any{ - "ref": part.Ref, - "error": err.Error(), - }) - continue - } - - filename := strings.TrimSpace(part.Filename) - if filename == "" { - filename = strings.TrimSpace(meta.Filename) - } - if filename == "" { - filename = filepath.Base(localPath) - } - - contentType := strings.TrimSpace(part.ContentType) - if contentType == "" { - contentType = strings.TrimSpace(meta.ContentType) - } - if contentType == "" { - contentType = "application/octet-stream" - } - - attachmentType := strings.TrimSpace(part.Type) - if attachmentType == "" { - attachmentType = picoInferAttachmentType(filename, contentType) - } - - attachmentURL, err := picoDownloadURLForRef(part.Ref) - if err != nil { - logger.ErrorCF("pico", "Failed to build media download URL", map[string]any{ - "ref": part.Ref, - "error": err.Error(), - }) - continue - } - - attachments = append(attachments, map[string]any{ - "type": attachmentType, - "url": attachmentURL, - "filename": filename, - "content_type": contentType, - }) - - if caption == "" && strings.TrimSpace(part.Caption) != "" { - caption = strings.TrimSpace(part.Caption) - } - } - - if len(attachments) == 0 { - return nil, fmt.Errorf("no deliverable media parts: %w", channels.ErrSendFailed) - } - - msgID := uuid.New().String() - outMsg := newMessage(TypeMessageCreate, map[string]any{ - PayloadKeyContent: caption, - "attachments": attachments, - "message_id": msgID, - }) - if modelName := strings.TrimSpace(msg.Context.Raw[PayloadKeyModelName]); modelName != "" { - outMsg.Payload[PayloadKeyModelName] = modelName - } - - if err := c.broadcastToSession(msg.ChatID, outMsg); err != nil { - return nil, err - } - if hasTrackedMsg { - c.dismissTrackedToolFeedbackMessage(ctx, msg.ChatID, trackedMsgID) - } - - return []string{msgID}, nil -} - -func picoDownloadURLForRef(ref string) (string, error) { - refID, err := picoMediaRefID(ref) - if err != nil { - return "", err - } - return "/pico/media/" + url.PathEscape(refID), nil -} - -func picoMediaRefID(ref string) (string, error) { - refID := strings.TrimSpace(strings.TrimPrefix(ref, "media://")) - if refID == "" || strings.Contains(refID, "/") { - return "", fmt.Errorf("invalid media ref %q", ref) - } - return refID, nil -} - -func picoInferAttachmentType(filename, contentType string) string { - contentType = strings.ToLower(strings.TrimSpace(contentType)) - filename = strings.ToLower(strings.TrimSpace(filename)) - - switch { - case strings.HasPrefix(contentType, "image/"): - return "image" - case strings.HasPrefix(contentType, "audio/"): - return "audio" - case strings.HasPrefix(contentType, "video/"): - return "video" - } - - switch ext := filepath.Ext(filename); ext { - case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg": - return "image" - case ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac", ".wma", ".opus": - return "audio" - case ".mp4", ".avi", ".mov", ".webm", ".mkv": - return "video" - default: - return "file" - } -} - -func picoAllowsInlineDisplay(filename, contentType string) bool { - contentType = strings.ToLower(strings.TrimSpace(contentType)) - filename = strings.ToLower(strings.TrimSpace(filename)) - - if strings.Contains(contentType, "svg") || filepath.Ext(filename) == ".svg" { - return false - } - - return picoInferAttachmentType(filename, contentType) == "image" -} - -func (c *PicoChannel) handleMediaDownload(w http.ResponseWriter, r *http.Request) { - if !c.IsRunning() { - http.Error(w, "channel not running", http.StatusServiceUnavailable) - return - } - if !c.authenticate(r) { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - - refID := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/pico/media/"), "/")) - if refID == "" { - http.NotFound(w, r) - return - } - - store := c.GetMediaStore() - if store == nil { - http.Error(w, "media store unavailable", http.StatusServiceUnavailable) - return - } - - localPath, meta, err := store.ResolveWithMeta("media://" + refID) - if err != nil { - http.NotFound(w, r) - return - } - - file, err := os.Open(localPath) - if err != nil { - http.Error(w, "failed to open media", http.StatusInternalServerError) - return - } - defer file.Close() - - info, err := file.Stat() - if err != nil { - http.Error(w, "failed to stat media", http.StatusInternalServerError) - return - } - - filename := strings.TrimSpace(meta.Filename) - if filename == "" { - filename = filepath.Base(localPath) - } - contentType := strings.TrimSpace(meta.ContentType) - if contentType == "" { - contentType = "application/octet-stream" - } - - dispositionType := "attachment" - if picoAllowsInlineDisplay(filename, contentType) { - dispositionType = "inline" - } - - if cd := mime.FormatMediaType(dispositionType, map[string]string{"filename": filename}); cd != "" { - w.Header().Set("Content-Disposition", cd) - } - w.Header().Set("Content-Type", contentType) - http.ServeContent(w, r, filename, info.ModTime(), file) -} - -// broadcast routes through broadcastFn when set (tests), else broadcastToSession. -func (c *PicoChannel) broadcast(chatID string, msg PicoMessage) error { - if c.broadcastFn != nil { - return c.broadcastFn(chatID, msg) - } - return c.broadcastToSession(chatID, msg) -} - -// broadcastToSession sends a message to all connections with a matching session. -func (c *PicoChannel) broadcastToSession(chatID string, msg PicoMessage) error { - // chatID format: "pico:" - sessionID := strings.TrimPrefix(chatID, "pico:") - msg.SessionID = sessionID - - var sent bool - for _, pc := range c.sessionConnectionsSnapshot(sessionID) { - if err := pc.writeJSON(msg); err != nil { - logger.DebugCF("pico", "Write to connection failed", map[string]any{ - "conn_id": pc.id, - "error": err.Error(), - }) - } else { - sent = true - } - } - - if !sent { - return fmt.Errorf("no active connections for session %s: %w", sessionID, channels.ErrSendFailed) - } - return nil -} - -// handleWebSocket upgrades the HTTP connection and manages the WebSocket lifecycle. -func (c *PicoChannel) handleWebSocket(w http.ResponseWriter, r *http.Request) { - if !c.IsRunning() { - http.Error(w, "channel not running", http.StatusServiceUnavailable) - return - } - - // Authenticate - if !c.authenticate(r) { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - - // Check connection limit - maxConns := c.config.MaxConnections - if maxConns <= 0 { - maxConns = 100 - } - if c.currentConnCount() >= maxConns { - http.Error(w, "too many connections", http.StatusServiceUnavailable) - return - } - - // Echo the matched subprotocol back so the browser accepts the upgrade. - var responseHeader http.Header - if proto := c.matchedSubprotocol(r); proto != "" { - responseHeader = http.Header{"Sec-WebSocket-Protocol": {proto}} - } - - conn, err := c.upgrader.Upgrade(w, r, responseHeader) - if err != nil { - logger.ErrorCF("pico", "WebSocket upgrade failed", map[string]any{ - "error": err.Error(), - }) - return - } - - // Determine session ID from query param or generate one - sessionID := r.URL.Query().Get("session_id") - if sessionID == "" { - sessionID = uuid.New().String() - } - - pc, err := c.createAndAddConnection(conn, sessionID, maxConns) - if err != nil { - _ = conn.WriteControl( - websocket.CloseMessage, - websocket.FormatCloseMessage(websocket.CloseTryAgainLater, "too many connections"), - time.Now().Add(2*time.Second), - ) - _ = conn.Close() - return - } - - logger.InfoCF("pico", "WebSocket client connected", map[string]any{ - "conn_id": pc.id, - "session_id": sessionID, - }) - - go c.readLoop(pc) -} - -// authenticate checks the request for a valid token: -// 1. Authorization: Bearer header -// 2. Sec-WebSocket-Protocol "token." (for browsers that can't set headers) -// 3. Query parameter "token" (only when AllowTokenQuery is on) -func (c *PicoChannel) authenticate(r *http.Request) bool { - token := c.config.Token.String() - if token == "" { - return false - } - - // Check Authorization header - auth := r.Header.Get("Authorization") - if after, ok := strings.CutPrefix(auth, "Bearer "); ok { - if after == token { - return true - } - } - - // Check Sec-WebSocket-Protocol subprotocol ("token.") - if c.matchedSubprotocol(r) != "" { - return true - } - - // Check query parameter only when explicitly allowed - if c.config.AllowTokenQuery { - if r.URL.Query().Get("token") == token { - return true - } - } - - return false -} - -// matchedSubprotocol returns the "token." subprotocol that matches -// the configured token, or "" if none do. -func (c *PicoChannel) matchedSubprotocol(r *http.Request) string { - token := c.config.Token.String() - for _, proto := range websocket.Subprotocols(r) { - if after, ok := strings.CutPrefix(proto, "token."); ok && after == token { - return proto - } - } - return "" -} - -// readLoop reads messages from a WebSocket connection. -func (c *PicoChannel) readLoop(pc *picoConn) { - defer func() { - pc.close() - if removed := c.removeConnection(pc.id); removed != nil { - logger.InfoCF("pico", "WebSocket client disconnected", map[string]any{ - "conn_id": removed.id, - "session_id": removed.sessionID, - }) - } - }() - - readTimeout := time.Duration(c.config.ReadTimeout) * time.Second - if readTimeout <= 0 { - readTimeout = 60 * time.Second - } - - _ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout)) - pc.conn.SetPongHandler(func(appData string) error { - _ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout)) - return nil - }) - - // Start ping ticker - pingInterval := time.Duration(c.config.PingInterval) * time.Second - if pingInterval <= 0 { - pingInterval = 30 * time.Second - } - go c.pingLoop(pc, pingInterval) - - for { - select { - case <-c.ctx.Done(): - return - default: - } - - _, rawMsg, err := pc.conn.ReadMessage() - if err != nil { - if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) { - logger.DebugCF("pico", "WebSocket read error", map[string]any{ - "conn_id": pc.id, - "error": err.Error(), - }) - } - return - } - - _ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout)) - - var msg PicoMessage - if err := json.Unmarshal(rawMsg, &msg); err != nil { - errMsg := newError("invalid_message", "failed to parse message") - pc.writeJSON(errMsg) - continue - } - - c.handleMessage(pc, msg) - } -} - -// pingLoop sends periodic ping frames to keep the connection alive. -func (c *PicoChannel) pingLoop(pc *picoConn, interval time.Duration) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - - for { - select { - case <-c.ctx.Done(): - return - case <-ticker.C: - if pc.closed.Load() { - return - } - pc.writeMu.Lock() - err := pc.conn.WriteMessage(websocket.PingMessage, nil) - pc.writeMu.Unlock() - if err != nil { - return - } - } - } -} - -// handleMessage processes an inbound Pico Protocol message. -func (c *PicoChannel) handleMessage(pc *picoConn, msg PicoMessage) { - switch msg.Type { - case TypePing: - pong := newMessage(TypePong, nil) - pong.ID = msg.ID - pc.writeJSON(pong) - - case TypeMessageSend: - c.handleMessageSend(pc, msg) - - case TypeMediaSend: - c.handleMessageSend(pc, msg) - - default: - errMsg := newError("unknown_type", fmt.Sprintf("unknown message type: %s", msg.Type)) - pc.writeJSON(errMsg) - } -} - -// handleMessageSend processes an inbound message.send from a client. -func (c *PicoChannel) handleMessageSend(pc *picoConn, msg PicoMessage) { - content, _ := msg.Payload["content"].(string) - media, err := parseInlineImageMedia(msg.Payload) - if err != nil { - errMsg := newErrorWithPayload("invalid_media", err.Error(), map[string]any{ - "request_id": msg.ID, - }) - pc.writeJSON(errMsg) - return - } - - if strings.TrimSpace(content) == "" && len(media) == 0 { - errMsg := newErrorWithPayload("empty_content", "message content is empty", map[string]any{ - "request_id": msg.ID, - }) - pc.writeJSON(errMsg) - return - } - - sessionID := msg.SessionID - if sessionID == "" { - sessionID = pc.sessionID - } - - chatID := "pico:" + sessionID - senderID := "pico-user" - - metadata := map[string]string{ - "platform": "pico", - "session_id": sessionID, - "conn_id": pc.id, - } - - logger.DebugCF("pico", "Received message", map[string]any{ - "session_id": sessionID, - "preview": truncate(content, 50), - "media": len(media), - }) - - sender := bus.SenderInfo{ - Platform: "pico", - PlatformID: senderID, - CanonicalID: identity.BuildCanonicalID("pico", senderID), - } - - if !c.IsAllowedSender(sender) { - return - } - - inboundCtx := bus.InboundContext{ - Channel: "pico", - ChatID: chatID, - ChatType: "direct", - SenderID: senderID, - MessageID: msg.ID, - Raw: metadata, - } - - c.HandleInboundContext(c.ctx, chatID, content, media, inboundCtx, sender) -} - -// truncate truncates a string to maxLen runes. -func truncate(s string, maxLen int) string { - runes := []rune(s) - if len(runes) <= maxLen { - return s - } - return string(runes[:maxLen]) + "..." -} - -func parseInlineImageMedia(payload map[string]any) ([]string, error) { - if len(payload) == 0 { - return nil, nil - } - - media, err := parseInlineImageValues(payload["media"]) - if err != nil { - return nil, err - } - - attachments, err := parseInlineImageAttachments(payload["attachments"]) - if err != nil { - return nil, err - } - media = append(media, attachments...) - - return media, nil -} - -func parseInlineImageValues(raw any) ([]string, error) { - if raw == nil { - return nil, nil - } - switch values := raw.(type) { - case []any: - media := make([]string, 0, len(values)) - for i, item := range values { - value, err := inlineImageValue(item) - if err != nil { - return nil, fmt.Errorf("media[%d]: %w", i, err) - } - if err := validateInlineImageDataURL(value); err != nil { - return nil, fmt.Errorf("media[%d]: %w", i, err) - } - media = append(media, value) - } - return media, nil - case []string: - media := make([]string, 0, len(values)) - for i, value := range values { - value = strings.TrimSpace(value) - if err := validateInlineImageDataURL(value); err != nil { - return nil, fmt.Errorf("media[%d]: %w", i, err) - } - media = append(media, value) - } - return media, nil - case string: - value := strings.TrimSpace(values) - if err := validateInlineImageDataURL(value); err != nil { - return nil, err - } - return []string{value}, nil - default: - return nil, fmt.Errorf("media must be a string or array of strings") - } -} - -func parseInlineImageAttachments(raw any) ([]string, error) { - if raw == nil { - return nil, nil - } - - values, ok := raw.([]any) - if !ok { - return nil, fmt.Errorf("attachments must be an array") - } - - media := make([]string, 0, len(values)) - for i, item := range values { - attachment, ok := item.(map[string]any) - if !ok { - return nil, fmt.Errorf("attachments[%d]: attachment must be an object", i) - } - - attachmentType, _ := attachment["type"].(string) - attachmentType = strings.ToLower(strings.TrimSpace(attachmentType)) - if attachmentType != "" && attachmentType != "image" { - continue - } - - value, err := inlineImageValue(attachment) - if err != nil { - if attachmentType == "image" { - return nil, fmt.Errorf("attachments[%d]: %w", i, err) - } - continue - } - if !strings.HasPrefix(value, "data:") { - continue - } - if err := validateInlineImageDataURL(value); err != nil { - return nil, fmt.Errorf("attachments[%d]: %w", i, err) - } - media = append(media, value) - } - return media, nil -} - -func inlineImageValue(item any) (string, error) { - switch value := item.(type) { - case string: - value = strings.TrimSpace(value) - if value == "" { - return "", fmt.Errorf("image payload is empty") - } - return value, nil - case map[string]any: - for _, key := range []string{"url", "data_url"} { - if raw, ok := value[key].(string); ok && strings.TrimSpace(raw) != "" { - return strings.TrimSpace(raw), nil - } - } - return "", fmt.Errorf("image payload must include url or data_url") - default: - return "", fmt.Errorf("image payload must be a string or object") - } -} - -func validateInlineImageDataURL(mediaURL string) error { - if mediaURL == "" { - return fmt.Errorf("image payload is empty") - } - if !strings.HasPrefix(mediaURL, "data:image/") { - return fmt.Errorf("only inline image data URLs are supported") - } - - header, data, found := strings.Cut(mediaURL, ",") - if !found || strings.TrimSpace(data) == "" { - return fmt.Errorf("image data URL is malformed") - } - if !strings.Contains(header, ";base64") { - return fmt.Errorf("image data URL must be base64 encoded") - } - mimeType, _, _ := strings.Cut(strings.TrimPrefix(header, "data:"), ";") - if _, ok := allowedInlineImageMIMETypes[mimeType]; !ok { - return fmt.Errorf("unsupported image format: %s", mimeType) - } - - data = strings.TrimSpace(data) - if base64.StdEncoding.DecodedLen(len(data)) > config.DefaultMaxMediaSize { - return fmt.Errorf("image exceeds %d byte limit", config.DefaultMaxMediaSize) - } - if _, err := base64.StdEncoding.DecodeString(data); err != nil { - return fmt.Errorf("invalid base64 image data") - } - - return nil -} - -// setContextUsagePayload adds context window usage stats to a pico payload. -func setContextUsagePayload(payload map[string]any, u *bus.ContextUsage) { - if u == nil { - return - } - payload["context_usage"] = map[string]any{ - "used_tokens": u.UsedTokens, - "total_tokens": u.TotalTokens, - "history_tokens": u.HistoryTokens, - "compress_at_tokens": u.CompressAtTokens, - "summarize_at_tokens": u.SummarizeAtTokens, - "used_percent": u.UsedPercent, - } -} - -// setTurnUsagePayload attaches real per-turn LLM token usage to the payload. -// Input and output are kept separate (billed at different rates); total is a -// convenience sum. Omitted entirely when both counts are zero. -func setTurnUsagePayload(payload map[string]any, inputTokens, outputTokens int) { - if inputTokens <= 0 && outputTokens <= 0 { - return - } - payload[PayloadKeyUsage] = map[string]any{ - "input_tokens": inputTokens, - "output_tokens": outputTokens, - "total_tokens": inputTokens + outputTokens, - } -} - -func picoToolCallsPayload(msg bus.OutboundMessage) ([]utils.VisibleToolCall, bool) { - raw := strings.TrimSpace(msg.Context.Raw[PayloadKeyToolCalls]) - if raw == "" { - return nil, false - } - - var toolCalls []utils.VisibleToolCall - if err := json.Unmarshal([]byte(raw), &toolCalls); err != nil || len(toolCalls) == 0 { - return nil, false - } - return toolCalls, true -} - -func (c *PicoChannel) editMessage( - ctx context.Context, - chatID string, - messageID string, - content string, - contextUsage *bus.ContextUsage, -) error { - return c.editMessagePayload(ctx, chatID, messageID, map[string]any{ - PayloadKeyContent: content, - }, contextUsage) -} - -func (c *PicoChannel) editMessagePayload( - ctx context.Context, - chatID string, - messageID string, - payload map[string]any, - contextUsage *bus.ContextUsage, -) error { - if payload == nil { - payload = map[string]any{} - } - normalized := make(map[string]any, len(payload)+1) - for key, value := range payload { - normalized[key] = value - } - if _, ok := normalized[PayloadKeyContent]; !ok { - normalized[PayloadKeyContent] = "" - } - normalized["message_id"] = messageID - setContextUsagePayload(normalized, contextUsage) - outMsg := newMessage(TypeMessageUpdate, normalized) - return c.broadcastToSession(chatID, outMsg) -} diff --git a/pkg/channels/pico/pico_test.go b/pkg/channels/pico/pico_test.go deleted file mode 100644 index f76cd113..00000000 --- a/pkg/channels/pico/pico_test.go +++ /dev/null @@ -1,1072 +0,0 @@ -package pico - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "sync" - "testing" - "time" - - "github.com/gorilla/websocket" - - "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 newTestPicoChannel(t *testing.T) *PicoChannel { - t.Helper() - - bc := &config.Channel{Type: config.ChannelPico, Enabled: true} - cfg := &config.PicoSettings{} - cfg.SetToken("test-token") - ch, err := NewPicoChannel(bc, cfg, bus.NewMessageBus()) - if err != nil { - t.Fatalf("NewPicoChannel: %v", err) - } - - ch.ctx = context.Background() - return ch -} - -func TestHandleMessageSend_ForwardsMessageMetadata(t *testing.T) { - msgBus := bus.NewMessageBus() - bc := &config.Channel{Type: config.ChannelPico, Enabled: true} - cfg := &config.PicoSettings{} - cfg.SetToken("test-token") - ch, err := NewPicoChannel(bc, cfg, msgBus) - if err != nil { - t.Fatalf("NewPicoChannel: %v", err) - } - ch.ctx = context.Background() - - ch.handleMessageSend(&picoConn{id: "conn-1", sessionID: "sess-1"}, PicoMessage{ - Type: TypeMessageSend, - ID: "msg-1", - SessionID: "sess-1", - Payload: map[string]any{ - PayloadKeyContent: "hello", - }, - }) - - select { - case inbound := <-msgBus.InboundChan(): - if inbound.Content != "hello" { - t.Fatalf("content = %q, want hello", inbound.Content) - } - if got := inbound.Context.Raw["session_id"]; got != "sess-1" { - t.Fatalf("session_id raw = %q, want sess-1", got) - } - case <-time.After(time.Second): - t.Fatal("expected inbound pico message") - } -} - -func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T) { - ch := &PicoChannel{ - progress: channels.NewToolFeedbackAnimator(nil), - } - ch.RecordToolFeedbackMessage("pico:chat-1", "msg-1", "🔧 `read_file`") - - msgIDs, handled := ch.finalizeTrackedToolFeedbackMessage( - context.Background(), - "pico:chat-1", - "final reply", - func(_ context.Context, chatID, messageID string, payload map[string]any, contextUsage *bus.ContextUsage) error { - if _, ok := ch.currentToolFeedbackMessage(chatID); ok { - t.Fatal("expected tracked tool feedback to be stopped before edit") - } - if chatID != "pico:chat-1" || messageID != "msg-1" { - t.Fatalf("unexpected edit args: %s %s", chatID, messageID) - } - if got := payload[PayloadKeyContent]; got != "final reply" { - t.Fatalf("unexpected content payload: %#v", got) - } - if contextUsage != nil { - t.Fatalf("unexpected context usage: %+v", contextUsage) - } - return nil - }, - nil, - nil, - ) - if !handled { - t.Fatal("expected finalizeTrackedToolFeedbackMessage to handle tracked message") - } - if len(msgIDs) != 1 || msgIDs[0] != "msg-1" { - t.Fatalf("finalizeTrackedToolFeedbackMessage() ids = %v, want [msg-1]", msgIDs) - } -} - -func TestDismissTrackedToolFeedbackMessage_DeletesProgressMessage(t *testing.T) { - ch := &PicoChannel{ - progress: channels.NewToolFeedbackAnimator(nil), - } - ch.RecordToolFeedbackMessage("pico:chat-1", "msg-1", "🔧 `read_file`") - - var deleted struct { - chatID string - messageID string - } - ch.deleteMessageFn = func(_ context.Context, chatID string, messageID string) error { - deleted.chatID = chatID - deleted.messageID = messageID - return nil - } - - ch.DismissToolFeedbackMessage(context.Background(), "pico:chat-1") - - if deleted.chatID != "pico:chat-1" || deleted.messageID != "msg-1" { - t.Fatalf("unexpected delete target: %+v", deleted) - } - if _, ok := ch.currentToolFeedbackMessage("pico:chat-1"); ok { - t.Fatal("expected tracked tool feedback to be cleared after dismissal") - } -} - -func TestSend_ThoughtMessageDoesNotFinalizeTrackedToolFeedback(t *testing.T) { - ch := newTestPicoChannel(t) - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - ch.RecordToolFeedbackMessage("pico:sess-1", "msg-progress", "🔧 `read_file`\nReading config") - - if _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "pico:sess-1", - Content: "thinking trace", - Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:sess-1", - Raw: map[string]string{ - "message_kind": MessageKindThought, - PayloadKeyModelName: "gpt-5.4-mini", - }, - }, - }); err != nil { - t.Fatalf("Send(thought) error = %v", err) - } - - select { - case msg := <-received: - if msg.Type != TypeMessageCreate { - t.Fatalf("thought message type = %q, want %q", msg.Type, TypeMessageCreate) - } - payload := msg.Payload - if got := payload[PayloadKeyContent]; got != "thinking trace" { - t.Fatalf("thought content = %#v, want %q", got, "thinking trace") - } - if got := payload[PayloadKeyKind]; got != MessageKindThought { - t.Fatalf("thought kind = %#v, want %q", got, MessageKindThought) - } - if got := payload[PayloadKeyModelName]; got != "gpt-5.4-mini" { - t.Fatalf("thought model_name = %#v, want %q", got, "gpt-5.4-mini") - } - if got := payload["message_id"]; got == "msg-progress" || got == nil || got == "" { - t.Fatalf("thought message_id = %#v, want new non-progress id", got) - } - case <-time.After(time.Second): - t.Fatal("expected thought message to be delivered") - } - - if msgID, ok := ch.currentToolFeedbackMessage("pico:sess-1"); !ok || msgID != "msg-progress" { - t.Fatalf("tracked tool feedback = (%q, %v), want (msg-progress, true)", msgID, ok) - } - - if _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "pico:sess-1", - Content: "final reply", - Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:sess-1", - Raw: map[string]string{ - PayloadKeyModelName: "gpt-5.4", - }, - }, - ContextUsage: &bus.ContextUsage{ - UsedTokens: 321, - TotalTokens: 4096, - CompressAtTokens: 3072, - UsedPercent: 8, - }, - }); err != nil { - t.Fatalf("Send(final) error = %v", err) - } - - select { - case msg := <-received: - if msg.Type != TypeMessageUpdate { - t.Fatalf("final message type = %q, want %q", msg.Type, TypeMessageUpdate) - } - payload := msg.Payload - if got := payload["message_id"]; got != "msg-progress" { - t.Fatalf("final message_id = %#v, want %q", got, "msg-progress") - } - if got := payload[PayloadKeyContent]; got != "final reply" { - t.Fatalf("final content = %#v, want %q", got, "final reply") - } - if got := payload[PayloadKeyModelName]; got != "gpt-5.4" { - t.Fatalf("final model_name = %#v, want %q", got, "gpt-5.4") - } - rawUsage, ok := payload["context_usage"].(map[string]any) - if !ok { - t.Fatalf("final context_usage = %#v, want map payload", payload["context_usage"]) - } - if got, ok := rawUsage["used_tokens"].(float64); !ok || got != 321 { - t.Fatalf("used_tokens = %#v, want 321", rawUsage["used_tokens"]) - } - if got, ok := rawUsage["total_tokens"].(float64); !ok || got != 4096 { - t.Fatalf("total_tokens = %#v, want 4096", rawUsage["total_tokens"]) - } - case <-time.After(time.Second): - t.Fatal("expected final reply to finalize tracked tool feedback") - } - - if _, ok := ch.currentToolFeedbackMessage("pico:sess-1"); ok { - t.Fatal("expected tracked tool feedback to be cleared after final reply") - } -} - -func TestSend_CommandReplyPreservesToolFeedback(t *testing.T) { - ch := newTestPicoChannel(t) - if err := ch.Start(t.Context()); err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = ch.Stop(context.Background()) }) - clientConn, received, cleanup := newTestPicoWebSocket(t) - t.Cleanup(cleanup) - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - ch.RecordToolFeedbackMessage("pico:sess-1", "progress-1", "Working") - _, err := ch.Send(t.Context(), bus.OutboundMessage{ - ChatID: "pico:sess-1", Content: "请待会再试", - Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}}, - }) - if err != nil { - t.Fatal(err) - } - select { - case msg := <-received: - if msg.Type != TypeMessageCreate || msg.Payload[PayloadKeyContent] != "请待会再试" || - msg.Payload["message_id"] == "progress-1" { - t.Fatalf("command reply replaced task progress: %+v", msg) - } - case <-time.After(time.Second): - t.Fatal("command reply was not delivered") - } - if id, ok := ch.currentToolFeedbackMessage("pico:sess-1"); !ok || id != "progress-1" { - t.Fatal("task progress was removed") - } -} - -func TestSend_ToolCallsMessageIncludesModelName(t *testing.T) { - ch := newTestPicoChannel(t) - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - if _, err := ch.Send(context.Background(), bus.OutboundMessage{ - ChatID: "pico:sess-1", - Content: "", - Context: bus.InboundContext{ - Channel: "pico", - ChatID: "pico:sess-1", - Raw: map[string]string{ - "message_kind": MessageKindToolCalls, - PayloadKeyModelName: "gpt-5.4", - PayloadKeyToolCalls: `[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\"}"}}]`, - }, - }, - }); err != nil { - t.Fatalf("Send(tool_calls) error = %v", err) - } - - select { - case msg := <-received: - if msg.Type != TypeMessageCreate { - t.Fatalf("tool_calls message type = %q, want %q", msg.Type, TypeMessageCreate) - } - payload := msg.Payload - if got := payload[PayloadKeyKind]; got != MessageKindToolCalls { - t.Fatalf("tool_calls kind = %#v, want %q", got, MessageKindToolCalls) - } - if got := payload[PayloadKeyModelName]; got != "gpt-5.4" { - t.Fatalf("tool_calls model_name = %#v, want %q", got, "gpt-5.4") - } - if _, ok := payload[PayloadKeyToolCalls].([]any); !ok { - t.Fatalf("tool_calls payload = %#v, want parsed array", payload[PayloadKeyToolCalls]) - } - case <-time.After(time.Second): - t.Fatal("expected tool_calls message to be delivered") - } -} - -func TestSendPlaceholder_EmitsNormalMessageWithoutKind(t *testing.T) { - ch := newTestPicoChannel(t) - ch.bc.Placeholder.Enabled = true - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - msgID, err := ch.SendPlaceholder(context.Background(), "pico:sess-1") - if err != nil { - t.Fatalf("SendPlaceholder() error = %v", err) - } - if msgID == "" { - t.Fatal("expected placeholder message id") - } - - select { - case msg := <-received: - if msg.Type != TypeMessageCreate { - t.Fatalf("placeholder message type = %q, want %q", msg.Type, TypeMessageCreate) - } - payload := msg.Payload - if got := payload["message_id"]; got != msgID { - t.Fatalf("placeholder message_id = %#v, want %q", got, msgID) - } - if got := payload[PayloadKeyContent]; got != "Thinking..." { - t.Fatalf("placeholder content = %#v, want %q", got, "Thinking...") - } - if got := payload[PayloadKeyPlaceholder]; got != true { - t.Fatalf("placeholder marker = %#v, want true", got) - } - if got, ok := payload[PayloadKeyKind]; ok { - t.Fatalf("placeholder kind = %#v, want absent", got) - } - case <-time.After(time.Second): - t.Fatal("expected placeholder message to be delivered") - } -} - -func TestBeginStream_CreatesAndUpdatesSameMessage(t *testing.T) { - ch := newTestPicoChannel(t) - ch.config.Streaming = config.StreamingConfig{ - Enabled: true, - ThrottleSeconds: 1, - MinGrowthChars: 1, - } - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - streamer, err := ch.BeginStream(context.Background(), "pico:sess-1") - if err != nil { - t.Fatalf("BeginStream() error = %v", err) - } - if setter, ok := streamer.(interface{ SetModelName(modelName string) }); ok { - setter.SetModelName("gpt-5.4") - } - if err := streamer.Update(context.Background(), "hello"); err != nil { - t.Fatalf("Update(first) error = %v", err) - } - first := mustReceivePicoMessage(t, received) - if first.Type != TypeMessageCreate { - t.Fatalf("first type = %q, want %q", first.Type, TypeMessageCreate) - } - msgID, _ := first.Payload["message_id"].(string) - if msgID == "" { - t.Fatalf("first message_id = %#v, want non-empty", first.Payload["message_id"]) - } - if got := first.Payload[PayloadKeyContent]; got != "hello" { - t.Fatalf("first content = %#v, want hello", got) - } - if got := first.Payload[PayloadKeyModelName]; got != "gpt-5.4" { - t.Fatalf("first model_name = %#v, want %q", got, "gpt-5.4") - } - - rawStreamer := streamer.(*picoStreamer) - rawStreamer.mu.Lock() - rawStreamer.lastAt = time.Now().Add(-2 * time.Second) - rawStreamer.mu.Unlock() - secondContent := "hello world with enough growth to pass the default streaming threshold" - if err := streamer.Update(context.Background(), secondContent); err != nil { - t.Fatalf("Update(second) error = %v", err) - } - second := mustReceivePicoMessage(t, received) - if second.Type != TypeMessageUpdate { - t.Fatalf("second type = %q, want %q", second.Type, TypeMessageUpdate) - } - if got := second.Payload["message_id"]; got != msgID { - t.Fatalf("second message_id = %#v, want %q", got, msgID) - } - if got := second.Payload[PayloadKeyContent]; got != secondContent { - t.Fatalf("second content = %#v, want %q", got, secondContent) - } - if got := second.Payload[PayloadKeyModelName]; got != "gpt-5.4" { - t.Fatalf("second model_name = %#v, want %q", got, "gpt-5.4") - } -} - -func TestBeginStream_DefaultStreamingShowsSmallIncrements(t *testing.T) { - ch := newTestPicoChannel(t) - ch.config.Streaming = config.StreamingConfig{Enabled: true} - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - streamer, err := ch.BeginStream(context.Background(), "pico:sess-1") - if err != nil { - t.Fatalf("BeginStream() error = %v", err) - } - if err := streamer.Update(context.Background(), "h"); err != nil { - t.Fatalf("Update(first) error = %v", err) - } - first := mustReceivePicoMessage(t, received) - if first.Type != TypeMessageCreate { - t.Fatalf("first type = %q, want %q", first.Type, TypeMessageCreate) - } - msgID, _ := first.Payload["message_id"].(string) - if msgID == "" { - t.Fatalf("first message_id = %#v, want non-empty", first.Payload["message_id"]) - } - - if err := streamer.Update(context.Background(), "he"); err != nil { - t.Fatalf("Update(second) error = %v", err) - } - second := mustReceivePicoMessage(t, received) - if second.Type != TypeMessageUpdate { - t.Fatalf("second type = %q, want %q", second.Type, TypeMessageUpdate) - } - if got := second.Payload["message_id"]; got != msgID { - t.Fatalf("second message_id = %#v, want %q", got, msgID) - } - if got := second.Payload[PayloadKeyContent]; got != "he" { - t.Fatalf("second content = %#v, want he", got) - } -} - -func TestBeginStream_StreamsReasoningAsThoughtUpdates(t *testing.T) { - ch := newTestPicoChannel(t) - ch.config.Streaming = config.StreamingConfig{Enabled: true} - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - streamer, err := ch.BeginStream(context.Background(), "pico:sess-1") - if err != nil { - t.Fatalf("BeginStream() error = %v", err) - } - reasoningStreamer, ok := streamer.(bus.ReasoningStreamer) - if !ok { - t.Fatal("pico stream should support reasoning updates") - } - if setter, ok := streamer.(interface{ SetModelName(modelName string) }); ok { - setter.SetModelName("gpt-5.4-mini") - } - if err := reasoningStreamer.UpdateReasoning(context.Background(), "thinking"); err != nil { - t.Fatalf("UpdateReasoning(first) error = %v", err) - } - first := mustReceivePicoMessage(t, received) - if first.Type != TypeMessageCreate { - t.Fatalf("first type = %q, want %q", first.Type, TypeMessageCreate) - } - msgID, _ := first.Payload["message_id"].(string) - if msgID == "" { - t.Fatalf("first message_id = %#v, want non-empty", first.Payload["message_id"]) - } - if got := first.Payload[PayloadKeyKind]; got != MessageKindThought { - t.Fatalf("first kind = %#v, want %q", got, MessageKindThought) - } - if got := first.Payload[PayloadKeyContent]; got != "thinking" { - t.Fatalf("first content = %#v, want thinking", got) - } - if got := first.Payload[PayloadKeyModelName]; got != "gpt-5.4-mini" { - t.Fatalf("first model_name = %#v, want %q", got, "gpt-5.4-mini") - } - - if err := reasoningStreamer.UpdateReasoning(context.Background(), "thinking more"); err != nil { - t.Fatalf("UpdateReasoning(second) error = %v", err) - } - second := mustReceivePicoMessage(t, received) - if second.Type != TypeMessageUpdate { - t.Fatalf("second type = %q, want %q", second.Type, TypeMessageUpdate) - } - if got := second.Payload["message_id"]; got != msgID { - t.Fatalf("second message_id = %#v, want %q", got, msgID) - } - if got := second.Payload[PayloadKeyKind]; got != MessageKindThought { - t.Fatalf("second kind = %#v, want %q", got, MessageKindThought) - } - if got := second.Payload[PayloadKeyContent]; got != "thinking more" { - t.Fatalf("second content = %#v, want thinking more", got) - } - if got := second.Payload[PayloadKeyModelName]; got != "gpt-5.4-mini" { - t.Fatalf("second model_name = %#v, want %q", got, "gpt-5.4-mini") - } -} - -func TestBeginStream_ThrottlesIntermediateUpdatesAndFinalFlushes(t *testing.T) { - ch := newTestPicoChannel(t) - ch.config.Streaming = config.StreamingConfig{ - Enabled: true, - ThrottleSeconds: 60, - MinGrowthChars: 100, - } - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - streamer, err := ch.BeginStream(context.Background(), "pico:sess-1") - if err != nil { - t.Fatalf("BeginStream() error = %v", err) - } - if err := streamer.Update(context.Background(), "first"); err != nil { - t.Fatalf("Update(first) error = %v", err) - } - if err := streamer.Update(context.Background(), "first plus short growth"); err != nil { - t.Fatalf("Update(throttled) error = %v", err) - } - if err := streamer.Update(context.Background(), "first"+strings.Repeat("x", 120)); err != nil { - t.Fatalf("Update(enough growth too soon) error = %v", err) - } - - first := mustReceivePicoMessage(t, received) - if first.Type != TypeMessageCreate { - t.Fatalf("first type = %q, want %q", first.Type, TypeMessageCreate) - } - msgID, _ := first.Payload["message_id"].(string) - assertNoPicoMessage(t, received) - - rawStreamer := streamer.(*picoStreamer) - rawStreamer.mu.Lock() - rawStreamer.lastAt = time.Now().Add(-61 * time.Second) - rawStreamer.mu.Unlock() - if err := streamer.Update(context.Background(), "first plus small growth"); err != nil { - t.Fatalf("Update(enough time too little growth) error = %v", err) - } - assertNoPicoMessage(t, received) - - if err := streamer.Finalize(context.Background(), "first plus final text"); err != nil { - t.Fatalf("Finalize() error = %v", err) - } - final := mustReceivePicoMessage(t, received) - if final.Type != TypeMessageUpdate { - t.Fatalf("final type = %q, want %q", final.Type, TypeMessageUpdate) - } - if got := final.Payload["message_id"]; got != msgID { - t.Fatalf("final message_id = %#v, want %q", got, msgID) - } - if got := final.Payload[PayloadKeyContent]; got != "first plus final text" { - t.Fatalf("final content = %#v, want final text", got) - } - assertNoPicoMessage(t, received) -} - -func TestBeginStream_FinalizeIncludesContextUsage(t *testing.T) { - ch := newTestPicoChannel(t) - ch.config.Streaming = config.StreamingConfig{ - Enabled: true, - ThrottleSeconds: 0, - MinGrowthChars: 0, - } - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - streamer, err := ch.BeginStream(context.Background(), "pico:sess-1") - if err != nil { - t.Fatalf("BeginStream() error = %v", err) - } - if setter, ok := streamer.(interface{ SetModelName(modelName string) }); ok { - setter.SetModelName("gpt-5.4") - } - if err := streamer.Update(context.Background(), "partial"); err != nil { - t.Fatalf("Update() error = %v", err) - } - first := mustReceivePicoMessage(t, received) - msgID, _ := first.Payload["message_id"].(string) - - contextStreamer, ok := streamer.(interface { - FinalizeWithContext(ctx context.Context, content string, usage *bus.ContextUsage) error - }) - if !ok { - t.Fatal("streamer should support FinalizeWithContext") - } - if err := contextStreamer.FinalizeWithContext(context.Background(), "final", &bus.ContextUsage{ - UsedTokens: 10, - TotalTokens: 100, - HistoryTokens: 5, - CompressAtTokens: 80, - SummarizeAtTokens: 60, - UsedPercent: 10, - }); err != nil { - t.Fatalf("FinalizeWithContext() error = %v", err) - } - - final := mustReceivePicoMessage(t, received) - if final.Type != TypeMessageUpdate { - t.Fatalf("final type = %q, want %q", final.Type, TypeMessageUpdate) - } - if got := final.Payload["message_id"]; got != msgID { - t.Fatalf("final message_id = %#v, want %q", got, msgID) - } - if got := final.Payload[PayloadKeyModelName]; got != "gpt-5.4" { - t.Fatalf("final model_name = %#v, want %q", got, "gpt-5.4") - } - rawUsage, ok := final.Payload["context_usage"].(map[string]any) - if !ok { - t.Fatalf("final context_usage = %#v, want map", final.Payload["context_usage"]) - } - if got := rawUsage["used_tokens"]; got != float64(10) { - t.Fatalf("used_tokens = %#v, want 10", got) - } - if got := rawUsage["history_tokens"]; got != float64(5) { - t.Fatalf("history_tokens = %#v, want 5", got) - } - if got := rawUsage["summarize_at_tokens"]; got != float64(60) { - t.Fatalf("summarize_at_tokens = %#v, want 60", got) - } -} - -func TestCreateAndAddConnection_RespectsMaxConnectionsConcurrently(t *testing.T) { - ch := newTestPicoChannel(t) - - const ( - maxConns = 5 - goroutines = 64 - sessionID = "session-a" - ) - - var wg sync.WaitGroup - var mu sync.Mutex - successCount := 0 - errCount := 0 - - wg.Add(goroutines) - for i := 0; i < goroutines; i++ { - go func() { - defer wg.Done() - - pc, err := ch.createAndAddConnection(nil, sessionID, maxConns) - mu.Lock() - defer mu.Unlock() - - if err == nil { - successCount++ - if pc == nil { - t.Errorf("pc is nil on success") - } - return - } - if !errors.Is(err, channels.ErrTemporary) { - t.Errorf("unexpected error: %v", err) - return - } - errCount++ - }() - } - wg.Wait() - - if successCount > maxConns { - t.Fatalf("successCount=%d > maxConns=%d", successCount, maxConns) - } - if successCount+errCount != goroutines { - t.Fatalf("success=%d err=%d total=%d want=%d", successCount, errCount, successCount+errCount, goroutines) - } - if got := ch.currentConnCount(); got != maxConns { - t.Fatalf("currentConnCount=%d want=%d", got, maxConns) - } -} - -func TestRemoveConnection_CleansBothIndexes(t *testing.T) { - ch := newTestPicoChannel(t) - - pc, err := ch.createAndAddConnection(nil, "session-cleanup", 10) - if err != nil { - t.Fatalf("createAndAddConnection: %v", err) - } - - removed := ch.removeConnection(pc.id) - if removed == nil { - t.Fatal("removeConnection returned nil") - } - - ch.connsMu.RLock() - defer ch.connsMu.RUnlock() - - if _, ok := ch.connections[pc.id]; ok { - t.Fatalf("connID %s still exists in connections", pc.id) - } - if _, ok := ch.sessionConnections[pc.sessionID]; ok { - t.Fatalf("session %s still exists in sessionConnections", pc.sessionID) - } - if got := len(ch.connections); got != 0 { - t.Fatalf("len(connections)=%d want=0", got) - } -} - -func TestBroadcastToSession_TargetsOnlyRequestedSession(t *testing.T) { - ch := newTestPicoChannel(t) - - target := &picoConn{id: "target", sessionID: "s-target"} - target.closed.Store(true) - ch.addConnForTest(target) - - other := &picoConn{id: "other", sessionID: "s-other"} - ch.addConnForTest(other) - - err := ch.broadcastToSession("pico:s-target", newMessage(TypeMessageCreate, map[string]any{"content": "hello"})) - if err == nil { - t.Fatal("expected send failure due to closed target connection") - } - if !errors.Is(err, channels.ErrSendFailed) { - t.Fatalf("expected ErrSendFailed, got %v", err) - } -} - -func TestSendMedia_ResolvesMediaBeforeDelivery(t *testing.T) { - ch := newTestPicoChannel(t) - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - localPath := filepath.Join(t.TempDir(), "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) - } - - closedConn := &picoConn{id: "closed", sessionID: "sess-1"} - closedConn.closed.Store(true) - ch.addConnForTest(closedConn) - - _, err = ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ - ChatID: "pico:sess-1", - Parts: []bus.MediaPart{{ - Ref: ref, - Type: "file", - Filename: "report.txt", - ContentType: "text/plain", - }}, - }) - if !errors.Is(err, channels.ErrSendFailed) { - t.Fatalf("SendMedia() error = %v, want ErrSendFailed", err) - } -} - -func TestSendMedia_DismissesTrackedToolFeedbackMessage(t *testing.T) { - ch := newTestPicoChannel(t) - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - localPath := filepath.Join(t.TempDir(), "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) - } - - ch.RecordToolFeedbackMessage("pico:sess-1", "msg-progress", "🔧 `read_file`") - - var deleted struct { - chatID string - messageID string - } - ch.deleteMessageFn = func(_ context.Context, chatID string, messageID string) error { - deleted.chatID = chatID - deleted.messageID = messageID - return nil - } - - _, err = ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ - ChatID: "pico:sess-1", - Parts: []bus.MediaPart{{ - Ref: ref, - Type: "file", - Filename: "report.txt", - ContentType: "text/plain", - }}, - }) - if err != nil { - t.Fatalf("SendMedia() error = %v", err) - } - - select { - case msg := <-received: - if msg.Type != TypeMessageCreate { - t.Fatalf("message type = %q, want %q", msg.Type, TypeMessageCreate) - } - case <-time.After(time.Second): - t.Fatal("expected media message to be delivered") - } - - if deleted.chatID != "pico:sess-1" || deleted.messageID != "msg-progress" { - t.Fatalf("unexpected delete target: %+v", deleted) - } - if _, ok := ch.currentToolFeedbackMessage("pico:sess-1"); ok { - t.Fatal("expected tracked tool feedback to be cleared after media delivery") - } -} - -func TestSendMedia_IncludesCaptionAndAttachmentsInSinglePayload(t *testing.T) { - ch := newTestPicoChannel(t) - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - clientConn, received, cleanup := newTestPicoWebSocket(t) - defer cleanup() - ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"}) - - localPath := filepath.Join(t.TempDir(), "photo.png") - if err := os.WriteFile(localPath, []byte("png-body"), 0o600); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - ref, err := store.Store(localPath, media.MediaMeta{ - Filename: "photo.png", - ContentType: "image/png", - }, "test-scope") - if err != nil { - t.Fatalf("Store() error = %v", err) - } - - _, err = ch.SendMedia(context.Background(), bus.OutboundMediaMessage{ - ChatID: "pico:sess-1", - Parts: []bus.MediaPart{{ - Ref: ref, - Type: "image", - Filename: "photo.png", - ContentType: "image/png", - Caption: "recipe translation", - }}, - }) - if err != nil { - t.Fatalf("SendMedia() error = %v", err) - } - - select { - case msg := <-received: - if msg.Type != TypeMessageCreate { - t.Fatalf("message type = %q, want %q", msg.Type, TypeMessageCreate) - } - payload := msg.Payload - if got := payload[PayloadKeyContent]; got != "recipe translation" { - t.Fatalf("content = %#v, want %q", got, "recipe translation") - } - rawAttachments, ok := payload["attachments"].([]any) - if !ok || len(rawAttachments) != 1 { - t.Fatalf("attachments = %#v, want 1 attachment", payload["attachments"]) - } - attachment, ok := rawAttachments[0].(map[string]any) - if !ok { - t.Fatalf("attachment = %#v, want map", rawAttachments[0]) - } - if got := attachment["type"]; got != "image" { - t.Fatalf("attachment type = %#v, want image", got) - } - if got := attachment["filename"]; got != "photo.png" { - t.Fatalf("attachment filename = %#v, want photo.png", got) - } - case <-time.After(time.Second): - t.Fatal("expected media payload to be delivered") - } -} - -func TestPicoDownloadURLForRef(t *testing.T) { - got, err := picoDownloadURLForRef("media://attachment-1") - if err != nil { - t.Fatalf("picoDownloadURLForRef() error = %v", err) - } - if got != "/pico/media/attachment-1" { - t.Fatalf("picoDownloadURLForRef() = %q, want %q", got, "/pico/media/attachment-1") - } -} - -func TestHandleMediaDownload_ServesStoredFile(t *testing.T) { - ch := newTestPicoChannel(t) - store := media.NewFileMediaStore() - ch.SetMediaStore(store) - - if err := ch.Start(context.Background()); err != nil { - t.Fatalf("Start() error = %v", err) - } - defer ch.Stop(context.Background()) - - localPath := filepath.Join(t.TempDir(), "report.txt") - if err := os.WriteFile(localPath, []byte("downloadable"), 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) - } - - refID := strings.TrimPrefix(ref, "media://") - req := httptest.NewRequest("GET", "/pico/media/"+refID, nil) - req.Header.Set("Authorization", "Bearer test-token") - rec := httptest.NewRecorder() - - ch.ServeHTTP(rec, req) - - if rec.Code != 200 { - t.Fatalf("status = %d, want 200", rec.Code) - } - if body := rec.Body.String(); body != "downloadable" { - t.Fatalf("body = %q, want %q", body, "downloadable") - } - if got := rec.Header().Get("Content-Type"); got != "text/plain" { - t.Fatalf("Content-Type = %q, want %q", got, "text/plain") - } -} - -func mustReceivePicoMessage(t *testing.T, received <-chan PicoMessage) PicoMessage { - t.Helper() - select { - case msg := <-received: - return msg - case <-time.After(time.Second): - t.Fatal("expected pico message") - } - return PicoMessage{} -} - -func assertNoPicoMessage(t *testing.T, received <-chan PicoMessage) { - t.Helper() - select { - case msg := <-received: - t.Fatalf("unexpected pico message: %+v", msg) - case <-time.After(150 * time.Millisecond): - } -} - -func (c *PicoChannel) addConnForTest(pc *picoConn) { - c.connsMu.Lock() - defer c.connsMu.Unlock() - if c.connections == nil { - c.connections = make(map[string]*picoConn) - } - if c.sessionConnections == nil { - c.sessionConnections = make(map[string]map[string]*picoConn) - } - if _, exists := c.connections[pc.id]; exists { - panic(fmt.Sprintf("duplicate conn id in test: %s", pc.id)) - } - c.connections[pc.id] = pc - bySession, ok := c.sessionConnections[pc.sessionID] - if !ok { - bySession = make(map[string]*picoConn) - c.sessionConnections[pc.sessionID] = bySession - } - bySession[pc.id] = pc -} - -func newTestPicoWebSocket(t *testing.T) (*websocket.Conn, <-chan PicoMessage, func()) { - t.Helper() - - received := make(chan PicoMessage, 4) - upgrader := websocket.Upgrader{} - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - t.Errorf("Upgrade() error = %v", err) - return - } - defer conn.Close() - for { - var msg PicoMessage - if err := conn.ReadJSON(&msg); err != nil { - return - } - received <- msg - } - })) - - wsURL := "ws" + strings.TrimPrefix(server.URL, "http") - clientConn, resp, err := websocket.DefaultDialer.Dial(wsURL, nil) - if err != nil { - server.Close() - t.Fatalf("Dial() error = %v", err) - } - - cleanup := func() { - clientConn.Close() - server.Close() - } - defer resp.Body.Close() - return clientConn, received, cleanup -} diff --git a/pkg/channels/pico/pico_usage_test.go b/pkg/channels/pico/pico_usage_test.go deleted file mode 100644 index 444fb49f..00000000 --- a/pkg/channels/pico/pico_usage_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package pico - -import ( - "context" - "testing" -) - -func TestSetTurnUsagePayload(t *testing.T) { - t.Run("populates usage block when counts present", func(t *testing.T) { - payload := map[string]any{PayloadKeyContent: "hi"} - setTurnUsagePayload(payload, 1234, 567) - - raw, ok := payload[PayloadKeyUsage] - if !ok { - t.Fatalf("expected %q key in payload", PayloadKeyUsage) - } - usage, ok := raw.(map[string]any) - if !ok { - t.Fatalf("usage block is not a map: %T", raw) - } - if usage["input_tokens"] != 1234 { - t.Errorf("input_tokens = %v, want 1234", usage["input_tokens"]) - } - if usage["output_tokens"] != 567 { - t.Errorf("output_tokens = %v, want 567", usage["output_tokens"]) - } - if usage["total_tokens"] != 1801 { - t.Errorf("total_tokens = %v, want 1801", usage["total_tokens"]) - } - }) - - t.Run("omits usage block when both counts zero", func(t *testing.T) { - payload := map[string]any{PayloadKeyContent: "hi"} - setTurnUsagePayload(payload, 0, 0) - if _, ok := payload[PayloadKeyUsage]; ok { - t.Errorf("expected no %q key when counts are zero", PayloadKeyUsage) - } - }) -} - -// newCaptureStreamer returns a streamer whose broadcasts are captured into the -// returned map pointer, so tests need no live websocket. -func newCaptureStreamer() (*picoStreamer, *map[string]any) { - var last map[string]any - ch := &PicoChannel{} - ch.broadcastFn = func(chatID string, msg PicoMessage) error { - last = msg.Payload - return nil - } - s := &picoStreamer{channel: ch, chatID: "c1"} - return s, &last -} - -func TestStreamerEmitsUsageOnFinalize(t *testing.T) { - s, last := newCaptureStreamer() - s.SetTurnUsage(100, 40) - - // sendLocked with empty messageID takes the create branch, which attaches - // usage from the streamer's stored counts. - s.mu.Lock() - err := s.sendLocked(context.Background(), "answer", nil) - s.mu.Unlock() - if err != nil { - t.Fatalf("sendLocked: %v", err) - } - if _, ok := (*last)[PayloadKeyUsage]; !ok { - t.Fatalf("expected usage in payload, got %+v", *last) - } -} diff --git a/pkg/channels/pico/protocol.go b/pkg/channels/pico/protocol.go deleted file mode 100644 index ac92913d..00000000 --- a/pkg/channels/pico/protocol.go +++ /dev/null @@ -1,81 +0,0 @@ -package pico - -import ( - "strings" - "time" -) - -// Protocol message types. -const ( - // TypeMessageSend is sent from client to server. - TypeMessageSend = "message.send" - TypeMediaSend = "media.send" - TypePing = "ping" - - // TypeMessageCreate is sent from server to client. - TypeMessageCreate = "message.create" - TypeMessageUpdate = "message.update" - TypeMessageDelete = "message.delete" - TypeMediaCreate = "media.create" - TypeTypingStart = "typing.start" - TypeTypingStop = "typing.stop" - TypeError = "error" - TypePong = "pong" - - PayloadKeyContent = "content" - PayloadKeyThought = "thought" - PayloadKeyKind = "kind" - PayloadKeyPlaceholder = "placeholder" - PayloadKeyToolCalls = "tool_calls" - PayloadKeyModelName = "model_name" - PayloadKeyUsage = "usage" - - MessageKindThought = "thought" - MessageKindToolCalls = "tool_calls" -) - -// PicoMessage is the wire format for all Pico Protocol messages. -type PicoMessage struct { - Type string `json:"type"` - ID string `json:"id,omitempty"` - SessionID string `json:"session_id,omitempty"` - Timestamp int64 `json:"timestamp,omitempty"` - Payload map[string]any `json:"payload,omitempty"` -} - -// newMessage creates a PicoMessage with the given type and payload. -func newMessage(msgType string, payload map[string]any) PicoMessage { - return PicoMessage{ - Type: msgType, - Timestamp: time.Now().UnixMilli(), - Payload: payload, - } -} - -func isThoughtPayload(payload map[string]any) bool { - kind, _ := payload[PayloadKeyKind].(string) - if strings.EqualFold(strings.TrimSpace(kind), MessageKindThought) { - return true - } - - // Keep pico_client inbound-compatible with legacy servers that still send - // the pre-kind boolean thought marker. - thought, _ := payload[PayloadKeyThought].(bool) - return thought -} - -func newErrorWithPayload(code, message string, extra map[string]any) PicoMessage { - payload := map[string]any{ - "code": code, - "message": message, - } - for key, value := range extra { - payload[key] = value - } - return newMessage(TypeError, payload) -} - -// newError creates an error PicoMessage. -func newError(code, message string) PicoMessage { - return newErrorWithPayload(code, message, nil) -} diff --git a/pkg/config/config.go b/pkg/config/config.go index df232f77..c409705a 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -27,10 +27,6 @@ var rrCounter atomic.Uint64 // CurrentVersion is the latest config schema version const CurrentVersion = 3 -func init() { - initChannel() -} - // Config is the current config structure with version support. type Config struct { // Config schema version for migration. @@ -565,11 +561,6 @@ type DiscordSettings struct { MentionOnly bool `json:"mention_only" yaml:"-" env:"PICOCLAW_CHANNELS_DISCORD_MENTION_ONLY"` } -type MaixCamSettings struct { - Host string `json:"host" yaml:"-" env:"PICOCLAW_CHANNELS_MAIXCAM_HOST"` - Port int `json:"port" yaml:"-" env:"PICOCLAW_CHANNELS_MAIXCAM_PORT"` -} - type QQSettings struct { AppID string `json:"app_id" yaml:"-" env:"PICOCLAW_CHANNELS_QQ_APP_ID"` AppSecret SecureString `json:"app_secret,omitzero" yaml:"app_secret,omitempty" env:"PICOCLAW_CHANNELS_QQ_APP_SECRET"` @@ -668,30 +659,6 @@ func (c *WeixinSettings) SetToken(token string) { c.Token = *NewSecureString(token) } -type PicoSettings struct { - Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"PICOCLAW_CHANNELS_PICO_TOKEN"` - AllowTokenQuery bool `json:"allow_token_query,omitempty" yaml:"-"` - AllowOrigins []string `json:"allow_origins,omitempty" yaml:"-"` - Streaming StreamingConfig `json:"streaming,omitzero" yaml:"-"` - PingInterval int `json:"ping_interval,omitempty" yaml:"-"` - ReadTimeout int `json:"read_timeout,omitempty" yaml:"-"` - WriteTimeout int `json:"write_timeout,omitempty" yaml:"-"` - MaxConnections int `json:"max_connections,omitempty" yaml:"-"` -} - -// SetToken sets the Pico token and marks it as dirty for security saving -func (c *PicoSettings) SetToken(token string) { - c.Token = *NewSecureString(token) -} - -type PicoClientSettings struct { - URL string `json:"url" yaml:"-" env:"PICOCLAW_CHANNELS_PICO_CLIENT_URL"` - Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"PICOCLAW_CHANNELS_PICO_CLIENT_TOKEN"` - SessionID string `json:"session_id,omitempty" yaml:"-"` - PingInterval int `json:"ping_interval,omitempty" yaml:"-"` - ReadTimeout int `json:"read_timeout,omitempty" yaml:"-"` -} - type IRCSettings struct { Server string `json:"server" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_SERVER"` TLS bool `json:"tls" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_TLS"` diff --git a/pkg/config/config_channel.go b/pkg/config/config_channel.go index 232c37cd..7dc5c46a 100644 --- a/pkg/config/config_channel.go +++ b/pkg/config/config_channel.go @@ -17,8 +17,6 @@ import ( // Channel type constants — single source of truth for all channel type names. const ( - ChannelPico = "pico" - ChannelPicoClient = "pico_client" ChannelTelegram = "telegram" ChannelDiscord = "discord" ChannelFeishu = "feishu" @@ -33,7 +31,6 @@ const ( ChannelQQ = "qq" ChannelIRC = "irc" ChannelVK = "vk" - ChannelMaixCam = "maixcam" ChannelWhatsApp = "whatsapp" ChannelWhatsAppNative = "whatsapp_native" ChannelTeamsWebHook = "teams_webhook" @@ -41,27 +38,6 @@ const ( ChannelSlackWebHook = "slack_webhook" ) -func initChannel() { - registerSingletonChannel(ChannelPico) - registerSingletonChannel(ChannelPicoClient) -} - -// singletonRegistry stores which channel types are singletons (only allow one instance). -// Each channel type should call registerSingletonChannel in its init() if it's a singleton. -var singletonRegistry = make(map[string]struct{}) - -// registerSingletonChannel marks a channel type as singleton (only one instance allowed). -// Should be called from the channel type's init() function. -func registerSingletonChannel(channelType string) { - singletonRegistry[channelType] = struct{}{} -} - -// IsSingletonChannel returns true if the channel type only allows one instance. -func IsSingletonChannel(channelType string) bool { - _, ok := singletonRegistry[channelType] - return ok -} - // RawNode stores raw configuration data as JSON bytes, supporting both JSON and YAML. // Internally uses json.RawMessage, so Decode always uses json.Unmarshal // which correctly respects json struct tags. @@ -506,37 +482,6 @@ func (c ChannelsConfig) SetEnabled(name string, enabled bool) bool { return true } -// validateSingletonChannels checks that singleton channel types have at most -// one enabled instance. Returns an error if a singleton type has multiple enabled channels. -func validateSingletonChannels(channels ChannelsConfig) error { - typeCount := make(map[string]int) - typeNames := make(map[string][]string) - for name, bc := range channels { - if !bc.Enabled { - continue - } - t := bc.Type - if t == "" { - t = name - } - if IsSingletonChannel(t) { - typeCount[t]++ - typeNames[t] = append(typeNames[t], name) - } - } - for t, count := range typeCount { - if count > 1 { - return fmt.Errorf( - "channel type %q is singleton and does not support multiple instances, found %d enabled instances: %v", - t, - count, - typeNames[t], - ) - } - } - return nil -} - // BaseFieldNames are JSON keys that belong to Channel, not to channel-specific settings. var BaseFieldNames = map[string]struct{}{ "enabled": {}, @@ -660,8 +605,6 @@ func filterSecureFields(r RawNode, secureFields map[string]struct{}) RawNode { var channelSettingsMu sync.RWMutex var channelSettingsFactory = map[string]any{ - ChannelPico: (PicoSettings{}), - ChannelPicoClient: (PicoClientSettings{}), ChannelTelegram: (TelegramSettings{}), ChannelDiscord: (DiscordSettings{}), ChannelFeishu: (FeishuSettings{}), @@ -676,7 +619,6 @@ var channelSettingsFactory = map[string]any{ ChannelQQ: (QQSettings{}), ChannelIRC: (IRCSettings{}), ChannelVK: (VKSettings{}), - ChannelMaixCam: (MaixCamSettings{}), ChannelWhatsApp: (WhatsAppSettings{}), ChannelWhatsAppNative: (WhatsAppSettings{}), ChannelTeamsWebHook: (TeamsWebhookSettings{}), @@ -717,16 +659,15 @@ func isValidChannelType(channelType string) bool { } // InitChannelList validates and initializes all channels in the ChannelsConfig. -// It performs three steps: +// It performs two steps: // 1. Validates that each channel has a non-empty Type -// 2. Validates singleton constraints -// 3. Decodes Settings into the correct typed struct based on Type, -// so that b.extend contains the actual settings (e.g., PicoSettings) +// 2. Decodes Settings into the correct typed struct based on Type, +// so that b.extend contains the actual settings (e.g., TelegramSettings) // // After calling this method, callers can safely use b.extend via Decode() // without re-parsing raw Settings. func InitChannelList(channels ChannelsConfig) error { - // Step 1 & 3: validate type and decode into typed settings + // Validate type and decode into typed settings. for name, bc := range channels { if bc == nil { delete(channels, name) @@ -757,11 +698,6 @@ func InitChannelList(channels ChannelsConfig) error { } } - // Step 2: validate singleton constraints - if err := validateSingletonChannels(channels); err != nil { - return err - } - return nil } @@ -791,8 +727,6 @@ func applyTelegramStreamingEnvCompat(target any) { func validateChannelStreamingConfig(channelName string, target any) error { var streaming StreamingConfig switch settings := target.(type) { - case *PicoSettings: - streaming = settings.Streaming case *TelegramSettings: streaming = settings.Streaming case *WeComSettings: diff --git a/pkg/config/config_channel_test.go b/pkg/config/config_channel_test.go index b34048ff..0fda5511 100644 --- a/pkg/config/config_channel_test.go +++ b/pkg/config/config_channel_test.go @@ -144,30 +144,6 @@ func TestStreamingConfig_IsChannelGeneric(t *testing.T) { } } -func TestPicoSettings_StreamingConfig(t *testing.T) { - raw := RawNode(`{ - "token": "test-token", - "streaming": { - "enabled": true, - "throttle_seconds": 2, - "min_growth_chars": 80 - } - }`) - ch := &Channel{ - Type: ChannelPico, - Enabled: true, - Settings: raw, - } - ch.SetName("pico") - var picoCfg PicoSettings - if err := ch.Decode(&picoCfg); err != nil { - t.Fatalf("Decode() error = %v", err) - } - assert.True(t, picoCfg.Streaming.Enabled) - assert.Equal(t, 2, picoCfg.Streaming.ThrottleSeconds) - assert.Equal(t, 80, picoCfg.Streaming.MinGrowthChars) -} - func TestWeComSettings_StreamingConfig(t *testing.T) { raw := RawNode(`{ "bot_id": "bot-1", @@ -192,7 +168,7 @@ func TestWeComSettings_StreamingConfig(t *testing.T) { assert.Equal(t, 160, wecomCfg.Streaming.MinGrowthChars) } -func TestPicoStreamingConfig_Defaults(t *testing.T) { +func TestStreamingConfig_Defaults(t *testing.T) { cfg := StreamingConfig{Enabled: true} got := cfg.WithDefaults(1, 40) assert.Equal(t, 1, got.ThrottleSeconds) @@ -220,10 +196,10 @@ func TestInitChannelList_TelegramStreamingEnvCompatibility(t *testing.T) { Enabled: true, Settings: RawNode(`{"token":"telegram-token"}`), }, - "pico": { - Type: ChannelPico, + "wecom": { + Type: ChannelWeCom, Enabled: true, - Settings: RawNode(`{"token":"pico-token"}`), + Settings: RawNode(`{"bot_id":"bot-1"}`), }, } if err := InitChannelList(channels); err != nil { @@ -239,14 +215,14 @@ func TestInitChannelList_TelegramStreamingEnvCompatibility(t *testing.T) { assert.Equal(t, 3, tgCfg.Streaming.ThrottleSeconds) assert.Equal(t, 120, tgCfg.Streaming.MinGrowthChars) - picoDecoded, err := channels["pico"].GetDecoded() + wecomDecoded, err := channels["wecom"].GetDecoded() if err != nil { - t.Fatalf("pico GetDecoded() error = %v", err) + t.Fatalf("wecom GetDecoded() error = %v", err) } - picoCfg := picoDecoded.(*PicoSettings) - assert.False(t, picoCfg.Streaming.Enabled) - assert.Equal(t, 0, picoCfg.Streaming.ThrottleSeconds) - assert.Equal(t, 0, picoCfg.Streaming.MinGrowthChars) + wecomCfg := wecomDecoded.(*WeComSettings) + assert.False(t, wecomCfg.Streaming.Enabled) + assert.Equal(t, 0, wecomCfg.Streaming.ThrottleSeconds) + assert.Equal(t, 0, wecomCfg.Streaming.MinGrowthChars) } func TestInitChannelList_RejectsNegativeStreamingDeliveryValues(t *testing.T) { @@ -255,16 +231,6 @@ func TestInitChannelList_RejectsNegativeStreamingDeliveryValues(t *testing.T) { channelType string settings string }{ - { - name: "pico throttle", - channelType: ChannelPico, - settings: `{"token":"pico-token","streaming":{"enabled":true,"throttle_seconds":-1}}`, - }, - { - name: "pico growth", - channelType: ChannelPico, - settings: `{"token":"pico-token","streaming":{"enabled":true,"min_growth_chars":-1}}`, - }, { name: "telegram throttle", channelType: ChannelTelegram, @@ -338,11 +304,11 @@ func TestChannel_JSON_Marshal_SecureMasked(t *testing.T) { func TestChannel_JSON_Marshal_OmitsUnconfiguredStreaming(t *testing.T) { ch := Channel{ Enabled: true, - Type: ChannelPico, - name: "pico", - Settings: mustParseRawNode(`{"ping_interval":30}`), + Type: ChannelWeCom, + name: "wecom", + Settings: mustParseRawNode(`{"bot_id":"bot-1"}`), } - var cfg PicoSettings + var cfg WeComSettings require.NoError(t, ch.Decode(&cfg)) data, err := json.MarshalIndent(ch, "", " ") diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 52dbea3b..a91199e5 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -1002,21 +1002,6 @@ func TestDefaultConfig_ChannelStreamingDisabled(t *testing.T) { t.Fatal("DefaultConfig().telegram.settings.streaming.enabled should be false") } - pico := cfg.Channels.Get(ChannelPico) - if pico == nil { - t.Fatal("DefaultConfig() missing pico channel") - } - decoded, err = pico.GetDecoded() - if err != nil { - t.Fatalf("pico GetDecoded() error = %v", err) - } - picoSettings, ok := decoded.(*PicoSettings) - if !ok { - t.Fatalf("pico settings type = %T, want *PicoSettings", decoded) - } - if !picoSettings.Streaming.Enabled { - t.Fatal("DefaultConfig().pico.settings.streaming.enabled should be true") - } } func TestDefaultConfig_DeltaChatExample(t *testing.T) { @@ -1051,52 +1036,6 @@ func TestDefaultConfig_DeltaChatExample(t *testing.T) { } } -func TestValidateSingletonChannels_RejectsMultipleInstances(t *testing.T) { - channels := ChannelsConfig{ - "pico1": &Channel{Enabled: true, Type: ChannelPico}, - "pico2": &Channel{Enabled: true, Type: ChannelPico}, - } - err := validateSingletonChannels(channels) - if err == nil { - t.Fatal("expected error for multiple pico channels, got nil") - } - if !strings.Contains(err.Error(), "singleton") { - t.Fatalf("expected singleton error, got: %v", err) - } -} - -func TestValidateSingletonChannels_AllowsSingleInstance(t *testing.T) { - channels := ChannelsConfig{ - "pico1": &Channel{Enabled: true, Type: ChannelPico}, - } - err := validateSingletonChannels(channels) - if err != nil { - t.Fatalf("expected no error for single pico channel, got: %v", err) - } -} - -func TestValidateSingletonChannels_IgnoresDisabledInstances(t *testing.T) { - channels := ChannelsConfig{ - "pico1": &Channel{Enabled: true, Type: ChannelPico}, - "pico2": &Channel{Enabled: false, Type: ChannelPico}, - } - err := validateSingletonChannels(channels) - if err != nil { - t.Fatalf("expected no error when only one pico channel is enabled, got: %v", err) - } -} - -func TestValidateSingletonChannels_AllowsMultiInstanceTypes(t *testing.T) { - channels := ChannelsConfig{ - "tg1": &Channel{Enabled: true, Type: ChannelTelegram}, - "tg2": &Channel{Enabled: true, Type: ChannelTelegram}, - } - err := validateSingletonChannels(channels) - if err != nil { - t.Fatalf("telegram should allow multiple instances, got error: %v", err) - } -} - // TestDefaultConfig_WebTools verifies web tools config func TestDefaultConfig_WebTools(t *testing.T) { cfg := DefaultConfig() @@ -1190,49 +1129,6 @@ func TestSaveConfig_PreservesDisabledTelegramPlaceholder(t *testing.T) { } } -func TestSaveConfig_PreservesExplicitDisabledPicoStreaming(t *testing.T) { - tmpDir := t.TempDir() - path := filepath.Join(tmpDir, "config.json") - - cfg := DefaultConfig() - pico := cfg.Channels.Get(ChannelPico) - if pico == nil { - t.Fatal("DefaultConfig() missing pico channel") - } - pico.Settings = RawNode(`{"streaming":{"enabled":false}}`) - - if err := SaveConfig(path, cfg); err != nil { - t.Fatalf("SaveConfig failed: %v", err) - } - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("ReadFile failed: %v", err) - } - if !strings.Contains(string(data), `"streaming"`) || !strings.Contains(string(data), `"enabled": false`) { - t.Fatalf("saved config should preserve explicit disabled pico streaming, got:\n%s", string(data)) - } - - loaded, err := LoadConfig(path) - if err != nil { - t.Fatalf("LoadConfig failed: %v", err) - } - loadedPico := loaded.Channels.Get(ChannelPico) - if loadedPico == nil { - t.Fatal("loaded config missing pico channel") - } - decoded, err := loadedPico.GetDecoded() - if err != nil { - t.Fatalf("pico GetDecoded() error = %v", err) - } - settings, ok := decoded.(*PicoSettings) - if !ok { - t.Fatalf("pico settings type = %T, want *PicoSettings", decoded) - } - if settings.Streaming.Enabled { - t.Fatal("explicit disabled pico streaming should remain disabled after SaveConfig/LoadConfig round-trip") - } -} - // TestSaveConfig_FiltersVirtualModels verifies that SaveConfig does not write // virtual models (generated by expandMultiKeyModels) to the config file. func TestSaveConfig_FiltersVirtualModels(t *testing.T) { @@ -3251,7 +3147,6 @@ func testChannelsConfigWithTokens() ChannelsConfig { {"dingtalk", DingTalkSettings{ClientSecret: *NewSecureString("dingtalk-client-secret")}}, {"onebot", OneBotSettings{AccessToken: *NewSecureString("onebot-access-token")}}, {"wecom", WeComSettings{Secret: *NewSecureString("wecom-secret")}}, - {"pico", PicoSettings{Token: *NewSecureString("pico-token-abc123")}}, { "irc", IRCSettings{ @@ -3269,3 +3164,46 @@ func testChannelsConfigWithTokens() ChannelsConfig { } return channels } + +func TestSaveConfig_PreservesExplicitDisabledTelegramStreaming(t *testing.T) { + tmpDir := t.TempDir() + path := filepath.Join(tmpDir, "config.json") + + cfg := DefaultConfig() + telegram := cfg.Channels.Get(ChannelTelegram) + if telegram == nil { + t.Fatal("DefaultConfig() missing telegram channel") + } + telegram.Settings = RawNode(`{"streaming":{"enabled":false}}`) + + if err := SaveConfig(path, cfg); err != nil { + t.Fatalf("SaveConfig failed: %v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("ReadFile failed: %v", err) + } + if !strings.Contains(string(data), `"streaming"`) || !strings.Contains(string(data), `"enabled": false`) { + t.Fatalf("saved config should preserve explicit disabled telegram streaming, got:\n%s", string(data)) + } + + loaded, err := LoadConfig(path) + if err != nil { + t.Fatalf("LoadConfig failed: %v", err) + } + loadedTelegram := loaded.Channels.Get(ChannelTelegram) + if loadedTelegram == nil { + t.Fatal("loaded config missing telegram channel") + } + decoded, err := loadedTelegram.GetDecoded() + if err != nil { + t.Fatalf("telegram GetDecoded() error = %v", err) + } + settings, ok := decoded.(*TelegramSettings) + if !ok { + t.Fatalf("telegram settings type = %T, want *TelegramSettings", decoded) + } + if settings.Streaming.Enabled { + t.Fatal("explicit disabled telegram streaming should remain disabled after SaveConfig/LoadConfig round-trip") + } +} diff --git a/pkg/config/defaults.go b/pkg/config/defaults.go index 96ce5f0f..de6d3320 100644 --- a/pkg/config/defaults.go +++ b/pkg/config/defaults.go @@ -533,9 +533,6 @@ func defaultChannels() ChannelsConfig { }, "feishu": map[string]any{}, "discord": map[string]any{}, - "maixcam": map[string]any{ - "settings": map[string]any{"host": "0.0.0.0", "port": 18790}, - }, "qq": map[string]any{ "settings": map[string]any{"max_message_length": 2000}, }, @@ -582,15 +579,6 @@ func defaultChannels() ChannelsConfig { "cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c", }, }, - "pico": map[string]any{ - "settings": map[string]any{ - "ping_interval": 30, - "read_timeout": 60, - "write_timeout": 10, - "max_connections": 100, - "streaming": map[string]any{"enabled": true}, - }, - }, "irc": map[string]any{ "settings": map[string]any{ "server": "", diff --git a/pkg/config/security_integration_test.go b/pkg/config/security_integration_test.go index cac76909..c7959cb1 100644 --- a/pkg/config/security_integration_test.go +++ b/pkg/config/security_integration_test.go @@ -250,9 +250,6 @@ func TestAllSecurityKeysAccessible(t *testing.T) { "enabled": true, "bot_id": "test_wecom_bot_id" }, - "pico": { - "enabled": true - }, "irc": { "enabled": true, "server": "irc.example.com", @@ -319,8 +316,6 @@ channels: access_token: "onebot_test_access_token" wecom: secret: "wecom_test_secret" - pico: - token: "pico_test_token" irc: password: "irc_test_password" nickserv_password: "irc_test_nickserv_password" @@ -437,11 +432,6 @@ skills: t.Logf("WeCom BotID: %s", wcSec.(*WeComSettings).BotID) t.Logf("WeCom Secret(): %s", secureStr(wcSec.(*WeComSettings).Secret)) - // Pico - picoSec := decodeChannel("pico") - assert.Equal(t, "pico_test_token", secureStr(picoSec.(*PicoSettings).Token)) - t.Logf("Pico Token(): %s", secureStr(picoSec.(*PicoSettings).Token)) - // IRC ircSec := decodeChannel("irc") assert.Equal(t, "irc_test_password", secureStr(ircSec.(*IRCSettings).Password)) diff --git a/pkg/config/security_test.go b/pkg/config/security_test.go index 23daf323..f4f13677 100644 --- a/pkg/config/security_test.go +++ b/pkg/config/security_test.go @@ -115,7 +115,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) { {"feishu", `{"enabled":true,"settings":{"app_id":"feishu_app_id","app_secret":"feishu_app_secret"}}`}, {"discord", `{"enabled":true,"settings":{"token":"discord_token"}}`}, {"qq", `{"enabled":true,"settings":{"app_secret":"qq_app_secret"}}`}, - {"pico_client", `{"enabled":true,"settings":{"token":"pico_client_token"}}`}, } { bc := &Channel{} json.Unmarshal([]byte(d.raw), bc) @@ -129,8 +128,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) { bc.Decode(&DiscordSettings{}) case "feishu": bc.Decode(&FeishuSettings{}) - case "pico_client": - bc.Decode(&PicoClientSettings{}) } chs[d.name] = bc } @@ -185,7 +182,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) { assert.Contains(t, getSetting("feishu")["app_secret"], "feishu_app_secret") assert.Contains(t, getSetting("discord")["token"], "discord_token") assert.Contains(t, getSetting("qq")["app_secret"], "qq_app_secret") - assert.Contains(t, getSetting("pico_client")["token"], "pico_client_token") // Rewrite file with deterministic content for load test (use channel_list) yamlOutput := `channel_list: @@ -197,8 +193,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) { token: discord_token qq: app_secret: qq_app_secret - pico_client: - token: pico_client_token model_list: model1:0: api_keys: diff --git a/pkg/gateway/gateway.go b/pkg/gateway/gateway.go index 41592937..042ce9ec 100644 --- a/pkg/gateway/gateway.go +++ b/pkg/gateway/gateway.go @@ -25,10 +25,8 @@ import ( _ "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/maixcam" _ "github.com/sipeed/picoclaw/pkg/channels/mqtt" _ "github.com/sipeed/picoclaw/pkg/channels/onebot" - _ "github.com/sipeed/picoclaw/pkg/channels/pico" _ "github.com/sipeed/picoclaw/pkg/channels/qq" _ "github.com/sipeed/picoclaw/pkg/channels/slack" _ "github.com/sipeed/picoclaw/pkg/channels/slack_webhook" diff --git a/pkg/heartbeat/service.go b/pkg/heartbeat/service.go index e5b28ec1..88905156 100644 --- a/pkg/heartbeat/service.go +++ b/pkg/heartbeat/service.go @@ -262,7 +262,7 @@ This file contains tasks for the heartbeat service to check periodically. - Check for unread messages - Review upcoming calendar events -- Check device status (e.g., MaixCam) +- Check device status ## Instructions diff --git a/pkg/migrate/sources/openclaw/common.go b/pkg/migrate/sources/openclaw/common.go index 938f15b8..536e5c3e 100644 --- a/pkg/migrate/sources/openclaw/common.go +++ b/pkg/migrate/sources/openclaw/common.go @@ -17,7 +17,6 @@ var supportedChannels = map[string]bool{ "telegram": true, "feishu": true, "discord": true, - "maixcam": true, "qq": true, "dingtalk": true, "slack": true, diff --git a/pkg/migrate/sources/openclaw/openclaw_config.go b/pkg/migrate/sources/openclaw/openclaw_config.go index 4b8fec22..c9f28dd4 100644 --- a/pkg/migrate/sources/openclaw/openclaw_config.go +++ b/pkg/migrate/sources/openclaw/openclaw_config.go @@ -128,7 +128,6 @@ type OpenClawChannels struct { BlueBubbles *OpenClawBlueBubblesConfig `json:"bluebubbles"` QQ *OpenClawQQConfig `json:"qq"` DingTalk *OpenClawDingTalkConfig `json:"dingtalk"` - MaixCam *OpenClawMaixCamConfig `json:"maixcam"` } type OpenClawTelegramConfig struct { @@ -267,14 +266,6 @@ type OpenClawDingTalkConfig struct { Enabled *bool `json:"enabled"` } -type OpenClawMaixCamConfig struct { - Host *string `json:"host"` - Port *int `json:"port"` - DmPolicy *string `json:"dmPolicy"` - AllowFrom []string `json:"allowFrom"` - Enabled *bool `json:"enabled"` -} - type OpenClawSkills struct { Entries map[string]json.RawMessage `json:"entries"` Load json.RawMessage `json:"load"` @@ -631,7 +622,6 @@ type ChannelsConfig struct { Telegram TelegramConfig `json:"telegram"` Feishu FeishuConfig `json:"feishu"` Discord DiscordConfig `json:"discord"` - MaixCam MaixCamConfig `json:"maixcam"` QQ QQConfig `json:"qq"` DingTalk DingTalkConfig `json:"dingtalk"` Slack SlackConfig `json:"slack"` @@ -669,13 +659,6 @@ type DiscordConfig struct { AllowFrom []string `json:"allow_from"` } -type MaixCamConfig struct { - Enabled bool `json:"enabled"` - Host string `json:"host"` - Port int `json:"port"` - AllowFrom []string `json:"allow_from"` -} - type QQConfig struct { Enabled bool `json:"enabled"` AppID string `json:"app_id"` @@ -872,19 +855,6 @@ func (c *OpenClawConfig) convertChannels(warnings *[]string) ChannelsConfig { } } - if c.Channels.MaixCam != nil && supportedChannels["maixcam"] { - channels.MaixCam = MaixCamConfig{ - Enabled: true, - AllowFrom: c.Channels.MaixCam.AllowFrom, - } - if c.Channels.MaixCam.Host != nil { - channels.MaixCam.Host = *c.Channels.MaixCam.Host - } - if c.Channels.MaixCam.Port != nil { - channels.MaixCam.Port = *c.Channels.MaixCam.Port - } - } - if c.Channels.Matrix != nil && supportedChannels["matrix"] { enabled := c.Channels.Matrix.Enabled == nil || *c.Channels.Matrix.Enabled channels.Matrix = MatrixConfig{ @@ -1064,12 +1034,6 @@ func (c ChannelsConfig) ToStandardChannels() config.ChannelsConfig { return m }()) - setChannel(channels, "maixcam", map[string]any{ - "enabled": c.MaixCam.Enabled, - "host": c.MaixCam.Host, - "port": c.MaixCam.Port, - }) - setChannel(channels, "qq", func() map[string]any { m := map[string]any{ "enabled": c.QQ.Enabled, diff --git a/pkg/migrate/sources/openclaw/openclaw_config_test.go b/pkg/migrate/sources/openclaw/openclaw_config_test.go index ceb27c4d..74590b0f 100644 --- a/pkg/migrate/sources/openclaw/openclaw_config_test.go +++ b/pkg/migrate/sources/openclaw/openclaw_config_test.go @@ -329,11 +329,6 @@ func TestConvertToPicoClawWithQQAndDingTalk(t *testing.T) { "appId": "ding-app-id", "appSecret": "ding-app-secret" }, - "maixcam": { - "enabled": true, - "host": "192.168.1.100", - "port": 9000 - }, "slack": { "enabled": true, "botToken": "xoxb-test", @@ -371,16 +366,6 @@ func TestConvertToPicoClawWithQQAndDingTalk(t *testing.T) { t.Errorf("expected dingtalk client ID 'ding-app-id', got '%s'", picoCfg.Channels.DingTalk.ClientID) } - if !picoCfg.Channels.MaixCam.Enabled { - t.Error("maixcam should be enabled") - } - if picoCfg.Channels.MaixCam.Host != "192.168.1.100" { - t.Errorf("expected maixcam host '192.168.1.100', got '%s'", picoCfg.Channels.MaixCam.Host) - } - if picoCfg.Channels.MaixCam.Port != 9000 { - t.Errorf("expected maixcam port 9000, got %d", picoCfg.Channels.MaixCam.Port) - } - if !picoCfg.Channels.Slack.Enabled { t.Error("slack should be enabled") } diff --git a/pkg/session/allocator_test.go b/pkg/session/allocator_test.go index 9750ffc3..3f8557fc 100644 --- a/pkg/session/allocator_test.go +++ b/pkg/session/allocator_test.go @@ -123,9 +123,9 @@ func TestAllocateRouteSession_PicoDirectAliasesIncludeLegacyChatKey(t *testing.T allocation := AllocateRouteSession(AllocationInput{ AgentID: "main", Context: bus.InboundContext{ - Channel: "pico", + Channel: "telegram", Account: "default", - ChatID: "pico:session-123", + ChatID: "telegram:session-123", ChatType: "direct", SenderID: "pico-user", }, @@ -134,7 +134,7 @@ func TestAllocateRouteSession_PicoDirectAliasesIncludeLegacyChatKey(t *testing.T }, }) - if !containsAlias(allocation.SessionAliases, "agent:main:pico:direct:pico:session-123") { + if !containsAlias(allocation.SessionAliases, "agent:main:telegram:direct:telegram:session-123") { t.Fatalf("SessionAliases = %v, want pico legacy alias", allocation.SessionAliases) } } diff --git a/pkg/session/jsonl_backend_test.go b/pkg/session/jsonl_backend_test.go index 6f67109d..77661bf2 100644 --- a/pkg/session/jsonl_backend_test.go +++ b/pkg/session/jsonl_backend_test.go @@ -264,13 +264,13 @@ func TestJSONLBackend_EnsureSessionMetadata_PromotesLegacyAliasHistory(t *testin func TestJSONLBackend_EnsureSessionMetadata_PromotesLegacyPicoDirectAliasHistory(t *testing.T) { b := newBackend(t) - legacyKey := "agent:main:pico:direct:pico:session-123" + legacyKey := "agent:main:telegram:direct:telegram:session-123" b.AddMessage(legacyKey, "user", "legacy pico history") scope := &session.SessionScope{ Version: session.ScopeVersionV1, AgentID: "main", - Channel: "pico", + Channel: "telegram", Account: "default", Dimensions: []string{"sender"}, Values: map[string]string{ @@ -280,9 +280,9 @@ func TestJSONLBackend_EnsureSessionMetadata_PromotesLegacyPicoDirectAliasHistory allocation := session.AllocateRouteSession(session.AllocationInput{ AgentID: "main", Context: bus.InboundContext{ - Channel: "pico", + Channel: "telegram", Account: "default", - ChatID: "pico:session-123", + ChatID: "telegram:session-123", ChatType: "direct", SenderID: "pico-user", },