This commit is contained in:
Worm 2026-02-18 11:26:39 +08:00
parent 0651fae151
commit b255196b4c
42 changed files with 2652 additions and 368 deletions

View file

@ -5,6 +5,11 @@
- [ ] 📖 Documentation update
- [ ] ⚡ Code refactoring (no functional changes, no api changes)
## 🤖 AI Code Generation
- [ ] 🤖 Fully AI-generated (100% AI, 0% Human)
- [ ] 🛠️ Mostly AI-generated (AI draft, Human verified/modified)
- [ ] 👨‍💻 Mostly Human-written (Human lead, AI assisted or none)
## 🔗 Linked Issue
## 📚 Technical Context (Skip for Docs)

View file

@ -32,11 +32,13 @@ jobs:
- name: Create and push tag
shell: bash
env:
RELEASE_TAG: ${{ inputs.tag }}
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "${{ inputs.tag }}" -m "Release ${{ inputs.tag }}"
git push origin "${{ inputs.tag }}"
git tag -a "$RELEASE_TAG" -m "Release $RELEASE_TAG"
git push origin "$RELEASE_TAG"
release:
name: GoReleaser Release

View file

@ -39,6 +39,8 @@ ifeq ($(UNAME_S),Linux)
ARCH=amd64
else ifeq ($(UNAME_M),aarch64)
ARCH=arm64
else ifeq ($(UNAME_M),loongarch64)
ARCH=loong64
else ifeq ($(UNAME_M),riscv64)
ARCH=riscv64
else
@ -84,6 +86,7 @@ build-all: generate
@mkdir -p $(BUILD_DIR)
GOOS=linux GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./$(CMD_DIR)
GOOS=linux GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 ./$(CMD_DIR)
GOOS=linux GOARCH=loong64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-loong64 ./$(CMD_DIR)
GOOS=linux GOARCH=riscv64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR)
GOOS=darwin GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR)
GOOS=windows GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./$(CMD_DIR)

View file

@ -195,6 +195,9 @@ picoclaw onboard
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
}
},
"cron": {
"exec_timeout_minutes": 5
}
},
"heartbeat": {
@ -697,6 +700,9 @@ HEARTBEAT_OK 応答 ユーザーが直接結果を受け取る
"search": {
"apiKey": "BSA..."
}
},
"cron": {
"exec_timeout_minutes": 5
}
},
"heartbeat": {

View file

@ -49,7 +49,7 @@
## 📢 News
2026-02-16 🎉 PicoClaw hit 12K stars in one week! Thank you all for your support! PicoClaw is growing faster than we ever imagined. Given the high volume of PRs, we urgently need community maintainers. Our volunteer roles and roadmap are officially posted [here](doc/picoclaw_community_roadmap_260216.md) —we cant wait to have you on board!
2026-02-16 🎉 PicoClaw hit 12K stars in one week! Thank you all for your support! PicoClaw is growing faster than we ever imagined. Given the high volume of PRs, we urgently need community maintainers. Our volunteer roles and roadmap are officially posted [here](docs/picoclaw_community_roadmap_260216.md) —we cant wait to have you on board!
2026-02-13 🎉 PicoClaw hit 5000 stars in 4days! Thank you for the community! There are so many PRs&issues come in (during Chinese New Year holidays), we are finalizing the Project Roadmap and setting up the Developer Group to accelerate PicoClaw's development.
🚀 Call to Action: Please submit your feature requests in GitHub Discussions. We will review and prioritize them during our upcoming weekly meeting.
@ -99,6 +99,20 @@
</tr>
</table>
### 📱 Run on old Android Phones
Give your decade-old phone a second life! Turn it into a smart AI Assistant with PicoClaw. Quick Start:
1. **Install Termux** (Available on F-Droid or Google Play).
2. **Execute cmds**
```bash
# Note: Replace v0.1.1 with the latest version from the Releases page
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
```
And then follow the instructions in the "Quick Start" section to complete the configuration!
<img src="assets/termux.jpg" alt="PicoClaw" width="512">
### 🐜 Innovative Low-Footprint Deploy
PicoClaw can be deployed on almost any Linux device!
@ -760,6 +774,9 @@ picoclaw agent -m "Hello"
"enabled": true,
"max_results": 5
}
},
"cron": {
"exec_timeout_minutes": 5
}
},
"heartbeat": {

View file

@ -50,7 +50,7 @@
## 📢 新闻 (News)
2026-02-16 🎉 PicoClaw 在一周内突破了12K star! 感谢大家的关注PicoClaw 的成长速度超乎我们预期. 由于PR数量的快速膨胀我们亟需社区开发者参与维护. 我们需要的志愿者角色和roadmap已经发布到了[这里](doc/picoclaw_community_roadmap_260216.md), 期待你的参与!
2026-02-16 🎉 PicoClaw 在一周内突破了12K star! 感谢大家的关注PicoClaw 的成长速度超乎我们预期. 由于PR数量的快速膨胀我们亟需社区开发者参与维护. 我们需要的志愿者角色和roadmap已经发布到了[这里](docs/picoclaw_community_roadmap_260216.md), 期待你的参与!
2026-02-13 🎉 **PicoClaw 在 4 天内突破 5000 Stars** 感谢社区的支持由于正值中国春节假期PR 和 Issue 涌入较多,我们正在利用这段时间敲定 **项目路线图 (Roadmap)** 并组建 **开发者群组**,以便加速 PicoClaw 的开发。
🚀 **行动号召:** 请在 GitHub Discussions 中提交您的功能请求 (Feature Requests)。我们将在接下来的周会上进行审查和优先级排序。
@ -100,6 +100,23 @@
</tr>
</table>
### 📱 在手机上轻松运行
picoclaw 可以将你10年前的老旧手机废物利用变身成为你的AI助理快速指南:
1. 先去应用商店下载安装Termux
2. 打开后执行指令
```bash
# 注意: 下面的v0.1.1 可以换为你实际看到的最新版本
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
```
然后跟随下面的“快速开始”章节继续配置picoclaw即可使用
<img src="assets/termux.jpg" alt="PicoClaw" width="512">
### 🐜 创新的低占用部署
PicoClaw 几乎可以部署在任何 Linux 设备上!
@ -219,6 +236,9 @@ picoclaw onboard
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
}
},
"cron": {
"exec_timeout_minutes": 5
}
}
}
@ -440,6 +460,46 @@ PicoClaw 将数据存储在您配置的工作区中(默认:`~/.picoclaw/work
```
### 按渠道清理对话会话 (session_ttl)
每个渠道的配置下都包含一个可选字段 `session_ttl`,用于控制该渠道的**对话会话保留时间**(存放在 `workspace/sessions/` 目录中的会话文件)。
示例(以 XMPP 为例):
```json
{
"channels": {
"xmpp": {
"enabled": true,
"jid": "bot@example.com",
"password": "YOUR_PASSWORD",
"server": "example.com:5222",
"upload_domain": "upload.example.com",
"allow_from": [],
"session_ttl": "1h"
}
}
}
```
行为说明:
- `session_ttl`: 字符串形式的时间长度,仅对该渠道生效
- `"false"` 或空字符串:禁用自动清理(默认值)
- `"30m"`:保留 30 分钟
- `"1h"`:保留 1 小时
- `"2h"`:保留 2 小时
- `"1d"`:保留 1 天(等价于 `24h`
- Agent 会定期检查所有会话:
- 如果某个会话最后更新时间早于当前时间减去 `session_ttl`
- 则删除该会话的历史记录(内存 + `sessions/*.json` 文件)
- 只影响会话历史,不会删除 `memory/` 目录中的长期记忆MEMORY.md或每日笔记。
这可以帮助在树莓派等内存/存储有限的设备上,按渠道控制对话保留时间,例如:
- 对安全敏感的 XMPP 渠道设置较短 TTL`1h`),降低明文历史泄露风险
- 对相对不敏感或需要长期上下文的渠道保留 `"false"`,完全不自动清理
### 心跳 / 周期性任务 (Heartbeat)
PicoClaw 可以自动执行周期性任务。在工作区创建 `HEARTBEAT.md` 文件:
@ -627,6 +687,9 @@ picoclaw agent -m "你好"
"search": {
"api_key": "BSA..."
}
},
"cron": {
"exec_timeout_minutes": 5
}
},
"heartbeat": {
@ -718,4 +781,4 @@ Discord: [https://discord.gg/V4sAZ9XWpN](https://discord.gg/V4sAZ9XWpN)
| **OpenRouter** | 200K tokens/月 | 多模型聚合 (Claude, GPT-4 等) |
| **智谱 (Zhipu)** | 200K tokens/月 | 最适合中国用户 |
| **Brave Search** | 2000 次查询/月 | 网络搜索功能 |
| **Groq** | 提供免费层级 | 极速推理 (Llama, Mixtral) |
| **Groq** | 提供免费层级 | 极速推理 (Llama, Mixtral) |

116
ROADMAP.md Normal file
View file

@ -0,0 +1,116 @@
# 🦐 PicoClaw Roadmap
> **Vision**: To build the ultimate lightweight, secure, and fully autonomous AI Agent infrastructure.automate the mundane, unleash your creativity
---
## 🚀 1. Core Optimization: Extreme Lightweight
*Our defining characteristic. We fight software bloat to ensure PicoClaw runs smoothly on the smallest embedded devices.*
* [**Memory Footprint Reduction**](https://github.com/sipeed/picoclaw/issues/346)
* **Goal**: Run smoothly on 64MB RAM embedded boards (e.g., low-end RISC-V SBCs) with the core process consuming < 20MB.
* **Context**: RAM is expensive and scarce on edge devices. Memory optimization takes precedence over storage size.
* **Action**: Analyze memory growth between releases, remove redundant dependencies, and optimize data structures.
## 🛡️ 2. Security Hardening: Defense in Depth
*Paying off early technical debt. We invite security experts to help build a "Secure-by-Default" agent.*
* **Input Defense & Permission Control**
* **Prompt Injection Defense**: Harden JSON extraction logic to prevent LLM manipulation.
* **Tool Abuse Prevention**: Strict parameter validation to ensure generated commands stay within safe boundaries.
* **SSRF Protection**: Built-in blocklists for network tools to prevent accessing internal IPs (LAN/Metadata services).
* **Sandboxing & Isolation**
* **Filesystem Sandbox**: Restrict file R/W operations to specific directories only.
* **Context Isolation**: Prevent data leakage between different user sessions or channels.
* **Privacy Redaction**: Auto-redact sensitive info (API Keys, PII) from logs and standard outputs.
* **Authentication & Secrets**
* **Crypto Upgrade**: Adopt modern algorithms like `ChaCha20-Poly1305` for secret storage.
* **OAuth 2.0 Flow**: Deprecate hardcoded API keys in the CLI; move to secure OAuth flows.
## 🔌 3. Connectivity: Protocol-First Architecture
*Connect every model, reach every platform.*
* **Provider**
* [**Architecture Upgrade**](https://github.com/sipeed/picoclaw/issues/283): Refactor from "Vendor-based" to "Protocol-based" classification (e.g., OpenAI-compatible, Ollama-compatible). *(Status: In progress by @Daming, ETA 5 days)*
* **Local Models**: Deep integration with **Ollama**, **vLLM**, **LM Studio**, and **Mistral** (local inference).
* **Online Models**: Continued support for frontier closed-source models.
* **Channel**
* **IM Matrix**: QQ, WeChat (Work), DingTalk, Feishu (Lark), Telegram, Discord, WhatsApp, LINE, Slack, Email, KOOK, Signal, ...
* **Standards**: Support for the **OneBot** protocol.
* [**attachment**](https://github.com/sipeed/picoclaw/issues/348): Native handling of images, audio, and video attachments.
* **Skill Marketplace**
* [**Discovery skills**](https://github.com/sipeed/picoclaw/issues/287): Implement `find_skill` to automatically discover and install skills from the [GitHub Skills Repo] or other registries.
## 🧠 4. Advanced Capabilities: From Chatbot to Agentic AI
*Beyond conversation—focusing on action and collaboration.*
* **Operations**
* [**MCP Support**](https://github.com/sipeed/picoclaw/issues/290): Native support for the **Model Context Protocol (MCP)**.
* [**Browser Automation**](https://github.com/sipeed/picoclaw/issues/293): Headless browser control via CDP (Chrome DevTools Protocol) or ActionBook.
* [**Mobile Operation**](https://github.com/sipeed/picoclaw/issues/292): Android device control (similar to BotDrop).
* **Multi-Agent Collaboration**
* [**Basic Multi-Agent**](https://github.com/sipeed/picoclaw/issues/294) implement
* [**Model Routing**](https://github.com/sipeed/picoclaw/issues/295): "Smart Routing" — dispatch simple tasks to small/local models (fast/cheap) and complex tasks to SOTA models (smart).
* [**Swarm Mode**](https://github.com/sipeed/picoclaw/issues/284): Collaboration between multiple PicoClaw instances on the same network.
* [**AIEOS**](https://github.com/sipeed/picoclaw/issues/296): Exploring AI-Native Operating System interaction paradigms.
## 📚 5. Developer Experience (DevEx) & Documentation
*Lowering the barrier to entry so anyone can deploy in minutes.*
* [**QuickGuide (Zero-Config Start)**](https://github.com/sipeed/picoclaw/issues/350)
* Interactive CLI Wizard: If launched without config, automatically detect the environment and guide the user through Token/Network setup step-by-step.
* **Comprehensive Documentation**
* **Platform Guides**: Dedicated guides for Windows, macOS, Linux, and Android.
* **Step-by-Step Tutorials**: "Babysitter-level" guides for configuring Providers and Channels.
* **AI-Assisted Docs**: Using AI to auto-generate API references and code comments (with human verification to prevent hallucinations).
## 🤖 6. Engineering: AI-Powered Open Source
*Born from Vibe Coding, we continue to use AI to accelerate development.*
* **AI-Enhanced CI/CD**
* Integrate AI for automated Code Review, Linting, and PR Labeling.
* **Bot Noise Reduction**: Optimize bot interactions to keep PR timelines clean.
* **Issue Triage**: AI agents to analyze incoming issues and suggest preliminary fixes.
## 🎨 7. Brand & Community
* [**Logo Design**](https://github.com/sipeed/picoclaw/issues/297): We are looking for a **Mantis Shrimp (Stomatopoda)** logo design!
* *Concept*: Needs to reflect "Small but Mighty" and "Lightning Fast Strikes."
---
### 🤝 Call for Contributions
We welcome community contributions to any item on this roadmap! Please comment on the relevant Issue or submit a PR. Let's build the best Edge AI Agent together!

BIN
assets/termux.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View file

@ -562,7 +562,8 @@ func gatewayCmd() {
})
// Setup cron tool and service
cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath(), cfg.Agents.Defaults.RestrictToWorkspace)
execTimeout := time.Duration(cfg.Tools.Cron.ExecTimeoutMinutes) * time.Minute
cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath(), cfg.Agents.Defaults.RestrictToWorkspace, execTimeout)
heartbeatService := heartbeat.NewHeartbeatService(
cfg.WorkspacePath(),
@ -987,14 +988,14 @@ func getConfigPath() string {
return filepath.Join(home, ".picoclaw", "config.json")
}
func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string, restrict bool) *cron.CronService {
func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string, restrict bool, execTimeout time.Duration) *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)
cronTool := tools.NewCronTool(cronService, agentLoop, msgBus, workspace, restrict, execTimeout)
agentLoop.RegisterTool(cronTool)
// Set the onJob handler

View file

@ -14,7 +14,9 @@
"enabled": false,
"token": "YOUR_TELEGRAM_BOT_TOKEN",
"proxy": "",
"allow_from": ["YOUR_USER_ID"]
"allow_from": [
"YOUR_USER_ID"
]
},
"discord": {
"enabled": false,
@ -68,20 +70,6 @@
"reconnect_interval": 5,
"group_trigger_prefix": [],
"allow_from": []
},
"xmpp": {
"enabled": false,
"server": "example.com:5222",
"domain": "example.com",
"username": "bot",
"password": "YOUR_PASSWORD",
"resource": "picoclaw",
"rooms": [],
"nickname": "PicoClaw",
"use_tls": true,
"insecure_skip_verify": false,
"enable_receipts": true,
"allow_from": []
}
},
"providers": {
@ -129,10 +117,19 @@
},
"tools": {
"web": {
"search": {
"brave": {
"enabled": false,
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
},
"perplexity": {
"enabled": false,
"api_key": "pplx-xxx",
"max_results": 5
}
},
"cron": {
"exec_timeout_minutes": 5
}
},
"heartbeat": {
@ -147,4 +144,4 @@
"host": "0.0.0.0",
"port": 18790
}
}
}

6
go.mod
View file

@ -18,8 +18,9 @@ require (
github.com/stretchr/testify v1.11.1
github.com/tencent-connect/botgo v0.2.1
golang.org/x/oauth2 v0.35.0
mellium.im/xmlstream v0.15.4-0.20211023152852-0ca80a938137
mellium.im/xmpp v0.21.3
mellium.im/sasl v0.3.2
mellium.im/xmlstream v0.15.4
mellium.im/xmpp v0.22.0
)
require (
@ -30,7 +31,6 @@ require (
golang.org/x/tools v0.41.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
mellium.im/reader v0.1.0 // indirect
mellium.im/sasl v0.3.0 // indirect
)
require (

12
go.sum
View file

@ -267,9 +267,9 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mellium.im/reader v0.1.0 h1:UUEMev16gdvaxxZC7fC08j7IzuDKh310nB6BlwnxTww=
mellium.im/reader v0.1.0/go.mod h1:F+X5HXpkIfJ9EE1zHQG9lM/hO946iYAmU7xjg5dsQHI=
mellium.im/sasl v0.3.0 h1:0qoaTCTo5Py7u/g0cBIQZcMOgG/5LM71nshbXwznBh8=
mellium.im/sasl v0.3.0/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw=
mellium.im/xmlstream v0.15.4-0.20211023152852-0ca80a938137 h1:ALOIzIw0sJLO0Agfwftq7yS7Rk8pWBEdrc3/5lSprzE=
mellium.im/xmlstream v0.15.4-0.20211023152852-0ca80a938137/go.mod h1:7SUlP7f2qnMczK+Cu/OFgqaIhldMolVjo8np7xG41D0=
mellium.im/xmpp v0.21.3 h1:yQQPBdOYnd15987UaWL/0eIM2fdaWn9FUpqZHfZTFQI=
mellium.im/xmpp v0.21.3/go.mod h1:NoTQy2Ry+c5WdkRUK2npXC1SzWTZ8zXIt79wMH0Du7Y=
mellium.im/sasl v0.3.2 h1:PT6Xp7ccn9XaXAnJ03FcEjmAn7kK1x7aoXV6F+Vmrl0=
mellium.im/sasl v0.3.2/go.mod h1:NKXDi1zkr+BlMHLQjY3ofYuU4KSPFxknb8mfEu6SveY=
mellium.im/xmlstream v0.15.4 h1:gLKxcWl4rLMUpKgtzrTBvr4OexPeO/edYus+uK3F6ZI=
mellium.im/xmlstream v0.15.4/go.mod h1:yXaCW2++fmVO4L9piKVkyLDqnCmictVYF7FDQW8prb4=
mellium.im/xmpp v0.22.0 h1:UthQVSwEAr7SNrmyc90c2ykGpVHxjn/3yw8Ey4+Im8s=
mellium.im/xmpp v0.22.0/go.mod h1:WSjq12nhREFD88Vy/0WD6Q8inE8t6a8w7QjzwivWitw=

View file

@ -44,6 +44,7 @@ type AgentLoop struct {
running atomic.Bool
summarizing sync.Map // Tracks which sessions are currently being summarized
channelManager *channels.Manager
channelTTLs map[string]time.Duration
}
// processOptions configures how a message is processed
@ -79,6 +80,9 @@ func createToolRegistry(workspace string, restrict bool, cfg *config.Config, msg
BraveEnabled: cfg.Tools.Web.Brave.Enabled,
DuckDuckGoMaxResults: cfg.Tools.Web.DuckDuckGo.MaxResults,
DuckDuckGoEnabled: cfg.Tools.Web.DuckDuckGo.Enabled,
PerplexityAPIKey: cfg.Tools.Web.Perplexity.APIKey,
PerplexityMaxResults: cfg.Tools.Web.Perplexity.MaxResults,
PerplexityEnabled: cfg.Tools.Web.Perplexity.Enabled,
}); searchTool != nil {
registry.Register(searchTool)
}
@ -91,11 +95,12 @@ func createToolRegistry(workspace string, restrict bool, cfg *config.Config, msg
// Message tool - available to both agent and subagent
// Subagent uses it to communicate directly with user
messageTool := tools.NewMessageTool()
messageTool.SetSendCallback(func(channel, chatID, content string) error {
messageTool.SetSendCallback(func(channel, chatID, content string, media []string) error {
msgBus.PublishOutbound(bus.OutboundMessage{
Channel: channel,
ChatID: chatID,
Content: content,
Media: media,
})
return nil
})
@ -136,7 +141,7 @@ func NewAgentLoop(cfg *config.Config, msgBus *bus.MessageBus, provider providers
contextBuilder := NewContextBuilder(workspace)
contextBuilder.SetToolsRegistry(toolsRegistry)
return &AgentLoop{
al := &AgentLoop{
bus: msgBus,
provider: provider,
workspace: workspace,
@ -148,7 +153,13 @@ func NewAgentLoop(cfg *config.Config, msgBus *bus.MessageBus, provider providers
contextBuilder: contextBuilder,
tools: toolsRegistry,
summarizing: sync.Map{},
channelTTLs: make(map[string]time.Duration),
}
al.initChannelTTLs(cfg)
go al.startSessionCleanup()
return al
}
func (al *AgentLoop) Run(ctx context.Context) error {
@ -979,6 +990,108 @@ func (al *AgentLoop) estimateTokens(messages []providers.Message) int {
return totalChars * 2 / 5
}
func (al *AgentLoop) initChannelTTLs(cfg *config.Config) {
parseTTL := func(raw string) (time.Duration, bool) {
if raw == "" {
return 0, false
}
lower := strings.ToLower(strings.TrimSpace(raw))
if lower == "false" {
return 0, false
}
if strings.HasSuffix(lower, "d") {
num := strings.TrimSuffix(lower, "d")
days, err := time.ParseDuration(num + "h")
if err != nil {
return 0, false
}
return days * 24, true
}
d, err := time.ParseDuration(lower)
if err != nil || d <= 0 {
return 0, false
}
return d, true
}
if ttl, ok := parseTTL(cfg.Channels.WhatsApp.SessionTTL); ok {
al.channelTTLs["whatsapp"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.Telegram.SessionTTL); ok {
al.channelTTLs["telegram"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.Feishu.SessionTTL); ok {
al.channelTTLs["feishu"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.Discord.SessionTTL); ok {
al.channelTTLs["discord"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.MaixCam.SessionTTL); ok {
al.channelTTLs["maixcam"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.QQ.SessionTTL); ok {
al.channelTTLs["qq"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.DingTalk.SessionTTL); ok {
al.channelTTLs["dingtalk"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.Slack.SessionTTL); ok {
al.channelTTLs["slack"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.LINE.SessionTTL); ok {
al.channelTTLs["line"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.OneBot.SessionTTL); ok {
al.channelTTLs["onebot"] = ttl
}
if ttl, ok := parseTTL(cfg.Channels.XMPP.SessionTTL); ok {
al.channelTTLs["xmpp"] = ttl
}
}
func (al *AgentLoop) startSessionCleanup() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
<-ticker.C
al.cleanupExpiredSessions()
}
}
func (al *AgentLoop) cleanupExpiredSessions() {
sessions := al.sessions.ListSessions()
for _, info := range sessions {
colon := strings.Index(info.Key, ":")
if colon <= 0 {
continue
}
channel := info.Key[:colon]
ttl, ok := al.channelTTLs[channel]
if !ok || ttl <= 0 {
continue
}
cutoff := time.Now().Add(-ttl)
if !info.Updated.Before(cutoff) {
continue
}
if err := al.sessions.DeleteSession(info.Key); err != nil {
logger.WarnCF("agent", "Failed to delete expired session", map[string]interface{}{
"session_key": info.Key,
"error": err.Error(),
})
} else {
logger.InfoCF("agent", "Deleted expired session", map[string]interface{}{
"session_key": info.Key,
})
}
}
}
func (al *AgentLoop) handleCommand(ctx context.Context, msg bus.InboundMessage) (string, bool) {
content := strings.TrimSpace(msg.Content)
if !strings.HasPrefix(content, "/") {

View file

@ -11,9 +11,10 @@ type InboundMessage struct {
}
type OutboundMessage struct {
Channel string `json:"channel"`
ChatID string `json:"chat_id"`
Content string `json:"content"`
Channel string `json:"channel"`
ChatID string `json:"chat_id"`
Content string `json:"content"`
Media []string `json:"media,omitempty"`
}
type MessageHandler func(InboundMessage) error

View file

@ -176,7 +176,7 @@ func (m *Manager) initChannels() error {
}
}
if m.config.Channels.XMPP.Enabled && m.config.Channels.XMPP.Server != "" {
if m.config.Channels.XMPP.Enabled && m.config.Channels.XMPP.JID != "" && m.config.Channels.XMPP.Password != "" {
logger.DebugC("channels", "Attempting to initialize XMPP channel")
xmppCh, err := NewXMPPChannel(m.config.Channels.XMPP, m.bus)
if err != nil {

View file

@ -5,337 +5,562 @@ import (
"crypto/tls"
"encoding/xml"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"mellium.im/sasl"
"mellium.im/xmlstream"
"mellium.im/xmpp"
"mellium.im/xmpp/disco"
"mellium.im/xmpp/disco/items"
"mellium.im/xmpp/jid"
"mellium.im/xmpp/mux"
"mellium.im/xmpp/stanza"
"mellium.im/xmpp/upload"
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/logger"
"github.com/sipeed/picoclaw/pkg/utils"
)
type XMPPChannel struct {
*BaseChannel
config config.XMPPConfig
session *xmpp.Session
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
joinedRooms map[string]bool
config config.XMPPConfig
session *xmpp.Session
ctx context.Context
cancel context.CancelFunc
httpClient *http.Client
uploadMu sync.Mutex
uploadJID jid.JID
lastMsgMu sync.Mutex
lastFromBare string
lastContent string
lastTime time.Time
}
func NewXMPPChannel(cfg config.XMPPConfig, bus *bus.MessageBus) (*XMPPChannel, error) {
base := NewBaseChannel("xmpp", cfg, bus, cfg.AllowFrom)
func NewXMPPChannel(cfg config.XMPPConfig, messageBus *bus.MessageBus) (*XMPPChannel, error) {
if cfg.JID == "" {
return nil, fmt.Errorf("xmpp jid is required")
}
if cfg.Password == "" {
return nil, fmt.Errorf("xmpp password is required")
}
base := NewBaseChannel("xmpp", cfg, messageBus, cfg.AllowFrom)
return &XMPPChannel{
BaseChannel: base,
config: cfg,
joinedRooms: make(map[string]bool),
httpClient: newHTTPClient(),
}, nil
}
func (c *XMPPChannel) Start(ctx context.Context) error {
if !c.config.Enabled {
return fmt.Errorf("xmpp channel disabled")
}
if c.config.Server == "" || c.config.Domain == "" || c.config.Username == "" {
return fmt.Errorf("xmpp server, domain and username must be configured")
if c.IsRunning() {
return nil
}
j, err := jid.Parse(fmt.Sprintf("%s@%s", c.config.Username, c.config.Domain))
j, err := jid.Parse(c.config.JID)
if err != nil {
return fmt.Errorf("invalid jid: %w", err)
return fmt.Errorf("invalid xmpp jid: %w", err)
}
dialCtx, cancel := context.WithCancel(ctx)
c.ctx = dialCtx
c.cancel = cancel
logger.InfoCF("xmpp", "Connecting XMPP client", map[string]interface{}{
"jid": j.String(),
})
features := []xmpp.StreamFeature{}
if c.config.UseTLS {
features = append(features, xmpp.StartTLS(&tls.Config{
InsecureSkipVerify: c.config.InsecureSkipVerify,
ServerName: c.config.Domain,
}))
}
if c.config.Password != "" {
features = append(features, xmpp.SASL("", c.config.Password, sasl.Plain))
}
features = append(features, xmpp.BindResource())
session, err := xmpp.DialClientSession(dialCtx, j, features...)
session, err := xmpp.DialClientSession(
ctx,
j,
xmpp.StartTLS(&tls.Config{
ServerName: j.Domain().String(),
MinVersion: tls.VersionTLS12,
}),
xmpp.SASL("", c.config.Password, sasl.ScramSha256Plus, sasl.ScramSha1Plus, sasl.ScramSha256, sasl.ScramSha1, sasl.Plain),
xmpp.BindResource(),
)
if err != nil {
cancel()
return fmt.Errorf("failed to dial xmpp: %w", err)
return fmt.Errorf("failed to establish XMPP session: %w", err)
}
c.mu.Lock()
handler := mux.MessageHandlerFunc(func(msg stanza.Message, t xmlstream.TokenReadEncoder) error {
return c.handleIncomingMessage(msg, t)
})
m := mux.New(
stanza.NSClient,
mux.Message(stanza.ChatMessage, xml.Name{}, handler),
mux.Message(stanza.MessageType(""), xml.Name{}, handler),
)
c.session = session
c.mu.Unlock()
c.ctx, c.cancel = context.WithCancel(context.Background())
for _, room := range c.config.Rooms {
if room == "" {
continue
}
go c.joinRoom(room)
if err := c.sendInitialPresence(); err != nil {
logger.WarnCF("xmpp", "Failed to send initial presence", map[string]interface{}{
"error": err.Error(),
})
}
c.setRunning(true)
go c.readLoop()
go func() {
err := session.Serve(m)
if err != nil {
logger.ErrorCF("xmpp", "XMPP session ended with error", map[string]interface{}{
"error": err.Error(),
})
} else {
logger.InfoC("xmpp", "XMPP session ended")
}
c.setRunning(false)
}()
return nil
}
func (c *XMPPChannel) Stop(ctx context.Context) error {
c.setRunning(false)
c.mu.Lock()
if !c.IsRunning() {
return nil
}
if c.cancel != nil {
c.cancel()
}
if c.session != nil {
_ = c.session.Close()
if err := c.session.Close(); err != nil {
logger.WarnCF("xmpp", "Error closing XMPP session", map[string]interface{}{
"error": err.Error(),
})
}
}
c.mu.Unlock()
c.setRunning(false)
logger.InfoC("xmpp", "XMPP channel stopped")
return nil
}
func (c *XMPPChannel) Send(ctx context.Context, msg bus.OutboundMessage) error {
if !c.IsRunning() {
if !c.IsRunning() || c.session == nil {
return fmt.Errorf("xmpp channel not running")
}
c.mu.Lock()
session := c.session
c.mu.Unlock()
if session == nil {
return fmt.Errorf("xmpp session not ready")
}
toJID, err := jid.Parse(msg.ChatID)
to, err := jid.Parse(msg.ChatID)
if err != nil {
return fmt.Errorf("invalid chat id: %w", err)
return fmt.Errorf("invalid xmpp chat id: %w", err)
}
msgType := stanza.ChatMessage
if c.isRoomJID(toJID) {
msgType = stanza.GroupChatMessage
}
content := strings.TrimSpace(msg.Content)
message := stanza.Message{
To: toJID,
Type: msgType,
}
var mediaLinks []string
var inlineParts []string
if len(msg.Media) > 0 {
uploadJID, discoverErr := c.discoverUploadService(ctx)
if discoverErr != nil {
logger.ErrorCF("xmpp", "Failed to discover XEP-0363 upload service", map[string]interface{}{
"error": discoverErr.Error(),
})
}
type outgoing struct {
stanza.Message
Body string `xml:"body"`
Request *struct {
XMLName xml.Name `xml:"urn:xmpp:receipts request"`
} `xml:"request,omitempty"`
}
for _, path := range msg.Media {
if discoverErr == nil {
link, err := c.uploadFile(ctx, uploadJID, path)
if err == nil && link != "" {
mediaLinks = append(mediaLinks, link)
continue
}
if err != nil {
logger.ErrorCF("xmpp", "Failed to upload media file", map[string]interface{}{
"path": path,
"error": err.Error(),
})
}
}
o := outgoing{
Message: message,
Body: msg.Content,
}
if c.config.EnableReceipts {
o.Request = &struct {
XMLName xml.Name `xml:"urn:xmpp:receipts request"`
}{
XMLName: xml.Name{Space: "urn:xmpp:receipts", Local: "request"},
inlineContent, err := c.readSmallFile(path, 32*1024)
if err != nil {
logger.ErrorCF("xmpp", "Failed to inline media file", map[string]interface{}{
"path": path,
"error": err.Error(),
})
continue
}
inlineParts = append(inlineParts, fmt.Sprintf("文件 %s:\n%s", filepath.Base(path), inlineContent))
}
}
if err := session.Encode(ctx, o); err != nil {
return fmt.Errorf("failed to send xmpp message: %w", err)
if len(inlineParts) > 0 {
inlineText := strings.Join(inlineParts, "\n\n")
if content == "" {
content = inlineText
} else {
content = content + "\n\n" + inlineText
}
}
if len(mediaLinks) > 0 {
body := mediaLinks[0]
desc := content
return c.sendChatMessage(to, body, desc, mediaLinks)
}
if content == "" {
return nil
}
return c.sendChatMessage(to, content, "", nil)
}
func (c *XMPPChannel) sendInitialPresence() error {
return c.sendStanza(stanza.Presence{}.Wrap(nil))
}
func (c *XMPPChannel) sendChatMessage(to jid.JID, body string, desc string, mediaLinks []string) error {
bodyElem := xmlstream.Wrap(
xmlstream.Token(xml.CharData([]byte(body))),
xml.StartElement{Name: xml.Name{Local: "body"}},
)
children := []xml.TokenReader{bodyElem}
for _, link := range mediaLinks {
urlElem := xmlstream.Wrap(
xmlstream.Token(xml.CharData([]byte(link))),
xml.StartElement{Name: xml.Name{Local: "url"}},
)
var inner xml.TokenReader = urlElem
if desc != "" {
descElem := xmlstream.Wrap(
xmlstream.Token(xml.CharData([]byte(desc))),
xml.StartElement{Name: xml.Name{Local: "desc"}},
)
inner = xmlstream.MultiReader(urlElem, descElem)
}
xElem := xmlstream.Wrap(
inner,
xml.StartElement{
Name: xml.Name{Local: "x"},
Attr: []xml.Attr{
{Name: xml.Name{Local: "xmlns"}, Value: "jabber:x:oob"},
},
},
)
children = append(children, xElem)
}
var payload xml.TokenReader
if len(children) == 1 {
payload = children[0]
} else {
payload = xmlstream.MultiReader(children...)
}
st := stanza.Message{
Type: stanza.ChatMessage,
To: to,
}
return c.sendStanza(st.Wrap(payload))
}
func (c *XMPPChannel) sendStanza(r xml.TokenReader) error {
if c.session == nil {
return fmt.Errorf("xmpp session not initialized")
}
w := c.session.TokenWriter()
defer w.Close()
if _, err := xmlstream.Copy(w, r); err != nil {
return err
}
type flusher interface {
Flush() error
}
if f, ok := w.(flusher); ok {
return f.Flush()
}
return nil
}
func (c *XMPPChannel) readLoop() {
c.mu.Lock()
session := c.session
c.mu.Unlock()
if session == nil {
return
func (c *XMPPChannel) handleIncomingMessage(msg stanza.Message, t xmlstream.TokenReadEncoder) error {
var payload struct {
Body string `xml:"body"`
}
type inbound struct {
stanza.Message
Body string `xml:"body"`
Request *struct {
XMLName xml.Name `xml:"urn:xmpp:receipts request"`
} `xml:"request"`
d := xml.NewTokenDecoder(t)
if err := d.Decode(&payload); err != nil {
return err
}
err := session.Serve(xmpp.HandlerFunc(func(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
if start.Name.Local != "message" {
return nil
}
var msg inbound
dec := xml.NewTokenDecoder(t)
if err := dec.DecodeElement(&msg, start); err != nil {
logger.ErrorCF("xmpp", "decode message error", map[string]interface{}{
"error": err.Error(),
})
return nil
}
if msg.Body == "" {
return nil
}
senderID := c.buildSenderID(msg.From)
if !c.IsAllowed(senderID) {
return nil
}
chatID := c.buildChatID(msg.Message)
if chatID == "" {
return nil
}
metadata := map[string]string{}
if msg.ID != "" {
metadata["xmpp_id"] = msg.ID
}
if msg.Type == stanza.GroupChatMessage {
metadata["xmpp_type"] = "groupchat"
} else {
metadata["xmpp_type"] = "chat"
}
if msg.Request != nil && msg.ID != "" && c.config.EnableReceipts {
go c.sendReceipt(msg.Message)
}
c.HandleMessage(senderID, chatID, msg.Body, nil, metadata)
content := strings.TrimSpace(payload.Body)
if content == "" {
return nil
}))
if err != nil && c.ctx.Err() == nil {
logger.ErrorCF("xmpp", "session serve error", map[string]interface{}{
"error": err.Error(),
})
}
fromBare := msg.From.Bare().String()
chatID := msg.From.String()
c.lastMsgMu.Lock()
if fromBare == c.lastFromBare && content == c.lastContent && time.Since(c.lastTime) < 2*time.Second {
c.lastMsgMu.Unlock()
return nil
}
c.lastFromBare = fromBare
c.lastContent = content
c.lastTime = time.Now()
c.lastMsgMu.Unlock()
logger.DebugCF("xmpp", "Received message", map[string]interface{}{
"from": chatID,
"from_bare": fromBare,
"preview": utils.Truncate(content, 80),
})
c.HandleMessage(fromBare, chatID, content, nil, map[string]string{
"stanza_type": "message",
"from_full": chatID,
})
return nil
}
func (c *XMPPChannel) sendReceipt(m stanza.Message) {
c.mu.Lock()
session := c.session
c.mu.Unlock()
if session == nil {
return
func (c *XMPPChannel) discoverUploadService(ctx context.Context) (jid.JID, error) {
c.uploadMu.Lock()
defer c.uploadMu.Unlock()
if !c.uploadJID.Equal(jid.JID{}) {
return c.uploadJID, nil
}
type receipt struct {
stanza.Message
Received struct {
XMLName xml.Name `xml:"urn:xmpp:receipts received"`
ID string `xml:"id,attr"`
} `xml:"received"`
}
r := receipt{
Message: stanza.Message{
To: m.From,
Type: m.Type,
},
}
r.Received.ID = m.ID
_ = session.Encode(context.Background(), r)
}
func (c *XMPPChannel) buildSenderID(j jid.JID) string {
bare := j.Bare().String()
resource := j.Resourcepart()
if resource == "" {
return bare
}
return bare + "|" + resource
}
func (c *XMPPChannel) buildChatID(m stanza.Message) string {
if m.Type == stanza.GroupChatMessage {
return m.From.Bare().String()
}
return m.From.Bare().String()
}
func (c *XMPPChannel) isRoomJID(j jid.JID) bool {
for _, room := range c.config.Rooms {
if room == "" {
continue
}
if strings.EqualFold(j.Bare().String(), room) {
return true
if c.config.UploadDomain != "" {
j, err := jid.Parse(c.config.UploadDomain)
if err == nil {
c.uploadJID = j
return c.uploadJID, nil
}
}
return false
}
func (c *XMPPChannel) effectiveResource() string {
if strings.TrimSpace(c.config.Resource) != "" {
return c.config.Resource
}
return "picoclaw"
}
func (c *XMPPChannel) joinRoom(room string) {
c.mu.Lock()
session := c.session
ctx := c.ctx
c.mu.Unlock()
if session == nil || ctx == nil {
return
if c.session == nil {
return jid.JID{}, fmt.Errorf("xmpp session not initialized")
}
roomJID, err := jid.Parse(room + "/" + c.roomNickname())
userJID, err := jid.Parse(c.config.JID)
if err != nil {
logger.ErrorCF("xmpp", "invalid room jid", map[string]interface{}{
"room": room,
"error": err.Error(),
})
return
return jid.JID{}, fmt.Errorf("invalid xmpp jid in config: %w", err)
}
domain := userJID.Domain()
info, err := disco.GetInfo(ctx, "", domain, c.session)
if err == nil {
for _, f := range info.Features {
if f.Var == upload.NS {
c.uploadJID = domain
logger.InfoCF("xmpp", "Discovered HTTP upload support on server domain", map[string]interface{}{
"jid": domain.String(),
})
return c.uploadJID, nil
}
}
}
type mucPresence struct {
stanza.Presence
X struct {
XMLName xml.Name `xml:"http://jabber.org/protocol/muc x"`
} `xml:"x"`
var found jid.JID
err = disco.WalkItem(ctx, items.Item{JID: domain}, c.session, func(level int, item items.Item, walkErr error) error {
if walkErr != nil {
return nil
}
info, err := disco.GetInfo(ctx, "", item.JID, c.session)
if err != nil {
return nil
}
for _, f := range info.Features {
if f.Var == upload.NS {
found = item.JID
return fmt.Errorf("found")
}
}
return nil
})
if err != nil && err.Error() != "found" {
return jid.JID{}, fmt.Errorf("service discovery failed: %w", err)
}
p := mucPresence{
Presence: stanza.Presence{
To: roomJID,
if found.Equal(jid.JID{}) {
return jid.JID{}, fmt.Errorf("no XEP-0363 upload service found via disco")
}
c.uploadJID = found
logger.InfoCF("xmpp", "Discovered HTTP upload service via disco", map[string]interface{}{
"jid": found.String(),
})
return c.uploadJID, nil
}
func (c *XMPPChannel) uploadFile(ctx context.Context, uploadJID jid.JID, path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("open file: %w", err)
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return "", fmt.Errorf("stat file: %w", err)
}
size := info.Size()
if size <= 0 {
return "", fmt.Errorf("file is empty")
}
buffer := make([]byte, 512)
n, _ := f.Read(buffer)
if _, err := f.Seek(0, 0); err != nil {
return "", fmt.Errorf("seek file: %w", err)
}
contentType := http.DetectContentType(buffer[:n])
if contentType == "" {
contentType = "application/octet-stream"
}
file := upload.File{
Name: filepath.Base(path),
Size: int(size),
Type: contentType,
}
slot, err := upload.GetSlot(ctx, file, uploadJID, c.session)
if err != nil {
return "", fmt.Errorf("get upload slot: %w", err)
}
logger.InfoCF("xmpp", "XEP-0363 upload slot acquired", map[string]interface{}{
"put_url": func() string {
if slot.PutURL != nil {
return slot.PutURL.String()
}
return ""
}(),
"get_url": func() string {
if slot.GetURL != nil {
return slot.GetURL.String()
}
return ""
}(),
"headers": slot.Header,
"mime": contentType,
"size": size,
"filename": filepath.Base(path),
})
req, err := slot.Put(ctx, f)
if err != nil {
return "", fmt.Errorf("build put request: %w", err)
}
req.ContentLength = size
if req.Header == nil {
req.Header = make(http.Header)
}
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", contentType)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("http put: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
bodyText := strings.TrimSpace(string(snippet))
if bodyText != "" {
return "", fmt.Errorf("upload failed with status %s: %s", resp.Status, bodyText)
}
return "", fmt.Errorf("upload failed with status %s", resp.Status)
}
if slot.GetURL == nil {
return "", fmt.Errorf("no download URL returned for upload slot")
}
return slot.GetURL.String(), nil
}
func (c *XMPPChannel) readSmallFile(path string, maxSize int64) (string, error) {
info, err := os.Stat(path)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() {
return "", fmt.Errorf("not a regular file")
}
if info.Size() <= 0 {
return "", fmt.Errorf("file is empty")
}
if info.Size() > maxSize {
return "", fmt.Errorf("file too large to inline")
}
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(data), nil
}
func newHTTPClient() *http.Client {
dialer := &net.Dialer{}
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := dialer.DialContext(ctx, network, addr)
if err == nil {
return conn, nil
}
if !strings.Contains(err.Error(), "no such host") {
return nil, err
}
host, port, splitErr := net.SplitHostPort(addr)
if splitErr != nil {
return nil, err
}
parts := strings.SplitN(host, ".", 2)
if len(parts) != 2 || parts[1] == "" {
return nil, err
}
fallbackHost := parts[1]
return dialer.DialContext(ctx, network, net.JoinHostPort(fallbackHost, port))
},
}
if err := session.Encode(ctx, p); err != nil {
logger.ErrorCF("xmpp", "join room failed", map[string]interface{}{
"room": room,
"error": err.Error(),
})
return
return &http.Client{
Timeout: 60 * time.Second,
Transport: transport,
}
c.mu.Lock()
c.joinedRooms[roomJID.Bare().String()] = true
c.mu.Unlock()
}
func (c *XMPPChannel) roomNickname() string {
n := strings.TrimSpace(c.config.Nickname)
if n == "" {
return "PicoClaw"
}
return n
}

View file

@ -66,6 +66,7 @@ type AgentDefaults struct {
MaxTokens int `json:"max_tokens" env:"PICOCLAW_AGENTS_DEFAULTS_MAX_TOKENS"`
Temperature float64 `json:"temperature" env:"PICOCLAW_AGENTS_DEFAULTS_TEMPERATURE"`
MaxToolIterations int `json:"max_tool_iterations" env:"PICOCLAW_AGENTS_DEFAULTS_MAX_TOOL_ITERATIONS"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_AGENTS_DEFAULTS_SESSION_TTL"`
}
type ChannelsConfig struct {
@ -83,16 +84,18 @@ type ChannelsConfig struct {
}
type WhatsAppConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_WHATSAPP_ENABLED"`
BridgeURL string `json:"bridge_url" env:"PICOCLAW_CHANNELS_WHATSAPP_BRIDGE_URL"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_WHATSAPP_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_WHATSAPP_ENABLED"`
BridgeURL string `json:"bridge_url" env:"PICOCLAW_CHANNELS_WHATSAPP_BRIDGE_URL"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_WHATSAPP_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_WHATSAPP_SESSION_TTL"`
}
type TelegramConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_TELEGRAM_ENABLED"`
Token string `json:"token" env:"PICOCLAW_CHANNELS_TELEGRAM_TOKEN"`
Proxy string `json:"proxy" env:"PICOCLAW_CHANNELS_TELEGRAM_PROXY"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_TELEGRAM_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_TELEGRAM_ENABLED"`
Token string `json:"token" env:"PICOCLAW_CHANNELS_TELEGRAM_TOKEN"`
Proxy string `json:"proxy" env:"PICOCLAW_CHANNELS_TELEGRAM_PROXY"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_TELEGRAM_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_TELEGRAM_SESSION_TTL"`
}
type FeishuConfig struct {
@ -102,26 +105,30 @@ type FeishuConfig struct {
EncryptKey string `json:"encrypt_key" env:"PICOCLAW_CHANNELS_FEISHU_ENCRYPT_KEY"`
VerificationToken string `json:"verification_token" env:"PICOCLAW_CHANNELS_FEISHU_VERIFICATION_TOKEN"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_FEISHU_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_FEISHU_SESSION_TTL"`
}
type DiscordConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_DISCORD_ENABLED"`
Token string `json:"token" env:"PICOCLAW_CHANNELS_DISCORD_TOKEN"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_DISCORD_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_DISCORD_ENABLED"`
Token string `json:"token" env:"PICOCLAW_CHANNELS_DISCORD_TOKEN"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_DISCORD_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_DISCORD_SESSION_TTL"`
}
type MaixCamConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_MAIXCAM_ENABLED"`
Host string `json:"host" env:"PICOCLAW_CHANNELS_MAIXCAM_HOST"`
Port int `json:"port" env:"PICOCLAW_CHANNELS_MAIXCAM_PORT"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_MAIXCAM_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_MAIXCAM_ENABLED"`
Host string `json:"host" env:"PICOCLAW_CHANNELS_MAIXCAM_HOST"`
Port int `json:"port" env:"PICOCLAW_CHANNELS_MAIXCAM_PORT"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_MAIXCAM_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_MAIXCAM_SESSION_TTL"`
}
type QQConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_QQ_ENABLED"`
AppID string `json:"app_id" env:"PICOCLAW_CHANNELS_QQ_APP_ID"`
AppSecret string `json:"app_secret" env:"PICOCLAW_CHANNELS_QQ_APP_SECRET"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_QQ_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_QQ_ENABLED"`
AppID string `json:"app_id" env:"PICOCLAW_CHANNELS_QQ_APP_ID"`
AppSecret string `json:"app_secret" env:"PICOCLAW_CHANNELS_QQ_APP_SECRET"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_QQ_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_QQ_SESSION_TTL"`
}
type DingTalkConfig struct {
@ -129,13 +136,15 @@ type DingTalkConfig struct {
ClientID string `json:"client_id" env:"PICOCLAW_CHANNELS_DINGTALK_CLIENT_ID"`
ClientSecret string `json:"client_secret" env:"PICOCLAW_CHANNELS_DINGTALK_CLIENT_SECRET"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_DINGTALK_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_DINGTALK_SESSION_TTL"`
}
type SlackConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_SLACK_ENABLED"`
BotToken string `json:"bot_token" env:"PICOCLAW_CHANNELS_SLACK_BOT_TOKEN"`
AppToken string `json:"app_token" env:"PICOCLAW_CHANNELS_SLACK_APP_TOKEN"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_SLACK_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_SLACK_ENABLED"`
BotToken string `json:"bot_token" env:"PICOCLAW_CHANNELS_SLACK_BOT_TOKEN"`
AppToken string `json:"app_token" env:"PICOCLAW_CHANNELS_SLACK_APP_TOKEN"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_SLACK_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_SLACK_SESSION_TTL"`
}
type LINEConfig struct {
@ -146,6 +155,7 @@ type LINEConfig struct {
WebhookPort int `json:"webhook_port" env:"PICOCLAW_CHANNELS_LINE_WEBHOOK_PORT"`
WebhookPath string `json:"webhook_path" env:"PICOCLAW_CHANNELS_LINE_WEBHOOK_PATH"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_LINE_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_LINE_SESSION_TTL"`
}
type OneBotConfig struct {
@ -155,21 +165,17 @@ type OneBotConfig struct {
ReconnectInterval int `json:"reconnect_interval" env:"PICOCLAW_CHANNELS_ONEBOT_RECONNECT_INTERVAL"`
GroupTriggerPrefix []string `json:"group_trigger_prefix" env:"PICOCLAW_CHANNELS_ONEBOT_GROUP_TRIGGER_PREFIX"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_ONEBOT_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_ONEBOT_SESSION_TTL"`
}
type XMPPConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_XMPP_ENABLED"`
Server string `json:"server" env:"PICOCLAW_CHANNELS_XMPP_SERVER"`
Domain string `json:"domain" env:"PICOCLAW_CHANNELS_XMPP_DOMAIN"`
Username string `json:"username" env:"PICOCLAW_CHANNELS_XMPP_USERNAME"`
Password string `json:"password" env:"PICOCLAW_CHANNELS_XMPP_PASSWORD"`
Resource string `json:"resource" env:"PICOCLAW_CHANNELS_XMPP_RESOURCE"`
Rooms []string `json:"rooms" env:"PICOCLAW_CHANNELS_XMPP_ROOMS"`
Nickname string `json:"nickname" env:"PICOCLAW_CHANNELS_XMPP_NICKNAME"`
UseTLS bool `json:"use_tls" env:"PICOCLAW_CHANNELS_XMPP_USE_TLS"`
InsecureSkipVerify bool `json:"insecure_skip_verify" env:"PICOCLAW_CHANNELS_XMPP_INSECURE_SKIP_VERIFY"`
EnableReceipts bool `json:"enable_receipts" env:"PICOCLAW_CHANNELS_XMPP_ENABLE_RECEIPTS"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_XMPP_ALLOW_FROM"`
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_XMPP_ENABLED"`
JID string `json:"jid" env:"PICOCLAW_CHANNELS_XMPP_JID"`
Password string `json:"password" env:"PICOCLAW_CHANNELS_XMPP_PASSWORD"`
Server string `json:"server" env:"PICOCLAW_CHANNELS_XMPP_SERVER"`
UploadDomain string `json:"upload_domain" env:"PICOCLAW_CHANNELS_XMPP_UPLOAD_DOMAIN"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_XMPP_ALLOW_FROM"`
SessionTTL string `json:"session_ttl" env:"PICOCLAW_CHANNELS_XMPP_SESSION_TTL"`
}
type HeartbeatConfig struct {
@ -222,13 +228,25 @@ type DuckDuckGoConfig struct {
MaxResults int `json:"max_results" env:"PICOCLAW_TOOLS_WEB_DUCKDUCKGO_MAX_RESULTS"`
}
type PerplexityConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_TOOLS_WEB_PERPLEXITY_ENABLED"`
APIKey string `json:"api_key" env:"PICOCLAW_TOOLS_WEB_PERPLEXITY_API_KEY"`
MaxResults int `json:"max_results" env:"PICOCLAW_TOOLS_WEB_PERPLEXITY_MAX_RESULTS"`
}
type WebToolsConfig struct {
Brave BraveConfig `json:"brave"`
DuckDuckGo DuckDuckGoConfig `json:"duckduckgo"`
Perplexity PerplexityConfig `json:"perplexity"`
}
type CronToolsConfig struct {
ExecTimeoutMinutes int `json:"exec_timeout_minutes" env:"PICOCLAW_TOOLS_CRON_EXEC_TIMEOUT_MINUTES"` // 0 means no timeout
}
type ToolsConfig struct {
Web WebToolsConfig `json:"web"`
Web WebToolsConfig `json:"web"`
Cron CronToolsConfig `json:"cron"`
}
func DefaultConfig() *Config {
@ -242,18 +260,21 @@ func DefaultConfig() *Config {
MaxTokens: 8192,
Temperature: 0.7,
MaxToolIterations: 20,
SessionTTL: "",
},
},
Channels: ChannelsConfig{
WhatsApp: WhatsAppConfig{
Enabled: false,
BridgeURL: "ws://localhost:3001",
AllowFrom: FlexibleStringSlice{},
Enabled: false,
BridgeURL: "ws://localhost:3001",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
Telegram: TelegramConfig{
Enabled: false,
Token: "",
AllowFrom: FlexibleStringSlice{},
Enabled: false,
Token: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
Feishu: FeishuConfig{
Enabled: false,
@ -262,35 +283,41 @@ func DefaultConfig() *Config {
EncryptKey: "",
VerificationToken: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
Discord: DiscordConfig{
Enabled: false,
Token: "",
AllowFrom: FlexibleStringSlice{},
Enabled: false,
Token: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
MaixCam: MaixCamConfig{
Enabled: false,
Host: "0.0.0.0",
Port: 18790,
AllowFrom: FlexibleStringSlice{},
Enabled: false,
Host: "0.0.0.0",
Port: 18790,
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
QQ: QQConfig{
Enabled: false,
AppID: "",
AppSecret: "",
AllowFrom: FlexibleStringSlice{},
Enabled: false,
AppID: "",
AppSecret: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
DingTalk: DingTalkConfig{
Enabled: false,
ClientID: "",
ClientSecret: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
Slack: SlackConfig{
Enabled: false,
BotToken: "",
AppToken: "",
AllowFrom: FlexibleStringSlice{},
Enabled: false,
BotToken: "",
AppToken: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
LINE: LINEConfig{
Enabled: false,
@ -300,6 +327,7 @@ func DefaultConfig() *Config {
WebhookPort: 18791,
WebhookPath: "/webhook/line",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
OneBot: OneBotConfig{
Enabled: false,
@ -308,20 +336,16 @@ func DefaultConfig() *Config {
ReconnectInterval: 5,
GroupTriggerPrefix: []string{},
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
XMPP: XMPPConfig{
Enabled: false,
Server: "",
Domain: "",
Username: "",
Password: "",
Resource: "picoclaw",
Rooms: []string{},
Nickname: "PicoClaw",
UseTLS: true,
InsecureSkipVerify: false,
EnableReceipts: true,
AllowFrom: FlexibleStringSlice{},
Enabled: false,
JID: "",
Password: "",
Server: "",
UploadDomain: "",
AllowFrom: FlexibleStringSlice{},
SessionTTL: "false",
},
},
Providers: ProvidersConfig{
@ -351,6 +375,14 @@ func DefaultConfig() *Config {
Enabled: true,
MaxResults: 5,
},
Perplexity: PerplexityConfig{
Enabled: false,
APIKey: "",
MaxResults: 5,
},
},
Cron: CronToolsConfig{
ExecTimeoutMinutes: 5, // default 5 minutes for LLM operations
},
},
Heartbeat: HeartbeatConfig{

View file

@ -201,18 +201,18 @@ func ConvertConfig(data map[string]interface{}) (*config.Config, []string, error
case "xmpp":
cfg.Channels.XMPP.Enabled = enabled
cfg.Channels.XMPP.AllowFrom = allowFrom
if v, ok := getString(cMap, "server"); ok {
cfg.Channels.XMPP.Server = v
}
if v, ok := getString(cMap, "domain"); ok {
cfg.Channels.XMPP.Domain = v
}
if v, ok := getString(cMap, "username"); ok {
cfg.Channels.XMPP.Username = v
if v, ok := getString(cMap, "jid"); ok {
cfg.Channels.XMPP.JID = v
}
if v, ok := getString(cMap, "password"); ok {
cfg.Channels.XMPP.Password = v
}
if v, ok := getString(cMap, "server"); ok {
cfg.Channels.XMPP.Server = v
}
if v, ok := getString(cMap, "upload_domain"); ok {
cfg.Channels.XMPP.UploadDomain = v
}
}
}
}
@ -291,6 +291,9 @@ func MergeConfig(existing, incoming *config.Config) *config.Config {
if !existing.Channels.MaixCam.Enabled && incoming.Channels.MaixCam.Enabled {
existing.Channels.MaixCam = incoming.Channels.MaixCam
}
if !existing.Channels.XMPP.Enabled && incoming.Channels.XMPP.Enabled {
existing.Channels.XMPP = incoming.Channels.XMPP
}
if existing.Tools.Web.Brave.APIKey == "" {
existing.Tools.Web.Brave = incoming.Tools.Web.Brave

View file

@ -19,6 +19,12 @@ type Session struct {
Updated time.Time `json:"updated"`
}
type SessionInfo struct {
Key string
Created time.Time
Updated time.Time
}
type SessionManager struct {
sessions map[string]*Session
mu sync.RWMutex
@ -145,6 +151,21 @@ func (sm *SessionManager) TruncateHistory(key string, keepLast int) {
session.Updated = time.Now()
}
func (sm *SessionManager) ListSessions() []SessionInfo {
sm.mu.RLock()
defer sm.mu.RUnlock()
infos := make([]SessionInfo, 0, len(sm.sessions))
for _, s := range sm.sessions {
infos = append(infos, SessionInfo{
Key: s.Key,
Created: s.Created,
Updated: s.Updated,
})
}
return infos
}
// sanitizeFilename converts a session key into a cross-platform safe filename.
// Session keys use "channel:chatID" (e.g. "telegram:123456") but ':' is the
// volume separator on Windows, so filepath.Base would misinterpret the key.
@ -154,6 +175,29 @@ func sanitizeFilename(key string) string {
return strings.ReplaceAll(key, ":", "_")
}
func (sm *SessionManager) DeleteSession(key string) error {
sm.mu.Lock()
defer sm.mu.Unlock()
delete(sm.sessions, key)
if sm.storage == "" {
return nil
}
filename := sanitizeFilename(key)
if filename == "." || !filepath.IsLocal(filename) || strings.ContainsAny(filename, `/\`) {
return os.ErrInvalid
}
sessionPath := filepath.Join(sm.storage, filename+".json")
err := os.Remove(sessionPath)
if err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
func (sm *SessionManager) Save(key string) error {
if sm.storage == "" {
return nil

View file

@ -28,12 +28,15 @@ type CronTool struct {
}
// NewCronTool creates a new CronTool
func NewCronTool(cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string, restrict bool) *CronTool {
// execTimeout: 0 means no timeout, >0 sets the timeout duration
func NewCronTool(cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string, restrict bool, execTimeout time.Duration) *CronTool {
execTool := NewExecTool(workspace, restrict)
execTool.SetTimeout(execTimeout) // 0 means no timeout
return &CronTool{
cronService: cronService,
executor: executor,
msgBus: msgBus,
execTool: NewExecTool(workspace, restrict),
execTool: execTool,
}
}

View file

@ -5,7 +5,7 @@ import (
"fmt"
)
type SendCallback func(channel, chatID, content string) error
type SendCallback func(channel, chatID, content string, media []string) error
type MessageTool struct {
sendCallback SendCallback
@ -31,8 +31,8 @@ func (t *MessageTool) Parameters() map[string]interface{} {
"type": "object",
"properties": map[string]interface{}{
"content": map[string]interface{}{
"type": "string",
"description": "The message content to send",
"type": "string",
"description": "The message content to send. When using media, this is the textual message that will be sent together with media links if supported by the channel.",
},
"channel": map[string]interface{}{
"type": "string",
@ -42,6 +42,13 @@ func (t *MessageTool) Parameters() map[string]interface{} {
"type": "string",
"description": "Optional: target chat/user ID",
},
"media": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "string",
},
"description": "Optional: list of local file paths to send as media. Channels that support uploads (for example XMPP with XEP-0363) can upload these files and include download links in the final message.",
},
},
"required": []string{"content"},
}
@ -71,6 +78,17 @@ func (t *MessageTool) Execute(ctx context.Context, args map[string]interface{})
channel, _ := args["channel"].(string)
chatID, _ := args["chat_id"].(string)
var media []string
if rawMedia, ok := args["media"]; ok {
if list, ok := rawMedia.([]interface{}); ok {
for _, item := range list {
if s, ok := item.(string); ok && s != "" {
media = append(media, s)
}
}
}
}
if channel == "" {
channel = t.defaultChannel
}
@ -86,7 +104,7 @@ func (t *MessageTool) Execute(ctx context.Context, args map[string]interface{})
return &ToolResult{ForLLM: "Message sending not configured", IsError: true}
}
if err := t.sendCallback(channel, chatID, content); err != nil {
if err := t.sendCallback(channel, chatID, content, media); err != nil {
return &ToolResult{
ForLLM: fmt.Sprintf("sending message: %v", err),
IsError: true,

View file

@ -11,16 +11,19 @@ func TestMessageTool_Execute_Success(t *testing.T) {
tool.SetContext("test-channel", "test-chat-id")
var sentChannel, sentChatID, sentContent string
tool.SetSendCallback(func(channel, chatID, content string) error {
var sentMedia []string
tool.SetSendCallback(func(channel, chatID, content string, media []string) error {
sentChannel = channel
sentChatID = chatID
sentContent = content
sentMedia = append([]string{}, media...)
return nil
})
ctx := context.Background()
args := map[string]interface{}{
"content": "Hello, world!",
"media": []interface{}{"a.png", "b.jpg"},
}
result := tool.Execute(ctx, args)
@ -35,6 +38,9 @@ func TestMessageTool_Execute_Success(t *testing.T) {
if sentContent != "Hello, world!" {
t.Errorf("Expected content 'Hello, world!', got '%s'", sentContent)
}
if len(sentMedia) != 2 || sentMedia[0] != "a.png" || sentMedia[1] != "b.jpg" {
t.Errorf("Expected media [a.png b.jpg], got %v", sentMedia)
}
// Verify ToolResult meets US-011 criteria:
// - Send success returns SilentResult (Silent=true)
@ -63,7 +69,7 @@ func TestMessageTool_Execute_WithCustomChannel(t *testing.T) {
tool.SetContext("default-channel", "default-chat-id")
var sentChannel, sentChatID string
tool.SetSendCallback(func(channel, chatID, content string) error {
tool.SetSendCallback(func(channel, chatID, content string, media []string) error {
sentChannel = channel
sentChatID = chatID
return nil
@ -99,7 +105,7 @@ func TestMessageTool_Execute_SendFailure(t *testing.T) {
tool.SetContext("test-channel", "test-chat-id")
sendErr := errors.New("network error")
tool.SetSendCallback(func(channel, chatID, content string) error {
tool.SetSendCallback(func(channel, chatID, content string, media []string) error {
return sendErr
})
@ -153,7 +159,7 @@ func TestMessageTool_Execute_NoTargetChannel(t *testing.T) {
tool := NewMessageTool()
// No SetContext called, so defaultChannel and defaultChatID are empty
tool.SetSendCallback(func(channel, chatID, content string) error {
tool.SetSendCallback(func(channel, chatID, content string, media []string) error {
return nil
})

View file

@ -89,7 +89,14 @@ func (t *ExecTool) Execute(ctx context.Context, args map[string]interface{}) *To
return ErrorResult(guardError)
}
cmdCtx, cancel := context.WithTimeout(ctx, t.timeout)
// timeout == 0 means no timeout
var cmdCtx context.Context
var cancel context.CancelFunc
if t.timeout > 0 {
cmdCtx, cancel = context.WithTimeout(ctx, t.timeout)
} else {
cmdCtx, cancel = context.WithCancel(ctx)
}
defer cancel()
var cmd *exec.Cmd

View file

@ -176,6 +176,71 @@ func stripTags(content string) string {
return re.ReplaceAllString(content, "")
}
type PerplexitySearchProvider struct {
apiKey string
}
func (p *PerplexitySearchProvider) Search(ctx context.Context, query string, count int) (string, error) {
searchURL := "https://api.perplexity.ai/chat/completions"
payload := map[string]interface{}{
"model": "sonar",
"messages": []map[string]string{
{"role": "system", "content": "You are a search assistant. Provide concise search results with titles, URLs, and brief descriptions in the following format:\n1. Title\n URL\n Description\n\nDo not add extra commentary."},
{"role": "user", "content": fmt.Sprintf("Search for: %s. Provide up to %d relevant results.", query, count)},
},
"max_tokens": 1000,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", searchURL, strings.NewReader(string(payloadBytes)))
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+p.apiKey)
req.Header.Set("User-Agent", userAgent)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("Perplexity API error: %s", string(body))
}
var searchResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(body, &searchResp); err != nil {
return "", fmt.Errorf("failed to parse response: %w", err)
}
if len(searchResp.Choices) == 0 {
return fmt.Sprintf("No results for: %s", query), nil
}
return fmt.Sprintf("Results for: %s (via Perplexity)\n%s", query, searchResp.Choices[0].Message.Content), nil
}
type WebSearchTool struct {
provider SearchProvider
maxResults int
@ -187,14 +252,22 @@ type WebSearchToolOptions struct {
BraveEnabled bool
DuckDuckGoMaxResults int
DuckDuckGoEnabled bool
PerplexityAPIKey string
PerplexityMaxResults int
PerplexityEnabled bool
}
func NewWebSearchTool(opts WebSearchToolOptions) *WebSearchTool {
var provider SearchProvider
maxResults := 5
// Priority: Brave > DuckDuckGo
if opts.BraveEnabled && opts.BraveAPIKey != "" {
// Priority: Perplexity > Brave > DuckDuckGo
if opts.PerplexityEnabled && opts.PerplexityAPIKey != "" {
provider = &PerplexitySearchProvider{apiKey: opts.PerplexityAPIKey}
if opts.PerplexityMaxResults > 0 {
maxResults = opts.PerplexityMaxResults
}
} else if opts.BraveEnabled && opts.BraveAPIKey != "" {
provider = &BraveSearchProvider{apiKey: opts.BraveAPIKey}
if opts.BraveMaxResults > 0 {
maxResults = opts.BraveMaxResults

298
tream Normal file
View file

@ -0,0 +1,298 @@
SSUUMMMMAARRYY OOFF LLEESSSS CCOOMMMMAANNDDSS
Commands marked with * may be preceded by a number, _N.
Notes in parentheses indicate the behavior if _N is given.
A key preceded by a caret indicates the Ctrl key; thus ^K is ctrl-K.
h H Display this help.
q :q Q :Q ZZ Exit.
---------------------------------------------------------------------------
MMOOVVIINNGG
e ^E j ^N CR * Forward one line (or _N lines).
y ^Y k ^K ^P * Backward one line (or _N lines).
f ^F ^V SPACE * Forward one window (or _N lines).
b ^B ESC-v * Backward one window (or _N lines).
z * Forward one window (and set window to _N).
w * Backward one window (and set window to _N).
ESC-SPACE * Forward one window, but don't stop at end-of-file.
d ^D * Forward one half-window (and set half-window to _N).
u ^U * Backward one half-window (and set half-window to _N).
ESC-) RightArrow * Right one half screen width (or _N positions).
ESC-( LeftArrow * Left one half screen width (or _N positions).
ESC-} ^RightArrow Right to last column displayed.
ESC-{ ^LeftArrow Left to first column.
F Forward forever; like "tail -f".
ESC-F Like F but stop when search pattern is found.
r ^R ^L Repaint screen.
R Repaint screen, discarding buffered input.
---------------------------------------------------
Default "window" is the screen height.
Default "half-window" is half of the screen height.
---------------------------------------------------------------------------
SSEEAARRCCHHIINNGG
/_p_a_t_t_e_r_n * Search forward for (_N-th) matching line.
?_p_a_t_t_e_r_n * Search backward for (_N-th) matching line.
n * Repeat previous search (for _N-th occurrence).
N * Repeat previous search in reverse direction.
ESC-n * Repeat previous search, spanning files.
ESC-N * Repeat previous search, reverse dir. & spanning files.
ESC-u Undo (toggle) search highlighting.
ESC-U Clear search highlighting.
&_p_a_t_t_e_r_n * Display only matching lines.
---------------------------------------------------
A search pattern may begin with one or more of:
^N or ! Search for NON-matching lines.
^E or * Search multiple files (pass thru END OF FILE).
^F or @ Start search at FIRST file (for /) or last file (for ?).
^K Highlight matches, but don't move (KEEP position).
^R Don't use REGULAR EXPRESSIONS.
^S _n Search for match in _n-th parenthesized subpattern.
^W WRAP search if no match found.
---------------------------------------------------------------------------
JJUUMMPPIINNGG
g < ESC-< * Go to first line in file (or line _N).
G > ESC-> * Go to last line in file (or line _N).
p % * Go to beginning of file (or _N percent into file).
t * Go to the (_N-th) next tag.
T * Go to the (_N-th) previous tag.
{ ( [ * Find close bracket } ) ].
} ) ] * Find open bracket { ( [.
ESC-^F _<_c_1_> _<_c_2_> * Find close bracket _<_c_2_>.
ESC-^B _<_c_1_> _<_c_2_> * Find open bracket _<_c_1_>.
---------------------------------------------------
Each "find close bracket" command goes forward to the close bracket
matching the (_N-th) open bracket in the top line.
Each "find open bracket" command goes backward to the open bracket
matching the (_N-th) close bracket in the bottom line.
m_<_l_e_t_t_e_r_> Mark the current top line with <letter>.
M_<_l_e_t_t_e_r_> Mark the current bottom line with <letter>.
'_<_l_e_t_t_e_r_> Go to a previously marked position.
'' Go to the previous position.
^X^X Same as '.
ESC-m_<_l_e_t_t_e_r_> Clear a mark.
---------------------------------------------------
A mark is any upper-case or lower-case letter.
Certain marks are predefined:
^ means beginning of the file
$ means end of the file
---------------------------------------------------------------------------
CCHHAANNGGIINNGG FFIILLEESS
:e [_f_i_l_e] Examine a new file.
^X^V Same as :e.
:n * Examine the (_N-th) next file from the command line.
:p * Examine the (_N-th) previous file from the command line.
:x * Examine the first (or _N-th) file from the command line.
:d Delete the current file from the command line list.
= ^G :f Print current file name.
---------------------------------------------------------------------------
MMIISSCCEELLLLAANNEEOOUUSS CCOOMMMMAANNDDSS
-_<_f_l_a_g_> Toggle a command line option [see OPTIONS below].
--_<_n_a_m_e_> Toggle a command line option, by name.
__<_f_l_a_g_> Display the setting of a command line option.
___<_n_a_m_e_> Display the setting of an option, by name.
+_c_m_d Execute the less cmd each time a new file is examined.
!_c_o_m_m_a_n_d Execute the shell command with $SHELL.
#_c_o_m_m_a_n_d Execute the shell command, expanded like a prompt.
|XX_c_o_m_m_a_n_d Pipe file between current pos & mark XX to shell command.
s _f_i_l_e Save input to a file.
v Edit the current file with $VISUAL or $EDITOR.
V Print version number of "less".
---------------------------------------------------------------------------
OOPPTTIIOONNSS
Most options may be changed either on the command line,
or from within less by using the - or -- command.
Options may be given in one of two forms: either a single
character preceded by a -, or a name preceded by --.
-? ........ --help
Display help (from command line).
-a ........ --search-skip-screen
Search skips current screen.
-A ........ --SEARCH-SKIP-SCREEN
Search starts just after target line.
-b [_N] .... --buffers=[_N]
Number of buffers.
-B ........ --auto-buffers
Don't automatically allocate buffers for pipes.
-c ........ --clear-screen
Repaint by clearing rather than scrolling.
-d ........ --dumb
Dumb terminal.
-D xx_c_o_l_o_r . --color=xx_c_o_l_o_r
Set screen colors.
-e -E .... --quit-at-eof --QUIT-AT-EOF
Quit at end of file.
-f ........ --force
Force open non-regular files.
-F ........ --quit-if-one-screen
Quit if entire file fits on first screen.
-g ........ --hilite-search
Highlight only last match for searches.
-G ........ --HILITE-SEARCH
Don't highlight any matches for searches.
-h [_N] .... --max-back-scroll=[_N]
Backward scroll limit.
-i ........ --ignore-case
Ignore case in searches that do not contain uppercase.
-I ........ --IGNORE-CASE
Ignore case in all searches.
-j [_N] .... --jump-target=[_N]
Screen position of target lines.
-J ........ --status-column
Display a status column at left edge of screen.
-k [_f_i_l_e] . --lesskey-file=[_f_i_l_e]
Use a lesskey file.
-K ........ --quit-on-intr
Exit less in response to ctrl-C.
-L ........ --no-lessopen
Ignore the LESSOPEN environment variable.
-m -M .... --long-prompt --LONG-PROMPT
Set prompt style.
-n ......... --line-numbers
Suppress line numbers in prompts and messages.
-N ......... --LINE-NUMBERS
Display line number at start of each line.
-o [_f_i_l_e] . --log-file=[_f_i_l_e]
Copy to log file (standard input only).
-O [_f_i_l_e] . --LOG-FILE=[_f_i_l_e]
Copy to log file (unconditionally overwrite).
-p [_p_a_t_t_e_r_n] --pattern=[_p_a_t_t_e_r_n]
Start at pattern (from command line).
-P [_p_r_o_m_p_t] --prompt=[_p_r_o_m_p_t]
Define new prompt.
-q -Q .... --quiet --QUIET --silent --SILENT
Quiet the terminal bell.
-r -R .... --raw-control-chars --RAW-CONTROL-CHARS
Output "raw" control characters.
-s ........ --squeeze-blank-lines
Squeeze multiple blank lines.
-S ........ --chop-long-lines
Chop (truncate) long lines rather than wrapping.
-t [_t_a_g] .. --tag=[_t_a_g]
Find a tag.
-T [_t_a_g_s_f_i_l_e] --tag-file=[_t_a_g_s_f_i_l_e]
Use an alternate tags file.
-u -U .... --underline-special --UNDERLINE-SPECIAL
Change handling of backspaces, tabs and carriage returns.
-V ........ --version
Display the version number of "less".
-w ........ --hilite-unread
Highlight first new line after forward-screen.
-W ........ --HILITE-UNREAD
Highlight first new line after any forward movement.
-x [_N[,...]] --tabs=[_N[,...]]
Set tab stops.
-X ........ --no-init
Don't use termcap init/deinit strings.
-y [_N] .... --max-forw-scroll=[_N]
Forward scroll limit.
-z [_N] .... --window=[_N]
Set size of window.
-" [_c[_c]] . --quotes=[_c[_c]]
Set shell quote characters.
-~ ........ --tilde
Don't display tildes after end of file.
-# [_N] .... --shift=[_N]
Set horizontal scroll amount (0 = one half screen width).
--exit-follow-on-close
Exit F command on a pipe when writer closes pipe.
--file-size
Automatically determine the size of the input file.
--follow-name
The F command changes files if the input file is renamed.
--header=[_N[,_M]]
Use N lines and M columns to display file headers.
--incsearch
Search file as each pattern character is typed in.
--intr=_C
Use _C instead of ^X to interrupt a read.
--line-num-width=_N
Set the width of the -N line number field to _N characters.
--modelines=_N
Read _N lines from the input file and look for vim modelines.
--mouse
Enable mouse input.
--no-keypad
Don't send termcap keypad init/deinit strings.
--no-histdups
Remove duplicates from command history.
--no-number-headers
Don't give line numbers to header lines.
--no-search-headers
Don't search in header lines or columns.
--no-vbell
Disable the terminal's visual bell.
--redraw-on-quit
Redraw final screen when quitting.
--rscroll=_C
Set the character used to mark truncated lines.
--save-marks
Retain marks across invocations of less.
--search-options=[EFKNRW-]
Set default options for every search.
--show-preproc-errors
Display a message if preprocessor exits with an error status.
--proc-backspace
Process backspaces for bold/underline.
--SPECIAL-BACKSPACE
Treat backspaces as control characters.
--proc-return
Delete carriage returns before newline.
--SPECIAL-RETURN
Treat carriage returns as control characters.
--proc-tab
Expand tabs to spaces.
--SPECIAL-TAB
Treat tabs as control characters.
--status-col-width=_N
Set the width of the -J status column to _N characters.
--status-line
Highlight or color the entire line containing a mark.
--use-backslash
Subsequent options use backslash as escape char.
--use-color
Enables colored text.
--wheel-lines=_N
Each click of the mouse wheel moves _N lines.
--wordwrap
Wrap lines at spaces.
---------------------------------------------------------------------------
LLIINNEE EEDDIITTIINNGG
These keys can be used to edit text being entered
on the "command line" at the bottom of the screen.
RightArrow ..................... ESC-l ... Move cursor right one character.
LeftArrow ...................... ESC-h ... Move cursor left one character.
ctrl-RightArrow ESC-RightArrow ESC-w ... Move cursor right one word.
ctrl-LeftArrow ESC-LeftArrow ESC-b ... Move cursor left one word.
HOME ........................... ESC-0 ... Move cursor to start of line.
END ............................ ESC-$ ... Move cursor to end of line.
BACKSPACE ................................ Delete char to left of cursor.
DELETE ......................... ESC-x ... Delete char under cursor.
ctrl-BACKSPACE ESC-BACKSPACE ........... Delete word to left of cursor.
ctrl-DELETE .... ESC-DELETE .... ESC-X ... Delete word under cursor.
ctrl-U ......... ESC (MS-DOS only) ....... Delete entire line.
UpArrow ........................ ESC-k ... Retrieve previous command line.
DownArrow ...................... ESC-j ... Retrieve next command line.
TAB ...................................... Complete filename & cycle.
SHIFT-TAB ...................... ESC-TAB Complete filename & reverse cycle.
ctrl-L ................................... Complete filename, list all.

12
workspace/AGENT.md Normal file
View file

@ -0,0 +1,12 @@
# Agent Instructions
You are a helpful AI assistant. Be concise, accurate, and friendly.
## Guidelines
- Always explain what you're doing before taking actions
- Ask for clarification when request is ambiguous
- Use tools to help accomplish tasks
- Remember important information in your memory files
- Be proactive and helpful
- Learn from user feedback

56
workspace/IDENTITY.md Normal file
View file

@ -0,0 +1,56 @@
# Identity
## Name
PicoClaw 🦞
## Description
Ultra-lightweight personal AI assistant written in Go, inspired by nanobot.
## Version
0.1.0
## Purpose
- Provide intelligent AI assistance with minimal resource usage
- Support multiple LLM providers (OpenAI, Anthropic, Zhipu, etc.)
- Enable easy customization through skills system
- Run on minimal hardware ($10 boards, <10MB RAM)
## Capabilities
- Web search and content fetching
- File system operations (read, write, edit)
- Shell command execution
- Multi-channel messaging (Telegram, WhatsApp, Feishu)
- Skill-based extensibility
- Memory and context management
## Philosophy
- Simplicity over complexity
- Performance over features
- User control and privacy
- Transparent operation
- Community-driven development
## Goals
- Provide a fast, lightweight AI assistant
- Support offline-first operation where possible
- Enable easy customization and extension
- Maintain high quality responses
- Run efficiently on constrained hardware
## License
MIT License - Free and open source
## Repository
https://github.com/sipeed/picoclaw
## Contact
Issues: https://github.com/sipeed/picoclaw/issues
Discussions: https://github.com/sipeed/picoclaw/discussions
---
"Every bit helps, every bit matters."
- Picoclaw

17
workspace/SOUL.md Normal file
View file

@ -0,0 +1,17 @@
# Soul
I am picoclaw, a lightweight AI assistant powered by AI.
## Personality
- Helpful and friendly
- Concise and to the point
- Curious and eager to learn
- Honest and transparent
## Values
- Accuracy over speed
- User privacy and safety
- Transparency in actions
- Continuous improvement

21
workspace/USER.md Normal file
View file

@ -0,0 +1,21 @@
# User
Information about user goes here.
## Preferences
- Communication style: (casual/formal)
- Timezone: (your timezone)
- Language: (your preferred language)
## Personal Information
- Name: (optional)
- Location: (optional)
- Occupation: (optional)
## Learning Goals
- What the user wants to learn from AI
- Preferred interaction style
- Areas of interest

View file

@ -0,0 +1,21 @@
# Long-term Memory
This file stores important information that should persist across sessions.
## User Information
(Important facts about user)
## Preferences
(User preferences learned over time)
## Important Notes
(Things to remember)
## Configuration
- Model preferences
- Channel settings
- Skills enabled

View file

@ -0,0 +1,48 @@
---
name: github
description: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries."
metadata: {"nanobot":{"emoji":"🐙","requires":{"bins":["gh"]},"install":[{"id":"brew","kind":"brew","formula":"gh","bins":["gh"],"label":"Install GitHub CLI (brew)"},{"id":"apt","kind":"apt","package":"gh","bins":["gh"],"label":"Install GitHub CLI (apt)"}]}}
---
# GitHub Skill
Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.
## Pull Requests
Check CI status on a PR:
```bash
gh pr checks 55 --repo owner/repo
```
List recent workflow runs:
```bash
gh run list --repo owner/repo --limit 10
```
View a run and see which steps failed:
```bash
gh run view <run-id> --repo owner/repo
```
View logs for failed steps only:
```bash
gh run view <run-id> --repo owner/repo --log-failed
```
## API for Advanced Queries
The `gh api` command is useful for accessing data not available through other subcommands.
Get PR with specific fields:
```bash
gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'
```
## JSON Output
Most commands support `--json` for structured output. You can use `--jq` to filter:
```bash
gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'
```

View file

@ -0,0 +1,64 @@
---
name: hardware
description: Read and control I2C and SPI peripherals on Sipeed boards (LicheeRV Nano, MaixCAM, NanoKVM).
homepage: https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html
metadata: {"nanobot":{"emoji":"🔧","requires":{"tools":["i2c","spi"]}}}
---
# Hardware (I2C / SPI)
Use the `i2c` and `spi` tools to interact with sensors, displays, and other peripherals connected to the board.
## Quick Start
```
# 1. Find available buses
i2c detect
# 2. Scan for connected devices
i2c scan (bus: "1")
# 3. Read from a sensor (e.g. AHT20 temperature/humidity)
i2c read (bus: "1", address: 0x38, register: 0xAC, length: 6)
# 4. SPI devices
spi list
spi read (device: "2.0", length: 4)
```
## Before You Start — Pinmux Setup
Most I2C/SPI pins are shared with WiFi on Sipeed boards. You must configure pinmux before use.
See `references/board-pinout.md` for board-specific commands.
**Common steps:**
1. Stop WiFi if using shared pins: `/etc/init.d/S30wifi stop`
2. Load i2c-dev module: `modprobe i2c-dev`
3. Configure pinmux with `devmem` (board-specific)
4. Verify with `i2c detect` and `i2c scan`
## Safety
- **Write operations** require `confirm: true` — always confirm with the user first
- I2C addresses are validated to 7-bit range (0x03-0x77)
- SPI modes are validated (0-3 only)
- Maximum per-transaction: 256 bytes (I2C), 4096 bytes (SPI)
## Common Devices
See `references/common-devices.md` for register maps and usage of popular sensors:
AHT20, BME280, SSD1306 OLED, MPU6050 IMU, DS3231 RTC, INA219 power monitor, PCA9685 PWM, and more.
## Troubleshooting
| Problem | Solution |
|---------|----------|
| No I2C buses found | `modprobe i2c-dev` and check device tree |
| Permission denied | Run as root or add user to `i2c` group |
| No devices on scan | Check wiring, pull-up resistors (4.7k typical), and pinmux |
| Bus number changed | I2C adapter numbers can shift between boots; use `i2c detect` to find current assignment |
| WiFi stopped working | I2C-1/SPI-2 share pins with WiFi SDIO; can't use both simultaneously |
| `devmem` not found | Download separately or use `busybox devmem` |
| SPI transfer returns all zeros | Check MISO wiring and device power |
| SPI transfer returns all 0xFF | Device not responding; check CS pin and clock polarity (mode) |

View file

@ -0,0 +1,131 @@
# Board Pinout & Pinmux Reference
## LicheeRV Nano (SG2002)
### I2C Buses
| Bus | Pins | Notes |
|-----|------|-------|
| I2C-1 | P18 (SCL), P21 (SDA) | **Shared with WiFi SDIO** — must stop WiFi first |
| I2C-3 | Available on header | Check device tree for pin assignment |
| I2C-5 | Software (BitBang) | Slower but no pin conflicts |
### SPI Buses
| Bus | Pins | Notes |
|-----|------|-------|
| SPI-2 | P18 (CS), P21 (MISO), P22 (MOSI), P23 (SCK) | **Shared with WiFi** — must stop WiFi first |
| SPI-4 | Software (BitBang) | Slower but no pin conflicts |
### Setup Steps for I2C-1
```bash
# 1. Stop WiFi (shares pins with I2C-1)
/etc/init.d/S30wifi stop
# 2. Configure pinmux for I2C-1
devmem 0x030010D0 b 0x2 # P18 → I2C1_SCL
devmem 0x030010DC b 0x2 # P21 → I2C1_SDA
# 3. Load i2c-dev module
modprobe i2c-dev
# 4. Verify
ls /dev/i2c-*
```
### Setup Steps for SPI-2
```bash
# 1. Stop WiFi (shares pins with SPI-2)
/etc/init.d/S30wifi stop
# 2. Configure pinmux for SPI-2
devmem 0x030010D0 b 0x1 # P18 → SPI2_CS
devmem 0x030010DC b 0x1 # P21 → SPI2_MISO
devmem 0x030010E0 b 0x1 # P22 → SPI2_MOSI
devmem 0x030010E4 b 0x1 # P23 → SPI2_SCK
# 3. Verify
ls /dev/spidev*
```
### Max Tested SPI Speed
- SPI-2 hardware: tested up to **93 MHz**
- `spidev_test` is pre-installed on the official image for loopback testing
---
## MaixCAM
### I2C Buses
| Bus | Pins | Notes |
|-----|------|-------|
| I2C-1 | Overlaps with WiFi | Not recommended |
| I2C-3 | Overlaps with WiFi | Not recommended |
| I2C-5 | A15 (SCL), A27 (SDA) | **Recommended** — software I2C, no conflicts |
### Setup Steps for I2C-5
```bash
# Configure pins using pinmap utility
# (MaixCAM uses a pinmap tool instead of devmem)
# Refer to: https://wiki.sipeed.com/hardware/en/maixcam/gpio.html
# Load i2c-dev
modprobe i2c-dev
# Verify
ls /dev/i2c-*
```
---
## MaixCAM2
### I2C Buses
| Bus | Pins | Notes |
|-----|------|-------|
| I2C-6 | A1 (SCL), A0 (SDA) | Available on header |
| I2C-7 | Available | Check device tree |
### Setup Steps
```bash
# Configure pinmap for I2C-6
# A1 → I2C6_SCL, A0 → I2C6_SDA
# Refer to MaixCAM2 documentation for pinmap commands
modprobe i2c-dev
ls /dev/i2c-*
```
---
## NanoKVM
Uses the same SG2002 SoC as LicheeRV Nano. GPIO and I2C access follows the same pinmux procedure. Refer to the LicheeRV Nano section above.
Check NanoKVM-specific pin headers for available I2C/SPI lines:
- https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html
---
## Common Issues
### devmem not found
The `devmem` utility may not be in the default image. Options:
- Use `busybox devmem` if busybox is installed
- Download devmem from the Sipeed package repository
- Cross-compile from source (single C file)
### Dynamic bus numbering
I2C adapter numbers can change between boots depending on driver load order. Always use `i2c detect` to find current bus assignments rather than hardcoding bus numbers.
### Permissions
`/dev/i2c-*` and `/dev/spidev*` typically require root access. Options:
- Run picoclaw as root
- Add user to `i2c` and `spi` groups
- Create udev rules: `SUBSYSTEM=="i2c-dev", MODE="0666"`

View file

@ -0,0 +1,78 @@
# Common I2C/SPI Device Reference
## I2C Devices
### AHT20 — Temperature & Humidity
- **Address:** 0x38
- **Init:** Write `[0xBE, 0x08, 0x00]` then wait 10ms
- **Measure:** Write `[0xAC, 0x33, 0x00]`, wait 80ms, read 6 bytes
- **Parse:** Status=byte[0], Humidity=(byte[1]<<12|byte[2]<<4|byte[3]>>4)/2^20*100, Temp=(byte[3]&0x0F<<16|byte[4]<<8|byte[5])/2^20*200-50
- **Notes:** No register addressing — write command bytes directly (omit `register` param)
### BME280 / BMP280 — Temperature, Humidity, Pressure
- **Address:** 0x76 or 0x77 (SDO pin selects)
- **Chip ID register:** 0xD0 → BMP280=0x58, BME280=0x60
- **Data registers:** 0xF7-0xFE (pressure, temperature, humidity)
- **Config:** Write 0xF2 (humidity oversampling), 0xF4 (temp/press oversampling + mode), 0xF5 (standby, filter)
- **Forced measurement:** Write `[0x25]` to register 0xF4, wait 40ms, read 8 bytes from 0xF7
- **Calibration:** Read 26 bytes from 0x88 and 7 bytes from 0xE1 for compensation formulas
- **Also available via SPI** (mode 0 or 3)
### SSD1306 — 128x64 OLED Display
- **Address:** 0x3C (or 0x3D if SA0 high)
- **Command prefix:** 0x00 (write to register 0x00)
- **Data prefix:** 0x40 (write to register 0x40)
- **Init sequence:** `[0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x00, 0x40, 0x8D, 0x14, 0x20, 0x00, 0xA1, 0xC8, 0xDA, 0x12, 0x81, 0xCF, 0xD9, 0xF1, 0xDB, 0x40, 0xA4, 0xA6, 0xAF]`
- **Display on:** 0xAF, **Display off:** 0xAE
- **Also available via SPI** (faster, recommended for animations)
### MPU6050 — 6-axis Accelerometer + Gyroscope
- **Address:** 0x68 (or 0x69 if AD0 high)
- **WHO_AM_I:** Register 0x75 → should return 0x68
- **Wake up:** Write `[0x00]` to register 0x6B (clear sleep bit)
- **Read accel:** 6 bytes from register 0x3B (XH,XL,YH,YL,ZH,ZL) — signed 16-bit, default ±2g
- **Read gyro:** 6 bytes from register 0x43 — signed 16-bit, default ±250°/s
- **Read temp:** 2 bytes from register 0x41 — Temp°C = value/340 + 36.53
### DS3231 — Real-Time Clock
- **Address:** 0x68
- **Read time:** 7 bytes from register 0x00 (seconds, minutes, hours, day, date, month, year) — BCD encoded
- **Set time:** Write 7 BCD bytes to register 0x00
- **Temperature:** 2 bytes from register 0x11 (signed, 0.25°C resolution)
- **Status:** Register 0x0F — bit 2 = busy, bit 0 = alarm 1 flag
### INA219 — Current & Power Monitor
- **Address:** 0x40-0x4F (A0,A1 pin selectable)
- **Config:** Register 0x00 — set voltage range, gain, ADC resolution
- **Shunt voltage:** Register 0x01 (signed 16-bit, LSB=10µV)
- **Bus voltage:** Register 0x02 (bits 15:3, LSB=4mV)
- **Power:** Register 0x03 (after calibration)
- **Current:** Register 0x04 (after calibration)
- **Calibration:** Register 0x05 — set based on shunt resistor value
### PCA9685 — 16-Channel PWM / Servo Controller
- **Address:** 0x40-0x7F (A0-A5 selectable, default 0x40)
- **Mode 1:** Register 0x00 — bit 4=sleep, bit 5=auto-increment
- **Set PWM freq:** Sleep → write prescale to 0xFE → wake. Prescale = round(25MHz / (4096 × freq)) - 1
- **Channel N on/off:** Registers 0x06+4*N to 0x09+4*N (ON_L, ON_H, OFF_L, OFF_H)
- **Servo 0°-180°:** ON=0, OFF=150-600 (at 50Hz). Typical: 0°=150, 90°=375, 180°=600
### AT24C256 — 256Kbit EEPROM
- **Address:** 0x50-0x57 (A0-A2 selectable)
- **Read:** Write 2-byte address (high, low), then read N bytes
- **Write:** Write 2-byte address + up to 64 bytes (page write), wait 5ms for write cycle
- **Page size:** 64 bytes. Writes that cross page boundary wrap around.
## SPI Devices
### MCP3008 — 8-Channel 10-bit ADC
- **Interface:** SPI mode 0, max 3.6 MHz @ 5V
- **Read channel N:** Send `[0x01, (0x80 | N<<4), 0x00]`, result in last 10 bits of bytes 1-2
- **Formula:** value = ((byte[1] & 0x03) << 8) | byte[2]
- **Voltage:** value × Vref / 1024
### W25Q128 — 128Mbit SPI Flash
- **Interface:** SPI mode 0 or 3, up to 104 MHz
- **Read ID:** Send `[0x9F, 0, 0, 0]` → manufacturer + device ID
- **Read data:** Send `[0x03, addr_high, addr_mid, addr_low]` + N zero bytes
- **Status:** Send `[0x05, 0]` → bit 0 = BUSY

View file

@ -0,0 +1,371 @@
---
name: skill-creator
description: Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
---
# Skill Creator
This skill provides guidance for creating effective skills.
## About Skills
Skills are modular, self-contained packages that extend the agent's capabilities by providing
specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
domains or tasks—they transform the agent from a general-purpose agent into a specialized agent
equipped with procedural knowledge that no model can fully possess.
### What Skills Provide
1. Specialized workflows - Multi-step procedures for specific domains
2. Tool integrations - Instructions for working with specific file formats or APIs
3. Domain expertise - Company-specific knowledge, schemas, business logic
4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
## Core Principles
### Concise is Key
The context window is a public good. Skills share the context window with everything else the agent needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
**Default assumption: the agent is already very smart.** Only add context the agent doesn't already have. Challenge each piece of information: "Does the agent really need this explanation?" and "Does this paragraph justify its token cost?"
Prefer concise examples over verbose explanations.
### Set Appropriate Degrees of Freedom
Match the level of specificity to the task's fragility and variability:
**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
Think of the agent as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
### Anatomy of a Skill
Every skill consists of a required SKILL.md file and optional bundled resources:
```
skill-name/
├── SKILL.md (required)
│ ├── YAML frontmatter metadata (required)
│ │ ├── name: (required)
│ │ └── description: (required)
│ └── Markdown instructions (required)
└── Bundled Resources (optional)
├── scripts/ - Executable code (Python/Bash/etc.)
├── references/ - Documentation intended to be loaded into context as needed
└── assets/ - Files used in output (templates, icons, fonts, etc.)
```
#### SKILL.md (required)
Every SKILL.md consists of:
- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that the agent reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
#### Bundled Resources (optional)
##### Scripts (`scripts/`)
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
- **Benefits**: Token efficient, deterministic, may be executed without loading into context
- **Note**: Scripts may still need to be read by the agent for patching or environment-specific adjustments
##### References (`references/`)
Documentation and reference material intended to be loaded as needed into context to inform the agent's process and thinking.
- **When to include**: For documentation that the agent should reference while working
- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
- **Benefits**: Keeps SKILL.md lean, loaded only when the agent determines it's needed
- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
##### Assets (`assets/`)
Files not intended to be loaded into context, but rather used within the output the agent produces.
- **When to include**: When the skill needs files that will be used in the final output
- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
- **Benefits**: Separates output resources from documentation, enables the agent to use files without loading them into context
#### What to Not Include in a Skill
A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
- README.md
- INSTALLATION_GUIDE.md
- QUICK_REFERENCE.md
- CHANGELOG.md
- etc.
The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxiliary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
### Progressive Disclosure Design Principle
Skills use a three-level loading system to manage context efficiently:
1. **Metadata (name + description)** - Always in context (~100 words)
2. **SKILL.md body** - When skill triggers (<5k words)
3. **Bundled resources** - As needed by the agent (Unlimited because scripts can be executed without reading into context window)
#### Progressive Disclosure Patterns
Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
**Pattern 1: High-level guide with references**
```markdown
# PDF Processing
## Quick start
Extract text with pdfplumber:
[code example]
## Advanced features
- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
```
the agent loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
**Pattern 2: Domain-specific organization**
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
```
bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
├── finance.md (revenue, billing metrics)
├── sales.md (opportunities, pipeline)
├── product.md (API usage, features)
└── marketing.md (campaigns, attribution)
```
When a user asks about sales metrics, the agent only reads sales.md.
Similarly, for skills supporting multiple frameworks or variants, organize by variant:
```
cloud-deploy/
├── SKILL.md (workflow + provider selection)
└── references/
├── aws.md (AWS deployment patterns)
├── gcp.md (GCP deployment patterns)
└── azure.md (Azure deployment patterns)
```
When the user chooses AWS, the agent only reads aws.md.
**Pattern 3: Conditional details**
Show basic content, link to advanced content:
```markdown
# DOCX Processing
## Creating documents
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
## Editing documents
For simple edits, modify the XML directly.
**For tracked changes**: See [REDLINING.md](REDLINING.md)
**For OOXML details**: See [OOXML.md](OOXML.md)
```
the agent reads REDLINING.md or OOXML.md only when the user needs those features.
**Important guidelines:**
- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so the agent can see the full scope when previewing.
## Skill Creation Process
Skill creation involves these steps:
1. Understand the skill with concrete examples
2. Plan reusable skill contents (scripts, references, assets)
3. Initialize the skill (run init_skill.py)
4. Edit the skill (implement resources and write SKILL.md)
5. Package the skill (run package_skill.py)
6. Iterate based on real usage
Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
### Skill Naming
- Use lowercase letters, digits, and hyphens only; normalize user-provided titles to hyphen-case (e.g., "Plan Mode" -> `plan-mode`).
- When generating names, generate a name under 64 characters (letters, digits, hyphens).
- Prefer short, verb-led phrases that describe the action.
- Namespace by tool when it improves clarity or triggering (e.g., `gh-address-comments`, `linear-address-issue`).
- Name the skill folder exactly after the skill name.
### Step 1: Understanding the Skill with Concrete Examples
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
For example, when building an image-editor skill, relevant questions include:
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
- "Can you give some examples of how this skill would be used?"
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
- "What would a user say that should trigger this skill?"
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
Conclude this step when there is a clear sense of the functionality the skill should support.
### Step 2: Planning the Reusable Skill Contents
To turn concrete examples into an effective skill, analyze each example by:
1. Considering how to execute on the example from scratch
2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
1. Rotating a PDF requires re-writing the same code each time
2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
1. Writing a frontend webapp requires the same boilerplate HTML/React each time
2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
1. Querying BigQuery requires re-discovering the table schemas and relationships each time
2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
### Step 3: Initializing the Skill
At this point, it is time to actually create the skill.
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
Usage:
```bash
scripts/init_skill.py <skill-name> --path <output-directory> [--resources scripts,references,assets] [--examples]
```
Examples:
```bash
scripts/init_skill.py my-skill --path skills/public
scripts/init_skill.py my-skill --path skills/public --resources scripts,references
scripts/init_skill.py my-skill --path skills/public --resources scripts --examples
```
The script:
- Creates the skill directory at the specified path
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
- Optionally creates resource directories based on `--resources`
- Optionally adds example files when `--examples` is set
After initialization, customize the SKILL.md and add resources as needed. If you used `--examples`, replace or delete placeholder files.
### Step 4: Edit the Skill
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of the agent to use. Include information that would be beneficial and non-obvious to the agent. Consider what procedural knowledge, domain-specific details, or reusable assets would help another the agent instance execute these tasks more effectively.
#### Learn Proven Design Patterns
Consult these helpful guides based on your skill's needs:
- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
These files contain established best practices for effective skill design.
#### Start with Reusable Skill Contents
To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
If you used `--examples`, delete any placeholder files that are not needed for the skill. Only create resource directories that are actually required.
#### Update SKILL.md
**Writing Guidelines:** Always use imperative/infinitive form.
##### Frontmatter
Write the YAML frontmatter with `name` and `description`:
- `name`: The skill name
- `description`: This is the primary triggering mechanism for your skill, and helps the agent understand when to use the skill.
- Include both what the Skill does and specific triggers/contexts for when to use it.
- Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to the agent.
- Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when the agent needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
Do not include any other fields in YAML frontmatter.
##### Body
Write instructions for using the skill and its bundled resources.
### Step 5: Packaging a Skill
Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
```bash
scripts/package_skill.py <path/to/skill-folder>
```
Optional output directory specification:
```bash
scripts/package_skill.py <path/to/skill-folder> ./dist
```
The packaging script will:
1. **Validate** the skill automatically, checking:
- YAML frontmatter format and required fields
- Skill naming conventions and directory structure
- Description completeness and quality
- File organization and resource references
2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
### Step 6: Iterate
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
**Iteration workflow:**
1. Use the skill on real tasks
2. Notice struggles or inefficiencies
3. Identify how SKILL.md or bundled resources should be updated
4. Implement changes and test again

View file

@ -0,0 +1,67 @@
---
name: summarize
description: Summarize or extract text/transcripts from URLs, podcasts, and local files (great fallback for “transcribe this YouTube/video”).
homepage: https://summarize.sh
metadata: {"nanobot":{"emoji":"🧾","requires":{"bins":["summarize"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/summarize","bins":["summarize"],"label":"Install summarize (brew)"}]}}
---
# Summarize
Fast CLI to summarize URLs, local files, and YouTube links.
## When to use (trigger phrases)
Use this skill immediately when the user asks any of:
- “use summarize.sh”
- “whats this link/video about?”
- “summarize this URL/article”
- “transcribe this YouTube/video” (best-effort transcript extraction; no `yt-dlp` needed)
## Quick start
```bash
summarize "https://example.com" --model google/gemini-3-flash-preview
summarize "/path/to/file.pdf" --model google/gemini-3-flash-preview
summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto
```
## YouTube: summary vs transcript
Best-effort transcript (URLs only):
```bash
summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto --extract-only
```
If the user asked for a transcript but its huge, return a tight summary first, then ask which section/time range to expand.
## Model + keys
Set the API key for your chosen provider:
- OpenAI: `OPENAI_API_KEY`
- Anthropic: `ANTHROPIC_API_KEY`
- xAI: `XAI_API_KEY`
- Google: `GEMINI_API_KEY` (aliases: `GOOGLE_GENERATIVE_AI_API_KEY`, `GOOGLE_API_KEY`)
Default model is `google/gemini-3-flash-preview` if none is set.
## Useful flags
- `--length short|medium|long|xl|xxl|<chars>`
- `--max-output-tokens <count>`
- `--extract-only` (URLs only)
- `--json` (machine readable)
- `--firecrawl auto|off|always` (fallback extraction)
- `--youtube auto` (Apify fallback if `APIFY_API_TOKEN` set)
## Config
Optional config file: `~/.summarize/config.json`
```json
{ "model": "openai/gpt-5.2" }
```
Optional services:
- `FIRECRAWL_API_KEY` for blocked sites
- `APIFY_API_TOKEN` for YouTube fallback

View file

@ -0,0 +1,121 @@
---
name: tmux
description: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.
metadata: {"nanobot":{"emoji":"🧵","os":["darwin","linux"],"requires":{"bins":["tmux"]}}}
---
# tmux Skill
Use tmux only when you need an interactive TTY. Prefer exec background mode for long-running, non-interactive tasks.
## Quickstart (isolated socket, exec tool)
```bash
SOCKET_DIR="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"
mkdir -p "$SOCKET_DIR"
SOCKET="$SOCKET_DIR/nanobot.sock"
SESSION=nanobot-python
tmux -S "$SOCKET" new -d -s "$SESSION" -n shell
tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- 'PYTHON_BASIC_REPL=1 python3 -q' Enter
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
```
After starting a session, always print monitor commands:
```
To monitor:
tmux -S "$SOCKET" attach -t "$SESSION"
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
```
## Socket convention
- Use `NANOBOT_TMUX_SOCKET_DIR` environment variable.
- Default socket path: `"$NANOBOT_TMUX_SOCKET_DIR/nanobot.sock"`.
## Targeting panes and naming
- Target format: `session:window.pane` (defaults to `:0.0`).
- Keep names short; avoid spaces.
- Inspect: `tmux -S "$SOCKET" list-sessions`, `tmux -S "$SOCKET" list-panes -a`.
## Finding sessions
- List sessions on your socket: `{baseDir}/scripts/find-sessions.sh -S "$SOCKET"`.
- Scan all sockets: `{baseDir}/scripts/find-sessions.sh --all` (uses `NANOBOT_TMUX_SOCKET_DIR`).
## Sending input safely
- Prefer literal sends: `tmux -S "$SOCKET" send-keys -t target -l -- "$cmd"`.
- Control keys: `tmux -S "$SOCKET" send-keys -t target C-c`.
## Watching output
- Capture recent history: `tmux -S "$SOCKET" capture-pane -p -J -t target -S -200`.
- Wait for prompts: `{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern'`.
- Attaching is OK; detach with `Ctrl+b d`.
## Spawning processes
- For python REPLs, set `PYTHON_BASIC_REPL=1` (non-basic REPL breaks send-keys flows).
## Windows / WSL
- tmux is supported on macOS/Linux. On Windows, use WSL and install tmux inside WSL.
- This skill is gated to `darwin`/`linux` and requires `tmux` on PATH.
## Orchestrating Coding Agents (Codex, Claude Code)
tmux excels at running multiple coding agents in parallel:
```bash
SOCKET="${TMPDIR:-/tmp}/codex-army.sock"
# Create multiple sessions
for i in 1 2 3 4 5; do
tmux -S "$SOCKET" new-session -d -s "agent-$i"
done
# Launch agents in different workdirs
tmux -S "$SOCKET" send-keys -t agent-1 "cd /tmp/project1 && codex --yolo 'Fix bug X'" Enter
tmux -S "$SOCKET" send-keys -t agent-2 "cd /tmp/project2 && codex --yolo 'Fix bug Y'" Enter
# Poll for completion (check if prompt returned)
for sess in agent-1 agent-2; do
if tmux -S "$SOCKET" capture-pane -p -t "$sess" -S -3 | grep -q ""; then
echo "$sess: DONE"
else
echo "$sess: Running..."
fi
done
# Get full output from completed session
tmux -S "$SOCKET" capture-pane -p -t agent-1 -S -500
```
**Tips:**
- Use separate git worktrees for parallel fixes (no branch conflicts)
- `pnpm install` first before running codex in fresh clones
- Check for shell prompt (`` or `$`) to detect completion
- Codex needs `--yolo` or `--full-auto` for non-interactive fixes
## Cleanup
- Kill a session: `tmux -S "$SOCKET" kill-session -t "$SESSION"`.
- Kill all sessions on a socket: `tmux -S "$SOCKET" list-sessions -F '#{session_name}' | xargs -r -n1 tmux -S "$SOCKET" kill-session -t`.
- Remove everything on the private socket: `tmux -S "$SOCKET" kill-server`.
## Helper: wait-for-text.sh
`{baseDir}/scripts/wait-for-text.sh` polls a pane for a regex (or fixed string) with a timeout.
```bash
{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern' [-F] [-T 20] [-i 0.5] [-l 2000]
```
- `-t`/`--target` pane target (required)
- `-p`/`--pattern` regex to match (required); add `-F` for fixed string
- `-T` timeout seconds (integer, default 15)
- `-i` poll interval seconds (default 0.5)
- `-l` history lines to search (integer, default 1000)

View file

@ -0,0 +1,112 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: find-sessions.sh [-L socket-name|-S socket-path|-A] [-q pattern]
List tmux sessions on a socket (default tmux socket if none provided).
Options:
-L, --socket tmux socket name (passed to tmux -L)
-S, --socket-path tmux socket path (passed to tmux -S)
-A, --all scan all sockets under NANOBOT_TMUX_SOCKET_DIR
-q, --query case-insensitive substring to filter session names
-h, --help show this help
USAGE
}
socket_name=""
socket_path=""
query=""
scan_all=false
socket_dir="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"
while [[ $# -gt 0 ]]; do
case "$1" in
-L|--socket) socket_name="${2-}"; shift 2 ;;
-S|--socket-path) socket_path="${2-}"; shift 2 ;;
-A|--all) scan_all=true; shift ;;
-q|--query) query="${2-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
if [[ "$scan_all" == true && ( -n "$socket_name" || -n "$socket_path" ) ]]; then
echo "Cannot combine --all with -L or -S" >&2
exit 1
fi
if [[ -n "$socket_name" && -n "$socket_path" ]]; then
echo "Use either -L or -S, not both" >&2
exit 1
fi
if ! command -v tmux >/dev/null 2>&1; then
echo "tmux not found in PATH" >&2
exit 1
fi
list_sessions() {
local label="$1"; shift
local tmux_cmd=(tmux "$@")
if ! sessions="$("${tmux_cmd[@]}" list-sessions -F '#{session_name}\t#{session_attached}\t#{session_created_string}' 2>/dev/null)"; then
echo "No tmux server found on $label" >&2
return 1
fi
if [[ -n "$query" ]]; then
sessions="$(printf '%s\n' "$sessions" | grep -i -- "$query" || true)"
fi
if [[ -z "$sessions" ]]; then
echo "No sessions found on $label"
return 0
fi
echo "Sessions on $label:"
printf '%s\n' "$sessions" | while IFS=$'\t' read -r name attached created; do
attached_label=$([[ "$attached" == "1" ]] && echo "attached" || echo "detached")
printf ' - %s (%s, started %s)\n' "$name" "$attached_label" "$created"
done
}
if [[ "$scan_all" == true ]]; then
if [[ ! -d "$socket_dir" ]]; then
echo "Socket directory not found: $socket_dir" >&2
exit 1
fi
shopt -s nullglob
sockets=("$socket_dir"/*)
shopt -u nullglob
if [[ "${#sockets[@]}" -eq 0 ]]; then
echo "No sockets found under $socket_dir" >&2
exit 1
fi
exit_code=0
for sock in "${sockets[@]}"; do
if [[ ! -S "$sock" ]]; then
continue
fi
list_sessions "socket path '$sock'" -S "$sock" || exit_code=$?
done
exit "$exit_code"
fi
tmux_cmd=(tmux)
socket_label="default socket"
if [[ -n "$socket_name" ]]; then
tmux_cmd+=(-L "$socket_name")
socket_label="socket name '$socket_name'"
elif [[ -n "$socket_path" ]]; then
tmux_cmd+=(-S "$socket_path")
socket_label="socket path '$socket_path'"
fi
list_sessions "$socket_label" "${tmux_cmd[@]:1}"

View file

@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: wait-for-text.sh -t target -p pattern [options]
Poll a tmux pane for text and exit when found.
Options:
-t, --target tmux target (session:window.pane), required
-p, --pattern regex pattern to look for, required
-F, --fixed treat pattern as a fixed string (grep -F)
-T, --timeout seconds to wait (integer, default: 15)
-i, --interval poll interval in seconds (default: 0.5)
-l, --lines number of history lines to inspect (integer, default: 1000)
-h, --help show this help
USAGE
}
target=""
pattern=""
grep_flag="-E"
timeout=15
interval=0.5
lines=1000
while [[ $# -gt 0 ]]; do
case "$1" in
-t|--target) target="${2-}"; shift 2 ;;
-p|--pattern) pattern="${2-}"; shift 2 ;;
-F|--fixed) grep_flag="-F"; shift ;;
-T|--timeout) timeout="${2-}"; shift 2 ;;
-i|--interval) interval="${2-}"; shift 2 ;;
-l|--lines) lines="${2-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
if [[ -z "$target" || -z "$pattern" ]]; then
echo "target and pattern are required" >&2
usage
exit 1
fi
if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then
echo "timeout must be an integer number of seconds" >&2
exit 1
fi
if ! [[ "$lines" =~ ^[0-9]+$ ]]; then
echo "lines must be an integer" >&2
exit 1
fi
if ! command -v tmux >/dev/null 2>&1; then
echo "tmux not found in PATH" >&2
exit 1
fi
# End time in epoch seconds (integer, good enough for polling)
start_epoch=$(date +%s)
deadline=$((start_epoch + timeout))
while true; do
# -J joins wrapped lines, -S uses negative index to read last N lines
pane_text="$(tmux capture-pane -p -J -t "$target" -S "-${lines}" 2>/dev/null || true)"
if printf '%s\n' "$pane_text" | grep $grep_flag -- "$pattern" >/dev/null 2>&1; then
exit 0
fi
now=$(date +%s)
if (( now >= deadline )); then
echo "Timed out after ${timeout}s waiting for pattern: $pattern" >&2
echo "Last ${lines} lines from $target:" >&2
printf '%s\n' "$pane_text" >&2
exit 1
fi
sleep "$interval"
done

View file

@ -0,0 +1,49 @@
---
name: weather
description: Get current weather and forecasts (no API key required).
homepage: https://wttr.in/:help
metadata: {"nanobot":{"emoji":"🌤️","requires":{"bins":["curl"]}}}
---
# Weather
Two free services, no API keys needed.
## wttr.in (primary)
Quick one-liner:
```bash
curl -s "wttr.in/London?format=3"
# Output: London: ⛅️ +8°C
```
Compact format:
```bash
curl -s "wttr.in/London?format=%l:+%c+%t+%h+%w"
# Output: London: ⛅️ +8°C 71% ↙5km/h
```
Full forecast:
```bash
curl -s "wttr.in/London?T"
```
Format codes: `%c` condition · `%t` temp · `%h` humidity · `%w` wind · `%l` location · `%m` moon
Tips:
- URL-encode spaces: `wttr.in/New+York`
- Airport codes: `wttr.in/JFK`
- Units: `?m` (metric) `?u` (USCS)
- Today only: `?1` · Current only: `?0`
- PNG: `curl -s "wttr.in/Berlin.png" -o /tmp/weather.png`
## Open-Meteo (fallback, JSON)
Free, no key, good for programmatic use:
```bash
curl -s "https://api.open-meteo.com/v1/forecast?latitude=51.5&longitude=-0.12&current_weather=true"
```
Find coordinates for a city, then query. Returns JSON with temp, windspeed, weathercode.
Docs: https://open-meteo.com/en/docs

BIN
xmpp-channel.patch Normal file

Binary file not shown.