From 82856bc57aa0af52dc8c3f9b563b90af2d030126 Mon Sep 17 00:00:00 2001
From: yinwm
Date: Sun, 15 Feb 2026 18:41:39 +0800
Subject: [PATCH 01/31] feat(cron): add configurable execution timeout for cron
jobs
Add a new configuration option `exec_timeout_minutes` under the `tools.cron`
section to control the maximum execution time for cron jobs. The default
timeout is set to 5 minutes, which is appropriate for LLM operations.
The configuration can be set in the config file or via the
`PICOCLAW_TOOLS_CRON_EXEC_TIMEOUT_MINUTES` environment variable. A value of
0 disables the timeout entirely.
This change improves system reliability by preventing cron jobs from running
indefinitely in case of unexpected failures or hanging processes.
---
README.ja.md | 6 ++++++
README.md | 3 +++
README.zh.md | 6 ++++++
cmd/picoclaw/main.go | 6 +++---
config/config.example.json | 3 +++
pkg/config/config.go | 10 +++++++++-
pkg/tools/cron.go | 8 ++++++--
7 files changed, 36 insertions(+), 6 deletions(-)
diff --git a/README.ja.md b/README.ja.md
index 48105ce2f..5e4e49411 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -195,6 +195,9 @@ picoclaw onboard
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
}
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
}
},
"heartbeat": {
@@ -646,6 +649,9 @@ HEARTBEAT_OK 応答 ユーザーが直接結果を受け取る
"search": {
"apiKey": "BSA..."
}
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
}
},
"heartbeat": {
diff --git a/README.md b/README.md
index 2ba70881b..1b7537fc9 100644
--- a/README.md
+++ b/README.md
@@ -697,6 +697,9 @@ picoclaw agent -m "Hello"
"search": {
"api_key": "BSA..."
}
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
}
},
"heartbeat": {
diff --git a/README.zh.md b/README.zh.md
index f2c9bf780..877cb0f5d 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -217,6 +217,9 @@ picoclaw onboard
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
}
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
}
}
}
@@ -625,6 +628,9 @@ picoclaw agent -m "你好"
"search": {
"api_key": "BSA..."
}
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
}
},
"heartbeat": {
diff --git a/cmd/picoclaw/main.go b/cmd/picoclaw/main.go
index 21246cf41..8225931c8 100644
--- a/cmd/picoclaw/main.go
+++ b/cmd/picoclaw/main.go
@@ -669,7 +669,7 @@ func gatewayCmd() {
})
// Setup cron tool and service
- cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath())
+ cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath(), time.Duration(cfg.Tools.Cron.ExecTimeoutMinutes)*time.Minute)
heartbeatService := heartbeat.NewHeartbeatService(
cfg.WorkspacePath(),
@@ -1069,14 +1069,14 @@ func getConfigPath() string {
return filepath.Join(home, ".picoclaw", "config.json")
}
-func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string) *cron.CronService {
+func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string, 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)
+ cronTool := tools.NewCronTool(cronService, agentLoop, msgBus, workspace, execTimeout)
agentLoop.RegisterTool(cronTool)
// Set the onJob handler
diff --git a/config/config.example.json b/config/config.example.json
index c71587a04..d56596f24 100644
--- a/config/config.example.json
+++ b/config/config.example.json
@@ -98,6 +98,9 @@
"api_key": "YOUR_BRAVE_API_KEY",
"max_results": 5
}
+ },
+ "cron": {
+ "exec_timeout_minutes": 5
}
},
"heartbeat": {
diff --git a/pkg/config/config.go b/pkg/config/config.go
index 391120e2d..9acbcce8c 100644
--- a/pkg/config/config.go
+++ b/pkg/config/config.go
@@ -173,8 +173,13 @@ type WebToolsConfig struct {
Search WebSearchConfig `json:"search"`
}
+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 {
@@ -262,6 +267,9 @@ func DefaultConfig() *Config {
MaxResults: 5,
},
},
+ Cron: CronToolsConfig{
+ ExecTimeoutMinutes: 5, // default 5 minutes for LLM operations
+ },
},
Heartbeat: HeartbeatConfig{
Enabled: true,
diff --git a/pkg/tools/cron.go b/pkg/tools/cron.go
index 0ef745e2b..8632b07b9 100644
--- a/pkg/tools/cron.go
+++ b/pkg/tools/cron.go
@@ -28,12 +28,16 @@ type CronTool struct {
}
// NewCronTool creates a new CronTool
-func NewCronTool(cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string) *CronTool {
+func NewCronTool(cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string, execTimeout time.Duration) *CronTool {
+ execTool := NewExecTool(workspace, false)
+ if execTimeout > 0 {
+ execTool.SetTimeout(execTimeout)
+ }
return &CronTool{
cronService: cronService,
executor: executor,
msgBus: msgBus,
- execTool: NewExecTool(workspace, false),
+ execTool: execTool,
}
}
From a6e885bb473a20d671ed1dab5e8e8ea9bb8cd399 Mon Sep 17 00:00:00 2001
From: Jared Mahotiere
Date: Sun, 15 Feb 2026 08:04:07 -0500
Subject: [PATCH 02/31] refactor(providers): extract protocol factory and
openai-compat transport
---
pkg/providers/factory.go | 291 ++++++++++++
pkg/providers/factory_test.go | 150 ++++++
pkg/providers/http_provider.go | 473 ++++---------------
pkg/providers/openai_compat/provider.go | 230 +++++++++
pkg/providers/openai_compat/provider_test.go | 149 ++++++
5 files changed, 905 insertions(+), 388 deletions(-)
create mode 100644 pkg/providers/factory.go
create mode 100644 pkg/providers/factory_test.go
create mode 100644 pkg/providers/openai_compat/provider.go
create mode 100644 pkg/providers/openai_compat/provider_test.go
diff --git a/pkg/providers/factory.go b/pkg/providers/factory.go
new file mode 100644
index 000000000..84dcd9aaa
--- /dev/null
+++ b/pkg/providers/factory.go
@@ -0,0 +1,291 @@
+package providers
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/sipeed/picoclaw/pkg/auth"
+ "github.com/sipeed/picoclaw/pkg/config"
+)
+
+type providerType int
+
+const (
+ providerTypeHTTPCompat providerType = iota
+ providerTypeClaudeAuth
+ providerTypeCodexAuth
+ providerTypeClaudeCLI
+ providerTypeGitHubCopilot
+)
+
+type providerSelection struct {
+ providerType providerType
+ apiKey string
+ apiBase string
+ proxy string
+ model string
+ workspace string
+ connectMode string
+}
+
+func createClaudeAuthProvider() (LLMProvider, error) {
+ cred, err := auth.GetCredential("anthropic")
+ if err != nil {
+ return nil, fmt.Errorf("loading auth credentials: %w", err)
+ }
+ if cred == nil {
+ return nil, fmt.Errorf("no credentials for anthropic. Run: picoclaw auth login --provider anthropic")
+ }
+ return NewClaudeProviderWithTokenSource(cred.AccessToken, createClaudeTokenSource()), nil
+}
+
+func createCodexAuthProvider() (LLMProvider, error) {
+ cred, err := auth.GetCredential("openai")
+ if err != nil {
+ return nil, fmt.Errorf("loading auth credentials: %w", err)
+ }
+ if cred == nil {
+ return nil, fmt.Errorf("no credentials for openai. Run: picoclaw auth login --provider openai")
+ }
+ return NewCodexProviderWithTokenSource(cred.AccessToken, cred.AccountID, createCodexTokenSource()), nil
+}
+
+func resolveProviderSelection(cfg *config.Config) (providerSelection, error) {
+ model := cfg.Agents.Defaults.Model
+ providerName := strings.ToLower(cfg.Agents.Defaults.Provider)
+ lowerModel := strings.ToLower(model)
+
+ sel := providerSelection{
+ providerType: providerTypeHTTPCompat,
+ model: model,
+ }
+
+ // First, prefer explicit provider configuration.
+ if providerName != "" {
+ switch providerName {
+ case "groq":
+ if cfg.Providers.Groq.APIKey != "" {
+ sel.apiKey = cfg.Providers.Groq.APIKey
+ sel.apiBase = cfg.Providers.Groq.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.groq.com/openai/v1"
+ }
+ }
+ case "openai", "gpt":
+ if cfg.Providers.OpenAI.APIKey != "" || cfg.Providers.OpenAI.AuthMethod != "" {
+ if cfg.Providers.OpenAI.AuthMethod == "oauth" || cfg.Providers.OpenAI.AuthMethod == "token" {
+ sel.providerType = providerTypeCodexAuth
+ return sel, nil
+ }
+ sel.apiKey = cfg.Providers.OpenAI.APIKey
+ sel.apiBase = cfg.Providers.OpenAI.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.openai.com/v1"
+ }
+ }
+ case "anthropic", "claude":
+ if cfg.Providers.Anthropic.APIKey != "" || cfg.Providers.Anthropic.AuthMethod != "" {
+ if cfg.Providers.Anthropic.AuthMethod == "oauth" || cfg.Providers.Anthropic.AuthMethod == "token" {
+ sel.providerType = providerTypeClaudeAuth
+ return sel, nil
+ }
+ sel.apiKey = cfg.Providers.Anthropic.APIKey
+ sel.apiBase = cfg.Providers.Anthropic.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.anthropic.com/v1"
+ }
+ }
+ case "openrouter":
+ if cfg.Providers.OpenRouter.APIKey != "" {
+ sel.apiKey = cfg.Providers.OpenRouter.APIKey
+ if cfg.Providers.OpenRouter.APIBase != "" {
+ sel.apiBase = cfg.Providers.OpenRouter.APIBase
+ } else {
+ sel.apiBase = "https://openrouter.ai/api/v1"
+ }
+ }
+ case "zhipu", "glm":
+ if cfg.Providers.Zhipu.APIKey != "" {
+ sel.apiKey = cfg.Providers.Zhipu.APIKey
+ sel.apiBase = cfg.Providers.Zhipu.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://open.bigmodel.cn/api/paas/v4"
+ }
+ }
+ case "gemini", "google":
+ if cfg.Providers.Gemini.APIKey != "" {
+ sel.apiKey = cfg.Providers.Gemini.APIKey
+ sel.apiBase = cfg.Providers.Gemini.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://generativelanguage.googleapis.com/v1beta"
+ }
+ }
+ case "vllm":
+ if cfg.Providers.VLLM.APIBase != "" {
+ sel.apiKey = cfg.Providers.VLLM.APIKey
+ sel.apiBase = cfg.Providers.VLLM.APIBase
+ }
+ case "shengsuanyun":
+ if cfg.Providers.ShengSuanYun.APIKey != "" {
+ sel.apiKey = cfg.Providers.ShengSuanYun.APIKey
+ sel.apiBase = cfg.Providers.ShengSuanYun.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://router.shengsuanyun.com/api/v1"
+ }
+ }
+ case "claude-cli", "claude-code", "claudecode":
+ workspace := cfg.Agents.Defaults.Workspace
+ if workspace == "" {
+ workspace = "."
+ }
+ sel.providerType = providerTypeClaudeCLI
+ sel.workspace = workspace
+ return sel, nil
+ case "deepseek":
+ if cfg.Providers.DeepSeek.APIKey != "" {
+ sel.apiKey = cfg.Providers.DeepSeek.APIKey
+ sel.apiBase = cfg.Providers.DeepSeek.APIBase
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.deepseek.com/v1"
+ }
+ if model != "deepseek-chat" && model != "deepseek-reasoner" {
+ sel.model = "deepseek-chat"
+ }
+ }
+ case "github_copilot", "copilot":
+ sel.providerType = providerTypeGitHubCopilot
+ if cfg.Providers.GitHubCopilot.APIBase != "" {
+ sel.apiBase = cfg.Providers.GitHubCopilot.APIBase
+ } else {
+ sel.apiBase = "localhost:4321"
+ }
+ sel.connectMode = cfg.Providers.GitHubCopilot.ConnectMode
+ return sel, nil
+ }
+ }
+
+ // Fallback: infer provider from model and configured keys.
+ if sel.apiKey == "" && sel.apiBase == "" {
+ switch {
+ case (strings.Contains(lowerModel, "kimi") || strings.Contains(lowerModel, "moonshot") || strings.HasPrefix(model, "moonshot/")) && cfg.Providers.Moonshot.APIKey != "":
+ sel.apiKey = cfg.Providers.Moonshot.APIKey
+ sel.apiBase = cfg.Providers.Moonshot.APIBase
+ sel.proxy = cfg.Providers.Moonshot.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.moonshot.cn/v1"
+ }
+ case strings.HasPrefix(model, "openrouter/") ||
+ strings.HasPrefix(model, "anthropic/") ||
+ strings.HasPrefix(model, "openai/") ||
+ strings.HasPrefix(model, "meta-llama/") ||
+ strings.HasPrefix(model, "deepseek/") ||
+ strings.HasPrefix(model, "google/"):
+ sel.apiKey = cfg.Providers.OpenRouter.APIKey
+ sel.proxy = cfg.Providers.OpenRouter.Proxy
+ if cfg.Providers.OpenRouter.APIBase != "" {
+ sel.apiBase = cfg.Providers.OpenRouter.APIBase
+ } else {
+ sel.apiBase = "https://openrouter.ai/api/v1"
+ }
+ case (strings.Contains(lowerModel, "claude") || strings.HasPrefix(model, "anthropic/")) &&
+ (cfg.Providers.Anthropic.APIKey != "" || cfg.Providers.Anthropic.AuthMethod != ""):
+ if cfg.Providers.Anthropic.AuthMethod == "oauth" || cfg.Providers.Anthropic.AuthMethod == "token" {
+ sel.providerType = providerTypeClaudeAuth
+ return sel, nil
+ }
+ sel.apiKey = cfg.Providers.Anthropic.APIKey
+ sel.apiBase = cfg.Providers.Anthropic.APIBase
+ sel.proxy = cfg.Providers.Anthropic.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.anthropic.com/v1"
+ }
+ case (strings.Contains(lowerModel, "gpt") || strings.HasPrefix(model, "openai/")) &&
+ (cfg.Providers.OpenAI.APIKey != "" || cfg.Providers.OpenAI.AuthMethod != ""):
+ if cfg.Providers.OpenAI.AuthMethod == "oauth" || cfg.Providers.OpenAI.AuthMethod == "token" {
+ sel.providerType = providerTypeCodexAuth
+ return sel, nil
+ }
+ sel.apiKey = cfg.Providers.OpenAI.APIKey
+ sel.apiBase = cfg.Providers.OpenAI.APIBase
+ sel.proxy = cfg.Providers.OpenAI.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.openai.com/v1"
+ }
+ case (strings.Contains(lowerModel, "gemini") || strings.HasPrefix(model, "google/")) && cfg.Providers.Gemini.APIKey != "":
+ sel.apiKey = cfg.Providers.Gemini.APIKey
+ sel.apiBase = cfg.Providers.Gemini.APIBase
+ sel.proxy = cfg.Providers.Gemini.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://generativelanguage.googleapis.com/v1beta"
+ }
+ case (strings.Contains(lowerModel, "glm") || strings.Contains(lowerModel, "zhipu") || strings.Contains(lowerModel, "zai")) && cfg.Providers.Zhipu.APIKey != "":
+ sel.apiKey = cfg.Providers.Zhipu.APIKey
+ sel.apiBase = cfg.Providers.Zhipu.APIBase
+ sel.proxy = cfg.Providers.Zhipu.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://open.bigmodel.cn/api/paas/v4"
+ }
+ case (strings.Contains(lowerModel, "groq") || strings.HasPrefix(model, "groq/")) && cfg.Providers.Groq.APIKey != "":
+ sel.apiKey = cfg.Providers.Groq.APIKey
+ sel.apiBase = cfg.Providers.Groq.APIBase
+ sel.proxy = cfg.Providers.Groq.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://api.groq.com/openai/v1"
+ }
+ case (strings.Contains(lowerModel, "nvidia") || strings.HasPrefix(model, "nvidia/")) && cfg.Providers.Nvidia.APIKey != "":
+ sel.apiKey = cfg.Providers.Nvidia.APIKey
+ sel.apiBase = cfg.Providers.Nvidia.APIBase
+ sel.proxy = cfg.Providers.Nvidia.Proxy
+ if sel.apiBase == "" {
+ sel.apiBase = "https://integrate.api.nvidia.com/v1"
+ }
+ case cfg.Providers.VLLM.APIBase != "":
+ sel.apiKey = cfg.Providers.VLLM.APIKey
+ sel.apiBase = cfg.Providers.VLLM.APIBase
+ sel.proxy = cfg.Providers.VLLM.Proxy
+ default:
+ if cfg.Providers.OpenRouter.APIKey != "" {
+ sel.apiKey = cfg.Providers.OpenRouter.APIKey
+ sel.proxy = cfg.Providers.OpenRouter.Proxy
+ if cfg.Providers.OpenRouter.APIBase != "" {
+ sel.apiBase = cfg.Providers.OpenRouter.APIBase
+ } else {
+ sel.apiBase = "https://openrouter.ai/api/v1"
+ }
+ } else {
+ return providerSelection{}, fmt.Errorf("no API key configured for model: %s", model)
+ }
+ }
+ }
+
+ if sel.providerType == providerTypeHTTPCompat {
+ if sel.apiKey == "" && !strings.HasPrefix(model, "bedrock/") {
+ return providerSelection{}, fmt.Errorf("no API key configured for provider (model: %s)", model)
+ }
+ if sel.apiBase == "" {
+ return providerSelection{}, fmt.Errorf("no API base configured for provider (model: %s)", model)
+ }
+ }
+
+ return sel, nil
+}
+
+func CreateProvider(cfg *config.Config) (LLMProvider, error) {
+ sel, err := resolveProviderSelection(cfg)
+ if err != nil {
+ return nil, err
+ }
+
+ switch sel.providerType {
+ case providerTypeClaudeAuth:
+ return createClaudeAuthProvider()
+ case providerTypeCodexAuth:
+ return createCodexAuthProvider()
+ case providerTypeClaudeCLI:
+ return NewClaudeCliProvider(sel.workspace), nil
+ case providerTypeGitHubCopilot:
+ return NewGitHubCopilotProvider(sel.apiBase, sel.connectMode, sel.model)
+ default:
+ return NewHTTPProvider(sel.apiKey, sel.apiBase, sel.proxy), nil
+ }
+}
diff --git a/pkg/providers/factory_test.go b/pkg/providers/factory_test.go
new file mode 100644
index 000000000..f894b292a
--- /dev/null
+++ b/pkg/providers/factory_test.go
@@ -0,0 +1,150 @@
+package providers
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/sipeed/picoclaw/pkg/config"
+)
+
+func TestResolveProviderSelection(t *testing.T) {
+ tests := []struct {
+ name string
+ setup func(*config.Config)
+ wantType providerType
+ wantAPIBase string
+ wantProxy string
+ wantErrSubstr string
+ }{
+ {
+ name: "explicit claude-cli provider routes to cli provider type",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Provider = "claude-cli"
+ cfg.Agents.Defaults.Workspace = "/tmp/ws"
+ },
+ wantType: providerTypeClaudeCLI,
+ },
+ {
+ name: "explicit copilot provider routes to github copilot type",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Provider = "copilot"
+ },
+ wantType: providerTypeGitHubCopilot,
+ wantAPIBase: "localhost:4321",
+ },
+ {
+ name: "openrouter model uses openrouter defaults",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "openrouter/auto"
+ cfg.Providers.OpenRouter.APIKey = "sk-or-test"
+ },
+ wantType: providerTypeHTTPCompat,
+ wantAPIBase: "https://openrouter.ai/api/v1",
+ },
+ {
+ name: "anthropic oauth routes to claude auth provider",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "claude-sonnet-4-5-20250929"
+ cfg.Providers.Anthropic.AuthMethod = "oauth"
+ },
+ wantType: providerTypeClaudeAuth,
+ },
+ {
+ name: "openai oauth routes to codex auth provider",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "gpt-4o"
+ cfg.Providers.OpenAI.AuthMethod = "oauth"
+ },
+ wantType: providerTypeCodexAuth,
+ },
+ {
+ name: "zhipu model uses zhipu base default",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "glm-4.7"
+ cfg.Providers.Zhipu.APIKey = "zhipu-key"
+ },
+ wantType: providerTypeHTTPCompat,
+ wantAPIBase: "https://open.bigmodel.cn/api/paas/v4",
+ },
+ {
+ name: "groq model uses groq base default",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "groq/llama-3.3-70b"
+ cfg.Providers.Groq.APIKey = "gsk-key"
+ },
+ wantType: providerTypeHTTPCompat,
+ wantAPIBase: "https://api.groq.com/openai/v1",
+ },
+ {
+ name: "moonshot model keeps proxy and default base",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "moonshot/kimi-k2.5"
+ cfg.Providers.Moonshot.APIKey = "moonshot-key"
+ cfg.Providers.Moonshot.Proxy = "http://127.0.0.1:7890"
+ },
+ wantType: providerTypeHTTPCompat,
+ wantAPIBase: "https://api.moonshot.cn/v1",
+ wantProxy: "http://127.0.0.1:7890",
+ },
+ {
+ name: "missing keys returns model config error",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "custom-model"
+ },
+ wantErrSubstr: "no API key configured for model",
+ },
+ {
+ name: "openrouter prefix without key returns provider key error",
+ setup: func(cfg *config.Config) {
+ cfg.Agents.Defaults.Model = "openrouter/auto"
+ },
+ wantErrSubstr: "no API key configured for provider",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cfg := config.DefaultConfig()
+ tt.setup(cfg)
+
+ got, err := resolveProviderSelection(cfg)
+ if tt.wantErrSubstr != "" {
+ if err == nil {
+ t.Fatalf("expected error containing %q, got nil", tt.wantErrSubstr)
+ }
+ if !strings.Contains(err.Error(), tt.wantErrSubstr) {
+ t.Fatalf("error = %q, want substring %q", err.Error(), tt.wantErrSubstr)
+ }
+ return
+ }
+
+ if err != nil {
+ t.Fatalf("resolveProviderSelection() error = %v", err)
+ }
+ if got.providerType != tt.wantType {
+ t.Fatalf("providerType = %v, want %v", got.providerType, tt.wantType)
+ }
+ if tt.wantAPIBase != "" && got.apiBase != tt.wantAPIBase {
+ t.Fatalf("apiBase = %q, want %q", got.apiBase, tt.wantAPIBase)
+ }
+ if tt.wantProxy != "" && got.proxy != tt.wantProxy {
+ t.Fatalf("proxy = %q, want %q", got.proxy, tt.wantProxy)
+ }
+ })
+ }
+}
+
+func TestCreateProviderReturnsHTTPProviderForOpenRouter(t *testing.T) {
+ cfg := config.DefaultConfig()
+ cfg.Agents.Defaults.Model = "openrouter/auto"
+ cfg.Providers.OpenRouter.APIKey = "sk-or-test"
+
+ provider, err := CreateProvider(cfg)
+ if err != nil {
+ t.Fatalf("CreateProvider() error = %v", err)
+ }
+
+ if _, ok := provider.(*HTTPProvider); !ok {
+ t.Fatalf("provider type = %T, want *HTTPProvider", provider)
+ }
+}
diff --git a/pkg/providers/http_provider.go b/pkg/providers/http_provider.go
index 17eb6214c..0f7f646d8 100644
--- a/pkg/providers/http_provider.go
+++ b/pkg/providers/http_provider.go
@@ -7,427 +7,124 @@
package providers
import (
- "bytes"
"context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "strings"
- "time"
-
- "github.com/sipeed/picoclaw/pkg/auth"
- "github.com/sipeed/picoclaw/pkg/config"
+ "github.com/sipeed/picoclaw/pkg/providers/openai_compat"
)
type HTTPProvider struct {
- apiKey string
- apiBase string
- httpClient *http.Client
+ delegate *openai_compat.Provider
}
-func NewHTTPProvider(apiKey, apiBase, proxy string) *HTTPProvider {
- client := &http.Client{
- Timeout: 120 * time.Second,
+func NewHTTPProvider(apiKey, apiBase string, proxy ...string) *HTTPProvider {
+ proxyURL := ""
+ if len(proxy) > 0 {
+ proxyURL = proxy[0]
}
-
- if proxy != "" {
- proxyURL, err := url.Parse(proxy)
- if err == nil {
- client.Transport = &http.Transport{
- Proxy: http.ProxyURL(proxyURL),
- }
- }
- }
-
return &HTTPProvider{
- apiKey: apiKey,
- apiBase: strings.TrimRight(apiBase, "/"),
- httpClient: client,
+ delegate: openai_compat.NewProvider(apiKey, apiBase, proxyURL),
}
}
func (p *HTTPProvider) Chat(ctx context.Context, messages []Message, tools []ToolDefinition, model string, options map[string]interface{}) (*LLMResponse, error) {
- if p.apiBase == "" {
- return nil, fmt.Errorf("API base not configured")
- }
-
- // Strip provider prefix from model name (e.g., moonshot/kimi-k2.5 -> kimi-k2.5)
- if idx := strings.Index(model, "/"); idx != -1 {
- prefix := model[:idx]
- if prefix == "moonshot" || prefix == "nvidia" {
- model = model[idx+1:]
- }
- }
-
- requestBody := map[string]interface{}{
- "model": model,
- "messages": messages,
- }
-
- if len(tools) > 0 {
- requestBody["tools"] = tools
- requestBody["tool_choice"] = "auto"
- }
-
- if maxTokens, ok := options["max_tokens"].(int); ok {
- lowerModel := strings.ToLower(model)
- if strings.Contains(lowerModel, "glm") || strings.Contains(lowerModel, "o1") {
- requestBody["max_completion_tokens"] = maxTokens
- } else {
- requestBody["max_tokens"] = maxTokens
- }
- }
-
- if temperature, ok := options["temperature"].(float64); ok {
- lowerModel := strings.ToLower(model)
- // Kimi k2 models only support temperature=1
- if strings.Contains(lowerModel, "kimi") && strings.Contains(lowerModel, "k2") {
- requestBody["temperature"] = 1.0
- } else {
- requestBody["temperature"] = temperature
- }
- }
-
- jsonData, err := json.Marshal(requestBody)
+ compatResp, err := p.delegate.Chat(ctx, toOpenAICompatMessages(messages), toOpenAICompatTools(tools), model, options)
if err != nil {
- return nil, fmt.Errorf("failed to marshal request: %w", err)
+ return nil, err
}
-
- req, err := http.NewRequestWithContext(ctx, "POST", p.apiBase+"/chat/completions", bytes.NewReader(jsonData))
- if err != nil {
- return nil, fmt.Errorf("failed to create request: %w", err)
- }
-
- req.Header.Set("Content-Type", "application/json")
- if p.apiKey != "" {
- req.Header.Set("Authorization", "Bearer "+p.apiKey)
- }
-
- resp, err := p.httpClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("failed to send request: %w", err)
- }
- defer resp.Body.Close()
-
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("failed to read response: %w", err)
- }
-
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("API request failed:\n Status: %d\n Body: %s", resp.StatusCode, string(body))
- }
-
- return p.parseResponse(body)
-}
-
-func (p *HTTPProvider) parseResponse(body []byte) (*LLMResponse, error) {
- var apiResponse struct {
- Choices []struct {
- Message struct {
- Content string `json:"content"`
- ToolCalls []struct {
- ID string `json:"id"`
- Type string `json:"type"`
- Function *struct {
- Name string `json:"name"`
- Arguments string `json:"arguments"`
- } `json:"function"`
- } `json:"tool_calls"`
- } `json:"message"`
- FinishReason string `json:"finish_reason"`
- } `json:"choices"`
- Usage *UsageInfo `json:"usage"`
- }
-
- if err := json.Unmarshal(body, &apiResponse); err != nil {
- return nil, fmt.Errorf("failed to unmarshal response: %w", err)
- }
-
- if len(apiResponse.Choices) == 0 {
- return &LLMResponse{
- Content: "",
- FinishReason: "stop",
- }, nil
- }
-
- choice := apiResponse.Choices[0]
-
- toolCalls := make([]ToolCall, 0, len(choice.Message.ToolCalls))
- for _, tc := range choice.Message.ToolCalls {
- arguments := make(map[string]interface{})
- name := ""
-
- // Handle OpenAI format with nested function object
- if tc.Type == "function" && tc.Function != nil {
- name = tc.Function.Name
- if tc.Function.Arguments != "" {
- if err := json.Unmarshal([]byte(tc.Function.Arguments), &arguments); err != nil {
- arguments["raw"] = tc.Function.Arguments
- }
- }
- } else if tc.Function != nil {
- // Legacy format without type field
- name = tc.Function.Name
- if tc.Function.Arguments != "" {
- if err := json.Unmarshal([]byte(tc.Function.Arguments), &arguments); err != nil {
- arguments["raw"] = tc.Function.Arguments
- }
- }
- }
-
- toolCalls = append(toolCalls, ToolCall{
- ID: tc.ID,
- Name: name,
- Arguments: arguments,
- })
- }
-
- return &LLMResponse{
- Content: choice.Message.Content,
- ToolCalls: toolCalls,
- FinishReason: choice.FinishReason,
- Usage: apiResponse.Usage,
- }, nil
+ return fromOpenAICompatResponse(compatResp), nil
}
func (p *HTTPProvider) GetDefaultModel() string {
return ""
}
-func createClaudeAuthProvider() (LLMProvider, error) {
- cred, err := auth.GetCredential("anthropic")
- if err != nil {
- return nil, fmt.Errorf("loading auth credentials: %w", err)
+func toOpenAICompatMessages(messages []Message) []openai_compat.Message {
+ out := make([]openai_compat.Message, 0, len(messages))
+ for _, msg := range messages {
+ out = append(out, openai_compat.Message{
+ Role: msg.Role,
+ Content: msg.Content,
+ ToolCalls: toOpenAICompatToolCalls(msg.ToolCalls),
+ ToolCallID: msg.ToolCallID,
+ })
}
- if cred == nil {
- return nil, fmt.Errorf("no credentials for anthropic. Run: picoclaw auth login --provider anthropic")
- }
- return NewClaudeProviderWithTokenSource(cred.AccessToken, createClaudeTokenSource()), nil
+ return out
}
-func createCodexAuthProvider() (LLMProvider, error) {
- cred, err := auth.GetCredential("openai")
- if err != nil {
- return nil, fmt.Errorf("loading auth credentials: %w", err)
+func toOpenAICompatTools(tools []ToolDefinition) []openai_compat.ToolDefinition {
+ out := make([]openai_compat.ToolDefinition, 0, len(tools))
+ for _, t := range tools {
+ out = append(out, openai_compat.ToolDefinition{
+ Type: t.Type,
+ Function: openai_compat.ToolFunctionDefinition{
+ Name: t.Function.Name,
+ Description: t.Function.Description,
+ Parameters: t.Function.Parameters,
+ },
+ })
}
- if cred == nil {
- return nil, fmt.Errorf("no credentials for openai. Run: picoclaw auth login --provider openai")
- }
- return NewCodexProviderWithTokenSource(cred.AccessToken, cred.AccountID, createCodexTokenSource()), nil
+ return out
}
-func CreateProvider(cfg *config.Config) (LLMProvider, error) {
- model := cfg.Agents.Defaults.Model
- providerName := strings.ToLower(cfg.Agents.Defaults.Provider)
-
- var apiKey, apiBase, proxy string
-
- lowerModel := strings.ToLower(model)
-
- // First, try to use explicitly configured provider
- if providerName != "" {
- switch providerName {
- case "groq":
- if cfg.Providers.Groq.APIKey != "" {
- apiKey = cfg.Providers.Groq.APIKey
- apiBase = cfg.Providers.Groq.APIBase
- if apiBase == "" {
- apiBase = "https://api.groq.com/openai/v1"
- }
+func toOpenAICompatToolCalls(toolCalls []ToolCall) []openai_compat.ToolCall {
+ out := make([]openai_compat.ToolCall, 0, len(toolCalls))
+ for _, tc := range toolCalls {
+ var fn *openai_compat.FunctionCall
+ if tc.Function != nil {
+ fn = &openai_compat.FunctionCall{
+ Name: tc.Function.Name,
+ Arguments: tc.Function.Arguments,
}
- case "openai", "gpt":
- if cfg.Providers.OpenAI.APIKey != "" || cfg.Providers.OpenAI.AuthMethod != "" {
- if cfg.Providers.OpenAI.AuthMethod == "oauth" || cfg.Providers.OpenAI.AuthMethod == "token" {
- return createCodexAuthProvider()
- }
- apiKey = cfg.Providers.OpenAI.APIKey
- apiBase = cfg.Providers.OpenAI.APIBase
- if apiBase == "" {
- apiBase = "https://api.openai.com/v1"
- }
- }
- case "anthropic", "claude":
- if cfg.Providers.Anthropic.APIKey != "" || cfg.Providers.Anthropic.AuthMethod != "" {
- if cfg.Providers.Anthropic.AuthMethod == "oauth" || cfg.Providers.Anthropic.AuthMethod == "token" {
- return createClaudeAuthProvider()
- }
- apiKey = cfg.Providers.Anthropic.APIKey
- apiBase = cfg.Providers.Anthropic.APIBase
- if apiBase == "" {
- apiBase = "https://api.anthropic.com/v1"
- }
- }
- case "openrouter":
- if cfg.Providers.OpenRouter.APIKey != "" {
- apiKey = cfg.Providers.OpenRouter.APIKey
- if cfg.Providers.OpenRouter.APIBase != "" {
- apiBase = cfg.Providers.OpenRouter.APIBase
- } else {
- apiBase = "https://openrouter.ai/api/v1"
- }
- }
- case "zhipu", "glm":
- if cfg.Providers.Zhipu.APIKey != "" {
- apiKey = cfg.Providers.Zhipu.APIKey
- apiBase = cfg.Providers.Zhipu.APIBase
- if apiBase == "" {
- apiBase = "https://open.bigmodel.cn/api/paas/v4"
- }
- }
- case "gemini", "google":
- if cfg.Providers.Gemini.APIKey != "" {
- apiKey = cfg.Providers.Gemini.APIKey
- apiBase = cfg.Providers.Gemini.APIBase
- if apiBase == "" {
- apiBase = "https://generativelanguage.googleapis.com/v1beta"
- }
- }
- case "vllm":
- if cfg.Providers.VLLM.APIBase != "" {
- apiKey = cfg.Providers.VLLM.APIKey
- apiBase = cfg.Providers.VLLM.APIBase
- }
- case "shengsuanyun":
- if cfg.Providers.ShengSuanYun.APIKey != "" {
- apiKey = cfg.Providers.ShengSuanYun.APIKey
- apiBase = cfg.Providers.ShengSuanYun.APIBase
- if apiBase == "" {
- apiBase = "https://router.shengsuanyun.com/api/v1"
- }
- }
- case "claude-cli", "claudecode", "claude-code":
- workspace := cfg.Agents.Defaults.Workspace
- if workspace == "" {
- workspace = "."
- }
- return NewClaudeCliProvider(workspace), nil
- case "deepseek":
- if cfg.Providers.DeepSeek.APIKey != "" {
- apiKey = cfg.Providers.DeepSeek.APIKey
- apiBase = cfg.Providers.DeepSeek.APIBase
- if apiBase == "" {
- apiBase = "https://api.deepseek.com/v1"
- }
- if model != "deepseek-chat" && model != "deepseek-reasoner" {
- model = "deepseek-chat"
- }
- }
- case "github_copilot", "copilot":
- if cfg.Providers.GitHubCopilot.APIBase != "" {
- apiBase = cfg.Providers.GitHubCopilot.APIBase
- } else {
- apiBase = "localhost:4321"
- }
- return NewGitHubCopilotProvider(apiBase, cfg.Providers.GitHubCopilot.ConnectMode, model)
-
}
+ out = append(out, openai_compat.ToolCall{
+ ID: tc.ID,
+ Type: tc.Type,
+ Function: fn,
+ Name: tc.Name,
+ Arguments: tc.Arguments,
+ })
+ }
+ return out
+}
+func fromOpenAICompatResponse(resp *openai_compat.LLMResponse) *LLMResponse {
+ if resp == nil {
+ return &LLMResponse{}
}
- // Fallback: detect provider from model name
- if apiKey == "" && apiBase == "" {
- switch {
- case (strings.Contains(lowerModel, "kimi") || strings.Contains(lowerModel, "moonshot") || strings.HasPrefix(model, "moonshot/")) && cfg.Providers.Moonshot.APIKey != "":
- apiKey = cfg.Providers.Moonshot.APIKey
- apiBase = cfg.Providers.Moonshot.APIBase
- proxy = cfg.Providers.Moonshot.Proxy
- if apiBase == "" {
- apiBase = "https://api.moonshot.cn/v1"
- }
-
- case strings.HasPrefix(model, "openrouter/") || strings.HasPrefix(model, "anthropic/") || strings.HasPrefix(model, "openai/") || strings.HasPrefix(model, "meta-llama/") || strings.HasPrefix(model, "deepseek/") || strings.HasPrefix(model, "google/"):
- apiKey = cfg.Providers.OpenRouter.APIKey
- proxy = cfg.Providers.OpenRouter.Proxy
- if cfg.Providers.OpenRouter.APIBase != "" {
- apiBase = cfg.Providers.OpenRouter.APIBase
- } else {
- apiBase = "https://openrouter.ai/api/v1"
- }
-
- case (strings.Contains(lowerModel, "claude") || strings.HasPrefix(model, "anthropic/")) && (cfg.Providers.Anthropic.APIKey != "" || cfg.Providers.Anthropic.AuthMethod != ""):
- if cfg.Providers.Anthropic.AuthMethod == "oauth" || cfg.Providers.Anthropic.AuthMethod == "token" {
- return createClaudeAuthProvider()
- }
- apiKey = cfg.Providers.Anthropic.APIKey
- apiBase = cfg.Providers.Anthropic.APIBase
- proxy = cfg.Providers.Anthropic.Proxy
- if apiBase == "" {
- apiBase = "https://api.anthropic.com/v1"
- }
-
- case (strings.Contains(lowerModel, "gpt") || strings.HasPrefix(model, "openai/")) && (cfg.Providers.OpenAI.APIKey != "" || cfg.Providers.OpenAI.AuthMethod != ""):
- if cfg.Providers.OpenAI.AuthMethod == "oauth" || cfg.Providers.OpenAI.AuthMethod == "token" {
- return createCodexAuthProvider()
- }
- apiKey = cfg.Providers.OpenAI.APIKey
- apiBase = cfg.Providers.OpenAI.APIBase
- proxy = cfg.Providers.OpenAI.Proxy
- if apiBase == "" {
- apiBase = "https://api.openai.com/v1"
- }
-
- case (strings.Contains(lowerModel, "gemini") || strings.HasPrefix(model, "google/")) && cfg.Providers.Gemini.APIKey != "":
- apiKey = cfg.Providers.Gemini.APIKey
- apiBase = cfg.Providers.Gemini.APIBase
- proxy = cfg.Providers.Gemini.Proxy
- if apiBase == "" {
- apiBase = "https://generativelanguage.googleapis.com/v1beta"
- }
-
- case (strings.Contains(lowerModel, "glm") || strings.Contains(lowerModel, "zhipu") || strings.Contains(lowerModel, "zai")) && cfg.Providers.Zhipu.APIKey != "":
- apiKey = cfg.Providers.Zhipu.APIKey
- apiBase = cfg.Providers.Zhipu.APIBase
- proxy = cfg.Providers.Zhipu.Proxy
- if apiBase == "" {
- apiBase = "https://open.bigmodel.cn/api/paas/v4"
- }
-
- case (strings.Contains(lowerModel, "groq") || strings.HasPrefix(model, "groq/")) && cfg.Providers.Groq.APIKey != "":
- apiKey = cfg.Providers.Groq.APIKey
- apiBase = cfg.Providers.Groq.APIBase
- proxy = cfg.Providers.Groq.Proxy
- if apiBase == "" {
- apiBase = "https://api.groq.com/openai/v1"
- }
-
- case (strings.Contains(lowerModel, "nvidia") || strings.HasPrefix(model, "nvidia/")) && cfg.Providers.Nvidia.APIKey != "":
- apiKey = cfg.Providers.Nvidia.APIKey
- apiBase = cfg.Providers.Nvidia.APIBase
- proxy = cfg.Providers.Nvidia.Proxy
- if apiBase == "" {
- apiBase = "https://integrate.api.nvidia.com/v1"
- }
-
- case cfg.Providers.VLLM.APIBase != "":
- apiKey = cfg.Providers.VLLM.APIKey
- apiBase = cfg.Providers.VLLM.APIBase
- proxy = cfg.Providers.VLLM.Proxy
-
- default:
- if cfg.Providers.OpenRouter.APIKey != "" {
- apiKey = cfg.Providers.OpenRouter.APIKey
- proxy = cfg.Providers.OpenRouter.Proxy
- if cfg.Providers.OpenRouter.APIBase != "" {
- apiBase = cfg.Providers.OpenRouter.APIBase
- } else {
- apiBase = "https://openrouter.ai/api/v1"
- }
- } else {
- return nil, fmt.Errorf("no API key configured for model: %s", model)
- }
+ var usage *UsageInfo
+ if resp.Usage != nil {
+ usage = &UsageInfo{
+ PromptTokens: resp.Usage.PromptTokens,
+ CompletionTokens: resp.Usage.CompletionTokens,
+ TotalTokens: resp.Usage.TotalTokens,
}
}
- if apiKey == "" && !strings.HasPrefix(model, "bedrock/") {
- return nil, fmt.Errorf("no API key configured for provider (model: %s)", model)
+ return &LLMResponse{
+ Content: resp.Content,
+ ToolCalls: fromOpenAICompatToolCalls(resp.ToolCalls),
+ FinishReason: resp.FinishReason,
+ Usage: usage,
}
-
- if apiBase == "" {
- return nil, fmt.Errorf("no API base configured for provider (model: %s)", model)
- }
-
- return NewHTTPProvider(apiKey, apiBase, proxy), nil
+}
+
+func fromOpenAICompatToolCalls(toolCalls []openai_compat.ToolCall) []ToolCall {
+ out := make([]ToolCall, 0, len(toolCalls))
+ for _, tc := range toolCalls {
+ var fn *FunctionCall
+ if tc.Function != nil {
+ fn = &FunctionCall{
+ Name: tc.Function.Name,
+ Arguments: tc.Function.Arguments,
+ }
+ }
+ out = append(out, ToolCall{
+ ID: tc.ID,
+ Type: tc.Type,
+ Function: fn,
+ Name: tc.Name,
+ Arguments: tc.Arguments,
+ })
+ }
+ return out
}
diff --git a/pkg/providers/openai_compat/provider.go b/pkg/providers/openai_compat/provider.go
new file mode 100644
index 000000000..4aef1389a
--- /dev/null
+++ b/pkg/providers/openai_compat/provider.go
@@ -0,0 +1,230 @@
+package openai_compat
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+type ToolCall struct {
+ ID string `json:"id"`
+ Type string `json:"type,omitempty"`
+ Function *FunctionCall `json:"function,omitempty"`
+ Name string `json:"name,omitempty"`
+ Arguments map[string]interface{} `json:"arguments,omitempty"`
+}
+
+type FunctionCall struct {
+ Name string `json:"name"`
+ Arguments string `json:"arguments"`
+}
+
+type LLMResponse struct {
+ Content string `json:"content"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ FinishReason string `json:"finish_reason"`
+ Usage *UsageInfo `json:"usage,omitempty"`
+}
+
+type UsageInfo struct {
+ PromptTokens int `json:"prompt_tokens"`
+ CompletionTokens int `json:"completion_tokens"`
+ TotalTokens int `json:"total_tokens"`
+}
+
+type Message struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ ToolCallID string `json:"tool_call_id,omitempty"`
+}
+
+type ToolDefinition struct {
+ Type string `json:"type"`
+ Function ToolFunctionDefinition `json:"function"`
+}
+
+type ToolFunctionDefinition struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Parameters map[string]interface{} `json:"parameters"`
+}
+
+type Provider struct {
+ apiKey string
+ apiBase string
+ httpClient *http.Client
+}
+
+func NewProvider(apiKey, apiBase string, proxy ...string) *Provider {
+ proxyURL := ""
+ if len(proxy) > 0 {
+ proxyURL = proxy[0]
+ }
+ client := &http.Client{
+ Timeout: 120 * time.Second,
+ }
+
+ if proxyURL != "" {
+ parsed, err := url.Parse(proxyURL)
+ if err == nil {
+ client.Transport = &http.Transport{
+ Proxy: http.ProxyURL(parsed),
+ }
+ }
+ }
+
+ return &Provider{
+ apiKey: apiKey,
+ apiBase: strings.TrimRight(apiBase, "/"),
+ httpClient: client,
+ }
+}
+
+func (p *Provider) Chat(ctx context.Context, messages []Message, tools []ToolDefinition, model string, options map[string]interface{}) (*LLMResponse, error) {
+ if p.apiBase == "" {
+ return nil, fmt.Errorf("API base not configured")
+ }
+
+ // Strip provider prefix (moonshot/kimi-*, nvidia/*) for OpenAI-compatible backends.
+ if idx := strings.Index(model, "/"); idx != -1 {
+ prefix := model[:idx]
+ if prefix == "moonshot" || prefix == "nvidia" {
+ model = model[idx+1:]
+ }
+ }
+
+ requestBody := map[string]interface{}{
+ "model": model,
+ "messages": messages,
+ }
+
+ if len(tools) > 0 {
+ requestBody["tools"] = tools
+ requestBody["tool_choice"] = "auto"
+ }
+
+ if maxTokens, ok := options["max_tokens"].(int); ok {
+ lowerModel := strings.ToLower(model)
+ if strings.Contains(lowerModel, "glm") || strings.Contains(lowerModel, "o1") {
+ requestBody["max_completion_tokens"] = maxTokens
+ } else {
+ requestBody["max_tokens"] = maxTokens
+ }
+ }
+
+ if temperature, ok := options["temperature"].(float64); ok {
+ lowerModel := strings.ToLower(model)
+ // Kimi k2 models only support temperature=1.
+ if strings.Contains(lowerModel, "kimi") && strings.Contains(lowerModel, "k2") {
+ requestBody["temperature"] = 1.0
+ } else {
+ requestBody["temperature"] = temperature
+ }
+ }
+
+ jsonData, err := json.Marshal(requestBody)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", p.apiBase+"/chat/completions", bytes.NewReader(jsonData))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ if p.apiKey != "" {
+ req.Header.Set("Authorization", "Bearer "+p.apiKey)
+ }
+
+ resp, err := p.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to send request: %w", err)
+ }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read response: %w", err)
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("API request failed:\n Status: %d\n Body: %s", resp.StatusCode, string(body))
+ }
+
+ return parseResponse(body)
+}
+
+func parseResponse(body []byte) (*LLMResponse, error) {
+ var apiResponse struct {
+ Choices []struct {
+ Message struct {
+ Content string `json:"content"`
+ ToolCalls []struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Function *struct {
+ Name string `json:"name"`
+ Arguments string `json:"arguments"`
+ } `json:"function"`
+ } `json:"tool_calls"`
+ } `json:"message"`
+ FinishReason string `json:"finish_reason"`
+ } `json:"choices"`
+ Usage *UsageInfo `json:"usage"`
+ }
+
+ if err := json.Unmarshal(body, &apiResponse); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal response: %w", err)
+ }
+
+ if len(apiResponse.Choices) == 0 {
+ return &LLMResponse{
+ Content: "",
+ FinishReason: "stop",
+ }, nil
+ }
+
+ choice := apiResponse.Choices[0]
+ toolCalls := make([]ToolCall, 0, len(choice.Message.ToolCalls))
+ for _, tc := range choice.Message.ToolCalls {
+ arguments := make(map[string]interface{})
+ name := ""
+
+ if tc.Type == "function" && tc.Function != nil {
+ name = tc.Function.Name
+ if tc.Function.Arguments != "" {
+ if err := json.Unmarshal([]byte(tc.Function.Arguments), &arguments); err != nil {
+ arguments["raw"] = tc.Function.Arguments
+ }
+ }
+ } else if tc.Function != nil {
+ name = tc.Function.Name
+ if tc.Function.Arguments != "" {
+ if err := json.Unmarshal([]byte(tc.Function.Arguments), &arguments); err != nil {
+ arguments["raw"] = tc.Function.Arguments
+ }
+ }
+ }
+
+ toolCalls = append(toolCalls, ToolCall{
+ ID: tc.ID,
+ Name: name,
+ Arguments: arguments,
+ })
+ }
+
+ return &LLMResponse{
+ Content: choice.Message.Content,
+ ToolCalls: toolCalls,
+ FinishReason: choice.FinishReason,
+ Usage: apiResponse.Usage,
+ }, nil
+}
diff --git a/pkg/providers/openai_compat/provider_test.go b/pkg/providers/openai_compat/provider_test.go
new file mode 100644
index 000000000..7c5f1c63c
--- /dev/null
+++ b/pkg/providers/openai_compat/provider_test.go
@@ -0,0 +1,149 @@
+package openai_compat
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestProviderChat_UsesMaxCompletionTokensForGLM(t *testing.T) {
+ var requestBody map[string]interface{}
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/chat/completions" {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ resp := map[string]interface{}{
+ "choices": []map[string]interface{}{
+ {
+ "message": map[string]interface{}{"content": "ok"},
+ "finish_reason": "stop",
+ },
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+ }))
+ defer server.Close()
+
+ p := NewProvider("key", server.URL)
+ _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "glm-4.7", map[string]interface{}{"max_tokens": 1234})
+ if err != nil {
+ t.Fatalf("Chat() error = %v", err)
+ }
+
+ if _, ok := requestBody["max_completion_tokens"]; !ok {
+ t.Fatalf("expected max_completion_tokens in request body")
+ }
+ if _, ok := requestBody["max_tokens"]; ok {
+ t.Fatalf("did not expect max_tokens key for glm model")
+ }
+}
+
+func TestProviderChat_ParsesToolCalls(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ resp := map[string]interface{}{
+ "choices": []map[string]interface{}{
+ {
+ "message": map[string]interface{}{
+ "content": "",
+ "tool_calls": []map[string]interface{}{
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": map[string]interface{}{
+ "name": "get_weather",
+ "arguments": "{\"city\":\"SF\"}",
+ },
+ },
+ },
+ },
+ "finish_reason": "tool_calls",
+ },
+ },
+ "usage": map[string]interface{}{
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+ }))
+ defer server.Close()
+
+ p := NewProvider("key", server.URL)
+ out, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "gpt-4o", nil)
+ if err != nil {
+ t.Fatalf("Chat() error = %v", err)
+ }
+ if len(out.ToolCalls) != 1 {
+ t.Fatalf("len(ToolCalls) = %d, want 1", len(out.ToolCalls))
+ }
+ if out.ToolCalls[0].Name != "get_weather" {
+ t.Fatalf("ToolCalls[0].Name = %q, want %q", out.ToolCalls[0].Name, "get_weather")
+ }
+ if out.ToolCalls[0].Arguments["city"] != "SF" {
+ t.Fatalf("ToolCalls[0].Arguments[city] = %v, want SF", out.ToolCalls[0].Arguments["city"])
+ }
+}
+
+func TestProviderChat_HTTPError(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ }))
+ defer server.Close()
+
+ p := NewProvider("key", server.URL)
+ _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "gpt-4o", nil)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+}
+
+func TestProviderChat_StripsMoonshotPrefixAndNormalizesKimiTemperature(t *testing.T) {
+ var requestBody map[string]interface{}
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ resp := map[string]interface{}{
+ "choices": []map[string]interface{}{
+ {
+ "message": map[string]interface{}{"content": "ok"},
+ "finish_reason": "stop",
+ },
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+ }))
+ defer server.Close()
+
+ p := NewProvider("key", server.URL)
+ _, err := p.Chat(
+ t.Context(),
+ []Message{{Role: "user", Content: "hi"}},
+ nil,
+ "moonshot/kimi-k2.5",
+ map[string]interface{}{"temperature": 0.3},
+ )
+ if err != nil {
+ t.Fatalf("Chat() error = %v", err)
+ }
+
+ if requestBody["model"] != "kimi-k2.5" {
+ t.Fatalf("model = %v, want kimi-k2.5", requestBody["model"])
+ }
+ if requestBody["temperature"] != 1.0 {
+ t.Fatalf("temperature = %v, want 1.0", requestBody["temperature"])
+ }
+}
From 762565b0d4406aee7fb617d0b5c46d85014ab04e Mon Sep 17 00:00:00 2001
From: Jared Mahotiere
Date: Sun, 15 Feb 2026 08:04:12 -0500
Subject: [PATCH 03/31] refactor(providers): move anthropic logic to protocol
package
---
pkg/providers/anthropic/provider.go | 241 +++++++++++++++++++
pkg/providers/anthropic/provider_test.go | 208 +++++++++++++++++
pkg/providers/claude_provider.go | 281 +++++++++--------------
pkg/providers/claude_provider_test.go | 137 +----------
4 files changed, 565 insertions(+), 302 deletions(-)
create mode 100644 pkg/providers/anthropic/provider.go
create mode 100644 pkg/providers/anthropic/provider_test.go
diff --git a/pkg/providers/anthropic/provider.go b/pkg/providers/anthropic/provider.go
new file mode 100644
index 000000000..ca72f0180
--- /dev/null
+++ b/pkg/providers/anthropic/provider.go
@@ -0,0 +1,241 @@
+package anthropicprovider
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/anthropics/anthropic-sdk-go"
+ "github.com/anthropics/anthropic-sdk-go/option"
+)
+
+type ToolCall struct {
+ ID string `json:"id"`
+ Type string `json:"type,omitempty"`
+ Function *FunctionCall `json:"function,omitempty"`
+ Name string `json:"name,omitempty"`
+ Arguments map[string]interface{} `json:"arguments,omitempty"`
+}
+
+type FunctionCall struct {
+ Name string `json:"name"`
+ Arguments string `json:"arguments"`
+}
+
+type LLMResponse struct {
+ Content string `json:"content"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ FinishReason string `json:"finish_reason"`
+ Usage *UsageInfo `json:"usage,omitempty"`
+}
+
+type UsageInfo struct {
+ PromptTokens int `json:"prompt_tokens"`
+ CompletionTokens int `json:"completion_tokens"`
+ TotalTokens int `json:"total_tokens"`
+}
+
+type Message struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ ToolCallID string `json:"tool_call_id,omitempty"`
+}
+
+type ToolDefinition struct {
+ Type string `json:"type"`
+ Function ToolFunctionDefinition `json:"function"`
+}
+
+type ToolFunctionDefinition struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Parameters map[string]interface{} `json:"parameters"`
+}
+
+type Provider struct {
+ client *anthropic.Client
+ tokenSource func() (string, error)
+}
+
+func NewProvider(token string) *Provider {
+ client := anthropic.NewClient(
+ option.WithAuthToken(token),
+ option.WithBaseURL("https://api.anthropic.com"),
+ )
+ return &Provider{client: &client}
+}
+
+func NewProviderWithClient(client *anthropic.Client) *Provider {
+ return &Provider{client: client}
+}
+
+func NewProviderWithTokenSource(token string, tokenSource func() (string, error)) *Provider {
+ p := NewProvider(token)
+ p.tokenSource = tokenSource
+ return p
+}
+
+func (p *Provider) Chat(ctx context.Context, messages []Message, tools []ToolDefinition, model string, options map[string]interface{}) (*LLMResponse, error) {
+ var opts []option.RequestOption
+ if p.tokenSource != nil {
+ tok, err := p.tokenSource()
+ if err != nil {
+ return nil, fmt.Errorf("refreshing token: %w", err)
+ }
+ opts = append(opts, option.WithAuthToken(tok))
+ }
+
+ params, err := buildParams(messages, tools, model, options)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := p.client.Messages.New(ctx, params, opts...)
+ if err != nil {
+ return nil, fmt.Errorf("claude API call: %w", err)
+ }
+
+ return parseResponse(resp), nil
+}
+
+func (p *Provider) GetDefaultModel() string {
+ return "claude-sonnet-4-5-20250929"
+}
+
+func buildParams(messages []Message, tools []ToolDefinition, model string, options map[string]interface{}) (anthropic.MessageNewParams, error) {
+ var system []anthropic.TextBlockParam
+ var anthropicMessages []anthropic.MessageParam
+
+ for _, msg := range messages {
+ switch msg.Role {
+ case "system":
+ system = append(system, anthropic.TextBlockParam{Text: msg.Content})
+ case "user":
+ if msg.ToolCallID != "" {
+ anthropicMessages = append(anthropicMessages,
+ anthropic.NewUserMessage(anthropic.NewToolResultBlock(msg.ToolCallID, msg.Content, false)),
+ )
+ } else {
+ anthropicMessages = append(anthropicMessages,
+ anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Content)),
+ )
+ }
+ case "assistant":
+ if len(msg.ToolCalls) > 0 {
+ var blocks []anthropic.ContentBlockParamUnion
+ if msg.Content != "" {
+ blocks = append(blocks, anthropic.NewTextBlock(msg.Content))
+ }
+ for _, tc := range msg.ToolCalls {
+ blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, tc.Arguments, tc.Name))
+ }
+ anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))
+ } else {
+ anthropicMessages = append(anthropicMessages,
+ anthropic.NewAssistantMessage(anthropic.NewTextBlock(msg.Content)),
+ )
+ }
+ case "tool":
+ anthropicMessages = append(anthropicMessages,
+ anthropic.NewUserMessage(anthropic.NewToolResultBlock(msg.ToolCallID, msg.Content, false)),
+ )
+ }
+ }
+
+ maxTokens := int64(4096)
+ if mt, ok := options["max_tokens"].(int); ok {
+ maxTokens = int64(mt)
+ }
+
+ params := anthropic.MessageNewParams{
+ Model: anthropic.Model(model),
+ Messages: anthropicMessages,
+ MaxTokens: maxTokens,
+ }
+
+ if len(system) > 0 {
+ params.System = system
+ }
+
+ if temp, ok := options["temperature"].(float64); ok {
+ params.Temperature = anthropic.Float(temp)
+ }
+
+ if len(tools) > 0 {
+ params.Tools = translateTools(tools)
+ }
+
+ return params, nil
+}
+
+func translateTools(tools []ToolDefinition) []anthropic.ToolUnionParam {
+ result := make([]anthropic.ToolUnionParam, 0, len(tools))
+ for _, t := range tools {
+ tool := anthropic.ToolParam{
+ Name: t.Function.Name,
+ InputSchema: anthropic.ToolInputSchemaParam{
+ Properties: t.Function.Parameters["properties"],
+ },
+ }
+ if desc := t.Function.Description; desc != "" {
+ tool.Description = anthropic.String(desc)
+ }
+ if req, ok := t.Function.Parameters["required"].([]interface{}); ok {
+ required := make([]string, 0, len(req))
+ for _, r := range req {
+ if s, ok := r.(string); ok {
+ required = append(required, s)
+ }
+ }
+ tool.InputSchema.Required = required
+ }
+ result = append(result, anthropic.ToolUnionParam{OfTool: &tool})
+ }
+ return result
+}
+
+func parseResponse(resp *anthropic.Message) *LLMResponse {
+ var content string
+ var toolCalls []ToolCall
+
+ for _, block := range resp.Content {
+ switch block.Type {
+ case "text":
+ tb := block.AsText()
+ content += tb.Text
+ case "tool_use":
+ tu := block.AsToolUse()
+ var args map[string]interface{}
+ if err := json.Unmarshal(tu.Input, &args); err != nil {
+ args = map[string]interface{}{"raw": string(tu.Input)}
+ }
+ toolCalls = append(toolCalls, ToolCall{
+ ID: tu.ID,
+ Name: tu.Name,
+ Arguments: args,
+ })
+ }
+ }
+
+ finishReason := "stop"
+ switch resp.StopReason {
+ case anthropic.StopReasonToolUse:
+ finishReason = "tool_calls"
+ case anthropic.StopReasonMaxTokens:
+ finishReason = "length"
+ case anthropic.StopReasonEndTurn:
+ finishReason = "stop"
+ }
+
+ return &LLMResponse{
+ Content: content,
+ ToolCalls: toolCalls,
+ FinishReason: finishReason,
+ Usage: &UsageInfo{
+ PromptTokens: int(resp.Usage.InputTokens),
+ CompletionTokens: int(resp.Usage.OutputTokens),
+ TotalTokens: int(resp.Usage.InputTokens + resp.Usage.OutputTokens),
+ },
+ }
+}
diff --git a/pkg/providers/anthropic/provider_test.go b/pkg/providers/anthropic/provider_test.go
new file mode 100644
index 000000000..01b4fe663
--- /dev/null
+++ b/pkg/providers/anthropic/provider_test.go
@@ -0,0 +1,208 @@
+package anthropicprovider
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/anthropics/anthropic-sdk-go"
+ anthropicoption "github.com/anthropics/anthropic-sdk-go/option"
+)
+
+func TestBuildParams_BasicMessage(t *testing.T) {
+ messages := []Message{
+ {Role: "user", Content: "Hello"},
+ }
+ params, err := buildParams(messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{
+ "max_tokens": 1024,
+ })
+ if err != nil {
+ t.Fatalf("buildParams() error: %v", err)
+ }
+ if string(params.Model) != "claude-sonnet-4-5-20250929" {
+ t.Errorf("Model = %q, want %q", params.Model, "claude-sonnet-4-5-20250929")
+ }
+ if params.MaxTokens != 1024 {
+ t.Errorf("MaxTokens = %d, want 1024", params.MaxTokens)
+ }
+ if len(params.Messages) != 1 {
+ t.Fatalf("len(Messages) = %d, want 1", len(params.Messages))
+ }
+}
+
+func TestBuildParams_SystemMessage(t *testing.T) {
+ messages := []Message{
+ {Role: "system", Content: "You are helpful"},
+ {Role: "user", Content: "Hi"},
+ }
+ params, err := buildParams(messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{})
+ if err != nil {
+ t.Fatalf("buildParams() error: %v", err)
+ }
+ if len(params.System) != 1 {
+ t.Fatalf("len(System) = %d, want 1", len(params.System))
+ }
+ if params.System[0].Text != "You are helpful" {
+ t.Errorf("System[0].Text = %q, want %q", params.System[0].Text, "You are helpful")
+ }
+ if len(params.Messages) != 1 {
+ t.Fatalf("len(Messages) = %d, want 1", len(params.Messages))
+ }
+}
+
+func TestBuildParams_ToolCallMessage(t *testing.T) {
+ messages := []Message{
+ {Role: "user", Content: "What's the weather?"},
+ {
+ Role: "assistant",
+ Content: "",
+ ToolCalls: []ToolCall{
+ {
+ ID: "call_1",
+ Name: "get_weather",
+ Arguments: map[string]interface{}{"city": "SF"},
+ },
+ },
+ },
+ {Role: "tool", Content: `{"temp": 72}`, ToolCallID: "call_1"},
+ }
+ params, err := buildParams(messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{})
+ if err != nil {
+ t.Fatalf("buildParams() error: %v", err)
+ }
+ if len(params.Messages) != 3 {
+ t.Fatalf("len(Messages) = %d, want 3", len(params.Messages))
+ }
+}
+
+func TestBuildParams_WithTools(t *testing.T) {
+ tools := []ToolDefinition{
+ {
+ Type: "function",
+ Function: ToolFunctionDefinition{
+ Name: "get_weather",
+ Description: "Get weather for a city",
+ Parameters: map[string]interface{}{
+ "type": "object",
+ "properties": map[string]interface{}{
+ "city": map[string]interface{}{"type": "string"},
+ },
+ "required": []interface{}{"city"},
+ },
+ },
+ },
+ }
+ params, err := buildParams([]Message{{Role: "user", Content: "Hi"}}, tools, "claude-sonnet-4-5-20250929", map[string]interface{}{})
+ if err != nil {
+ t.Fatalf("buildParams() error: %v", err)
+ }
+ if len(params.Tools) != 1 {
+ t.Fatalf("len(Tools) = %d, want 1", len(params.Tools))
+ }
+}
+
+func TestParseResponse_TextOnly(t *testing.T) {
+ resp := &anthropic.Message{
+ Content: []anthropic.ContentBlockUnion{},
+ Usage: anthropic.Usage{
+ InputTokens: 10,
+ OutputTokens: 20,
+ },
+ }
+ result := parseResponse(resp)
+ if result.Usage.PromptTokens != 10 {
+ t.Errorf("PromptTokens = %d, want 10", result.Usage.PromptTokens)
+ }
+ if result.Usage.CompletionTokens != 20 {
+ t.Errorf("CompletionTokens = %d, want 20", result.Usage.CompletionTokens)
+ }
+ if result.FinishReason != "stop" {
+ t.Errorf("FinishReason = %q, want %q", result.FinishReason, "stop")
+ }
+}
+
+func TestParseResponse_StopReasons(t *testing.T) {
+ tests := []struct {
+ stopReason anthropic.StopReason
+ want string
+ }{
+ {anthropic.StopReasonEndTurn, "stop"},
+ {anthropic.StopReasonMaxTokens, "length"},
+ {anthropic.StopReasonToolUse, "tool_calls"},
+ }
+ for _, tt := range tests {
+ resp := &anthropic.Message{
+ StopReason: tt.stopReason,
+ }
+ result := parseResponse(resp)
+ if result.FinishReason != tt.want {
+ t.Errorf("StopReason %q: FinishReason = %q, want %q", tt.stopReason, result.FinishReason, tt.want)
+ }
+ }
+}
+
+func TestProvider_ChatRoundTrip(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/messages" {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ if r.Header.Get("Authorization") != "Bearer test-token" {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+
+ var reqBody map[string]interface{}
+ json.NewDecoder(r.Body).Decode(&reqBody)
+
+ resp := map[string]interface{}{
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": reqBody["model"],
+ "stop_reason": "end_turn",
+ "content": []map[string]interface{}{
+ {"type": "text", "text": "Hello! How can I help you?"},
+ },
+ "usage": map[string]interface{}{
+ "input_tokens": 15,
+ "output_tokens": 8,
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+ }))
+ defer server.Close()
+
+ provider := NewProviderWithClient(createAnthropicTestClient(server.URL, "test-token"))
+ messages := []Message{{Role: "user", Content: "Hello"}}
+ resp, err := provider.Chat(t.Context(), messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{"max_tokens": 1024})
+ if err != nil {
+ t.Fatalf("Chat() error: %v", err)
+ }
+ if resp.Content != "Hello! How can I help you?" {
+ t.Errorf("Content = %q, want %q", resp.Content, "Hello! How can I help you?")
+ }
+ if resp.FinishReason != "stop" {
+ t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop")
+ }
+ if resp.Usage.PromptTokens != 15 {
+ t.Errorf("PromptTokens = %d, want 15", resp.Usage.PromptTokens)
+ }
+}
+
+func TestProvider_GetDefaultModel(t *testing.T) {
+ p := NewProvider("test-token")
+ if got := p.GetDefaultModel(); got != "claude-sonnet-4-5-20250929" {
+ t.Errorf("GetDefaultModel() = %q, want %q", got, "claude-sonnet-4-5-20250929")
+ }
+}
+
+func createAnthropicTestClient(baseURL, token string) *anthropic.Client {
+ c := anthropic.NewClient(
+ anthropicoption.WithAuthToken(token),
+ anthropicoption.WithBaseURL(baseURL),
+ )
+ return &c
+}
diff --git a/pkg/providers/claude_provider.go b/pkg/providers/claude_provider.go
index ae6aca96d..16f1884c5 100644
--- a/pkg/providers/claude_provider.go
+++ b/pkg/providers/claude_provider.go
@@ -2,195 +2,48 @@ package providers
import (
"context"
- "encoding/json"
"fmt"
- "github.com/anthropics/anthropic-sdk-go"
- "github.com/anthropics/anthropic-sdk-go/option"
"github.com/sipeed/picoclaw/pkg/auth"
+ anthropicprovider "github.com/sipeed/picoclaw/pkg/providers/anthropic"
)
type ClaudeProvider struct {
- client *anthropic.Client
- tokenSource func() (string, error)
+ delegate *anthropicprovider.Provider
}
func NewClaudeProvider(token string) *ClaudeProvider {
- client := anthropic.NewClient(
- option.WithAuthToken(token),
- option.WithBaseURL("https://api.anthropic.com"),
- )
- return &ClaudeProvider{client: &client}
+ return &ClaudeProvider{
+ delegate: anthropicprovider.NewProvider(token),
+ }
}
func NewClaudeProviderWithTokenSource(token string, tokenSource func() (string, error)) *ClaudeProvider {
- p := NewClaudeProvider(token)
- p.tokenSource = tokenSource
- return p
+ return &ClaudeProvider{
+ delegate: anthropicprovider.NewProviderWithTokenSource(token, tokenSource),
+ }
+}
+
+func newClaudeProviderWithDelegate(delegate *anthropicprovider.Provider) *ClaudeProvider {
+ return &ClaudeProvider{delegate: delegate}
}
func (p *ClaudeProvider) Chat(ctx context.Context, messages []Message, tools []ToolDefinition, model string, options map[string]interface{}) (*LLMResponse, error) {
- var opts []option.RequestOption
- if p.tokenSource != nil {
- tok, err := p.tokenSource()
- if err != nil {
- return nil, fmt.Errorf("refreshing token: %w", err)
- }
- opts = append(opts, option.WithAuthToken(tok))
- }
-
- params, err := buildClaudeParams(messages, tools, model, options)
+ resp, err := p.delegate.Chat(
+ ctx,
+ toAnthropicProviderMessages(messages),
+ toAnthropicProviderTools(tools),
+ model,
+ options,
+ )
if err != nil {
return nil, err
}
-
- resp, err := p.client.Messages.New(ctx, params, opts...)
- if err != nil {
- return nil, fmt.Errorf("claude API call: %w", err)
- }
-
- return parseClaudeResponse(resp), nil
+ return fromAnthropicProviderResponse(resp), nil
}
func (p *ClaudeProvider) GetDefaultModel() string {
- return "claude-sonnet-4-5-20250929"
-}
-
-func buildClaudeParams(messages []Message, tools []ToolDefinition, model string, options map[string]interface{}) (anthropic.MessageNewParams, error) {
- var system []anthropic.TextBlockParam
- var anthropicMessages []anthropic.MessageParam
-
- for _, msg := range messages {
- switch msg.Role {
- case "system":
- system = append(system, anthropic.TextBlockParam{Text: msg.Content})
- case "user":
- if msg.ToolCallID != "" {
- anthropicMessages = append(anthropicMessages,
- anthropic.NewUserMessage(anthropic.NewToolResultBlock(msg.ToolCallID, msg.Content, false)),
- )
- } else {
- anthropicMessages = append(anthropicMessages,
- anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Content)),
- )
- }
- case "assistant":
- if len(msg.ToolCalls) > 0 {
- var blocks []anthropic.ContentBlockParamUnion
- if msg.Content != "" {
- blocks = append(blocks, anthropic.NewTextBlock(msg.Content))
- }
- for _, tc := range msg.ToolCalls {
- blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, tc.Arguments, tc.Name))
- }
- anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))
- } else {
- anthropicMessages = append(anthropicMessages,
- anthropic.NewAssistantMessage(anthropic.NewTextBlock(msg.Content)),
- )
- }
- case "tool":
- anthropicMessages = append(anthropicMessages,
- anthropic.NewUserMessage(anthropic.NewToolResultBlock(msg.ToolCallID, msg.Content, false)),
- )
- }
- }
-
- maxTokens := int64(4096)
- if mt, ok := options["max_tokens"].(int); ok {
- maxTokens = int64(mt)
- }
-
- params := anthropic.MessageNewParams{
- Model: anthropic.Model(model),
- Messages: anthropicMessages,
- MaxTokens: maxTokens,
- }
-
- if len(system) > 0 {
- params.System = system
- }
-
- if temp, ok := options["temperature"].(float64); ok {
- params.Temperature = anthropic.Float(temp)
- }
-
- if len(tools) > 0 {
- params.Tools = translateToolsForClaude(tools)
- }
-
- return params, nil
-}
-
-func translateToolsForClaude(tools []ToolDefinition) []anthropic.ToolUnionParam {
- result := make([]anthropic.ToolUnionParam, 0, len(tools))
- for _, t := range tools {
- tool := anthropic.ToolParam{
- Name: t.Function.Name,
- InputSchema: anthropic.ToolInputSchemaParam{
- Properties: t.Function.Parameters["properties"],
- },
- }
- if desc := t.Function.Description; desc != "" {
- tool.Description = anthropic.String(desc)
- }
- if req, ok := t.Function.Parameters["required"].([]interface{}); ok {
- required := make([]string, 0, len(req))
- for _, r := range req {
- if s, ok := r.(string); ok {
- required = append(required, s)
- }
- }
- tool.InputSchema.Required = required
- }
- result = append(result, anthropic.ToolUnionParam{OfTool: &tool})
- }
- return result
-}
-
-func parseClaudeResponse(resp *anthropic.Message) *LLMResponse {
- var content string
- var toolCalls []ToolCall
-
- for _, block := range resp.Content {
- switch block.Type {
- case "text":
- tb := block.AsText()
- content += tb.Text
- case "tool_use":
- tu := block.AsToolUse()
- var args map[string]interface{}
- if err := json.Unmarshal(tu.Input, &args); err != nil {
- args = map[string]interface{}{"raw": string(tu.Input)}
- }
- toolCalls = append(toolCalls, ToolCall{
- ID: tu.ID,
- Name: tu.Name,
- Arguments: args,
- })
- }
- }
-
- finishReason := "stop"
- switch resp.StopReason {
- case anthropic.StopReasonToolUse:
- finishReason = "tool_calls"
- case anthropic.StopReasonMaxTokens:
- finishReason = "length"
- case anthropic.StopReasonEndTurn:
- finishReason = "stop"
- }
-
- return &LLMResponse{
- Content: content,
- ToolCalls: toolCalls,
- FinishReason: finishReason,
- Usage: &UsageInfo{
- PromptTokens: int(resp.Usage.InputTokens),
- CompletionTokens: int(resp.Usage.OutputTokens),
- TotalTokens: int(resp.Usage.InputTokens + resp.Usage.OutputTokens),
- },
- }
+ return p.delegate.GetDefaultModel()
}
func createClaudeTokenSource() func() (string, error) {
@@ -205,3 +58,95 @@ func createClaudeTokenSource() func() (string, error) {
return cred.AccessToken, nil
}
}
+
+func toAnthropicProviderMessages(messages []Message) []anthropicprovider.Message {
+ out := make([]anthropicprovider.Message, 0, len(messages))
+ for _, msg := range messages {
+ out = append(out, anthropicprovider.Message{
+ Role: msg.Role,
+ Content: msg.Content,
+ ToolCalls: toAnthropicProviderToolCalls(msg.ToolCalls),
+ ToolCallID: msg.ToolCallID,
+ })
+ }
+ return out
+}
+
+func toAnthropicProviderTools(tools []ToolDefinition) []anthropicprovider.ToolDefinition {
+ out := make([]anthropicprovider.ToolDefinition, 0, len(tools))
+ for _, t := range tools {
+ out = append(out, anthropicprovider.ToolDefinition{
+ Type: t.Type,
+ Function: anthropicprovider.ToolFunctionDefinition{
+ Name: t.Function.Name,
+ Description: t.Function.Description,
+ Parameters: t.Function.Parameters,
+ },
+ })
+ }
+ return out
+}
+
+func toAnthropicProviderToolCalls(toolCalls []ToolCall) []anthropicprovider.ToolCall {
+ out := make([]anthropicprovider.ToolCall, 0, len(toolCalls))
+ for _, tc := range toolCalls {
+ var fn *anthropicprovider.FunctionCall
+ if tc.Function != nil {
+ fn = &anthropicprovider.FunctionCall{
+ Name: tc.Function.Name,
+ Arguments: tc.Function.Arguments,
+ }
+ }
+ out = append(out, anthropicprovider.ToolCall{
+ ID: tc.ID,
+ Type: tc.Type,
+ Function: fn,
+ Name: tc.Name,
+ Arguments: tc.Arguments,
+ })
+ }
+ return out
+}
+
+func fromAnthropicProviderResponse(resp *anthropicprovider.LLMResponse) *LLMResponse {
+ if resp == nil {
+ return &LLMResponse{}
+ }
+
+ var usage *UsageInfo
+ if resp.Usage != nil {
+ usage = &UsageInfo{
+ PromptTokens: resp.Usage.PromptTokens,
+ CompletionTokens: resp.Usage.CompletionTokens,
+ TotalTokens: resp.Usage.TotalTokens,
+ }
+ }
+
+ return &LLMResponse{
+ Content: resp.Content,
+ ToolCalls: fromAnthropicProviderToolCalls(resp.ToolCalls),
+ FinishReason: resp.FinishReason,
+ Usage: usage,
+ }
+}
+
+func fromAnthropicProviderToolCalls(toolCalls []anthropicprovider.ToolCall) []ToolCall {
+ out := make([]ToolCall, 0, len(toolCalls))
+ for _, tc := range toolCalls {
+ var fn *FunctionCall
+ if tc.Function != nil {
+ fn = &FunctionCall{
+ Name: tc.Function.Name,
+ Arguments: tc.Function.Arguments,
+ }
+ }
+ out = append(out, ToolCall{
+ ID: tc.ID,
+ Type: tc.Type,
+ Function: fn,
+ Name: tc.Name,
+ Arguments: tc.Arguments,
+ })
+ }
+ return out
+}
diff --git a/pkg/providers/claude_provider_test.go b/pkg/providers/claude_provider_test.go
index bbad2d269..13bbde1fc 100644
--- a/pkg/providers/claude_provider_test.go
+++ b/pkg/providers/claude_provider_test.go
@@ -8,140 +8,9 @@ import (
"github.com/anthropics/anthropic-sdk-go"
anthropicoption "github.com/anthropics/anthropic-sdk-go/option"
+ anthropicprovider "github.com/sipeed/picoclaw/pkg/providers/anthropic"
)
-func TestBuildClaudeParams_BasicMessage(t *testing.T) {
- messages := []Message{
- {Role: "user", Content: "Hello"},
- }
- params, err := buildClaudeParams(messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{
- "max_tokens": 1024,
- })
- if err != nil {
- t.Fatalf("buildClaudeParams() error: %v", err)
- }
- if string(params.Model) != "claude-sonnet-4-5-20250929" {
- t.Errorf("Model = %q, want %q", params.Model, "claude-sonnet-4-5-20250929")
- }
- if params.MaxTokens != 1024 {
- t.Errorf("MaxTokens = %d, want 1024", params.MaxTokens)
- }
- if len(params.Messages) != 1 {
- t.Fatalf("len(Messages) = %d, want 1", len(params.Messages))
- }
-}
-
-func TestBuildClaudeParams_SystemMessage(t *testing.T) {
- messages := []Message{
- {Role: "system", Content: "You are helpful"},
- {Role: "user", Content: "Hi"},
- }
- params, err := buildClaudeParams(messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{})
- if err != nil {
- t.Fatalf("buildClaudeParams() error: %v", err)
- }
- if len(params.System) != 1 {
- t.Fatalf("len(System) = %d, want 1", len(params.System))
- }
- if params.System[0].Text != "You are helpful" {
- t.Errorf("System[0].Text = %q, want %q", params.System[0].Text, "You are helpful")
- }
- if len(params.Messages) != 1 {
- t.Fatalf("len(Messages) = %d, want 1", len(params.Messages))
- }
-}
-
-func TestBuildClaudeParams_ToolCallMessage(t *testing.T) {
- messages := []Message{
- {Role: "user", Content: "What's the weather?"},
- {
- Role: "assistant",
- Content: "",
- ToolCalls: []ToolCall{
- {
- ID: "call_1",
- Name: "get_weather",
- Arguments: map[string]interface{}{"city": "SF"},
- },
- },
- },
- {Role: "tool", Content: `{"temp": 72}`, ToolCallID: "call_1"},
- }
- params, err := buildClaudeParams(messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{})
- if err != nil {
- t.Fatalf("buildClaudeParams() error: %v", err)
- }
- if len(params.Messages) != 3 {
- t.Fatalf("len(Messages) = %d, want 3", len(params.Messages))
- }
-}
-
-func TestBuildClaudeParams_WithTools(t *testing.T) {
- tools := []ToolDefinition{
- {
- Type: "function",
- Function: ToolFunctionDefinition{
- Name: "get_weather",
- Description: "Get weather for a city",
- Parameters: map[string]interface{}{
- "type": "object",
- "properties": map[string]interface{}{
- "city": map[string]interface{}{"type": "string"},
- },
- "required": []interface{}{"city"},
- },
- },
- },
- }
- params, err := buildClaudeParams([]Message{{Role: "user", Content: "Hi"}}, tools, "claude-sonnet-4-5-20250929", map[string]interface{}{})
- if err != nil {
- t.Fatalf("buildClaudeParams() error: %v", err)
- }
- if len(params.Tools) != 1 {
- t.Fatalf("len(Tools) = %d, want 1", len(params.Tools))
- }
-}
-
-func TestParseClaudeResponse_TextOnly(t *testing.T) {
- resp := &anthropic.Message{
- Content: []anthropic.ContentBlockUnion{},
- Usage: anthropic.Usage{
- InputTokens: 10,
- OutputTokens: 20,
- },
- }
- result := parseClaudeResponse(resp)
- if result.Usage.PromptTokens != 10 {
- t.Errorf("PromptTokens = %d, want 10", result.Usage.PromptTokens)
- }
- if result.Usage.CompletionTokens != 20 {
- t.Errorf("CompletionTokens = %d, want 20", result.Usage.CompletionTokens)
- }
- if result.FinishReason != "stop" {
- t.Errorf("FinishReason = %q, want %q", result.FinishReason, "stop")
- }
-}
-
-func TestParseClaudeResponse_StopReasons(t *testing.T) {
- tests := []struct {
- stopReason anthropic.StopReason
- want string
- }{
- {anthropic.StopReasonEndTurn, "stop"},
- {anthropic.StopReasonMaxTokens, "length"},
- {anthropic.StopReasonToolUse, "tool_calls"},
- }
- for _, tt := range tests {
- resp := &anthropic.Message{
- StopReason: tt.stopReason,
- }
- result := parseClaudeResponse(resp)
- if result.FinishReason != tt.want {
- t.Errorf("StopReason %q: FinishReason = %q, want %q", tt.stopReason, result.FinishReason, tt.want)
- }
- }
-}
-
func TestClaudeProvider_ChatRoundTrip(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/messages" {
@@ -175,8 +44,8 @@ func TestClaudeProvider_ChatRoundTrip(t *testing.T) {
}))
defer server.Close()
- provider := NewClaudeProvider("test-token")
- provider.client = createAnthropicTestClient(server.URL, "test-token")
+ delegate := anthropicprovider.NewProviderWithClient(createAnthropicTestClient(server.URL, "test-token"))
+ provider := newClaudeProviderWithDelegate(delegate)
messages := []Message{{Role: "user", Content: "Hello"}}
resp, err := provider.Chat(t.Context(), messages, nil, "claude-sonnet-4-5-20250929", map[string]interface{}{"max_tokens": 1024})
From 362c49a69d0465b711153e1ab14eeaaeb779eee6 Mon Sep 17 00:00:00 2001
From: Jared Mahotiere
Date: Sun, 15 Feb 2026 08:04:16 -0500
Subject: [PATCH 04/31] docs(test): document protocol architecture and
migration compatibility
---
README.md | 10 ++++++++++
pkg/migrate/migrate_test.go | 18 ++++++++++++++++++
2 files changed, 28 insertions(+)
diff --git a/README.md b/README.md
index 091af2811..25c6d9863 100644
--- a/README.md
+++ b/README.md
@@ -662,6 +662,16 @@ The subagent has access to tools (message, web_search, etc.) and can communicate
| `deepseek(To be tested)` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) |
| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) |
+### Provider Architecture
+
+PicoClaw routes providers by protocol family:
+
+- OpenAI-compatible protocol: OpenRouter, OpenAI-compatible gateways, Groq, Zhipu, and vLLM-style endpoints.
+- Anthropic protocol: Claude-native API behavior.
+- Codex/OAuth path: OpenAI OAuth/token authentication route.
+
+This keeps the runtime lightweight while making new OpenAI-compatible backends mostly a config operation (`api_base` + `api_key`).
+
Zhipu
diff --git a/pkg/migrate/migrate_test.go b/pkg/migrate/migrate_test.go
index be2360aac..e930d45f4 100644
--- a/pkg/migrate/migrate_test.go
+++ b/pkg/migrate/migrate_test.go
@@ -299,6 +299,24 @@ func TestConvertConfig(t *testing.T) {
})
}
+func TestSupportedProvidersCompatibility(t *testing.T) {
+ expected := []string{
+ "anthropic",
+ "openai",
+ "openrouter",
+ "groq",
+ "zhipu",
+ "vllm",
+ "gemini",
+ }
+
+ for _, provider := range expected {
+ if !supportedProviders[provider] {
+ t.Fatalf("supportedProviders missing expected key %q", provider)
+ }
+ }
+}
+
func TestMergeConfig(t *testing.T) {
t.Run("fills empty fields", func(t *testing.T) {
existing := config.DefaultConfig()
From 97bf4ff3fddd99c5a6a1d9a74a4e7637f34d7063 Mon Sep 17 00:00:00 2001
From: Yasuhiro Matsumoto
Date: Sun, 15 Feb 2026 23:56:13 +0900
Subject: [PATCH 05/31] Fix Japanese translation
---
README.ja.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/README.ja.md b/README.ja.md
index e33b312f9..706af2c75 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -3,7 +3,7 @@
PicoClaw: Go で書かれた超効率 AI アシスタント
-$10 ハードウェア · 10MB RAM · 1秒起動 · 皮皮虾,我们走!
+$10 ハードウェア · 10MB RAM · 1秒起動 · 行くぜ、シャコ!
@@ -39,7 +39,7 @@
## 📢 ニュース
-2026-02-09 🎉 PicoClaw リリース!$10 ハードウェアで 10MB 未満の RAM で動く AI エージェントを 1 日で構築。🦐 皮皮虾,我们走!
+2026-02-09 🎉 PicoClaw リリース!$10 ハードウェアで 10MB 未満の RAM で動く AI エージェントを 1 日で構築。🦐 行くぜ、シャコ!
## ✨ 特徴
@@ -729,7 +729,7 @@ Discord: https://discord.gg/V4sAZ9XWpN
## 🐛 トラブルシューティング
-### Web 検索で「API 配置问题」と表示される
+### Web 検索で「API 設定の問題」と表示される
検索 API キーをまだ設定していない場合、これは正常です。PicoClaw は手動検索用の便利なリンクを提供します。
From 7ce5b75178356d4c81044faa6d2ea06cd69ec507 Mon Sep 17 00:00:00 2001
From: Yasuhiro Matsumoto
Date: Mon, 16 Feb 2026 00:47:17 +0900
Subject: [PATCH 06/31] Fix shadowing field runnnig
---
pkg/channels/maixcam.go | 2 --
1 file changed, 2 deletions(-)
diff --git a/pkg/channels/maixcam.go b/pkg/channels/maixcam.go
index 5fc19adbe..01e570b25 100644
--- a/pkg/channels/maixcam.go
+++ b/pkg/channels/maixcam.go
@@ -18,7 +18,6 @@ type MaixCamChannel struct {
listener net.Listener
clients map[net.Conn]bool
clientsMux sync.RWMutex
- running bool
}
type MaixCamMessage struct {
@@ -35,7 +34,6 @@ func NewMaixCamChannel(cfg config.MaixCamConfig, bus *bus.MessageBus) (*MaixCamC
BaseChannel: base,
config: cfg,
clients: make(map[net.Conn]bool),
- running: false,
}, nil
}
From ff3c875b3fad1116a7ea7e22a10034a741b38f18 Mon Sep 17 00:00:00 2001
From: Humaid Koreshi
Date: Tue, 17 Feb 2026 02:15:59 +0600
Subject: [PATCH 07/31] docs: add missing Chinese language link to Japanese
README
---
README.ja.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.ja.md b/README.ja.md
index e33b312f9..c6babf510 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -12,7 +12,7 @@
-**日本語** | [English](README.md)
+[中文](README.zh.md) | **日本語** | [English](README.md)
From 57dac394c517615b542d545008ad611252eadeb9 Mon Sep 17 00:00:00 2001
From: zepan
Date: Tue, 17 Feb 2026 09:30:30 +0800
Subject: [PATCH 08/31] update pr template
---
.github/pull_request_template.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
create mode 100644 .github/pull_request_template.md
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 000000000..d2773e27d
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,32 @@
+## 📝 Description
+## 🗣️ Type of Change
+- [ ] 🐞 Bug fix (non-breaking change which fixes an issue)
+- [ ] ✨ New feature (non-breaking change which adds functionality)
+- [ ] 📖 Documentation update
+- [ ] ⚡ Code refactoring (no functional changes, no api changes)
+
+
+## 🔗 Linked Issue
+## 📚 Technical Context (Skip for Docs)
+* **Reference:** [URL]
+* **Reasoning:** ...
+
+
+## 🧪 Test Environment & Hardware
+- **Hardware:** [e.g. Raspberry Pi 5, Orange Pi, PC]
+- **OS:** [e.g. Debian 12, Ubuntu 22.04]
+- **Model/Provider:** [e.g. OpenAI GPT-4o, Kimi k2, DeepSeek-V3]
+- **Channels:** [e.g. Discord, Telegram, Feishu, ...]
+
+
+## 📸 Proof of Work (Optional for Docs)
+
+Click to view Logs/Screenshots
+
+
+
+
+## ☑️ Checklist
+- [ ] My code/docs follow the style of this project.
+- [ ] I have performed a self-review of my own changes.
+- [ ] I have updated the documentation accordingly.
\ No newline at end of file
From 75fb728a1161a6a92e17f3470f9b28508c0daada Mon Sep 17 00:00:00 2001
From: AlbertBui010
Date: Tue, 17 Feb 2026 09:17:03 +0700
Subject: [PATCH 09/31] docs: add Vietnamese README (README.vi.md)
- Add full Vietnamese translation of README.md
- Update language selector links in README.md, README.zh.md, README.ja.md
---
README.ja.md | 2 +-
README.md | 2 +-
README.vi.md | 859 +++++++++++++++++++++++++++++++++++++++++++++++++++
README.zh.md | 2 +-
4 files changed, 862 insertions(+), 3 deletions(-)
create mode 100644 README.vi.md
diff --git a/README.ja.md b/README.ja.md
index e33b312f9..fa4eae69a 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -12,7 +12,7 @@
-**日本語** | [English](README.md)
+**日本語** | [Tiếng Việt](README.vi.md) | [English](README.md)
diff --git a/README.md b/README.md
index 0a9dacce6..6ec28a315 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@
- [中文](README.zh.md) | [日本語](README.ja.md) | **English**
+ [中文](README.zh.md) | [日本語](README.ja.md) | [Tiếng Việt](README.vi.md) | **English**
---
diff --git a/README.vi.md b/README.vi.md
new file mode 100644
index 000000000..533ef7607
--- /dev/null
+++ b/README.vi.md
@@ -0,0 +1,859 @@
+
+

+
+
PicoClaw: Trợ lý AI Siêu Nhẹ viết bằng Go
+
+
Phần cứng $10 · RAM 10MB · Khởi động 1 giây · 皮皮虾,我们走!
+
+
+
+
+
+
+
+
+
+
+ [中文](README.zh.md) | [日本語](README.ja.md) | [English](README.md) | **Tiếng Việt**
+
+
+---
+
+🦐 **PicoClaw** là trợ lý AI cá nhân siêu nhẹ, lấy cảm hứng từ [nanobot](https://github.com/HKUDS/nanobot), được viết lại hoàn toàn bằng **Go** thông qua quá trình "tự khởi tạo" (self-bootstrapping) — nơi chính AI Agent đã tự dẫn dắt toàn bộ quá trình chuyển đổi kiến trúc và tối ưu hóa mã nguồn.
+
+⚡️ **Cực kỳ nhẹ:** Chạy trên phần cứng chỉ **$10** với RAM **<10MB**. Tiết kiệm 99% bộ nhớ so với OpenClaw và rẻ hơn 98% so với Mac mini!
+
+
+
+|
+
+
+
+ |
+
+
+
+
+ |
+
+
+
+> [!CAUTION]
+> **🚨 TUYÊN BỐ BẢO MẬT & KÊNH CHÍNH THỨC**
+>
+> * **KHÔNG CÓ CRYPTO:** PicoClaw **KHÔNG** có bất kỳ token/coin chính thức nào. Mọi thông tin trên `pump.fun` hoặc các sàn giao dịch khác đều là **LỪA ĐẢO**.
+> * **DOMAIN CHÍNH THỨC:** Website chính thức **DUY NHẤT** là **[picoclaw.io](https://picoclaw.io)**, website công ty là **[sipeed.com](https://sipeed.com)**.
+> * **Cảnh báo:** Nhiều tên miền `.ai/.org/.com/.net/...` đã bị bên thứ ba đăng ký, không phải của chúng tôi.
+> * **Cảnh báo:** PicoClaw đang trong giai đoạn phát triển sớm và có thể còn các vấn đề bảo mật mạng chưa được giải quyết. Không nên triển khai lên môi trường production trước phiên bản v1.0.
+> * **Lưu ý:** PicoClaw gần đây đã merge nhiều PR, dẫn đến bộ nhớ sử dụng có thể lớn hơn (10–20MB) ở các phiên bản mới nhất. Chúng tôi sẽ ưu tiên tối ưu tài nguyên khi bộ tính năng đã ổn định.
+
+
+## 📢 Tin tức
+
+2026-02-16 🎉 PicoClaw đạt 12K stars chỉ trong một tuần! Cảm ơn tất cả mọi người! PicoClaw đang phát triển nhanh hơn chúng tôi tưởng tượng. Do số lượng PR tăng cao, chúng tôi cấp thiết cần maintainer từ cộng đồng. Các vai trò tình nguyện viên và roadmap đã được công bố [tại đây](doc/picoclaw_community_roadmap_260216.md) — rất mong đón nhận sự tham gia của bạn!
+
+2026-02-13 🎉 PicoClaw đạt 5000 stars trong 4 ngày! Cảm ơn cộng đồng! Chúng tôi đang hoàn thiện **Lộ trình dự án (Roadmap)** và thiết lập **Nhóm phát triển** để đẩy nhanh tốc độ phát triển PicoClaw.
+🚀 **Kêu gọi hành động:** Vui lòng gửi yêu cầu tính năng tại GitHub Discussions. Chúng tôi sẽ xem xét và ưu tiên trong cuộc họp hàng tuần.
+
+2026-02-09 🎉 PicoClaw chính thức ra mắt! Được xây dựng trong 1 ngày để mang AI Agent đến phần cứng $10 với RAM <10MB. 🦐 PicoClaw, Lên Đường!
+
+## ✨ Tính năng nổi bật
+
+🪶 **Siêu nhẹ**: Bộ nhớ sử dụng <10MB — nhỏ hơn 99% so với Clawdbot (chức năng cốt lõi).
+
+💰 **Chi phí tối thiểu**: Đủ hiệu quả để chạy trên phần cứng $10 — rẻ hơn 98% so với Mac mini.
+
+⚡️ **Khởi động siêu nhanh**: Nhanh gấp 400 lần, khởi động trong 1 giây ngay cả trên CPU đơn nhân 0.6GHz.
+
+🌍 **Di động thực sự**: Một file binary duy nhất chạy trên RISC-V, ARM và x86. Một click là chạy!
+
+🤖 **AI tự xây dựng**: Triển khai Go-native tự động — 95% mã nguồn cốt lõi được Agent tạo ra, với sự tinh chỉnh của con người.
+
+| | OpenClaw | NanoBot | **PicoClaw** |
+| ----------------------------- | ------------- | ------------------------ | ----------------------------------------- |
+| **Ngôn ngữ** | TypeScript | Python | **Go** |
+| **RAM** | >1GB | >100MB | **< 10MB** |
+| **Thời gian khởi động**(CPU 0.8GHz) | >500s | >30s | **<1s** |
+| **Chi phí** | Mac Mini $599 | Hầu hết SBC Linux ~$50 | **Mọi bo mạch Linux****Chỉ từ $10** |
+
+
+
+## 🦾 Demo
+
+### 🛠️ Quy trình trợ lý tiêu chuẩn
+
+
+
+🧩 Lập trình Full-Stack |
+🗂️ Quản lý Nhật ký & Kế hoạch |
+🔎 Tìm kiếm Web & Học hỏi |
+
+
+
|
+
|
+
|
+
+
+| Phát triển • Triển khai • Mở rộng |
+Lên lịch • Tự động hóa • Ghi nhớ |
+Khám phá • Phân tích • Xu hướng |
+
+
+
+### 🐜 Triển khai sáng tạo trên phần cứng tối thiểu
+
+PicoClaw có thể triển khai trên hầu hết mọi thiết bị Linux!
+
+* $9.9 [LicheeRV-Nano](https://www.aliexpress.com/item/1005006519668532.html) phiên bản E (Ethernet) hoặc W (WiFi6), dùng làm Trợ lý Gia đình tối giản.
+* $30~50 [NanoKVM](https://www.aliexpress.com/item/1005007369816019.html), hoặc $100 [NanoKVM-Pro](https://www.aliexpress.com/item/1005010048471263.html), dùng cho quản trị Server tự động.
+* $50 [MaixCAM](https://www.aliexpress.com/item/1005008053333693.html) hoặc $100 [MaixCAM2](https://www.kickstarter.com/projects/zepan/maixcam2-build-your-next-gen-4k-ai-camera), dùng cho Giám sát thông minh.
+
+https://private-user-images.githubusercontent.com/83055338/547056448-e7b031ff-d6f5-4468-bcca-5726b6fecb5c.mp4
+
+🌟 Nhiều hình thức triển khai hơn đang chờ bạn khám phá!
+
+## 📦 Cài đặt
+
+### Cài đặt bằng binary biên dịch sẵn
+
+Tải file binary cho nền tảng của bạn từ [trang Release](https://github.com/sipeed/picoclaw/releases).
+
+### Cài đặt từ mã nguồn (có tính năng mới nhất, khuyên dùng cho phát triển)
+
+```bash
+git clone https://github.com/sipeed/picoclaw.git
+
+cd picoclaw
+make deps
+
+# Build (không cần cài đặt)
+make build
+
+# Build cho nhiều nền tảng
+make build-all
+
+# Build và cài đặt
+make install
+```
+
+## 🐳 Docker Compose
+
+Bạn cũng có thể chạy PicoClaw bằng Docker Compose mà không cần cài đặt gì trên máy.
+
+```bash
+# 1. Clone repo
+git clone https://github.com/sipeed/picoclaw.git
+cd picoclaw
+
+# 2. Thiết lập API Key
+cp config/config.example.json config/config.json
+vim config/config.json # Thiết lập DISCORD_BOT_TOKEN, API keys, v.v.
+
+# 3. Build & Khởi động
+docker compose --profile gateway up -d
+
+# 4. Xem logs
+docker compose logs -f picoclaw-gateway
+
+# 5. Dừng
+docker compose --profile gateway down
+```
+
+### Chế độ Agent (chạy một lần)
+
+```bash
+# Đặt câu hỏi
+docker compose run --rm picoclaw-agent -m "2+2 bằng mấy?"
+
+# Chế độ tương tác
+docker compose run --rm picoclaw-agent
+```
+
+### Build lại
+
+```bash
+docker compose --profile gateway build --no-cache
+docker compose --profile gateway up -d
+```
+
+### 🚀 Bắt đầu nhanh
+
+> [!TIP]
+> Thiết lập API key trong `~/.picoclaw/config.json`.
+> Lấy API key: [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM)
+> Tìm kiếm web là **tùy chọn** — lấy [Brave Search API](https://brave.com/search/api) miễn phí (2000 truy vấn/tháng) hoặc dùng tính năng auto fallback tích hợp sẵn.
+
+**1. Khởi tạo**
+
+```bash
+picoclaw onboard
+```
+
+**2. Cấu hình** (`~/.picoclaw/config.json`)
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "workspace": "~/.picoclaw/workspace",
+ "model": "glm-4.7",
+ "max_tokens": 8192,
+ "temperature": 0.7,
+ "max_tool_iterations": 20
+ }
+ },
+ "providers": {
+ "openrouter": {
+ "api_key": "xxx",
+ "api_base": "https://openrouter.ai/api/v1"
+ }
+ },
+ "tools": {
+ "web": {
+ "brave": {
+ "enabled": false,
+ "api_key": "YOUR_BRAVE_API_KEY",
+ "max_results": 5
+ },
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ }
+ }
+ }
+}
+```
+
+**3. Lấy API Key**
+
+* **Nhà cung cấp LLM**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys)
+* **Tìm kiếm Web** (tùy chọn): [Brave Search](https://brave.com/search/api) — Có gói miễn phí (2000 truy vấn/tháng)
+
+> **Lưu ý**: Xem `config.example.json` để có mẫu cấu hình đầy đủ.
+
+**4. Trò chuyện**
+
+```bash
+picoclaw agent -m "Xin chào, bạn là ai?"
+```
+
+Vậy là xong! Bạn đã có một trợ lý AI hoạt động chỉ trong 2 phút.
+
+---
+
+## 💬 Tích hợp ứng dụng Chat
+
+Trò chuyện với PicoClaw qua Telegram, Discord, DingTalk hoặc LINE.
+
+| Kênh | Mức độ thiết lập |
+| --- | --- |
+| **Telegram** | Dễ (chỉ cần token) |
+| **Discord** | Dễ (bot token + intents) |
+| **QQ** | Dễ (AppID + AppSecret) |
+| **DingTalk** | Trung bình (app credentials) |
+| **LINE** | Trung bình (credentials + webhook URL) |
+
+
+Telegram (Khuyên dùng)
+
+**1. Tạo bot**
+
+* Mở Telegram, tìm `@BotFather`
+* Gửi `/newbot`, làm theo hướng dẫn
+* Sao chép token
+
+**2. Cấu hình**
+
+```json
+{
+ "channels": {
+ "telegram": {
+ "enabled": true,
+ "token": "YOUR_BOT_TOKEN",
+ "allowFrom": ["YOUR_USER_ID"]
+ }
+ }
+}
+```
+
+> Lấy User ID từ `@userinfobot` trên Telegram.
+
+**3. Chạy**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+Discord
+
+**1. Tạo bot**
+
+* Truy cập
+* Create an application → Bot → Add Bot
+* Sao chép bot token
+
+**2. Bật Intents**
+
+* Trong phần Bot settings, bật **MESSAGE CONTENT INTENT**
+* (Tùy chọn) Bật **SERVER MEMBERS INTENT** nếu muốn dùng danh sách cho phép theo thông tin thành viên
+
+**3. Lấy User ID**
+
+* Discord Settings → Advanced → bật **Developer Mode**
+* Click chuột phải vào avatar → **Copy User ID**
+
+**4. Cấu hình**
+
+```json
+{
+ "channels": {
+ "discord": {
+ "enabled": true,
+ "token": "YOUR_BOT_TOKEN",
+ "allowFrom": ["YOUR_USER_ID"]
+ }
+ }
+}
+```
+
+**5. Mời bot vào server**
+
+* OAuth2 → URL Generator
+* Scopes: `bot`
+* Bot Permissions: `Send Messages`, `Read Message History`
+* Mở URL mời được tạo và thêm bot vào server của bạn
+
+**6. Chạy**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+QQ
+
+**1. Tạo bot**
+
+* Truy cập [QQ Open Platform](https://q.qq.com/#)
+* Tạo ứng dụng → Lấy **AppID** và **AppSecret**
+
+**2. Cấu hình**
+
+```json
+{
+ "channels": {
+ "qq": {
+ "enabled": true,
+ "app_id": "YOUR_APP_ID",
+ "app_secret": "YOUR_APP_SECRET",
+ "allow_from": []
+ }
+ }
+}
+```
+
+> Để `allow_from` trống để cho phép tất cả người dùng, hoặc chỉ định số QQ để giới hạn quyền truy cập.
+
+**3. Chạy**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+DingTalk
+
+**1. Tạo bot**
+
+* Truy cập [Open Platform](https://open.dingtalk.com/)
+* Tạo ứng dụng nội bộ
+* Sao chép Client ID và Client Secret
+
+**2. Cấu hình**
+
+```json
+{
+ "channels": {
+ "dingtalk": {
+ "enabled": true,
+ "client_id": "YOUR_CLIENT_ID",
+ "client_secret": "YOUR_CLIENT_SECRET",
+ "allow_from": []
+ }
+ }
+}
+```
+
+> Để `allow_from` trống để cho phép tất cả người dùng, hoặc chỉ định ID để giới hạn quyền truy cập.
+
+**3. Chạy**
+
+```bash
+picoclaw gateway
+```
+
+
+
+
+LINE
+
+**1. Tạo tài khoản LINE Official**
+
+- Truy cập [LINE Developers Console](https://developers.line.biz/)
+- Tạo provider → Tạo Messaging API channel
+- Sao chép **Channel Secret** và **Channel Access Token**
+
+**2. Cấu hình**
+
+```json
+{
+ "channels": {
+ "line": {
+ "enabled": true,
+ "channel_secret": "YOUR_CHANNEL_SECRET",
+ "channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
+ "webhook_host": "0.0.0.0",
+ "webhook_port": 18791,
+ "webhook_path": "/webhook/line",
+ "allow_from": []
+ }
+ }
+}
+```
+
+**3. Thiết lập Webhook URL**
+
+LINE yêu cầu HTTPS cho webhook. Sử dụng reverse proxy hoặc tunnel:
+
+```bash
+# Ví dụ với ngrok
+ngrok http 18791
+```
+
+Sau đó cài đặt Webhook URL trong LINE Developers Console thành `https://your-domain/webhook/line` và bật **Use webhook**.
+
+**4. Chạy**
+
+```bash
+picoclaw gateway
+```
+
+> Trong nhóm chat, bot chỉ phản hồi khi được @mention. Các câu trả lời sẽ trích dẫn tin nhắn gốc.
+
+> **Docker Compose**: Thêm `ports: ["18791:18791"]` vào service `picoclaw-gateway` để mở port webhook.
+
+
+
+##
Tham gia Mạng xã hội Agent
+
+Kết nối PicoClaw với Mạng xã hội Agent chỉ bằng cách gửi một tin nhắn qua CLI hoặc bất kỳ ứng dụng Chat nào đã tích hợp.
+
+**Đọc `https://clawdchat.ai/skill.md` và làm theo hướng dẫn để tham gia [ClawdChat.ai](https://clawdchat.ai)**
+
+## ⚙️ Cấu hình chi tiết
+
+File cấu hình: `~/.picoclaw/config.json`
+
+### Cấu trúc Workspace
+
+PicoClaw lưu trữ dữ liệu trong workspace đã cấu hình (mặc định: `~/.picoclaw/workspace`):
+
+```
+~/.picoclaw/workspace/
+├── sessions/ # Phiên hội thoại và lịch sử
+├── memory/ # Bộ nhớ dài hạn (MEMORY.md)
+├── state/ # Trạng thái lưu trữ (kênh cuối cùng, v.v.)
+├── cron/ # Cơ sở dữ liệu tác vụ định kỳ
+├── skills/ # Kỹ năng tùy chỉnh
+├── AGENTS.md # Hướng dẫn hành vi Agent
+├── HEARTBEAT.md # Prompt tác vụ định kỳ (kiểm tra mỗi 30 phút)
+├── IDENTITY.md # Danh tính Agent
+├── SOUL.md # Tâm hồn/Tính cách Agent
+├── TOOLS.md # Mô tả công cụ
+└── USER.md # Tùy chọn người dùng
+```
+
+### 🔒 Hộp cát bảo mật (Security Sandbox)
+
+PicoClaw chạy trong môi trường sandbox theo mặc định. Agent chỉ có thể truy cập file và thực thi lệnh trong phạm vi workspace.
+
+#### Cấu hình mặc định
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "workspace": "~/.picoclaw/workspace",
+ "restrict_to_workspace": true
+ }
+ }
+}
+```
+
+| Tùy chọn | Mặc định | Mô tả |
+|----------|---------|-------|
+| `workspace` | `~/.picoclaw/workspace` | Thư mục làm việc của agent |
+| `restrict_to_workspace` | `true` | Giới hạn truy cập file/lệnh trong workspace |
+
+#### Công cụ được bảo vệ
+
+Khi `restrict_to_workspace: true`, các công cụ sau bị giới hạn trong sandbox:
+
+| Công cụ | Chức năng | Giới hạn |
+|---------|----------|---------|
+| `read_file` | Đọc file | Chỉ file trong workspace |
+| `write_file` | Ghi file | Chỉ file trong workspace |
+| `list_dir` | Liệt kê thư mục | Chỉ thư mục trong workspace |
+| `edit_file` | Sửa file | Chỉ file trong workspace |
+| `append_file` | Thêm vào file | Chỉ file trong workspace |
+| `exec` | Thực thi lệnh | Đường dẫn lệnh phải trong workspace |
+
+#### Bảo vệ bổ sung cho Exec
+
+Ngay cả khi `restrict_to_workspace: false`, công cụ `exec` vẫn chặn các lệnh nguy hiểm sau:
+
+* `rm -rf`, `del /f`, `rmdir /s` — Xóa hàng loạt
+* `format`, `mkfs`, `diskpart` — Định dạng ổ đĩa
+* `dd if=` — Tạo ảnh đĩa
+* Ghi vào `/dev/sd[a-z]` — Ghi trực tiếp lên đĩa
+* `shutdown`, `reboot`, `poweroff` — Tắt/khởi động lại hệ thống
+* Fork bomb `:(){ :|:& };:`
+
+#### Ví dụ lỗi
+
+```
+[ERROR] tool: Tool execution failed
+{tool=exec, error=Command blocked by safety guard (path outside working dir)}
+```
+
+```
+[ERROR] tool: Tool execution failed
+{tool=exec, error=Command blocked by safety guard (dangerous pattern detected)}
+```
+
+#### Tắt giới hạn (Rủi ro bảo mật)
+
+Nếu bạn cần agent truy cập đường dẫn ngoài workspace:
+
+**Cách 1: File cấu hình**
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "restrict_to_workspace": false
+ }
+ }
+}
+```
+
+**Cách 2: Biến môi trường**
+
+```bash
+export PICOCLAW_AGENTS_DEFAULTS_RESTRICT_TO_WORKSPACE=false
+```
+
+> ⚠️ **Cảnh báo**: Tắt giới hạn này cho phép agent truy cập mọi đường dẫn trên hệ thống. Chỉ sử dụng cẩn thận trong môi trường được kiểm soát.
+
+#### Tính nhất quán của ranh giới bảo mật
+
+Cài đặt `restrict_to_workspace` áp dụng nhất quán trên mọi đường thực thi:
+
+| Đường thực thi | Ranh giới bảo mật |
+|----------------|-------------------|
+| Agent chính | `restrict_to_workspace` ✅ |
+| Subagent / Spawn | Kế thừa cùng giới hạn ✅ |
+| Tác vụ Heartbeat | Kế thừa cùng giới hạn ✅ |
+
+Tất cả đường thực thi chia sẻ cùng giới hạn workspace — không có cách nào vượt qua ranh giới bảo mật thông qua subagent hoặc tác vụ định kỳ.
+
+### Heartbeat (Tác vụ định kỳ)
+
+PicoClaw có thể tự động thực hiện các tác vụ định kỳ. Tạo file `HEARTBEAT.md` trong workspace:
+
+```markdown
+# Tác vụ định kỳ
+
+- Kiểm tra email xem có tin nhắn quan trọng không
+- Xem lại lịch cho các sự kiện sắp tới
+- Kiểm tra dự báo thời tiết
+```
+
+Agent sẽ đọc file này mỗi 30 phút (có thể cấu hình) và thực hiện các tác vụ bằng công cụ có sẵn.
+
+#### Tác vụ bất đồng bộ với Spawn
+
+Đối với các tác vụ chạy lâu (tìm kiếm web, gọi API), sử dụng công cụ `spawn` để tạo **subagent**:
+
+```markdown
+# Tác vụ định kỳ
+
+## Tác vụ nhanh (trả lời trực tiếp)
+- Báo cáo thời gian hiện tại
+
+## Tác vụ lâu (dùng spawn cho async)
+- Tìm kiếm tin tức AI trên web và tóm tắt
+- Kiểm tra email và báo cáo tin nhắn quan trọng
+```
+
+**Hành vi chính:**
+
+| Tính năng | Mô tả |
+|-----------|-------|
+| **spawn** | Tạo subagent bất đồng bộ, không chặn heartbeat |
+| **Context độc lập** | Subagent có context riêng, không có lịch sử phiên |
+| **message tool** | Subagent giao tiếp trực tiếp với người dùng qua công cụ message |
+| **Không chặn** | Sau khi spawn, heartbeat tiếp tục tác vụ tiếp theo |
+
+#### Cách Subagent giao tiếp
+
+```
+Heartbeat kích hoạt
+ ↓
+Agent đọc HEARTBEAT.md
+ ↓
+Tác vụ lâu: spawn subagent
+ ↓ ↓
+Tiếp tục tác vụ tiếp theo Subagent làm việc độc lập
+ ↓ ↓
+Tất cả tác vụ hoàn thành Subagent dùng công cụ "message"
+ ↓ ↓
+Phản hồi HEARTBEAT_OK Người dùng nhận kết quả trực tiếp
+```
+
+Subagent có quyền truy cập các công cụ (message, web_search, v.v.) và có thể giao tiếp với người dùng một cách độc lập mà không cần thông qua agent chính.
+
+**Cấu hình:**
+
+```json
+{
+ "heartbeat": {
+ "enabled": true,
+ "interval": 30
+ }
+}
+```
+
+| Tùy chọn | Mặc định | Mô tả |
+|----------|---------|-------|
+| `enabled` | `true` | Bật/tắt heartbeat |
+| `interval` | `30` | Khoảng thời gian kiểm tra (phút, tối thiểu: 5) |
+
+**Biến môi trường:**
+
+* `PICOCLAW_HEARTBEAT_ENABLED=false` để tắt
+* `PICOCLAW_HEARTBEAT_INTERVAL=60` để thay đổi khoảng thời gian
+
+### Nhà cung cấp (Providers)
+
+> [!NOTE]
+> Groq cung cấp dịch vụ chuyển giọng nói thành văn bản miễn phí qua Whisper. Nếu đã cấu hình Groq, tin nhắn thoại trên Telegram sẽ được tự động chuyển thành văn bản.
+
+| Nhà cung cấp | Mục đích | Lấy API Key |
+| --- | --- | --- |
+| `gemini` | LLM (Gemini trực tiếp) | [aistudio.google.com](https://aistudio.google.com) |
+| `zhipu` | LLM (Zhipu trực tiếp) | [bigmodel.cn](bigmodel.cn) |
+| `openrouter` (Đang thử nghiệm) | LLM (khuyên dùng, truy cập mọi model) | [openrouter.ai](https://openrouter.ai) |
+| `anthropic` (Đang thử nghiệm) | LLM (Claude trực tiếp) | [console.anthropic.com](https://console.anthropic.com) |
+| `openai` (Đang thử nghiệm) | LLM (GPT trực tiếp) | [platform.openai.com](https://platform.openai.com) |
+| `deepseek` (Đang thử nghiệm) | LLM (DeepSeek trực tiếp) | [platform.deepseek.com](https://platform.deepseek.com) |
+| `groq` | LLM + **Chuyển giọng nói** (Whisper) | [console.groq.com](https://console.groq.com) |
+
+
+Cấu hình Zhipu
+
+**1. Lấy API key**
+
+* Lấy [API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)
+
+**2. Cấu hình**
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "workspace": "~/.picoclaw/workspace",
+ "model": "glm-4.7",
+ "max_tokens": 8192,
+ "temperature": 0.7,
+ "max_tool_iterations": 20
+ }
+ },
+ "providers": {
+ "zhipu": {
+ "api_key": "Your API Key",
+ "api_base": "https://open.bigmodel.cn/api/paas/v4"
+ }
+ }
+}
+```
+
+**3. Chạy**
+
+```bash
+picoclaw agent -m "Xin chào"
+```
+
+
+
+
+Ví dụ cấu hình đầy đủ
+
+```json
+{
+ "agents": {
+ "defaults": {
+ "model": "anthropic/claude-opus-4-5"
+ }
+ },
+ "providers": {
+ "openrouter": {
+ "api_key": "sk-or-v1-xxx"
+ },
+ "groq": {
+ "api_key": "gsk_xxx"
+ }
+ },
+ "channels": {
+ "telegram": {
+ "enabled": true,
+ "token": "123456:ABC...",
+ "allow_from": ["123456789"]
+ },
+ "discord": {
+ "enabled": true,
+ "token": "",
+ "allow_from": [""]
+ },
+ "whatsapp": {
+ "enabled": false
+ },
+ "feishu": {
+ "enabled": false,
+ "app_id": "cli_xxx",
+ "app_secret": "xxx",
+ "encrypt_key": "",
+ "verification_token": "",
+ "allow_from": []
+ },
+ "qq": {
+ "enabled": false,
+ "app_id": "",
+ "app_secret": "",
+ "allow_from": []
+ }
+ },
+ "tools": {
+ "web": {
+ "brave": {
+ "enabled": false,
+ "api_key": "BSA...",
+ "max_results": 5
+ },
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ }
+ }
+ },
+ "heartbeat": {
+ "enabled": true,
+ "interval": 30
+ }
+}
+```
+
+
+
+## Tham chiếu CLI
+
+| Lệnh | Mô tả |
+| --- | --- |
+| `picoclaw onboard` | Khởi tạo cấu hình & workspace |
+| `picoclaw agent -m "..."` | Trò chuyện với agent |
+| `picoclaw agent` | Chế độ chat tương tác |
+| `picoclaw gateway` | Khởi động gateway (cho bot chat) |
+| `picoclaw status` | Hiển thị trạng thái |
+| `picoclaw cron list` | Liệt kê tất cả tác vụ định kỳ |
+| `picoclaw cron add ...` | Thêm tác vụ định kỳ |
+
+### Tác vụ định kỳ / Nhắc nhở
+
+PicoClaw hỗ trợ nhắc nhở theo lịch và tác vụ lặp lại thông qua công cụ `cron`:
+
+* **Nhắc nhở một lần**: "Remind me in 10 minutes" (Nhắc tôi sau 10 phút) → kích hoạt một lần sau 10 phút
+* **Tác vụ lặp lại**: "Remind me every 2 hours" (Nhắc tôi mỗi 2 giờ) → kích hoạt mỗi 2 giờ
+* **Biểu thức Cron**: "Remind me at 9am daily" (Nhắc tôi lúc 9 giờ sáng mỗi ngày) → sử dụng biểu thức cron
+
+Các tác vụ được lưu trong `~/.picoclaw/workspace/cron/` và được xử lý tự động.
+
+## 🤝 Đóng góp & Lộ trình
+
+Chào đón mọi PR! Mã nguồn được thiết kế nhỏ gọn và dễ đọc. 🤗
+
+Lộ trình sắp được công bố...
+
+Nhóm phát triển đang được xây dựng. Điều kiện tham gia: Ít nhất 1 PR đã được merge.
+
+Nhóm người dùng:
+
+Discord:
+
+
+
+## 🐛 Xử lý sự cố
+
+### Tìm kiếm web hiện "API 配置问题"
+
+Điều này là bình thường nếu bạn chưa cấu hình API key cho tìm kiếm. PicoClaw sẽ cung cấp các liên kết hữu ích để tìm kiếm thủ công.
+
+Để bật tìm kiếm web:
+
+1. **Tùy chọn 1 (Khuyên dùng)**: Lấy API key miễn phí tại [https://brave.com/search/api](https://brave.com/search/api) (2000 truy vấn miễn phí/tháng) để có kết quả tốt nhất.
+2. **Tùy chọn 2 (Không cần thẻ tín dụng)**: Nếu không có key, hệ thống tự động chuyển sang dùng **DuckDuckGo** (không cần key).
+
+Thêm key vào `~/.picoclaw/config.json` nếu dùng Brave:
+
+```json
+{
+ "tools": {
+ "web": {
+ "brave": {
+ "enabled": true,
+ "api_key": "YOUR_BRAVE_API_KEY",
+ "max_results": 5
+ },
+ "duckduckgo": {
+ "enabled": true,
+ "max_results": 5
+ }
+ }
+ }
+}
+```
+
+### Gặp lỗi lọc nội dung (Content Filtering)
+
+Một số nhà cung cấp (như Zhipu) có bộ lọc nội dung nghiêm ngặt. Thử diễn đạt lại câu hỏi hoặc sử dụng model khác.
+
+### Telegram bot báo "Conflict: terminated by other getUpdates"
+
+Điều này xảy ra khi có một instance bot khác đang chạy. Đảm bảo chỉ có một tiến trình `picoclaw gateway` chạy tại một thời điểm.
+
+---
+
+## 📝 So sánh API Key
+
+| Dịch vụ | Gói miễn phí | Trường hợp sử dụng |
+| --- | --- | --- |
+| **OpenRouter** | 200K tokens/tháng | Đa model (Claude, GPT-4, v.v.) |
+| **Zhipu** | 200K tokens/tháng | Tốt nhất cho người dùng Trung Quốc |
+| **Brave Search** | 2000 truy vấn/tháng | Chức năng tìm kiếm web |
+| **Groq** | Có gói miễn phí | Suy luận siêu nhanh (Llama, Mixtral) |
diff --git a/README.zh.md b/README.zh.md
index 2ca2987bb..ceddb170c 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -14,7 +14,7 @@
- **中文** | [日本語](README.ja.md) | [English](README.md)
+ **中文** | [日本語](README.ja.md) | [Tiếng Việt](README.vi.md) | [English](README.md)
---
From a961a2df878342af8522aead61361534663fc73f Mon Sep 17 00:00:00 2001
From: Guoguo <16666742+imguoguo@users.noreply.github.com>
Date: Tue, 17 Feb 2026 14:32:51 +0800
Subject: [PATCH 10/31] fix(ci): use env var for release tag (#342)
Signed-off-by: Guoguo
---
.github/workflows/release.yml | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index f9987b35f..9fe3a684e 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -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
From 0fadbcd340dfa7dc9b5fde7dfba413ba1d5831d0 Mon Sep 17 00:00:00 2001
From: zepan
Date: Tue, 17 Feb 2026 16:03:07 +0800
Subject: [PATCH 11/31] 1. add roadmap.md
---
ROADMAP.md | 116 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 116 insertions(+)
create mode 100644 ROADMAP.md
diff --git a/ROADMAP.md b/ROADMAP.md
new file mode 100644
index 000000000..8c5c0e252
--- /dev/null
+++ b/ROADMAP.md
@@ -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!
\ No newline at end of file
From ac4b16dfb4bc961507b0385d32b089ee955ca7a6 Mon Sep 17 00:00:00 2001
From: zepan
Date: Tue, 17 Feb 2026 16:51:38 +0800
Subject: [PATCH 12/31] 1. rename doc to docs
---
README.md | 2 +-
README.zh.md | 2 +-
{doc => docs}/picoclaw_community_roadmap_260216.md | 0
3 files changed, 2 insertions(+), 2 deletions(-)
rename {doc => docs}/picoclaw_community_roadmap_260216.md (100%)
diff --git a/README.md b/README.md
index 0a9dacce6..29fddb7e3 100644
--- a/README.md
+++ b/README.md
@@ -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 can’t 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 can’t 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.
diff --git a/README.zh.md b/README.zh.md
index 2ca2987bb..8b59effa3 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -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)。我们将在接下来的周会上进行审查和优先级排序。
diff --git a/doc/picoclaw_community_roadmap_260216.md b/docs/picoclaw_community_roadmap_260216.md
similarity index 100%
rename from doc/picoclaw_community_roadmap_260216.md
rename to docs/picoclaw_community_roadmap_260216.md
From 951b05d2550202f8ebbdf89eb39e582991fffb97 Mon Sep 17 00:00:00 2001
From: zepan
Date: Tue, 17 Feb 2026 17:15:40 +0800
Subject: [PATCH 13/31] 1. add AI Code Generation selection in pr template
---
.github/pull_request_template.md | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index d2773e27d..7910cb1e2 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -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)
From 5fb2721d22d3e8d45d5969d5219e76dd34ff8ec6 Mon Sep 17 00:00:00 2001
From: zepan
Date: Tue, 17 Feb 2026 18:01:39 +0800
Subject: [PATCH 14/31] 1. add android phone termux quick guide
---
README.md | 14 ++++++++++++++
README.zh.md | 17 +++++++++++++++++
assets/termux.jpg | Bin 0 -> 99784 bytes
3 files changed, 31 insertions(+)
create mode 100644 assets/termux.jpg
diff --git a/README.md b/README.md
index 29fddb7e3..a6f421e9d 100644
--- a/README.md
+++ b/README.md
@@ -99,6 +99,20 @@
+### 📱 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!
+
+
### 🐜 Innovative Low-Footprint Deploy
PicoClaw can be deployed on almost any Linux device!
diff --git a/README.zh.md b/README.zh.md
index 8b59effa3..b09adf74a 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -100,6 +100,23 @@
+### 📱 在手机上轻松运行
+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即可使用!
+
+
+
+
+
### 🐜 创新的低占用部署
PicoClaw 几乎可以部署在任何 Linux 设备上!
diff --git a/assets/termux.jpg b/assets/termux.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..30c724a2054885569cca76286d7d5c81e9f88a5d
GIT binary patch
literal 99784
zcmcG#byQr>wl3Oe;}TpNNU$VWaA-UP3&Ab8ySsbPKw|-dySsaU0NuE|y9RfE{Id5s
zXTSIEAMd^~?(8wws_s>5Rn4+*)i-B9&pxjLa6XGmi38x^-~f^@AHee(0j-#uxd{Lu
zCG{SF0ssKu0c>#a0Q{E}-HV!sAOhfC&fpgneo?j$Y+T?EY+zPyDpqbVCp(yx_2t)p
z1Ob2m_piLjFW=zc|CP3QNyGm;UGvXFU*!2e>+zEHp8}p20HOe7L?mP+L}X+nWFQb3
z1q}xc4HXp)9}61;hX|jTmhJ2cLOM2>WTEyYX3Cc
zzXc8+;ibMn6jU_ymkf0{0C+eA1b9RQBqT({m)zbj*8zyQNUvVAiXh`D=mX!_Sjb0g!h561a#-ke!A7l<1yzO|M#KvNEk=D%@Mh4kI6_?Skm||607ZEuqM&8y
z*6Qaf0t!vzt_Cz^$GAPsgv3`8M8^;Bt|Cg2jL$0VYXOe6fvpd7$1Ux|08NE_DaPKX
zx9uUe39nQ!L!PLkQK94Ba=e_P3Xs110QPm%qc^TGG!BqXqM_B*bP-CS8Ax_r_gS#r
z6V^F8iVGakUEMhuKp)(Ier^=o1{GufoN($TU0%J*b&b~soh!?a5e~U-LIJ~jbp-m4
z;zHa2!Ile>7oO5)oCAfwM#wWoiA>BJ$^1yjWH&B4pcd#QOavyeBIPp9uT|09m0AW2
z;0&$4sDz1`18@iE-7R)o;iRQkZH*ekv{Zj`5OIymkn*S{Y($4)>!E@-BbHQ^}Zs7-(
z_U0B
z!Yt@OKlK{(@wg#OzY`u6@SCmNuP}UFDQA?Coe}V=CrAQqjFZ)w=qDCDI9;Q
z+ocBrR@2=(pe2Bzxqxpg{}t
zPqVxTju#uLk*zT^F)gHgBJFQ;yDI0@$B-FXEfOeqFdpUWU657;Dmc29$u<
z?9a;aFZvYuFwT8IXwF}|G^HGWM8B6n`58PrYaJ3iZ#TVCT{xis~YTNV~!7>ya4)A9_E#JwpVllpL*a`klkFtbUX8pH?DB>zB;pln4wx6Y(t
zG#yLwrpf-Q?(Dj^F*@<1BnhpuS3%mNy~1NoS4o`UcaN-Z;^c&sZ(SDUhR$uYb0Qp2
zh!12YmW6I4FLfEjVm(cM8cb>;o2iY+B?4)svC;kv&RfR-O
zR`+s!L>`OqL%X1^1g(u_w^|EM<(&%Tm73TlPx2eV?z_(6(po7~7791fWMs)SBYD@O
zx@JyBu6*bS;e4EVP7B3ovA>J6N#cIjWn5LM1a_GP%t;M
zWbak4P&`0F3|}7Zf1$_?K^w`|+KMYk5sF7jByk?@)=eKHUVYxglAtd<&^C$vMa%Vv
z$%b(&gs`JDi58g9g3OwZr_VFY8q>?OS@&9xV}P)hau19B!_ykM;pu?}HT#|;86W5-dw{ZPCz=wCyPS>jGjDfPT`kej^
z^|i@M->kke@^87M0}%ovA}~_@zpA+;7o&&KC5#L}Jgb;~n;zF1eaR$uK?6HG?QEBR
z=Wz;|aMfOvO!QIiesA=!VVi(G5J8!ebvL1bt~i}@mtTg00_ZNYK`am91>X~jC~
zlAX)*rr#PnhaU~o5zlqTE(B+A0u!9yLW>eQyVFY|GlZ%Ou%sdZSLndGx6RVBS(ZibGxd9yTQ
z@|6E%9jbnVa9#mKQHQ5vc#3~@!;iI7;4QplD{IMM#EC{2t_o<5_9G7OYgh8qw1SF!
zi?pYB&w?QC=+FimsJ4Sk{RG6@7nbMj)-X|fYh(SO#6MFR*+(ig@cOdcWdvEEu;8>f6qUYYWZ?dP_tb+~4%!{XKq4+;I2O;QJtUd-G=m8-s5qsQ7Ok*&As
zM-bc_UMRQGPQK$rp7qLJI!U-VWI!Q(_eZRlFROwbwL#{QysOPD>k54VK3t!I<{d>`
z-aer{=XMn+vNLULYQhfp8%EirvsH!e06B~~-qgBuZf;SRlJ4u+RphJMfeDqgK|5VH@L6H_linb7GEC()1bTnr3vSQ6U7-x!HO
zHzYj7G=_rhOfu$~=0r@*)*j0}ToOTEpB)S^o&io#>-|wP(|)`b4Bi}R%o5HrU$Gf8
z7ZvR34q?=cto~J!I~cN(2%PMD8sv0Fq+N^c{W18FhT1)GG+WKqCKp?BUmW0u6tt0R
z)-I~5tC|A-$TH7cy$M>S@kbsfKBA|(Aon;AE3d`mBC(mOix0~(pE8VPZTvZl1jK}{
zN?oq{VFDaER1Phsr$>~M(a}fh7wEX;YD^yd+9twKD%Tm
zpvUdS3J+H3(zjxk#J;cYv_H#8q4#e%Hag+jF1wM1f1<4o7x=h5TIr?L8{QjY
z=#1?@@+CcK#NyD4e)V2@CD4cdbU<6Hr^M`RCc?d^T6Urx_q6w-XZj4@B`qw>5X6XvRN2|f(69Y}ZV6krH3vfjkgw;KYoAdXXM6Os;
z(V^U^$^=OabSyxD_;5{y79z%;NnSkGIc!o4g#Pwn)bp*?zNlST-RG0raq?$2%H
6vL6hYc2SGNpg(f+bE$Bf*~DC?(520H8o^qJ-=WTAy+;-`%V)6
z`(!5Pw2#x{mS34SHQnR-o#?4;`7tgiS@#ZvK?F%s>-QRN*7S8|v{W>HUY$P^c}QM%
z806l|;M9sVTXNaRwOq7UcHjBK%kvCEt85Tn0Zcld0qLnu<)&YzSezPMCXS36OoCOWz;je!9R{hIChVgP1Li#JnZ7Ohcx>MRP_KXzJ3&1qcT5oA~IsDE{g+qXSr-C
zACU~Ntna%Cc+AvI|6w|Qr8?eyivKBrmmITGpY=p|gC;>pWKUfKQs7!7Ij%FX%?Ii}
zL`XHPdkEHOBZuGwxsEa!6z7yS}2d`4Y=*RgZ6&*;j6{HZC2eL-US|^?h!D
zvZ;SG@QeV24^R;Mt8ga2hduA}8tR14Dor}|a?tXA#=h*cQTr~+%ox2yKq0eKv1^RB
z=zPM7RAO|)<@;nd$b-Q)f?9z+@}qU?7uvFX2g3QvYQn^o#7=MB6;alrr~)-adlEBD
zq)qDUV;4!#C0@sLg$%3F_9>j3Zc)X;(L`ec^knclIbuGy7>U2{8iio8Ww3|Q#R`WJ
zn=s{5AO*^zmwYH{Zqmtmbe;%jk4e
z9+7KQ+S!qyt(k-_zT52k)X!9a5NV5bwuPE1bRAua0w-P126^q==~9ULg!fkJP^I>u
z&*|~w^wo-On)Um^lwk2Ks)(mI^@&i@9I;nR9Ig((GetR}JF#3yC#y$W?QR~McCGfp
z1VmjLo$(vif@X7Mh9q|31p{n)HG0_5gm;eWY_B2W;?OM`avX_m@QeZwa@ly~HIrlv
zmlRK2{cSNe3r!^ui_S)51brAlFgWr$*`1aeX|@Uw7m=YT_0Y!wXZU%-meaDQZlY{?
zeJ%dy8|MxZ`ZEIg08~Uh$dsXMt0#IE|L4+9ZM&rp{mM_lCGzn8asC<&f}p9g)@K0M
zP_KXZ=idJP2!hn2_mYV3Sz)?Arsa94AX8I1ZpUiPP3=E#8Ll?tnTd9yKg6Ilte8-f
z^meZLM|}qTo^mQ#qO-@!Lio7Dv-yFB95-6BmnwjdREAx;b&BFsrQhIbp^3aOe>8xE
z|7AE~$yz|$%SOuNwq-DISdwUyOs283$RO)&4#u43g`=}_NS7TBmj%C|^QUoW;k8y&)bEa)|ZrRL+eN=1y
z`T=mgTa+XRwHtZn8ALj*xT2hOsiVdCvE0~UjUowM7?ew|Z(TMaj&aJ)88{Xi-3nsf
z4#)V$KgF@|Yxr0Vz^2TL_oGPGL~_=esBKZm@di?KOO@>87>9^wc3{`C0~Q1e
zwHWjB9?rtrU-u#bYposMKB5}vpV!%
zE92_$ZR6S>M{c5^QnwvSzlV@KfYU|?>G#KizP8GE>*MyCxtSp};}ueJJYr&Gm4g6b
z1GpahsVu^pA~6PO&|`n^ILUWZEa?PQrpv`p$Nik~;w7yiSG)7Y-to`R0QZ!l4SYD?
zkE6DAwUau(KMWXJTsxWy*?Vjtl(YFFC@!15(onZxAM!M#fNojq;BFJS=yem^a&4e2
zN$ySLJ6cyTTZ=OlB)o1jz9o)Ia;$w6-+ma9@h)CjDbgHh%2%q5K1_`t9`}}9TuI7A
z<8+mrV7~OMu`cM@9;9~vyonu;Uqj*TU#wg_Snys_Fmn`fCLwN4R=+s{_7)J&iG(kY
zRK_)QeALrwMG(%nd2y@Ua8X=m`(@IWqol5RqTIN?NnTkB&sqvL8ZcStNSbjK)yf<4|iQ43r#5pVXdO
zQn{t~Vy+1s+qd}jaJM$^*)B&2Hcsj4
z$VyAtE8Y5PujbFH|EC8yy`L0~h<%D_m?`Ts%T@B0PLj0$g0;*TkeC
z5G5rg9?=_`HxxAF6qFQy>B*N{fyh8C6cj89d|Z5r|84n8Pr|Pv@*u#yFmwM!Pl8@J
z)ECC2c|Ixz#AMab@ESNcI!(}us;W7Ei~CVk&7~9=6dT{!Jw8cC
z&mobMSGPuDX!Mp-T*Wv$ckJY)D6*F-!2f4G{^5fE5~VK}Y5tb`LJ0p)j(;xxB}tL-
zUTQ%={rrF9?y_#=l5G}kZJWNnx0)oOV{x7{j?C{x)0$OYZUS7pSrh0Fc_I%)=jfG!Z
zqcV?Psd`f%dh7UV?zqaukAj_d?k*`y_EsuY%}`MIGba|M`N;>?es6Tk6&gCUIw(0*
za!Hs^u?DOgB0flH&Yi*i5%k+-7gHv{k9Sm@>Y?GpX@xN=a?}mlftjeT5plC|G#4|5
zDIu+E5of0Buu5;leQr-+!|gBMnn|$j8h`!8rL)tcQkiXgHuk`^