diff --git a/FEATURES.md b/FEATURES.md index 8dea54a..292e9b1 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -2668,4 +2668,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ## 其他(2026-11-04) - **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:/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 不會再卡住。 diff --git a/docs/feature-map/bots.md b/docs/feature-map/bots.md index 50cfea3..84d4a86 100644 --- a/docs/feature-map/bots.md +++ b/docs/feature-map/bots.md @@ -12,7 +12,8 @@ - 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀平均排成兩列;10 種顏色和「自訂」同一列;按「自訂」出現一格一格的色盤——12 個色相各四種深淺加一列灰階,直接點,沒有滑桿——和「色碼」欄,打完整的 #rrggbb 才換色);「AI 供應商與模型」(供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」——欄位名稱在上,說明在名稱旁的「?」);接著「電腦操作」「能力」「技能」「記憶」四張預設收起,各只有一行:名稱、目前怎麼設(例如「11 / 11 類」「會 8 / 8」「還沒有」)和 ▸,點了才展開;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot」(「?」說明:團隊成員看得到它的聊天、頁面和檔案)。 - Soul 與指示只有它自己讀;描述、擅長、不找它做的事、會的技能、在哪幾台電腦做事會寫進其他 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 選單:右鍵側邊欄的 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,填 Soul 與指示和擅長後按「建立 Bot」,重開 AnyBot 還在;在聊天裡說「把你的檔案與指令能力關掉」,要先跳出列出改動的確認卡片,按拒絕什麼都不變,按允許後 Bot 設定的「能力」少勾一格;換一個沒金鑰的供應商,要出現紅字和「前往設定」。頭像按「自訂」,色盤點一格頭像就換色,「色碼」打 #6b4a55 也換;整個視窗不能變寬(下面的卡片和最上面的標題列一樣寬)。自動測試:`cargo test profile::`、`cargo test appctl::`、`cargo test app::sidebar_ui::`、`cargo test app::tests::`。 +- 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 設定的「能力」少勾一格;換一個沒金鑰的供應商,要出現紅字和「前往設定」。設定 › 模型 › 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」不帶聊天記錄、金鑰和 Token。 +- ChatGPT 方案:額度用完會停下來說「已達用量上限(ChatGPT 方案)」並給「管理用量」連結,不會自動改用 API 金鑰付費,也不會一直重試;沒勾同意使用方案,算登入了但不能用;在 ChatGPT 設定裡中斷連線,下一次要求才會發現,要重新登入。語音轉文字、朗讀不能用方案,還是要 OpenAI 的 API 金鑰。登入的 token 存在大腦,不會傳到螢幕電腦和手機。連到大腦的螢幕電腦:設定 › 模型 › ChatGPT 方案 按鈕一樣,登入頁開在這台;登入後那頁打不開,把網址貼進下面的欄位按「完成登入」。手機:設定 › AI 服務 › ChatGPT 方案 →「使用 ChatGPT 繼續…」,同樣貼回網址。`chatgpt_login` 的 logout、switch_account 會先跳確認卡片。 diff --git a/docs/feature-map/settings.md b/docs/feature-map/settings.md index 4270575..c83567b 100644 --- a/docs/feature-map/settings.md +++ b/docs/feature-map/settings.md @@ -12,7 +12,7 @@ - Bot:時區,例行任務和提醒用([routines](routines.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))。 - 連接器:「連接器(MCP)」清單、「可以用的工具」、「連接器市集」、「新增連接器」([connectors](connectors.md))。 diff --git a/mobile/index.html b/mobile/index.html index a561462..1502914 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2499,6 +2499,18 @@ function wireSettings(kind, st) { const p = st.providers[+x.dataset.prov]; 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(); }}] : []), + // 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(); }}, ...(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 7d2c112..d58dd6b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2480,6 +2480,13 @@ impl App { self.manage_connectors(ctx, call); 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). if call.name == crate::hooks::MANAGE_TOOL { 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()); } + /// 設定 › 模型 › 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::(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) { let mut done = vec![]; 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()); } 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); - 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.settings_tab = SettingsTab::Providers; self.settings_provider = bot.provider; @@ -4966,14 +5098,14 @@ impl App { .iter() .map(|&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(); 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| { ui.set_min_width(menu_ui::MENU_W); 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 r = menu_ui::item_text(ui, p, Some(icon), &title); egui::containers::menu::SubMenu::new().show(ui, &r, |ui| { @@ -5165,9 +5297,10 @@ impl App { }); }); 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.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() { self.show_settings = true; self.settings_tab = SettingsTab::Providers; @@ -5791,7 +5924,7 @@ impl App { ui.spacing_mut().item_spacing.y = 2.0; for k in ALL_PROVIDERS { 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 on = self.settings_provider == k; if on || r.hovered() { @@ -5804,7 +5937,7 @@ impl App { 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 }); - let tip = if ready { "已可使用" } else { "還沒設定金鑰" }; + let tip = t(if ready { "已可使用" } else if k == ProviderKind::ChatGpt { "還沒用 ChatGPT 登入" } else { "還沒設定金鑰" }); if r.on_hover_text(tip).clicked() { self.settings_provider = k; } @@ -5817,14 +5950,20 @@ impl App { ui.label(RichText::new(k.label()).strong().family(crate::bold()).size(FONT_H3)); hint(ui, k.key_help(), p); 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 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); 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(); } - field_label(ui, "服務網址", p); - changed |= ui.add(egui::TextEdit::singleline(&mut ps.base_url).hint_text(k.default_base_url()).desired_width(w)).changed(); + if k != ProviderKind::ChatGpt { + field_label(ui, "服務網址", p); + 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); 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. @@ -7275,6 +7414,7 @@ fn short_provider(k: ProviderKind) -> &'static str { match k { ProviderKind::Xai => "Grok", ProviderKind::OpenAi => "OpenAI", + ProviderKind::ChatGpt => "ChatGPT 方案", ProviderKind::Anthropic => "Claude", ProviderKind::Gemini => "Gemini", ProviderKind::OpenRouter => "OpenRouter", diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index 3372638..7877335 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -135,6 +135,13 @@ impl App { } self.triggers_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. let rotated: Vec<(u64, String)> = crate::teams::rotated().lock().unwrap().iter().map(|(k, v)| (*k, v.clone())).collect(); for (id, tok) in rotated { diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index ccc35d7..b65877c 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -256,7 +256,9 @@ impl App { /// 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. 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 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() }; diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index b409e44..12a7c59 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -478,7 +478,7 @@ impl App { // The models a bot can be switched to from the phone: each provider that is ready. view.models = crate::providers::ALL_PROVIDERS .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. .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::>()})) .collect(); @@ -1777,8 +1777,9 @@ impl App { "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| { let ps = st.provider(k); - json!({"key": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "needs_key": k.needs_key(), - "ready": !k.needs_key() || !crate::providers::resolve_key(k, &ps.api_key).is_empty(), + // (ChatGPT 方案 signs in with an account, not a key: `account`.) + 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()}) }).collect::>(), "skills": st.skills.iter().map(|k| json!({ diff --git a/src/app/welcome_ui.rs b/src/app/welcome_ui.rs index dbfac2d..07b1596 100644 --- a/src/app/welcome_ui.rs +++ b/src/app/welcome_ui.rs @@ -7,7 +7,7 @@ use super::*; impl App { /// The first AI service that is ready to answer (has its key). pub(super) fn ready_provider(&self) -> Option { - 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) { diff --git a/src/appctl.rs b/src/appctl.rs index 529ff3e..54cf65d 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -9,7 +9,7 @@ use crate::model::{self, Bot, Message, State, Theme, Accent}; use crate::providers::{ProviderKind, ALL_PROVIDERS}; 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_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); @@ -25,6 +25,8 @@ pub const NAMES: [&str; 30] = [ crate::mcp::MANAGE_TOOL, // Hooks: list, add and remove the person's (asked every time, even with 一律放行). 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 { @@ -36,6 +38,7 @@ pub fn label(name: &str) -> &'static str { "list_routines" => "查看例行任務", crate::mcp::MANAGE_TOOL => "管理連接器", crate::hooks::MANAGE_TOOL => "管理 hook", + crate::chatgpt::TOOL => "ChatGPT 方案登入", "create_routine" => "建立例行任務", "update_routine" => "修改例行任務", "delete_routine" => "刪除例行任務", @@ -163,6 +166,7 @@ pub fn specs() -> Vec { "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::hooks::manage_spec(), + crate::chatgpt::spec(), ] .into_iter() .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)), 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::chatgpt::TOOL => crate::chatgpt::describe(args), "message_bot" => format!("給 {}:{}", s("bot"), s("text").chars().take(40).collect::()), "ask_bot" => format!("問 {}:{}", s("bot"), s("question").chars().take(40).collect::()), "teach_skill" => format!("「{}」給 {}", s("skill"), s("bot")), @@ -202,6 +207,14 @@ pub fn describe(name: &str, args: &str) -> String { /// "這會刪除例行任務並停止其後續執行。此操作無法復原。", VAgxC4). pub fn needs_approval(name: &str, args: &str, state: &State) -> Option { 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" { 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}")); @@ -997,6 +1010,10 @@ mod tests { assert!(needs_approval("update_bot", r#"{"name":"小幫手"}"#, &st).unwrap().contains("修改 Bot 自己")); // Nothing to change: nothing to ask. 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] diff --git a/src/chatgpt.rs b/src/chatgpt.rs new file mode 100644 index 0000000..ebd1c9b --- /dev/null +++ b/src/chatgpt.rs @@ -0,0 +1,1211 @@ +//! ChatGPT 方案: bots run on the person's ChatGPT plan (the usage Plus, Pro, Business… come with, +//! the same Codex uses) instead of an API key — OpenAI's Sign in with ChatGPT for open-source and +//! locally hosted apps (developers.openai.com/siwc/token-sharing-open-source). +//! +//! Signing in: the browser goes to auth.openai.com. The first time, AnyBot registers itself there +//! (`client_id=dynamic_agent_client`) and is given its own client id (`oaiapp_…`), kept and used +//! from then on, with this computer's own opaque host id. The browser comes back to +//! `http://127.0.0.1:/auth/callback` on the brain; when the browser is on another computer +//! (a brain on a server) that page can't load, and the person copies its address into the chat +//! (`chatgpt_login` with `callback`): the code is swapped here, where the PKCE verifier is. +//! The ID token is checked (RS256 against OpenAI's published keys, issuer, audience, nonce, +//! expiry) and the grant must include `chatgpt.tokens.use.direct` — without it the person is +//! signed in but the plan can't be used. +//! +//! Requests go to the public Responses API with the access token (providers::stream_responses). +//! An access token lasts an hour; it is renewed with the refresh token, which rotates, so one +//! renewal at a time. A usage limit stops the request: it never moves to API-key billing. +//! +//! Kept in `<資料夾>/providers/chatgpt.json`, the tokens sealed like the settings' secrets; never in +//! the settings, which screens and the phone get. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::io::{BufRead, BufReader, Write}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// The bot tool that signs in, out, and says how it stands. +pub const TOOL: &str = "chatgpt_login"; +pub const ISSUER: &str = "https://auth.openai.com"; +/// Where requests on the plan go: only here (the token is never sent to another address). +pub const API_BASE: &str = "https://api.openai.com/v1"; +/// The setting the person manages the plan's usage with. +pub const USAGE_URL: &str = "https://chatgpt.com/settings/usage"; +/// The scope that lets an app use the plan (signing in alone doesn't). +pub const PLAN_SCOPE: &str = "chatgpt.tokens.use.direct"; +const SCOPES: &str = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"; +const FIRST_CLIENT: &str = "dynamic_agent_client"; +const PREFERRED_PORT: u16 = 1455; +const LOGIN_WAIT: Duration = Duration::from_secs(10 * 60); +const HTTP_SECS: u64 = 20; +/// Renew this long before the access token ends. +const RENEW_EARLY_MS: i64 = 5 * 60_000; + +pub const NEED_LOGIN: &str = "還沒有登入 ChatGPT。請到「設定 › 模型 › ChatGPT 方案」按「使用 ChatGPT 繼續」,或在聊天裡請 Bot 幫你登入。"; +pub const NO_PLAN: &str = "已登入 ChatGPT,但沒有同意讓 AnyBot 使用你的 ChatGPT 方案。要用的話再登入一次並同意;或改用 OpenAI 的 API 金鑰。"; +const EXPIRED: &str = "ChatGPT 的登入失效了(登出、在 ChatGPT 設定裡中斷連線,或太久沒用)。請重新登入:設定 › 模型 › ChatGPT 方案,或在聊天裡請 Bot 幫你登入。"; + +/// The one ChatGPT account this AnyBot uses. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct Account { + /// The client id OpenAI issued to this AnyBot for this account (oaiapp_…): kept after + /// signing out and reused, so signing in again doesn't register again. + #[serde(default)] + pub client_id: String, + /// This computer's stable, opaque id for OpenAI (urn:uuid:…): made once, never replaced. + #[serde(default)] + pub host_id: String, + #[serde(default)] + pub access: String, + #[serde(default)] + pub refresh: String, + #[serde(default)] + pub id_token: String, + /// When the access token ends (ms; 0: not said). + #[serde(default)] + pub expires_at: i64, + #[serde(default)] + pub scopes: Vec, + /// Who signed in (from the checked ID token): `sub` is the identity, the email for showing. + #[serde(default)] + pub sub: String, + #[serde(default)] + pub email: String, + /// The first sign-in with the plan was welcomed (that note shows once). + #[serde(default)] + pub welcomed: bool, +} + +impl Account { + pub fn signed_in(&self) -> bool { + !self.access.is_empty() && !self.access.starts_with(crate::vault_store::SEALED) + } + + pub fn plan_ok(&self) -> bool { + self.scopes.iter().any(|s| s == PLAN_SCOPE) + } + + fn near_end(&self) -> bool { + self.expires_at > 0 && self.expires_at - RENEW_EARLY_MS < crate::model::now_ms() + } + + /// Signed out: the tokens go, the registration (client id, who) and the host id stay. + fn without_tokens(&self) -> Account { + Account { client_id: self.client_id.clone(), host_id: self.host_id.clone(), sub: self.sub.clone(), email: self.email.clone(), welcomed: self.welcomed, ..Default::default() } + } +} + +// ---------- where things are (tests point them elsewhere) ---------- + +#[cfg(test)] +thread_local! { + static TEST_AUTH: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static TEST_FILE: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static TEST_API: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +fn auth_base() -> String { + #[cfg(test)] + if let Some(b) = TEST_AUTH.with(|t| t.borrow().clone()) { + return b; + } + ISSUER.to_string() +} + +/// Where requests on the plan go (a test's own server in tests). +pub fn api_base() -> String { + #[cfg(test)] + if let Some(b) = TEST_API.with(|t| t.borrow().clone()) { + return b; + } + API_BASE.to_string() +} + +fn file() -> std::path::PathBuf { + #[cfg(test)] + if let Some(p) = TEST_FILE.with(|t| t.borrow().clone()) { + return p; + } + crate::model::State::path().parent().map(|d| d.join("providers").join("chatgpt.json")).unwrap_or_else(|| std::path::PathBuf::from("chatgpt.json")) +} + +// ---------- the account on disk ---------- + +fn store() -> &'static Mutex<()> { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| Mutex::new(())) +} + +const SEALED_FIELDS: [&str; 3] = ["access", "refresh", "id_token"]; + +fn read() -> Account { + let mut v: Value = serde_json::from_str(&std::fs::read_to_string(file()).unwrap_or_default()).unwrap_or(json!({})); + for k in SEALED_FIELDS { + if let Some(s) = v[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 and isn't used.) + if let Some(plain) = crate::vault_store::open_text(&s) { + v[k] = json!(plain); + } + } + } + serde_json::from_value(v).unwrap_or_default() +} + +fn write(a: &Account) -> Result<(), String> { + let mut v = serde_json::to_value(a).map_err(|e| e.to_string())?; + for k in SEALED_FIELDS { + if let Some(sealed) = v[k].as_str().and_then(crate::vault_store::seal_text) { + v[k] = json!(sealed); + } + } + let p = file(); + if let Some(d) = p.parent() { + std::fs::create_dir_all(d).map_err(|e| e.to_string())?; + } + // Written whole and then moved into place, readable by this user only from the start. + let tmp = p.with_extension("json.tmp"); + let _ = std::fs::remove_file(&tmp); + let mut o = std::fs::OpenOptions::new(); + o.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); + o.open(&tmp).and_then(|mut f| f.write_all(serde_json::to_string_pretty(&v).unwrap_or_default().as_bytes())).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &p).map_err(|e| e.to_string()) +} + +/// The account as last read or written (the settings ask every frame): by file, and only once +/// every token in it could be opened (a locked keychain is tried again next time). +fn cache() -> &'static Mutex> { + static C: OnceLock>> = OnceLock::new(); + C.get_or_init(Default::default) +} + +fn remember(a: &Account) { + let opened = [&a.access, &a.refresh, &a.id_token].iter().all(|t| !t.starts_with(crate::vault_store::SEALED)); + *cache().lock().unwrap_or_else(|e| e.into_inner()) = opened.then(|| (file(), a.clone())); +} + +/// The account as kept (tokens opened). +pub fn account() -> Account { + let _g = store().lock().unwrap_or_else(|e| e.into_inner()); + if let Some((p, a)) = cache().lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + if *p == file() { + return a.clone(); + } + } + let a = read(); + remember(&a); + a +} + +/// Change the account and keep it, in one go. +fn update(f: impl FnOnce(&mut Account)) -> Result { + let _g = store().lock().unwrap_or_else(|e| e.into_inner()); + let mut a = read(); + f(&mut a); + write(&a)?; + remember(&a); + Ok(a) +} + +/// What the settings show under the sign-in buttons (set by the sign-in started there). +fn note_cell() -> &'static Mutex { + static N: OnceLock> = OnceLock::new(); + N.get_or_init(Default::default) +} + +pub fn note() -> String { + note_cell().lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +pub fn set_note(s: impl Into) { + *note_cell().lock().unwrap_or_else(|e| e.into_inner()) = s.into(); +} + +/// The sign-in page of the sign-in waiting now (a link in the settings, for when the browser +/// didn't open, or on Windows, whose `start` cuts an address at its first &). +pub fn login_url() -> Option { + let p = pending().lock().unwrap_or_else(|e| e.into_inner()); + p.values().next().filter(|x| x.started.elapsed() < LOGIN_WAIT).map(|x| x.url.clone()) +} + +/// This computer's host id, made once (an opaque random UUID: nothing about the person). +fn host_id() -> Result { + let a = account(); + if !a.host_id.is_empty() { + return Ok(a.host_id); + } + let h = crate::httpd::random_hex(16); + let b = h.as_bytes(); + let s = |r: std::ops::Range| std::str::from_utf8(&b[r]).unwrap_or("0").to_string(); + // Version 4, variant 10xx. + let variant = ["8", "9", "a", "b"][usize::from_str_radix(&s(16..17), 16).unwrap_or(0) % 4]; + let id = format!("urn:uuid:{}-{}-4{}-{}{}-{}", s(0..8), s(8..12), s(13..16), variant, s(17..20), s(20..32)); + let id2 = id.clone(); + update(move |a| { + if a.host_id.is_empty() { + a.host_id = id2; + } + }) + .map(|a| a.host_id) + .or(Ok(id)) +} + +/// The access token as kept, without asking anyone (whether the provider is ready to use): +/// empty when not signed in or the plan wasn't allowed. +pub fn stored_token() -> String { + let a = account(); + if a.signed_in() && a.plan_ok() { a.access } else { String::new() } +} + +/// Why there is no token to send (without asking anyone): not signed in, or the plan not allowed. +pub fn why_not_ready() -> &'static str { + let a = account(); + if a.signed_in() && !a.plan_ok() { NO_PLAN } else { NEED_LOGIN } +} + +// ---------- the protocol ---------- + +fn enc(s: &str) -> String { + crate::mcp_oauth::enc(s) +} + +fn dec(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + match b[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < b.len() => match std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { + Some(x) => { + out.push(x); + i += 3; + continue; + } + None => out.push(b'%'), + }, + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn query_pairs(q: &str) -> HashMap { + q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (dec(k), dec(v))).collect() +} + +/// A form POST: (status, the JSON answer). Err only when nothing came back. +fn post_form(url: &str, form: &[(&str, String)]) -> Result<(u16, Value), String> { + let body: String = form.iter().map(|(k, v)| format!("{}={}", enc(k), enc(v))).collect::>().join("&"); + let mut resp = crate::net::agent(HTTP_SECS) + .post(url) + .header("Content-Type", "application/x-www-form-urlencoded") + .header("Accept", "application/json") + .send(body.as_bytes()) + .map_err(|e| format!("連不上 OpenAI 的登入伺服器:{e}"))?; + let status = resp.status().as_u16(); + let text = resp.body_mut().read_to_string().unwrap_or_default(); + Ok((status, serde_json::from_str(&text).unwrap_or(json!({"error": text.chars().take(200).collect::()})))) +} + +/// An OAuth error's code, flat (`{"error":"invalid_grant"}`) or nested (`{"error":{"code":…}}`). +fn err_code(v: &Value) -> &str { + v["error"].as_str().or(v["error"]["code"].as_str()).or(v["code"].as_str()).unwrap_or("") +} + +fn oauth_error(v: &Value) -> String { + let code = err_code(v); + let said = v["error_description"].as_str().or(v["error"]["message"].as_str()).unwrap_or(code); + if said.is_empty() { "(沒有說原因)".into() } else { said.to_string() } +} + +fn challenge(verifier: &str) -> String { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(ring::digest::digest(&ring::digest::SHA256, verifier.as_bytes()).as_ref()) +} + +/// A sign-in waiting for the person. +#[derive(Clone)] +struct Pending { + /// The sign-in page (shown again as a link in the settings). + url: String, + verifier: String, + nonce: String, + redirect: String, + /// The client id the browser was sent with (FIRST_CLIENT: a new registration). + client_id: String, + started: Instant, +} + +fn pending() -> &'static Mutex> { + static P: OnceLock>> = OnceLock::new(); + P.get_or_init(Default::default) +} + +/// Sign-ins that finished since last asked: Ok(who) or why not. +fn finished() -> &'static Mutex>> { + static F: OnceLock>>> = OnceLock::new(); + F.get_or_init(Default::default) +} + +pub fn take_finished() -> Vec> { + std::mem::take(&mut *finished().lock().unwrap_or_else(|e| e.into_inner())) +} + +/// The address that sends the browser to sign in (and, the first time, register AnyBot). +fn authorize_url(a: &Account, host: &str, redirect: &str, state: &str, nonce: &str, verifier: &str) -> (String, String) { + let first = a.client_id.is_empty(); + let client = if first { FIRST_CLIENT.to_string() } else { a.client_id.clone() }; + let mut url = format!("{}/api/accounts/authorize?client_id={}", auth_base(), enc(&client)); + if first { + url.push_str("&agent_name_hint=AnyBot"); + } else if !a.email.is_empty() { + url.push_str(&format!("&login_hint={}", enc(&a.email))); + } + // Signed in without the plan: asked again for it (OpenAI shows the consent once more). + if a.signed_in() && !a.plan_ok() { + url.push_str("&prompt=consent"); + } + url.push_str(&format!( + "&ext_agent_host_id={}&response_type=code&redirect_uri={}&scope={}&resource={}&state={}&nonce={}&code_challenge={}&code_challenge_method=S256", + enc(host), + enc(redirect), + enc(SCOPES), + enc(API_BASE), + enc(state), + enc(nonce), + enc(&challenge(verifier)) + )); + (url, client) +} + +/// Start signing in: the address to open in the person's browser. A listener on this computer +/// waits for the browser to come back (10 minutes); the address it comes back to can also be +/// handed over with [`finish_from_url`]. +pub fn start() -> Result { + let host = host_id()?; + // OpenAI's usual port first; any other free one if it's taken (only the port may change). + let listener = std::net::TcpListener::bind(("127.0.0.1", PREFERRED_PORT)) + .or_else(|_| std::net::TcpListener::bind("127.0.0.1:0")) + .map_err(|e| format!("開不了接登入結果的連接埠:{e}"))?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + let redirect = format!("http://127.0.0.1:{port}/auth/callback"); + let (verifier, state, nonce) = (crate::httpd::random_hex(32), crate::httpd::random_hex(16), crate::httpd::random_hex(16)); + let (url, client_id) = authorize_url(&account(), &host, &redirect, &state, &nonce, &verifier); + { + // One sign-in at a time: a newer one replaces the one before (its listener stops). + let mut p = pending().lock().unwrap_or_else(|e| e.into_inner()); + p.clear(); + p.insert(state.clone(), Pending { url: url.clone(), verifier, nonce, redirect, client_id, started: Instant::now() }); + } + std::thread::spawn(move || listen(listener, &state)); + Ok(url) +} + +/// Wait for the browser to come back (or the time to run out). +fn listen(listener: std::net::TcpListener, state: &str) { + let _ = listener.set_nonblocking(true); + let t0 = Instant::now(); + while t0.elapsed() < LOGIN_WAIT { + if !pending().lock().unwrap_or_else(|e| e.into_inner()).contains_key(state) { + return; // (finished another way, or a newer sign-in started) + } + let Ok((mut stream, _)) = listener.accept() else { + std::thread::sleep(Duration::from_millis(100)); + continue; + }; + let _ = stream.set_nonblocking(false); + let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + let mut line = String::new(); + let _ = BufReader::new(&stream).read_line(&mut line); + let target = line.split_whitespace().nth(1).unwrap_or(""); + let Some(query) = target.strip_prefix("/auth/callback?") else { + let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + continue; + }; + let r = finish_query(query); + let page = match &r { + Ok(who) => format!("已用 ChatGPT({who})登入,可以關掉這頁,回到 AnyBot。"), + Err(e) => format!("沒有登入成功:{e}"), + }; + let html = format!("AnyBot{}", page.replace('&', "&").replace('<', "<")); + let _ = stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{html}", html.len()).as_bytes()); + if r.is_ok() || !pending().lock().unwrap_or_else(|e| e.into_inner()).contains_key(state) { + return; + } + } + if pending().lock().unwrap_or_else(|e| e.into_inner()).remove(state).is_some() { + finished().lock().unwrap_or_else(|e| e.into_inner()).push(Err("等了 10 分鐘都沒有登入,取消了".into())); + } +} + +/// The address the browser came back to, pasted in the chat: finish that sign-in. +pub fn finish_from_url(callback: &str) -> Result { + let callback = callback.trim(); + let query = callback.split_once('?').map(|x| x.1).ok_or("這個網址裡沒有登入的結果(要有 ?code=…&state=…)")?; + finish_query(query.split('#').next().unwrap_or(query)) +} + +/// Check the callback, swap the code for tokens, check the ID token and keep it all: who signed in. +fn finish_query(query: &str) -> Result { + let q = query_pairs(query); + let state = q.get("state").cloned().unwrap_or_default(); + let p = pending().lock().unwrap_or_else(|e| e.into_inner()).remove(&state).ok_or("這個登入結果對不上進行中的登入(過期了、已經用過,或之後又開始了一次):重新登入一次")?; + let r = finish_pending(&p, &q); + set_note(String::new()); + finished().lock().unwrap_or_else(|e| e.into_inner()).push(r.clone()); + r +} + +fn finish_pending(p: &Pending, q: &HashMap) -> Result { + if p.started.elapsed() > LOGIN_WAIT { + return Err("這次登入等太久過期了:重新登入一次".into()); + } + if let Some(e) = q.get("error") { + if e == "access_denied" { + return Err("你在 ChatGPT 的頁面上沒有同意,所以沒有登入。".into()); + } + return Err(format!("OpenAI 說:{}", q.get("error_description").unwrap_or(e))); + } + let code = q.get("code").filter(|c| !c.is_empty()).ok_or("網址裡沒有 code")?; + let given = q.get("client_id").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + let client_id = if p.client_id == FIRST_CLIENT { + // A new registration must come back with the client id OpenAI issued. + given.filter(|g| g != FIRST_CLIENT).ok_or("OpenAI 沒有給這個 AnyBot 用戶端編號,註冊沒有完成:重新登入一次")? + } else { + if given.as_ref().is_some_and(|g| *g != p.client_id) { + return Err("登入結果裡的用戶端編號跟這個 AnyBot 註冊的不一樣,沒有採用。重新登入一次".into()); + } + p.client_id.clone() + }; + let (status, v) = post_form( + &format!("{}/api/accounts/oauth/token", auth_base()), + &[ + ("grant_type", "authorization_code".into()), + ("client_id", client_id.clone()), + ("code", code.clone()), + ("code_verifier", p.verifier.clone()), + ("redirect_uri", p.redirect.clone()), + ("resource", API_BASE.into()), + ], + )?; + if !(200..300).contains(&status) || v["access_token"].as_str().unwrap_or("").is_empty() { + let again = if err_code(&v) == "invalid_grant" { "(這個登入碼不能用了)" } else { "" }; + return Err(format!("OpenAI 沒有給登入憑證{again}:{}。重新登入一次", oauth_error(&v))); + } + let id_token = v["id_token"].as_str().unwrap_or(""); + if id_token.is_empty() { + return Err("OpenAI 沒有給身分憑證(ID token),沒有採用這次登入".into()); + } + let jwks = fetch_jwks()?; + let who = verify_id_token(id_token, &jwks, &client_id, &p.nonce, crate::model::now_ms() / 1000)?; + // (What was granted, as OpenAI's token answer says: not the address, which may be pasted.) + let scopes: Vec = v["scope"].as_str().unwrap_or("").split_whitespace().map(String::from).collect(); + let before = account(); + // The same registration signs in the same person: another account is not put in its place. + if !before.sub.is_empty() && before.client_id == client_id && before.sub != who.sub { + return Err(format!("登入的是另一個 ChatGPT 帳號({}),這個 AnyBot 用的是 {}。要換帳號,請先「換帳號」再登入。", who.email, before.email)); + } + let now = crate::model::now_ms(); + update(|a| { + a.client_id = client_id.clone(); + a.access = v["access_token"].as_str().unwrap_or("").to_string(); + a.refresh = v["refresh_token"].as_str().unwrap_or("").to_string(); + a.id_token = id_token.to_string(); + a.expires_at = v["expires_in"].as_i64().map(|s| now + s * 1000).unwrap_or(0); + a.scopes = scopes.clone(); + a.sub = who.sub.clone(); + a.email = who.email.clone(); + })?; + if !scopes.iter().any(|s| s == PLAN_SCOPE) { + return Err(NO_PLAN.into()); + } + Ok(if who.email.is_empty() { "你的帳號".into() } else { who.email }) +} + +// ---------- the ID token ---------- + +#[derive(Debug, PartialEq)] +pub struct Who { + pub sub: String, + pub email: String, +} + +fn b64url(s: &str) -> Result, String> { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s.trim_end_matches('=')).map_err(|_| "身分憑證的格式不對".to_string()) +} + +fn fetch_jwks() -> Result { + let mut resp = crate::net::agent(HTTP_SECS).get(&format!("{}/.well-known/jwks.json", auth_base())).call().map_err(|e| format!("拿不到 OpenAI 的簽章金鑰:{e}"))?; + if !(200..300).contains(&resp.status().as_u16()) { + return Err(format!("拿不到 OpenAI 的簽章金鑰(HTTP {})", resp.status().as_u16())); + } + serde_json::from_str(&resp.body_mut().read_to_string().unwrap_or_default()).map_err(|_| "OpenAI 的簽章金鑰不是 JSON".into()) +} + +/// Check an ID token: signed (RS256) by one of `jwks`' keys, from OpenAI, for this client, for +/// this sign-in (nonce), not ended. Who it is. +pub fn verify_id_token(token: &str, jwks: &Value, client_id: &str, nonce: &str, now_secs: i64) -> Result { + let parts: Vec<&str> = token.split('.').collect(); + if parts.len() != 3 { + return Err("身分憑證的格式不對".into()); + } + let header: Value = serde_json::from_slice(&b64url(parts[0])?).map_err(|_| "身分憑證的格式不對")?; + if header["alg"] != "RS256" { + return Err(format!("身分憑證的簽章方式不是 RS256({}),沒有採用", header["alg"])); + } + let kid = header["kid"].as_str(); + let keys: Vec<&Value> = jwks["keys"].as_array().into_iter().flatten().filter(|k| k["kty"] == "RSA" && (kid.is_none() || k["kid"].as_str() == kid)).collect(); + if keys.is_empty() { + return Err("找不到簽這個身分憑證的金鑰,沒有採用".into()); + } + let signed = format!("{}.{}", parts[0], parts[1]); + let sig = b64url(parts[2])?; + let ok = keys.iter().any(|k| { + let (Some(n), Some(e)) = (k["n"].as_str().and_then(|n| b64url(n).ok()), k["e"].as_str().and_then(|e| b64url(e).ok())) else { return false }; + ring::signature::RsaPublicKeyComponents { n: &n, e: &e }.verify(&ring::signature::RSA_PKCS1_2048_8192_SHA256, signed.as_bytes(), &sig).is_ok() + }); + if !ok { + return Err("身分憑證的簽章對不上,沒有採用".into()); + } + let c: Value = serde_json::from_slice(&b64url(parts[1])?).map_err(|_| "身分憑證的格式不對")?; + if c["iss"].as_str().map(|s| s.trim_end_matches('/')) != Some(ISSUER) { + return Err("身分憑證不是 OpenAI 發的,沒有採用".into()); + } + let aud_ok = match &c["aud"] { + Value::String(s) => s == client_id, + Value::Array(a) => a.iter().any(|x| x == client_id), + _ => false, + }; + if !aud_ok { + return Err("身分憑證不是給這個 AnyBot 的,沒有採用".into()); + } + // (A minute of clock difference allowed.) + if c["exp"].as_i64().is_none_or(|e| e + 60 < now_secs) { + return Err("身分憑證已經過期,重新登入一次".into()); + } + if c["nonce"].as_str() != Some(nonce) { + return Err("身分憑證不是這次登入的,沒有採用".into()); + } + let sub = c["sub"].as_str().unwrap_or("").to_string(); + if sub.is_empty() { + return Err("身分憑證裡沒有帳號,沒有採用".into()); + } + Ok(Who { sub, email: c["email"].as_str().unwrap_or("").to_string() }) +} + +// ---------- tokens for requests ---------- + +/// Why there is no token: the words, and whether trying again later may help (a network +/// hiccup) or the person has to do something (sign in again). +#[derive(Debug, Clone, PartialEq)] +pub struct NoToken { + pub msg: String, + pub retry: bool, +} + +impl NoToken { + fn needs_person(msg: &str) -> NoToken { + NoToken { msg: msg.into(), retry: false } + } +} + +fn renewing() -> &'static Mutex<()> { + static R: OnceLock> = OnceLock::new(); + R.get_or_init(|| Mutex::new(())) +} + +/// The access token to send, renewed first when it is about to end. +pub fn fresh_token() -> Result { + let a = account(); + if !a.signed_in() { + return Err(NoToken::needs_person(NEED_LOGIN)); + } + if !a.plan_ok() { + return Err(NoToken::needs_person(NO_PLAN)); + } + if a.near_end() { renew_after(&a.access) } else { Ok(a.access) } +} + +/// A new access token, because `stale` ended or was refused. One renewal at a time (the refresh +/// token rotates: two at once would spend it twice); one that another already did is used. +pub fn renew_after(stale: &str) -> Result { + let _g = renewing().lock().unwrap_or_else(|e| e.into_inner()); + let a = account(); + if !a.signed_in() || a.refresh.is_empty() { + return Err(NoToken::needs_person(NEED_LOGIN)); + } + if a.access != stale && !a.near_end() { + return Ok(a.access); + } + let (status, v) = post_form( + &format!("{}/api/accounts/oauth/token", auth_base()), + &[("grant_type", "refresh_token".into()), ("client_id", a.client_id.clone()), ("refresh_token", a.refresh.clone()), ("resource", API_BASE.into())], + ) + .map_err(|msg| NoToken { msg, retry: true })?; + let access = v["access_token"].as_str().unwrap_or("").to_string(); + if (200..300).contains(&status) && !access.is_empty() { + let now = crate::model::now_ms(); + let mut moved = false; + let fresh = update(|x| { + // (Signed out, or signed in anew, while this was on its way: that stands.) + if x.refresh != a.refresh || x.client_id != a.client_id { + moved = true; + return; + } + x.access = access.clone(); + // (It rotates: the new one replaces the old, together with the access token.) + if let Some(r) = v["refresh_token"].as_str().filter(|r| !r.is_empty()) { + x.refresh = r.to_string(); + } + x.expires_at = v["expires_in"].as_i64().map(|s| now + s * 1000).unwrap_or(0); + if let Some(s) = v["scope"].as_str() { + x.scopes = s.split_whitespace().map(String::from).collect(); + } + if let Some(t) = v["id_token"].as_str().filter(|t| !t.is_empty()) { + x.id_token = t.to_string(); + } + }) + .map_err(|msg| NoToken { msg, retry: true })?; + if moved { + return if fresh.signed_in() && fresh.plan_ok() { Ok(fresh.access) } else { Err(NoToken::needs_person(NEED_LOGIN)) }; + } + if !fresh.plan_ok() { + return Err(NoToken::needs_person(NO_PLAN)); + } + return Ok(access); + } + let code = err_code(&v); + const SPENT: [&str; 6] = ["invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused"]; + if SPENT.contains(&code) { + // The refresh token can't be used any more: those tokens go; signing in again reuses the registration. + let _ = update(|x| { + if x.refresh == a.refresh { + *x = x.without_tokens(); + } + }); + return Err(NoToken::needs_person(EXPIRED)); + } + if code == "invalid_client" { + return Err(NoToken::needs_person("OpenAI 不認得這個 AnyBot 的註冊了。請在「設定 › 模型 › ChatGPT 方案」按「換帳號」,再登入一次。")); + } + // A hiccup (a 5xx, the network): the tokens stay; try again later. + Err(NoToken { msg: format!("沒辦法更新 ChatGPT 的登入(HTTP {status}):{}", oauth_error(&v)), retry: status >= 500 || status == 429 }) +} + +/// Sign out: AnyBot's access is revoked at OpenAI and the tokens go (the registration stays, so +/// signing in again doesn't register again). `forget`: the registration goes too (換帳號). +pub fn logout(forget: bool) -> Result { + // (After a renewal on its way, so it doesn't sign back in.) + let _g = renewing().lock().unwrap_or_else(|e| e.into_inner()); + let a = account(); + let mut said = String::new(); + if !a.refresh.is_empty() && !a.refresh.starts_with(crate::vault_store::SEALED) { + // (Revoked twice at most over a network hiccup; signed out here either way.) + let mut revoked = false; + for _ in 0..2 { + match post_form(&format!("{}/api/accounts/oauth/revoke", auth_base()), &[("token", a.refresh.clone()), ("token_type_hint", "refresh_token".into()), ("client_id", a.client_id.clone())]) { + Ok((s, _)) if (200..300).contains(&s) => { + revoked = true; + break; + } + Ok((s, _)) if s < 500 => break, + _ => {} + } + } + if !revoked { + said = "(OpenAI 那邊沒有確認撤銷;可以到 ChatGPT 設定裡中斷 AnyBot 的連線)".into(); + } + } + update(|x| { + *x = if forget { Account { host_id: x.host_id.clone(), ..Default::default() } } else { x.without_tokens() }; + })?; + Ok(format!("已登出 ChatGPT{}。{said}", if forget { ",也忘了這個帳號的註冊(下次登入可以換帳號)" } else { "" })) +} + +/// The first sign-in with the plan: the welcome, once (None after). +pub fn welcome_once() -> Option { + let a = account(); + if a.welcomed || !a.signed_in() || !a.plan_ok() { + return None; + } + let _ = update(|x| x.welcomed = true); + Some(format!("你正在使用你的 ChatGPT 方案:Bot 選「ChatGPT 方案」時,它的 AI 要求會用你 ChatGPT 方案的額度(不是 API 金鑰,不另外計費)。用量可以在 ChatGPT 設定管理:{USAGE_URL}")) +} + +/// How it stands, in words (the tool, the settings). +pub fn status_text() -> String { + let a = account(); + match (a.signed_in(), a.plan_ok()) { + (true, true) => format!("已用 ChatGPT 登入({}),Bot 可以用你的 ChatGPT 方案。管理用量:{USAGE_URL}", if a.email.is_empty() { "帳號" } else { &a.email }), + (true, false) => NO_PLAN.into(), + _ if !a.email.is_empty() => format!("目前沒有登入(上次是 {})。", a.email), + _ => "還沒有用 ChatGPT 登入。".into(), + } +} + +// ---------- a screen or the phone of this brain ---------- + +/// A screen of this brain (設定 › 模型 on a computer connected to it) or the owner's phone asks: +/// the tool's actions, done here where the account is, and how it stands after. `login` without +/// a callback gives the sign-in page as `url` (the browser on their side opens it; the page it +/// comes back to won't load there, and they paste its address back: `login` with `callback`). +pub fn for_screen(v: &Value) -> Value { + let action = v["action"].as_str().unwrap_or("status"); + let callback = v["callback"].as_str().map(str::trim).filter(|c| !c.is_empty()); + let (text, ok, url) = match (action, callback) { + ("login", None) => match start() { + Ok(u) => (String::new(), true, Some(u)), + Err(e) => (e, false, None), + }, + _ => { + let (t, ok) = run_tool(&json!({"action": action, "callback": callback}).to_string()); + (t, ok, None) + } + }; + let a = account(); + json!({"ok": ok, "text": text, "url": url, "signed_in": a.signed_in(), "plan_ok": a.plan_ok(), "email": a.email, "registered": !a.client_id.is_empty(), "status": status_text()}) +} + +/// On a screen: how the brain's account stands, as it last said (None: not asked yet). +fn brain_cell() -> &'static Mutex> { + static B: OnceLock>> = OnceLock::new(); + B.get_or_init(Default::default) +} + +pub fn brain_view() -> Option { + brain_cell().lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, v)| v.clone()) +} + +/// (The sign-in page the brain gave stays until the account is usable: a later "how it stands" +/// answer doesn't carry it.) +pub fn set_brain_view(mut v: Value) { + let mut c = brain_cell().lock().unwrap_or_else(|e| e.into_inner()); + let usable = v["signed_in"] == true && v["plan_ok"] == true; + if v["url"].is_null() && !usable { + if let Some((_, old)) = c.as_ref() { + v["url"] = old["url"].clone(); + } + } + *c = Some((Instant::now(), v)); +} + +/// The brain's view is old enough to ask again (or was never asked). +pub fn brain_view_stale(secs: u64) -> bool { + brain_cell().lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_none_or(|(t, _)| t.elapsed().as_secs() >= secs) +} + +/// The plan can be used: signed in here, or (on a screen) on the brain, with the plan allowed. +pub fn usable() -> bool { + !stored_token().is_empty() || brain_view().is_some_and(|v| v["signed_in"] == true && v["plan_ok"] == true) +} + +// ---------- the bot's tool ---------- + +pub fn spec() -> Value { + json!({"name": TOOL, "description": "The ChatGPT plan provider (「ChatGPT 方案」): bots run on the person's ChatGPT plan (Plus, Pro, Business…) instead of an OpenAI API key. action=status: signed in or not, as whom. action=login: an address for the person to sign in with (open it with open_for_person or give it to them); it finishes by itself within 10 minutes. If the page it comes back to can't load (their browser is on another computer), ask them to copy that page's whole address and call again with callback=that address. action=logout: sign out (AnyBot's access is revoked). action=switch_account: sign out and forget this account's registration, to sign in with another ChatGPT account. A bot uses the plan once its provider is ChatGPT 方案 (update_my_profile provider=chatgpt).", + "parameters": {"type": "object", "properties": { + "action": {"type": "string", "enum": ["status", "login", "logout", "switch_account"]}, + "callback": {"type": "string", "description": "login only: the whole address the browser came back to (http://127.0.0.1:…/auth/callback?code=…)."} + }, "required": ["action"]}}) +} + +/// Run the tool (over the network: off the window's thread). (text, ok) +pub fn run_tool(args: &str) -> (String, bool) { + let v: Value = serde_json::from_str(args).unwrap_or(json!({})); + let r = match v["action"].as_str().unwrap_or("") { + "status" => Ok(status_text()), + "login" => match v["callback"].as_str().map(str::trim).filter(|c| !c.is_empty()) { + Some(cb) => finish_from_url(cb).map(|who| { + let welcome = welcome_once().map(|w| format!("\n請轉告使用者:{w}")).unwrap_or_default(); + format!("已用 ChatGPT({who})登入。Bot 的供應商選「ChatGPT 方案」就會用你的方案。{welcome}") + }), + None => start().map(|u| { + format!("請使用者打開這個網址,用 ChatGPT 帳號登入並同意讓 AnyBot 使用方案(用 open_for_person 開在他正在用的電腦上,或把網址給他):\n{u}\n登入好了 AnyBot 會自己接上(最多等 10 分鐘)。如果登入後那一頁打不開(他的瀏覽器在別台電腦),請他把那一頁的網址整個複製給你,再用 {TOOL}(action=login、callback=那個網址)。") + }), + }, + "logout" => logout(false), + "switch_account" => logout(true), + other => Err(format!("{TOOL} 的 action 要是 status、login、logout 或 switch_account(收到「{other}」)。")), + }; + match r { + Ok(t) => (t, true), + Err(e) => (e, false), + } +} + +/// What the call does, in a line (the step, the approval card). +pub fn describe(args: &str) -> String { + let v: Value = serde_json::from_str(args).unwrap_or(json!({})); + match v["action"].as_str().unwrap_or("") { + "login" if v["callback"].as_str().is_some_and(|c| !c.trim().is_empty()) => "完成登入".into(), + "login" => "登入".into(), + "logout" => "登出".into(), + "switch_account" => "換帳號".into(), + _ => "查看狀態".into(), + } +} + +#[cfg(test)] +pub mod tests { + use super::*; + use std::io::Read; + + /// A test RSA key (2048-bit, PKCS#8 DER, base64) — made for these tests only. + const TEST_KEY: &str = include_str!("chatgpt_test_key.b64"); + + pub fn key() -> ring::signature::RsaKeyPair { + use base64::Engine; + let der = base64::engine::general_purpose::STANDARD.decode(TEST_KEY.split_whitespace().collect::()).unwrap(); + ring::signature::RsaKeyPair::from_pkcs8(&der).unwrap() + } + + pub fn jwks() -> Value { + use base64::Engine; + use ring::signature::KeyPair; + let k = key(); + // The public key is DER: SEQUENCE { INTEGER n, INTEGER e }. + let der = k.public_key().as_ref().to_vec(); + let mut at = 0; + let mut item = |want: u8| -> Vec { + assert_eq!(der[at], want); + at += 1; + let mut len = der[at] as usize; + at += 1; + if len & 0x80 != 0 { + let n = len & 0x7f; + len = der[at..at + n].iter().fold(0, |a, b| a * 256 + *b as usize); + at += n; + } + let v = if want == 0x30 { vec![] } else { der[at..at + len].to_vec() }; + if want != 0x30 { + at += len; + } + v + }; + item(0x30); + let (n, e) = (item(0x02), item(0x02)); + let trim = |v: Vec| v.into_iter().skip_while(|b| *b == 0).collect::>(); + let b = |x: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x); + json!({"keys": [{"kty": "RSA", "kid": "k1", "alg": "RS256", "n": b(&trim(n)), "e": b(&trim(e))}]}) + } + + pub fn id_token(claims: &Value) -> String { + use base64::Engine; + let b = |x: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x); + let signed = format!("{}.{}", b(json!({"alg": "RS256", "kid": "k1", "typ": "JWT"}).to_string().as_bytes()), b(claims.to_string().as_bytes())); + let k = key(); + let mut sig = vec![0u8; k.public().modulus_len()]; + k.sign(&ring::signature::RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), signed.as_bytes(), &mut sig).unwrap(); + format!("{signed}.{}", b(&sig)) + } + + fn claims(aud: &str, nonce: &str, exp: i64) -> Value { + json!({"iss": ISSUER, "aud": aud, "sub": "user-1", "email": "a@example.com", "nonce": nonce, "exp": exp, "iat": exp - 3600}) + } + + #[test] + fn an_id_token_is_taken_only_when_everything_checks_out() { + let now = 1_900_000_000; + let ok = id_token(&claims("oaiapp_1", "n1", now + 600)); + assert_eq!(verify_id_token(&ok, &jwks(), "oaiapp_1", "n1", now).unwrap(), Who { sub: "user-1".into(), email: "a@example.com".into() }); + // Another client, another sign-in, ended, not OpenAI's. + assert!(verify_id_token(&ok, &jwks(), "oaiapp_2", "n1", now).unwrap_err().contains("不是給這個")); + assert!(verify_id_token(&ok, &jwks(), "oaiapp_1", "n2", now).unwrap_err().contains("不是這次登入")); + assert!(verify_id_token(&ok, &jwks(), "oaiapp_1", "n1", now + 3600).unwrap_err().contains("過期")); + let mut other = claims("oaiapp_1", "n1", now + 600); + other["iss"] = json!("https://evil.example"); + assert!(verify_id_token(&id_token(&other), &jwks(), "oaiapp_1", "n1", now).unwrap_err().contains("不是 OpenAI")); + // A token changed after signing: the signature no longer matches. + let parts: Vec<&str> = ok.split('.').collect(); + use base64::Engine; + let forged = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims("oaiapp_1", "n1", now + 99_999).to_string()); + assert!(verify_id_token(&format!("{}.{forged}.{}", parts[0], parts[2]), &jwks(), "oaiapp_1", "n1", now).unwrap_err().contains("簽章")); + // Not signed at all. + let none = format!("{}.{}.", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(r#"{"alg":"none"}"#), parts[1]); + assert!(verify_id_token(&none, &jwks(), "oaiapp_1", "n1", now).is_err()); + } + + #[test] + fn the_first_sign_in_registers_and_later_ones_reuse_the_client_id() { + let (first, c) = authorize_url(&Account::default(), "urn:uuid:h", "http://127.0.0.1:1455/auth/callback", "s", "n", "v"); + assert_eq!(c, FIRST_CLIENT); + assert!(first.starts_with("https://auth.openai.com/api/accounts/authorize?client_id=dynamic_agent_client&agent_name_hint=AnyBot&"), "{first}"); + for part in ["ext_agent_host_id=urn%3Auuid%3Ah", "redirect_uri=http%3A%2F%2F127.0.0.1%3A1455%2Fauth%2Fcallback", "scope=openid%20profile%20email%20offline_access%20resource.invoke%20chatgpt.tokens.use.direct", "resource=https%3A%2F%2Fapi.openai.com%2Fv1", "code_challenge_method=S256", "nonce=n", "state=s"] { + assert!(first.contains(part), "{part} missing: {first}"); + } + let known = Account { client_id: "oaiapp_9".into(), email: "a@example.com".into(), ..Default::default() }; + let (again, c) = authorize_url(&known, "urn:uuid:h", "http://127.0.0.1:5000/auth/callback", "s", "n", "v"); + assert_eq!(c, "oaiapp_9"); + assert!(again.contains("client_id=oaiapp_9") && !again.contains("agent_name_hint") && again.contains("login_hint=a%40example.com"), "{again}"); + } + + #[test] + fn a_host_id_is_an_opaque_uuid_made_once() { + let dir = std::env::temp_dir().join(format!("anybot-chatgpt-host-{}", crate::httpd::random_hex(6))); + TEST_FILE.with(|t| *t.borrow_mut() = Some(dir.join("chatgpt.json"))); + let h = host_id().unwrap(); + assert!(h.starts_with("urn:uuid:") && h.len() == "urn:uuid:".len() + 36 && h.chars().nth(23) == Some('4'), "{h}"); + assert_eq!(host_id().unwrap(), h); + // Signing out, even forgetting the registration, keeps it. + let _ = logout(true); + assert_eq!(account().host_id, h); + TEST_FILE.with(|t| *t.borrow_mut() = None); + let _ = std::fs::remove_dir_all(dir); + } + + /// OpenAI's sign-in server, as far as AnyBot uses it: the token endpoint (codes, refresh + /// tokens), the keys, revocation. + pub struct FakeAuth { + pub url: String, + pub seen: std::sync::Arc>>, + } + + impl FakeAuth { + /// `client`: the id it issues; `nonce`: what the ID token carries; `scope`: what it grants. + pub fn start(client: &str, nonce_of: std::sync::Arc>, scope: &str) -> FakeAuth { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://127.0.0.1:{}", l.local_addr().unwrap().port()); + let seen: std::sync::Arc>> = Default::default(); + let (client, scope, s2) = (client.to_string(), scope.to_string(), seen.clone()); + let refreshes = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + std::thread::spawn(move || { + for s in l.incoming().flatten() { + let mut s = s; + let mut r = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + let mut len = 0; + loop { + let mut h = String::new(); + r.read_line(&mut h).unwrap(); + if h.trim().is_empty() { + break; + } + if let Some(v) = h.to_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0; len]; + r.read_exact(&mut body).unwrap(); + let body = String::from_utf8_lossy(&body).to_string(); + let path = line.split_whitespace().nth(1).unwrap_or("").to_string(); + s2.lock().unwrap().push(format!("{path} {body}")); + let q = query_pairs(&body); + let answer = match path.as_str() { + "/.well-known/jwks.json" => jwks(), + "/api/accounts/oauth/revoke" => json!({}), + _ if q.get("grant_type").map(String::as_str) == Some("refresh_token") => { + let n = refreshes.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + if let Some(spent) = q.get("refresh_token").filter(|r| r.starts_with("spent")) { + // (Flat, or nested as {"error":{"code":…}}.) + let b = if spent == "spent-nested" { json!({"error": {"code": "refresh_token_expired", "message": "expired"}}) } else { json!({"error": "refresh_token_reused"}) }.to_string(); + let _ = s.write_all(format!("HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()).as_bytes()); + continue; + } + json!({"access_token": format!("access-{n}"), "refresh_token": format!("refresh-{n}"), "expires_in": 3600, "scope": scope}) + } + _ => { + let now = crate::model::now_ms() / 1000; + let nonce = nonce_of.lock().unwrap().clone(); + json!({"access_token": "access-0", "refresh_token": "refresh-0", "expires_in": 3600, "token_type": "Bearer", "scope": scope, "id_token": id_token(&json!({"iss": ISSUER, "aud": client, "sub": "user-1", "email": "a@example.com", "nonce": nonce, "exp": now + 600}))}) + } + }; + let b = answer.to_string(); + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()).as_bytes()); + } + }); + FakeAuth { url, seen } + } + } + + /// Point this thread's sign-in at `auth` and its account file at a folder of its own. + pub fn use_test_place(auth: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anybot-chatgpt-{}", crate::httpd::random_hex(6))); + TEST_FILE.with(|t| *t.borrow_mut() = Some(dir.join("chatgpt.json"))); + TEST_AUTH.with(|t| *t.borrow_mut() = Some(auth.to_string())); + dir + } + + pub fn use_test_api(url: Option) { + TEST_API.with(|t| *t.borrow_mut() = url); + } + + pub fn leave_test_place(dir: std::path::PathBuf) { + TEST_FILE.with(|t| *t.borrow_mut() = None); + TEST_AUTH.with(|t| *t.borrow_mut() = None); + let _ = std::fs::remove_dir_all(dir); + } + + /// Save a signed-in account (for the provider's tests). + pub fn sign_in_for_test(access: &str, expires_in_ms: i64) { + update(|a| { + a.client_id = "oaiapp_1".into(); + a.access = access.into(); + a.refresh = "refresh-x".into(); + a.expires_at = crate::model::now_ms() + expires_in_ms; + a.scopes = vec![PLAN_SCOPE.into()]; + a.email = "a@example.com".into(); + a.sub = "user-1".into(); + }) + .unwrap(); + } + + /// Sign-ins are one at a time for the whole program: the tests that start one take turns. + fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> { + static T: Mutex<()> = Mutex::new(()); + T.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Start a sign-in without a browser: the state and nonce it is waiting on. + fn begin() -> (String, String) { + let url = start().unwrap(); + let q = query_pairs(url.split_once('?').unwrap().1); + (q["state"].clone(), q["nonce"].clone()) + } + + #[test] + fn signing_in_registers_checks_the_id_token_and_keeps_the_tokens() { + let nonce = std::sync::Arc::new(Mutex::new(String::new())); + let fake = FakeAuth::start("oaiapp_new", nonce.clone(), "chatgpt.tokens.use.direct email offline_access openid profile resource.invoke"); + let _turn = one_at_a_time(); + let dir = use_test_place(&fake.url); + let (state, n) = begin(); + *nonce.lock().unwrap() = n; + // A new registration that comes back without the issued client id isn't finished. + assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&state={state}")).unwrap_err().contains("註冊沒有完成")); + let (state, n) = begin(); + *nonce.lock().unwrap() = n; + let who = finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&scope=openid&state={state}&client_id=oaiapp_new")).unwrap(); + assert_eq!(who, "a@example.com"); + let a = account(); + assert_eq!((a.client_id.as_str(), a.access.as_str(), a.refresh.as_str(), a.sub.as_str()), ("oaiapp_new", "access-0", "refresh-0", "user-1")); + assert!(a.plan_ok() && a.host_id.starts_with("urn:uuid:")); + let exchange = fake.seen.lock().unwrap().iter().find(|s| s.contains("authorization_code")).cloned().unwrap(); + assert!(exchange.contains("client_id=oaiapp_new") && exchange.contains("code_verifier=") && exchange.contains("resource=https%3A%2F%2Fapi.openai.com%2Fv1"), "{exchange}"); + assert_eq!(stored_token(), "access-0"); + // The welcome shows once. + assert!(welcome_once().unwrap().contains(USAGE_URL)); + assert!(welcome_once().is_none()); + // A used state is gone; a callback for another client id is refused. + assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&state={state}&client_id=oaiapp_new")).is_err()); + let (state, n) = begin(); + *nonce.lock().unwrap() = n; + assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c2&state={state}&client_id=oaiapp_other")).unwrap_err().contains("不一樣")); + // The registration's own placeholder is never taken as the issued id. + logout(true).unwrap(); + let (state, n) = begin(); + *nonce.lock().unwrap() = n; + assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c3&state={state}&client_id=dynamic_agent_client")).unwrap_err().contains("註冊沒有完成")); + let (state, n) = begin(); + *nonce.lock().unwrap() = n; + finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c4&state={state}&client_id=oaiapp_new")).unwrap(); + // A screen of this brain: how it stands, and a sign-in page for its browser. + let v = for_screen(&json!({"action": "status"})); + assert_eq!((v["signed_in"].clone(), v["plan_ok"].clone(), v["email"].clone()), (json!(true), json!(true), json!("a@example.com"))); + // Declining on OpenAI's page. + let (state, _) = begin(); + assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?error=access_denied&state={state}")).unwrap_err().contains("沒有同意")); + let v = for_screen(&json!({"action": "login"})); + assert!(v["url"].as_str().unwrap().contains("/api/accounts/authorize?"), "{v}"); + pending().lock().unwrap().clear(); + // Signing out revokes and keeps the registration; switching accounts forgets it. + logout(false).unwrap(); + assert!(fake.seen.lock().unwrap().iter().any(|s| s.starts_with("/api/accounts/oauth/revoke") && s.contains("token=refresh-0"))); + let a = account(); + assert!(!a.signed_in() && a.client_id == "oaiapp_new" && stored_token().is_empty()); + logout(true).unwrap(); + assert!(account().client_id.is_empty()); + leave_test_place(dir); + } + + #[test] + fn without_the_plan_scope_it_is_signed_in_but_not_usable() { + let nonce = std::sync::Arc::new(Mutex::new(String::new())); + let fake = FakeAuth::start("oaiapp_new", nonce.clone(), "email offline_access openid profile"); + let _turn = one_at_a_time(); + let dir = use_test_place(&fake.url); + let (state, n) = begin(); + *nonce.lock().unwrap() = n; + let e = finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&state={state}&client_id=oaiapp_new")).unwrap_err(); + assert_eq!(e, NO_PLAN); + assert!(account().signed_in() && stored_token().is_empty()); + assert_eq!(fresh_token().unwrap_err(), NoToken { msg: NO_PLAN.into(), retry: false }); + leave_test_place(dir); + } + + #[test] + fn a_token_near_its_end_is_renewed_and_a_spent_refresh_token_signs_out() { + let fake = FakeAuth::start("oaiapp_1", Default::default(), PLAN_SCOPE); + let dir = use_test_place(&fake.url); + sign_in_for_test("old", 60_000); + assert_eq!(fresh_token().unwrap(), "access-1"); + let a = account(); + assert_eq!((a.access.as_str(), a.refresh.as_str()), ("access-1", "refresh-1")); + // Another step that still holds the old one gets the one already renewed. + assert_eq!(renew_after("old").unwrap(), "access-1"); + assert_eq!(fake.seen.lock().unwrap().iter().filter(|s| s.contains("grant_type=refresh_token")).count(), 1); + // Plenty of time left: not renewed. + sign_in_for_test("fine", 3_600_000); + assert_eq!(fresh_token().unwrap(), "fine"); + // A refresh token OpenAI won't take: signed out, the registration kept. + update(|a| a.refresh = "spent".into()).unwrap(); + let e = renew_after("fine").unwrap_err(); + assert!(!e.retry && e.msg.contains("重新登入"), "{e:?}"); + assert!(!account().signed_in() && account().client_id == "oaiapp_1"); + // The same when OpenAI nests the code. + sign_in_for_test("fine", 3_600_000); + update(|a| a.refresh = "spent-nested".into()).unwrap(); + assert!(renew_after("fine").unwrap_err().msg.contains("重新登入")); + assert!(!account().signed_in()); + leave_test_place(dir); + } + + #[test] + fn tokens_that_could_not_be_opened_are_not_used_as_tokens() { + let dir = use_test_place("http://127.0.0.1:1"); + let p = file(); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + // Sealed with a key this computer can't open now (a locked keychain): not a sign-in. + let sealed = format!("{}00ff", crate::vault_store::SEALED); + std::fs::write(&p, json!({"client_id": "oaiapp_1", "access": sealed, "refresh": sealed, "scopes": [PLAN_SCOPE], "expires_at": crate::model::now_ms() + 3_600_000}).to_string()).unwrap(); + assert!(!account().signed_in()); + assert!(stored_token().is_empty()); + assert_eq!(fresh_token().unwrap_err().msg, NEED_LOGIN); + // Written by AnyBot: this user's only. + update(|a| a.email = "a@example.com".into()).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600); + } + leave_test_place(dir); + } + + #[test] + fn signed_in_without_the_plan_asks_for_consent_again() { + let declined = Account { client_id: "oaiapp_9".into(), access: "a".into(), scopes: vec!["openid".into()], ..Default::default() }; + let (url, _) = authorize_url(&declined, "urn:uuid:h", "http://127.0.0.1:1455/auth/callback", "s", "n", "v"); + assert!(url.contains("&prompt=consent"), "{url}"); + let fine = Account { scopes: vec![PLAN_SCOPE.into()], ..declined }; + assert!(!authorize_url(&fine, "urn:uuid:h", "http://127.0.0.1:1455/auth/callback", "s", "n", "v").0.contains("prompt=")); + } + + #[test] + fn the_tool_says_what_to_do() { + let _turn = one_at_a_time(); + let dir = use_test_place("http://127.0.0.1:1"); + assert!(run_tool(r#"{"action":"status"}"#).0.contains("還沒有用 ChatGPT 登入")); + let (text, ok) = run_tool(r#"{"action":"login"}"#); + assert!(ok && text.contains("/api/accounts/authorize?") && text.contains("callback"), "{text}"); + assert!(!run_tool(r#"{"action":"nope"}"#).1); + assert_eq!(describe(r#"{"action":"login","callback":"http://x"}"#), "完成登入"); + pending().lock().unwrap().clear(); + leave_test_place(dir); + } +} diff --git a/src/chatgpt_test_key.b64 b/src/chatgpt_test_key.b64 new file mode 100644 index 0000000..b7ff490 --- /dev/null +++ b/src/chatgpt_test_key.b64 @@ -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== diff --git a/src/i18n_table.rs b/src/i18n_table.rs index 42e4f22..d89956e 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -728,4 +728,19 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("手機已下載", "Downloaded on the phone", "スマホでダウンロード済み"), ("沒有送達", "Not delivered", "届きませんでした"), ("不知道原因", "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", "キー未設定"), ]; diff --git a/src/main.rs b/src/main.rs index 32c1c2d..6797210 100644 --- a/src/main.rs +++ b/src/main.rs @@ -43,6 +43,7 @@ mod macapps; mod marks; mod mcp; mod mcp_oauth; +mod chatgpt; mod memory; mod memstore; mod mention; diff --git a/src/mcp_oauth.rs b/src/mcp_oauth.rs index d612618..c68ae36 100644 --- a/src/mcp_oauth.rs +++ b/src/mcp_oauth.rs @@ -59,7 +59,7 @@ fn read_all() -> HashMap { if let Some(o) = v.as_object_mut() { for t in o.values_mut() { 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: // it isn't used, and saving another connector's doesn't empty it.) if let Some(plain) = crate::vault_store::open_text(&s) { @@ -100,7 +100,7 @@ fn write_all(all: &HashMap) -> Result<(), String> { /// This connector's tokens, if it is logged in. pub fn tokens(server: &str) -> Option { 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) -> Result<(), String> { @@ -597,6 +597,24 @@ pub mod tests { 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, /// the code becomes tokens (PKCE checked by the server), and a token near its end is renewed. #[test] diff --git a/src/profile.rs b/src/profile.rs index 8f39e53..6ffdc52 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -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", "write_page" | "read_page" | "list_pages" => "pages", "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, }) } diff --git a/src/providers.rs b/src/providers.rs index bbe53dd..b467c6f 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -15,6 +15,8 @@ use crate::model::{Message, Role, ToolCall, ToolStatus}; pub enum ProviderKind { Xai, OpenAi, + /// ChatGPT 方案: the person's ChatGPT plan, signed in with ChatGPT instead of a key (chatgpt.rs). + ChatGpt, Anthropic, Gemini, OpenRouter, @@ -23,9 +25,10 @@ pub enum ProviderKind { Custom, } -pub const ALL_PROVIDERS: [ProviderKind; 8] = [ +pub const ALL_PROVIDERS: [ProviderKind; 9] = [ ProviderKind::Xai, ProviderKind::OpenAi, + ProviderKind::ChatGpt, ProviderKind::Anthropic, ProviderKind::Gemini, ProviderKind::OpenRouter, @@ -60,6 +63,7 @@ impl ProviderKind { match self { ProviderKind::Xai => "xai", ProviderKind::OpenAi => "openai", + ProviderKind::ChatGpt => "chatgpt", ProviderKind::Anthropic => "anthropic", ProviderKind::Gemini => "gemini", ProviderKind::OpenRouter => "openrouter", @@ -73,6 +77,7 @@ impl ProviderKind { match self { ProviderKind::Xai => "xAI Grok", ProviderKind::OpenAi => "OpenAI", + ProviderKind::ChatGpt => "ChatGPT 方案", ProviderKind::Anthropic => "Claude", ProviderKind::Gemini => "Google Gemini", ProviderKind::OpenRouter => "OpenRouter", @@ -86,6 +91,7 @@ impl ProviderKind { match self { ProviderKind::Xai => "https://api.x.ai/v1", ProviderKind::OpenAi => "https://api.openai.com/v1", + ProviderKind::ChatGpt => crate::chatgpt::API_BASE, ProviderKind::Anthropic => "https://api.anthropic.com/v1", ProviderKind::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai", ProviderKind::OpenRouter => "https://openrouter.ai/api/v1", @@ -100,6 +106,8 @@ impl ProviderKind { match self { ProviderKind::Xai => "grok-4", 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::Gemini => "gemini-2.5-flash", ProviderKind::OpenRouter => "openrouter/auto", @@ -128,6 +136,7 @@ impl ProviderKind { match self { ProviderKind::Xai => &["grok-4", "grok-4-fast", "grok-3-mini"], 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::Gemini => &["gemini-2.5-flash", "gemini-2.5-pro"], ProviderKind::OpenRouter => &["openrouter/auto"], @@ -157,6 +166,7 @@ impl ProviderKind { match self { ProviderKind::Xai => "在 console.x.ai 取得 API 金鑰", ProviderKind::OpenAi => "在 platform.openai.com 取得 API 金鑰", + ProviderKind::ChatGpt => "用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰:用 ChatGPT 帳號登入就好", ProviderKind::Anthropic => "在 console.anthropic.com 取得 API 金鑰", ProviderKind::Gemini => "在 aistudio.google.com 取得 API 金鑰", ProviderKind::OpenRouter => "在 openrouter.ai 取得 API 金鑰", @@ -440,6 +450,10 @@ fn agent() -> ureq::Agent { } 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() { 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 — /// used to send the server's environment key there.) 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() { 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) } +/// 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 { let b = if stored.trim().is_empty() { kind.default_base_url() } else { stored.trim() }; 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"))] 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() { 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 result = match req.kind { ProviderKind::Anthropic => stream_anthropic(req, cancel, &tracked), + ProviderKind::ChatGpt => stream_responses(req, cancel, &tracked), ProviderKind::OpenCodeGo => { let mut r = req.clone(); 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) } +// ---------- 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 { + 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::>()), + _ => 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) -> Option { + 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) -> 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 { + 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 { + // (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::>()); + } + // 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 = None; + read_sse(resp.into_body(), cancel, send, |ev, data| { + let Ok(v) = serde_json::from_str::(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(¬e); + 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, 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 = 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 { let mut messages: Vec = vec![]; let mut push = |role: &str, blocks: Vec| { @@ -1681,6 +1960,10 @@ fn opencode_session(req: &ChatRequest) -> String { /// Ask the provider which models it offers. pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result, 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() { return Err("請先貼上 API 金鑰".into()); } @@ -2267,4 +2550,118 @@ mod tests { let m = cache_tail(vec![json!({"role": "user", "content": []})]); assert!(m[0]["content"].as_array().unwrap().is_empty()); } + + // ---------- ChatGPT 方案 (the Responses API) ---------- + + fn plan_req(history: Vec, tools: Vec) -> 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::(&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); + } } diff --git a/src/remote.rs b/src/remote.rs index 4546b81..f523c7d 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -685,6 +685,13 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { if !via_relay && loosens_guard(action, &body) { 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) } // 記憶: 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, "不認得的操作"), } } + // 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) { Ok(v) => Resp::json(&v), 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() } } + /// 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 /// computer takes parcels only from its own brain. #[test] diff --git a/src/setup.rs b/src/setup.rs index 4b8c507..6f11439 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1079,6 +1079,7 @@ fn provider_from_name(s: &str) -> Option { match s.trim().to_ascii_lowercase().as_str() { "xai" | "grok" => Some(Xai), "openai" | "open-ai" => Some(OpenAi), + "chatgpt" | "chatgpt-plan" | "chatgpt_plan" => Some(ChatGpt), "anthropic" | "claude" => Some(Anthropic), "gemini" | "google" => Some(Gemini), "openrouter" => Some(OpenRouter), @@ -1095,11 +1096,14 @@ fn seed_first() -> i32 { use crate::model::{Bot, State}; let name = std::env::var("ANYBOT_PROVIDER").unwrap_or_default(); 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; }; 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"); return 2; } diff --git a/src/testkit.rs b/src/testkit.rs index 22af22b..9c5aeaf 100644 --- a/src/testkit.rs +++ b/src/testkit.rs @@ -1,6 +1,7 @@ //! 測試工具: 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 -//! 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 //! connection, an empty answer — and keeps every request it got. Like grok-build's //! xai-grok-test-support. @@ -45,6 +46,8 @@ impl Reply { pub enum Format { OpenAi, Anthropic, + /// OpenAI's Responses API (ChatGPT 方案). + Responses, } /// A running fake model service. @@ -148,6 +151,20 @@ pub fn stream(format: Format, reply: &Reply) -> String { ] .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::Fail { body, .. }) => body.clone(), (_, Reply::Drop) => String::new(),