feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰

- 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。
  第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce;
  ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。
- 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions),
  token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結,
  不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。
- 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量;
  連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。
- Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。
- 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token
  沒解開就被當成憑證送出,登入等於每次重開都失效。

已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::);
  授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。
未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器);
  螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。
  動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-17 17:23:10 +08:00
parent d64766e953
commit a03f7c7458
20 changed files with 1923 additions and 29 deletions

View File

@ -2668,4 +2668,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
## 其他(2026-11-04) ## 其他(2026-11-04)
- **OpenCode Go 供應商**:設定 → 模型 選「OpenCode Go」,貼上 opencode.ai Console 的 Go 金鑰。依官方模型清單自動決定每個模型用 OpenAI 格式(/openai/v1)或 Anthropic 格式(/anthropic/v1);每個 Bot 的對話帶固定的 x-opencode-session。 - **OpenCode Go 供應商**:設定 → 模型 選「OpenCode Go」,貼上 opencode.ai Console 的 Go 金鑰。依官方模型清單自動決定每個模型用 OpenAI 格式(/openai/v1)或 Anthropic 格式(/anthropic/v1);每個 Bot 的對話帶固定的 x-opencode-session。
- **ChatGPT 方案供應商**(`src/chatgpt.rs`):用 ChatGPT 帳號登入,Bot 用使用者 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰——OpenAI 給開源、本機執行 App 的 Sign in with ChatGPT(developers.openai.com/siwc/token-sharing-open-source)。
- 登入:設定 → 模型 → ChatGPT 方案 →「使用 ChatGPT 繼續」,或請 Bot 用 `chatgpt_login`。瀏覽器到 auth.openai.com(PKCE S256、state、nonce、`resource=https://api.openai.com/v1`、scope 含 `chatgpt.tokens.use.direct`),回到大腦上的 `http://127.0.0.1:<port>/auth/callback`(先試 1455);瀏覽器在別台電腦時,把那頁網址貼回聊天由大腦換 token。第一次用 `client_id=dynamic_agent_client` 註冊、`agent_name_hint=AnyBot`,記住發下來的 `oaiapp_…` 之後重用;每台大腦一個隨機 `ext_agent_host_id`(urn:uuid)。
- 檢查:callback 的 state;新註冊一定要帶回 client_id,重新登入帶回不同的就拒絕;ID token 用 OpenAI 的 JWKS 驗 RS256 簽章、iss、aud(=client_id)、exp、nonce;同一個註冊換成別的帳號(sub 不同)就拒絕。沒有 `chatgpt.tokens.use.direct` 算登入但不能用。
- Token 存在 `<資料夾>/providers/chatgpt.json`(0600、先寫暫存檔再換名),access/refresh/id_token 用設定密鑰封存;不進設定檔,螢幕電腦和手機拿不到。剩 5 分鐘到期或被回 401 時用 refresh token 更新(一次一個,refresh token 會輪替);refresh token 失效就清掉 token、保留註冊,請使用者重新登入。登出會到 OpenAI 撤銷 refresh token;「換帳號」連註冊一起忘掉。
- 要求:只送到 `https://api.openai.com/v1/responses`(不管設定裡的網址),`store:false`、`stream:true`,系統提示放 `instructions`,工具用 function(`strict:false`),思考模式用 `reasoning.effort`;不送 temperature、max_output_tokens、previous_response_id 等方案不收的欄位。收到 `response.completed` 才算回答完成。模型清單從 `/v1/models` 的 `models`(visibility=list 的 slug)。
- 錯誤:`subscription_sharing_usage_limit_exceeded` 顯示「已達用量上限(ChatGPT 方案)」和管理用量連結(chatgpt.com/settings/usage),不重試、不改用 API 金鑰;`usage_unavailable`、503 稍後重試;不支援的功能說出是哪個參數(思考模式不支援就自動拿掉再試)。
- 第一次用方案登入成功時說一次「你正在使用你的 ChatGPT 方案」。語音不能用方案。
- 螢幕電腦和手機:帳號在大腦。螢幕電腦的設定頁經 `/api/sync/chatgpt`(只有擁有者的螢幕),手機經 `/api/act/chatgpt`(只有擁有者)請大腦開始登入、登出、換帳號、看狀態;登入頁開在使用者那台,回來的那頁打不開時貼回網址,由大腦完成。大腦的狀態顯示在螢幕電腦的模型選單和 Bot 設定(不再一律寫「未登入」)。
- Bot 請求登出、換帳號要先經使用者確認。目標檢查、發布前檢查找「別家模型」時,ChatGPT 方案排最後。
- 已知限制:「換帳號」會忘掉原帳號的註冊,換回來時會重新註冊一次。
- **看不到圖片的模型**:模型回「不能收圖片」(例如「At most 0 image(s)」)時,AnyBot 記住這個模型,立刻改成不附圖片重試,截圖的位置換成文字說明,Bot 不會再卡住。 - **看不到圖片的模型**:模型回「不能收圖片」(例如「At most 0 image(s)」)時,AnyBot 記住這個模型,立刻改成不附圖片重試,截圖的位置換成文字說明,Bot 不會再卡住。

View File

@ -12,7 +12,8 @@
- 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀平均排成兩列;10 種顏色和「自訂」同一列;按「自訂」出現一格一格的色盤——12 個色相各四種深淺加一列灰階,直接點,沒有滑桿——和「色碼」欄,打完整的 #rrggbb 才換色);「AI 供應商與模型」(供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」——欄位名稱在上,說明在名稱旁的「?」);接著「電腦操作」「能力」「技能」「記憶」四張預設收起,各只有一行:名稱、目前怎麼設(例如「11 / 11 類」「會 8 / 8」「還沒有」)和 ▸,點了才展開;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot」(「?」說明:團隊成員看得到它的聊天、頁面和檔案)。 - 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀平均排成兩列;10 種顏色和「自訂」同一列;按「自訂」出現一格一格的色盤——12 個色相各四種深淺加一列灰階,直接點,沒有滑桿——和「色碼」欄,打完整的 #rrggbb 才換色);「AI 供應商與模型」(供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」——欄位名稱在上,說明在名稱旁的「?」);接著「電腦操作」「能力」「技能」「記憶」四張預設收起,各只有一行:名稱、目前怎麼設(例如「11 / 11 類」「會 8 / 8」「還沒有」)和 ▸,點了才展開;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot」(「?」說明:團隊成員看得到它的聊天、頁面和檔案)。
- Soul 與指示只有它自己讀;描述、擅長、不找它做的事、會的技能、在哪幾台電腦做事會寫進其他 Bot 的同事名冊。 - Soul 與指示只有它自己讀;描述、擅長、不找它做的事、會的技能、在哪幾台電腦做事會寫進其他 Bot 的同事名冊。
- 能力 11 類:「上網」「瀏覽器」「看螢幕與操作」「檔案與指令」「Mac App」「連接器」「電話、簡訊、X」「例行任務」「頁面」「和其他 Bot 合作」「管理 App」。沒勾的工具不提供給它,也不寫進說明。記憶、技能、問你問題、傳檔案到聊天、表情和卡片每個 Bot 都有。 - 能力 11 類:「上網」「瀏覽器」「看螢幕與操作」「檔案與指令」「Mac App」「連接器」「電話、簡訊、X」「例行任務」「頁面」「和其他 Bot 合作」「管理 App」。沒勾的工具不提供給它,也不寫進說明。記憶、技能、問你問題、傳檔案到聊天、表情和卡片每個 Bot 都有。
- 供應商:xAI Grok、OpenAI、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama(本機)、自訂(OpenAI 相容),每個 Bot 各選各的。 - 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama(本機)、自訂(OpenAI 相容),每個 Bot 各選各的。
- 「ChatGPT 方案」:用 ChatGPT 帳號登入(OpenAI 的 Sign in with ChatGPT),用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰。第一次登入時 AnyBot 向 OpenAI 註冊自己,之後重用;登入後第一次會說一次「你正在使用你的 ChatGPT 方案」。
- 思考模式:「自動(模型自己決定)」「快速(想得少,回得快)」「平衡」「深入(想得久,較慢)」。執行步驟用的模型:「自動」、「不分開(每一步都用上面的模型)」或指定一個;上面的模型負責想計畫、遇到問題和最後確認,中間的步驟交給快的模型。 - 思考模式:「自動(模型自己決定)」「快速(想得少,回得快)」「平衡」「深入(想得久,較慢)」。執行步驟用的模型:「自動」、「不分開(每一步都用上面的模型)」或指定一個;上面的模型負責想計畫、遇到問題和最後確認,中間的步驟交給快的模型。
## 使用者怎麼到 ## 使用者怎麼到
@ -20,12 +21,12 @@
- 側邊欄右上角的 +(「新增」):「新增 Bot」「從範本建立」;⌘N 直接打開「建立 Bot」。放大鏡或 ⌘F 搜尋。 - 側邊欄右上角的 +(「新增」):「新增 Bot」「從範本建立」;⌘N 直接打開「建立 Bot」。放大鏡或 ⌘F 搜尋。
- Bot 選單:右鍵側邊欄的 Bot,或聊天右上角「更多」。「Bot 設定」從「編輯 Bot…」進去。 - Bot 選單:右鍵側邊欄的 Bot,或聊天右上角「更多」。「Bot 設定」從「編輯 Bot…」進去。
- 換模型最快:輸入框左邊 + 裡的模型那一行(「選擇這個 Bot 用來思考的模型」),每家一個子選單,沒金鑰的標「(未設定金鑰)」,「其他模型…」打開 Bot 設定自己填。 - 換模型最快:輸入框左邊 + 裡的模型那一行(「選擇這個 Bot 用來思考的模型」),每家一個子選單,沒金鑰的標「(未設定金鑰)」,「其他模型…」打開 Bot 設定自己填。
- 金鑰在「設定 › 模型」。聊天還沒有訊息又沒金鑰時,中間有「設定 (供應商) 的 API 金鑰」直接帶過去;Bot 設定裡是紅字加「前往設定」。 - 金鑰在「設定 › 模型」;ChatGPT 方案在同一頁按「使用 ChatGPT 繼續」,瀏覽器登入並勾同意。聊天還沒有訊息又沒金鑰時,中間有「設定 (供應商) 的 API 金鑰」直接帶過去;Bot 設定裡是紅字加「前往設定」。
## 怎麼操作 ## 怎麼操作
- Bot:使用者問「你會什麼」「你的設定是什麼」時先用 `my_profile`;要改自己用 `update_my_profile`,只帶要改的欄位(description、soul、strengths、not_for、abilities_on/abilities_off、skills_add/skills_remove、computers_add/computers_remove、default_computer、provider、model、thinking、step_model、color、shape);soul 要先讀再送整段。`list_bots` 看所有 Bot 的供應商、模型、描述和所在分區。`create_bot`(template,或 name、description、instructions、provider、model)建新 Bot;`update_bot`(bot 空白是自己)改名稱、描述、指示、供應商、模型、釘選、預設電腦。 - Bot:使用者問「你會什麼」「你的設定是什麼」時先用 `my_profile`;要改自己用 `update_my_profile`,只帶要改的欄位(description、soul、strengths、not_for、abilities_on/abilities_off、skills_add/skills_remove、computers_add/computers_remove、default_computer、provider、model、thinking、step_model、color、shape);soul 要先讀再送整段。`list_bots` 看所有 Bot 的供應商、模型、描述和所在分區。`create_bot`(template,或 name、description、instructions、provider、model)建新 Bot;`update_bot`(bot 空白是自己)改名稱、描述、指示、供應商、模型、釘選、預設電腦。用 ChatGPT 方案:`chatgpt_login`(action:status、login、logout、switch_account)——login 給一個網址,用 open_for_person 開給使用者或直接給他;登入後那頁打不開(瀏覽器在別台電腦、大腦在伺服器),請他把那頁網址整個貼回來,再帶 callback 呼叫一次;然後把供應商改成 chatgpt。
- 驗證:用 + 建一個 Bot,填 Soul 與指示和擅長後按「建立 Bot」,重開 AnyBot 還在;在聊天裡說「把你的檔案與指令能力關掉」,要先跳出列出改動的確認卡片,按拒絕什麼都不變,按允許後 Bot 設定的「能力」少勾一格;換一個沒金鑰的供應商,要出現紅字和「前往設定」。頭像按「自訂」,色盤點一格頭像就換色,「色碼」打 #6b4a55 也換;整個視窗不能變寬(下面的卡片和最上面的標題列一樣寬)。自動測試:`cargo test profile::`、`cargo test appctl::`、`cargo test app::sidebar_ui::`、`cargo test app::tests::`。 - 驗證:用 + 建一個 Bot,填 Soul 與指示和擅長後按「建立 Bot」,重開 AnyBot 還在;在聊天裡說「把你的檔案與指令能力關掉」,要先跳出列出改動的確認卡片,按拒絕什麼都不變,按允許後 Bot 設定的「能力」少勾一格;換一個沒金鑰的供應商,要出現紅字和「前往設定」。設定 › 模型 › ChatGPT 方案 按「使用 ChatGPT 繼續」,登入並同意後顯示「已用 ChatGPT 登入(信箱)」,Bot 換成 ChatGPT 方案能回話;請 Bot 用 `chatgpt_login` 的 login 也能登入(大腦在伺服器時貼回網址);連到伺服器大腦的螢幕電腦按「使用 ChatGPT 繼續」、貼回網址按「完成登入」,大腦的狀態要變成已登入;請 Bot 登出要先跳確認卡片。頭像按「自訂」,色盤點一格頭像就換色,「色碼」打 #6b4a55 也換;整個視窗不能變寬(下面的卡片和最上面的標題列一樣寬)。自動測試:`cargo test profile::`、`cargo test appctl::`、`cargo test chatgpt::`、`cargo test providers::`、`cargo test app::sidebar_ui::`、`cargo test app::tests::`。
## 陷阱 ## 陷阱
@ -38,3 +39,4 @@
- 能力或技能全部勾回來就是「全部」:之後新增的能力類別、新裝的技能也自動算它的。它自己的電腦一定能用,拿不掉。 - 能力或技能全部勾回來就是「全部」:之後新增的能力類別、新裝的技能也自動算它的。它自己的電腦一定能用,拿不掉。
- 名字或模型空白時,「建立 Bot」「儲存」按不下去。`create_bot` 建出來的 Bot 電腦工具是關的。 - 名字或模型空白時,「建立 Bot」「儲存」按不下去。`create_bot` 建出來的 Bot 電腦工具是關的。
- 「匯出 Bot」不帶聊天記錄、金鑰和 Token。 - 「匯出 Bot」不帶聊天記錄、金鑰和 Token。
- ChatGPT 方案:額度用完會停下來說「已達用量上限(ChatGPT 方案)」並給「管理用量」連結,不會自動改用 API 金鑰付費,也不會一直重試;沒勾同意使用方案,算登入了但不能用;在 ChatGPT 設定裡中斷連線,下一次要求才會發現,要重新登入。語音轉文字、朗讀不能用方案,還是要 OpenAI 的 API 金鑰。登入的 token 存在大腦,不會傳到螢幕電腦和手機。連到大腦的螢幕電腦:設定 › 模型 › ChatGPT 方案 按鈕一樣,登入頁開在這台;登入後那頁打不開,把網址貼進下面的欄位按「完成登入」。手機:設定 › AI 服務 › ChatGPT 方案 →「使用 ChatGPT 繼續…」,同樣貼回網址。`chatgpt_login` 的 logout、switch_account 會先跳確認卡片。

View File

@ -12,7 +12,7 @@
- Bot:時區,例行任務和提醒用([routines](routines.md))。 - Bot:時區,例行任務和提醒用([routines](routines.md))。
- 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。 - 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。
- 「手機與帳號」頁(從 一般 › 帳戶 進去,[phone](phone.md)):「AnyBot 帳號」(登入、備份、還原)、大腦和「加一台電腦」([computers](computers.md))、「同一個網路直接連」、「手機可以做什麼」、「直接連線的裝置」、「分享給團隊」([team](team.md))、「帳號裡的電腦」。 - 「手機與帳號」頁(從 一般 › 帳戶 進去,[phone](phone.md)):「AnyBot 帳號」(登入、備份、還原)、大腦和「加一台電腦」([computers](computers.md))、「同一個網路直接連」、「手機可以做什麼」、「直接連線的裝置」、「分享給團隊」([team](team.md))、「帳號裡的電腦」。
- 「模型」:每家 AI 供應商的 API 金鑰、服務網址、新 Bot 預設模型、「測試連線並取得模型清單」([bots](bots.md));本機或區網的供應商多一個「看不到圖時,請雲端模型看截圖和附件」(預設關,[chat](chat.md))。 - 「模型」:每家 AI 供應商的 API 金鑰、服務網址、新 Bot 預設模型、「測試連線並取得模型清單」([bots](bots.md));本機或區網的供應商多一個「看不到圖時,請雲端模型看截圖和附件」(預設關,[chat](chat.md))。「ChatGPT 方案」沒有金鑰和網址欄,改成「ChatGPT 帳號」:登入狀態、「使用 ChatGPT 繼續」「登出」「換帳號」「打開登入頁」「管理用量」;連到別台大腦時多一格貼回登入網址和「完成登入」([bots](bots.md))。
- 「整合」,三個小分頁: - 「整合」,三個小分頁:
- 訊息管道:Slack、Discord、Telegram、Teams…([channels](channels.md))。 - 訊息管道:Slack、Discord、Telegram、Teams…([channels](channels.md))。
- 連接器:「連接器(MCP)」清單、「可以用的工具」、「連接器市集」、「新增連接器」([connectors](connectors.md))。 - 連接器:「連接器(MCP)」清單、「可以用的工具」、「連接器市集」、「新增連接器」([connectors](connectors.md))。

View File

@ -2499,6 +2499,18 @@ function wireSettings(kind, st) {
const p = st.providers[+x.dataset.prov]; const p = st.providers[+x.dataset.prov];
sheet(p.label, [ sheet(p.label, [
...(p.needs_key || p.key === "Custom" ? [{icon: "key", label: p.ready && p.needs_key ? "換一把 API 金鑰…" : "設定 API 金鑰…", on: async () => { const k = await ask(p.label + " 的 API 金鑰", "", "貼上金鑰(存在這台 AnyBot,手機看不到)"); if (k && await act("provider", {provider: p.key, key: k}, "已設定金鑰")) again(); }}] : []), ...(p.needs_key || p.key === "Custom" ? [{icon: "key", label: p.ready && p.needs_key ? "換一把 API 金鑰…" : "設定 API 金鑰…", on: async () => { const k = await ask(p.label + " 的 API 金鑰", "", "貼上金鑰(存在這台 AnyBot,手機看不到)"); if (k && await act("provider", {provider: p.key, key: k}, "已設定金鑰")) again(); }}] : []),
// ChatGPT 方案: an account on the brain, not a key. The sign-in page opens here; the page it
// comes back to (127.0.0.1 on the brain) won't load on the phone, so its address is pasted back.
...(p.account ? [{icon: "key", label: p.ready ? "重新用 ChatGPT 登入…" : "使用 ChatGPT 繼續…", on: async () => {
const w = window.open("", "_blank");
const v = await act("chatgpt", {action: "login"}, false);
if (!v || !v.url) { if (w) w.close(); if (v && v.text) toast(v.text); return; }
if (w) w.location = v.url; else location.assign(v.url);
const cb = await ask("登入並同意後,那一頁打不開的話,把它的網址整個貼在這裡", "", "http://127.0.0.1:1455/auth/callback?code=…");
if (!cb) return;
const r = await act("chatgpt", {action: "login", callback: cb}, false);
if (r) { toast(r.text || (r.ok ? "已登入" : "沒有登入成功")); again(); }
}}, ...(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(); }}, {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(); }},
...(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(); }}] : []), ...(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(); }}] : []),
]); ]);

View File

@ -2480,6 +2480,13 @@ impl App {
self.manage_connectors(ctx, call); self.manage_connectors(ctx, call);
return; return;
} }
// ChatGPT 方案: over the network, on a thread (signing in finishes when the person does).
if call.name == crate::chatgpt::TOOL {
std::thread::spawn(move || {
let _ = call.reply.send(crate::chatgpt::run_tool(&call.args));
});
return;
}
// Hooks: the person's file (the change was shown to them and they said yes). // Hooks: the person's file (the change was shown to them and they said yes).
if call.name == crate::hooks::MANAGE_TOOL { if call.name == crate::hooks::MANAGE_TOOL {
let r = crate::hooks::parse_change(&call.args).and_then(|c| crate::hooks::apply_change(&c)); let r = crate::hooks::parse_change(&call.args).and_then(|c| crate::hooks::apply_change(&c));
@ -3248,6 +3255,130 @@ impl App {
self.fetch_status.insert(kind, "正在取得模型清單…".into()); self.fetch_status.insert(kind, "正在取得模型清單…".into());
} }
/// 設定 › 模型 › ChatGPT 方案: who is signed in, and 使用 ChatGPT 繼續 / 登出 / 換帳號 / 管理用量.
/// (On a screen of another brain the account is the brain's: a bot signs it in from the chat.)
fn chatgpt_account_ui(&mut self, ui: &mut egui::Ui, p: Palette) {
field_label(ui, "ChatGPT 帳號", p);
if self.mir.on {
self.chatgpt_on_brain_ui(ui, p);
return;
}
let a = crate::chatgpt::account();
hint(ui, crate::chatgpt::status_text(), p);
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
if !(a.signed_in() && a.plan_ok()) && ui.add(primary_button("使用 ChatGPT 繼續", p)).on_hover_text(t("在瀏覽器登入你的 ChatGPT 帳號,並同意讓 AnyBot 使用你的 ChatGPT 方案")).clicked() {
crate::chatgpt::set_note("正在打開 ChatGPT 的登入頁…");
std::thread::spawn(|| match crate::chatgpt::start() {
// (Windows' `start` reads & in an address as the end of it: there, the link below opens it.)
Ok(_) if cfg!(windows) => crate::chatgpt::set_note("按「打開登入頁」,登入並同意後回到這裡(最多等 10 分鐘)。"),
Ok(u) => {
crate::chatgpt::set_note("已在瀏覽器打開 ChatGPT 的登入頁:登入並同意後回到這裡(最多等 10 分鐘)。");
let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&u));
}
Err(e) => crate::chatgpt::set_note(format!("沒辦法開始登入:{e}")),
});
}
if a.signed_in() && ui.add(secondary_button("登出")).on_hover_text(t("撤銷 AnyBot 使用這個 ChatGPT 帳號的權限")).clicked() {
std::thread::spawn(|| crate::chatgpt::set_note(crate::chatgpt::logout(false).unwrap_or_else(|e| e)));
}
if !a.client_id.is_empty() && ui.add(secondary_button("換帳號")).on_hover_text(t("登出並忘記這個帳號,下次用另一個 ChatGPT 帳號登入")).clicked() {
std::thread::spawn(|| crate::chatgpt::set_note(crate::chatgpt::logout(true).unwrap_or_else(|e| e)));
}
if let Some(u) = crate::chatgpt::login_url() {
ui.hyperlink_to(t("打開登入頁"), u);
}
ui.hyperlink_to(t("管理用量"), crate::chatgpt::USAGE_URL);
});
let note = crate::chatgpt::note();
if !note.is_empty() {
hint(ui, note, p);
}
ui.add_space(6.0);
}
/// The same, on a screen of another brain: the account is the brain's (its tokens stay
/// there), so each button asks the brain; the sign-in page opens here, and the page it comes
/// back to (127.0.0.1 on the brain) is pasted back below.
fn chatgpt_on_brain_ui(&mut self, ui: &mut egui::Ui, p: Palette) {
if crate::chatgpt::brain_view_stale(30) {
self.chatgpt_ask_brain(serde_json::json!({"action": "status"}), true);
}
let v = crate::chatgpt::brain_view().unwrap_or(serde_json::Value::Null);
let said = v["status"].as_str().or(v["error"].as_str()).unwrap_or("正在問大腦…").to_string();
hint(ui, said, p);
let (signed_in, usable) = (v["signed_in"] == true, v["signed_in"] == true && v["plan_ok"] == true);
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
if !usable && ui.add(primary_button("使用 ChatGPT 繼續", p)).on_hover_text(t("在瀏覽器登入你的 ChatGPT 帳號,並同意讓 AnyBot 使用你的 ChatGPT 方案")).clicked() {
crate::chatgpt::set_note("正在請大腦開始登入…");
self.chatgpt_ask_brain(serde_json::json!({"action": "login"}), false);
}
if signed_in && ui.add(secondary_button("登出")).on_hover_text(t("撤銷 AnyBot 使用這個 ChatGPT 帳號的權限")).clicked() {
self.chatgpt_ask_brain(serde_json::json!({"action": "logout"}), false);
}
if v["registered"] == true && ui.add(secondary_button("換帳號")).on_hover_text(t("登出並忘記這個帳號,下次用另一個 ChatGPT 帳號登入")).clicked() {
self.chatgpt_ask_brain(serde_json::json!({"action": "switch_account"}), false);
}
if let Some(u) = v["url"].as_str().filter(|_| !usable) {
ui.hyperlink_to(t("打開登入頁"), u);
}
ui.hyperlink_to(t("管理用量"), crate::chatgpt::USAGE_URL);
});
// The page the browser came back to, pasted: the brain finishes the sign-in with it.
if v["url"].is_string() && !usable {
let id = egui::Id::unique("chatgpt-callback");
let mut pasted = ui.data_mut(|d| d.get_temp::<String>(id)).unwrap_or_default();
ui.add_space(4.0);
ui.allocate_ui_with_layout(vec2(ui.available_width(), 30.0), Layout::right_to_left(Align::Center), |ui| {
if ui.add_enabled(pasted.contains("code="), secondary_button("完成登入")).clicked() {
crate::chatgpt::set_note("正在請大腦完成登入…");
self.chatgpt_ask_brain(serde_json::json!({"action": "login", "callback": pasted.trim()}), false);
pasted.clear();
}
ui.add(egui::TextEdit::singleline(&mut pasted).hint_text(t("登入後打不開的那一頁的網址(http://127.0.0.1:…)")).desired_width(ui.available_width()));
});
ui.data_mut(|d| d.insert_temp(id, pasted));
}
let note = crate::chatgpt::note();
if !note.is_empty() {
hint(ui, note, p);
}
ui.add_space(6.0);
}
/// Ask the brain about its ChatGPT account (`quiet`: just how it stands, one at a time).
fn chatgpt_ask_brain(&self, body: serde_json::Value, quiet: bool) {
static ASKING: AtomicBool = AtomicBool::new(false);
if quiet && ASKING.swap(true, Ordering::SeqCst) {
return;
}
let s = self.state.remote.clone();
std::thread::spawn(move || {
match crate::remote::sync_post(&s, "chatgpt", &body) {
Ok(v) => {
if let Some(u) = v["url"].as_str() {
// (Windows' `start` reads & in an address as the end of it: there, the link opens it.)
if cfg!(windows) {
crate::chatgpt::set_note("按「打開登入頁」登入並同意。之後那一頁打不開的話,把它的網址整個貼在下面,按「完成登入」。");
} else {
crate::chatgpt::set_note("已在瀏覽器打開登入頁:登入並同意。之後那一頁打不開的話,把它的網址整個貼在下面,按「完成登入」。");
let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(u));
}
} else if !quiet {
crate::chatgpt::set_note(v["text"].as_str().unwrap_or(""));
}
crate::chatgpt::set_brain_view(v);
}
Err(e) if quiet => crate::chatgpt::set_brain_view(serde_json::json!({"error": format!("問不到大腦:{e}")})),
Err(e) => crate::chatgpt::set_note(format!("問不到大腦:{e}")),
}
if quiet {
ASKING.store(false, Ordering::SeqCst);
}
});
}
fn poll_fetches(&mut self) { fn poll_fetches(&mut self) {
let mut done = vec![]; let mut done = vec![];
for (k, rx) in &self.model_fetch { for (k, rx) in &self.model_fetch {
@ -3825,9 +3956,10 @@ impl App {
ui.add(egui::Label::new(RichText::new(format!("可以在「{}」裡查看、修改檔案和執行指令,動手前會先問你", bot.workdir)).size(FONT_SM).color(p.text3)).wrap()); ui.add(egui::Label::new(RichText::new(format!("可以在「{}」裡查看、修改檔案和執行指令,動手前會先問你", bot.workdir)).size(FONT_SM).color(p.text3)).wrap());
} }
let ps = self.state.provider(bot.provider); let ps = self.state.provider(bot.provider);
if bot.provider.needs_key() && providers::resolve_key(bot.provider, &ps.api_key).is_empty() { if !providers::ready(bot.provider, &ps.api_key) {
ui.add_space(10.0); ui.add_space(10.0);
if ui.button(format!("設定 {} 的 API 金鑰", bot.provider.label())).clicked() { let words = if bot.provider == ProviderKind::ChatGpt { t("用 ChatGPT 登入") } else { format!("設定 {} 的 API 金鑰", bot.provider.label()) };
if ui.button(words).clicked() {
self.show_settings = true; self.show_settings = true;
self.settings_tab = SettingsTab::Providers; self.settings_tab = SettingsTab::Providers;
self.settings_provider = bot.provider; self.settings_provider = bot.provider;
@ -4966,14 +5098,14 @@ impl App {
.iter() .iter()
.map(|&kind| { .map(|&kind| {
let ps = self.state.provider(kind); let ps = self.state.provider(kind);
(kind, !kind.needs_key() || !providers::resolve_key(kind, &ps.api_key).is_empty(), self.models_for(kind)) (kind, providers::ready(kind, &ps.api_key), self.models_for(kind))
}) })
.collect(); .collect();
let row = menu_ui::item_text(ui, p, Some(crate::icons::Icon::Sparkle), &label).on_hover_text(t("選擇這個 Bot 用來思考的模型")); let row = menu_ui::item_text(ui, p, Some(crate::icons::Icon::Sparkle), &label).on_hover_text(t("選擇這個 Bot 用來思考的模型"));
egui::containers::menu::SubMenu::new().show(ui, &row, |ui| { egui::containers::menu::SubMenu::new().show(ui, &row, |ui| {
ui.set_min_width(menu_ui::MENU_W); ui.set_min_width(menu_ui::MENU_W);
for (kind, ready, list) in &models { for (kind, ready, list) in &models {
let title = if *ready { kind.label().to_string() } else { format!("{}({})", kind.label(), t("未設定金鑰")) }; let title = if *ready { kind.label().to_string() } else { format!("{}({})", kind.label(), t(if *kind == ProviderKind::ChatGpt { "未登入" } else { "未設定金鑰" })) };
let icon = if *kind == bot.provider { crate::icons::Icon::Check } else { crate::icons::Icon::Sparkle }; let icon = if *kind == bot.provider { crate::icons::Icon::Check } else { crate::icons::Icon::Sparkle };
let r = menu_ui::item_text(ui, p, Some(icon), &title); let r = menu_ui::item_text(ui, p, Some(icon), &title);
egui::containers::menu::SubMenu::new().show(ui, &r, |ui| { egui::containers::menu::SubMenu::new().show(ui, &r, |ui| {
@ -5165,9 +5297,10 @@ impl App {
}); });
}); });
let ps = self.state.provider(b.provider); let ps = self.state.provider(b.provider);
if b.provider.needs_key() && providers::resolve_key(b.provider, &ps.api_key).is_empty() { if !providers::ready(b.provider, &ps.api_key) {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(RichText::new(format!("還沒有設定 {} 的 API 金鑰", b.provider.label())).size(FONT_XS).color(p.danger)); let words = if b.provider == ProviderKind::ChatGpt { t("還沒用 ChatGPT 登入") } else { format!("還沒有設定 {} 的 API 金鑰", b.provider.label()) };
ui.label(RichText::new(words).size(FONT_XS).color(p.danger));
if ui.add(egui::Button::new(RichText::new(t("前往設定")).size(FONT_XS).color(p.accent)).frame(false)).clicked() { if ui.add(egui::Button::new(RichText::new(t("前往設定")).size(FONT_XS).color(p.accent)).frame(false)).clicked() {
self.show_settings = true; self.show_settings = true;
self.settings_tab = SettingsTab::Providers; self.settings_tab = SettingsTab::Providers;
@ -5791,7 +5924,7 @@ impl App {
ui.spacing_mut().item_spacing.y = 2.0; ui.spacing_mut().item_spacing.y = 2.0;
for k in ALL_PROVIDERS { for k in ALL_PROVIDERS {
let ps = self.state.provider(k); let ps = self.state.provider(k);
let ready = !k.needs_key() || !providers::resolve_key(k, &ps.api_key).is_empty(); let ready = providers::ready(k, &ps.api_key);
let (rect, r) = ui.allocate_exact_size(vec2(PROVIDER_LIST_WIDTH, 32.0), egui::Sense::click()); let (rect, r) = ui.allocate_exact_size(vec2(PROVIDER_LIST_WIDTH, 32.0), egui::Sense::click());
let on = self.settings_provider == k; let on = self.settings_provider == k;
if on || r.hovered() { if on || r.hovered() {
@ -5804,7 +5937,7 @@ impl App {
ui.painter().circle_filled(dot, 4.0, p.up); ui.painter().circle_filled(dot, 4.0, p.up);
} }
ui.painter().text(rect.left_center() + vec2(28.0, 0.0), egui::Align2::LEFT_CENTER, k.label(), egui::FontId::proportional(FONT_BASE), if on { p.text } else { p.text2 }); ui.painter().text(rect.left_center() + vec2(28.0, 0.0), egui::Align2::LEFT_CENTER, k.label(), egui::FontId::proportional(FONT_BASE), if on { p.text } else { p.text2 });
let tip = if ready { "已可使用" } else { "還沒設定金鑰" }; let tip = t(if ready { "已可使用" } else if k == ProviderKind::ChatGpt { "還沒用 ChatGPT 登入" } else { "還沒設定金鑰" });
if r.on_hover_text(tip).clicked() { if r.on_hover_text(tip).clicked() {
self.settings_provider = k; self.settings_provider = k;
} }
@ -5817,14 +5950,20 @@ impl App {
ui.label(RichText::new(k.label()).strong().family(crate::bold()).size(FONT_H3)); ui.label(RichText::new(k.label()).strong().family(crate::bold()).size(FONT_H3));
hint(ui, k.key_help(), p); hint(ui, k.key_help(), p);
ui.add_space(6.0); ui.add_space(6.0);
// ChatGPT 方案: an account instead of a key, and only OpenAI's own address.
if k == ProviderKind::ChatGpt {
self.chatgpt_account_ui(ui, p);
}
let ps = self.state.provider_mut(k); let ps = self.state.provider_mut(k);
let mut changed = false; let mut changed = false;
if k.needs_key() || k == ProviderKind::Custom { if (k.needs_key() || k == ProviderKind::Custom) && k != ProviderKind::ChatGpt {
field_label(ui, "API 金鑰", p); 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(); 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 {
field_label(ui, "服務網址", p); field_label(ui, "服務網址", p);
changed |= ui.add(egui::TextEdit::singleline(&mut ps.base_url).hint_text(k.default_base_url()).desired_width(w)).changed(); changed |= ui.add(egui::TextEdit::singleline(&mut ps.base_url).hint_text(k.default_base_url()).desired_width(w)).changed();
}
field_label(ui, "新 Bot 預設模型", p); field_label(ui, "新 Bot 預設模型", p);
changed |= ui.add(egui::TextEdit::singleline(&mut ps.default_model).hint_text(k.suggested_model()).desired_width(w)).changed(); changed |= ui.add(egui::TextEdit::singleline(&mut ps.default_model).hint_text(k.suggested_model()).desired_width(w)).changed();
// 看圖小幫手 for a local or LAN model: off, its pictures never leave. // 看圖小幫手 for a local or LAN model: off, its pictures never leave.
@ -7275,6 +7414,7 @@ fn short_provider(k: ProviderKind) -> &'static str {
match k { match k {
ProviderKind::Xai => "Grok", ProviderKind::Xai => "Grok",
ProviderKind::OpenAi => "OpenAI", ProviderKind::OpenAi => "OpenAI",
ProviderKind::ChatGpt => "ChatGPT 方案",
ProviderKind::Anthropic => "Claude", ProviderKind::Anthropic => "Claude",
ProviderKind::Gemini => "Gemini", ProviderKind::Gemini => "Gemini",
ProviderKind::OpenRouter => "OpenRouter", ProviderKind::OpenRouter => "OpenRouter",

View File

@ -135,6 +135,13 @@ impl App {
} }
self.triggers_poll(ctx); self.triggers_poll(ctx);
self.mcp_poll(ctx); self.mcp_poll(ctx);
// ChatGPT 方案: a sign-in that finished (the first one with the plan gets the welcome).
for r in crate::chatgpt::take_finished() {
self.notice = Some(match r {
Ok(who) => crate::chatgpt::welcome_once().unwrap_or_else(|| format!("已用 ChatGPT({who})登入。")),
Err(e) => format!("ChatGPT 沒有登入成功:{e}"),
});
}
// Microsoft rotates refresh tokens: keep the newest. // Microsoft rotates refresh tokens: keep the newest.
let rotated: Vec<(u64, String)> = crate::teams::rotated().lock().unwrap().iter().map(|(k, v)| (*k, v.clone())).collect(); let rotated: Vec<(u64, String)> = crate::teams::rotated().lock().unwrap().iter().map(|(k, v)| (*k, v.clone())).collect();
for (id, tok) in rotated { for (id, tok) in rotated {

View File

@ -256,7 +256,9 @@ impl App {
/// Another provider the person has set up, for judging a bot's goal: (kind, base url, key, /// Another provider the person has set up, for judging a bot's goal: (kind, base url, key,
/// model). Not a local Ollama model (small ones judge poorly), not the bot's own provider. /// model). Not a local Ollama model (small ones judge poorly), not the bot's own provider.
pub(super) fn judge_elsewhere(&self, own: ProviderKind) -> Option<(ProviderKind, String, String, String)> { pub(super) fn judge_elsewhere(&self, own: ProviderKind) -> Option<(ProviderKind, String, String, String)> {
providers::ALL_PROVIDERS.into_iter().filter(|k| *k != own && *k != ProviderKind::Ollama).find_map(|kind| { // (ChatGPT 方案 last: the person's plan is spent on checks only when nothing else is set up.)
let order = providers::ALL_PROVIDERS.into_iter().filter(|k| *k != ProviderKind::ChatGpt).chain([ProviderKind::ChatGpt]);
order.filter(|k| *k != own && *k != ProviderKind::Ollama).find_map(|kind| {
let ps = self.state.provider(kind); let ps = self.state.provider(kind);
let key = providers::resolve_key_for(kind, &ps.api_key, &ps.base_url); let key = providers::resolve_key_for(kind, &ps.api_key, &ps.base_url);
let usable = if kind == ProviderKind::Custom { !ps.base_url.trim().is_empty() } else { !kind.needs_key() || !key.is_empty() }; let usable = if kind == ProviderKind::Custom { !ps.base_url.trim().is_empty() } else { !kind.needs_key() || !key.is_empty() };

View File

@ -478,7 +478,7 @@ impl App {
// The models a bot can be switched to from the phone: each provider that is ready. // The models a bot can be switched to from the phone: each provider that is ready.
view.models = crate::providers::ALL_PROVIDERS view.models = crate::providers::ALL_PROVIDERS
.iter() .iter()
.filter(|&&k| !k.needs_key() || !crate::providers::resolve_key(k, &self.state.provider(k).api_key).is_empty()) .filter(|&&k| crate::providers::ready(k, &self.state.provider(k).api_key))
// Only models that chat: an image or video generator picked for a bot would break it. // Only models that chat: an image or video generator picked for a bot would break it.
.map(|&k| json!({"provider": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "models": self.models_for(k).into_iter().filter(|m| chats(m)).collect::<Vec<_>>()})) .map(|&k| json!({"provider": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "models": self.models_for(k).into_iter().filter(|m| chats(m)).collect::<Vec<_>>()}))
.collect(); .collect();
@ -1777,8 +1777,9 @@ impl App {
"auto_review": st.auto_review, "allow_rules": st.review_allow_rules, "ask_rules": st.review_ask_rules, "auto_review": st.auto_review, "allow_rules": st.review_allow_rules, "ask_rules": st.review_ask_rules,
"providers": crate::providers::ALL_PROVIDERS.iter().map(|&k| { "providers": crate::providers::ALL_PROVIDERS.iter().map(|&k| {
let ps = st.provider(k); let ps = st.provider(k);
json!({"key": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "needs_key": k.needs_key(), // (ChatGPT 方案 signs in with an account, not a key: `account`.)
"ready": !k.needs_key() || !crate::providers::resolve_key(k, &ps.api_key).is_empty(), json!({"key": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "needs_key": k.needs_key() && k != crate::providers::ProviderKind::ChatGpt, "account": k == crate::providers::ProviderKind::ChatGpt,
"ready": crate::providers::ready(k, &ps.api_key),
"default_model": ps.default_model, "custom_url": !ps.base_url.is_empty()}) "default_model": ps.default_model, "custom_url": !ps.base_url.is_empty()})
}).collect::<Vec<_>>(), }).collect::<Vec<_>>(),
"skills": st.skills.iter().map(|k| json!({ "skills": st.skills.iter().map(|k| json!({

View File

@ -7,7 +7,7 @@ use super::*;
impl App { impl App {
/// The first AI service that is ready to answer (has its key). /// The first AI service that is ready to answer (has its key).
pub(super) fn ready_provider(&self) -> Option<ProviderKind> { pub(super) fn ready_provider(&self) -> Option<ProviderKind> {
ALL_PROVIDERS.iter().copied().find(|k| k.needs_key() && !providers::resolve_key(*k, &self.state.provider(*k).api_key).is_empty()) ALL_PROVIDERS.iter().copied().find(|k| k.needs_key() && providers::ready(*k, &self.state.provider(*k).api_key))
} }
pub(super) fn welcome(&mut self, ui: &mut egui::Ui) { pub(super) fn welcome(&mut self, ui: &mut egui::Ui) {

View File

@ -9,7 +9,7 @@ use crate::model::{self, Bot, Message, State, Theme, Accent};
use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::providers::{ProviderKind, ALL_PROVIDERS};
use crate::routines::{self, Routine, Schedule}; use crate::routines::{self, Routine, Schedule};
pub const NAMES: [&str; 30] = [ pub const NAMES: [&str; 31] = [
"list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now", "list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now",
"list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings", "list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings",
// 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs); // 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs);
@ -25,6 +25,8 @@ pub const NAMES: [&str; 30] = [
crate::mcp::MANAGE_TOOL, crate::mcp::MANAGE_TOOL,
// Hooks: list, add and remove the person's (asked every time, even with 一律放行). // Hooks: list, add and remove the person's (asked every time, even with 一律放行).
crate::hooks::MANAGE_TOOL, crate::hooks::MANAGE_TOOL,
// ChatGPT 方案: sign in with ChatGPT (the address for the person), out, how it stands.
crate::chatgpt::TOOL,
]; ];
pub fn is_app_tool(name: &str) -> bool { pub fn is_app_tool(name: &str) -> bool {
@ -36,6 +38,7 @@ pub fn label(name: &str) -> &'static str {
"list_routines" => "查看例行任務", "list_routines" => "查看例行任務",
crate::mcp::MANAGE_TOOL => "管理連接器", crate::mcp::MANAGE_TOOL => "管理連接器",
crate::hooks::MANAGE_TOOL => "管理 hook", crate::hooks::MANAGE_TOOL => "管理 hook",
crate::chatgpt::TOOL => "ChatGPT 方案登入",
"create_routine" => "建立例行任務", "create_routine" => "建立例行任務",
"update_routine" => "修改例行任務", "update_routine" => "修改例行任務",
"delete_routine" => "刪除例行任務", "delete_routine" => "刪除例行任務",
@ -163,6 +166,7 @@ pub fn specs() -> Vec<Value> {
"theme": {"type": "string", "enum": ["light", "dark", "system"]}, "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}), "theme": {"type": "string", "enum": ["light", "dark", "system"]}, "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}),
crate::mcp::manage_spec(), crate::mcp::manage_spec(),
crate::hooks::manage_spec(), crate::hooks::manage_spec(),
crate::chatgpt::spec(),
] ]
.into_iter() .into_iter()
.chain(crate::pages::specs()) .chain(crate::pages::specs())
@ -182,6 +186,7 @@ pub fn describe(name: &str, args: &str) -> String {
"delete_routine" | "run_routine_now" => format!("#{}", v.get("id").and_then(Value::as_u64).unwrap_or(0)), "delete_routine" | "run_routine_now" => format!("#{}", v.get("id").and_then(Value::as_u64).unwrap_or(0)),
crate::mcp::MANAGE_TOOL => format!("{} {}", s("action"), s("name")).trim().to_string(), crate::mcp::MANAGE_TOOL => format!("{} {}", s("action"), s("name")).trim().to_string(),
crate::hooks::MANAGE_TOOL => format!("{} {}", s("action"), s("event")).trim().to_string(), crate::hooks::MANAGE_TOOL => format!("{} {}", s("action"), s("event")).trim().to_string(),
crate::chatgpt::TOOL => crate::chatgpt::describe(args),
"message_bot" => format!("給 {}:{}", s("bot"), s("text").chars().take(40).collect::<String>()), "message_bot" => format!("給 {}:{}", s("bot"), s("text").chars().take(40).collect::<String>()),
"ask_bot" => format!("問 {}:{}", s("bot"), s("question").chars().take(40).collect::<String>()), "ask_bot" => format!("問 {}:{}", s("bot"), s("question").chars().take(40).collect::<String>()),
"teach_skill" => format!("「{}」給 {}", s("skill"), s("bot")), "teach_skill" => format!("「{}」給 {}", s("skill"), s("bot")),
@ -202,6 +207,14 @@ pub fn describe(name: &str, args: &str) -> String {
/// "這會刪除例行任務並停止其後續執行。此操作無法復原。", VAgxC4). /// "這會刪除例行任務並停止其後續執行。此操作無法復原。", VAgxC4).
pub fn needs_approval(name: &str, args: &str, state: &State) -> Option<String> { pub fn needs_approval(name: &str, args: &str, state: &State) -> Option<String> {
let v: Value = serde_json::from_str(args).unwrap_or(Value::Null); let v: Value = serde_json::from_str(args).unwrap_or(Value::Null);
// ChatGPT 方案: signing out (and forgetting the account) stops every bot on the plan.
if name == crate::chatgpt::TOOL {
return match v["action"].as_str().unwrap_or("") {
"logout" => Some("登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。".into()),
"switch_account" => Some("換 ChatGPT 帳號:登出,並忘記這個帳號在 AnyBot 的註冊(之後要重新登入)。".into()),
_ => None,
};
}
if name == "delete_routine" { if name == "delete_routine" {
let id = v.get("id").and_then(Value::as_u64).unwrap_or(0); let id = v.get("id").and_then(Value::as_u64).unwrap_or(0);
let title = state.bots.iter().flat_map(|b| b.routines.iter()).find(|r| r.id == id).map(|r| r.title.clone()).unwrap_or_else(|| format!("#{id}")); let title = state.bots.iter().flat_map(|b| b.routines.iter()).find(|r| r.id == id).map(|r| r.title.clone()).unwrap_or_else(|| format!("#{id}"));
@ -997,6 +1010,10 @@ mod tests {
assert!(needs_approval("update_bot", r#"{"name":"小幫手"}"#, &st).unwrap().contains("修改 Bot 自己")); assert!(needs_approval("update_bot", r#"{"name":"小幫手"}"#, &st).unwrap().contains("修改 Bot 自己"));
// Nothing to change: nothing to ask. // Nothing to change: nothing to ask.
assert!(needs_approval("update_bot", r#"{"bot":""}"#, &st).is_none()); assert!(needs_approval("update_bot", r#"{"bot":""}"#, &st).is_none());
// ChatGPT 方案: signing out is asked; looking and signing in aren't.
assert!(needs_approval(crate::chatgpt::TOOL, r#"{"action":"logout"}"#, &st).unwrap().contains("登出 ChatGPT"));
assert!(needs_approval(crate::chatgpt::TOOL, r#"{"action":"switch_account"}"#, &st).is_some());
assert!(needs_approval(crate::chatgpt::TOOL, r#"{"action":"login"}"#, &st).is_none());
} }
#[test] #[test]

1211
src/chatgpt.rs Normal file

File diff suppressed because it is too large Load Diff

17
src/chatgpt_test_key.b64 Normal file
View File

@ -0,0 +1,17 @@
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCvGwftl3LY57l2m3CYdTjUDjabzVn6VrrkqNXxzxwiOcAjy7ro
FnHjdQMs9XLZ3XjdM4L2LdNu9N7NpjAdEgLXlpw7LO3RpihQxz4Suko/o3ecoqzSNaRDnnx/VnUknkGTeacmKGwJ2Bq84UtNHhHN
EYGGSmqW8pJhBd30luO4hHmaNVe7G768q73xqcnXESqDomMRLUuZ2naD7vcbFWHaqEEqpuHBOjFmn33eQxf5h9EVqOqEaAjyXZYp
+BpusKmf6dtFynHvyXsDle4g3d48yu9cuvcZuocr0kxopvkeiGh/c6zjfwjiScZi+4eRWc7BMo6ThmQzMy/djLuBdjAbAgMBAAEC
ggEBAIJ/uLbfKd5xRA0a5x0YL5QKS7RtpGMng/2pvliKK8NuGr4StWcGYzZLHGTDQCcSIWNpYm6p1Gta3zmQY0cnBys4uZJ4d3zJ
Qj6BXseCQpeO8jOwIPBAvf0O/mXAP2lc8C5Cecm8Ulg70CF4HjCI+mdEZq14hFueyGy6fKIuWeRGynIVlUiBINSEL1oCUcKXwWfZ
gRlTmaFeuWiE9U6xPndaRk4ixMNQ5YQJP0aAV2K7D9Cj4iSpoNC0Q9cgoPo0opxThKhvul+gE+9DvsXUcwL21AwJPggvNTd/upav
FV39pPMBn4Adw4PwngRDcvi+QitSTVFt1V6PlOC0ZDU9CtECgYEA37LiywbB2ZsQR8ORF+hYSAwM0MyJrVa7x+F/7Y+yi6YlLDSq
TALG8wkVCDqpFHQocc6S1Fjx8xs8GlKQGwcheZjcTVc1GQSGor0lJl3lv38lwePE+tWWCRZy8Cb6g8lCwsUBIIc+XQYgE+YXLv1Z
4vSlzbwvyhcrx5bhqhMzlg0CgYEAyGPg83d8aGi0529dLiYQN3lcj59CVT6ZlAXO/2DFS6FPFs2/hJ1Y6r/1rld893Bvo3rviY0G
lSxG2h3DozmdhhYNmgeCaUPZRmkj5j9sxJ+XiMM0IzEWvgOm0i+HmcFQEqQYXL0LQ3P7+2bGrwoCJi4JhsdIej1hUjKjtFMXvMcC
gYEA3f0bavbNsDBdO5orhlogIX8zyJDxn36O4pA473rGaCb8hJ3O0Zd/7vZ4VK5B0/ZhnG6u7uNFV0cToduE/g1Zft3e4TFFlAoV
wbGKCETuFdcLlRl/BJyoQ2Rvszo7KES1Z6swryMHFDFb6+NN5mesp7i4QS4bDqVn4K0uTCS58JECgYEApX1uqkKUOHm4ZKUgs9r1
a4rLeUTR+CpBlPATGe5mIWZvNWrnbnKvmva6w6c26fYuDDmbluIjfJBbVwhbp/IN+E1AIGNxPNOunSp5Xk4k2mDeOTDUXvfMS1Ii
s9RSzRTLtwlToUryAVvIzr76+FVwnu1IKslrPqBwPfzaGzLAGMMCgYA9Sti0lWNuykefyt0tcq9ApHWhrYX66MaLjpQqIJBjy2EI
5w7O28WFiQ7vY3qGXDL3PdWuIuZwlDhp5yoNONCBuX0C0qQ67Hx/KaUz6G6n+9IvBKFCqAjelppJv6O3tQRn7sbeT5U+kH2ZYZBh
fRspxPT7S5CRmUvjEYl4eCRl0Q==

View File

@ -728,4 +728,19 @@ pub const ROWS: &[(&str, &str, &str)] = &[
("手機已下載", "Downloaded on the phone", "スマホでダウンロード済み"), ("手機已下載", "Downloaded on the phone", "スマホでダウンロード済み"),
("沒有送達", "Not delivered", "届きませんでした"), ("沒有送達", "Not delivered", "届きませんでした"),
("不知道原因", "unknown reason", "原因不明"), ("不知道原因", "unknown reason", "原因不明"),
// ChatGPT 方案 (設定 › 模型)
("ChatGPT 方案", "ChatGPT plan", "ChatGPT プラン"),
("ChatGPT 帳號", "ChatGPT account", "ChatGPT アカウント"),
("使用 ChatGPT 繼續", "Continue with ChatGPT", "ChatGPT で続ける"),
("在瀏覽器登入你的 ChatGPT 帳號,並同意讓 AnyBot 使用你的 ChatGPT 方案", "Sign in to your ChatGPT account in the browser and let AnyBot use your ChatGPT plan", "ブラウザで ChatGPT アカウントにログインし、AnyBot に ChatGPT プランの利用を許可します"),
("撤銷 AnyBot 使用這個 ChatGPT 帳號的權限", "Revoke AnyBot's access to this ChatGPT account", "この ChatGPT アカウントへの AnyBot のアクセスを取り消します"),
("換帳號", "Switch account", "アカウントを切り替え"),
("登出並忘記這個帳號,下次用另一個 ChatGPT 帳號登入", "Sign out and forget this account, to sign in with another ChatGPT account", "ログアウトしてこのアカウントを忘れ、別の ChatGPT アカウントでログインします"),
("打開登入頁", "Open the sign-in page", "ログインページを開く"),
("管理用量", "Manage usage", "使用量を管理"),
("用 ChatGPT 登入", "Sign in with ChatGPT", "ChatGPT でログイン"),
("還沒用 ChatGPT 登入", "Not signed in with ChatGPT yet", "まだ ChatGPT でログインしていません"),
("未登入", "not signed in", "未ログイン"),
("已可使用", "Ready", "利用できます"),
("還沒設定金鑰", "No key yet", "キー未設定"),
]; ];

View File

@ -43,6 +43,7 @@ mod macapps;
mod marks; mod marks;
mod mcp; mod mcp;
mod mcp_oauth; mod mcp_oauth;
mod chatgpt;
mod memory; mod memory;
mod memstore; mod memstore;
mod mention; mod mention;

View File

@ -59,7 +59,7 @@ fn read_all() -> HashMap<String, Tokens> {
if let Some(o) = v.as_object_mut() { if let Some(o) = v.as_object_mut() {
for t in o.values_mut() { for t in o.values_mut() {
for k in ["access", "refresh", "client_secret"] { for k in ["access", "refresh", "client_secret"] {
if let Some(s) = t[k].as_str().filter(|s| s.starts_with("sealed:")).map(String::from) { if let Some(s) = t[k].as_str().filter(|s| s.starts_with(crate::vault_store::SEALED)).map(String::from) {
// (One that can't be opened now — the keychain is locked — stays sealed: // (One that can't be opened now — the keychain is locked — stays sealed:
// it isn't used, and saving another connector's doesn't empty it.) // it isn't used, and saving another connector's doesn't empty it.)
if let Some(plain) = crate::vault_store::open_text(&s) { if let Some(plain) = crate::vault_store::open_text(&s) {
@ -100,7 +100,7 @@ fn write_all(all: &HashMap<String, Tokens>) -> Result<(), String> {
/// This connector's tokens, if it is logged in. /// This connector's tokens, if it is logged in.
pub fn tokens(server: &str) -> Option<Tokens> { pub fn tokens(server: &str) -> Option<Tokens> {
let _g = store().lock().unwrap_or_else(|e| e.into_inner()); let _g = store().lock().unwrap_or_else(|e| e.into_inner());
read_all().remove(server).filter(|t| !t.access.is_empty() && !t.access.starts_with("sealed:")) read_all().remove(server).filter(|t| !t.access.is_empty() && !t.access.starts_with(crate::vault_store::SEALED))
} }
fn save(server: &str, t: Option<Tokens>) -> Result<(), String> { fn save(server: &str, t: Option<Tokens>) -> Result<(), String> {
@ -597,6 +597,24 @@ pub mod tests {
assert_eq!(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWwjXk"), "qBDSUaImE-WxTq4xZVKSKIi4bDy4teecLEwvWS_LsfQ"); assert_eq!(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWwjXk"), "qBDSUaImE-WxTq4xZVKSKIi4bDy4teecLEwvWS_LsfQ");
} }
/// A token still sealed (its key can't be opened now) is not a token: never sent as one
/// (the sealed text used to go out as the bearer, and its refresh token to the server).
#[test]
fn a_token_that_could_not_be_opened_is_not_sent() {
let name = format!("oauth-sealed-{}", crate::httpd::random_hex(4));
let sealed = format!("{}00ff", crate::vault_store::SEALED);
save(&name, Some(Tokens { access: "plain".into(), url: "https://x.example/mcp".into(), ..Default::default() })).unwrap();
{
let _g = store().lock().unwrap_or_else(|e| e.into_inner());
let mut v: Value = serde_json::from_str(&std::fs::read_to_string(file()).unwrap()).unwrap();
v[&name]["access"] = json!(sealed);
std::fs::write(file(), v.to_string()).unwrap();
}
assert!(tokens(&name).is_none());
assert!(bearer(&name, "https://x.example/mcp").is_none());
let _ = logout(&name);
}
/// Against a test OAuth server: the login address is right, the browser's way back is caught, /// Against a test OAuth server: the login address is right, the browser's way back is caught,
/// the code becomes tokens (PKCE checked by the server), and a token near its end is renewed. /// the code becomes tokens (PKCE checked by the server), and a token near its end is renewed.
#[test] #[test]

View File

@ -43,7 +43,7 @@ pub fn ability_of(tool: &str) -> Option<&'static str> {
"create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" => "routines", "create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" => "routines",
"write_page" | "read_page" | "list_pages" => "pages", "write_page" | "read_page" | "list_pages" => "pages",
"message_bot" | "ask_bot" | "teach_skill" | "list_bots" => "team", "message_bot" | "ask_bot" | "teach_skill" | "list_bots" => "team",
"create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" | crate::mcp::MANAGE_TOOL | crate::hooks::MANAGE_TOOL => "admin", "create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" | crate::mcp::MANAGE_TOOL | crate::hooks::MANAGE_TOOL | crate::chatgpt::TOOL => "admin",
_ => return None, _ => return None,
}) })
} }

View File

@ -15,6 +15,8 @@ use crate::model::{Message, Role, ToolCall, ToolStatus};
pub enum ProviderKind { pub enum ProviderKind {
Xai, Xai,
OpenAi, OpenAi,
/// ChatGPT 方案: the person's ChatGPT plan, signed in with ChatGPT instead of a key (chatgpt.rs).
ChatGpt,
Anthropic, Anthropic,
Gemini, Gemini,
OpenRouter, OpenRouter,
@ -23,9 +25,10 @@ pub enum ProviderKind {
Custom, Custom,
} }
pub const ALL_PROVIDERS: [ProviderKind; 8] = [ pub const ALL_PROVIDERS: [ProviderKind; 9] = [
ProviderKind::Xai, ProviderKind::Xai,
ProviderKind::OpenAi, ProviderKind::OpenAi,
ProviderKind::ChatGpt,
ProviderKind::Anthropic, ProviderKind::Anthropic,
ProviderKind::Gemini, ProviderKind::Gemini,
ProviderKind::OpenRouter, ProviderKind::OpenRouter,
@ -60,6 +63,7 @@ impl ProviderKind {
match self { match self {
ProviderKind::Xai => "xai", ProviderKind::Xai => "xai",
ProviderKind::OpenAi => "openai", ProviderKind::OpenAi => "openai",
ProviderKind::ChatGpt => "chatgpt",
ProviderKind::Anthropic => "anthropic", ProviderKind::Anthropic => "anthropic",
ProviderKind::Gemini => "gemini", ProviderKind::Gemini => "gemini",
ProviderKind::OpenRouter => "openrouter", ProviderKind::OpenRouter => "openrouter",
@ -73,6 +77,7 @@ impl ProviderKind {
match self { match self {
ProviderKind::Xai => "xAI Grok", ProviderKind::Xai => "xAI Grok",
ProviderKind::OpenAi => "OpenAI", ProviderKind::OpenAi => "OpenAI",
ProviderKind::ChatGpt => "ChatGPT 方案",
ProviderKind::Anthropic => "Claude", ProviderKind::Anthropic => "Claude",
ProviderKind::Gemini => "Google Gemini", ProviderKind::Gemini => "Google Gemini",
ProviderKind::OpenRouter => "OpenRouter", ProviderKind::OpenRouter => "OpenRouter",
@ -86,6 +91,7 @@ impl ProviderKind {
match self { match self {
ProviderKind::Xai => "https://api.x.ai/v1", ProviderKind::Xai => "https://api.x.ai/v1",
ProviderKind::OpenAi => "https://api.openai.com/v1", ProviderKind::OpenAi => "https://api.openai.com/v1",
ProviderKind::ChatGpt => crate::chatgpt::API_BASE,
ProviderKind::Anthropic => "https://api.anthropic.com/v1", ProviderKind::Anthropic => "https://api.anthropic.com/v1",
ProviderKind::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai", ProviderKind::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai",
ProviderKind::OpenRouter => "https://openrouter.ai/api/v1", ProviderKind::OpenRouter => "https://openrouter.ai/api/v1",
@ -100,6 +106,8 @@ impl ProviderKind {
match self { match self {
ProviderKind::Xai => "grok-4", ProviderKind::Xai => "grok-4",
ProviderKind::OpenAi => "gpt-5", ProviderKind::OpenAi => "gpt-5",
// (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::Anthropic => "claude-opus-5-5",
ProviderKind::Gemini => "gemini-2.5-flash", ProviderKind::Gemini => "gemini-2.5-flash",
ProviderKind::OpenRouter => "openrouter/auto", ProviderKind::OpenRouter => "openrouter/auto",
@ -128,6 +136,7 @@ impl ProviderKind {
match self { match self {
ProviderKind::Xai => &["grok-4", "grok-4-fast", "grok-3-mini"], ProviderKind::Xai => &["grok-4", "grok-4-fast", "grok-3-mini"],
ProviderKind::OpenAi => &["gpt-5", "gpt-5-mini", "gpt-4.1"], 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::Anthropic => &["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-1"],
ProviderKind::Gemini => &["gemini-2.5-flash", "gemini-2.5-pro"], ProviderKind::Gemini => &["gemini-2.5-flash", "gemini-2.5-pro"],
ProviderKind::OpenRouter => &["openrouter/auto"], ProviderKind::OpenRouter => &["openrouter/auto"],
@ -157,6 +166,7 @@ impl ProviderKind {
match self { match self {
ProviderKind::Xai => "在 console.x.ai 取得 API 金鑰", ProviderKind::Xai => "在 console.x.ai 取得 API 金鑰",
ProviderKind::OpenAi => "在 platform.openai.com 取得 API 金鑰", ProviderKind::OpenAi => "在 platform.openai.com 取得 API 金鑰",
ProviderKind::ChatGpt => "用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰:用 ChatGPT 帳號登入就好",
ProviderKind::Anthropic => "在 console.anthropic.com 取得 API 金鑰", ProviderKind::Anthropic => "在 console.anthropic.com 取得 API 金鑰",
ProviderKind::Gemini => "在 aistudio.google.com 取得 API 金鑰", ProviderKind::Gemini => "在 aistudio.google.com 取得 API 金鑰",
ProviderKind::OpenRouter => "在 openrouter.ai 取得 API 金鑰", ProviderKind::OpenRouter => "在 openrouter.ai 取得 API 金鑰",
@ -440,6 +450,10 @@ fn agent() -> ureq::Agent {
} }
pub fn resolve_key(kind: ProviderKind, stored: &str) -> String { pub fn resolve_key(kind: ProviderKind, stored: &str) -> String {
// ChatGPT 方案 has no key: the signed-in access token, as kept (renewed when a request is made).
if kind == ProviderKind::ChatGpt {
return crate::chatgpt::stored_token();
}
if !stored.trim().is_empty() { if !stored.trim().is_empty() {
return stored.trim().to_string(); return stored.trim().to_string();
} }
@ -453,6 +467,9 @@ pub fn resolve_key(kind: ProviderKind, stored: &str) -> String {
/// address. (Pointing a provider at another address — a screen's edit, a mistaken setting — /// address. (Pointing a provider at another address — a screen's edit, a mistaken setting —
/// used to send the server's environment key there.) /// used to send the server's environment key there.)
pub fn resolve_key_for(kind: ProviderKind, stored: &str, stored_base: &str) -> String { pub fn resolve_key_for(kind: ProviderKind, stored: &str, stored_base: &str) -> String {
if kind == ProviderKind::ChatGpt {
return resolve_key(kind, stored);
}
if !stored.trim().is_empty() { if !stored.trim().is_empty() {
return stored.trim().to_string(); return stored.trim().to_string();
} }
@ -463,6 +480,16 @@ pub fn resolve_key_for(kind: ProviderKind, stored: &str, stored_base: &str) -> S
resolve_key(kind, stored) resolve_key(kind, stored)
} }
/// The provider can answer: its key is there (from the settings or the environment), it needs
/// none, or — ChatGPT 方案 — the account is signed in with the plan allowed (here or, on a
/// screen, on the brain).
pub fn ready(kind: ProviderKind, stored_key: &str) -> bool {
match kind {
ProviderKind::ChatGpt => crate::chatgpt::usable(),
_ => !kind.needs_key() || !resolve_key(kind, stored_key).is_empty(),
}
}
pub fn resolve_base(kind: ProviderKind, stored: &str) -> String { pub fn resolve_base(kind: ProviderKind, stored: &str) -> String {
let b = if stored.trim().is_empty() { kind.default_base_url() } else { stored.trim() }; let b = if stored.trim().is_empty() { kind.default_base_url() } else { stored.trim() };
b.trim_end_matches('/').to_string() b.trim_end_matches('/').to_string()
@ -742,6 +769,9 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea
}; };
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
let req = &localized; let req = &localized;
if req.kind == ProviderKind::ChatGpt && req.api_key.is_empty() {
return Err(crate::chatgpt::why_not_ready().into());
}
if req.kind.needs_key() && req.api_key.is_empty() { if req.kind.needs_key() && req.api_key.is_empty() {
return Err(format!("還沒有設定 {} 的 API 金鑰。請到「設定 → 模型」貼上金鑰。", req.kind.label())); return Err(format!("還沒有設定 {} 的 API 金鑰。請到「設定 → 模型」貼上金鑰。", req.kind.label()));
} }
@ -768,6 +798,7 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea
let req = blind_copy.as_ref().unwrap_or(req); let req = blind_copy.as_ref().unwrap_or(req);
let result = match req.kind { let result = match req.kind {
ProviderKind::Anthropic => stream_anthropic(req, cancel, &tracked), ProviderKind::Anthropic => stream_anthropic(req, cancel, &tracked),
ProviderKind::ChatGpt => stream_responses(req, cancel, &tracked),
ProviderKind::OpenCodeGo => { ProviderKind::OpenCodeGo => {
let mut r = req.clone(); let mut r = req.clone();
if opencode_go_style(&req.base_url, &req.model) == "messages" { if opencode_go_style(&req.base_url, &req.model) == "messages" {
@ -1382,6 +1413,254 @@ fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBo
Ok(out) Ok(out)
} }
// ---------- ChatGPT 方案: the Responses API on the person's plan ----------
/// The chat as Responses API input items (the system prompt goes in `instructions`: the plan's
/// route refuses system items). Built from the chat-completions shape, so both read the history
/// the same way (pictures kept, older screenshots noted, each result after its call).
pub fn responses_input(req: &ChatRequest) -> Vec<Value> {
let parts = |c: &Value| -> Value {
match c {
Value::String(s) => json!([{"type": "input_text", "text": s}]),
Value::Array(a) => json!(a
.iter()
.filter_map(|p| match p["type"].as_str() {
Some("text") => Some(json!({"type": "input_text", "text": p["text"]})),
Some("image_url") => Some(json!({"type": "input_image", "image_url": p["image_url"]["url"]})),
_ => None,
})
.collect::<Vec<_>>()),
_ => json!([]),
}
};
let mut items = vec![];
for m in openai_messages(req) {
match m["role"].as_str().unwrap_or("") {
"user" => items.push(json!({"role": "user", "content": parts(&m["content"])})),
"assistant" => {
if let Some(t) = m["content"].as_str().filter(|t| !t.is_empty()) {
items.push(json!({"role": "assistant", "content": t}));
}
for c in m["tool_calls"].as_array().into_iter().flatten() {
items.push(json!({"type": "function_call", "call_id": c["id"], "name": c["function"]["name"], "arguments": c["function"]["arguments"]}));
}
}
"tool" => items.push(json!({"type": "function_call_output", "call_id": m["tool_call_id"], "output": m["content"].as_str().unwrap_or("")})),
// (system: sent as `instructions`)
_ => {}
}
}
items
}
impl Usage {
/// A Responses API `usage` object (cached input taken out of `input`, like OpenAI's other one).
pub fn of_responses(u: &Value) -> Usage {
let g = |v: &Value| v.as_u64().unwrap_or(0);
let cached = g(&u["input_tokens_details"]["cached_tokens"]);
Usage { input: g(&u["input_tokens"]).saturating_sub(cached), output: g(&u["output_tokens"]), cache_read: cached, ..Default::default() }
}
}
/// The plan's own refusals (developers.openai.com/siwc/token-sharing-open-source/errors-and-recovery),
/// in words; None for anything else. A usage limit stops the request: it is never moved to
/// another way of paying, and not asked again by itself.
fn plan_failure(e: &Value, retry_after: Option<u64>) -> Option<Failure> {
let code = e["code"].as_str().unwrap_or("");
let said = e["message"].as_str().unwrap_or("");
let param = e["param"].as_str().unwrap_or("");
Some(match code {
"subscription_sharing_usage_limit_exceeded" => Failure::fatal(format!(
"已達用量上限(ChatGPT 方案):你的 ChatGPT 方案,或你給 AnyBot 的上限,這段時間用完了。到 ChatGPT 設定的「用量」查看或調整(管理用量:{})。",
crate::chatgpt::USAGE_URL
)),
"subscription_sharing_usage_unavailable" | "subscription_sharing_user_unavailable" => {
Failure { msg: "ChatGPT 方案暫時沒辦法用,等一下再試。".into(), retryable: true, retry_after_ms: Some(retry_after.unwrap_or(BUSY_RETRY_MS)) }
}
"subscription_sharing_user_not_eligible" => Failure::fatal(format!("這個 ChatGPT 帳號(或它的工作區)不能用方案的額度跑 AnyBot。可以改用 OpenAI 的 API 金鑰。\n({said})")),
"subscription_sharing_unsupported_capability" => Failure::fatal(format!("ChatGPT 方案不支援這個要求裡的「{param}」:換一個模型,或關掉這個 Bot 的這項設定。\n({said})")),
"subscription_sharing_route_not_supported" => Failure::fatal(format!("ChatGPT 方案不接受這種要求(AnyBot 送錯了地方)。\n({said})")),
"subscription_sharing_invalid_user" => Failure::fatal(format!("ChatGPT 的登入不能用了:請重新登入(設定 › 模型 › ChatGPT 方案)。\n({said})")),
c if c.starts_with("chatpass_v2_") => Failure::fatal(format!("ChatGPT 方案不接受這個 AnyBot 的授權:請重新登入(設定 › 模型 › ChatGPT 方案)。\n({said})")),
_ => return None,
})
}
fn plan_http_error(status: u16, body: &str, retry_after: Option<u64>) -> Failure {
let v: Value = serde_json::from_str(body).unwrap_or(Value::Null);
if let Some(f) = plan_failure(&v["error"], retry_after) {
return f;
}
let said = v["error"]["message"].as_str().map(String::from).unwrap_or_else(|| page_words(body).chars().take(300).collect());
match status {
401 => Failure::fatal(format!("ChatGPT 的登入不能用了:請重新登入(設定 › 模型 › ChatGPT 方案)。\n({said})")),
403 => Failure::fatal(format!("ChatGPT 方案不讓這個要求通過(例如你所在的地區不支援,或工作區的設定不允許)。\n({said})")),
503 => Failure { msg: format!("ChatGPT 方案暫時沒辦法用,等一下再試。\n({said})"), retryable: true, retry_after_ms: Some(retry_after.unwrap_or(BUSY_RETRY_MS)) },
_ => http_error(status, body, retry_after),
}
}
fn no_token(e: crate::chatgpt::NoToken) -> Failure {
Failure { msg: e.msg, retryable: e.retry, retry_after_ms: None }
}
/// 思考模式 rides along as `reasoning.effort`; a model that refuses it gets the request again
/// without it (as with the other OpenAI-style services).
fn stream_responses(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
let key = (crate::chatgpt::API_BASE.to_string(), req.model.clone());
let effort = effort_of(req).filter(|_| !effort_refused().lock().unwrap().contains(&key));
match stream_responses_with(req, effort, cancel, send) {
Err(f) if effort.is_some() && refuses_effort(&f) => {
effort_refused().lock().unwrap().insert(key);
stream_responses_with(req, None, cancel, send)
}
r => r,
}
}
fn stream_responses_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
// (The plan's route takes no temperature, output limit, metadata, previous_response_id…:
// only these. Nothing is stored at OpenAI; the whole chat goes every time.)
let mut body = json!({"model": req.model, "input": responses_input(req), "store": false, "stream": true});
let system = system_with_summaries(req);
if !system.trim().is_empty() {
body["instructions"] = json!(system);
}
if let Some(e) = effort {
body["reasoning"] = json!({"effort": e});
}
if !req.tools.is_empty() {
// (Not strict: AnyBot's schemas have optional fields, which strict mode refuses.)
body["tools"] = json!(req.tools.iter().map(|t| json!({"type": "function", "name": t["name"], "description": t["description"], "parameters": t["parameters"], "strict": false})).collect::<Vec<_>>());
}
// Only ever OpenAI's own address, whatever the settings say: the token goes nowhere else.
let url = format!("{}/responses", crate::chatgpt::api_base());
let mut token = crate::chatgpt::fresh_token().map_err(no_token)?;
let mut renewed = false;
let resp = loop {
// SAND-E0418 turnBackendUnreachable: retryable.
let resp = agent()
.post(&url)
.header("Content-Type", "application/json")
.header("Authorization", &format!("Bearer {token}"))
.send_json(&body)
.map_err(|e| Failure::retry(connect_error(req.kind, &e.to_string())))?;
let status = resp.status().as_u16();
// Refused before its time (signed in elsewhere, the clock): renewed once and asked again.
if status == 401 && !renewed {
renewed = true;
token = crate::chatgpt::renew_after(&token).map_err(no_token)?;
continue;
}
if status >= 400 {
let ra = retry_after_ms(&resp);
let text = resp.into_body().read_to_string().unwrap_or_default();
return Err(plan_http_error(status, &text, ra));
}
break resp;
};
let mut out = StepOutput::default();
let mut ended = false;
let mut error: Option<Failure> = None;
read_sse(resp.into_body(), cancel, send, |ev, data| {
let Ok(v) = serde_json::from_str::<Value>(data) else { return true };
let kind = v["type"].as_str().unwrap_or(ev).to_string();
match kind.as_str() {
"response.output_text.delta" => {
let t = v["delta"].as_str().unwrap_or("");
if !t.is_empty() {
out.text.push_str(t);
send(StreamEvent::Text(t.to_string()));
}
}
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => {
let t = v["delta"].as_str().unwrap_or("");
if !t.is_empty() {
out.thinking.push_str(t);
send(StreamEvent::Thinking(t.to_string()));
}
}
"response.reasoning_summary_part.added" if !out.thinking.is_empty() => {
out.thinking.push_str("\n\n");
send(StreamEvent::Thinking("\n\n".into()));
}
"response.output_item.done" if v["item"]["type"] == "function_call" => {
let it = &v["item"];
let args = it["arguments"].as_str().filter(|a| !a.trim().is_empty()).unwrap_or("{}");
let call = ToolCall { id: it["call_id"].as_str().unwrap_or("").into(), name: it["name"].as_str().unwrap_or("").into(), args: args.into(), status: ToolStatus::Waiting };
if !call.name.is_empty() {
send(StreamEvent::ToolCall(call.clone()));
out.tool_calls.push(call);
}
}
"response.completed" | "response.incomplete" => {
if let Some(u) = v["response"].get("usage").filter(|u| u.is_object()) {
out.usage = Usage::of_responses(u);
}
let note = match v["response"]["incomplete_details"]["reason"].as_str() {
Some("max_output_tokens") => "\n\n(回答太長,已達長度上限。)".to_string(),
Some("content_filter") => "\n\n(模型拒絕回答這個要求。)".to_string(),
_ if kind == "response.incomplete" => format!("\n\n(回答沒有完成:{})", v["response"]["incomplete_details"]["reason"].as_str().unwrap_or("沒有說原因")),
_ => String::new(),
};
if !note.is_empty() {
out.text.push_str(&note);
send(StreamEvent::Text(note));
}
ended = true;
return false;
}
"response.failed" | "error" => {
// (response.failed carries it in response.error; an error event carries it itself.)
let e = if kind == "error" { if v["error"].is_object() { v["error"].clone() } else { v.clone() } } else { v["response"]["error"].clone() };
error = Some(plan_failure(&e, None).unwrap_or_else(|| stream_failure(e["message"].as_str().unwrap_or("未知錯誤"))));
return false;
}
_ => {}
}
true
})?;
if let Some(f) = error {
return Err(f);
}
// Only an answer that reached its end counts.
if !ended && !cancel.load(Ordering::Relaxed) {
return Err(Failure::retry("ChatGPT 的回答中途斷了(沒有收到結尾)。".into()));
}
Ok(out)
}
/// The models this ChatGPT plan offers (the ones it lists, by their slug).
fn chatgpt_models() -> Result<Vec<String>, String> {
let token = crate::chatgpt::fresh_token().map_err(|e| e.msg)?;
let url = format!("{}/models", crate::chatgpt::api_base());
let resp = agent().get(&url).header("Authorization", &format!("Bearer {token}")).call().map_err(|e| connect_error(ProviderKind::ChatGpt, &e.to_string()))?;
let status = resp.status().as_u16();
let text = resp.into_body().read_to_string().map_err(|e| e.to_string())?;
if status >= 400 {
return Err(plan_http_error(status, &text, None).msg);
}
let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
// (Only the ones it lists, in its own order.)
let mut ids: Vec<String> = vec![];
for id in v["models"]
.as_array()
.into_iter()
.flatten()
.filter(|m| m["visibility"] == "list")
.filter_map(|m| m["slug"].as_str())
.chain(v["data"].as_array().into_iter().flatten().filter_map(|m| m["id"].as_str()))
{
if !ids.iter().any(|x| x == id) {
ids.push(id.to_string());
}
}
if ids.is_empty() {
return Err("ChatGPT 方案沒有列出任何模型".into());
}
Ok(ids)
}
pub fn anthropic_messages(req: &ChatRequest) -> Vec<Value> { pub fn anthropic_messages(req: &ChatRequest) -> Vec<Value> {
let mut messages: Vec<Value> = vec![]; let mut messages: Vec<Value> = vec![];
let mut push = |role: &str, blocks: Vec<Value>| { let mut push = |role: &str, blocks: Vec<Value>| {
@ -1681,6 +1960,10 @@ fn opencode_session(req: &ChatRequest) -> String {
/// Ask the provider which models it offers. /// Ask the provider which models it offers.
pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result<Vec<String>, String> { pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result<Vec<String>, String> {
// ChatGPT 方案: with the signed-in token, at OpenAI's own address only.
if kind == ProviderKind::ChatGpt {
return chatgpt_models();
}
if kind.needs_key() && api_key.is_empty() { if kind.needs_key() && api_key.is_empty() {
return Err("請先貼上 API 金鑰".into()); return Err("請先貼上 API 金鑰".into());
} }
@ -2267,4 +2550,118 @@ mod tests {
let m = cache_tail(vec![json!({"role": "user", "content": []})]); let m = cache_tail(vec![json!({"role": "user", "content": []})]);
assert!(m[0]["content"].as_array().unwrap().is_empty()); assert!(m[0]["content"].as_array().unwrap().is_empty());
} }
// ---------- ChatGPT 方案 (the Responses API) ----------
fn plan_req(history: Vec<Message>, tools: Vec<Value>) -> ChatRequest {
// (Whatever the settings say, requests go to chatgpt::api_base(): a test points it at its own server.)
ChatRequest { kind: ProviderKind::ChatGpt, base_url: "https://evil.example/v1".into(), api_key: "stale-from-settings".into(), model: "gpt-6.1-sol".into(), system: "你是助手".into(), history, tools, session: String::new(), effort: String::new() }
}
#[test]
fn the_plan_gets_the_chat_as_responses_items() {
let mut asked = Message::assistant("我看一下", "x");
asked.tool_calls = vec![ToolCall { id: "c1".into(), name: "computer_use_screenshot".into(), args: "{}".into(), status: ToolStatus::Done }];
let mut shot = Message::tool_result("c1", "computer_use_screenshot", "拍好了");
shot.images = vec!["SHOT".into()];
let mut photo = Message::user("這是什麼");
photo.images = vec!["PHOTO".into()];
let req = plan_req(vec![photo, Message::assistant("一隻貓", "x"), Message::user("看螢幕"), asked, shot], vec![]);
let items = responses_input(&req);
// No system item (it goes in `instructions`).
assert!(items.iter().all(|i| i["role"] != "system"), "{items:?}");
assert_eq!(items[0]["content"][0], json!({"type": "input_text", "text": "這是什麼"}));
assert_eq!(items[0]["content"][1], json!({"type": "input_image", "image_url": "data:image/jpeg;base64,PHOTO"}));
assert_eq!(items[1], json!({"role": "assistant", "content": "一隻貓"}));
assert_eq!(items[3], json!({"role": "assistant", "content": "我看一下"}));
assert_eq!(items[4], json!({"type": "function_call", "call_id": "c1", "name": "computer_use_screenshot", "arguments": "{}"}));
assert_eq!(items[5], json!({"type": "function_call_output", "call_id": "c1", "output": "拍好了"}));
// The screenshot follows its result, as the person's picture.
assert_eq!(items[6]["role"], "user");
assert_eq!(items[6]["content"][1]["image_url"], "data:image/jpeg;base64,SHOT");
}
#[test]
fn the_plan_streams_words_and_tool_calls_with_its_own_token_and_address() {
use crate::testkit::{Fake, Format, Reply};
let fake = Fake::start(Format::Responses, vec![Reply::text("你好"), Reply::call("call_9", "list_dir", json!({"path": "."}))], None);
let dir = crate::chatgpt::tests::use_test_place("http://127.0.0.1:1");
crate::chatgpt::tests::sign_in_for_test("plan-token", 3_600_000);
crate::chatgpt::tests::use_test_api(Some(fake.base()));
let tools = vec![json!({"name": "list_dir", "description": "List", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}})];
let mut req = plan_req(vec![Message::user("hi")], tools);
req.effort = "high".into();
let cancel = AtomicBool::new(false);
let out = run_step_as_written(&req, &cancel, &|_| {}).unwrap();
assert_eq!(out.text, "你好");
assert_eq!(out.usage, Usage { input: 100, output: 7, cache_read: 20, ..Default::default() });
let raw = fake.raw.lock().unwrap()[0].clone();
assert!(raw.starts_with("POST /v1/responses "), "{raw}");
assert!(raw.to_lowercase().contains("authorization: bearer plan-token"), "{raw}");
let body = fake.bodies.lock().unwrap()[0].clone();
assert_eq!((body["store"].clone(), body["stream"].clone()), (json!(false), json!(true)));
assert_eq!(body["instructions"], "你是助手");
assert_eq!(body["reasoning"]["effort"], "high");
assert_eq!(body["tools"][0], json!({"type": "function", "name": "list_dir", "description": "List", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}, "strict": false}));
// None of what the plan's route refuses.
for k in ["temperature", "max_output_tokens", "previous_response_id", "metadata", "messages", "user"] {
assert!(body.get(k).is_none(), "{k} sent");
}
let out = run_step_as_written(&req, &cancel, &|_| {}).unwrap();
assert_eq!(out.tool_calls.len(), 1);
assert_eq!((out.tool_calls[0].id.as_str(), out.tool_calls[0].name.as_str()), ("call_9", "list_dir"));
assert_eq!(serde_json::from_str::<Value>(&out.tool_calls[0].args).unwrap(), json!({"path": "."}));
crate::chatgpt::tests::use_test_api(None);
crate::chatgpt::tests::leave_test_place(dir);
}
#[test]
fn a_used_up_plan_stops_and_says_where_to_look() {
use crate::testkit::{Fake, Format, Reply};
let failed = format!("event: response.failed\ndata: {}\n\n", json!({"type": "response.failed", "response": {"error": {"code": "subscription_sharing_usage_limit_exceeded", "message": "limit"}}}));
let fake = Fake::start(Format::Responses, vec![Reply::Raw(200, failed)], Some(Reply::text("不該再問")));
let dir = crate::chatgpt::tests::use_test_place("http://127.0.0.1:1");
crate::chatgpt::tests::sign_in_for_test("plan-token", 3_600_000);
crate::chatgpt::tests::use_test_api(Some(fake.base()));
let e = run_step_as_written(&plan_req(vec![Message::user("hi")], vec![]), &AtomicBool::new(false), &|_| {}).unwrap_err();
assert!(e.contains("已達用量上限(ChatGPT 方案)") && e.contains(crate::chatgpt::USAGE_URL), "{e}");
// Asked once: not retried, and never sent anywhere else.
assert_eq!(fake.requests(), 1);
// The same over HTTP; a stream that never reaches its end is not taken as an answer.
assert!(plan_http_error(429, r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded","message":"x"}}"#, None).msg.contains("管理用量"));
assert!(!plan_http_error(429, r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded"}}"#, None).retryable);
assert!(plan_http_error(503, r#"{"error":{"code":"subscription_sharing_usage_unavailable"}}"#, None).retryable);
assert!(plan_http_error(400, r#"{"error":{"code":"subscription_sharing_unsupported_capability","param":"reasoning.effort"}}"#, None).msg.contains("reasoning.effort"));
crate::chatgpt::tests::use_test_api(None);
crate::chatgpt::tests::leave_test_place(dir);
}
#[test]
fn a_refused_token_is_renewed_once_and_a_cut_stream_is_not_an_answer() {
use crate::testkit::{Fake, Format, Reply};
let auth = crate::chatgpt::tests::FakeAuth::start("oaiapp_1", Default::default(), crate::chatgpt::PLAN_SCOPE);
let cut = format!("event: response.output_text.delta\ndata: {}\n\n", json!({"type": "response.output_text.delta", "delta": "說到一半"}));
let fake = Fake::start(Format::Responses, vec![Reply::Fail { status: 401, body: r#"{"error":{"message":"expired"}}"#.into(), retry_after: None }, Reply::text("好了"), Reply::Raw(200, cut)], None);
let dir = crate::chatgpt::tests::use_test_place(&auth.url);
crate::chatgpt::tests::sign_in_for_test("old-token", 3_600_000);
crate::chatgpt::tests::use_test_api(Some(fake.base()));
let req = plan_req(vec![Message::user("hi")], vec![]);
assert_eq!(run_step_as_written(&req, &AtomicBool::new(false), &|_| {}).unwrap().text, "好了");
assert!(fake.raw.lock().unwrap()[1].to_lowercase().contains("authorization: bearer access-1"));
let e = run_step_as_written(&req, &AtomicBool::new(false), &|_| {}).unwrap_err();
assert!(e.contains("中途斷了"), "{e}");
crate::chatgpt::tests::use_test_api(None);
crate::chatgpt::tests::leave_test_place(dir);
}
#[test]
fn without_a_sign_in_the_plan_says_how_to_sign_in() {
let dir = crate::chatgpt::tests::use_test_place("http://127.0.0.1:1");
assert!(resolve_key(ProviderKind::ChatGpt, "sk-typed-in-settings").is_empty());
let mut req = plan_req(vec![Message::user("hi")], vec![]);
req.api_key = String::new();
let e = run_step_as_written(&req, &AtomicBool::new(false), &|_| {}).unwrap_err();
assert_eq!(e, crate::chatgpt::NEED_LOGIN);
crate::chatgpt::tests::leave_test_place(dir);
}
} }

View File

@ -685,6 +685,13 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
if !via_relay && loosens_guard(action, &body) { if !via_relay && loosens_guard(action, &body) {
return Resp::error(403, "這項設定會讓 Bot 不用問就動手,不能從區網連線(沒有加密)打開:請在電腦上的 AnyBot 改,或用帳號連線。"); return Resp::error(403, "這項設定會讓 Bot 不用問就動手,不能從區網連線(沒有加密)打開:請在電腦上的 AnyBot 改,或用帳號連線。");
} }
// ChatGPT 方案 from the phone: the owner's; over the network, so not on the app's thread.
if *action == "chatgpt" {
if role != "owner" {
return Resp::error(403, "只有擁有者能登入或登出 ChatGPT");
}
return Resp::json(&crate::chatgpt::for_screen(&body));
}
phone_act(action, body, &role) phone_act(action, body, &role)
} }
// 記憶: the memory page and the composer's suggestions — the owner's (a screen of the // 記憶: the memory page and the composer's suggestions — the owner's (a screen of the
@ -827,6 +834,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
_ => Resp::error(400, "不認得的操作"), _ => Resp::error(400, "不認得的操作"),
} }
} }
// ChatGPT 方案 from a screen: the account lives here (signing in, out, how it stands).
("POST", ["api", "sync", "chatgpt"]) => Resp::json(&crate::chatgpt::for_screen(&req.json())),
("POST", ["api", "sync", "models"]) => match hub().ask_sync_for(SyncKind::Models(req.json()["provider"].as_str().unwrap_or("").to_string()), 45) { ("POST", ["api", "sync", "models"]) => match hub().ask_sync_for(SyncKind::Models(req.json()["provider"].as_str().unwrap_or("").to_string()), 45) {
Ok(v) => Resp::json(&v), Ok(v) => Resp::json(&v),
Err(e) => Resp::error(503, &e), Err(e) => Resp::error(503, &e),
@ -2502,6 +2511,20 @@ mod tests {
Req { method: "POST".into(), path: path.into(), query, headers, body: body.to_vec(), peer: String::new() } Req { method: "POST".into(), path: path.into(), query, headers, body: body.to_vec(), peer: String::new() }
} }
/// ChatGPT 方案: only the owner (the phone) and the owner's screens sign this brain in or out.
#[test]
fn only_the_owner_signs_the_brain_in_to_chatgpt() {
for role in ["admin", "member", "device", "none"] {
assert_eq!(handle(voice_req("/api/act/chatgpt", role, br#"{"action":"logout"}"#), true).status, 403, "{role}");
}
assert_eq!(handle(voice_req("/api/sync/chatgpt", "owner", br#"{"action":"status"}"#), true).status, 403, "the screens' road isn't the phone's");
for (path, role) in [("/api/act/chatgpt", "owner"), ("/api/sync/chatgpt", "mirror")] {
let r = handle(voice_req(path, role, br#"{"action":"status"}"#), true);
assert_eq!(r.status, 200, "{path} {role}");
assert!(String::from_utf8_lossy(&r.body).contains("signed_in"), "{path}");
}
}
/// 傳送 is the owner's: a team member or an admin can't send through this brain, and a /// 傳送 is the owner's: a team member or an admin can't send through this brain, and a
/// computer takes parcels only from its own brain. /// computer takes parcels only from its own brain.
#[test] #[test]

View File

@ -1079,6 +1079,7 @@ fn provider_from_name(s: &str) -> Option<crate::providers::ProviderKind> {
match s.trim().to_ascii_lowercase().as_str() { match s.trim().to_ascii_lowercase().as_str() {
"xai" | "grok" => Some(Xai), "xai" | "grok" => Some(Xai),
"openai" | "open-ai" => Some(OpenAi), "openai" | "open-ai" => Some(OpenAi),
"chatgpt" | "chatgpt-plan" | "chatgpt_plan" => Some(ChatGpt),
"anthropic" | "claude" => Some(Anthropic), "anthropic" | "claude" => Some(Anthropic),
"gemini" | "google" => Some(Gemini), "gemini" | "google" => Some(Gemini),
"openrouter" => Some(OpenRouter), "openrouter" => Some(OpenRouter),
@ -1095,11 +1096,14 @@ fn seed_first() -> i32 {
use crate::model::{Bot, State}; use crate::model::{Bot, State};
let name = std::env::var("ANYBOT_PROVIDER").unwrap_or_default(); let name = std::env::var("ANYBOT_PROVIDER").unwrap_or_default();
let Some(kind) = provider_from_name(&name) else { let Some(kind) = provider_from_name(&name) else {
eprintln!("✗ 請設 ANYBOT_PROVIDER(openai、anthropic、xai、gemini、openrouter、opencode、ollama、custom)"); eprintln!("✗ 請設 ANYBOT_PROVIDER(openai、chatgpt、anthropic、xai、gemini、openrouter、opencode、ollama、custom)");
return 2; return 2;
}; };
let key = std::env::var("ANYBOT_API_KEY").unwrap_or_default(); let key = std::env::var("ANYBOT_API_KEY").unwrap_or_default();
if kind.needs_key() && key.is_empty() { // ChatGPT 方案 has no key: the account is signed in afterwards (設定 › 模型, or ask a bot).
if kind == crate::providers::ProviderKind::ChatGpt {
eprintln!("ChatGPT 方案不用金鑰:裝好後到 設定 › 模型 › ChatGPT 方案 按「使用 ChatGPT 繼續」(大腦在伺服器時,從螢幕電腦或手機登入)。");
} else if kind.needs_key() && key.is_empty() {
eprintln!("✗ 請設 ANYBOT_API_KEY"); eprintln!("✗ 請設 ANYBOT_API_KEY");
return 2; return 2;
} }

View File

@ -1,6 +1,7 @@
//! 測試工具: one fake model service for every test that needs a model (agent.rs, app.rs and here), //! 測試工具: one fake model service for every test that needs a model (agent.rs, app.rs and here),
//! instead of three servers each written in its own test module. It speaks OpenAI's chat //! instead of three servers each written in its own test module. It speaks OpenAI's chat
//! completions stream and Anthropic's messages stream, answers each request with the next //! completions stream, Anthropic's messages stream and OpenAI's Responses stream (ChatGPT 方案),
//! answers each request with the next
//! reply of a script — words, a tool call, an error status with Retry-After, a dropped //! reply of a script — words, a tool call, an error status with Retry-After, a dropped
//! connection, an empty answer — and keeps every request it got. Like grok-build's //! connection, an empty answer — and keeps every request it got. Like grok-build's
//! xai-grok-test-support. //! xai-grok-test-support.
@ -45,6 +46,8 @@ impl Reply {
pub enum Format { pub enum Format {
OpenAi, OpenAi,
Anthropic, Anthropic,
/// OpenAI's Responses API (ChatGPT 方案).
Responses,
} }
/// A running fake model service. /// A running fake model service.
@ -148,6 +151,20 @@ pub fn stream(format: Format, reply: &Reply) -> String {
] ]
.concat(), .concat(),
(Format::Anthropic, Reply::Empty) => [event("message_start", json!({"type": "message_start"})), event("message_stop", json!({"type": "message_stop"}))].concat(), (Format::Anthropic, Reply::Empty) => [event("message_start", json!({"type": "message_start"})), event("message_stop", json!({"type": "message_stop"}))].concat(),
(Format::Responses, Reply::Text(t)) => [
event("response.created", json!({"type": "response.created", "response": {"status": "in_progress"}})),
event("response.output_text.delta", json!({"type": "response.output_text.delta", "delta": t})),
event("response.completed", json!({"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 120, "input_tokens_details": {"cached_tokens": 20}, "output_tokens": 7}}})),
]
.concat(),
(Format::Responses, Reply::Call { id, name, args }) => [
event("response.output_item.added", json!({"type": "response.output_item.added", "item": {"type": "function_call", "call_id": id, "name": name, "arguments": ""}})),
event("response.function_call_arguments.delta", json!({"type": "response.function_call_arguments.delta", "delta": args.to_string()})),
event("response.output_item.done", json!({"type": "response.output_item.done", "item": {"type": "function_call", "call_id": id, "name": name, "arguments": args.to_string()}})),
event("response.completed", json!({"type": "response.completed", "response": {"status": "completed"}})),
]
.concat(),
(Format::Responses, Reply::Empty) => event("response.completed", json!({"type": "response.completed", "response": {"status": "completed"}})),
(_, Reply::Raw(_, body)) => body.clone(), (_, Reply::Raw(_, body)) => body.clone(),
(_, Reply::Fail { body, .. }) => body.clone(), (_, Reply::Fail { body, .. }) => body.clone(),
(_, Reply::Drop) => String::new(), (_, Reply::Drop) => String::new(),