From 2bdcfc4d36c128abad52e788f7fc92f1caea957b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Thu, 26 Nov 2026 11:58:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E4=B8=8A=20Claude=20Code=EF=BC=88?= =?UTF-8?q?=E6=9C=AC=E6=A9=9F=EF=BC=89=EF=BC=9ABot=20=E7=9A=84=E5=A4=A7?= =?UTF-8?q?=E8=85=A6=E5=8F=AF=E4=BB=A5=E7=94=A8=E9=80=99=E5=8F=B0=E9=9B=BB?= =?UTF-8?q?=E8=85=A6=E4=B8=8A=20claude=20=E6=8C=87=E4=BB=A4=E7=9A=84?= =?UTF-8?q?=E8=A8=82=E9=96=B1=EF=BC=8C=E5=B7=A5=E5=85=B7=E5=92=8C=E5=AF=A9?= =?UTF-8?q?=E6=89=B9=E4=BB=8D=E8=B5=B0=20AnyBot=20=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E7=9A=84=E9=97=9C=E5=8D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/claudecli.rs:每一步跑一次 claude(-p、stream-json、不給內建工具、不載入使用者的設定與 MCP、結構化回答);工具呼叫回到 AnyBot 執行,要問的照樣出卡片 - providers:新增 Claude Code(沒有金鑰、沒有服務網址;模型 opus、sonnet、haiku);沒裝時回覆說明怎麼裝 - ANYBOT_CLAUDE_CLI:只給驗證用;指到不存在的檔案就當作沒裝 - 功能地圖新增 claudecode 區;models、README、FEATURES 同步 - 手機:Claude Code 不顯示服務網址 已驗證: cargo test 全部 927 通過(含 claudecli::、featuremap::、tool_specs_are_locked、approval_decisions_are_characterized);verify-anybot scratch:沒裝時 Bot 回「找不到 Claude Code」、沒有 claude 程序、設定 › 模型的格子與選單只有預設模型和測試連線 未驗證: claude 已登入的真實路徑(要這台電腦和 Claude 額度,cargo test claudecli::real_cli -- --ignored 還沒跑);Windows;真的 claude 底下的審批卡片實際表現 Co-authored-by: Cursor --- .../skills/verify-anybot/scripts/scratch-env | 1 + FEATURES.md | 2 + docs/feature-map/README.md | 1 + docs/feature-map/claudecode.md | 37 ++ docs/feature-map/models.md | 8 +- mobile/index.html | 3 +- src/app.rs | 4 +- src/claudecli.rs | 504 ++++++++++++++++++ src/featuremap.rs | 1 + src/icons.rs | 5 +- src/main.rs | 3 + src/providers.rs | 33 +- 12 files changed, 590 insertions(+), 12 deletions(-) create mode 100644 docs/feature-map/claudecode.md create mode 100644 src/claudecli.rs diff --git a/.claude/skills/verify-anybot/scripts/scratch-env b/.claude/skills/verify-anybot/scripts/scratch-env index bc73684..90a89e0 100755 --- a/.claude/skills/verify-anybot/scripts/scratch-env +++ b/.claude/skills/verify-anybot/scripts/scratch-env @@ -68,6 +68,7 @@ exec env -i \ ANYBOT_HF_BASE="http://127.0.0.1:9" \ ANYBOT_VAULT_KEY_FILE="$S/data/vault.key" \ ANYBOT_VAULT_DIR="$S/data" \ + ANYBOT_CLAUDE_CLI="$S/no-claude-code-here" \ ANYBOT_BOX_NAME="anybot-verify-scratch" \ ANYBOT_BOX_VOLUME="anybot-verify-scratch" \ ${EXTRA[@]+"${EXTRA[@]}"} \ diff --git a/FEATURES.md b/FEATURES.md index 5a581e5..10ddc24 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -693,6 +693,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 | 「xAI Grok」 | https://api.x.ai/v1 | grok-4 | grok-4、grok-4-fast、grok-3-mini | 要 | XAI_API_KEY | 「在 console.x.ai 取得 API 金鑰」 | | 「OpenAI」 | https://api.openai.com/v1 | gpt-5 | gpt-5、gpt-5-mini、gpt-4.1 | 要 | OPENAI_API_KEY | 「在 platform.openai.com 取得 API 金鑰」 | | 「Claude」 | https://api.anthropic.com/v1 | claude-opus-5-5 | claude-opus-5-5、claude-sonnet-5-5、claude-haiku-5-5、claude-fable-5-1 | 要 | ANTHROPIC_API_KEY | 「在 console.anthropic.com 取得 API 金鑰」 | +| 「Claude Code」 | (無:用這台電腦的 claude 指令,見 `src/claudecli.rs`) | sonnet | opus、sonnet、haiku | 不用 | – | 「用這台電腦上已登入的 Claude Code(Claude 訂閱),不用 API 金鑰:先安裝 claude,再在終端機執行 claude 並輸入 /login」 | | 「Google Gemini」 | https://generativelanguage.googleapis.com/v1beta/openai | gemini-2.5-flash | gemini-2.5-flash、gemini-2.5-pro | 要 | GEMINI_API_KEY | 「在 aistudio.google.com 取得 API 金鑰」 | | 「OpenRouter」 | https://openrouter.ai/api/v1 | openrouter/auto | openrouter/auto | 要 | OPENROUTER_API_KEY | 「在 openrouter.ai 取得 API 金鑰」 | | 「Ollama」 | http://localhost:11434/v1 | llama3.2 | llama3.2、qwen2.5、gemma3 | 不用 | – | 「先安裝並開啟 Ollama,不需要金鑰」 | @@ -1638,6 +1639,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 模型在哪裡跑(本機/區網/雲端) - **換了模型,聊天裡留一行**(計畫 D1 的一部分):換過模型之後的第一個回答前面多一行 AnyBot 的小字「改用 xAI Grok · grok-4 回答(上一個回答是 OpenAI · gpt-5)」。在一輪開始時比對,所以從 + 選單、Bot 設定、手機、或 Bot 自己用 update_my_profile 換的都會寫;AnyBot 自己的提示行不算上一個回答;不送給模型;群組聊天每個成員本來就各用各的,不寫。 +- **Claude Code 供應商**(`src/claudecli.rs`,地圖見 `docs/feature-map/claudecode.md`):用這台電腦上的 `claude` 指令(Claude 訂閱登入),每一步跑一次 `claude -p`:`--tools ""` 關掉它自己的工具、`--strict-mcp-config` 不載入 MCP、`--setting-sources project`、`--no-session-persistence`,回答用 `--json-schema` 固定成 `{text, tool_calls}`,讀 `structured_output`。工具呼叫仍由 AnyBot 執行,照原本的規則和審批。移除 `ANTHROPIC_API_KEY`(否則變按量計費)。不串流(說完才顯示)。圖片用 stream-json 的圖片區塊直接給 Claude。找不到指令時說「找不到 Claude Code(claude 指令)」;用量上限說「已達用量上限(Claude Code)」(備用模型會接手)。標「雲端」,說明「經這台電腦上的 Claude Code 送到 Claude」。 - 每個模型服務依它的網址標在哪裡跑:「本機」(localhost、127.x、::1)、「區網」(10.x、172.16–31.x、192.168.x、169.254.x、100.64–127.x 的 tailnet、fc00::/7、fe80::、`.local`、`.lan`、`.home`、`.internal`、`.home.arpa`、`.ts.net`、沒有點的名字)、「雲端」(其他全部,ChatGPT 方案一律算雲端)。只看網址字串、不查 DNS(畫面每一格都會畫到);一個公開網域就算其實指回家裡,也說雲端——分不出來時寧可說「會送出去」。本機、區網是綠字,雲端是灰字。 - 一句話說清楚:「在這台電腦上跑:對話、檔案內容和截圖都不會離開這台」「在你網路裡的 192.168.1.20 上跑:…不會離開你自己的網路」「在 xAI Grok 的伺服器上跑:Bot 的對話、它讀到的檔案內容和截圖會送過去」(OpenRouter 寫「再轉給模型公司」;自訂寫網址的主機名,不寫帳密)。螢幕電腦(設定是大腦的、請求從大腦發出)和手機上,本機寫成「在大腦「名字」那台電腦上跑」。 - 標在:設定 › 模型 左欄每列右邊(滑過看整句)、右邊標題下一句;Bot 設定「AI 供應商與模型」下面;聊天頂端 Bot 名字後面(滑過看模型和整句);空聊天的「供應商 · 模型 · 雲端」;輸入框 + 的模型選單每家後面。手機:Bot 設定 › 模型 右邊、選模型時每家的標題、設定 › 模型 每家的說明(大腦送 `runs`、`runs_words`)。左欄放寬到 212 px 放得下「自訂(OpenAI 相容)」加標籤。 diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index ed7d80b..9483d52 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -77,6 +77,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 - [bots](bots.md):側邊欄、搜尋、Bot 選單、建立 Bot。 - [profile](profile.md):Bot 設定、個人檔案、能力、頭像。 - [models](models.md):供應商、模型、思考模式、ChatGPT 方案。 +- [claudecode](claudecode.md):Claude Code(本機):用這台電腦上的 Claude 訂閱當模型,工具和審批還是 AnyBot 的。 - [team](team.md):問同事、交辦、教技能、群組聊天、分區。 - [branch](branch.md):支線(/btw):同時做另一件事、支線卡、回報。 - [memory](memory.md):核心記憶、帶入的記憶、記住與忘記、關於你。 diff --git a/docs/feature-map/claudecode.md b/docs/feature-map/claudecode.md new file mode 100644 index 0000000..81ab49a --- /dev/null +++ b/docs/feature-map/claudecode.md @@ -0,0 +1,37 @@ +# Claude Code(本機) + +用這台電腦上已登入的 Claude Code(`claude` 指令,Claude 訂閱)當 Bot 的模型,不用 API 金鑰。Claude 只負責想和回答;工具(檔案、電腦、瀏覽器、連接器)還是 AnyBot 自己執行,每一次都照原本的規則允許、詢問或拒絕。 + +## 子功能 + +- `claudecode-run` 當大腦:在 設定 › 模型 或 Bot 設定選「Claude Code」,每一步就用這台電腦的 `claude` 指令跑。沒有金鑰、沒有服務網址;模型是 opus、sonnet、haiku(跟著 Claude Code 的最新版)。 +- `claudecode-missing` 沒裝或沒登入:找不到 `claude` 時,Bot 回「找不到 Claude Code(claude 指令)…」;還沒登入時說明要在終端機執行 `claude`,輸入 `/login`。格子寫「未設定」,裝好重新開啟 AnyBot 後寫「可以用」。 +- `claudecode-tools` 工具與審批不變:Claude 的內建工具全部關掉,它要用工具就在回答裡提出,AnyBot 照原來的規則處理,要問的照樣出卡片。 +- `claudecode-answer` 回答與圖片:整段說完才出現(不逐字),圖片和截圖直接給 Claude 看;訂閱額度用完時說「已達用量上限」,Bot 有備用模型就換。 + +## 使用者怎麼到 + +- 設定 › 模型 › 「Claude Code」格子:寫「可以用」或「未設定」;「測試連線並取得模型清單」會確認 `claude` 找得到。 +- 輸入框 + 的模型選單「Claude Code」子選單;Bot 設定「AI 供應商與模型」的供應商。 +- 手機:設定 › 模型 也列出 Claude Code,同樣的「可以用」或「未設定」。 + +## 怎麼操作(verify-anybot) + +- Bot:換成 Claude Code 用 `update_my_profile`(provider 填 `claude-code`,model 填 `opus`、`sonnet` 或 `haiku`)。這台電腦沒有 `claude` 時,會回「找不到 Claude Code」。 + +前提: + +- 基本前提和「手機已登入」(README)。scratch 用 `ANYBOT_CLAUDE_CLI` 指到不存在的檔案,所以「沒裝」在 scratch 裡驗,不會碰這台電腦上真的 `claude`;裝好的情境用假的 `claude` 指令(`cargo test claudecli::`)和真實測試(`--ignored`)。 + +- **沒裝時請 Bot 換成 Claude Code**(covers `claudecode-missing`、`claudecode-run`):指令:`$CTL api POST /api/bots/1/set '{"provider":"ClaudeCode","model":"sonnet"}' && $CTL api POST /api/bots/1/send '{"text":"你好"}' && $CTL wait-api /api/bots/1 '[.messages[]?.text] | any(test("找不到 Claude Code"))' 60 && $CTL procs --none claude && $CTL phone shot claudecode-missing`。看到:Bot 回「找不到 Claude Code(claude 指令)。請先安裝 Claude Code,再重新開啟 AnyBot。」;`procs --none claude` 沒有任何 claude 程序(沒有連出去)。 +- **設定 › 模型 的格子**(covers `claudecode-missing`):指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="models"]' && $CTL phone wait-text 'Claude Code' --in '#list' && $CTL phone shot models-claudecode && $CTL phone click '[data-prov="4"]' && $CTL phone wait-text '測試連線並取得模型清單' && $CTL phone shot models-claudecode-sheet`(`data-prov="4"` 是 Claude Code 在供應商清單的位置)。看到:「Claude Code」一列寫「未設定」;點進去的選單只有「新 Bot 預設模型…」和「測試連線並取得模型清單」,沒有金鑰、也沒有服務網址。 +- **裝好以後**(covers `claudecode-run`、`claudecode-tools`、`claudecode-answer`):走不到——要這台電腦上真的 `claude` 並且已登入,會用掉你的 Claude 額度。最接近的真路:`cargo test claudecli::`(假的 `claude` 指令:記下它收到的參數和輸入,讀回結構化回答,工具呼叫交給 AnyBot)。看到:測試通過。 +- 自動測試:`cargo test claudecli::`、`cargo test providers::`、`cargo test claudecli::real_cli -- --ignored`(真的 `claude` 已登入才跑,會用額度,要先問)。 + +## 陷阱 + +- 不用 `ANTHROPIC_API_KEY`:這個環境變數會讓 `claude` 改成按量計費,所以 AnyBot 啟動它時拿掉。要用 API 金鑰計費請選「Claude」。 +- Claude 的內建工具(檔案、終端、網路)全部關掉,也不載入使用者資料夾裡的 MCP 和設定;Bot 能做的事只有 AnyBot 的工具。 +- 每一步都重新啟動一次 `claude`,比 API 慢一點;回答不串流,要等整段說完。 +- 登入在 Claude Code 裡管:換帳號、登出都在終端機的 `claude` 做,AnyBot 不管。 +- (驗證)Windows 沒有實機測過。真的 `claude` 在 `/opt/homebrew/bin`(登入在鑰匙圈,不在 HOME),scratch 的登入 shell 找得到它;所以 scratch 一定要設 `ANYBOT_CLAUDE_CLI`(`scratch-env` 已設),拿掉的話 scratch 會送訊息到你的訂閱。 diff --git a/docs/feature-map/models.md b/docs/feature-map/models.md index ce8886b..2375f1a 100644 --- a/docs/feature-map/models.md +++ b/docs/feature-map/models.md @@ -4,7 +4,7 @@ ## 子功能 -- `models-providers` 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama、自訂(OpenAI 相容),每個 Bot 各選各的。 +- `models-providers` 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Claude Code(見 [claudecode](claudecode.md))、Google Gemini、OpenRouter、OpenCode Go、Ollama、自訂(OpenAI 相容),每個 Bot 各選各的。 - `models-where` 在哪裡跑:每家依服務網址標「本機」(localhost)、「區網」(私有位址、tailnet、.local、沒有點的名字)或「雲端」(其他;分不出來也算雲端),本機、區網是綠字。標在:設定 › 模型 每列右邊、標題下一句(在哪台跑、會不會送出去);Bot 設定「AI 供應商與模型」;聊天頂端名字後面;空聊天的模型那行;+ 的模型選單每家後面;手機上同樣這些地方。螢幕電腦和手機上,「本機」是大腦那台。只看網址、不查名字。 - `models-switch` 換模型:資料、記憶、聊天都不用動;換過之後的第一個回答前面,聊天裡留一行「改用 ○○ 回答(上一個回答是 ○○)」(不送給模型;群組聊天不寫)。正在跑的那一輪照舊。換過去的第一個請求先把舊步驟的結果收起(要用再讀);思考內容只送回寫它的模型,之前的歷史對不上就不用那段思考、照樣回答(不會整輪停在「Invalid signature in thinking block」);模型說過的可讀長度各記各的。 - `models-fallback` 備用模型(Bot 設定,最多 8 個,依序):Bot 自己的模型額度用完(402、「已達用量上限」)、太忙(429)、金鑰或登入不能用(401、403)、服務出錯(5xx)或連不上,換下一個還沒休息的,從同一步接著做,聊天裡一行「改用 ○○ 繼續(○○:原因,10 分鐘內先不用它)」。不能用的休息 10 分鐘,這段時間新的一輪直接用備用(「改用 ○○ 回答(○○ 剛剛不能用…)」)。對話太長、不支援工具、模型名稱錯不換;沒金鑰的跳過;換過去不用思考和快速模型。 @@ -30,12 +30,12 @@ - **換到沒金鑰的供應商**(covers `models-bot`、`models-providers`):請 Bot 只換供應商成 xAI,允許,再傳一句。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '換 [[call update_my_profile {"provider":"xai"}]]' && $CTL phone wait-text 'xAI Grok' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0].via == "xAI Grok · grok-4"' && $CTL phone send '你好' && $CTL phone wait-text '還沒有設定 xAI Grok 的 API 金鑰' --in '#msgs' && $CTL phone shot models-nokey`。看到:卡片「AI 供應商:自訂(OpenAI 相容) → xAI Grok」;模型自動換成 xAI 的建議模型 grok-4;下一則出錯「還沒有設定 xAI Grok 的 API 金鑰。請到「設定 → 模型」貼上金鑰。」(沒有連出去)。 - **從手機換回來**(covers `models-bot`、`models-switch`):標題 › 模型,選 fake-model。指令:`$CTL phone click '#island' && $CTL phone click '[data-d="model"]' && $CTL phone wait-text '其他模型' --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text fake-model && $CTL wait-api '/api/state?since=0' '.bots[0].via == "自訂(OpenAI 相容) · fake-model"' && $CTL phone click '[data-back]' && $CTL phone send '回來了嗎' && $CTL phone wait-text 'FAKE-MODEL 回答:回來了嗎' --in '#msgs'`。看到:選單只列可以用的(Ollama(本機)、自訂(OpenAI 相容))和「其他模型…」;換回後又能回話。 - **在哪裡跑**(covers `models-where`):手機開 Bot 設定看模型那列,再點開選模型。指令:`$CTL api GET '/api/state?since=0' --jq '.bots[0] | {runs, runs_words}' && $CTL phone click '.row[data-bot="1"]' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text 'Bot 設定' && $CTL phone wait-text '模型可讀長度' && $CTL phone text '[data-e="model"]' && $CTL phone click '[data-e="model"]' && $CTL phone wait-text '自訂(OpenAI 相容) · 本機' --in '#sheet-in' && $CTL phone shot models-where`;桌面要開視窗:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot models ANYBOT_SHOT_TAB=providers`。看到:runs「本機」、runs_words「在大腦「驗證用 AnyBot」那台電腦上跑:對話、檔案內容和截圖都不會離開那台」;模型那列右邊「本機」;選單每家的標題帶「· 本機」或「· 雲端」;桌面每列右邊有標籤、xAI Grok 標題下寫「雲端 在 xAI Grok 的伺服器上跑:…會送過去」。 -- **換了模型留一行**(covers `models-switch`):問一句、換模型、再問一句。指令:`$CTL api POST /api/bots/1/send '{"text":"第一個問題"}' && $CTL wait-api /api/bots/1 '[.messages[]?.text] | any(test("FAKE-MODEL 回答:第一個問題"))' 60 && $CTL api POST /api/bots/1/set '{"provider":"Custom","model":"fake-model-2"}' && $CTL api POST /api/bots/1/send '{"text":"換了之後"}' && $CTL phone wait-text '改用 自訂' --in '#msgs' && $CTL phone shot model-changed`。看到:問題和新回答中間一行「改用 自訂(OpenAI 相容) · fake-model-2 回答(上一個回答是 自訂(OpenAI 相容) · fake-model)」(API 裡 note: true);`model-requests.jsonl` 裡沒有「改用」。 -- **思考模式、執行步驟用的模型**(covers `models-thinking`):指令:`$CTL phone send '想深一點 [[call update_my_profile {"thinking":"high","step_model":"off"}]]' && $CTL phone wait-text '思考模式' --in '#ask' && $CTL phone wait-text '執行步驟用的模型:自動 → 不分開' --in '#ask' && $CTL phone shot models-thinking && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0] | .thinking == "high" and .step_model == "off"' && $CTL phone send '再說一次' && $CTL phone wait-text 'FAKE-MODEL 回答:再說一次' --in '#msgs'`。看到:卡片列出「思考模式:自動(模型自己決定) → 深入(想得久,較慢)」和「執行步驟用的模型:自動 → 不分開」(設定畫面上的說法);允許後大腦記著 high、off,照常回話。 +- **換了模型留一行**(covers `models-switch`):問一句、換模型、再問一句。指令:`$CTL api POST /api/bots/1/send '{"text":"第一個問題"}' && $CTL wait-api /api/bots/1 '[.messages[]?.text] | any(test("FAKE-MODEL 回答:第一個問題"))' 60 && $CTL api POST /api/bots/1/set '{"provider":"Custom","model":"fake-model-2"}' && $CTL api POST /api/bots/1/send '{"text":"換了之後"}' && $CTL phone wait-text '改用 自訂' --in '#msgs' && $CTL phone shot model-changed`。看到:問題和新回答中間一行「改用 自訂(OpenAI 相容) · fake-model-2 回答(上一個回答是 自訂(OpenAI 相容) · fake-model)」;`model-requests.jsonl` 裡沒有「改用」。 +- **思考模式、執行步驟用的模型**(covers `models-thinking`):指令:`$CTL phone send '想深一點 [[call update_my_profile {"thinking":"high","step_model":"off"}]]' && $CTL phone wait-text '思考模式' --in '#ask' && $CTL phone wait-text '執行步驟用的模型:自動 → 不分開' --in '#ask' && $CTL phone shot models-thinking && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0] | .thinking == "high" and .step_model == "off"' && $CTL phone send '再說一次' && $CTL phone wait-text 'FAKE-MODEL 回答:再說一次' --in '#msgs'`。看到:卡片列出「思考模式:自動(模型自己決定) → 深入(想得久,較慢)」和「執行步驟用的模型:自動 → 不分開」;允許後大腦記著 high、off,照常回話。 - **ChatGPT 登出要先問**(covers `models-chatgpt`):請 Bot 登出,按拒絕;再看狀態。指令:`$CTL phone send '登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '登出 ChatGPT' --in '#ask' && $CTL phone wait-text '驗證小幫手 想要登出 ChatGPT 方案' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '狀態 [[call chatgpt_login {"action":"status"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "chatgpt_login" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "chatgpt_login") | {status, result}]'`。看到:登出先跳卡片「驗證小幫手 想要登出 ChatGPT 方案」(「登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答…」),拒絕後 denied;status 不用問,「還沒有用 ChatGPT 登入。」 - **用 ChatGPT 登入**(covers `models-chatgpt`):指令:走不到——登入會向 OpenAI 註冊、要真的 ChatGPT 帳號和方案(貼回網址、螢幕電腦的「完成登入」、額度用完都一樣)。看到:最接近的真路是上一步的 status 和 `cargo test chatgpt::`(註冊一次後重用、貼回網址、沒勾同意、額度用完)。 - **桌面**(covers `models-bot`、`models-providers`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot models ANYBOT_SHOT_TAB=providers`。看到:設定 › 模型 每家的金鑰欄和「使用 ChatGPT 繼續」;輸入框 + 的模型子選單(「(未設定金鑰)」)、Bot 設定的紅字「前往設定」靠自動測試。 -- **備用模型接手**(covers `models-fallback`):Bot 1 改用連不上的 Ollama、備用假模型(只改沒秘密的欄位),問兩輪。指令:`$CTL stop && F="$(sed -n 's/^SCR=//p' target/verify-anybot/current/run.env)/data/state.json" && jq '.bots[0].provider = "Ollama" | .bots[0].model = "llama3.2" | .bots[0].fallbacks = [{"provider":"Custom","model":"fake-model"}] | .providers.ollama = {"base_url":"http://127.0.0.1:9"}' "$F" > "$F.new" && mv "$F.new" "$F" && $CTL serve && for n in 一 二; do $CTL api POST /api/bots/1/send "{\"text\":\"第${n}輪\"}" && $CTL wait-api /api/bots/1 "[.messages[]?.text] | any(test(\"回答:第${n}輪\"))" 90 || break; done && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.note) | .text]' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone shot models-fallback`;桌面:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot fb ANYBOT_SHOT_VIEW=editor ANYBOT_SHOT_SIZE=1000x820 'ANYBOT_SHOT_SCROLL=500,400,-12@10' 'ANYBOT_SHOT_CLICK=335,375@125' ANYBOT_SHOT_FRAMES=140`。看到:第一輪前一行「改用 自訂(OpenAI 相容) · fake-model 繼續(Ollama · llama3.2:連不上…)」,回答標 fake-model;第二輪「改用 … 回答(… 剛剛不能用…)」;手機星星;「+」多一列。 +- **備用模型接手**(covers `models-fallback`):Bot 1 改用連不上的 Ollama、備用假模型(只改沒秘密的欄位),問兩輪。指令:`$CTL stop && F="$(sed -n 's/^SCR=//p' target/verify-anybot/current/run.env)/data/state.json" && jq '.bots[0].provider = "Ollama" | .bots[0].model = "llama3.2" | .bots[0].fallbacks = [{"provider":"Custom","model":"fake-model"}] | .providers.ollama = {"base_url":"http://127.0.0.1:9"}' "$F" > "$F.new" && mv "$F.new" "$F" && $CTL serve && for n in 一 二; do $CTL api POST /api/bots/1/send "{\"text\":\"第${n}輪\"}" && $CTL wait-api /api/bots/1 "[.messages[]?.text] | any(test(\"回答:第${n}輪\"))" 90 || break; done && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.note) | .text]' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone shot models-fallback`;桌面:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot fb ANYBOT_SHOT_VIEW=editor ANYBOT_SHOT_SIZE=1000x820 'ANYBOT_SHOT_SCROLL=500,400,-12@10' 'ANYBOT_SHOT_CLICK=335,375@125' ANYBOT_SHOT_FRAMES=140`。看到:第一輪前一行「改用 自訂(OpenAI 相容) · fake-model 繼續(Ollama · llama3.2:連不上…)」;第二輪「改用 … 回答(… 剛剛不能用…)」;手機星星;「+」多一列。 - 自動測試:`cargo test a_backup_model_carries_on_when_the_bots_own_cannot`、`cargo test only_failures_another_model_could_get_past_switch_models`、`cargo test chatgpt::`、`cargo test providers::`(含 `calls_of_set_aside_steps_go_shortened`、`each_model_says_where_it_runs`)、`a_changed_model_leaves_a_line_in_the_chat`、`cargo test a_switched_model_starts_from_a_lean_request`、`cargo test profile::`、`cargo test remote::tests::only_the_owner_signs_the_brain_in_to_chatgpt`。 ## 陷阱 diff --git a/mobile/index.html b/mobile/index.html index 2bbc657..3d4ab6b 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -4143,7 +4143,8 @@ function wireSettings(kind, st) { }}, ...(p.ready ? [{icon: "trash", label: "登出 ChatGPT", danger: true, on: async () => { if (await confirmSheet("登出 ChatGPT?", "用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。", "登出") && await act("chatgpt", {action: "logout"})) again(); }}] : [])] : []), {icon: "sparkles", label: "新 Bot 預設模型…", x: p.default_model || "", on: async () => { const m = await ask("新 Bot 預設用的模型", p.default_model || ""); if (m != null && await act("provider", {provider: p.key, default_model: m}, "已更新")) again(); }}, // 服務網址, 測試連線並取得模型清單, and a local model's 看圖小幫手 — as on the computer. - ...(p.account ? [] : [{icon: "globe", label: "服務網址…", x: p.base_url ? "自訂" : "預設", on: async () => { const u = await ask("服務網址(空白=預設)", p.base_url || "", p.default_url || ""); if (u != null && await act("provider", {provider: p.key, base_url: u}, "已更新網址")) again(); }}]), + // Claude Code runs from this computer's `claude` command: there is no address to set. + ...(p.account || p.key === "ClaudeCode" ? [] : [{icon: "globe", label: "服務網址…", x: p.base_url ? "自訂" : "預設", on: async () => { const u = await ask("服務網址(空白=預設)", p.base_url || "", p.default_url || ""); if (u != null && await act("provider", {provider: p.key, base_url: u}, "已更新網址")) again(); }}]), {icon: "refresh", label: p.testing ? "正在測試連線…" : "測試連線並取得模型清單", x: p.status ? p.status.slice(0, 18) : p.known ? `記住 ${p.known} 個` : "", on: async () => { if (await act("provider", {provider: p.key, fetch: true})) { setTimeout(again, 2500); setTimeout(again, 8000); } }}, ...(p.local ? [{icon: "eye", label: p.cloud_eyes ? "看不到圖時請雲端模型看:開" : "看不到圖時請雲端模型看:關", x: "", on: async () => { if (await act("provider", {provider: p.key, cloud_eyes: !p.cloud_eyes}, p.cloud_eyes ? "圖片不會離開了" : "看不到的圖會給雲端模型看")) again(); }}] : []), ...(p.ready && p.needs_key ? [{icon: "trash", label: "清除金鑰", danger: true, on: async () => { if (await confirmSheet(`清除 ${p.label} 的金鑰?`, "用這個服務的 Bot 會沒辦法回答,直到再設定一把。", "清除") && await act("provider", {provider: p.key, key: ""}, "已清除")) again(); }}] : []), diff --git a/src/app.rs b/src/app.rs index d4d7e6c..a09a504 100644 --- a/src/app.rs +++ b/src/app.rs @@ -6936,7 +6936,8 @@ impl App { field_label(ui, "API 金鑰", p); changed |= ui.add(egui::TextEdit::singleline(&mut ps.api_key).password(true).hint_text(k.env_var().map(|v| format!("貼上金鑰,或設定環境變數 {v}")).unwrap_or_else(|| "(選填)".into())).desired_width(w)).changed(); } - if k != ProviderKind::ChatGpt { + // ChatGPT 方案 and Claude Code have no address to type: the account or the command is the service. + if k != ProviderKind::ChatGpt && k != ProviderKind::ClaudeCode { field_label(ui, "服務網址", p); changed |= ui.add(egui::TextEdit::singleline(&mut ps.base_url).hint_text(k.default_base_url()).desired_width(w)).changed(); } @@ -8490,6 +8491,7 @@ fn short_provider(k: ProviderKind) -> &'static str { ProviderKind::OpenAi => "OpenAI", ProviderKind::ChatGpt => "ChatGPT 方案", ProviderKind::Anthropic => "Claude", + ProviderKind::ClaudeCode => "Claude Code", ProviderKind::Gemini => "Gemini", ProviderKind::OpenRouter => "OpenRouter", ProviderKind::OpenCodeGo => "OpenCode Go", diff --git a/src/claudecli.rs b/src/claudecli.rs new file mode 100644 index 0000000..7161058 --- /dev/null +++ b/src/claudecli.rs @@ -0,0 +1,504 @@ +// Claude Code as a model: the person's own `claude` command, signed in with their Claude +// subscription (no API key), run once per model step. AnyBot keeps its tool loop. The CLI gets +// no tools of its own (`--tools ""`), so the model asks for AnyBot's tools in its answer, and +// AnyBot runs them through its usual gate (rules, approvals, the 安全規則) like any other +// provider's tool calls. Nothing about approvals changes here. +// +// The answer is forced into `{text, tool_calls}` (`--json-schema`) and read from the CLI's +// `structured_output`. The CLI doesn't stream here: the words arrive when the step is done. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +use crate::model::{Message, Role, ToolCall, ToolStatus}; +use crate::providers::{self, ChatRequest, Failure, StepOutput, StreamEvent, Usage}; + +/// A step that runs longer than this is stopped. +const STEP_TIMEOUT: Duration = Duration::from_secs(15 * 60); +/// How often a waiting step tells the agent it is alive (the stall watchdog waits 35 s). +const ALIVE_EVERY: Duration = Duration::from_secs(1); +/// The model when a bot names none: the CLI's own alias for the newest Sonnet. +const DEFAULT_MODEL: &str = "sonnet"; +/// The aliases the CLI takes; each follows the newest model of its family. +pub const MODELS: [&str; 3] = ["opus", "sonnet", "haiku"]; + +const CLI_NAME: &str = if cfg!(windows) { "claude.exe" } else { "claude" }; + +/// The answer shape: the words, and the tools the model asks AnyBot to run. `arguments` is JSON +/// text, the way AnyBot keeps a call's arguments. +const ANSWER_SCHEMA: &str = r#"{"type":"object","properties":{"text":{"type":"string"},"tool_calls":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"arguments":{"type":"string"}},"required":["name","arguments"]}}},"required":["text","tool_calls"]}"#; + +static CALL_SEQ: AtomicU64 = AtomicU64::new(0); + +#[cfg(test)] +static CLI_FOR_TESTS: Mutex> = Mutex::new(None); + +#[cfg(test)] +fn test_cli() -> Option { + CLI_FOR_TESTS.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +#[cfg(not(test))] +fn test_cli() -> Option { + None +} + +/// The `claude` command the app can run: searched in the same places a shell would find it (a +/// Mac app started from Finder has no shell PATH; `cloudbox::tool_path` adds the usual places). +pub fn cli_path() -> Option { + if let Some(p) = test_cli() { + return Some(p); + } + // For the verify harness only: a path given here is the command, and a path that is not a file + // means "not installed", whatever this machine has (scratch's login shell finds the real one). + if let Some(v) = std::env::var_os("ANYBOT_CLAUDE_CLI") { + let p = PathBuf::from(v); + return p.is_file().then_some(p); + } + std::env::split_paths(&crate::cloudbox::tool_path()).map(|d| d.join(CLI_NAME)).find(|p| p.is_file()) +} + +/// Whether the command is installed. (Being signed in is only known when a step runs.) +pub fn installed() -> bool { + cli_path().is_some() +} + +/// Looks for the command once on a background thread at start, so the first frame of the settings +/// page doesn't wait on the login shell. +pub fn warm() { + std::thread::spawn(|| { + let _ = cli_path(); + }); +} + +/// The system prompt for the step: the bot's own words, the earlier summaries, then the tools the +/// model may ask for and the answer's shape. The tools' own definitions go in as they are. +fn system_prompt(req: &ChatRequest) -> String { + let mut s = providers::system_with_summaries(req); + if !req.tools.is_empty() { + s.push_str("\n\n# 工具\n\n你不能自己執行工具。要用的時候,在回覆的 tool_calls 列出工具名稱和參數(arguments 是 JSON 文字);AnyBot 會執行,再把結果放進下一輪的對話給你。"); + for t in &req.tools { + s.push_str(&format!( + "\n\n## {}\n{}\n參數(JSON Schema):{}", + t["name"].as_str().unwrap_or(""), + t["description"].as_str().unwrap_or(""), + t["parameters"] + )); + } + } + s.push_str("\n\n# 回覆格式\n\n每次都只回一個 JSON 物件:text 是要給使用者看的話(沒有就空字串),tool_calls 是要執行的工具(沒有就空陣列)。"); + s +} + +/// The conversation as one user message: each earlier message labelled, pictures after the text +/// (the person's own, and the kept screenshots of tool results). The last line asks for the next +/// reply, so the answer is a reply, not a continuation of the transcript. +fn input_line(req: &ChatRequest) -> String { + let mut text = String::new(); + let mut images: Vec = vec![]; + let kept = providers::kept_images(&req.history); + let picture = |images: &mut Vec, b: &String| { + images.push(b.clone()); + format!("(附圖 {})", images.len()) + }; + for (i, m) in req.history.iter().enumerate().filter(|(_, m)| !m.summary) { + match m.role { + Role::User => { + let mut line = if m.context.is_empty() { m.text.clone() } else { format!("{}\n\n{}", m.text, m.context) }; + for b in &m.images { + line.push_str(&picture(&mut images, b)); + } + text.push_str(&format!("【使用者】\n{line}\n\n")); + } + Role::Assistant => { + if m.error && m.tool_calls.is_empty() { + continue; + } + if !m.text.is_empty() { + text.push_str(&format!("【你】\n{}\n\n", m.text)); + } + for c in &m.tool_calls { + text.push_str(&format!("【你呼叫了工具 {}(id {})】參數:{}\n\n", c.name, c.id, c.args.trim())); + } + } + Role::Tool => { + let mut line = m.text.clone(); + if !m.images.is_empty() && kept.contains(&i) { + for b in &m.images { + line.push_str(&picture(&mut images, b)); + } + } + text.push_str(&format!("【工具結果(id {})】\n{line}\n\n", m.tool_call_id)); + } + } + } + text.push_str("請依上面的對話,回覆你的下一則(JSON 格式)。"); + let mut content = vec![json!({"type": "text", "text": text})]; + content.extend(images.iter().map(|b| json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": b}}))); + json!({"type": "user", "message": {"role": "user", "content": content}}).to_string() +} + +/// The command-line flags for one step. The CLI runs with no tools, no MCP servers, no settings +/// from the person's user folder and no session saved: the only thing it does is answer. +fn args(req: &ChatRequest, system_file: &Path) -> Vec { + let model = if req.model.trim().is_empty() { DEFAULT_MODEL } else { req.model.trim() }; + let mut a: Vec = [ + "-p", + "--input-format", + "stream-json", + // Stream-json in and out go together; the answer is the last `result` line. + "--output-format", + "stream-json", + "--verbose", + "--tools", + "", + "--strict-mcp-config", + "--setting-sources", + "project", + "--no-session-persistence", + ] + .map(String::from) + .to_vec(); + a.extend(["--system-prompt-file".into(), system_file.display().to_string()]); + a.extend(["--json-schema".into(), ANSWER_SCHEMA.into()]); + a.extend(["--model".into(), model.into()]); + if matches!(req.effort.as_str(), "low" | "medium" | "high") { + a.extend(["--effort".into(), req.effort.clone()]); + } + a +} + +/// What a failed step says, in words the person can act on. "已達用量上限" at the start is what +/// AnyBot's 備用模型 switch looks for. +fn failure_of(detail: &str) -> Failure { + let d = detail.trim(); + let low = d.to_lowercase(); + if low.contains("not logged in") || low.contains("/login") || (low.contains("please run") && low.contains("login")) { + return Failure::fatal("Claude Code 還沒有登入。請在這台電腦的終端機執行 claude,輸入 /login,用你的 Claude 帳號登入。".into()); + } + if low.contains("usage limit") || low.contains("rate limit") || low.contains("limit reached") { + return Failure::fatal(format!("已達用量上限(Claude Code):{d}")); + } + Failure::fatal(format!("Claude Code 出錯:{}", if d.is_empty() { "沒有說明" } else { d })) +} + +/// The tool calls and words in the CLI's answer. `structured_output` is the schema's object; a +/// result that is only text (no structured answer) is taken as the words. +fn parse_answer(v: &Value) -> Result<(String, Vec), Failure> { + let structured = v.get("structured_output").filter(|s| s.is_object()).cloned().or_else(|| v["result"].as_str().and_then(|r| serde_json::from_str::(r).ok()).filter(Value::is_object)); + let Some(s) = structured else { + return Ok((v["result"].as_str().unwrap_or("").to_string(), vec![])); + }; + let text = s["text"].as_str().unwrap_or("").to_string(); + let mut calls = vec![]; + for c in s["tool_calls"].as_array().map(Vec::as_slice).unwrap_or(&[]) { + let name = c["name"].as_str().unwrap_or("").trim().to_string(); + if name.is_empty() { + continue; + } + let args = match &c["arguments"] { + Value::String(a) if !a.trim().is_empty() => a.trim().to_string(), + Value::Object(_) => c["arguments"].to_string(), + _ => "{}".into(), + }; + let n = CALL_SEQ.fetch_add(1, Ordering::Relaxed); + calls.push(ToolCall { id: format!("cc{n}"), name, args, status: ToolStatus::Waiting }); + } + Ok((text, calls)) +} + +/// The CLI's final answer. With stream-json output it prints one JSON line per event and the +/// `result` line comes last; a single JSON object is taken as it is. +fn answer_of(stdout: &str) -> Option { + if let Ok(v) = serde_json::from_str::(stdout.trim()) { + return Some(v); + } + stdout.lines().rev().filter_map(|l| serde_json::from_str::(l.trim()).ok()).find(|v| v["type"].as_str() == Some("result")) +} + +fn usage_of(v: &Value) -> Usage { + let g = |k: &str| v["usage"][k].as_u64().unwrap_or(0); + // The CLI's own dollar figure is a list-price estimate, not a bill (a subscription pays none): left at zero. + Usage { input: g("input_tokens"), output: g("output_tokens"), cache_read: g("cache_read_input_tokens"), cache_write: g("cache_creation_input_tokens"), cost_micros: 0 } +} + +/// One model step through the local `claude` command. Cancelling kills it and gives back nothing +/// (as the other providers do). +pub fn run(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { + let Some(cli) = cli_path() else { + return Err(Failure::fatal("找不到 Claude Code(claude 指令)。請先安裝 Claude Code,再重新開啟 AnyBot。".into())); + }; + let work = std::env::temp_dir().join("anybot-claude-code"); + std::fs::create_dir_all(&work).map_err(|e| Failure::fatal(format!("Claude Code 的工作資料夾開不了:{e}")))?; + // The system prompt carries the bot's words and memory: a file only the person can read, + // not the command line (which `ps` shows). + let seq = CALL_SEQ.fetch_add(1, Ordering::Relaxed); + let system_file = work.join(format!("system-{}-{seq}.txt", std::process::id())); + std::fs::write(&system_file, system_prompt(req)).map_err(|e| Failure::fatal(format!("Claude Code 的設定檔寫不了:{e}")))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&system_file, std::fs::Permissions::from_mode(0o600)); + } + let outcome = run_child(&cli, &work, &args(req, &system_file), input_line(req), cancel, send); + let _ = std::fs::remove_file(&system_file); + let (ok, stdout, stderr) = outcome?; + let Some(stdout) = stdout else { + // Cancelled: the answer is not wanted. + return Ok(StepOutput::default()); + }; + let v: Value = answer_of(&stdout).ok_or_else(|| { + let seen = if stdout.trim().is_empty() { stderr.trim() } else { stdout.trim() }; + Failure::fatal(format!("Claude Code 回了看不懂的內容:{}", seen.chars().take(300).collect::())) + })?; + let is_error = v["is_error"].as_bool().unwrap_or(false) || v.get("subtype").is_some_and(|s| s.as_str() != Some("success")); + if is_error || !ok { + let detail = v["result"].as_str().map(str::to_string).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| stderr.trim().to_string()); + return Err(failure_of(&detail)); + } + let (text, tool_calls) = parse_answer(&v)?; + if !text.is_empty() { + send(StreamEvent::Text(text.clone())); + } + for call in &tool_calls { + send(StreamEvent::ToolCall(call.clone())); + } + Ok(StepOutput { text, tool_calls, usage: usage_of(&v), ..StepOutput::default() }) +} + +/// Runs the command with the prompt on stdin. Returns (exited ok, stdout, stderr); stdout is None +/// when the step was cancelled. Alive is sent while it runs. +fn run_child(cli: &Path, work: &Path, args: &[String], input: String, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<(bool, Option, String), Failure> { + let mut cmd = Command::new(cli); + cmd.args(args) + .current_dir(work) + .env("PATH", crate::cloudbox::tool_path()) + // An API key in the environment would switch the login to pay-as-you-go; this path is the subscription. + .env_remove("ANTHROPIC_API_KEY") + .env_remove("ANTHROPIC_AUTH_TOKEN") + // Started from inside a Claude Code session (a developer's terminal), the CLI would refuse to nest. + .env_remove("CLAUDECODE") + .env_remove("CLAUDE_CODE_ENTRYPOINT") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = cmd.spawn().map_err(|e| Failure::fatal(format!("打不開 Claude Code({e})。確認它還在,然後重新開啟 AnyBot。")))?; + if let Some(mut stdin) = child.stdin.take() { + // A thread: a prompt larger than the pipe must not hold this one up. + std::thread::spawn(move || { + let _ = writeln!(stdin, "{input}"); + }); + } + // The readers own their pipes, so a long answer never fills one and holds the CLI up. + let out_pipe = child.stdout.take(); + let err_pipe = child.stderr.take(); + let out_reader = std::thread::spawn(move || read_to_string(out_pipe)); + let err_reader = std::thread::spawn(move || read_to_string(err_pipe)); + let started = Instant::now(); + let mut last_alive = started; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => {} + Err(e) => return Err(Failure::fatal(format!("Claude Code 的程序出錯:{e}"))), + } + if cancel.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + return Ok((false, None, String::new())); + } + if started.elapsed() > STEP_TIMEOUT { + let _ = child.kill(); + let _ = child.wait(); + return Err(Failure::fatal("Claude Code 超過 15 分鐘還沒有回答,已停止。".into())); + } + if last_alive.elapsed() >= ALIVE_EVERY { + send(StreamEvent::Alive); + last_alive = Instant::now(); + } + std::thread::sleep(Duration::from_millis(100)); + }; + let stdout = out_reader.join().unwrap_or_default(); + let stderr = err_reader.join().unwrap_or_default(); + Ok((status.success(), Some(stdout), stderr)) +} + +fn read_to_string(pipe: Option) -> String { + let mut buf = String::new(); + if let Some(mut p) = pipe { + let _ = std::io::Read::read_to_string(&mut p, &mut buf); + } + buf +} + +#[cfg(test)] +mod tests { + use super::*; + + fn req(history: Vec, tools: Vec) -> ChatRequest { + ChatRequest { + kind: providers::ProviderKind::ClaudeCode, + base_url: String::new(), + api_key: String::new(), + model: "sonnet".into(), + system: "你是助理。".into(), + history, + tools, + session: String::new(), + effort: String::new(), + } + } + + fn tool(name: &str) -> Value { + json!({"name": name, "description": "讀檔案", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}) + } + + #[test] + fn system_prompt_lists_tools_and_answer_shape() { + let s = system_prompt(&req(vec![], vec![tool("read_file")])); + assert!(s.starts_with("你是助理。")); + assert!(s.contains("## read_file"), "{s}"); + assert!(s.contains("參數(JSON Schema)")); + assert!(s.contains("回覆格式")); + // No tools: no tool section. + assert!(!system_prompt(&req(vec![], vec![])).contains("# 工具")); + } + + #[test] + fn input_line_labels_turns_and_sends_pictures_as_blocks() { + let mut pic = Message::user("這是什麼"); + pic.images = vec!["AAAA".into()]; + let mut tool_msg = Message { role: Role::Tool, text: "檔案內容".into(), tool_call_id: "t1".into(), ..Message::default() }; + tool_msg.images = vec!["BBBB".into()]; + let call = ToolCall { id: "t1".into(), name: "read_file".into(), args: r#"{"path":"a"}"#.into(), status: ToolStatus::Done }; + let asked = Message { role: Role::Assistant, text: "我來看".into(), tool_calls: vec![call], ..Message::default() }; + let line: Value = serde_json::from_str(&input_line(&req(vec![pic, asked, tool_msg], vec![]))).unwrap(); + let content = &line["message"]["content"]; + let text = content[0]["text"].as_str().unwrap(); + assert!(text.contains("【使用者】\n這是什麼(附圖 1)"), "{text}"); + assert!(text.contains("【你呼叫了工具 read_file(id t1)】")); + assert!(text.contains("【工具結果(id t1)】\n檔案內容(附圖 2)"), "{text}"); + assert_eq!(content[1]["source"]["data"], "AAAA"); + assert_eq!(content[2]["source"]["data"], "BBBB"); + assert!(text.ends_with("(JSON 格式)。")); + } + + #[test] + fn the_answer_is_the_result_line_of_the_stream() { + let stream = "{\"type\":\"system\",\"subtype\":\"init\"}\n{\"type\":\"assistant\",\"message\":{}}\n{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\":\"好\"}\n"; + let v = answer_of(stream).expect("the result line"); + assert_eq!(v["result"].as_str(), Some("好")); + let single = answer_of("{\"type\":\"result\",\"result\":\"單行\"}").expect("one object"); + assert_eq!(single["result"].as_str(), Some("單行")); + assert!(answer_of("不是 JSON").is_none()); + } + + #[test] + fn args_run_the_cli_with_no_tools_and_the_schema() { + let a = args(&req(vec![], vec![]), Path::new("/tmp/s.txt")); + let at = |flag: &str| a.iter().position(|x| x == flag).map(|i| a[i + 1].clone()); + assert_eq!(at("--tools").as_deref(), Some("")); + assert_eq!(at("--model").as_deref(), Some("sonnet")); + assert_eq!(at("--system-prompt-file").as_deref(), Some("/tmp/s.txt")); + assert!(at("--json-schema").unwrap().contains("tool_calls")); + assert!(a.contains(&"--strict-mcp-config".to_string())); + assert!(!a.contains(&"--effort".to_string()), "no effort unless the bot sets one"); + let mut r = req(vec![], vec![]); + r.effort = "high".into(); + r.model = String::new(); + let b = args(&r, Path::new("/tmp/s.txt")); + assert!(b.windows(2).any(|w| w == ["--effort", "high"])); + assert!(b.windows(2).any(|w| w == ["--model", DEFAULT_MODEL])); + } + + #[test] + fn answer_becomes_words_and_calls() { + let v = json!({"is_error": false, "subtype": "success", "result": "", + "structured_output": {"text": "好", "tool_calls": [{"name": "read_file", "arguments": "{\"path\":\"a\"}"}, {"name": "", "arguments": "{}"}, {"name": "list_dir", "arguments": {"path": "."}}]}, + "usage": {"input_tokens": 3, "output_tokens": 5, "cache_read_input_tokens": 100}}); + let (text, calls) = parse_answer(&v).unwrap_or_else(|e| panic!("{}", e.msg)); + assert_eq!(text, "好"); + assert_eq!(calls.len(), 2, "an unnamed call is dropped"); + assert_eq!(calls[0].name, "read_file"); + assert_eq!(calls[0].args, r#"{"path":"a"}"#); + assert_eq!(calls[1].args, r#"{"path":"."}"#, "an object argument is kept as JSON text"); + assert_ne!(calls[0].id, calls[1].id); + let u = usage_of(&v); + assert_eq!((u.input, u.output, u.cache_read), (3, 5, 100)); + } + + #[test] + fn plain_result_is_the_words_without_calls() { + let v = json!({"is_error": false, "subtype": "success", "result": "只是文字"}); + let (text, calls) = parse_answer(&v).unwrap_or_else(|e| panic!("{}", e.msg)); + assert_eq!((text.as_str(), calls.len()), ("只是文字", 0)); + } + + #[test] + fn login_and_limit_failures_say_what_to_do() { + assert!(failure_of("Not logged in · Please run /login").msg.contains("還沒有登入")); + assert!(failure_of("Claude usage limit reached").msg.starts_with("已達用量上限")); + assert!(failure_of("something else").msg.starts_with("Claude Code 出錯:")); + } + + /// A stand-in `claude`: records its flags and its input, and answers with a structured reply. + #[cfg(unix)] + #[test] + fn a_step_runs_the_command_and_reads_its_answer() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("anybot-claudecli-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("fake-claude"); + let seen = dir.join("seen"); + std::fs::write( + &script, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" > '{0}.args'\ncat > '{0}.input'\n\ + echo '{{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\":\"\",\"structured_output\":{{\"text\":\"你好\",\"tool_calls\":[{{\"name\":\"read_file\",\"arguments\":\"{{\\\"path\\\":\\\"a.txt\\\"}}\"}}]}},\"usage\":{{\"input_tokens\":5,\"output_tokens\":7}}}}'\n", + seen.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + *CLI_FOR_TESTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(script); + let cancel = AtomicBool::new(false); + let events = Mutex::new(vec![]); + let out = run(&req(vec![Message::user("嗨")], vec![tool("read_file")]), &cancel, &|e| { + if let StreamEvent::ToolCall(c) = e { + events.lock().unwrap().push(c.name); + } + }); + *CLI_FOR_TESTS.lock().unwrap_or_else(|e| e.into_inner()) = None; + let out = out.unwrap_or_else(|e| panic!("{}", e.msg)); + assert_eq!(out.text, "你好"); + assert_eq!(out.tool_calls[0].name, "read_file"); + assert_eq!(out.tool_calls[0].args, r#"{"path":"a.txt"}"#); + assert_eq!(events.lock().unwrap().as_slice(), ["read_file"]); + assert_eq!(out.usage.output, 7); + let flags = std::fs::read_to_string(format!("{}.args", seen.display())).unwrap(); + assert!(flags.lines().any(|l| l == "--tools")); + assert!(flags.lines().any(|l| l == "--no-session-persistence")); + let input = std::fs::read_to_string(format!("{}.input", seen.display())).unwrap(); + assert!(input.contains("【使用者】") && input.contains("嗨"), "{input}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The real command, signed in: one short question on the cheapest model. Run by hand; it uses + /// a little of the person's Claude quota. + #[test] + #[ignore = "uses the real claude command and the person's Claude quota"] + fn real_cli_answers_when_installed() { + assert!(installed(), "claude 指令找不到"); + let cancel = AtomicBool::new(false); + let mut r = req(vec![Message::user("只回答一個字:好")], vec![]); + r.model = "haiku".into(); + let out = run(&r, &cancel, &|_| {}).unwrap_or_else(|e| panic!("{}", e.msg)); + assert!(!out.text.trim().is_empty(), "the CLI answered with no words"); + } +} diff --git a/src/featuremap.rs b/src/featuremap.rs index f90084f..fce5659 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -39,6 +39,7 @@ pub const AREAS: &[Area] = &[ area!("bots", "Bot 清單與選單"), area!("profile", "Bot 設定與能力"), area!("models", "模型與 ChatGPT 方案"), + area!("claudecode", "Claude Code(本機)"), area!("team", "同事與群組"), area!("branch", "支線(/btw)"), area!("memory", "記憶"), diff --git a/src/icons.rs b/src/icons.rs index 944166f..383b2b2 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -412,7 +412,8 @@ pub fn provider_mark(p: &Painter, rect: Rect, kind: crate::providers::ProviderKi K::Xai => (rgb(0x14, 0x14, 0x14), Color32::WHITE), K::OpenAi => (rgb(0x14, 0x14, 0x14), Color32::WHITE), K::ChatGpt => (rgb(0x10, 0xa3, 0x7f), Color32::WHITE), - K::Anthropic => (rgb(0xd9, 0x77, 0x57), Color32::WHITE), + // Claude Code is Claude's own tool: the same tile and burst as Claude. + K::Anthropic | K::ClaudeCode => (rgb(0xd9, 0x77, 0x57), Color32::WHITE), K::Gemini => (rgb(0xee, 0xf2, 0xfd), rgb(0x3f, 0x7b, 0xf0)), K::OpenRouter => (rgb(0x64, 0x67, 0xf2), Color32::WHITE), K::OpenCodeGo => (rgb(0x23, 0x20, 0x1e), Color32::WHITE), @@ -437,7 +438,7 @@ pub fn provider_mark(p: &Painter, rect: Rect, kind: crate::providers::ProviderKi } } // A burst of rays. - K::Anthropic => { + K::Anthropic | K::ClaudeCode => { for i in 0..10 { let a = i as f32 * std::f32::consts::TAU / 10.0; let len = if i % 2 == 0 { r * 1.15 } else { r * 0.8 }; diff --git a/src/main.rs b/src/main.rs index 07b3c6a..2be4a1f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,6 +47,7 @@ mod marks; mod mcp; mod mcp_oauth; mod chatgpt; +mod claudecli; mod memory; mod memstore; mod mention; @@ -550,6 +551,8 @@ fn main() -> eframe::Result<()> { viewport = viewport.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false); } let mut options = eframe::NativeOptions { viewport, ..Default::default() }; + // Finding the `claude` command asks the login shell for its PATH (slow); the settings page asks every frame. + claudecli::warm(); // The built-in graphics, not the separate card: egui-wgpu asks for HighPerformance, which on // a two-GPU Intel Mac keeps the discrete card awake (heat, fans, battery) for a chat window. // WGPU_POWER_PREF still wins when set. diff --git a/src/providers.rs b/src/providers.rs index a966987..9286a41 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -18,6 +18,9 @@ pub enum ProviderKind { /// ChatGPT 方案: the person's ChatGPT plan, signed in with ChatGPT instead of a key (chatgpt.rs). ChatGpt, Anthropic, + /// Claude Code: the person's own `claude` command, signed in with their Claude subscription + /// (claudecli.rs). No key, no address; the tools and approvals stay AnyBot's. + ClaudeCode, Gemini, OpenRouter, OpenCodeGo, @@ -25,11 +28,12 @@ pub enum ProviderKind { Custom, } -pub const ALL_PROVIDERS: [ProviderKind; 9] = [ +pub const ALL_PROVIDERS: [ProviderKind; 10] = [ ProviderKind::Xai, ProviderKind::OpenAi, ProviderKind::ChatGpt, ProviderKind::Anthropic, + ProviderKind::ClaudeCode, ProviderKind::Gemini, ProviderKind::OpenRouter, ProviderKind::OpenCodeGo, @@ -65,6 +69,7 @@ impl ProviderKind { ProviderKind::OpenAi => "openai", ProviderKind::ChatGpt => "chatgpt", ProviderKind::Anthropic => "anthropic", + ProviderKind::ClaudeCode => "claude-code", ProviderKind::Gemini => "gemini", ProviderKind::OpenRouter => "openrouter", ProviderKind::OpenCodeGo => "opencode-go", @@ -79,6 +84,7 @@ impl ProviderKind { ProviderKind::OpenAi => "OpenAI", ProviderKind::ChatGpt => "ChatGPT 方案", ProviderKind::Anthropic => "Claude", + ProviderKind::ClaudeCode => "Claude Code", ProviderKind::Gemini => "Google Gemini", ProviderKind::OpenRouter => "OpenRouter", ProviderKind::OpenCodeGo => "OpenCode Go", @@ -94,6 +100,8 @@ impl ProviderKind { ProviderKind::OpenAi => "https://api.openai.com/v1", ProviderKind::ChatGpt => crate::chatgpt::API_BASE, ProviderKind::Anthropic => "https://api.anthropic.com/v1", + // No address: the command runs on this computer (claudecli.rs). + ProviderKind::ClaudeCode => "", ProviderKind::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai", ProviderKind::OpenRouter => "https://openrouter.ai/api/v1", // The models list is {base}/v1/models; chat goes to {base}/openai/v1 or {base}/anthropic/v1. @@ -110,6 +118,7 @@ impl ProviderKind { // (The example in OpenAI's plan-usage docs; the real list comes from 取得模型清單.) ProviderKind::ChatGpt => "gpt-6.1-sol", ProviderKind::Anthropic => "claude-opus-5-5", + ProviderKind::ClaudeCode => "sonnet", ProviderKind::Gemini => "gemini-2.5-flash", ProviderKind::OpenRouter => "openrouter/auto", ProviderKind::OpenCodeGo => "kimi-k3", @@ -139,6 +148,7 @@ impl ProviderKind { ProviderKind::OpenAi => &["gpt-5", "gpt-5-mini", "gpt-4.1"], ProviderKind::ChatGpt => &["gpt-6.1-sol"], ProviderKind::Anthropic => &["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-1"], + ProviderKind::ClaudeCode => &crate::claudecli::MODELS, ProviderKind::Gemini => &["gemini-2.5-flash", "gemini-2.5-pro"], ProviderKind::OpenRouter => &["openrouter/auto"], ProviderKind::OpenCodeGo => &["kimi-k3", "glm-5.3", "deepseek-v4-pro", "qwen3.8-max", "minimax-m3", "mimo-v2.6-pro"], @@ -148,7 +158,7 @@ impl ProviderKind { } pub fn needs_key(self) -> bool { - !matches!(self, ProviderKind::Ollama | ProviderKind::Custom) + !matches!(self, ProviderKind::Ollama | ProviderKind::Custom | ProviderKind::ClaudeCode) } pub fn env_var(self) -> Option<&'static str> { @@ -169,6 +179,7 @@ impl ProviderKind { ProviderKind::OpenAi => "在 platform.openai.com 取得 API 金鑰", ProviderKind::ChatGpt => "用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰:用 ChatGPT 帳號登入就好", ProviderKind::Anthropic => "在 console.anthropic.com 取得 API 金鑰", + ProviderKind::ClaudeCode => "用這台電腦上已登入的 Claude Code(Claude 訂閱),不用 API 金鑰:先安裝 claude,再在終端機執行 claude 並輸入 /login", ProviderKind::Gemini => "在 aistudio.google.com 取得 API 金鑰", ProviderKind::OpenRouter => "在 openrouter.ai 取得 API 金鑰", ProviderKind::OpenCodeGo => "在 opencode.ai 的 Console 訂閱 Go,再複製 API 金鑰", @@ -406,7 +417,7 @@ impl Failure { fn retry(msg: String) -> Self { Failure { msg, retryable: true, retry_after_ms: None } } - fn fatal(msg: String) -> Self { + pub fn fatal(msg: String) -> Self { Failure { msg, retryable: false, retry_after_ms: None } } } @@ -549,6 +560,7 @@ pub fn resolve_key_for(kind: ProviderKind, stored: &str, stored_base: &str) -> S pub fn ready(kind: ProviderKind, stored_key: &str) -> bool { match kind { ProviderKind::ChatGpt => crate::chatgpt::usable(), + ProviderKind::ClaudeCode => crate::claudecli::installed(), _ => !kind.needs_key() || !resolve_key(kind, stored_key).is_empty(), } } @@ -578,6 +590,10 @@ pub fn runs_at(kind: ProviderKind, base_url: &str) -> RunsAt { if kind == ProviderKind::ChatGpt { return RunsAt::Cloud(service()); } + // The command runs here, but what it is given goes to Claude's servers. + if kind == ProviderKind::ClaudeCode { + return RunsAt::Cloud("Claude(經這台電腦上的 Claude Code)".into()); + } let Some(host) = base_host(base_url) else { return RunsAt::Cloud(service()) }; let h = host.trim_start_matches('[').trim_end_matches(']').trim_end_matches('.').to_ascii_lowercase(); if h == "localhost" || h.ends_with(".localhost") { @@ -990,6 +1006,7 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea let req = blind_copy.as_ref().unwrap_or(req); let result = match req.kind { ProviderKind::Anthropic => stream_anthropic(req, cancel, &tracked), + ProviderKind::ClaudeCode => crate::claudecli::run(req, cancel, &tracked), ProviderKind::ChatGpt => stream_responses(req, cancel, &tracked), ProviderKind::OpenCodeGo => { let mut r = req.clone(); @@ -1081,7 +1098,7 @@ fn with_context(m: &Message) -> String { } } -fn system_with_summaries(req: &ChatRequest) -> String { +pub(crate) fn system_with_summaries(req: &ChatRequest) -> String { let mut s = req.system.clone(); for m in req.history.iter().filter(|m| m.summary) { s.push_str("\n\n先前對話的摘要:\n"); @@ -2444,6 +2461,14 @@ pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result< if kind == ProviderKind::ChatGpt { return chatgpt_models(); } + // The command's own names; "測試連線" here means: is it installed. + if kind == ProviderKind::ClaudeCode { + return if crate::claudecli::installed() { + Ok(crate::claudecli::MODELS.iter().map(|m| m.to_string()).collect()) + } else { + Err("找不到 Claude Code(claude 指令)。請先安裝,再重新開啟 AnyBot。".into()) + }; + } if kind.needs_key() && api_key.is_empty() { return Err("請先貼上 API 金鑰".into()); }