+
+---
+
+🦐 **PicoClaw** est un assistant personnel IA ultra-léger inspiré de [nanobot](https://github.com/HKUDS/nanobot), entièrement réécrit en **Go** via un processus d'auto-amorçage (self-bootstrapping) — où l'agent IA lui-même a piloté l'intégralité de la migration architecturale et de l'optimisation du code.
+
+⚡️ **Extrêmement léger :** Fonctionne sur du matériel à seulement **10$** avec **<10 Mo** de RAM. C'est 99% de mémoire en moins qu'OpenClaw et 98% moins cher qu'un Mac mini !
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+> [!CAUTION]
+> **🚨 SÉCURITÉ & CANAUX OFFICIELS**
+>
+> * **PAS DE CRYPTO :** PicoClaw n'a **AUCUN** token/jeton officiel. Toute annonce sur `pump.fun` ou d'autres plateformes de trading est une **ARNAQUE**.
+> * **DOMAINE OFFICIEL :** Le **SEUL** site officiel est **[picoclaw.io](https://picoclaw.io)**, et le site de l'entreprise est **[sipeed.com](https://sipeed.com)**.
+> * **Attention :** De nombreux domaines `.ai/.org/.com/.net/...` sont enregistrés par des tiers et ne nous appartiennent pas.
+> * **Attention :** PicoClaw est en phase de développement précoce et peut présenter des problèmes de sécurité réseau non résolus. Ne déployez pas en environnement de production avant la version v1.0.
+> * **Note :** PicoClaw a récemment fusionné de nombreuses PR, ce qui peut entraîner une empreinte mémoire plus importante (10–20 Mo) dans les dernières versions. Nous prévoyons de prioriser l'optimisation des ressources dès que l'ensemble des fonctionnalités sera stabilisé.
+
+
+## 📢 Actualités
+
+2026-02-16 🎉 PicoClaw a atteint 12K étoiles en une semaine ! Merci à tous pour votre soutien ! PicoClaw grandit plus vite que nous ne l'avions jamais imaginé. Vu le volume élevé de PR, nous avons un besoin urgent de mainteneurs communautaires. Nos rôles de bénévoles et notre feuille de route sont officiellement publiés [ici](docs/picoclaw_community_roadmap_260216.md) — nous avons hâte de vous accueillir !
+
+2026-02-13 🎉 PicoClaw a atteint 5000 étoiles en 4 jours ! Merci à la communauté ! Nous finalisons la **Feuille de Route du Projet** et mettons en place le **Groupe de Développeurs** pour accélérer le développement de PicoClaw.
+🚀 **Appel à l'action :** Soumettez vos demandes de fonctionnalités dans les GitHub Discussions. Nous les examinerons et les prioriserons lors de notre prochaine réunion hebdomadaire.
+
+2026-02-09 🎉 PicoClaw est lancé ! Construit en 1 jour pour apporter les Agents IA au matériel à 10$ avec <10 Mo de RAM. 🦐 PicoClaw, c'est parti !
+
+## ✨ Fonctionnalités
+
+🪶 **Ultra-Léger** : Empreinte mémoire <10 Mo — 99% plus petit que Clawdbot pour les fonctionnalités essentielles.
+
+💰 **Coût Minimal** : Suffisamment efficace pour fonctionner sur du matériel à 10$ — 98% moins cher qu'un Mac mini.
+
+⚡️ **Démarrage Éclair** : Temps de démarrage 400X plus rapide, boot en 1 seconde même sur un cœur unique à 0,6 GHz.
+
+🌍 **Véritable Portabilité** : Un seul binaire autonome pour RISC-V, ARM et x86. Un clic et c'est parti !
+
+🤖 **Auto-Construit par l'IA** : Implémentation native en Go de manière autonome — 95% du cœur généré par l'Agent avec affinement humain dans la boucle.
+
+| | OpenClaw | NanoBot | **PicoClaw** |
+| ----------------------------- | ------------- | ------------------------ | ----------------------------------------- |
+| **Langage** | TypeScript | Python | **Go** |
+| **RAM** | >1 Go | >100 Mo | **< 10 Mo** |
+| **Démarrage**(cœur 0,8 GHz) | >500s | >30s | **<1s** |
+| **Coût** | Mac Mini 599$ | La plupart des SBC Linux ~50$ | **N'importe quelle carte Linux****À partir de 10$** |
+
+
+
+## 🦾 Démonstration
+
+### 🛠️ Flux de Travail Standard de l'Assistant
+
+
+
+
🧩 Ingénieur Full-Stack
+
🗂️ Gestion des Logs & Planification
+
🔎 Recherche Web & Apprentissage
+
+
+
+
+
+
+
+
Développer • Déployer • Mettre à l'échelle
+
Planifier • Automatiser • Mémoriser
+
Découvrir • Analyser • Tendances
+
+
+
+### 📱 Utiliser sur d'anciens téléphones Android
+
+Donnez une seconde vie à votre téléphone d'il y a dix ans ! Transformez-le en assistant IA intelligent avec PicoClaw. Démarrage rapide :
+
+1. **Installez Termux** (disponible sur F-Droid ou Google Play).
+2. **Exécutez les commandes**
+
+```bash
+# Note : Remplacez v0.1.1 par la dernière version depuis la page des Releases
+wget https://github.com/sipeed/picoclaw/releases/download/v0.1.1/picoclaw-linux-arm64
+chmod +x picoclaw-linux-arm64
+pkg install proot
+termux-chroot ./picoclaw-linux-arm64 onboard
+```
+
+Puis suivez les instructions de la section « Démarrage Rapide » pour terminer la configuration !
+
+
+
+### 🐜 Déploiement Innovant à Faible Empreinte
+
+PicoClaw peut être déployé sur pratiquement n'importe quel appareil Linux !
+
+- 9,9$ [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) version E (Ethernet) ou W (WiFi6), pour un Assistant Domotique Minimaliste
+- 30~50$ [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), ou 100$ [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html) pour la Maintenance Automatisée de Serveurs
+- 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
+
+
+
+🌟 Encore plus de scénarios de déploiement vous attendent !
+
+## 📦 Installation
+
+### Installer avec un binaire précompilé
+
+Téléchargez le binaire pour votre plateforme depuis la page des [releases](https://github.com/sipeed/picoclaw/releases).
+
+### Installer depuis les sources (dernières fonctionnalités, recommandé pour le développement)
+
+```bash
+git clone https://github.com/sipeed/picoclaw.git
+
+cd picoclaw
+make deps
+
+# Compiler, pas besoin d'installer
+make build
+
+# Compiler pour plusieurs plateformes
+make build-all
+
+# Compiler et Installer
+make install
+```
+
+## 🐳 Docker Compose
+
+Vous pouvez également exécuter PicoClaw avec Docker Compose sans rien installer localement.
+
+```bash
+# 1. Clonez ce dépôt
+git clone https://github.com/sipeed/picoclaw.git
+cd picoclaw
+
+# 2. Configurez vos clés API
+cp config/config.example.json config/config.json
+vim config/config.json # Configurez DISCORD_BOT_TOKEN, clés API, etc.
+
+# 3. Compiler & Démarrer
+docker compose --profile gateway up -d
+
+# 4. Voir les logs
+docker compose logs -f picoclaw-gateway
+
+# 5. Arrêter
+docker compose --profile gateway down
+```
+
+### Mode Agent (exécution unique)
+
+```bash
+# Poser une question
+docker compose run --rm picoclaw-agent -m "Combien font 2+2 ?"
+
+# Mode interactif
+docker compose run --rm picoclaw-agent
+```
+
+### Recompiler
+
+```bash
+docker compose --profile gateway build --no-cache
+docker compose --profile gateway up -d
+```
+
+### 🚀 Démarrage Rapide
+
+> [!TIP]
+> Configurez votre clé API dans `~/.picoclaw/config.json`.
+> Obtenir des clés API : [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM)
+> La recherche web est **optionnelle** — obtenez gratuitement l'[API Brave Search](https://brave.com/search/api) (2000 requêtes gratuites/mois) ou utilisez le repli automatique intégré.
+
+**1. Initialiser**
+
+```bash
+picoclaw onboard
+```
+
+**2. Configurer** (`~/.picoclaw/config.json`)
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "workspace": "~/.picoclaw/workspace",
+ "model": "glm-4.7",
+ "max_tokens": 8192,
+ "temperature": 0.7,
+ "max_tool_iterations": 20
+ }
+ },
+ "providers": {
+ "openrouter": {
+ "api_key": "xxx",
+ "api_base": "https://openrouter.ai/api/v1"
+ }
+ },
+ "tools": {
+ "web": {
+ "brave": {
+ "enabled": false,
+ "api_key": "VOTRE_CLE_API_BRAVE",
+ "max_results": 5
+ },
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ }
+ }
+ }
+}
+```
+
+**3. Obtenir des Clés API**
+
+* **Fournisseur LLM** : [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys)
+* **Recherche Web** (optionnel) : [Brave Search](https://brave.com/search/api) - Offre gratuite disponible (2000 requêtes/mois)
+
+> **Note** : Consultez `config.example.json` pour un modèle de configuration complet.
+
+**4. Discuter**
+
+```bash
+picoclaw agent -m "Combien font 2+2 ?"
+```
+
+Et voilà ! Vous avez un assistant IA fonctionnel en 2 minutes.
+
+---
+
+## 💬 Applications de Chat
+
+Discutez avec votre PicoClaw via Telegram, Discord, DingTalk, LINE ou WeCom
+
+| Canal | Configuration |
+| ------------ | -------------------------------------- |
+| **Telegram** | Facile (juste un token) |
+| **Discord** | Facile (token bot + intents) |
+| **QQ** | Facile (AppID + AppSecret) |
+| **DingTalk** | Moyen (identifiants de l'application) |
+| **LINE** | Moyen (identifiants + URL de webhook) |
+| **WeCom** | Moyen (CorpID + configuration webhook) |
+
+
+Telegram (Recommandé)
+
+**1. Créer un bot**
+
+* Ouvrez Telegram, recherchez `@BotFather`
+* Envoyez `/newbot`, suivez les instructions
+* Copiez le token
+
+**2. Configurer**
+
+```json
+{
+ "channels": {
+ "telegram": {
+ "enabled": true,
+ "token": "VOTRE_TOKEN_BOT",
+ "allowFrom": ["VOTRE_USER_ID"]
+ }
+ }
+}
+```
+
+> Obtenez votre User ID via `@userinfobot` sur Telegram.
+
+**3. Lancer**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+Discord
+
+**1. Créer un bot**
+
+* Rendez-vous sur
+* Créez une application → Bot → Add Bot
+* Copiez le token du bot
+
+**2. Activer les intents**
+
+* Dans les paramètres du Bot, activez **MESSAGE CONTENT INTENT**
+* (Optionnel) Activez **SERVER MEMBERS INTENT** si vous souhaitez utiliser des listes d'autorisation basées sur les données des membres
+
+**3. Obtenir votre User ID**
+
+* Paramètres Discord → Avancé → activez le **Mode Développeur**
+* Clic droit sur votre avatar → **Copier l'identifiant**
+
+**4. Configurer**
+
+```json
+{
+ "channels": {
+ "discord": {
+ "enabled": true,
+ "token": "VOTRE_TOKEN_BOT",
+ "allowFrom": ["VOTRE_USER_ID"]
+ }
+ }
+}
+```
+
+**5. Inviter le bot**
+
+* OAuth2 → URL Generator
+* Scopes : `bot`
+* Permissions du Bot : `Send Messages`, `Read Message History`
+* Ouvrez l'URL d'invitation générée et ajoutez le bot à votre serveur
+
+**6. Lancer**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+QQ
+
+**1. Créer un bot**
+
+- Rendez-vous sur la [QQ Open Platform](https://q.qq.com/#)
+- Créez une application → Obtenez l'**AppID** et l'**AppSecret**
+
+**2. Configurer**
+
+```json
+{
+ "channels": {
+ "qq": {
+ "enabled": true,
+ "app_id": "VOTRE_APP_ID",
+ "app_secret": "VOTRE_APP_SECRET",
+ "allow_from": []
+ }
+ }
+}
+```
+
+> Laissez `allow_from` vide pour autoriser tous les utilisateurs, ou spécifiez des numéros QQ pour restreindre l'accès.
+
+**3. Lancer**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+DingTalk
+
+**1. Créer un bot**
+
+* Rendez-vous sur la [Open Platform](https://open.dingtalk.com/)
+* Créez une application interne
+* Copiez le Client ID et le Client Secret
+
+**2. Configurer**
+
+```json
+{
+ "channels": {
+ "dingtalk": {
+ "enabled": true,
+ "client_id": "VOTRE_CLIENT_ID",
+ "client_secret": "VOTRE_CLIENT_SECRET",
+ "allow_from": []
+ }
+ }
+}
+```
+
+> Laissez `allow_from` vide pour autoriser tous les utilisateurs, ou spécifiez des identifiants pour restreindre l'accès.
+
+**3. Lancer**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+LINE
+
+**1. Créer un Compte Officiel LINE**
+
+- Rendez-vous sur la [LINE Developers Console](https://developers.line.biz/)
+- Créez un provider → Créez un canal Messaging API
+- Copiez le **Channel Secret** et le **Channel Access Token**
+
+**2. Configurer**
+
+```json
+{
+ "channels": {
+ "line": {
+ "enabled": true,
+ "channel_secret": "VOTRE_CHANNEL_SECRET",
+ "channel_access_token": "VOTRE_CHANNEL_ACCESS_TOKEN",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18791,
+ "webhook_path": "/webhook/line",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**3. Configurer l'URL du Webhook**
+
+LINE exige HTTPS pour les webhooks. Utilisez un reverse proxy ou un tunnel :
+
+```bash
+# Exemple avec ngrok
+ngrok http 18791
+```
+
+Puis configurez l'URL du Webhook dans la LINE Developers Console sur `https://votre-domaine/webhook/line` et activez **Use webhook**.
+
+**4. Lancer**
+
+```bash
+picoclaw gateway
+```
+
+> Dans les discussions de groupe, le bot répond uniquement lorsqu'il est mentionné avec @. Les réponses citent le message original.
+
+> **Docker Compose** : Ajoutez `ports: ["18791:18791"]` au service `picoclaw-gateway` pour exposer le port du webhook.
+
+
+
+
+WeCom (WeChat Work)
+
+PicoClaw prend en charge deux types d'intégration WeCom :
+
+**Option 1 : WeCom Bot (Robot Intelligent)** - Configuration plus facile, prend en charge les discussions de groupe
+**Option 2 : WeCom App (Application Personnalisée)** - Plus de fonctionnalités, messagerie proactive
+
+Voir le [Guide de Configuration WeCom App](docs/wecom-app-configuration.md) pour des instructions détaillées.
+
+**Configuration Rapide - WeCom Bot :**
+
+**1. Créer un bot**
+
+* Accédez à la Console d'Administration WeCom → Discussion de Groupe → Ajouter un Bot de Groupe
+* Copiez l'URL du webhook (format : `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`)
+
+**2. Configurer**
+
+```json
+{
+ "channels": {
+ "wecom": {
+ "enabled": true,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**Configuration Rapide - WeCom App :**
+
+**1. Créer une application**
+
+* Accédez à la Console d'Administration WeCom → Gestion des Applications → Créer une Application
+* Copiez l'**AgentId** et le **Secret**
+* Accédez à la page "Mon Entreprise", copiez le **CorpID**
+
+**2. Configurer la réception des messages**
+
+* Dans les détails de l'application, cliquez sur "Recevoir les Messages" → "Configurer l'API"
+* Définissez l'URL sur `http://your-server:18792/webhook/wecom-app`
+* Générez le **Token** et l'**EncodingAESKey**
+
+**3. Configurer**
+
+```json
+{
+ "channels": {
+ "wecom_app": {
+ "enabled": true,
+ "corp_id": "wwxxxxxxxxxxxxxxxx",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**4. Lancer**
+
+```bash
+picoclaw gateway
+```
+
+> **Note** : WeCom App nécessite l'ouverture du port 18792 pour les callbacks webhook. Utilisez un proxy inverse pour HTTPS en production.
+
+
+
+## Rejoignez le Réseau Social d'Agents
+
+Connectez PicoClaw au Réseau Social d'Agents simplement en envoyant un seul message via le CLI ou n'importe quelle application de chat intégrée.
+
+**Lisez `https://clawdchat.ai/skill.md` et suivez les instructions pour rejoindre [ClawdChat.ai](https://clawdchat.ai)**
+
+## ⚙️ Configuration
+
+Fichier de configuration : `~/.picoclaw/config.json`
+
+### Structure du Workspace
+
+PicoClaw stocke les données dans votre workspace configuré (par défaut : `~/.picoclaw/workspace`) :
+
+```
+~/.picoclaw/workspace/
+├── sessions/ # Sessions de conversation et historique
+├── memory/ # Mémoire à long terme (MEMORY.md)
+├── state/ # État persistant (dernier canal, etc.)
+├── cron/ # Base de données des tâches planifiées
+├── skills/ # Compétences personnalisées
+├── AGENTS.md # Guide de comportement de l'Agent
+├── HEARTBEAT.md # Invites de tâches périodiques (vérifiées toutes les 30 min)
+├── IDENTITY.md # Identité de l'Agent
+├── SOUL.md # Âme de l'Agent
+├── TOOLS.md # Description des outils
+└── USER.md # Préférences utilisateur
+```
+
+### 🔒 Bac à Sable de Sécurité
+
+PicoClaw s'exécute dans un environnement sandboxé par défaut. L'agent ne peut accéder aux fichiers et exécuter des commandes qu'au sein du workspace configuré.
+
+#### Configuration par Défaut
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "workspace": "~/.picoclaw/workspace",
+ "restrict_to_workspace": true
+ }
+ }
+}
+```
+
+| Option | Par défaut | Description |
+|--------|------------|-------------|
+| `workspace` | `~/.picoclaw/workspace` | Répertoire de travail de l'agent |
+| `restrict_to_workspace` | `true` | Restreindre l'accès fichiers/commandes au workspace |
+
+#### Outils Protégés
+
+Lorsque `restrict_to_workspace: true`, les outils suivants sont restreints au bac à sable :
+
+| Outil | Fonction | Restriction |
+|-------|----------|-------------|
+| `read_file` | Lire des fichiers | Uniquement les fichiers dans le workspace |
+| `write_file` | Écrire des fichiers | Uniquement les fichiers dans le workspace |
+| `list_dir` | Lister des répertoires | Uniquement les répertoires dans le workspace |
+| `edit_file` | Éditer des fichiers | Uniquement les fichiers dans le workspace |
+| `append_file` | Ajouter à des fichiers | Uniquement les fichiers dans le workspace |
+| `exec` | Exécuter des commandes | Les chemins doivent être dans le workspace |
+
+#### Protection Supplémentaire d'Exec
+
+Même avec `restrict_to_workspace: false`, l'outil `exec` bloque ces commandes dangereuses :
+
+* `rm -rf`, `del /f`, `rmdir /s` — Suppression en masse
+* `format`, `mkfs`, `diskpart` — Formatage de disque
+* `dd if=` — Écriture d'image disque
+* Écriture vers `/dev/sd[a-z]` — Écriture directe sur le disque
+* `shutdown`, `reboot`, `poweroff` — Arrêt du système
+* Fork bomb `:(){ :|:& };:`
+
+#### Exemples d'Erreurs
+
+```
+[ERROR] tool: Tool execution failed
+{tool=exec, error=Command blocked by safety guard (path outside working dir)}
+```
+
+```
+[ERROR] tool: Tool execution failed
+{tool=exec, error=Command blocked by safety guard (dangerous pattern detected)}
+```
+
+#### Désactiver les Restrictions (Risque de Sécurité)
+
+Si vous avez besoin que l'agent accède à des chemins en dehors du workspace :
+
+**Méthode 1 : Fichier de configuration**
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "restrict_to_workspace": false
+ }
+ }
+}
+```
+
+**Méthode 2 : Variable d'environnement**
+
+```bash
+export PICOCLAW_AGENTS_DEFAULTS_RESTRICT_TO_WORKSPACE=false
+```
+
+> ⚠️ **Attention** : Désactiver cette restriction permet à l'agent d'accéder à n'importe quel chemin sur votre système. À utiliser avec précaution uniquement dans des environnements contrôlés.
+
+#### Cohérence du Périmètre de Sécurité
+
+Le paramètre `restrict_to_workspace` s'applique de manière cohérente sur tous les chemins d'exécution :
+
+| Chemin d'Exécution | Périmètre de Sécurité |
+|--------------------|----------------------|
+| Agent Principal | `restrict_to_workspace` ✅ |
+| Sous-agent / Spawn | Hérite de la même restriction ✅ |
+| Tâches Heartbeat | Hérite de la même restriction ✅ |
+
+Tous les chemins partagent la même restriction de workspace — il est impossible de contourner le périmètre de sécurité via des sous-agents ou des tâches planifiées.
+
+### Heartbeat (Tâches Périodiques)
+
+PicoClaw peut exécuter des tâches périodiques automatiquement. Créez un fichier `HEARTBEAT.md` dans votre workspace :
+
+```markdown
+# Tâches Périodiques
+
+- Vérifier mes e-mails pour les messages importants
+- Consulter mon agenda pour les événements à venir
+- Vérifier les prévisions météo
+```
+
+L'agent lira ce fichier toutes les 30 minutes (configurable) et exécutera les tâches à l'aide des outils disponibles.
+
+#### Tâches Asynchrones avec Spawn
+
+Pour les tâches de longue durée (recherche web, appels API), utilisez l'outil `spawn` pour créer un **sous-agent** :
+
+```markdown
+# Tâches Périodiques
+
+## Tâches Rapides (réponse directe)
+- Indiquer l'heure actuelle
+
+## Tâches Longues (utiliser spawn pour l'asynchrone)
+- Rechercher les actualités IA sur le web et les résumer
+- Vérifier les e-mails et signaler les messages importants
+```
+
+**Comportements clés :**
+
+| Fonctionnalité | Description |
+|----------------|-------------|
+| **spawn** | Crée un sous-agent asynchrone, ne bloque pas le heartbeat |
+| **Contexte indépendant** | Le sous-agent a son propre contexte, sans historique de session |
+| **Outil message** | Le sous-agent communique directement avec l'utilisateur via l'outil message |
+| **Non-bloquant** | Après le spawn, le heartbeat continue vers la tâche suivante |
+
+#### Fonctionnement de la Communication du Sous-agent
+
+```
+Le Heartbeat se déclenche
+ ↓
+L'Agent lit HEARTBEAT.md
+ ↓
+Pour une tâche longue : spawn d'un sous-agent
+ ↓ ↓
+Continue la tâche suivante Le sous-agent travaille indépendamment
+ ↓ ↓
+Toutes les tâches terminées Le sous-agent utilise l'outil "message"
+ ↓ ↓
+Répond HEARTBEAT_OK L'utilisateur reçoit le résultat directement
+```
+
+Le sous-agent a accès aux outils (message, web_search, etc.) et peut communiquer avec l'utilisateur indépendamment sans passer par l'agent principal.
+
+**Configuration :**
+
+```json
+{
+ "heartbeat": {
+ "enabled": true,
+ "interval": 30
+ }
+}
+```
+
+| Option | Par défaut | Description |
+|--------|------------|-------------|
+| `enabled` | `true` | Activer/désactiver le heartbeat |
+| `interval` | `30` | Intervalle de vérification en minutes (min : 5) |
+
+**Variables d'environnement :**
+
+* `PICOCLAW_HEARTBEAT_ENABLED=false` pour désactiver
+* `PICOCLAW_HEARTBEAT_INTERVAL=60` pour modifier l'intervalle
+
+### Fournisseurs
+
+> [!NOTE]
+> Groq fournit la transcription vocale gratuite via Whisper. Si configuré, les messages vocaux Telegram seront automatiquement transcrits.
+
+| Fournisseur | Utilisation | Obtenir une Clé API |
+| ------------------------ | ---------------------------------------- | ------------------------------------------------------ |
+| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) |
+| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](bigmodel.cn) |
+| `openrouter` (À tester) | LLM (recommandé, accès à tous les modèles) | [openrouter.ai](https://openrouter.ai) |
+| `anthropic` (À tester) | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) |
+| `openai` (À tester) | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) |
+| `deepseek` (À tester) | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) |
+| `groq` | LLM + **Transcription vocale** (Whisper) | [console.groq.com](https://console.groq.com) |
+
+
+Configuration Zhipu
+
+**1. Obtenir la clé API**
+
+* Obtenez la [clé API](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)
+
+**2. Configurer**
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "workspace": "~/.picoclaw/workspace",
+ "model": "glm-4.7",
+ "max_tokens": 8192,
+ "temperature": 0.7,
+ "max_tool_iterations": 20
+ }
+ },
+ "providers": {
+ "zhipu": {
+ "api_key": "Votre Clé API",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ }
+}
+```
+
+**3. Lancer**
+
+```bash
+picoclaw agent -m "Bonjour, comment ça va ?"
+```
+
+
+
+
+Exemple de configuration complète
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "model": "anthropic/claude-opus-4-5"
+ }
+ },
+ "providers": {
+ "openrouter": {
+ "api_key": "sk-or-v1-xxx"
+ },
+ "groq": {
+ "api_key": "gsk_xxx"
+ }
+ },
+ "channels": {
+ "telegram": {
+ "enabled": true,
+ "token": "123456:ABC...",
+ "allow_from": ["123456789"]
+ },
+ "discord": {
+ "enabled": true,
+ "token": "",
+ "allow_from": [""]
+ },
+ "whatsapp": {
+ "enabled": false
+ },
+ "feishu": {
+ "enabled": false,
+ "app_id": "cli_xxx",
+ "app_secret": "xxx",
+ "encrypt_key": "",
+ "verification_token": "",
+ "allow_from": []
+ },
+ "qq": {
+ "enabled": false,
+ "app_id": "",
+ "app_secret": "",
+ "allow_from": []
+ }
+ },
+ "tools": {
+ "web": {
+ "brave": {
+ "enabled": false,
+ "api_key": "BSA...",
+ "max_results": 5
+ },
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ }
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
+ }
+ },
+ "heartbeat": {
+ "enabled": true,
+ "interval": 30
+ }
+}
+```
+
+
+
+### Configuration de Modèle (model_list)
+
+> **Nouveau !** PicoClaw utilise désormais une approche de configuration **centrée sur le modèle**. Spécifiez simplement le format `fournisseur/modèle` (par exemple, `zhipu/glm-4.7`) pour ajouter de nouveaux fournisseurs—**aucune modification de code requise !**
+
+Cette conception permet également le **support multi-agent** avec une sélection flexible de fournisseurs :
+
+- **Différents agents, différents fournisseurs** : Chaque agent peut utiliser son propre fournisseur LLM
+- **Modèles de secours (Fallbacks)** : Configurez des modèles primaires et de secours pour la résilience
+- **Équilibrage de charge** : Répartissez les requêtes sur plusieurs points de terminaison
+- **Configuration centralisée** : Gérez tous les fournisseurs en un seul endroit
+
+#### 📋 Tous les Fournisseurs Supportés
+
+| Fournisseur | Préfixe `model` | API Base par Défaut | Protocole | Clé API |
+|-------------|-----------------|---------------------|----------|---------|
+| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Obtenir Clé](https://platform.openai.com) |
+| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Obtenir Clé](https://console.anthropic.com) |
+| **Zhipu AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Obtenir Clé](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) |
+| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Obtenir Clé](https://platform.deepseek.com) |
+| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | OpenAI | [Obtenir Clé](https://aistudio.google.com/api-keys) |
+| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Obtenir Clé](https://console.groq.com) |
+| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Obtenir Clé](https://platform.moonshot.cn) |
+| **Qwen (Alibaba)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Obtenir Clé](https://dashscope.console.aliyun.com) |
+| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Obtenir Clé](https://build.nvidia.com) |
+| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (pas de clé nécessaire) |
+| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Obtenir Clé](https://openrouter.ai/keys) |
+| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local |
+| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Obtenir Clé](https://cerebras.ai) |
+| **Volcengine** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Obtenir Clé](https://console.volcengine.com) |
+| **ShengsuanYun** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - |
+| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth uniquement |
+| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - |
+
+#### Configuration de Base
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key"
+ },
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-zhipu-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "gpt-5.2"
+ }
+ }
+}
+```
+
+#### Exemples par Fournisseur
+
+**OpenAI**
+```json
+{
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-..."
+}
+```
+
+**Zhipu AI (GLM)**
+```json
+{
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+}
+```
+
+**Anthropic (avec OAuth)**
+```json
+{
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "auth_method": "oauth"
+}
+```
+> Exécutez `picoclaw auth login --provider anthropic` pour configurer les identifiants OAuth.
+
+#### Équilibrage de Charge
+
+Configurez plusieurs points de terminaison pour le même nom de modèle—PicoClaw utilisera automatiquement le round-robin entre eux :
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api1.example.com/v1",
+ "api_key": "sk-key1"
+ },
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api2.example.com/v1",
+ "api_key": "sk-key2"
+ }
+ ]
+}
+```
+
+#### Migration depuis l'Ancienne Configuration `providers`
+
+L'ancienne configuration `providers` est **dépréciée** mais toujours supportée pour la rétrocompatibilité.
+
+**Ancienne Configuration (dépréciée) :**
+```json
+{
+ "providers": {
+ "zhipu": {
+ "api_key": "your-key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ },
+ "agents": {
+ "defaults": {
+ "provider": "zhipu",
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+**Nouvelle Configuration (recommandée) :**
+```json
+{
+ "model_list": [
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+Pour le guide de migration détaillé, voir [docs/migration/model-list-migration.md](docs/migration/model-list-migration.md).
+
+## Référence CLI
+
+| Commande | Description |
+| ------------------------- | ------------------------------------- |
+| `picoclaw onboard` | Initialiser la configuration & le workspace |
+| `picoclaw agent -m "..."` | Discuter avec l'agent |
+| `picoclaw agent` | Mode de discussion interactif |
+| `picoclaw gateway` | Démarrer la passerelle |
+| `picoclaw status` | Afficher le statut |
+| `picoclaw cron list` | Lister toutes les tâches planifiées |
+| `picoclaw cron add ...` | Ajouter une tâche planifiée |
+
+### Tâches Planifiées / Rappels
+
+PicoClaw prend en charge les rappels planifiés et les tâches récurrentes via l'outil `cron` :
+
+* **Rappels ponctuels** : « Rappelle-moi dans 10 minutes » → se déclenche une fois après 10 min
+* **Tâches récurrentes** : « Rappelle-moi toutes les 2 heures » → se déclenche toutes les 2 heures
+* **Expressions Cron** : « Rappelle-moi à 9h tous les jours » → utilise une expression cron
+
+Les tâches sont stockées dans `~/.picoclaw/workspace/cron/` et traitées automatiquement.
+
+## 🤝 Contribuer & Feuille de Route
+
+Les PR sont les bienvenues ! Le code source est volontairement petit et lisible. 🤗
+
+Feuille de route à venir...
+
+Groupe de développeurs en construction. Condition d'entrée : au moins 1 PR fusionnée.
+
+Groupes d'utilisateurs :
+
+Discord :
+
+
+
+## 🐛 Dépannage
+
+### La recherche web affiche « API 配置问题 »
+
+C'est normal si vous n'avez pas encore configuré de clé API de recherche. PicoClaw fournira des liens utiles pour la recherche manuelle.
+
+Pour activer la recherche web :
+
+1. **Option 1 (Recommandé)** : Obtenez une clé API gratuite sur [https://brave.com/search/api](https://brave.com/search/api) (2000 requêtes gratuites/mois) pour les meilleurs résultats.
+2. **Option 2 (Sans carte bancaire)** : Si vous n'avez pas de clé, le système bascule automatiquement sur **DuckDuckGo** (aucune clé requise).
+
+Ajoutez la clé dans `~/.picoclaw/config.json` si vous utilisez Brave :
+
+```json
+{
+ "tools": {
+ "web": {
+ "brave": {
+ "enabled": true,
+ "api_key": "VOTRE_CLE_API_BRAVE",
+ "max_results": 5
+ },
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ }
+ }
+ }
+}
+```
+
+### Erreurs de filtrage de contenu
+
+Certains fournisseurs (comme Zhipu) disposent d'un filtrage de contenu. Essayez de reformuler votre requête ou utilisez un modèle différent.
+
+### Le bot Telegram affiche « Conflict: terminated by other getUpdates »
+
+Cela se produit lorsqu'une autre instance du bot est en cours d'exécution. Assurez-vous qu'un seul `picoclaw gateway` fonctionne à la fois.
+
+---
+
+## 📝 Comparaison des Clés API
+
+| Service | Offre Gratuite | Cas d'Utilisation |
+| ---------------- | -------------------- | ------------------------------------- |
+| **OpenRouter** | 200K tokens/mois | Multiples modèles (Claude, GPT-4, etc.) |
+| **Zhipu** | 200K tokens/mois | Idéal pour les utilisateurs chinois |
+| **Brave Search** | 2000 requêtes/mois | Fonctionnalité de recherche web |
+| **Groq** | Offre gratuite dispo | Inférence ultra-rapide (Llama, Mixtral) |
diff --git a/README.ja.md b/README.ja.md
index 70ba458e9..c66f83734 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -12,7 +12,7 @@
-[中文](README.zh.md) | **日本語** | [Português](README.pt-br.md) | [Tiếng Việt](README.vi.md) | [English](README.md)
+[中文](README.zh.md) | **日本語** | [Português](README.pt-br.md) | [Tiếng Việt](README.vi.md) | [Français](README.fr.md) | [English](README.md)
@@ -213,7 +213,7 @@ picoclaw onboard
**3. API キーの取得**
-- **LLM プロバイダー**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys)
+- **LLM プロバイダー**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) · [Qwen](https://dashscope.console.aliyun.com)
- **Web 検索**(任意): [Brave Search](https://brave.com/search/api) - 無料枠あり(月 2000 リクエスト)
> **注意**: 完全な設定テンプレートは `config.example.json` を参照してください。
@@ -230,7 +230,7 @@ picoclaw agent -m "What is 2+2?"
## 💬 チャットアプリ
-Telegram、Discord、QQ、DingTalk、LINE で PicoClaw と会話できます
+Telegram、Discord、QQ、DingTalk、LINE、WeCom で PicoClaw と会話できます
| チャネル | セットアップ |
|---------|------------|
@@ -239,6 +239,7 @@ Telegram、Discord、QQ、DingTalk、LINE で PicoClaw と会話できます
| **QQ** | 簡単(AppID + AppSecret) |
| **DingTalk** | 普通(アプリ認証情報) |
| **LINE** | 普通(認証情報 + Webhook URL) |
+| **WeCom** | 普通(CorpID + Webhook設定) |
Telegram(推奨)
@@ -434,6 +435,87 @@ picoclaw gateway
+
+WeCom (企業微信)
+
+PicoClaw は2種類の WeCom 統合をサポートしています:
+
+**オプション1: WeCom Bot (智能ロボット)** - 簡単な設定、グループチャット対応
+**オプション2: WeCom App (自作アプリ)** - より多機能、アクティブメッセージング対応
+
+詳細な設定手順は [WeCom App Configuration Guide](docs/wecom-app-configuration.md) を参照してください。
+
+**クイックセットアップ - WeCom Bot:**
+
+**1. ボットを作成**
+
+* WeCom 管理コンソール → グループチャット → グループボットを追加
+* Webhook URL をコピー(形式: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`)
+
+**2. 設定**
+
+```json
+{
+ "channels": {
+ "wecom": {
+ "enabled": true,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**クイックセットアップ - WeCom App:**
+
+**1. アプリを作成**
+
+* WeCom 管理コンソール → アプリ管理 → アプリを作成
+* **AgentId** と **Secret** をコピー
+* "マイ会社" ページで **CorpID** をコピー
+
+**2. メッセージ受信を設定**
+
+* アプリ詳細で "メッセージを受信" → "APIを設定" をクリック
+* URL を `http://your-server:18792/webhook/wecom-app` に設定
+* **Token** と **EncodingAESKey** を生成
+
+**3. 設定**
+
+```json
+{
+ "channels": {
+ "wecom_app": {
+ "enabled": true,
+ "corp_id": "wwxxxxxxxxxxxxxxxx",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**4. 起動**
+
+```bash
+picoclaw gateway
+```
+
+> **注意**: WeCom App は Webhook コールバック用にポート 18792 を開放する必要があります。本番環境では HTTPS 用のリバースプロキシを使用してください。
+
+
+
## ⚙️ 設定
設定ファイル: `~/.picoclaw/config.json`
@@ -625,6 +707,22 @@ HEARTBEAT_OK 応答 ユーザーが直接結果を受け取る
- `PICOCLAW_HEARTBEAT_ENABLED=false` で無効化
- `PICOCLAW_HEARTBEAT_INTERVAL=60` で間隔変更
+### プロバイダー
+
+> [!NOTE]
+> Groq は Whisper による無料の音声文字起こしを提供しています。設定すると、Telegram の音声メッセージが自動的に文字起こしされます。
+
+| プロバイダー | 用途 | API キー取得先 |
+| --- | --- | --- |
+| `gemini` | LLM(Gemini 直接) | [aistudio.google.com](https://aistudio.google.com) |
+| `zhipu` | LLM(Zhipu 直接) | [bigmodel.cn](https://bigmodel.cn) |
+| `openrouter`(要テスト) | LLM(推奨、全モデルにアクセス可能) | [openrouter.ai](https://openrouter.ai) |
+| `anthropic`(要テスト) | LLM(Claude 直接) | [console.anthropic.com](https://console.anthropic.com) |
+| `openai`(要テスト) | LLM(GPT 直接) | [platform.openai.com](https://platform.openai.com) |
+| `deepseek`(要テスト) | LLM(DeepSeek 直接) | [platform.deepseek.com](https://platform.deepseek.com) |
+| `groq` | LLM + **音声文字起こし**(Whisper) | [console.groq.com](https://console.groq.com) |
+| `cerebras` | LLM(Cerebras 直接) | [cerebras.ai](https://cerebras.ai) |
+
### 基本設定
1. **設定ファイルの作成:**
@@ -718,6 +816,163 @@ HEARTBEAT_OK 応答 ユーザーが直接結果を受け取る
+### モデル設定 (model_list)
+
+> **新機能!** PicoClaw は現在 **モデル中心** の設定アプローチを採用しています。`ベンダー/モデル` 形式(例: `zhipu/glm-4.7`)を指定するだけで、新しいプロバイダーを追加できます—**コードの変更は一切不要!**
+
+この設計は、柔軟なプロバイダー選択による **マルチエージェントサポート** も可能にします:
+
+- **異なるエージェント、異なるプロバイダー** : 各エージェントは独自の LLM プロバイダーを使用可能
+- **フォールバックモデル** : 耐障性のため、プライマリモデルとフォールバックモデルを設定可能
+- **ロードバランシング** : 複数のエンドポイントにリクエストを分散
+- **集中設定管理** : すべてのプロバイダーを一箇所で管理
+
+#### 📋 サポートされているすべてのベンダー
+
+| ベンダー | `model` プレフィックス | デフォルト API Base | プロトコル | API キー |
+|-------------|-----------------|---------------------|----------|---------|
+| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [キーを取得](https://platform.openai.com) |
+| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [キーを取得](https://console.anthropic.com) |
+| **Zhipu AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [キーを取得](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) |
+| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [キーを取得](https://platform.deepseek.com) |
+| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | OpenAI | [キーを取得](https://aistudio.google.com/api-keys) |
+| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [キーを取得](https://console.groq.com) |
+| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [キーを取得](https://platform.moonshot.cn) |
+| **Qwen (Alibaba)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [キーを取得](https://dashscope.console.aliyun.com) |
+| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [キーを取得](https://build.nvidia.com) |
+| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | ローカル(キー不要) |
+| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [キーを取得](https://openrouter.ai/keys) |
+| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | ローカル |
+| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [キーを取得](https://cerebras.ai) |
+| **Volcengine** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [キーを取得](https://console.volcengine.com) |
+| **ShengsuanYun** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - |
+| **Antigravity** | `antigravity/` | Google Cloud | カスタム | OAuthのみ |
+| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - |
+
+#### 基本設定
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key"
+ },
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-zhipu-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "gpt-5.2"
+ }
+ }
+}
+```
+
+#### ベンダー別の例
+
+**OpenAI**
+```json
+{
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-..."
+}
+```
+
+**Zhipu AI (GLM)**
+```json
+{
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+}
+```
+
+**Anthropic (OAuth使用)**
+```json
+{
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "auth_method": "oauth"
+}
+```
+> OAuth認証を設定するには、`picoclaw auth login --provider anthropic` を実行してください。
+
+#### ロードバランシング
+
+同じモデル名で複数のエンドポイントを設定すると、PicoClaw が自動的にラウンドロビンで分散します:
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api1.example.com/v1",
+ "api_key": "sk-key1"
+ },
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api2.example.com/v1",
+ "api_key": "sk-key2"
+ }
+ ]
+}
+```
+
+#### 従来の `providers` 設定からの移行
+
+古い `providers` 設定は**非推奨**ですが、後方互換性のためにサポートされています。
+
+**旧設定(非推奨):**
+```json
+{
+ "providers": {
+ "zhipu": {
+ "api_key": "your-key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ },
+ "agents": {
+ "defaults": {
+ "provider": "zhipu",
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+**新設定(推奨):**
+```json
+{
+ "model_list": [
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+詳細な移行ガイドは、[docs/migration/model-list-migration.md](docs/migration/model-list-migration.md) を参照してください。
+
## CLI リファレンス
| コマンド | 説明 |
@@ -775,5 +1030,7 @@ Web 検索を有効にするには:
|---------|--------|------------|
| **OpenRouter** | 月 200K トークン | 複数モデル(Claude, GPT-4 など) |
| **Zhipu** | 月 200K トークン | 中国ユーザー向け最適 |
+| **Qwen** | 無料枠あり | 通義千問 (Qwen) |
| **Brave Search** | 月 2000 クエリ | Web 検索機能 |
| **Groq** | 無料枠あり | 高速推論(Llama, Mixtral) |
+| **Cerebras** | 無料枠あり | 高速推論(Llama, Qwen など) |
diff --git a/README.md b/README.md
index 01c81b20b..5aa7508d9 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@
- [中文](README.zh.md) | [日本語](README.ja.md) | [Português](README.pt-br.md) | [Tiếng Việt](README.vi.md) | **English**
+ [中文](README.zh.md) | [日本語](README.ja.md) | [Português](README.pt-br.md) | [Tiếng Việt](README.vi.md) | [Français](README.fr.md) | **English**
---
@@ -213,18 +213,24 @@ picoclaw onboard
"agents": {
"defaults": {
"workspace": "~/.picoclaw/workspace",
- "model": "glm-4.7",
+ "model": "gpt4",
"max_tokens": 8192,
"temperature": 0.7,
"max_tool_iterations": 20
}
},
- "providers": {
- "openrouter": {
- "api_key": "xxx",
- "api_base": "https://openrouter.ai/api/v1"
+ "model_list": [
+ {
+ "model_name": "gpt4",
+ "model": "openai/gpt-5.2",
+ "api_key": "your-api-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "your-anthropic-key"
}
- },
+ ],
"tools": {
"web": {
"brave": {
@@ -241,6 +247,8 @@ picoclaw onboard
}
```
+> **New**: The `model_list` configuration format allows zero-code provider addition. See [Model Configuration](#-model-configuration) for details.
+
**3. Get API Keys**
* **LLM Provider**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys)
@@ -260,7 +268,7 @@ That's it! You have a working AI assistant in 2 minutes.
## 💬 Chat Apps
-Talk to your picoclaw through Telegram, Discord, DingTalk, or LINE
+Talk to your picoclaw through Telegram, Discord, DingTalk, LINE, or WeCom
| Channel | Setup |
| ------------ | ---------------------------------- |
@@ -269,6 +277,7 @@ Talk to your picoclaw through Telegram, Discord, DingTalk, or LINE
| **QQ** | Easy (AppID + AppSecret) |
| **DingTalk** | Medium (app credentials) |
| **LINE** | Medium (credentials + webhook URL) |
+| **WeCom** | Medium (CorpID + webhook setup) |
Telegram (Recommended)
@@ -330,7 +339,8 @@ picoclaw gateway
"discord": {
"enabled": true,
"token": "YOUR_BOT_TOKEN",
- "allow_from": ["YOUR_USER_ID"]
+ "allow_from": ["YOUR_USER_ID"],
+ "mention_only": false
}
}
}
@@ -343,6 +353,10 @@ picoclaw gateway
* Bot Permissions: `Send Messages`, `Read Message History`
* Open the generated invite URL and add the bot to your server
+**Optional: Mention-only mode**
+
+Set `"mention_only": true` to make the bot respond only when @-mentioned. Useful for shared servers where you want the bot to respond only when explicitly called.
+
**6. Run**
```bash
@@ -468,6 +482,87 @@ picoclaw gateway
+
+WeCom (企业微信)
+
+PicoClaw supports two types of WeCom integration:
+
+**Option 1: WeCom Bot (智能机器人)** - Easier setup, supports group chats
+**Option 2: WeCom App (自建应用)** - More features, proactive messaging
+
+See [WeCom App Configuration Guide](docs/wecom-app-configuration.md) for detailed setup instructions.
+
+**Quick Setup - WeCom Bot:**
+
+**1. Create a bot**
+
+* Go to WeCom Admin Console → Group Chat → Add Group Bot
+* Copy the webhook URL (format: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`)
+
+**2. Configure**
+
+```json
+{
+ "channels": {
+ "wecom": {
+ "enabled": true,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**Quick Setup - WeCom App:**
+
+**1. Create an app**
+
+* Go to WeCom Admin Console → App Management → Create App
+* Copy **AgentId** and **Secret**
+* Go to "My Company" page, copy **CorpID**
+
+**2. Configure receive message**
+
+* In App details, click "Receive Message" → "Set API"
+* Set URL to `http://your-server:18792/webhook/wecom-app`
+* Generate **Token** and **EncodingAESKey**
+
+**3. Configure**
+
+```json
+{
+ "channels": {
+ "wecom_app": {
+ "enabled": true,
+ "corp_id": "wwxxxxxxxxxxxxxxxx",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**4. Run**
+
+```bash
+picoclaw gateway
+```
+
+> **Note**: WeCom App requires opening port 18792 for webhook callbacks. Use a reverse proxy for HTTPS.
+
+
+
## Join the Agent Social Network
Connect Picoclaw to the Agent Social Network simply by sending a single message via the CLI or any integrated Chat App.
@@ -681,7 +776,193 @@ The subagent has access to tools (message, web_search, etc.) and can communicate
| `anthropic(To be tested)` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) |
| `openai(To be tested)` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) |
| `deepseek(To be tested)` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) |
+| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) |
| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) |
+| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) |
+
+### Model Configuration (model_list)
+
+> **What's New?** PicoClaw now uses a **model-centric** configuration approach. Simply specify `vendor/model` format (e.g., `zhipu/glm-4.7`) to add new providers—**zero code changes required!**
+
+This design also enables **multi-agent support** with flexible provider selection:
+
+- **Different agents, different providers**: Each agent can use its own LLM provider
+- **Model fallbacks**: Configure primary and fallback models for resilience
+- **Load balancing**: Distribute requests across multiple endpoints
+- **Centralized configuration**: Manage all providers in one place
+
+#### 📋 All Supported Vendors
+
+| Vendor | `model` Prefix | Default API Base | Protocol | API Key |
+|--------|----------------|------------------|----------|---------|
+| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Get Key](https://platform.openai.com) |
+| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Get Key](https://console.anthropic.com) |
+| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Get Key](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) |
+| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Get Key](https://platform.deepseek.com) |
+| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | OpenAI | [Get Key](https://aistudio.google.com/api-keys) |
+| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Get Key](https://console.groq.com) |
+| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Get Key](https://platform.moonshot.cn) |
+| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Get Key](https://dashscope.console.aliyun.com) |
+| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Get Key](https://build.nvidia.com) |
+| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (no key needed) |
+| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Get Key](https://openrouter.ai/keys) |
+| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local |
+| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Get Key](https://cerebras.ai) |
+| **火山引擎** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Get Key](https://console.volcengine.com) |
+| **神算云** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - |
+| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth only |
+| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - |
+
+#### Basic Configuration
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key"
+ },
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-zhipu-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "gpt-5.2"
+ }
+ }
+}
+```
+
+#### Vendor-Specific Examples
+
+**OpenAI**
+```json
+{
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-..."
+}
+```
+
+**智谱 AI (GLM)**
+```json
+{
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+}
+```
+
+**DeepSeek**
+```json
+{
+ "model_name": "deepseek-chat",
+ "model": "deepseek/deepseek-chat",
+ "api_key": "sk-..."
+}
+```
+
+**Anthropic (with OAuth)**
+```json
+{
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "auth_method": "oauth"
+}
+```
+> Run `picoclaw auth login --provider anthropic` to set up OAuth credentials.
+
+**Ollama (local)**
+```json
+{
+ "model_name": "llama3",
+ "model": "ollama/llama3"
+}
+```
+
+**Custom Proxy/API**
+```json
+{
+ "model_name": "my-custom-model",
+ "model": "openai/custom-model",
+ "api_base": "https://my-proxy.com/v1",
+ "api_key": "sk-..."
+}
+```
+
+#### Load Balancing
+
+Configure multiple endpoints for the same model name—PicoClaw will automatically round-robin between them:
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api1.example.com/v1",
+ "api_key": "sk-key1"
+ },
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api2.example.com/v1",
+ "api_key": "sk-key2"
+ }
+ ]
+}
+```
+
+#### Migration from Legacy `providers` Config
+
+The old `providers` configuration is **deprecated** but still supported for backward compatibility.
+
+**Old Config (deprecated):**
+```json
+{
+ "providers": {
+ "zhipu": {
+ "api_key": "your-key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ },
+ "agents": {
+ "defaults": {
+ "provider": "zhipu",
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+**New Config (recommended):**
+```json
+{
+ "model_list": [
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+For detailed migration guide, see [docs/migration/model-list-migration.md](docs/migration/model-list-migration.md).
### Provider Architecture
@@ -887,3 +1168,4 @@ This happens when another instance of the bot is running. Make sure only one `pi
| **Zhipu** | 200K tokens/month | Best for Chinese users |
| **Brave Search** | 2000 queries/month | Web search functionality |
| **Groq** | Free tier available | Fast inference (Llama, Mixtral) |
+| **Cerebras** | Free tier available | Fast inference (Llama, Qwen, etc.) |
diff --git a/README.pt-br.md b/README.pt-br.md
index 171a6557b..4f43992c5 100644
--- a/README.pt-br.md
+++ b/README.pt-br.md
@@ -14,7 +14,7 @@
- [中文](README.zh.md) | [日本語](README.ja.md) | [English](README.md) | **Português**
+ [中文](README.zh.md) | [日本語](README.ja.md) | **Português** | [Tiếng Việt](README.vi.md) | [Français](README.fr.md) | [English](README.md)
---
@@ -267,7 +267,7 @@ Pronto! Você tem um assistente de IA funcionando em 2 minutos.
## 💬 Integração com Apps de Chat
-Converse com seu PicoClaw via Telegram, Discord, DingTalk ou LINE.
+Converse com seu PicoClaw via Telegram, Discord, DingTalk, LINE ou WeCom.
| Canal | Nível de Configuração |
| --- | --- |
@@ -276,6 +276,7 @@ Converse com seu PicoClaw via Telegram, Discord, DingTalk ou LINE.
| **QQ** | Fácil (AppID + AppSecret) |
| **DingTalk** | Médio (credenciais do app) |
| **LINE** | Médio (credenciais + webhook URL) |
+| **WeCom** | Médio (CorpID + configuração webhook) |
Telegram (Recomendado)
@@ -475,6 +476,87 @@ picoclaw gateway
+
+WeCom (WeChat Work)
+
+O PicoClaw suporta dois tipos de integração WeCom:
+
+**Opção 1: WeCom Bot (Robô Inteligente)** - Configuração mais fácil, suporta chats em grupo
+**Opção 2: WeCom App (Aplicativo Personalizado)** - Mais recursos, mensagens proativas
+
+Veja o [Guia de Configuração WeCom App](docs/wecom-app-configuration.md) para instruções detalhadas.
+
+**Configuração Rápida - WeCom Bot:**
+
+**1. Criar um bot**
+
+* Acesse o Console de Administração WeCom → Chat em Grupo → Adicionar Bot de Grupo
+* Copie a URL do webhook (formato: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`)
+
+**2. Configurar**
+
+```json
+{
+ "channels": {
+ "wecom": {
+ "enabled": true,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**Configuração Rápida - WeCom App:**
+
+**1. Criar um aplicativo**
+
+* Acesse o Console de Administração WeCom → Gerenciamento de Aplicativos → Criar Aplicativo
+* Copie o **AgentId** e o **Secret**
+* Acesse a página "Minha Empresa", copie o **CorpID**
+
+**2. Configurar recebimento de mensagens**
+
+* Nos detalhes do aplicativo, clique em "Receber Mensagens" → "Configurar API"
+* Defina a URL como `http://your-server:18792/webhook/wecom-app`
+* Gere o **Token** e o **EncodingAESKey**
+
+**3. Configurar**
+
+```json
+{
+ "channels": {
+ "wecom_app": {
+ "enabled": true,
+ "corp_id": "wwxxxxxxxxxxxxxxxx",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**4. Executar**
+
+```bash
+picoclaw gateway
+```
+
+> **Nota**: O WeCom App requer a abertura da porta 18792 para callbacks de webhook. Use um proxy reverso para HTTPS em produção.
+
+
+
## Junte-se a Rede Social de Agentes
Conecte o PicoClaw a Rede Social de Agentes simplesmente enviando uma única mensagem via CLI ou qualquer App de Chat integrado.
@@ -799,6 +881,163 @@ picoclaw agent -m "Ola, como vai?"
+### Configuração de Modelo (model_list)
+
+> **Novidade!** PicoClaw agora usa uma abordagem de configuração **centrada no modelo**. Basta especificar o formato `fornecedor/modelo` (ex: `zhipu/glm-4.7`) para adicionar novos provedores—**nenhuma alteração de código necessária!**
+
+Este design também possibilita o **suporte multi-agent** com seleção flexível de provedores:
+
+- **Diferentes agentes, diferentes provedores** : Cada agente pode usar seu próprio provedor LLM
+- **Modelos de fallback** : Configure modelos primários e de reserva para resiliência
+- **Balanceamento de carga** : Distribua solicitações entre múltiplos endpoints
+- **Configuração centralizada** : Gerencie todos os provedores em um só lugar
+
+#### 📋 Todos os Fornecedores Suportados
+
+| Fornecedor | Prefixo `model` | API Base Padrão | Protocolo | Chave API |
+|-------------|-----------------|------------------|----------|-----------|
+| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Obter Chave](https://platform.openai.com) |
+| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Obter Chave](https://console.anthropic.com) |
+| **Zhipu AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Obter Chave](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) |
+| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Obter Chave](https://platform.deepseek.com) |
+| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | OpenAI | [Obter Chave](https://aistudio.google.com/api-keys) |
+| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Obter Chave](https://console.groq.com) |
+| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Obter Chave](https://platform.moonshot.cn) |
+| **Qwen (Alibaba)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Obter Chave](https://dashscope.console.aliyun.com) |
+| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Obter Chave](https://build.nvidia.com) |
+| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (sem chave necessária) |
+| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Obter Chave](https://openrouter.ai/keys) |
+| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local |
+| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Obter Chave](https://cerebras.ai) |
+| **Volcengine** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Obter Chave](https://console.volcengine.com) |
+| **ShengsuanYun** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - |
+| **Antigravity** | `antigravity/` | Google Cloud | Custom | Apenas OAuth |
+| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - |
+
+#### Configuração Básica
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key"
+ },
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-zhipu-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "gpt-5.2"
+ }
+ }
+}
+```
+
+#### Exemplos por Fornecedor
+
+**OpenAI**
+```json
+{
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-..."
+}
+```
+
+**Zhipu AI (GLM)**
+```json
+{
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+}
+```
+
+**Anthropic (com OAuth)**
+```json
+{
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "auth_method": "oauth"
+}
+```
+> Execute `picoclaw auth login --provider anthropic` para configurar credenciais OAuth.
+
+#### Balanceamento de Carga
+
+Configure vários endpoints para o mesmo nome de modelo—PicoClaw fará round-robin automaticamente entre eles:
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api1.example.com/v1",
+ "api_key": "sk-key1"
+ },
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api2.example.com/v1",
+ "api_key": "sk-key2"
+ }
+ ]
+}
+```
+
+#### Migração da Configuração Legada `providers`
+
+A configuração antiga `providers` está **descontinuada** mas ainda é suportada para compatibilidade reversa.
+
+**Configuração Antiga (descontinuada):**
+```json
+{
+ "providers": {
+ "zhipu": {
+ "api_key": "your-key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ },
+ "agents": {
+ "defaults": {
+ "provider": "zhipu",
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+**Nova Configuração (recomendada):**
+```json
+{
+ "model_list": [
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+Para o guia de migração detalhado, consulte [docs/migration/model-list-migration.md](docs/migration/model-list-migration.md).
+
## Referência CLI
| Comando | Descrição |
diff --git a/README.vi.md b/README.vi.md
index e629eaa9b..5548f88a4 100644
--- a/README.vi.md
+++ b/README.vi.md
@@ -14,7 +14,7 @@
-**Tiếng Việt** | [中文](README.zh.md) | [日本語](README.ja.md) | [English](README.md)
+[中文](README.zh.md) | [日本語](README.ja.md) | [Português](README.pt-br.md) | **Tiếng Việt** | [Français](README.fr.md) | [English](README.md)
---
@@ -243,7 +243,7 @@ Vậy là xong! Bạn đã có một trợ lý AI hoạt động chỉ trong 2 p
## 💬 Tích hợp ứng dụng Chat
-Trò chuyện với PicoClaw qua Telegram, Discord, DingTalk hoặc LINE.
+Trò chuyện với PicoClaw qua Telegram, Discord, DingTalk, LINE hoặc WeCom.
| Kênh | Mức độ thiết lập |
| --- | --- |
@@ -252,6 +252,7 @@ Trò chuyện với PicoClaw qua Telegram, Discord, DingTalk hoặc LINE.
| **QQ** | Dễ (AppID + AppSecret) |
| **DingTalk** | Trung bình (app credentials) |
| **LINE** | Trung bình (credentials + webhook URL) |
+| **WeCom** | Trung bình (CorpID + cấu hình webhook) |
Telegram (Khuyên dùng)
@@ -451,6 +452,87 @@ picoclaw gateway
+
+WeCom (WeChat Work)
+
+PicoClaw hỗ trợ hai loại tích hợp WeCom:
+
+**Tùy chọn 1: WeCom Bot (Robot Thông minh)** - Thiết lập dễ dàng hơn, hỗ trợ chat nhóm
+**Tùy chọn 2: WeCom App (Ứng dụng Tự xây dựng)** - Nhiều tính năng hơn, nhắn tin chủ động
+
+Xem [Hướng dẫn Cấu hình WeCom App](docs/wecom-app-configuration.md) để biết hướng dẫn chi tiết.
+
+**Thiết lập Nhanh - WeCom Bot:**
+
+**1. Tạo bot**
+
+* Truy cập Bảng điều khiển Quản trị WeCom → Chat Nhóm → Thêm Bot Nhóm
+* Sao chép URL webhook (định dạng: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`)
+
+**2. Cấu hình**
+
+```json
+{
+ "channels": {
+ "wecom": {
+ "enabled": true,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**Thiết lập Nhanh - WeCom App:**
+
+**1. Tạo ứng dụng**
+
+* Truy cập Bảng điều khiển Quản trị WeCom → Quản lý Ứng dụng → Tạo Ứng dụng
+* Sao chép **AgentId** và **Secret**
+* Truy cập trang "Công ty của tôi", sao chép **CorpID**
+
+**2. Cấu hình nhận tin nhắn**
+
+* Trong chi tiết ứng dụng, nhấp vào "Nhận Tin nhắn" → "Thiết lập API"
+* Đặt URL thành `http://your-server:18792/webhook/wecom-app`
+* Tạo **Token** và **EncodingAESKey**
+
+**3. Cấu hình**
+
+```json
+{
+ "channels": {
+ "wecom_app": {
+ "enabled": true,
+ "corp_id": "wwxxxxxxxxxxxxxxxx",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**4. Chạy**
+
+```bash
+picoclaw gateway
+```
+
+> **Lưu ý**: WeCom App yêu cầu mở cổng 18792 cho callback webhook. Sử dụng proxy ngược cho HTTPS trong môi trường sản xuất.
+
+
+
## Tham gia Mạng xã hội Agent
Kết nối PicoClaw với Mạng xã hội Agent chỉ bằng cách gửi một tin nhắn qua CLI hoặc bất kỳ ứng dụng Chat nào đã tích hợp.
@@ -772,6 +854,163 @@ picoclaw agent -m "Xin chào"
+### Cấu hình Mô hình (model_list)
+
+> **Tính năng mới!** PicoClaw hiện sử dụng phương pháp cấu hình **đặt mô hình vào trung tâm**. Chỉ cần chỉ định dạng `nhà cung cấp/mô hình` (ví dụ: `zhipu/glm-4.7`) để thêm nhà cung cấp mới—**không cần thay đổi mã!**
+
+Thiết kế này cũng cho phép **hỗ trợ đa tác nhân** với lựa chọn nhà cung cấp linh hoạt:
+
+- **Tác nhân khác nhau, nhà cung cấp khác nhau** : Mỗi tác nhân có thể sử dụng nhà cung cấp LLM riêng
+- **Mô hình dự phòng** : Cấu hình mô hình chính và dự phòng để tăng độ tin cậy
+- **Cân bằng tải** : Phân phối yêu cầu trên nhiều endpoint khác nhau
+- **Cấu hình tập trung** : Quản lý tất cả nhà cung cấp ở một nơi
+
+#### 📋 Tất cả Nhà cung cấp được Hỗ trợ
+
+| Nhà cung cấp | Prefix `model` | API Base Mặc định | Giao thức | Khóa API |
+|-------------|----------------|-------------------|-----------|----------|
+| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Lấy Khóa](https://platform.openai.com) |
+| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Lấy Khóa](https://console.anthropic.com) |
+| **Zhipu AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Lấy Khóa](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) |
+| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Lấy Khóa](https://platform.deepseek.com) |
+| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | OpenAI | [Lấy Khóa](https://aistudio.google.com/api-keys) |
+| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Lấy Khóa](https://console.groq.com) |
+| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Lấy Khóa](https://platform.moonshot.cn) |
+| **Qwen (Alibaba)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Lấy Khóa](https://dashscope.console.aliyun.com) |
+| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Lấy Khóa](https://build.nvidia.com) |
+| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (không cần khóa) |
+| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Lấy Khóa](https://openrouter.ai/keys) |
+| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local |
+| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Lấy Khóa](https://cerebras.ai) |
+| **Volcengine** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Lấy Khóa](https://console.volcengine.com) |
+| **ShengsuanYun** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - |
+| **Antigravity** | `antigravity/` | Google Cloud | Tùy chỉnh | Chỉ OAuth |
+| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - |
+
+#### Cấu hình Cơ bản
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key"
+ },
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-zhipu-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "gpt-5.2"
+ }
+ }
+}
+```
+
+#### Ví dụ theo Nhà cung cấp
+
+**OpenAI**
+```json
+{
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-..."
+}
+```
+
+**Zhipu AI (GLM)**
+```json
+{
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+}
+```
+
+**Anthropic (với OAuth)**
+```json
+{
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "auth_method": "oauth"
+}
+```
+> Chạy `picoclaw auth login --provider anthropic` để thiết lập thông tin xác thực OAuth.
+
+#### Cân bằng Tải tải
+
+Định cấu hình nhiều endpoint cho cùng một tên mô hình—PicoClaw sẽ tự động phân phối round-robin giữa chúng:
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api1.example.com/v1",
+ "api_key": "sk-key1"
+ },
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api2.example.com/v1",
+ "api_key": "sk-key2"
+ }
+ ]
+}
+```
+
+#### Chuyển đổi từ Cấu hình `providers` Cũ
+
+Cấu hình `providers` cũ đã **ngừng sử dụng** nhưng vẫn được hỗ trợ để tương thích ngược.
+
+**Cấu hình Cũ (đã ngừng sử dụng):**
+```json
+{
+ "providers": {
+ "zhipu": {
+ "api_key": "your-key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ },
+ "agents": {
+ "defaults": {
+ "provider": "zhipu",
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+**Cấu hình Mới (khuyến nghị):**
+```json
+{
+ "model_list": [
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+Xem hướng dẫn chuyển đổi chi tiết tại [docs/migration/model-list-migration.md](docs/migration/model-list-migration.md).
+
## Tham chiếu CLI
| Lệnh | Mô tả |
diff --git a/README.zh.md b/README.zh.md
index 434805f93..7b5955689 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -14,7 +14,7 @@
- **中文** | [日本語](README.ja.md) | [Português](README.pt-br.md) | [Tiếng Việt](README.vi.md) | [English](README.md)
+ **中文** | [日本語](README.ja.md) | [Português](README.pt-br.md) | [Tiếng Việt](README.vi.md) | [Français](README.fr.md) | [English](README.md)
---
@@ -222,18 +222,24 @@ picoclaw onboard
"agents": {
"defaults": {
"workspace": "~/.picoclaw/workspace",
- "model": "glm-4.7",
+ "model": "gpt4",
"max_tokens": 8192,
"temperature": 0.7,
"max_tool_iterations": 20
}
},
- "providers": {
- "openrouter": {
- "api_key": "xxx",
- "api_base": "https://openrouter.ai/api/v1"
+ "model_list": [
+ {
+ "model_name": "gpt4",
+ "model": "openai/gpt-5.2",
+ "api_key": "your-api-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "your-anthropic-key"
}
- },
+ ],
"tools": {
"web": {
"search": {
@@ -249,6 +255,8 @@ picoclaw onboard
```
+> **新功能**: `model_list` 配置格式支持零代码添加 provider。详见[模型配置](#-模型配置-model_list)章节。
+
**3. 获取 API Key**
* **LLM 提供商**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys)
@@ -269,14 +277,15 @@ picoclaw agent -m "2+2 等于几?"
## 💬 聊天应用集成 (Chat Apps)
-通过 Telegram, Discord 或钉钉与您的 PicoClaw 对话。
+通过 Telegram, Discord, 钉钉或企业微信与您的 PicoClaw 对话。
| 渠道 | 设置难度 |
| --- | --- |
| **Telegram** | 简单 (仅需 token) |
| **Discord** | 简单 (bot token + intents) |
| **QQ** | 简单 (AppID + AppSecret) |
-| **钉钉 (DingTalk)** | 中等 (app credentials) |
+| **钉钉 (DingTalk)** | 中等 (应用凭证) |
+| **企业微信 (WeCom)** | 中等 (企业ID + Webhook配置) |
Telegram (推荐)
@@ -434,6 +443,88 @@ picoclaw gateway
+
+企业微信 (WeCom)
+
+PicoClaw 支持两种企业微信集成方式:
+
+**选项1: 智能机器人 (WeCom Bot)** - 设置更简单,支持群聊
+**选项2: 自建应用 (WeCom App)** - 功能更丰富,支持主动推送消息
+
+详见 [企业微信自建应用配置指南](docs/wecom-app-configuration.md)。
+
+**快速设置 - 智能机器人:**
+
+**1. 创建机器人**
+
+* 前往企业微信管理后台 → 群聊 → 添加群机器人
+* 复制 Webhook URL (格式: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`)
+
+**2. 配置**
+
+```json
+{
+ "channels": {
+ "wecom": {
+ "enabled": true,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**快速设置 - 自建应用:**
+
+**1. 创建应用**
+
+* 前往企业微信管理后台 → 应用管理 → 创建应用
+* 复制 **AgentId** 和 **Secret**
+* 前往"我的企业"页面,复制 **CorpID**
+
+**2. 配置接收消息**
+
+* 在应用详情页,点击"接收消息" → "设置API"
+* 设置 URL 为 `http://your-server:18792/webhook/wecom-app`
+* 生成 **Token** 和 **EncodingAESKey**
+
+**3. 配置**
+
+```json
+{
+ "channels": {
+ "wecom_app": {
+ "enabled": true,
+ "corp_id": "wwxxxxxxxxxxxxxxxx",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**4. 运行**
+
+```bash
+picoclaw gateway
+
+```
+
+> **注意**: 自建应用需要开放 18792 端口用于接收 Webhook 回调。生产环境建议使用反向代理配置 HTTPS。
+
+
+
## 加入 Agent 社交网络
只需通过 CLI 或任何集成的聊天应用发送一条消息,即可将 PicoClaw 连接到 Agent 社交网络。
@@ -558,7 +649,193 @@ Agent 读取 HEARTBEAT.md
| `anthropic(待测试)` | LLM (Claude 直连) | [console.anthropic.com](https://console.anthropic.com) |
| `openai(待测试)` | LLM (GPT 直连) | [platform.openai.com](https://platform.openai.com) |
| `deepseek(待测试)` | LLM (DeepSeek 直连) | [platform.deepseek.com](https://platform.deepseek.com) |
+| `qwen` | LLM (通义千问) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) |
| `groq` | LLM + **语音转录** (Whisper) | [console.groq.com](https://console.groq.com) |
+| `cerebras` | LLM (Cerebras 直连) | [cerebras.ai](https://cerebras.ai) |
+
+### 模型配置 (model_list)
+
+> **新功能!** PicoClaw 现在采用**以模型为中心**的配置方式。只需使用 `厂商/模型` 格式(如 `zhipu/glm-4.7`)即可添加新的 provider——**无需修改任何代码!**
+
+该设计同时支持**多 Agent 场景**,提供灵活的 Provider 选择:
+
+- **不同 Agent 使用不同 Provider**:每个 Agent 可以使用自己的 LLM provider
+- **模型回退(Fallback)**:配置主模型和备用模型,提高可靠性
+- **负载均衡**:在多个 API 端点之间分配请求
+- **集中化配置**:在一个地方管理所有 provider
+
+#### 📋 所有支持的厂商
+
+| 厂商 | `model` 前缀 | 默认 API Base | 协议 | 获取 API Key |
+|------|-------------|---------------|------|--------------|
+| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [获取密钥](https://platform.openai.com) |
+| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [获取密钥](https://console.anthropic.com) |
+| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [获取密钥](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) |
+| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [获取密钥](https://platform.deepseek.com) |
+| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | OpenAI | [获取密钥](https://aistudio.google.com/api-keys) |
+| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [获取密钥](https://console.groq.com) |
+| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [获取密钥](https://platform.moonshot.cn) |
+| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [获取密钥](https://dashscope.console.aliyun.com) |
+| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [获取密钥](https://build.nvidia.com) |
+| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | 本地(无需密钥) |
+| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [获取密钥](https://openrouter.ai/keys) |
+| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | 本地 |
+| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [获取密钥](https://cerebras.ai) |
+| **火山引擎** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [获取密钥](https://console.volcengine.com) |
+| **神算云** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - |
+| **Antigravity** | `antigravity/` | Google Cloud | 自定义 | 仅 OAuth |
+| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - |
+
+#### 基础配置示例
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key"
+ },
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-zhipu-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "gpt-5.2"
+ }
+ }
+}
+```
+
+#### 各厂商配置示例
+
+**OpenAI**
+```json
+{
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-..."
+}
+```
+
+**智谱 AI (GLM)**
+```json
+{
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+}
+```
+
+**DeepSeek**
+```json
+{
+ "model_name": "deepseek-chat",
+ "model": "deepseek/deepseek-chat",
+ "api_key": "sk-..."
+}
+```
+
+**Anthropic (使用 OAuth)**
+```json
+{
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "auth_method": "oauth"
+}
+```
+> 运行 `picoclaw auth login --provider anthropic` 来设置 OAuth 凭证。
+
+**Ollama (本地)**
+```json
+{
+ "model_name": "llama3",
+ "model": "ollama/llama3"
+}
+```
+
+**自定义代理/API**
+```json
+{
+ "model_name": "my-custom-model",
+ "model": "openai/custom-model",
+ "api_base": "https://my-proxy.com/v1",
+ "api_key": "sk-..."
+}
+```
+
+#### 负载均衡
+
+为同一个模型名称配置多个端点——PicoClaw 会自动在它们之间轮询:
+
+```json
+{
+ "model_list": [
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api1.example.com/v1",
+ "api_key": "sk-key1"
+ },
+ {
+ "model_name": "gpt-5.2",
+ "model": "openai/gpt-5.2",
+ "api_base": "https://api2.example.com/v1",
+ "api_key": "sk-key2"
+ }
+ ]
+}
+```
+
+#### 从旧的 `providers` 配置迁移
+
+旧的 `providers` 配置格式**已弃用**,但为向后兼容仍支持。
+
+**旧配置(已弃用):**
+```json
+{
+ "providers": {
+ "zhipu": {
+ "api_key": "your-key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ },
+ "agents": {
+ "defaults": {
+ "provider": "zhipu",
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+**新配置(推荐):**
+```json
+{
+ "model_list": [
+ {
+ "model_name": "glm-4.7",
+ "model": "zhipu/glm-4.7",
+ "api_key": "your-key"
+ }
+ ],
+ "agents": {
+ "defaults": {
+ "model": "glm-4.7"
+ }
+ }
+}
+```
+
+详细的迁移指南请参考 [docs/migration/model-list-migration.md](docs/migration/model-list-migration.md)。
智谱 (Zhipu) 配置示例
@@ -745,4 +1022,5 @@ Discord: [https://discord.gg/V4sAZ9XWpN](https://discord.gg/V4sAZ9XWpN)
| **OpenRouter** | 200K tokens/月 | 多模型聚合 (Claude, GPT-4 等) |
| **智谱 (Zhipu)** | 200K tokens/月 | 最适合中国用户 |
| **Brave Search** | 2000 次查询/月 | 网络搜索功能 |
-| **Groq** | 提供免费层级 | 极速推理 (Llama, Mixtral) |
\ No newline at end of file
+| **Groq** | 提供免费层级 | 极速推理 (Llama, Mixtral) |
+| **Cerebras** | 提供免费层级 | 极速推理 (Llama, Qwen 等) |
\ No newline at end of file
diff --git a/cmd/picoclaw/cmd_agent.go b/cmd/picoclaw/cmd_agent.go
new file mode 100644
index 000000000..cee9f68ec
--- /dev/null
+++ b/cmd/picoclaw/cmd_agent.go
@@ -0,0 +1,181 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/chzyer/readline"
+ "github.com/sipeed/picoclaw/pkg/agent"
+ "github.com/sipeed/picoclaw/pkg/bus"
+ "github.com/sipeed/picoclaw/pkg/logger"
+ "github.com/sipeed/picoclaw/pkg/providers"
+)
+
+func agentCmd() {
+ message := ""
+ sessionKey := "cli:default"
+ modelOverride := ""
+
+ args := os.Args[2:]
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--debug", "-d":
+ logger.SetLevel(logger.DEBUG)
+ fmt.Println("🔍 Debug mode enabled")
+ case "-m", "--message":
+ if i+1 < len(args) {
+ message = args[i+1]
+ i++
+ }
+ case "-s", "--session":
+ if i+1 < len(args) {
+ sessionKey = args[i+1]
+ i++
+ }
+ case "--model", "-model":
+ if i+1 < len(args) {
+ modelOverride = args[i+1]
+ i++
+ }
+ }
+ }
+
+ cfg, err := loadConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if modelOverride != "" {
+ cfg.Agents.Defaults.Model = modelOverride
+ }
+
+ provider, modelID, err := providers.CreateProvider(cfg)
+ if err != nil {
+ fmt.Printf("Error creating provider: %v\n", err)
+ os.Exit(1)
+ }
+ // Use the resolved model ID from provider creation
+ if modelID != "" {
+ cfg.Agents.Defaults.Model = modelID
+ }
+
+ msgBus := bus.NewMessageBus()
+ agentLoop := agent.NewAgentLoop(cfg, msgBus, provider)
+
+ // Print agent startup info (only for interactive mode)
+ startupInfo := agentLoop.GetStartupInfo()
+ logger.InfoCF("agent", "Agent initialized",
+ map[string]interface{}{
+ "tools_count": startupInfo["tools"].(map[string]interface{})["count"],
+ "skills_total": startupInfo["skills"].(map[string]interface{})["total"],
+ "skills_available": startupInfo["skills"].(map[string]interface{})["available"],
+ })
+
+ if message != "" {
+ ctx := context.Background()
+ response, err := agentLoop.ProcessDirect(ctx, message, sessionKey)
+ if err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+ fmt.Printf("\n%s %s\n", logo, response)
+ } else {
+ fmt.Printf("%s Interactive mode (Ctrl+C to exit)\n\n", logo)
+ interactiveMode(agentLoop, sessionKey)
+ }
+}
+
+func interactiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
+ prompt := fmt.Sprintf("%s You: ", logo)
+
+ rl, err := readline.NewEx(&readline.Config{
+ Prompt: prompt,
+ HistoryFile: filepath.Join(os.TempDir(), ".picoclaw_history"),
+ HistoryLimit: 100,
+ InterruptPrompt: "^C",
+ EOFPrompt: "exit",
+ })
+
+ if err != nil {
+ fmt.Printf("Error initializing readline: %v\n", err)
+ fmt.Println("Falling back to simple input mode...")
+ simpleInteractiveMode(agentLoop, sessionKey)
+ return
+ }
+ defer rl.Close()
+
+ for {
+ line, err := rl.Readline()
+ if err != nil {
+ if err == readline.ErrInterrupt || err == io.EOF {
+ fmt.Println("\nGoodbye!")
+ return
+ }
+ fmt.Printf("Error reading input: %v\n", err)
+ continue
+ }
+
+ input := strings.TrimSpace(line)
+ if input == "" {
+ continue
+ }
+
+ if input == "exit" || input == "quit" {
+ fmt.Println("Goodbye!")
+ return
+ }
+
+ ctx := context.Background()
+ response, err := agentLoop.ProcessDirect(ctx, input, sessionKey)
+ if err != nil {
+ fmt.Printf("Error: %v\n", err)
+ continue
+ }
+
+ fmt.Printf("\n%s %s\n\n", logo, response)
+ }
+}
+
+func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
+ reader := bufio.NewReader(os.Stdin)
+ for {
+ fmt.Print(fmt.Sprintf("%s You: ", logo))
+ line, err := reader.ReadString('\n')
+ if err != nil {
+ if err == io.EOF {
+ fmt.Println("\nGoodbye!")
+ return
+ }
+ fmt.Printf("Error reading input: %v\n", err)
+ continue
+ }
+
+ input := strings.TrimSpace(line)
+ if input == "" {
+ continue
+ }
+
+ if input == "exit" || input == "quit" {
+ fmt.Println("Goodbye!")
+ return
+ }
+
+ ctx := context.Background()
+ response, err := agentLoop.ProcessDirect(ctx, input, sessionKey)
+ if err != nil {
+ fmt.Printf("Error: %v\n", err)
+ continue
+ }
+
+ fmt.Printf("\n%s %s\n\n", logo, response)
+ }
+}
diff --git a/cmd/picoclaw/cmd_auth.go b/cmd/picoclaw/cmd_auth.go
new file mode 100644
index 000000000..5bed7f116
--- /dev/null
+++ b/cmd/picoclaw/cmd_auth.go
@@ -0,0 +1,512 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/sipeed/picoclaw/pkg/auth"
+ "github.com/sipeed/picoclaw/pkg/config"
+ "github.com/sipeed/picoclaw/pkg/providers"
+)
+
+const supportedProvidersMsg = "Supported providers: openai, anthropic, google-antigravity"
+
+func authCmd() {
+ if len(os.Args) < 3 {
+ authHelp()
+ return
+ }
+
+ switch os.Args[2] {
+ case "login":
+ authLoginCmd()
+ case "logout":
+ authLogoutCmd()
+ case "status":
+ authStatusCmd()
+ case "models":
+ authModelsCmd()
+ default:
+ fmt.Printf("Unknown auth command: %s\n", os.Args[2])
+ authHelp()
+ }
+}
+
+func authHelp() {
+ fmt.Println("\nAuth commands:")
+ fmt.Println(" login Login via OAuth or paste token")
+ fmt.Println(" logout Remove stored credentials")
+ fmt.Println(" status Show current auth status")
+ fmt.Println(" models List available Antigravity models")
+ fmt.Println()
+ fmt.Println("Login options:")
+ fmt.Println(" --provider Provider to login with (openai, anthropic, google-antigravity)")
+ fmt.Println(" --device-code Use device code flow (for headless environments)")
+ fmt.Println()
+ fmt.Println("Examples:")
+ fmt.Println(" picoclaw auth login --provider openai")
+ fmt.Println(" picoclaw auth login --provider openai --device-code")
+ fmt.Println(" picoclaw auth login --provider anthropic")
+ fmt.Println(" picoclaw auth login --provider google-antigravity")
+ fmt.Println(" picoclaw auth models")
+ fmt.Println(" picoclaw auth logout --provider openai")
+ fmt.Println(" picoclaw auth status")
+}
+
+func authLoginCmd() {
+ provider := ""
+ useDeviceCode := false
+
+ args := os.Args[3:]
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--provider", "-p":
+ if i+1 < len(args) {
+ provider = args[i+1]
+ i++
+ }
+ case "--device-code":
+ useDeviceCode = true
+ }
+ }
+
+ if provider == "" {
+ fmt.Println("Error: --provider is required")
+ fmt.Println(supportedProvidersMsg)
+ return
+ }
+
+ switch provider {
+ case "openai":
+ authLoginOpenAI(useDeviceCode)
+ case "anthropic":
+ authLoginPasteToken(provider)
+ case "google-antigravity", "antigravity":
+ authLoginGoogleAntigravity()
+ default:
+ fmt.Printf("Unsupported provider: %s\n", provider)
+ fmt.Println(supportedProvidersMsg)
+ }
+}
+
+func authLoginOpenAI(useDeviceCode bool) {
+ cfg := auth.OpenAIOAuthConfig()
+
+ var cred *auth.AuthCredential
+ var err error
+
+ if useDeviceCode {
+ cred, err = auth.LoginDeviceCode(cfg)
+ } else {
+ cred, err = auth.LoginBrowser(cfg)
+ }
+
+ if err != nil {
+ fmt.Printf("Login failed: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := auth.SetCredential("openai", cred); err != nil {
+ fmt.Printf("Failed to save credentials: %v\n", err)
+ os.Exit(1)
+ }
+
+ appCfg, err := loadConfig()
+ if err == nil {
+ // Update Providers (legacy format)
+ appCfg.Providers.OpenAI.AuthMethod = "oauth"
+
+ // Update or add openai in ModelList
+ foundOpenAI := false
+ for i := range appCfg.ModelList {
+ if isOpenAIModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = "oauth"
+ foundOpenAI = true
+ break
+ }
+ }
+
+ // If no openai in ModelList, add it
+ if !foundOpenAI {
+ appCfg.ModelList = append(appCfg.ModelList, config.ModelConfig{
+ ModelName: "gpt-5.2",
+ Model: "openai/gpt-5.2",
+ AuthMethod: "oauth",
+ })
+ }
+
+ // Update default model to use OpenAI
+ appCfg.Agents.Defaults.Model = "gpt-5.2"
+
+ if err := config.SaveConfig(getConfigPath(), appCfg); err != nil {
+ fmt.Printf("Warning: could not update config: %v\n", err)
+ }
+ }
+
+ fmt.Println("Login successful!")
+ if cred.AccountID != "" {
+ fmt.Printf("Account: %s\n", cred.AccountID)
+ }
+ fmt.Println("Default model set to: gpt-5.2")
+}
+
+func authLoginGoogleAntigravity() {
+ cfg := auth.GoogleAntigravityOAuthConfig()
+
+ cred, err := auth.LoginBrowser(cfg)
+ if err != nil {
+ fmt.Printf("Login failed: %v\n", err)
+ os.Exit(1)
+ }
+
+ cred.Provider = "google-antigravity"
+
+ // Fetch user email from Google userinfo
+ email, err := fetchGoogleUserEmail(cred.AccessToken)
+ if err != nil {
+ fmt.Printf("Warning: could not fetch email: %v\n", err)
+ } else {
+ cred.Email = email
+ fmt.Printf("Email: %s\n", email)
+ }
+
+ // Fetch Cloud Code Assist project ID
+ projectID, err := providers.FetchAntigravityProjectID(cred.AccessToken)
+ if err != nil {
+ fmt.Printf("Warning: could not fetch project ID: %v\n", err)
+ fmt.Println("You may need Google Cloud Code Assist enabled on your account.")
+ } else {
+ cred.ProjectID = projectID
+ fmt.Printf("Project: %s\n", projectID)
+ }
+
+ if err := auth.SetCredential("google-antigravity", cred); err != nil {
+ fmt.Printf("Failed to save credentials: %v\n", err)
+ os.Exit(1)
+ }
+
+ appCfg, err := loadConfig()
+ if err == nil {
+ // Update Providers (legacy format, for backward compatibility)
+ appCfg.Providers.Antigravity.AuthMethod = "oauth"
+
+ // Update or add antigravity in ModelList
+ foundAntigravity := false
+ for i := range appCfg.ModelList {
+ if isAntigravityModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = "oauth"
+ foundAntigravity = true
+ break
+ }
+ }
+
+ // If no antigravity in ModelList, add it
+ if !foundAntigravity {
+ appCfg.ModelList = append(appCfg.ModelList, config.ModelConfig{
+ ModelName: "gemini-flash",
+ Model: "antigravity/gemini-3-flash",
+ AuthMethod: "oauth",
+ })
+ }
+
+ // Update default model
+ appCfg.Agents.Defaults.Model = "gemini-flash"
+
+ if err := config.SaveConfig(getConfigPath(), appCfg); err != nil {
+ fmt.Printf("Warning: could not update config: %v\n", err)
+ }
+ }
+
+ fmt.Println("\n✓ Google Antigravity login successful!")
+ fmt.Println("Default model set to: gemini-flash")
+ fmt.Println("Try it: picoclaw agent -m \"Hello world\"")
+}
+
+func fetchGoogleUserEmail(accessToken string) (string, error) {
+ req, err := http.NewRequest("GET", "https://www.googleapis.com/oauth2/v2/userinfo", nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+
+ client := &http.Client{Timeout: 10 * time.Second}
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("userinfo request failed: %s", string(body))
+ }
+
+ var userInfo struct {
+ Email string `json:"email"`
+ }
+ if err := json.Unmarshal(body, &userInfo); err != nil {
+ return "", err
+ }
+ return userInfo.Email, nil
+}
+
+func authLoginPasteToken(provider string) {
+ cred, err := auth.LoginPasteToken(provider, os.Stdin)
+ if err != nil {
+ fmt.Printf("Login failed: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := auth.SetCredential(provider, cred); err != nil {
+ fmt.Printf("Failed to save credentials: %v\n", err)
+ os.Exit(1)
+ }
+
+ appCfg, err := loadConfig()
+ if err == nil {
+ switch provider {
+ case "anthropic":
+ appCfg.Providers.Anthropic.AuthMethod = "token"
+ // Update ModelList
+ found := false
+ for i := range appCfg.ModelList {
+ if isAnthropicModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = "token"
+ found = true
+ break
+ }
+ }
+ if !found {
+ appCfg.ModelList = append(appCfg.ModelList, config.ModelConfig{
+ ModelName: "claude-sonnet-4.6",
+ Model: "anthropic/claude-sonnet-4.6",
+ AuthMethod: "token",
+ })
+ }
+ // Update default model
+ appCfg.Agents.Defaults.Model = "claude-sonnet-4.6"
+ case "openai":
+ appCfg.Providers.OpenAI.AuthMethod = "token"
+ // Update ModelList
+ found := false
+ for i := range appCfg.ModelList {
+ if isOpenAIModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = "token"
+ found = true
+ break
+ }
+ }
+ if !found {
+ appCfg.ModelList = append(appCfg.ModelList, config.ModelConfig{
+ ModelName: "gpt-5.2",
+ Model: "openai/gpt-5.2",
+ AuthMethod: "token",
+ })
+ }
+ // Update default model
+ appCfg.Agents.Defaults.Model = "gpt-5.2"
+ }
+ if err := config.SaveConfig(getConfigPath(), appCfg); err != nil {
+ fmt.Printf("Warning: could not update config: %v\n", err)
+ }
+ }
+
+ fmt.Printf("Token saved for %s!\n", provider)
+ fmt.Printf("Default model set to: %s\n", appCfg.Agents.Defaults.Model)
+}
+
+func authLogoutCmd() {
+ provider := ""
+
+ args := os.Args[3:]
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--provider", "-p":
+ if i+1 < len(args) {
+ provider = args[i+1]
+ i++
+ }
+ }
+ }
+
+ if provider != "" {
+ if err := auth.DeleteCredential(provider); err != nil {
+ fmt.Printf("Failed to remove credentials: %v\n", err)
+ os.Exit(1)
+ }
+
+ appCfg, err := loadConfig()
+ if err == nil {
+ // Clear AuthMethod in ModelList
+ for i := range appCfg.ModelList {
+ switch provider {
+ case "openai":
+ if isOpenAIModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = ""
+ }
+ case "anthropic":
+ if isAnthropicModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = ""
+ }
+ case "google-antigravity", "antigravity":
+ if isAntigravityModel(appCfg.ModelList[i].Model) {
+ appCfg.ModelList[i].AuthMethod = ""
+ }
+ }
+ }
+ // Clear AuthMethod in Providers (legacy)
+ switch provider {
+ case "openai":
+ appCfg.Providers.OpenAI.AuthMethod = ""
+ case "anthropic":
+ appCfg.Providers.Anthropic.AuthMethod = ""
+ case "google-antigravity", "antigravity":
+ appCfg.Providers.Antigravity.AuthMethod = ""
+ }
+ config.SaveConfig(getConfigPath(), appCfg)
+ }
+
+ fmt.Printf("Logged out from %s\n", provider)
+ } else {
+ if err := auth.DeleteAllCredentials(); err != nil {
+ fmt.Printf("Failed to remove credentials: %v\n", err)
+ os.Exit(1)
+ }
+
+ appCfg, err := loadConfig()
+ if err == nil {
+ // Clear all AuthMethods in ModelList
+ for i := range appCfg.ModelList {
+ appCfg.ModelList[i].AuthMethod = ""
+ }
+ // Clear all AuthMethods in Providers (legacy)
+ appCfg.Providers.OpenAI.AuthMethod = ""
+ appCfg.Providers.Anthropic.AuthMethod = ""
+ appCfg.Providers.Antigravity.AuthMethod = ""
+ config.SaveConfig(getConfigPath(), appCfg)
+ }
+
+ fmt.Println("Logged out from all providers")
+ }
+}
+
+func authStatusCmd() {
+ store, err := auth.LoadStore()
+ if err != nil {
+ fmt.Printf("Error loading auth store: %v\n", err)
+ return
+ }
+
+ if len(store.Credentials) == 0 {
+ fmt.Println("No authenticated providers.")
+ fmt.Println("Run: picoclaw auth login --provider ")
+ return
+ }
+
+ fmt.Println("\nAuthenticated Providers:")
+ fmt.Println("------------------------")
+ for provider, cred := range store.Credentials {
+ status := "active"
+ if cred.IsExpired() {
+ status = "expired"
+ } else if cred.NeedsRefresh() {
+ status = "needs refresh"
+ }
+
+ fmt.Printf(" %s:\n", provider)
+ fmt.Printf(" Method: %s\n", cred.AuthMethod)
+ fmt.Printf(" Status: %s\n", status)
+ if cred.AccountID != "" {
+ fmt.Printf(" Account: %s\n", cred.AccountID)
+ }
+ if cred.Email != "" {
+ fmt.Printf(" Email: %s\n", cred.Email)
+ }
+ if cred.ProjectID != "" {
+ fmt.Printf(" Project: %s\n", cred.ProjectID)
+ }
+ if !cred.ExpiresAt.IsZero() {
+ fmt.Printf(" Expires: %s\n", cred.ExpiresAt.Format("2006-01-02 15:04"))
+ }
+ }
+}
+
+func authModelsCmd() {
+ cred, err := auth.GetCredential("google-antigravity")
+ if err != nil || cred == nil {
+ fmt.Println("Not logged in to Google Antigravity.")
+ fmt.Println("Run: picoclaw auth login --provider google-antigravity")
+ return
+ }
+
+ // Refresh token if needed
+ if cred.NeedsRefresh() && cred.RefreshToken != "" {
+ oauthCfg := auth.GoogleAntigravityOAuthConfig()
+ refreshed, refreshErr := auth.RefreshAccessToken(cred, oauthCfg)
+ if refreshErr == nil {
+ cred = refreshed
+ _ = auth.SetCredential("google-antigravity", cred)
+ }
+ }
+
+ projectID := cred.ProjectID
+ if projectID == "" {
+ fmt.Println("No project ID stored. Try logging in again.")
+ return
+ }
+
+ fmt.Printf("Fetching models for project: %s\n\n", projectID)
+
+ models, err := providers.FetchAntigravityModels(cred.AccessToken, projectID)
+ if err != nil {
+ fmt.Printf("Error fetching models: %v\n", err)
+ return
+ }
+
+ if len(models) == 0 {
+ fmt.Println("No models available.")
+ return
+ }
+
+ fmt.Println("Available Antigravity Models:")
+ fmt.Println("-----------------------------")
+ for _, m := range models {
+ status := "✓"
+ if m.IsExhausted {
+ status = "✗ (quota exhausted)"
+ }
+ name := m.ID
+ if m.DisplayName != "" {
+ name = fmt.Sprintf("%s (%s)", m.ID, m.DisplayName)
+ }
+ fmt.Printf(" %s %s\n", status, name)
+ }
+}
+
+// isAntigravityModel checks if a model string belongs to antigravity provider
+func isAntigravityModel(model string) bool {
+ return model == "antigravity" ||
+ model == "google-antigravity" ||
+ strings.HasPrefix(model, "antigravity/") ||
+ strings.HasPrefix(model, "google-antigravity/")
+}
+
+// isOpenAIModel checks if a model string belongs to openai provider
+func isOpenAIModel(model string) bool {
+ return model == "openai" ||
+ strings.HasPrefix(model, "openai/")
+}
+
+// isAnthropicModel checks if a model string belongs to anthropic provider
+func isAnthropicModel(model string) bool {
+ return model == "anthropic" ||
+ strings.HasPrefix(model, "anthropic/")
+}
diff --git a/cmd/picoclaw/cmd_cron.go b/cmd/picoclaw/cmd_cron.go
new file mode 100644
index 000000000..8c42bde06
--- /dev/null
+++ b/cmd/picoclaw/cmd_cron.go
@@ -0,0 +1,227 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/sipeed/picoclaw/pkg/cron"
+)
+
+func cronCmd() {
+ if len(os.Args) < 3 {
+ cronHelp()
+ return
+ }
+
+ subcommand := os.Args[2]
+
+ // Load config to get workspace path
+ cfg, err := loadConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ return
+ }
+
+ cronStorePath := filepath.Join(cfg.WorkspacePath(), "cron", "jobs.json")
+
+ switch subcommand {
+ case "list":
+ cronListCmd(cronStorePath)
+ case "add":
+ cronAddCmd(cronStorePath)
+ case "remove":
+ if len(os.Args) < 4 {
+ fmt.Println("Usage: picoclaw cron remove ")
+ return
+ }
+ cronRemoveCmd(cronStorePath, os.Args[3])
+ case "enable":
+ cronEnableCmd(cronStorePath, false)
+ case "disable":
+ cronEnableCmd(cronStorePath, true)
+ default:
+ fmt.Printf("Unknown cron command: %s\n", subcommand)
+ cronHelp()
+ }
+}
+
+func cronHelp() {
+ fmt.Println("\nCron commands:")
+ fmt.Println(" list List all scheduled jobs")
+ fmt.Println(" add Add a new scheduled job")
+ fmt.Println(" remove Remove a job by ID")
+ fmt.Println(" enable Enable a job")
+ fmt.Println(" disable Disable a job")
+ fmt.Println()
+ fmt.Println("Add options:")
+ fmt.Println(" -n, --name Job name")
+ fmt.Println(" -m, --message Message for agent")
+ fmt.Println(" -e, --every Run every N seconds")
+ fmt.Println(" -c, --cron Cron expression (e.g. '0 9 * * *')")
+ fmt.Println(" -d, --deliver Deliver response to channel")
+ fmt.Println(" --to Recipient for delivery")
+ fmt.Println(" --channel Channel for delivery")
+}
+
+func cronListCmd(storePath string) {
+ cs := cron.NewCronService(storePath, nil)
+ jobs := cs.ListJobs(true) // Show all jobs, including disabled
+
+ if len(jobs) == 0 {
+ fmt.Println("No scheduled jobs.")
+ return
+ }
+
+ fmt.Println("\nScheduled Jobs:")
+ fmt.Println("----------------")
+ for _, job := range jobs {
+ var schedule string
+ if job.Schedule.Kind == "every" && job.Schedule.EveryMS != nil {
+ schedule = fmt.Sprintf("every %ds", *job.Schedule.EveryMS/1000)
+ } else if job.Schedule.Kind == "cron" {
+ schedule = job.Schedule.Expr
+ } else {
+ schedule = "one-time"
+ }
+
+ nextRun := "scheduled"
+ if job.State.NextRunAtMS != nil {
+ nextTime := time.UnixMilli(*job.State.NextRunAtMS)
+ nextRun = nextTime.Format("2006-01-02 15:04")
+ }
+
+ status := "enabled"
+ if !job.Enabled {
+ status = "disabled"
+ }
+
+ fmt.Printf(" %s (%s)\n", job.Name, job.ID)
+ fmt.Printf(" Schedule: %s\n", schedule)
+ fmt.Printf(" Status: %s\n", status)
+ fmt.Printf(" Next run: %s\n", nextRun)
+ }
+}
+
+func cronAddCmd(storePath string) {
+ name := ""
+ message := ""
+ var everySec *int64
+ cronExpr := ""
+ deliver := false
+ channel := ""
+ to := ""
+
+ args := os.Args[3:]
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "-n", "--name":
+ if i+1 < len(args) {
+ name = args[i+1]
+ i++
+ }
+ case "-m", "--message":
+ if i+1 < len(args) {
+ message = args[i+1]
+ i++
+ }
+ case "-e", "--every":
+ if i+1 < len(args) {
+ var sec int64
+ fmt.Sscanf(args[i+1], "%d", &sec)
+ everySec = &sec
+ i++
+ }
+ case "-c", "--cron":
+ if i+1 < len(args) {
+ cronExpr = args[i+1]
+ i++
+ }
+ case "-d", "--deliver":
+ deliver = true
+ case "--to":
+ if i+1 < len(args) {
+ to = args[i+1]
+ i++
+ }
+ case "--channel":
+ if i+1 < len(args) {
+ channel = args[i+1]
+ i++
+ }
+ }
+ }
+
+ if name == "" {
+ fmt.Println("Error: --name is required")
+ return
+ }
+
+ if message == "" {
+ fmt.Println("Error: --message is required")
+ return
+ }
+
+ if everySec == nil && cronExpr == "" {
+ fmt.Println("Error: Either --every or --cron must be specified")
+ return
+ }
+
+ var schedule cron.CronSchedule
+ if everySec != nil {
+ everyMS := *everySec * 1000
+ schedule = cron.CronSchedule{
+ Kind: "every",
+ EveryMS: &everyMS,
+ }
+ } else {
+ schedule = cron.CronSchedule{
+ Kind: "cron",
+ Expr: cronExpr,
+ }
+ }
+
+ cs := cron.NewCronService(storePath, nil)
+ job, err := cs.AddJob(name, schedule, message, deliver, channel, to)
+ if err != nil {
+ fmt.Printf("Error adding job: %v\n", err)
+ return
+ }
+
+ fmt.Printf("✓ Added job '%s' (%s)\n", job.Name, job.ID)
+}
+
+func cronRemoveCmd(storePath, jobID string) {
+ cs := cron.NewCronService(storePath, nil)
+ if cs.RemoveJob(jobID) {
+ fmt.Printf("✓ Removed job %s\n", jobID)
+ } else {
+ fmt.Printf("✗ Job %s not found\n", jobID)
+ }
+}
+
+func cronEnableCmd(storePath string, disable bool) {
+ if len(os.Args) < 4 {
+ fmt.Println("Usage: picoclaw cron enable/disable ")
+ return
+ }
+
+ jobID := os.Args[3]
+ cs := cron.NewCronService(storePath, nil)
+ enabled := !disable
+
+ job := cs.EnableJob(jobID, enabled)
+ if job != nil {
+ status := "enabled"
+ if disable {
+ status = "disabled"
+ }
+ fmt.Printf("✓ Job '%s' %s\n", job.Name, status)
+ } else {
+ fmt.Printf("✗ Job %s not found\n", jobID)
+ }
+}
diff --git a/cmd/picoclaw/cmd_gateway.go b/cmd/picoclaw/cmd_gateway.go
new file mode 100644
index 000000000..1f1bf5491
--- /dev/null
+++ b/cmd/picoclaw/cmd_gateway.go
@@ -0,0 +1,223 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "time"
+
+ "github.com/sipeed/picoclaw/pkg/agent"
+ "github.com/sipeed/picoclaw/pkg/bus"
+ "github.com/sipeed/picoclaw/pkg/channels"
+ "github.com/sipeed/picoclaw/pkg/config"
+ "github.com/sipeed/picoclaw/pkg/cron"
+ "github.com/sipeed/picoclaw/pkg/devices"
+ "github.com/sipeed/picoclaw/pkg/health"
+ "github.com/sipeed/picoclaw/pkg/heartbeat"
+ "github.com/sipeed/picoclaw/pkg/logger"
+ "github.com/sipeed/picoclaw/pkg/providers"
+ "github.com/sipeed/picoclaw/pkg/state"
+ "github.com/sipeed/picoclaw/pkg/tools"
+ "github.com/sipeed/picoclaw/pkg/voice"
+)
+
+func gatewayCmd() {
+ // Check for --debug flag
+ args := os.Args[2:]
+ for _, arg := range args {
+ if arg == "--debug" || arg == "-d" {
+ logger.SetLevel(logger.DEBUG)
+ fmt.Println("🔍 Debug mode enabled")
+ break
+ }
+ }
+
+ cfg, err := loadConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ provider, modelID, err := providers.CreateProvider(cfg)
+ if err != nil {
+ fmt.Printf("Error creating provider: %v\n", err)
+ os.Exit(1)
+ }
+ // Use the resolved model ID from provider creation
+ if modelID != "" {
+ cfg.Agents.Defaults.Model = modelID
+ }
+
+ msgBus := bus.NewMessageBus()
+ agentLoop := agent.NewAgentLoop(cfg, msgBus, provider)
+
+ // Print agent startup info
+ fmt.Println("\n📦 Agent Status:")
+ startupInfo := agentLoop.GetStartupInfo()
+ toolsInfo := startupInfo["tools"].(map[string]interface{})
+ skillsInfo := startupInfo["skills"].(map[string]interface{})
+ fmt.Printf(" • Tools: %d loaded\n", toolsInfo["count"])
+ fmt.Printf(" • Skills: %d/%d available\n",
+ skillsInfo["available"],
+ skillsInfo["total"])
+
+ // Log to file as well
+ logger.InfoCF("agent", "Agent initialized",
+ map[string]interface{}{
+ "tools_count": toolsInfo["count"],
+ "skills_total": skillsInfo["total"],
+ "skills_available": skillsInfo["available"],
+ })
+
+ // Setup cron tool and service
+ execTimeout := time.Duration(cfg.Tools.Cron.ExecTimeoutMinutes) * time.Minute
+ cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath(), cfg.Agents.Defaults.RestrictToWorkspace, execTimeout, cfg)
+
+ heartbeatService := heartbeat.NewHeartbeatService(
+ cfg.WorkspacePath(),
+ cfg.Heartbeat.Interval,
+ cfg.Heartbeat.Enabled,
+ )
+ heartbeatService.SetBus(msgBus)
+ heartbeatService.SetHandler(func(prompt, channel, chatID string) *tools.ToolResult {
+ // Use cli:direct as fallback if no valid channel
+ if channel == "" || chatID == "" {
+ channel, chatID = "cli", "direct"
+ }
+ // Use ProcessHeartbeat - no session history, each heartbeat is independent
+ response, err := agentLoop.ProcessHeartbeat(context.Background(), prompt, channel, chatID)
+ if err != nil {
+ return tools.ErrorResult(fmt.Sprintf("Heartbeat error: %v", err))
+ }
+ if response == "HEARTBEAT_OK" {
+ return tools.SilentResult("Heartbeat OK")
+ }
+ // For heartbeat, always return silent - the subagent result will be
+ // sent to user via processSystemMessage when the async task completes
+ return tools.SilentResult(response)
+ })
+
+ channelManager, err := channels.NewManager(cfg, msgBus)
+ if err != nil {
+ fmt.Printf("Error creating channel manager: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Inject channel manager into agent loop for command handling
+ agentLoop.SetChannelManager(channelManager)
+
+ var transcriber *voice.GroqTranscriber
+ if cfg.Providers.Groq.APIKey != "" {
+ transcriber = voice.NewGroqTranscriber(cfg.Providers.Groq.APIKey)
+ logger.InfoC("voice", "Groq voice transcription enabled")
+ }
+
+ if transcriber != nil {
+ if telegramChannel, ok := channelManager.GetChannel("telegram"); ok {
+ if tc, ok := telegramChannel.(*channels.TelegramChannel); ok {
+ tc.SetTranscriber(transcriber)
+ logger.InfoC("voice", "Groq transcription attached to Telegram channel")
+ }
+ }
+ if discordChannel, ok := channelManager.GetChannel("discord"); ok {
+ if dc, ok := discordChannel.(*channels.DiscordChannel); ok {
+ dc.SetTranscriber(transcriber)
+ logger.InfoC("voice", "Groq transcription attached to Discord channel")
+ }
+ }
+ if slackChannel, ok := channelManager.GetChannel("slack"); ok {
+ if sc, ok := slackChannel.(*channels.SlackChannel); ok {
+ sc.SetTranscriber(transcriber)
+ logger.InfoC("voice", "Groq transcription attached to Slack channel")
+ }
+ }
+ }
+
+ enabledChannels := channelManager.GetEnabledChannels()
+ if len(enabledChannels) > 0 {
+ fmt.Printf("✓ Channels enabled: %s\n", enabledChannels)
+ } else {
+ fmt.Println("⚠ Warning: No channels enabled")
+ }
+
+ fmt.Printf("✓ Gateway started on %s:%d\n", cfg.Gateway.Host, cfg.Gateway.Port)
+ fmt.Println("Press Ctrl+C to stop")
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ if err := cronService.Start(); err != nil {
+ fmt.Printf("Error starting cron service: %v\n", err)
+ }
+ fmt.Println("✓ Cron service started")
+
+ if err := heartbeatService.Start(); err != nil {
+ fmt.Printf("Error starting heartbeat service: %v\n", err)
+ }
+ fmt.Println("✓ Heartbeat service started")
+
+ stateManager := state.NewManager(cfg.WorkspacePath())
+ deviceService := devices.NewService(devices.Config{
+ Enabled: cfg.Devices.Enabled,
+ MonitorUSB: cfg.Devices.MonitorUSB,
+ }, stateManager)
+ deviceService.SetBus(msgBus)
+ if err := deviceService.Start(ctx); err != nil {
+ fmt.Printf("Error starting device service: %v\n", err)
+ } else if cfg.Devices.Enabled {
+ fmt.Println("✓ Device event service started")
+ }
+
+ if err := channelManager.StartAll(ctx); err != nil {
+ fmt.Printf("Error starting channels: %v\n", err)
+ }
+
+ healthServer := health.NewServer(cfg.Gateway.Host, cfg.Gateway.Port)
+ go func() {
+ if err := healthServer.Start(); err != nil && err != http.ErrServerClosed {
+ logger.ErrorCF("health", "Health server error", map[string]interface{}{"error": err.Error()})
+ }
+ }()
+ fmt.Printf("✓ Health endpoints available at http://%s:%d/health and /ready\n", cfg.Gateway.Host, cfg.Gateway.Port)
+
+ go agentLoop.Run(ctx)
+
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, os.Interrupt)
+ <-sigChan
+
+ fmt.Println("\nShutting down...")
+ cancel()
+ healthServer.Stop(context.Background())
+ deviceService.Stop()
+ heartbeatService.Stop()
+ cronService.Stop()
+ agentLoop.Stop()
+ channelManager.StopAll(ctx)
+ fmt.Println("✓ Gateway stopped")
+}
+
+func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string, restrict bool, execTimeout time.Duration, cfg *config.Config) *cron.CronService {
+ cronStorePath := filepath.Join(workspace, "cron", "jobs.json")
+
+ // Create cron service
+ cronService := cron.NewCronService(cronStorePath, nil)
+
+ // Create and register CronTool
+ cronTool := tools.NewCronTool(cronService, agentLoop, msgBus, workspace, restrict, execTimeout, cfg)
+ agentLoop.RegisterTool(cronTool)
+
+ // Set the onJob handler
+ cronService.SetOnJob(func(job *cron.CronJob) (string, error) {
+ result := cronTool.ExecuteJob(context.Background(), job)
+ return result, nil
+ })
+
+ return cronService
+}
diff --git a/cmd/picoclaw/cmd_migrate.go b/cmd/picoclaw/cmd_migrate.go
new file mode 100644
index 000000000..86d4903ef
--- /dev/null
+++ b/cmd/picoclaw/cmd_migrate.go
@@ -0,0 +1,81 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/sipeed/picoclaw/pkg/migrate"
+)
+
+func migrateCmd() {
+ if len(os.Args) > 2 && (os.Args[2] == "--help" || os.Args[2] == "-h") {
+ migrateHelp()
+ return
+ }
+
+ opts := migrate.Options{}
+
+ args := os.Args[2:]
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--dry-run":
+ opts.DryRun = true
+ case "--config-only":
+ opts.ConfigOnly = true
+ case "--workspace-only":
+ opts.WorkspaceOnly = true
+ case "--force":
+ opts.Force = true
+ case "--refresh":
+ opts.Refresh = true
+ case "--openclaw-home":
+ if i+1 < len(args) {
+ opts.OpenClawHome = args[i+1]
+ i++
+ }
+ case "--picoclaw-home":
+ if i+1 < len(args) {
+ opts.PicoClawHome = args[i+1]
+ i++
+ }
+ default:
+ fmt.Printf("Unknown flag: %s\n", args[i])
+ migrateHelp()
+ os.Exit(1)
+ }
+ }
+
+ result, err := migrate.Run(opts)
+ if err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ if !opts.DryRun {
+ migrate.PrintSummary(result)
+ }
+}
+
+func migrateHelp() {
+ fmt.Println("\nMigrate from OpenClaw to PicoClaw")
+ fmt.Println()
+ fmt.Println("Usage: picoclaw migrate [options]")
+ fmt.Println()
+ fmt.Println("Options:")
+ fmt.Println(" --dry-run Show what would be migrated without making changes")
+ fmt.Println(" --refresh Re-sync workspace files from OpenClaw (repeatable)")
+ fmt.Println(" --config-only Only migrate config, skip workspace files")
+ fmt.Println(" --workspace-only Only migrate workspace files, skip config")
+ fmt.Println(" --force Skip confirmation prompts")
+ fmt.Println(" --openclaw-home Override OpenClaw home directory (default: ~/.openclaw)")
+ fmt.Println(" --picoclaw-home Override PicoClaw home directory (default: ~/.picoclaw)")
+ fmt.Println()
+ fmt.Println("Examples:")
+ fmt.Println(" picoclaw migrate Detect and migrate from OpenClaw")
+ fmt.Println(" picoclaw migrate --dry-run Show what would be migrated")
+ fmt.Println(" picoclaw migrate --refresh Re-sync workspace files")
+ fmt.Println(" picoclaw migrate --force Migrate without confirmation")
+}
diff --git a/cmd/picoclaw/cmd_onboard.go b/cmd/picoclaw/cmd_onboard.go
new file mode 100644
index 000000000..6e61e3267
--- /dev/null
+++ b/cmd/picoclaw/cmd_onboard.go
@@ -0,0 +1,108 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "embed"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+
+ "github.com/sipeed/picoclaw/pkg/config"
+)
+
+//go:generate cp -r ../../workspace .
+//go:embed workspace
+var embeddedFiles embed.FS
+
+func onboard() {
+ configPath := getConfigPath()
+
+ if _, err := os.Stat(configPath); err == nil {
+ fmt.Printf("Config already exists at %s\n", configPath)
+ fmt.Print("Overwrite? (y/n): ")
+ var response string
+ fmt.Scanln(&response)
+ if response != "y" {
+ fmt.Println("Aborted.")
+ return
+ }
+ }
+
+ cfg := config.DefaultConfig()
+ if err := config.SaveConfig(configPath, cfg); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
+
+ workspace := cfg.WorkspacePath()
+ createWorkspaceTemplates(workspace)
+
+ fmt.Printf("%s picoclaw is ready!\n", logo)
+ fmt.Println("\nNext steps:")
+ fmt.Println(" 1. Add your API key to", configPath)
+ fmt.Println("")
+ fmt.Println(" Recommended:")
+ fmt.Println(" - OpenRouter: https://openrouter.ai/keys (access 100+ models)")
+ fmt.Println(" - Ollama: https://ollama.com (local, free)")
+ fmt.Println("")
+ fmt.Println(" See README.md for 17+ supported providers.")
+ fmt.Println("")
+ fmt.Println(" 2. Chat: picoclaw agent -m \"Hello!\"")
+}
+
+func copyEmbeddedToTarget(targetDir string) error {
+ // Ensure target directory exists
+ if err := os.MkdirAll(targetDir, 0755); err != nil {
+ return fmt.Errorf("Failed to create target directory: %w", err)
+ }
+
+ // Walk through all files in embed.FS
+ err := fs.WalkDir(embeddedFiles, "workspace", func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+
+ // Skip directories
+ if d.IsDir() {
+ return nil
+ }
+
+ // Read embedded file
+ data, err := embeddedFiles.ReadFile(path)
+ if err != nil {
+ return fmt.Errorf("Failed to read embedded file %s: %w", path, err)
+ }
+
+ new_path, err := filepath.Rel("workspace", path)
+ if err != nil {
+ return fmt.Errorf("Failed to get relative path for %s: %v\n", path, err)
+ }
+
+ // Build target file path
+ targetPath := filepath.Join(targetDir, new_path)
+
+ // Ensure target file's directory exists
+ if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
+ return fmt.Errorf("Failed to create directory %s: %w", filepath.Dir(targetPath), err)
+ }
+
+ // Write file
+ if err := os.WriteFile(targetPath, data, 0644); err != nil {
+ return fmt.Errorf("Failed to write file %s: %w", targetPath, err)
+ }
+
+ return nil
+ })
+
+ return err
+}
+
+func createWorkspaceTemplates(workspace string) {
+ err := copyEmbeddedToTarget(workspace)
+ if err != nil {
+ fmt.Printf("Error copying workspace templates: %v\n", err)
+ }
+}
diff --git a/cmd/picoclaw/cmd_skills.go b/cmd/picoclaw/cmd_skills.go
new file mode 100644
index 000000000..32b7c62b8
--- /dev/null
+++ b/cmd/picoclaw/cmd_skills.go
@@ -0,0 +1,305 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/sipeed/picoclaw/pkg/config"
+ "github.com/sipeed/picoclaw/pkg/skills"
+ "github.com/sipeed/picoclaw/pkg/utils"
+)
+
+func skillsHelp() {
+ fmt.Println("\nSkills commands:")
+ fmt.Println(" list List installed skills")
+ fmt.Println(" install Install skill from GitHub")
+ fmt.Println(" install-builtin Install all builtin skills to workspace")
+ fmt.Println(" list-builtin List available builtin skills")
+ fmt.Println(" remove Remove installed skill")
+ fmt.Println(" search Search available skills")
+ fmt.Println(" show Show skill details")
+ fmt.Println()
+ fmt.Println("Examples:")
+ fmt.Println(" picoclaw skills list")
+ fmt.Println(" picoclaw skills install sipeed/picoclaw-skills/weather")
+ fmt.Println(" picoclaw skills install-builtin")
+ fmt.Println(" picoclaw skills list-builtin")
+ fmt.Println(" picoclaw skills remove weather")
+ fmt.Println(" picoclaw skills install --registry clawhub github")
+}
+
+func skillsListCmd(loader *skills.SkillsLoader) {
+ allSkills := loader.ListSkills()
+
+ if len(allSkills) == 0 {
+ fmt.Println("No skills installed.")
+ return
+ }
+
+ fmt.Println("\nInstalled Skills:")
+ fmt.Println("------------------")
+ for _, skill := range allSkills {
+ fmt.Printf(" ✓ %s (%s)\n", skill.Name, skill.Source)
+ if skill.Description != "" {
+ fmt.Printf(" %s\n", skill.Description)
+ }
+ }
+}
+
+func skillsInstallCmd(installer *skills.SkillInstaller, cfg *config.Config) {
+ if len(os.Args) < 4 {
+ fmt.Println("Usage: picoclaw skills install ")
+ fmt.Println(" picoclaw skills install --registry ")
+ return
+ }
+
+ // Check for --registry flag.
+ if os.Args[3] == "--registry" {
+ if len(os.Args) < 6 {
+ fmt.Println("Usage: picoclaw skills install --registry ")
+ fmt.Println("Example: picoclaw skills install --registry clawhub github")
+ return
+ }
+ registryName := os.Args[4]
+ slug := os.Args[5]
+ skillsInstallFromRegistry(cfg, registryName, slug)
+ return
+ }
+
+ // Default: install from GitHub (backward compatible).
+ repo := os.Args[3]
+ fmt.Printf("Installing skill from %s...\n", repo)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ if err := installer.InstallFromGitHub(ctx, repo); err != nil {
+ fmt.Printf("\u2717 Failed to install skill: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("\u2713 Skill '%s' installed successfully!\n", filepath.Base(repo))
+}
+
+// skillsInstallFromRegistry installs a skill from a named registry (e.g. clawhub).
+func skillsInstallFromRegistry(cfg *config.Config, registryName, slug string) {
+ err := utils.ValidateSkillIdentifier(registryName)
+ if err != nil {
+ fmt.Printf("\u2717 Invalid registry name: %v\n", err)
+ os.Exit(1)
+ }
+
+ err = utils.ValidateSkillIdentifier(slug)
+ if err != nil {
+ fmt.Printf("\u2717 Invalid slug: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("Installing skill '%s' from %s registry...\n", slug, registryName)
+
+ registryMgr := skills.NewRegistryManagerFromConfig(skills.RegistryConfig{
+ MaxConcurrentSearches: cfg.Tools.Skills.MaxConcurrentSearches,
+ ClawHub: skills.ClawHubConfig(cfg.Tools.Skills.Registries.ClawHub),
+ })
+
+ registry := registryMgr.GetRegistry(registryName)
+ if registry == nil {
+ fmt.Printf("\u2717 Registry '%s' not found or not enabled. Check your config.json.\n", registryName)
+ os.Exit(1)
+ }
+
+ workspace := cfg.WorkspacePath()
+ targetDir := filepath.Join(workspace, "skills", slug)
+
+ if _, err := os.Stat(targetDir); err == nil {
+ fmt.Printf("\u2717 Skill '%s' already installed at %s\n", slug, targetDir)
+ os.Exit(1)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ if err := os.MkdirAll(filepath.Join(workspace, "skills"), 0755); err != nil {
+ fmt.Printf("\u2717 Failed to create skills directory: %v\n", err)
+ os.Exit(1)
+ }
+
+ result, err := registry.DownloadAndInstall(ctx, slug, "", targetDir)
+ if err != nil {
+ rmErr := os.RemoveAll(targetDir)
+ if rmErr != nil {
+ fmt.Printf("\u2717 Failed to remove partial install: %v\n", rmErr)
+ }
+ fmt.Printf("\u2717 Failed to install skill: %v\n", err)
+ os.Exit(1)
+ }
+
+ if result.IsMalwareBlocked {
+ rmErr := os.RemoveAll(targetDir)
+ if rmErr != nil {
+ fmt.Printf("\u2717 Failed to remove partial install: %v\n", rmErr)
+ }
+ fmt.Printf("\u2717 Skill '%s' is flagged as malicious and cannot be installed.\n", slug)
+ os.Exit(1)
+ }
+
+ if result.IsSuspicious {
+ fmt.Printf("\u26a0\ufe0f Warning: skill '%s' is flagged as suspicious.\n", slug)
+ }
+
+ fmt.Printf("\u2713 Skill '%s' v%s installed successfully!\n", slug, result.Version)
+ if result.Summary != "" {
+ fmt.Printf(" %s\n", result.Summary)
+ }
+}
+
+func skillsRemoveCmd(installer *skills.SkillInstaller, skillName string) {
+ fmt.Printf("Removing skill '%s'...\n", skillName)
+
+ if err := installer.Uninstall(skillName); err != nil {
+ fmt.Printf("✗ Failed to remove skill: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("✓ Skill '%s' removed successfully!\n", skillName)
+}
+
+func skillsInstallBuiltinCmd(workspace string) {
+ builtinSkillsDir := "./picoclaw/skills"
+ workspaceSkillsDir := filepath.Join(workspace, "skills")
+
+ fmt.Printf("Copying builtin skills to workspace...\n")
+
+ skillsToInstall := []string{
+ "weather",
+ "news",
+ "stock",
+ "calculator",
+ }
+
+ for _, skillName := range skillsToInstall {
+ builtinPath := filepath.Join(builtinSkillsDir, skillName)
+ workspacePath := filepath.Join(workspaceSkillsDir, skillName)
+
+ if _, err := os.Stat(builtinPath); err != nil {
+ fmt.Printf("⊘ Builtin skill '%s' not found: %v\n", skillName, err)
+ continue
+ }
+
+ if err := os.MkdirAll(workspacePath, 0755); err != nil {
+ fmt.Printf("✗ Failed to create directory for %s: %v\n", skillName, err)
+ continue
+ }
+
+ if err := copyDirectory(builtinPath, workspacePath); err != nil {
+ fmt.Printf("✗ Failed to copy %s: %v\n", skillName, err)
+ }
+ }
+
+ fmt.Println("\n✓ All builtin skills installed!")
+ fmt.Println("Now you can use them in your workspace.")
+}
+
+func skillsListBuiltinCmd() {
+ cfg, err := loadConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ return
+ }
+ builtinSkillsDir := filepath.Join(filepath.Dir(cfg.WorkspacePath()), "picoclaw", "skills")
+
+ fmt.Println("\nAvailable Builtin Skills:")
+ fmt.Println("-----------------------")
+
+ entries, err := os.ReadDir(builtinSkillsDir)
+ if err != nil {
+ fmt.Printf("Error reading builtin skills: %v\n", err)
+ return
+ }
+
+ if len(entries) == 0 {
+ fmt.Println("No builtin skills available.")
+ return
+ }
+
+ for _, entry := range entries {
+ if entry.IsDir() {
+ skillName := entry.Name()
+ skillFile := filepath.Join(builtinSkillsDir, skillName, "SKILL.md")
+
+ description := "No description"
+ if _, err := os.Stat(skillFile); err == nil {
+ data, err := os.ReadFile(skillFile)
+ if err == nil {
+ content := string(data)
+ if idx := strings.Index(content, "\n"); idx > 0 {
+ firstLine := content[:idx]
+ if strings.Contains(firstLine, "description:") {
+ descLine := strings.Index(content[idx:], "\n")
+ if descLine > 0 {
+ description = strings.TrimSpace(content[idx+descLine : idx+descLine])
+ }
+ }
+ }
+ }
+ }
+ status := "✓"
+ fmt.Printf(" %s %s\n", status, entry.Name())
+ if description != "" {
+ fmt.Printf(" %s\n", description)
+ }
+ }
+ }
+}
+
+func skillsSearchCmd(installer *skills.SkillInstaller) {
+ fmt.Println("Searching for available skills...")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ availableSkills, err := installer.ListAvailableSkills(ctx)
+ if err != nil {
+ fmt.Printf("✗ Failed to fetch skills list: %v\n", err)
+ return
+ }
+
+ if len(availableSkills) == 0 {
+ fmt.Println("No skills available.")
+ return
+ }
+
+ fmt.Printf("\nAvailable Skills (%d):\n", len(availableSkills))
+ fmt.Println("--------------------")
+ for _, skill := range availableSkills {
+ fmt.Printf(" 📦 %s\n", skill.Name)
+ fmt.Printf(" %s\n", skill.Description)
+ fmt.Printf(" Repo: %s\n", skill.Repository)
+ if skill.Author != "" {
+ fmt.Printf(" Author: %s\n", skill.Author)
+ }
+ if len(skill.Tags) > 0 {
+ fmt.Printf(" Tags: %v\n", skill.Tags)
+ }
+ fmt.Println()
+ }
+}
+
+func skillsShowCmd(loader *skills.SkillsLoader, skillName string) {
+ content, ok := loader.LoadSkill(skillName)
+ if !ok {
+ fmt.Printf("✗ Skill '%s' not found\n", skillName)
+ return
+ }
+
+ fmt.Printf("\n📦 Skill: %s\n", skillName)
+ fmt.Println("----------------------")
+ fmt.Println(content)
+}
diff --git a/cmd/picoclaw/cmd_status.go b/cmd/picoclaw/cmd_status.go
new file mode 100644
index 000000000..07296784e
--- /dev/null
+++ b/cmd/picoclaw/cmd_status.go
@@ -0,0 +1,102 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// License: MIT
+
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/sipeed/picoclaw/pkg/auth"
+)
+
+func statusCmd() {
+ cfg, err := loadConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ return
+ }
+
+ configPath := getConfigPath()
+
+ fmt.Printf("%s picoclaw Status\n", logo)
+ fmt.Printf("Version: %s\n", formatVersion())
+ build, _ := formatBuildInfo()
+ if build != "" {
+ fmt.Printf("Build: %s\n", build)
+ }
+ fmt.Println()
+
+ if _, err := os.Stat(configPath); err == nil {
+ fmt.Println("Config:", configPath, "✓")
+ } else {
+ fmt.Println("Config:", configPath, "✗")
+ }
+
+ workspace := cfg.WorkspacePath()
+ if _, err := os.Stat(workspace); err == nil {
+ fmt.Println("Workspace:", workspace, "✓")
+ } else {
+ fmt.Println("Workspace:", workspace, "✗")
+ }
+
+ if _, err := os.Stat(configPath); err == nil {
+ fmt.Printf("Model: %s\n", cfg.Agents.Defaults.Model)
+
+ hasOpenRouter := cfg.Providers.OpenRouter.APIKey != ""
+ hasAnthropic := cfg.Providers.Anthropic.APIKey != ""
+ hasOpenAI := cfg.Providers.OpenAI.APIKey != ""
+ hasGemini := cfg.Providers.Gemini.APIKey != ""
+ hasZhipu := cfg.Providers.Zhipu.APIKey != ""
+ hasQwen := cfg.Providers.Qwen.APIKey != ""
+ hasGroq := cfg.Providers.Groq.APIKey != ""
+ hasVLLM := cfg.Providers.VLLM.APIBase != ""
+ hasMoonshot := cfg.Providers.Moonshot.APIKey != ""
+ hasDeepSeek := cfg.Providers.DeepSeek.APIKey != ""
+ hasVolcEngine := cfg.Providers.VolcEngine.APIKey != ""
+ hasNvidia := cfg.Providers.Nvidia.APIKey != ""
+ hasOllama := cfg.Providers.Ollama.APIBase != ""
+
+ status := func(enabled bool) string {
+ if enabled {
+ return "✓"
+ }
+ return "not set"
+ }
+ fmt.Println("OpenRouter API:", status(hasOpenRouter))
+ fmt.Println("Anthropic API:", status(hasAnthropic))
+ fmt.Println("OpenAI API:", status(hasOpenAI))
+ fmt.Println("Gemini API:", status(hasGemini))
+ fmt.Println("Zhipu API:", status(hasZhipu))
+ fmt.Println("Qwen API:", status(hasQwen))
+ fmt.Println("Groq API:", status(hasGroq))
+ fmt.Println("Moonshot API:", status(hasMoonshot))
+ fmt.Println("DeepSeek API:", status(hasDeepSeek))
+ fmt.Println("VolcEngine API:", status(hasVolcEngine))
+ fmt.Println("Nvidia API:", status(hasNvidia))
+ if hasVLLM {
+ fmt.Printf("vLLM/Local: ✓ %s\n", cfg.Providers.VLLM.APIBase)
+ } else {
+ fmt.Println("vLLM/Local: not set")
+ }
+ if hasOllama {
+ fmt.Printf("Ollama: ✓ %s\n", cfg.Providers.Ollama.APIBase)
+ } else {
+ fmt.Println("Ollama: not set")
+ }
+
+ store, _ := auth.LoadStore()
+ if store != nil && len(store.Credentials) > 0 {
+ fmt.Println("\nOAuth/Token Auth:")
+ for provider, cred := range store.Credentials {
+ status := "authenticated"
+ if cred.IsExpired() {
+ status = "expired"
+ } else if cred.NeedsRefresh() {
+ status = "needs refresh"
+ }
+ fmt.Printf(" %s (%s): %s\n", provider, cred.AuthMethod, status)
+ }
+ }
+ }
+}
diff --git a/cmd/picoclaw/main.go b/cmd/picoclaw/main.go
index 128f8c421..1e4b393f8 100644
--- a/cmd/picoclaw/main.go
+++ b/cmd/picoclaw/main.go
@@ -7,43 +7,16 @@
package main
import (
- "bufio"
- "context"
- "embed"
"fmt"
"io"
- "io/fs"
- "net/http"
"os"
- "os/signal"
"path/filepath"
"runtime"
- "strings"
- "time"
- "github.com/chzyer/readline"
- "github.com/sipeed/picoclaw/pkg/agent"
- "github.com/sipeed/picoclaw/pkg/auth"
- "github.com/sipeed/picoclaw/pkg/bus"
- "github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/config"
- "github.com/sipeed/picoclaw/pkg/cron"
- "github.com/sipeed/picoclaw/pkg/devices"
- "github.com/sipeed/picoclaw/pkg/health"
- "github.com/sipeed/picoclaw/pkg/heartbeat"
- "github.com/sipeed/picoclaw/pkg/logger"
- "github.com/sipeed/picoclaw/pkg/migrate"
- "github.com/sipeed/picoclaw/pkg/providers"
"github.com/sipeed/picoclaw/pkg/skills"
- "github.com/sipeed/picoclaw/pkg/state"
- "github.com/sipeed/picoclaw/pkg/tools"
- "github.com/sipeed/picoclaw/pkg/voice"
)
-//go:generate cp -r ../../workspace .
-//go:embed workspace
-var embeddedFiles embed.FS
-
var (
version = "dev"
gitCommit string
@@ -168,7 +141,7 @@ func main() {
case "list":
skillsListCmd(skillsLoader)
case "install":
- skillsInstallCmd(installer)
+ skillsInstallCmd(installer, cfg)
case "remove", "uninstall":
if len(os.Args) < 4 {
fmt.Println("Usage: picoclaw skills remove ")
@@ -216,1212 +189,11 @@ func printHelp() {
fmt.Println(" version Show version information")
}
-func onboard() {
- configPath := getConfigPath()
-
- if _, err := os.Stat(configPath); err == nil {
- fmt.Printf("Config already exists at %s\n", configPath)
- fmt.Print("Overwrite? (y/n): ")
- var response string
- fmt.Scanln(&response)
- if response != "y" {
- fmt.Println("Aborted.")
- return
- }
- }
-
- cfg := config.DefaultConfig()
- if err := config.SaveConfig(configPath, cfg); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
- }
-
- workspace := cfg.WorkspacePath()
- createWorkspaceTemplates(workspace)
-
- fmt.Printf("%s picoclaw is ready!\n", logo)
- fmt.Println("\nNext steps:")
- fmt.Println(" 1. Add your API key to", configPath)
- fmt.Println(" Get one at: https://openrouter.ai/keys")
- fmt.Println(" 2. Chat: picoclaw agent -m \"Hello!\"")
-}
-
-func copyEmbeddedToTarget(targetDir string) error {
- // Ensure target directory exists
- if err := os.MkdirAll(targetDir, 0755); err != nil {
- return fmt.Errorf("Failed to create target directory: %w", err)
- }
-
- // Walk through all files in embed.FS
- err := fs.WalkDir(embeddedFiles, "workspace", func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
-
- // Skip directories
- if d.IsDir() {
- return nil
- }
-
- // Read embedded file
- data, err := embeddedFiles.ReadFile(path)
- if err != nil {
- return fmt.Errorf("Failed to read embedded file %s: %w", path, err)
- }
-
- new_path, err := filepath.Rel("workspace", path)
- if err != nil {
- return fmt.Errorf("Failed to get relative path for %s: %v\n", path, err)
- }
-
- // Build target file path
- targetPath := filepath.Join(targetDir, new_path)
-
- // Ensure target file's directory exists
- if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
- return fmt.Errorf("Failed to create directory %s: %w", filepath.Dir(targetPath), err)
- }
-
- // Write file
- if err := os.WriteFile(targetPath, data, 0644); err != nil {
- return fmt.Errorf("Failed to write file %s: %w", targetPath, err)
- }
-
- return nil
- })
-
- return err
-}
-
-func createWorkspaceTemplates(workspace string) {
- err := copyEmbeddedToTarget(workspace)
- if err != nil {
- fmt.Printf("Error copying workspace templates: %v\n", err)
- }
-}
-
-func migrateCmd() {
- if len(os.Args) > 2 && (os.Args[2] == "--help" || os.Args[2] == "-h") {
- migrateHelp()
- return
- }
-
- opts := migrate.Options{}
-
- args := os.Args[2:]
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--dry-run":
- opts.DryRun = true
- case "--config-only":
- opts.ConfigOnly = true
- case "--workspace-only":
- opts.WorkspaceOnly = true
- case "--force":
- opts.Force = true
- case "--refresh":
- opts.Refresh = true
- case "--openclaw-home":
- if i+1 < len(args) {
- opts.OpenClawHome = args[i+1]
- i++
- }
- case "--picoclaw-home":
- if i+1 < len(args) {
- opts.PicoClawHome = args[i+1]
- i++
- }
- default:
- fmt.Printf("Unknown flag: %s\n", args[i])
- migrateHelp()
- os.Exit(1)
- }
- }
-
- result, err := migrate.Run(opts)
- if err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
-
- if !opts.DryRun {
- migrate.PrintSummary(result)
- }
-}
-
-func migrateHelp() {
- fmt.Println("\nMigrate from OpenClaw to PicoClaw")
- fmt.Println()
- fmt.Println("Usage: picoclaw migrate [options]")
- fmt.Println()
- fmt.Println("Options:")
- fmt.Println(" --dry-run Show what would be migrated without making changes")
- fmt.Println(" --refresh Re-sync workspace files from OpenClaw (repeatable)")
- fmt.Println(" --config-only Only migrate config, skip workspace files")
- fmt.Println(" --workspace-only Only migrate workspace files, skip config")
- fmt.Println(" --force Skip confirmation prompts")
- fmt.Println(" --openclaw-home Override OpenClaw home directory (default: ~/.openclaw)")
- fmt.Println(" --picoclaw-home Override PicoClaw home directory (default: ~/.picoclaw)")
- fmt.Println()
- fmt.Println("Examples:")
- fmt.Println(" picoclaw migrate Detect and migrate from OpenClaw")
- fmt.Println(" picoclaw migrate --dry-run Show what would be migrated")
- fmt.Println(" picoclaw migrate --refresh Re-sync workspace files")
- fmt.Println(" picoclaw migrate --force Migrate without confirmation")
-}
-
-func agentCmd() {
- message := ""
- sessionKey := "cli:default"
-
- args := os.Args[2:]
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--debug", "-d":
- logger.SetLevel(logger.DEBUG)
- fmt.Println("🔍 Debug mode enabled")
- case "-m", "--message":
- if i+1 < len(args) {
- message = args[i+1]
- i++
- }
- case "-s", "--session":
- if i+1 < len(args) {
- sessionKey = args[i+1]
- i++
- }
- }
- }
-
- cfg, err := loadConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- provider, err := providers.CreateProvider(cfg)
- if err != nil {
- fmt.Printf("Error creating provider: %v\n", err)
- os.Exit(1)
- }
-
- msgBus := bus.NewMessageBus()
- agentLoop := agent.NewAgentLoop(cfg, msgBus, provider)
-
- // Print agent startup info (only for interactive mode)
- startupInfo := agentLoop.GetStartupInfo()
- logger.InfoCF("agent", "Agent initialized",
- map[string]interface{}{
- "tools_count": startupInfo["tools"].(map[string]interface{})["count"],
- "skills_total": startupInfo["skills"].(map[string]interface{})["total"],
- "skills_available": startupInfo["skills"].(map[string]interface{})["available"],
- })
-
- if message != "" {
- ctx := context.Background()
- response, err := agentLoop.ProcessDirect(ctx, message, sessionKey)
- if err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
- fmt.Printf("\n%s %s\n", logo, response)
- } else {
- fmt.Printf("%s Interactive mode (Ctrl+C to exit)\n\n", logo)
- interactiveMode(agentLoop, sessionKey)
- }
-}
-
-func interactiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
- prompt := fmt.Sprintf("%s You: ", logo)
-
- rl, err := readline.NewEx(&readline.Config{
- Prompt: prompt,
- HistoryFile: filepath.Join(os.TempDir(), ".picoclaw_history"),
- HistoryLimit: 100,
- InterruptPrompt: "^C",
- EOFPrompt: "exit",
- })
-
- if err != nil {
- fmt.Printf("Error initializing readline: %v\n", err)
- fmt.Println("Falling back to simple input mode...")
- simpleInteractiveMode(agentLoop, sessionKey)
- return
- }
- defer rl.Close()
-
- for {
- line, err := rl.Readline()
- if err != nil {
- if err == readline.ErrInterrupt || err == io.EOF {
- fmt.Println("\nGoodbye!")
- return
- }
- fmt.Printf("Error reading input: %v\n", err)
- continue
- }
-
- input := strings.TrimSpace(line)
- if input == "" {
- continue
- }
-
- if input == "exit" || input == "quit" {
- fmt.Println("Goodbye!")
- return
- }
-
- ctx := context.Background()
- response, err := agentLoop.ProcessDirect(ctx, input, sessionKey)
- if err != nil {
- fmt.Printf("Error: %v\n", err)
- continue
- }
-
- fmt.Printf("\n%s %s\n\n", logo, response)
- }
-}
-
-func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
- reader := bufio.NewReader(os.Stdin)
- for {
- fmt.Print(fmt.Sprintf("%s You: ", logo))
- line, err := reader.ReadString('\n')
- if err != nil {
- if err == io.EOF {
- fmt.Println("\nGoodbye!")
- return
- }
- fmt.Printf("Error reading input: %v\n", err)
- continue
- }
-
- input := strings.TrimSpace(line)
- if input == "" {
- continue
- }
-
- if input == "exit" || input == "quit" {
- fmt.Println("Goodbye!")
- return
- }
-
- ctx := context.Background()
- response, err := agentLoop.ProcessDirect(ctx, input, sessionKey)
- if err != nil {
- fmt.Printf("Error: %v\n", err)
- continue
- }
-
- fmt.Printf("\n%s %s\n\n", logo, response)
- }
-}
-
-func gatewayCmd() {
- // Check for --debug flag
- args := os.Args[2:]
- for _, arg := range args {
- if arg == "--debug" || arg == "-d" {
- logger.SetLevel(logger.DEBUG)
- fmt.Println("🔍 Debug mode enabled")
- break
- }
- }
-
- cfg, err := loadConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- provider, err := providers.CreateProvider(cfg)
- if err != nil {
- fmt.Printf("Error creating provider: %v\n", err)
- os.Exit(1)
- }
-
- msgBus := bus.NewMessageBus()
- agentLoop := agent.NewAgentLoop(cfg, msgBus, provider)
-
- // Print agent startup info
- fmt.Println("\n📦 Agent Status:")
- startupInfo := agentLoop.GetStartupInfo()
- toolsInfo := startupInfo["tools"].(map[string]interface{})
- skillsInfo := startupInfo["skills"].(map[string]interface{})
- fmt.Printf(" • Tools: %d loaded\n", toolsInfo["count"])
- fmt.Printf(" • Skills: %d/%d available\n",
- skillsInfo["available"],
- skillsInfo["total"])
-
- // Log to file as well
- logger.InfoCF("agent", "Agent initialized",
- map[string]interface{}{
- "tools_count": toolsInfo["count"],
- "skills_total": skillsInfo["total"],
- "skills_available": skillsInfo["available"],
- })
-
- // Setup cron tool and service
- execTimeout := time.Duration(cfg.Tools.Cron.ExecTimeoutMinutes) * time.Minute
- cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath(), cfg.Agents.Defaults.RestrictToWorkspace, execTimeout, cfg)
-
- heartbeatService := heartbeat.NewHeartbeatService(
- cfg.WorkspacePath(),
- cfg.Heartbeat.Interval,
- cfg.Heartbeat.Enabled,
- )
- heartbeatService.SetBus(msgBus)
- heartbeatService.SetHandler(func(prompt, channel, chatID string) *tools.ToolResult {
- // Use cli:direct as fallback if no valid channel
- if channel == "" || chatID == "" {
- channel, chatID = "cli", "direct"
- }
- // Use ProcessHeartbeat - no session history, each heartbeat is independent
- response, err := agentLoop.ProcessHeartbeat(context.Background(), prompt, channel, chatID)
- if err != nil {
- return tools.ErrorResult(fmt.Sprintf("Heartbeat error: %v", err))
- }
- if response == "HEARTBEAT_OK" {
- return tools.SilentResult("Heartbeat OK")
- }
- // For heartbeat, always return silent - the subagent result will be
- // sent to user via processSystemMessage when the async task completes
- return tools.SilentResult(response)
- })
-
- channelManager, err := channels.NewManager(cfg, msgBus)
- if err != nil {
- fmt.Printf("Error creating channel manager: %v\n", err)
- os.Exit(1)
- }
-
- // Inject channel manager into agent loop for command handling
- agentLoop.SetChannelManager(channelManager)
-
- var transcriber *voice.GroqTranscriber
- if cfg.Providers.Groq.APIKey != "" {
- transcriber = voice.NewGroqTranscriber(cfg.Providers.Groq.APIKey)
- logger.InfoC("voice", "Groq voice transcription enabled")
- }
-
- if transcriber != nil {
- if telegramChannel, ok := channelManager.GetChannel("telegram"); ok {
- if tc, ok := telegramChannel.(*channels.TelegramChannel); ok {
- tc.SetTranscriber(transcriber)
- logger.InfoC("voice", "Groq transcription attached to Telegram channel")
- }
- }
- if discordChannel, ok := channelManager.GetChannel("discord"); ok {
- if dc, ok := discordChannel.(*channels.DiscordChannel); ok {
- dc.SetTranscriber(transcriber)
- logger.InfoC("voice", "Groq transcription attached to Discord channel")
- }
- }
- if slackChannel, ok := channelManager.GetChannel("slack"); ok {
- if sc, ok := slackChannel.(*channels.SlackChannel); ok {
- sc.SetTranscriber(transcriber)
- logger.InfoC("voice", "Groq transcription attached to Slack channel")
- }
- }
- }
-
- enabledChannels := channelManager.GetEnabledChannels()
- if len(enabledChannels) > 0 {
- fmt.Printf("✓ Channels enabled: %s\n", enabledChannels)
- } else {
- fmt.Println("⚠ Warning: No channels enabled")
- }
-
- fmt.Printf("✓ Gateway started on %s:%d\n", cfg.Gateway.Host, cfg.Gateway.Port)
- fmt.Println("Press Ctrl+C to stop")
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
-
- if err := cronService.Start(); err != nil {
- fmt.Printf("Error starting cron service: %v\n", err)
- }
- fmt.Println("✓ Cron service started")
-
- if err := heartbeatService.Start(); err != nil {
- fmt.Printf("Error starting heartbeat service: %v\n", err)
- }
- fmt.Println("✓ Heartbeat service started")
-
- stateManager := state.NewManager(cfg.WorkspacePath())
- deviceService := devices.NewService(devices.Config{
- Enabled: cfg.Devices.Enabled,
- MonitorUSB: cfg.Devices.MonitorUSB,
- }, stateManager)
- deviceService.SetBus(msgBus)
- if err := deviceService.Start(ctx); err != nil {
- fmt.Printf("Error starting device service: %v\n", err)
- } else if cfg.Devices.Enabled {
- fmt.Println("✓ Device event service started")
- }
-
- if err := channelManager.StartAll(ctx); err != nil {
- fmt.Printf("Error starting channels: %v\n", err)
- }
-
- healthServer := health.NewServer(cfg.Gateway.Host, cfg.Gateway.Port)
- go func() {
- if err := healthServer.Start(); err != nil && err != http.ErrServerClosed {
- logger.ErrorCF("health", "Health server error", map[string]interface{}{"error": err.Error()})
- }
- }()
- fmt.Printf("✓ Health endpoints available at http://%s:%d/health and /ready\n", cfg.Gateway.Host, cfg.Gateway.Port)
-
- go agentLoop.Run(ctx)
-
- sigChan := make(chan os.Signal, 1)
- signal.Notify(sigChan, os.Interrupt)
- <-sigChan
-
- fmt.Println("\nShutting down...")
- cancel()
- healthServer.Stop(context.Background())
- deviceService.Stop()
- heartbeatService.Stop()
- cronService.Stop()
- agentLoop.Stop()
- channelManager.StopAll(ctx)
- fmt.Println("✓ Gateway stopped")
-}
-
-func statusCmd() {
- cfg, err := loadConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- return
- }
-
- configPath := getConfigPath()
-
- fmt.Printf("%s picoclaw Status\n", logo)
- fmt.Printf("Version: %s\n", formatVersion())
- build, _ := formatBuildInfo()
- if build != "" {
- fmt.Printf("Build: %s\n", build)
- }
- fmt.Println()
-
- if _, err := os.Stat(configPath); err == nil {
- fmt.Println("Config:", configPath, "✓")
- } else {
- fmt.Println("Config:", configPath, "✗")
- }
-
- workspace := cfg.WorkspacePath()
- if _, err := os.Stat(workspace); err == nil {
- fmt.Println("Workspace:", workspace, "✓")
- } else {
- fmt.Println("Workspace:", workspace, "✗")
- }
-
- if _, err := os.Stat(configPath); err == nil {
- fmt.Printf("Model: %s\n", cfg.Agents.Defaults.Model)
-
- hasOpenRouter := cfg.Providers.OpenRouter.APIKey != ""
- hasAnthropic := cfg.Providers.Anthropic.APIKey != ""
- hasOpenAI := cfg.Providers.OpenAI.APIKey != ""
- hasGemini := cfg.Providers.Gemini.APIKey != ""
- hasZhipu := cfg.Providers.Zhipu.APIKey != ""
- hasGroq := cfg.Providers.Groq.APIKey != ""
- hasVLLM := cfg.Providers.VLLM.APIBase != ""
-
- status := func(enabled bool) string {
- if enabled {
- return "✓"
- }
- return "not set"
- }
- fmt.Println("OpenRouter API:", status(hasOpenRouter))
- fmt.Println("Anthropic API:", status(hasAnthropic))
- fmt.Println("OpenAI API:", status(hasOpenAI))
- fmt.Println("Gemini API:", status(hasGemini))
- fmt.Println("Zhipu API:", status(hasZhipu))
- fmt.Println("Groq API:", status(hasGroq))
- if hasVLLM {
- fmt.Printf("vLLM/Local: ✓ %s\n", cfg.Providers.VLLM.APIBase)
- } else {
- fmt.Println("vLLM/Local: not set")
- }
-
- store, _ := auth.LoadStore()
- if store != nil && len(store.Credentials) > 0 {
- fmt.Println("\nOAuth/Token Auth:")
- for provider, cred := range store.Credentials {
- status := "authenticated"
- if cred.IsExpired() {
- status = "expired"
- } else if cred.NeedsRefresh() {
- status = "needs refresh"
- }
- fmt.Printf(" %s (%s): %s\n", provider, cred.AuthMethod, status)
- }
- }
- }
-}
-
-func authCmd() {
- if len(os.Args) < 3 {
- authHelp()
- return
- }
-
- switch os.Args[2] {
- case "login":
- authLoginCmd()
- case "logout":
- authLogoutCmd()
- case "status":
- authStatusCmd()
- default:
- fmt.Printf("Unknown auth command: %s\n", os.Args[2])
- authHelp()
- }
-}
-
-func authHelp() {
- fmt.Println("\nAuth commands:")
- fmt.Println(" login Login via OAuth or paste token")
- fmt.Println(" logout Remove stored credentials")
- fmt.Println(" status Show current auth status")
- fmt.Println()
- fmt.Println("Login options:")
- fmt.Println(" --provider Provider to login with (openai, anthropic)")
- fmt.Println(" --device-code Use device code flow (for headless environments)")
- fmt.Println()
- fmt.Println("Examples:")
- fmt.Println(" picoclaw auth login --provider openai")
- fmt.Println(" picoclaw auth login --provider openai --device-code")
- fmt.Println(" picoclaw auth login --provider anthropic")
- fmt.Println(" picoclaw auth logout --provider openai")
- fmt.Println(" picoclaw auth status")
-}
-
-func authLoginCmd() {
- provider := ""
- useDeviceCode := false
-
- args := os.Args[3:]
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--provider", "-p":
- if i+1 < len(args) {
- provider = args[i+1]
- i++
- }
- case "--device-code":
- useDeviceCode = true
- }
- }
-
- if provider == "" {
- fmt.Println("Error: --provider is required")
- fmt.Println("Supported providers: openai, anthropic")
- return
- }
-
- switch provider {
- case "openai":
- authLoginOpenAI(useDeviceCode)
- case "anthropic":
- authLoginPasteToken(provider)
- default:
- fmt.Printf("Unsupported provider: %s\n", provider)
- fmt.Println("Supported providers: openai, anthropic")
- }
-}
-
-func authLoginOpenAI(useDeviceCode bool) {
- cfg := auth.OpenAIOAuthConfig()
-
- var cred *auth.AuthCredential
- var err error
-
- if useDeviceCode {
- cred, err = auth.LoginDeviceCode(cfg)
- } else {
- cred, err = auth.LoginBrowser(cfg)
- }
-
- if err != nil {
- fmt.Printf("Login failed: %v\n", err)
- os.Exit(1)
- }
-
- if err := auth.SetCredential("openai", cred); err != nil {
- fmt.Printf("Failed to save credentials: %v\n", err)
- os.Exit(1)
- }
-
- appCfg, err := loadConfig()
- if err == nil {
- appCfg.Providers.OpenAI.AuthMethod = "oauth"
- if err := config.SaveConfig(getConfigPath(), appCfg); err != nil {
- fmt.Printf("Warning: could not update config: %v\n", err)
- }
- }
-
- fmt.Println("Login successful!")
- if cred.AccountID != "" {
- fmt.Printf("Account: %s\n", cred.AccountID)
- }
-}
-
-func authLoginPasteToken(provider string) {
- cred, err := auth.LoginPasteToken(provider, os.Stdin)
- if err != nil {
- fmt.Printf("Login failed: %v\n", err)
- os.Exit(1)
- }
-
- if err := auth.SetCredential(provider, cred); err != nil {
- fmt.Printf("Failed to save credentials: %v\n", err)
- os.Exit(1)
- }
-
- appCfg, err := loadConfig()
- if err == nil {
- switch provider {
- case "anthropic":
- appCfg.Providers.Anthropic.AuthMethod = "token"
- case "openai":
- appCfg.Providers.OpenAI.AuthMethod = "token"
- }
- if err := config.SaveConfig(getConfigPath(), appCfg); err != nil {
- fmt.Printf("Warning: could not update config: %v\n", err)
- }
- }
-
- fmt.Printf("Token saved for %s!\n", provider)
-}
-
-func authLogoutCmd() {
- provider := ""
-
- args := os.Args[3:]
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--provider", "-p":
- if i+1 < len(args) {
- provider = args[i+1]
- i++
- }
- }
- }
-
- if provider != "" {
- if err := auth.DeleteCredential(provider); err != nil {
- fmt.Printf("Failed to remove credentials: %v\n", err)
- os.Exit(1)
- }
-
- appCfg, err := loadConfig()
- if err == nil {
- switch provider {
- case "openai":
- appCfg.Providers.OpenAI.AuthMethod = ""
- case "anthropic":
- appCfg.Providers.Anthropic.AuthMethod = ""
- }
- config.SaveConfig(getConfigPath(), appCfg)
- }
-
- fmt.Printf("Logged out from %s\n", provider)
- } else {
- if err := auth.DeleteAllCredentials(); err != nil {
- fmt.Printf("Failed to remove credentials: %v\n", err)
- os.Exit(1)
- }
-
- appCfg, err := loadConfig()
- if err == nil {
- appCfg.Providers.OpenAI.AuthMethod = ""
- appCfg.Providers.Anthropic.AuthMethod = ""
- config.SaveConfig(getConfigPath(), appCfg)
- }
-
- fmt.Println("Logged out from all providers")
- }
-}
-
-func authStatusCmd() {
- store, err := auth.LoadStore()
- if err != nil {
- fmt.Printf("Error loading auth store: %v\n", err)
- return
- }
-
- if len(store.Credentials) == 0 {
- fmt.Println("No authenticated providers.")
- fmt.Println("Run: picoclaw auth login --provider ")
- return
- }
-
- fmt.Println("\nAuthenticated Providers:")
- fmt.Println("------------------------")
- for provider, cred := range store.Credentials {
- status := "active"
- if cred.IsExpired() {
- status = "expired"
- } else if cred.NeedsRefresh() {
- status = "needs refresh"
- }
-
- fmt.Printf(" %s:\n", provider)
- fmt.Printf(" Method: %s\n", cred.AuthMethod)
- fmt.Printf(" Status: %s\n", status)
- if cred.AccountID != "" {
- fmt.Printf(" Account: %s\n", cred.AccountID)
- }
- if !cred.ExpiresAt.IsZero() {
- fmt.Printf(" Expires: %s\n", cred.ExpiresAt.Format("2006-01-02 15:04"))
- }
- }
-}
-
func getConfigPath() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".picoclaw", "config.json")
}
-func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string, restrict bool, execTimeout time.Duration, config *config.Config) *cron.CronService {
- cronStorePath := filepath.Join(workspace, "cron", "jobs.json")
-
- // Create cron service
- cronService := cron.NewCronService(cronStorePath, nil)
-
- // Create and register CronTool
- cronTool := tools.NewCronTool(cronService, agentLoop, msgBus, workspace, restrict, execTimeout, config)
- agentLoop.RegisterTool(cronTool)
-
- // Set the onJob handler
- cronService.SetOnJob(func(job *cron.CronJob) (string, error) {
- result := cronTool.ExecuteJob(context.Background(), job)
- return result, nil
- })
-
- return cronService
-}
-
func loadConfig() (*config.Config, error) {
return config.LoadConfig(getConfigPath())
}
-
-func cronCmd() {
- if len(os.Args) < 3 {
- cronHelp()
- return
- }
-
- subcommand := os.Args[2]
-
- // Load config to get workspace path
- cfg, err := loadConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- return
- }
-
- cronStorePath := filepath.Join(cfg.WorkspacePath(), "cron", "jobs.json")
-
- switch subcommand {
- case "list":
- cronListCmd(cronStorePath)
- case "add":
- cronAddCmd(cronStorePath)
- case "remove":
- if len(os.Args) < 4 {
- fmt.Println("Usage: picoclaw cron remove ")
- return
- }
- cronRemoveCmd(cronStorePath, os.Args[3])
- case "enable":
- cronEnableCmd(cronStorePath, false)
- case "disable":
- cronEnableCmd(cronStorePath, true)
- default:
- fmt.Printf("Unknown cron command: %s\n", subcommand)
- cronHelp()
- }
-}
-
-func cronHelp() {
- fmt.Println("\nCron commands:")
- fmt.Println(" list List all scheduled jobs")
- fmt.Println(" add Add a new scheduled job")
- fmt.Println(" remove Remove a job by ID")
- fmt.Println(" enable Enable a job")
- fmt.Println(" disable Disable a job")
- fmt.Println()
- fmt.Println("Add options:")
- fmt.Println(" -n, --name Job name")
- fmt.Println(" -m, --message Message for agent")
- fmt.Println(" -e, --every Run every N seconds")
- fmt.Println(" -c, --cron Cron expression (e.g. '0 9 * * *')")
- fmt.Println(" -d, --deliver Deliver response to channel")
- fmt.Println(" --to Recipient for delivery")
- fmt.Println(" --channel Channel for delivery")
-}
-
-func cronListCmd(storePath string) {
- cs := cron.NewCronService(storePath, nil)
- jobs := cs.ListJobs(true) // Show all jobs, including disabled
-
- if len(jobs) == 0 {
- fmt.Println("No scheduled jobs.")
- return
- }
-
- fmt.Println("\nScheduled Jobs:")
- fmt.Println("----------------")
- for _, job := range jobs {
- var schedule string
- if job.Schedule.Kind == "every" && job.Schedule.EveryMS != nil {
- schedule = fmt.Sprintf("every %ds", *job.Schedule.EveryMS/1000)
- } else if job.Schedule.Kind == "cron" {
- schedule = job.Schedule.Expr
- } else {
- schedule = "one-time"
- }
-
- nextRun := "scheduled"
- if job.State.NextRunAtMS != nil {
- nextTime := time.UnixMilli(*job.State.NextRunAtMS)
- nextRun = nextTime.Format("2006-01-02 15:04")
- }
-
- status := "enabled"
- if !job.Enabled {
- status = "disabled"
- }
-
- fmt.Printf(" %s (%s)\n", job.Name, job.ID)
- fmt.Printf(" Schedule: %s\n", schedule)
- fmt.Printf(" Status: %s\n", status)
- fmt.Printf(" Next run: %s\n", nextRun)
- }
-}
-
-func cronAddCmd(storePath string) {
- name := ""
- message := ""
- var everySec *int64
- cronExpr := ""
- deliver := false
- channel := ""
- to := ""
-
- args := os.Args[3:]
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "-n", "--name":
- if i+1 < len(args) {
- name = args[i+1]
- i++
- }
- case "-m", "--message":
- if i+1 < len(args) {
- message = args[i+1]
- i++
- }
- case "-e", "--every":
- if i+1 < len(args) {
- var sec int64
- fmt.Sscanf(args[i+1], "%d", &sec)
- everySec = &sec
- i++
- }
- case "-c", "--cron":
- if i+1 < len(args) {
- cronExpr = args[i+1]
- i++
- }
- case "-d", "--deliver":
- deliver = true
- case "--to":
- if i+1 < len(args) {
- to = args[i+1]
- i++
- }
- case "--channel":
- if i+1 < len(args) {
- channel = args[i+1]
- i++
- }
- }
- }
-
- if name == "" {
- fmt.Println("Error: --name is required")
- return
- }
-
- if message == "" {
- fmt.Println("Error: --message is required")
- return
- }
-
- if everySec == nil && cronExpr == "" {
- fmt.Println("Error: Either --every or --cron must be specified")
- return
- }
-
- var schedule cron.CronSchedule
- if everySec != nil {
- everyMS := *everySec * 1000
- schedule = cron.CronSchedule{
- Kind: "every",
- EveryMS: &everyMS,
- }
- } else {
- schedule = cron.CronSchedule{
- Kind: "cron",
- Expr: cronExpr,
- }
- }
-
- cs := cron.NewCronService(storePath, nil)
- job, err := cs.AddJob(name, schedule, message, deliver, channel, to)
- if err != nil {
- fmt.Printf("Error adding job: %v\n", err)
- return
- }
-
- fmt.Printf("✓ Added job '%s' (%s)\n", job.Name, job.ID)
-}
-
-func cronRemoveCmd(storePath, jobID string) {
- cs := cron.NewCronService(storePath, nil)
- if cs.RemoveJob(jobID) {
- fmt.Printf("✓ Removed job %s\n", jobID)
- } else {
- fmt.Printf("✗ Job %s not found\n", jobID)
- }
-}
-
-func cronEnableCmd(storePath string, disable bool) {
- if len(os.Args) < 4 {
- fmt.Println("Usage: picoclaw cron enable/disable ")
- return
- }
-
- jobID := os.Args[3]
- cs := cron.NewCronService(storePath, nil)
- enabled := !disable
-
- job := cs.EnableJob(jobID, enabled)
- if job != nil {
- status := "enabled"
- if disable {
- status = "disabled"
- }
- fmt.Printf("✓ Job '%s' %s\n", job.Name, status)
- } else {
- fmt.Printf("✗ Job %s not found\n", jobID)
- }
-}
-
-func skillsHelp() {
- fmt.Println("\nSkills commands:")
- fmt.Println(" list List installed skills")
- fmt.Println(" install Install skill from GitHub")
- fmt.Println(" install-builtin Install all builtin skills to workspace")
- fmt.Println(" list-builtin List available builtin skills")
- fmt.Println(" remove Remove installed skill")
- fmt.Println(" search Search available skills")
- fmt.Println(" show Show skill details")
- fmt.Println()
- fmt.Println("Examples:")
- fmt.Println(" picoclaw skills list")
- fmt.Println(" picoclaw skills install sipeed/picoclaw-skills/weather")
- fmt.Println(" picoclaw skills install-builtin")
- fmt.Println(" picoclaw skills list-builtin")
- fmt.Println(" picoclaw skills remove weather")
-}
-
-func skillsListCmd(loader *skills.SkillsLoader) {
- allSkills := loader.ListSkills()
-
- if len(allSkills) == 0 {
- fmt.Println("No skills installed.")
- return
- }
-
- fmt.Println("\nInstalled Skills:")
- fmt.Println("------------------")
- for _, skill := range allSkills {
- fmt.Printf(" ✓ %s (%s)\n", skill.Name, skill.Source)
- if skill.Description != "" {
- fmt.Printf(" %s\n", skill.Description)
- }
- }
-}
-
-func skillsInstallCmd(installer *skills.SkillInstaller) {
- if len(os.Args) < 4 {
- fmt.Println("Usage: picoclaw skills install ")
- fmt.Println("Example: picoclaw skills install sipeed/picoclaw-skills/weather")
- return
- }
-
- repo := os.Args[3]
- fmt.Printf("Installing skill from %s...\n", repo)
-
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- if err := installer.InstallFromGitHub(ctx, repo); err != nil {
- fmt.Printf("✗ Failed to install skill: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Printf("✓ Skill '%s' installed successfully!\n", filepath.Base(repo))
-}
-
-func skillsRemoveCmd(installer *skills.SkillInstaller, skillName string) {
- fmt.Printf("Removing skill '%s'...\n", skillName)
-
- if err := installer.Uninstall(skillName); err != nil {
- fmt.Printf("✗ Failed to remove skill: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Printf("✓ Skill '%s' removed successfully!\n", skillName)
-}
-
-func skillsInstallBuiltinCmd(workspace string) {
- builtinSkillsDir := "./picoclaw/skills"
- workspaceSkillsDir := filepath.Join(workspace, "skills")
-
- fmt.Printf("Copying builtin skills to workspace...\n")
-
- skillsToInstall := []string{
- "weather",
- "news",
- "stock",
- "calculator",
- }
-
- for _, skillName := range skillsToInstall {
- builtinPath := filepath.Join(builtinSkillsDir, skillName)
- workspacePath := filepath.Join(workspaceSkillsDir, skillName)
-
- if _, err := os.Stat(builtinPath); err != nil {
- fmt.Printf("⊘ Builtin skill '%s' not found: %v\n", skillName, err)
- continue
- }
-
- if err := os.MkdirAll(workspacePath, 0755); err != nil {
- fmt.Printf("✗ Failed to create directory for %s: %v\n", skillName, err)
- continue
- }
-
- if err := copyDirectory(builtinPath, workspacePath); err != nil {
- fmt.Printf("✗ Failed to copy %s: %v\n", skillName, err)
- }
- }
-
- fmt.Println("\n✓ All builtin skills installed!")
- fmt.Println("Now you can use them in your workspace.")
-}
-
-func skillsListBuiltinCmd() {
- cfg, err := loadConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- return
- }
- builtinSkillsDir := filepath.Join(filepath.Dir(cfg.WorkspacePath()), "picoclaw", "skills")
-
- fmt.Println("\nAvailable Builtin Skills:")
- fmt.Println("-----------------------")
-
- entries, err := os.ReadDir(builtinSkillsDir)
- if err != nil {
- fmt.Printf("Error reading builtin skills: %v\n", err)
- return
- }
-
- if len(entries) == 0 {
- fmt.Println("No builtin skills available.")
- return
- }
-
- for _, entry := range entries {
- if entry.IsDir() {
- skillName := entry.Name()
- skillFile := filepath.Join(builtinSkillsDir, skillName, "SKILL.md")
-
- description := "No description"
- if _, err := os.Stat(skillFile); err == nil {
- data, err := os.ReadFile(skillFile)
- if err == nil {
- content := string(data)
- if idx := strings.Index(content, "\n"); idx > 0 {
- firstLine := content[:idx]
- if strings.Contains(firstLine, "description:") {
- descLine := strings.Index(content[idx:], "\n")
- if descLine > 0 {
- description = strings.TrimSpace(content[idx+descLine : idx+descLine])
- }
- }
- }
- }
- }
- status := "✓"
- fmt.Printf(" %s %s\n", status, entry.Name())
- if description != "" {
- fmt.Printf(" %s\n", description)
- }
- }
- }
-}
-
-func skillsSearchCmd(installer *skills.SkillInstaller) {
- fmt.Println("Searching for available skills...")
-
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- availableSkills, err := installer.ListAvailableSkills(ctx)
- if err != nil {
- fmt.Printf("✗ Failed to fetch skills list: %v\n", err)
- return
- }
-
- if len(availableSkills) == 0 {
- fmt.Println("No skills available.")
- return
- }
-
- fmt.Printf("\nAvailable Skills (%d):\n", len(availableSkills))
- fmt.Println("--------------------")
- for _, skill := range availableSkills {
- fmt.Printf(" 📦 %s\n", skill.Name)
- fmt.Printf(" %s\n", skill.Description)
- fmt.Printf(" Repo: %s\n", skill.Repository)
- if skill.Author != "" {
- fmt.Printf(" Author: %s\n", skill.Author)
- }
- if len(skill.Tags) > 0 {
- fmt.Printf(" Tags: %v\n", skill.Tags)
- }
- fmt.Println()
- }
-}
-
-func skillsShowCmd(loader *skills.SkillsLoader, skillName string) {
- content, ok := loader.LoadSkill(skillName)
- if !ok {
- fmt.Printf("✗ Skill '%s' not found\n", skillName)
- return
- }
-
- fmt.Printf("\n📦 Skill: %s\n", skillName)
- fmt.Println("----------------------")
- fmt.Println(content)
-}
diff --git a/config/config.example.json b/config/config.example.json
index 07f052a98..dd0b16366 100644
--- a/config/config.example.json
+++ b/config/config.example.json
@@ -3,12 +3,48 @@
"defaults": {
"workspace": "~/.picoclaw/workspace",
"restrict_to_workspace": true,
- "model": "glm-4.7",
+ "model": "gpt4",
"max_tokens": 8192,
"temperature": 0.7,
"max_tool_iterations": 20
}
},
+ "model_list": [
+ {
+ "model_name": "gpt4",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-your-openai-key",
+ "api_base": "https://api.openai.com/v1"
+ },
+ {
+ "model_name": "claude-sonnet-4.6",
+ "model": "anthropic/claude-sonnet-4.6",
+ "api_key": "sk-ant-your-key",
+ "api_base": "https://api.anthropic.com/v1"
+ },
+ {
+ "model_name": "gemini",
+ "model": "antigravity/gemini-2.0-flash",
+ "auth_method": "oauth"
+ },
+ {
+ "model_name": "deepseek",
+ "model": "deepseek/deepseek-chat",
+ "api_key": "sk-your-deepseek-key"
+ },
+ {
+ "model_name": "loadbalanced-gpt4",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-key1",
+ "api_base": "https://api1.example.com/v1"
+ },
+ {
+ "model_name": "loadbalanced-gpt4",
+ "model": "openai/gpt-5.2",
+ "api_key": "sk-key2",
+ "api_base": "https://api2.example.com/v1"
+ }
+ ],
"channels": {
"telegram": {
"enabled": false,
@@ -21,6 +57,13 @@
"discord": {
"enabled": false,
"token": "YOUR_DISCORD_BOT_TOKEN",
+ "allow_from": [],
+ "mention_only": false
+ },
+ "qq": {
+ "enabled": false,
+ "app_id": "YOUR_QQ_APP_ID",
+ "app_secret": "YOUR_QQ_APP_SECRET",
"allow_from": []
},
"maixcam": {
@@ -70,9 +113,36 @@
"reconnect_interval": 5,
"group_trigger_prefix": [],
"allow_from": []
+ },
+ "wecom": {
+ "_comment": "WeCom Bot (智能机器人) - Easier setup, supports group chats",
+ "enabled": false,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY",
+ "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18793,
+ "webhook_path": "/webhook/wecom",
+ "allow_from": [],
+ "reply_timeout": 5
+ },
+ "wecom_app": {
+ "_comment": "WeCom App (自建应用) - More features, proactive messaging, private chat only. See docs/wecom-app-configuration.md",
+ "enabled": false,
+ "corp_id": "YOUR_CORP_ID",
+ "corp_secret": "YOUR_CORP_SECRET",
+ "agent_id": 1000002,
+ "token": "YOUR_TOKEN",
+ "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18792,
+ "webhook_path": "/webhook/wecom-app",
+ "allow_from": [],
+ "reply_timeout": 5
}
},
"providers": {
+ "_comment": "DEPRECATED: Use model_list instead. This will be removed in a future version",
"anthropic": {
"api_key": "",
"api_base": ""
@@ -111,9 +181,21 @@
"api_key": "sk-xxx",
"api_base": ""
},
+ "qwen": {
+ "api_key": "sk-xxx",
+ "api_base": ""
+ },
"ollama": {
"api_key": "",
"api_base": "http://localhost:11434/v1"
+ },
+ "cerebras": {
+ "api_key": "",
+ "api_base": ""
+ },
+ "volcengine": {
+ "api_key": "",
+ "api_base": ""
}
},
"tools": {
@@ -123,6 +205,10 @@
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
},
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ },
"perplexity": {
"enabled": false,
"api_key": "pplx-xxx",
@@ -131,6 +217,21 @@
},
"cron": {
"exec_timeout_minutes": 5
+ },
+ "exec": {
+ "enable_deny_patterns": false,
+ "custom_deny_patterns": []
+ },
+ "skills": {
+ "registries": {
+ "clawhub": {
+ "enabled": true,
+ "base_url": "https://clawhub.ai",
+ "search_path": "/api/v1/search",
+ "skills_path": "/api/v1/skills",
+ "download_path": "/api/v1/download"
+ }
+ }
}
},
"heartbeat": {
diff --git a/docs/ANTIGRAVITY_AUTH.md b/docs/ANTIGRAVITY_AUTH.md
new file mode 100644
index 000000000..5d68de427
--- /dev/null
+++ b/docs/ANTIGRAVITY_AUTH.md
@@ -0,0 +1,1002 @@
+# Antigravity Authentication & Integration Guide
+
+## Overview
+
+**Antigravity** (Google Cloud Code Assist) is a Google-backed AI model provider that offers access to models like Claude Opus 4.6 and Gemini through Google's Cloud infrastructure. This document provides a complete guide on how authentication works, how to fetch models, and how to implement a new provider in PicoClaw.
+
+---
+
+## Table of Contents
+
+1. [Authentication Flow](#authentication-flow)
+2. [OAuth Implementation Details](#oauth-implementation-details)
+3. [Token Management](#token-management)
+4. [Models List Fetching](#models-list-fetching)
+5. [Usage Tracking](#usage-tracking)
+6. [Provider Plugin Structure](#provider-plugin-structure)
+7. [Integration Requirements](#integration-requirements)
+8. [API Endpoints](#api-endpoints)
+9. [Configuration](#configuration)
+10. [Creating a New Provider in PicoClaw](#creating-a-new-provider-in-picoclaw)
+
+---
+
+## Authentication Flow
+
+### 1. OAuth 2.0 with PKCE
+
+Antigravity uses **OAuth 2.0 with PKCE (Proof Key for Code Exchange)** for secure authentication:
+
+```
+┌─────────────┐ ┌─────────────────┐
+│ Client │ ───(1) Generate PKCE Pair────────> │ │
+│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │
+│ │ │ Server │
+│ │ <──(3) Redirect with Code───────── │ │
+│ │ └─────────────────┘
+│ │ ───(4) Exchange Code for Tokens──> │ Token URL │
+│ │ │ │
+│ │ <──(5) Access + Refresh Tokens──── │ │
+└─────────────┘ └─────────────────┘
+```
+
+### 2. Detailed Steps
+
+#### Step 1: Generate PKCE Parameters
+```typescript
+function generatePkce(): { verifier: string; challenge: string } {
+ const verifier = randomBytes(32).toString("hex");
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
+ return { verifier, challenge };
+}
+```
+
+#### Step 2: Build Authorization URL
+```typescript
+const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
+const REDIRECT_URI = "http://localhost:51121/oauth-callback";
+
+function buildAuthUrl(params: { challenge: string; state: string }): string {
+ const url = new URL(AUTH_URL);
+ url.searchParams.set("client_id", CLIENT_ID);
+ url.searchParams.set("response_type", "code");
+ url.searchParams.set("redirect_uri", REDIRECT_URI);
+ url.searchParams.set("scope", SCOPES.join(" "));
+ url.searchParams.set("code_challenge", params.challenge);
+ url.searchParams.set("code_challenge_method", "S256");
+ url.searchParams.set("state", params.state);
+ url.searchParams.set("access_type", "offline");
+ url.searchParams.set("prompt", "consent");
+ return url.toString();
+}
+```
+
+**Required Scopes:**
+```typescript
+const SCOPES = [
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/userinfo.profile",
+ "https://www.googleapis.com/auth/cclog",
+ "https://www.googleapis.com/auth/experimentsandconfigs",
+];
+```
+
+#### Step 3: Handle OAuth Callback
+
+**Automatic Mode (Local Development):**
+- Start a local HTTP server on port 51121
+- Wait for the redirect from Google
+- Extract the authorization code from the query parameters
+
+**Manual Mode (Remote/Headless):**
+- Display the authorization URL to the user
+- User completes authentication in their browser
+- User pastes the full redirect URL back into the terminal
+- Parse the code from the pasted URL
+
+#### Step 4: Exchange Code for Tokens
+```typescript
+const TOKEN_URL = "https://oauth2.googleapis.com/token";
+
+async function exchangeCode(params: {
+ code: string;
+ verifier: string;
+}): Promise<{ access: string; refresh: string; expires: number }> {
+ const response = await fetch(TOKEN_URL, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ client_id: CLIENT_ID,
+ client_secret: CLIENT_SECRET,
+ code: params.code,
+ grant_type: "authorization_code",
+ redirect_uri: REDIRECT_URI,
+ code_verifier: params.verifier,
+ }),
+ });
+
+ const data = await response.json();
+
+ return {
+ access: data.access_token,
+ refresh: data.refresh_token,
+ expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer
+ };
+}
+```
+
+#### Step 5: Fetch Additional User Data
+
+**User Email:**
+```typescript
+async function fetchUserEmail(accessToken: string): Promise {
+ const response = await fetch(
+ "https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
+ { headers: { Authorization: `Bearer ${accessToken}` } }
+ );
+ const data = await response.json();
+ return data.email;
+}
+```
+
+**Project ID (Required for API calls):**
+```typescript
+async function fetchProjectId(accessToken: string): Promise {
+ const headers = {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ "User-Agent": "google-api-nodejs-client/9.15.1",
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
+ "Client-Metadata": JSON.stringify({
+ ideType: "IDE_UNSPECIFIED",
+ platform: "PLATFORM_UNSPECIFIED",
+ pluginType: "GEMINI",
+ }),
+ };
+
+ const response = await fetch(
+ "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",
+ {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ metadata: {
+ ideType: "IDE_UNSPECIFIED",
+ platform: "PLATFORM_UNSPECIFIED",
+ pluginType: "GEMINI",
+ },
+ }),
+ }
+ );
+
+ const data = await response.json();
+ return data.cloudaicompanionProject || "rising-fact-p41fc"; // Default fallback
+}
+```
+
+---
+
+## OAuth Implementation Details
+
+### Client Credentials
+
+**Important:** These are base64-encoded in the source code for sync with pi-ai:
+
+```typescript
+const decode = (s: string) => Buffer.from(s, "base64").toString();
+
+const CLIENT_ID = decode(
+ "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="
+);
+const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY=");
+```
+
+### OAuth Flow Modes
+
+1. **Automatic Flow** (Local machines with browser):
+ - Opens browser automatically
+ - Local callback server captures redirect
+ - No user interaction required after initial auth
+
+2. **Manual Flow** (Remote/headless/WSL2):
+ - URL displayed for manual copy-paste
+ - User completes auth in external browser
+ - User pastes full redirect URL back
+
+```typescript
+function shouldUseManualOAuthFlow(isRemote: boolean): boolean {
+ return isRemote || isWSL2Sync();
+}
+```
+
+---
+
+## Token Management
+
+### Auth Profile Structure
+
+```typescript
+type OAuthCredential = {
+ type: "oauth";
+ provider: "google-antigravity";
+ access: string; // Access token
+ refresh: string; // Refresh token
+ expires: number; // Expiration timestamp (ms since epoch)
+ email?: string; // User email
+ projectId?: string; // Google Cloud project ID
+};
+```
+
+### Token Refresh
+
+The credential includes a refresh token that can be used to obtain new access tokens when the current one expires. The expiration is set with a 5-minute buffer to prevent race conditions.
+
+---
+
+## Models List Fetching
+
+### Fetch Available Models
+
+```typescript
+const BASE_URL = "https://cloudcode-pa.googleapis.com";
+
+async function fetchAvailableModels(
+ accessToken: string,
+ projectId: string
+): Promise {
+ const headers = {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ "User-Agent": "antigravity",
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
+ };
+
+ const response = await fetch(
+ `${BASE_URL}/v1internal:fetchAvailableModels`,
+ {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ project: projectId }),
+ }
+ );
+
+ const data = await response.json();
+
+ // Returns models with quota information
+ return Object.entries(data.models).map(([modelId, modelInfo]) => ({
+ id: modelId,
+ displayName: modelInfo.displayName,
+ quotaInfo: {
+ remainingFraction: modelInfo.quotaInfo?.remainingFraction,
+ resetTime: modelInfo.quotaInfo?.resetTime,
+ isExhausted: modelInfo.quotaInfo?.isExhausted,
+ },
+ }));
+}
+```
+
+### Response Format
+
+```typescript
+type FetchAvailableModelsResponse = {
+ models?: Record;
+};
+```
+
+---
+
+## Usage Tracking
+
+### Fetch Usage Data
+
+```typescript
+export async function fetchAntigravityUsage(
+ token: string,
+ timeoutMs: number
+): Promise {
+ // 1. Fetch credits and plan info
+ const loadCodeAssistRes = await fetch(
+ `${BASE_URL}/v1internal:loadCodeAssist`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ metadata: {
+ ideType: "ANTIGRAVITY",
+ platform: "PLATFORM_UNSPECIFIED",
+ pluginType: "GEMINI",
+ },
+ }),
+ }
+ );
+
+ // Extract credits info
+ const { availablePromptCredits, planInfo, currentTier } = data;
+
+ // 2. Fetch model quotas
+ const modelsRes = await fetch(
+ `${BASE_URL}/v1internal:fetchAvailableModels`,
+ {
+ method: "POST",
+ headers: { Authorization: `Bearer ${token}` },
+ body: JSON.stringify({ project: projectId }),
+ }
+ );
+
+ // Build usage windows
+ return {
+ provider: "google-antigravity",
+ displayName: "Google Antigravity",
+ windows: [
+ { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) },
+ // Individual model quotas...
+ ],
+ plan: currentTier?.name || planType,
+ };
+}
+```
+
+### Usage Response Structure
+
+```typescript
+type ProviderUsageSnapshot = {
+ provider: "google-antigravity";
+ displayName: string;
+ windows: UsageWindow[];
+ plan?: string;
+ error?: string;
+};
+
+type UsageWindow = {
+ label: string; // "Credits" or model ID
+ usedPercent: number; // 0-100
+ resetAt?: number; // Timestamp when quota resets
+};
+```
+
+---
+
+## Provider Plugin Structure
+
+### Plugin Definition
+
+```typescript
+const antigravityPlugin = {
+ id: "google-antigravity-auth",
+ name: "Google Antigravity Auth",
+ description: "OAuth flow for Google Antigravity (Cloud Code Assist)",
+ configSchema: emptyPluginConfigSchema(),
+
+ register(api: OpenClawPluginApi) {
+ api.registerProvider({
+ id: "google-antigravity",
+ label: "Google Antigravity",
+ docsPath: "/providers/models",
+ aliases: ["antigravity"],
+
+ auth: [
+ {
+ id: "oauth",
+ label: "Google OAuth",
+ hint: "PKCE + localhost callback",
+ kind: "oauth",
+ run: async (ctx: ProviderAuthContext) => {
+ // OAuth implementation here
+ },
+ },
+ ],
+ });
+ },
+};
+```
+
+### ProviderAuthContext
+
+```typescript
+type ProviderAuthContext = {
+ config: OpenClawConfig;
+ agentDir?: string;
+ workspaceDir?: string;
+ prompter: WizardPrompter; // UI prompts/notifications
+ runtime: RuntimeEnv; // Logging, etc.
+ isRemote: boolean; // Whether running remotely
+ openUrl: (url: string) => Promise; // Browser opener
+ oauth: {
+ createVpsAwareHandlers: Function;
+ };
+};
+```
+
+### ProviderAuthResult
+
+```typescript
+type ProviderAuthResult = {
+ profiles: Array<{
+ profileId: string;
+ credential: AuthProfileCredential;
+ }>;
+ configPatch?: Partial;
+ defaultModel?: string;
+ notes?: string[];
+};
+```
+
+---
+
+## Integration Requirements
+
+### 1. Required Environment/Dependencies
+
+- Node.js ≥ 22
+- OpenClaw plugin-sdk
+- crypto module (built-in)
+- http module (built-in)
+
+### 2. Required Headers for API Calls
+
+```typescript
+const REQUIRED_HEADERS = {
+ "Authorization": `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ "User-Agent": "antigravity", // or "google-api-nodejs-client/9.15.1"
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
+};
+
+// For loadCodeAssist calls, also include:
+const CLIENT_METADATA = {
+ ideType: "ANTIGRAVITY", // or "IDE_UNSPECIFIED"
+ platform: "PLATFORM_UNSPECIFIED",
+ pluginType: "GEMINI",
+};
+```
+
+### 3. Model Schema Sanitization
+
+Antigravity uses Gemini-compatible models, so tool schemas must be sanitized:
+
+```typescript
+const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([
+ "patternProperties",
+ "additionalProperties",
+ "$schema",
+ "$id",
+ "$ref",
+ "$defs",
+ "definitions",
+ "examples",
+ "minLength",
+ "maxLength",
+ "minimum",
+ "maximum",
+ "multipleOf",
+ "pattern",
+ "format",
+ "minItems",
+ "maxItems",
+ "uniqueItems",
+ "minProperties",
+ "maxProperties",
+]);
+
+// Clean schema before sending
+function cleanToolSchemaForGemini(schema: Record): unknown {
+ // Remove unsupported keywords
+ // Ensure top-level has type: "object"
+ // Flatten anyOf/oneOf unions
+}
+```
+
+### 4. Thinking Block Handling (Claude Models)
+
+For Antigravity Claude models, thinking blocks require special handling:
+
+```typescript
+const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/;
+
+export function sanitizeAntigravityThinkingBlocks(
+ messages: AgentMessage[]
+): AgentMessage[] {
+ // Validate thinking signatures
+ // Normalize signature fields
+ // Discard unsigned thinking blocks
+}
+```
+
+---
+
+## API Endpoints
+
+### Authentication Endpoints
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `https://accounts.google.com/o/oauth2/v2/auth` | GET | OAuth authorization |
+| `https://oauth2.googleapis.com/token` | POST | Token exchange |
+| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | User info (email) |
+
+### Cloud Code Assist Endpoints
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | Load project info, credits, plan |
+| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | List available models with quotas |
+| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | Chat streaming endpoint |
+
+**API Request Format (Chat):**
+The `v1internal:streamGenerateContent` endpoint expects an envelope wrapping the standard Gemini request:
+
+```json
+{
+ "project": "your-project-id",
+ "model": "model-id",
+ "request": {
+ "contents": [...],
+ "systemInstruction": {...},
+ "generationConfig": {...},
+ "tools": [...]
+ },
+ "requestType": "agent",
+ "userAgent": "antigravity",
+ "requestId": "agent-timestamp-random"
+}
+```
+
+**API Response Format (SSE):**
+Each SSE message (`data: {...}`) is wrapped in a `response` field:
+
+```json
+{
+ "response": {
+ "candidates": [...],
+ "usageMetadata": {...},
+ "modelVersion": "...",
+ "responseId": "..."
+ },
+ "traceId": "...",
+ "metadata": {}
+}
+```
+
+---
+
+## Configuration
+
+### openclaw.json Configuration
+
+```json5
+{
+ agents: {
+ defaults: {
+ model: {
+ primary: "google-antigravity/claude-opus-4-6-thinking",
+ },
+ },
+ },
+}
+```
+
+### Auth Profile Storage
+
+Auth profiles are stored in `~/.openclaw/agent/auth-profiles.json`:
+
+```json
+{
+ "version": 1,
+ "profiles": {
+ "google-antigravity:user@example.com": {
+ "type": "oauth",
+ "provider": "google-antigravity",
+ "access": "ya29...",
+ "refresh": "1//...",
+ "expires": 1704067200000,
+ "email": "user@example.com",
+ "projectId": "my-project-id"
+ }
+ }
+}
+```
+
+---
+
+## Creating a New Provider in PicoClaw
+
+### Step-by-Step Implementation
+
+#### 1. Create Plugin Structure
+
+```
+extensions/
+└── your-provider-auth/
+ ├── openclaw.plugin.json
+ ├── package.json
+ ├── README.md
+ └── index.ts
+```
+
+#### 2. Define Plugin Manifest
+
+**openclaw.plugin.json:**
+```json
+{
+ "id": "your-provider-auth",
+ "providers": ["your-provider"],
+ "configSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {}
+ }
+}
+```
+
+**package.json:**
+```json
+{
+ "name": "@openclaw/your-provider-auth",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Your Provider OAuth plugin",
+ "type": "module"
+}
+```
+
+#### 3. Implement OAuth Flow
+
+```typescript
+import {
+ buildOauthProviderAuthResult,
+ emptyPluginConfigSchema,
+ type OpenClawPluginApi,
+ type ProviderAuthContext,
+} from "openclaw/plugin-sdk";
+
+const YOUR_CLIENT_ID = "your-client-id";
+const YOUR_CLIENT_SECRET = "your-client-secret";
+const AUTH_URL = "https://provider.com/oauth/authorize";
+const TOKEN_URL = "https://provider.com/oauth/token";
+const REDIRECT_URI = "http://localhost:PORT/oauth-callback";
+
+async function loginYourProvider(params: {
+ isRemote: boolean;
+ openUrl: (url: string) => Promise;
+ prompt: (message: string) => Promise;
+ note: (message: string, title?: string) => Promise;
+ log: (message: string) => void;
+ progress: { update: (msg: string) => void; stop: (msg?: string) => void };
+}) {
+ // 1. Generate PKCE
+ const { verifier, challenge } = generatePkce();
+ const state = randomBytes(16).toString("hex");
+
+ // 2. Build auth URL
+ const authUrl = buildAuthUrl({ challenge, state });
+
+ // 3. Start callback server (if not remote)
+ const callbackServer = !params.isRemote
+ ? await startCallbackServer({ timeoutMs: 5 * 60 * 1000 })
+ : null;
+
+ // 4. Open browser or show URL
+ if (callbackServer) {
+ await params.openUrl(authUrl);
+ const callback = await callbackServer.waitForCallback();
+ code = callback.searchParams.get("code");
+ } else {
+ await params.note(`Auth URL: ${authUrl}`, "OAuth");
+ const input = await params.prompt("Paste redirect URL:");
+ const parsed = parseCallbackInput(input);
+ code = parsed.code;
+ }
+
+ // 5. Exchange code for tokens
+ const tokens = await exchangeCode({ code, verifier });
+
+ // 6. Fetch additional user data
+ const email = await fetchUserEmail(tokens.access);
+
+ return { ...tokens, email };
+}
+```
+
+#### 4. Register Provider
+
+```typescript
+const yourProviderPlugin = {
+ id: "your-provider-auth",
+ name: "Your Provider Auth",
+ description: "OAuth for Your Provider",
+ configSchema: emptyPluginConfigSchema(),
+
+ register(api: OpenClawPluginApi) {
+ api.registerProvider({
+ id: "your-provider",
+ label: "Your Provider",
+ docsPath: "/providers/models",
+ aliases: ["yp"],
+
+ auth: [
+ {
+ id: "oauth",
+ label: "OAuth Login",
+ hint: "Browser-based authentication",
+ kind: "oauth",
+
+ run: async (ctx: ProviderAuthContext) => {
+ const spin = ctx.prompter.progress("Starting OAuth...");
+
+ try {
+ const result = await loginYourProvider({
+ isRemote: ctx.isRemote,
+ openUrl: ctx.openUrl,
+ prompt: async (msg) => String(await ctx.prompter.text({ message: msg })),
+ note: ctx.prompter.note,
+ log: (msg) => ctx.runtime.log(msg),
+ progress: spin,
+ });
+
+ return buildOauthProviderAuthResult({
+ providerId: "your-provider",
+ defaultModel: "your-provider/model-name",
+ access: result.access,
+ refresh: result.refresh,
+ expires: result.expires,
+ email: result.email,
+ notes: ["Provider-specific notes"],
+ });
+ } catch (err) {
+ spin.stop("OAuth failed");
+ throw err;
+ }
+ },
+ },
+ ],
+ });
+ },
+};
+
+export default yourProviderPlugin;
+```
+
+#### 5. Implement Usage Tracking (Optional)
+
+```typescript
+// src/infra/provider-usage.fetch.your-provider.ts
+export async function fetchYourProviderUsage(
+ token: string,
+ timeoutMs: number,
+ fetchFn: typeof fetch
+): Promise {
+ // Fetch usage data from provider API
+ const response = await fetchFn("https://api.provider.com/usage", {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ const data = await response.json();
+
+ return {
+ provider: "your-provider",
+ displayName: "Your Provider",
+ windows: [
+ { label: "Credits", usedPercent: data.usedPercent },
+ ],
+ plan: data.planName,
+ };
+}
+```
+
+#### 6. Register Usage Fetcher
+
+```typescript
+// src/infra/provider-usage.load.ts
+case "your-provider":
+ return await fetchYourProviderUsage(auth.token, timeoutMs, fetchFn);
+```
+
+#### 7. Add Provider to Type Definitions
+
+```typescript
+// src/infra/provider-usage.types.ts
+export type SupportedProvider =
+ | "anthropic"
+ | "github-copilot"
+ | "google-gemini-cli"
+ | "google-antigravity"
+ | "your-provider" // Add here
+ | "minimax"
+ | "openai-codex";
+```
+
+#### 8. Add Auth Choice Handler
+
+```typescript
+// src/commands/auth-choice.apply.your-provider.ts
+import { applyAuthChoicePluginProvider } from "./auth-choice.apply.plugin-provider.js";
+
+export async function applyAuthChoiceYourProvider(
+ params: ApplyAuthChoiceParams
+): Promise {
+ return await applyAuthChoicePluginProvider(params, {
+ authChoice: "your-provider",
+ pluginId: "your-provider-auth",
+ providerId: "your-provider",
+ methodId: "oauth",
+ label: "Your Provider",
+ });
+}
+```
+
+#### 9. Export from Main Index
+
+```typescript
+// src/commands/auth-choice.apply.ts
+import { applyAuthChoiceYourProvider } from "./auth-choice.apply.your-provider.js";
+
+// In the switch statement:
+case "your-provider":
+ return await applyAuthChoiceYourProvider(params);
+```
+
+### Helper Utilities
+
+#### PKCE Generation
+```typescript
+function generatePkce(): { verifier: string; challenge: string } {
+ const verifier = randomBytes(32).toString("hex");
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
+ return { verifier, challenge };
+}
+```
+
+#### Callback Server
+```typescript
+async function startCallbackServer(params: { timeoutMs: number }) {
+ const port = 51121; // Your port
+
+ const server = createServer((request, response) => {
+ const url = new URL(request.url!, `http://localhost:${port}`);
+
+ if (url.pathname === "/oauth-callback") {
+ response.writeHead(200, { "Content-Type": "text/html" });
+ response.end("