AnyBot/src/providers.rs

2717 lines
138 KiB
Rust
Raw Normal View History

// The switchable AI providers and how to talk to each one.
// Every provider streams its reply piece by piece over Server-Sent Events.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::io::{BufRead, BufReader};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender;
use std::time::Duration;
use crate::model::{Message, Role, ToolCall, ToolStatus};
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)]
pub enum ProviderKind {
Xai,
OpenAi,
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
/// ChatGPT 方案: the person's ChatGPT plan, signed in with ChatGPT instead of a key (chatgpt.rs).
ChatGpt,
Anthropic,
Gemini,
OpenRouter,
OpenCodeGo,
Ollama,
Custom,
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
pub const ALL_PROVIDERS: [ProviderKind; 9] = [
ProviderKind::Xai,
ProviderKind::OpenAi,
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
ProviderKind::ChatGpt,
ProviderKind::Anthropic,
ProviderKind::Gemini,
ProviderKind::OpenRouter,
ProviderKind::OpenCodeGo,
ProviderKind::Ollama,
ProviderKind::Custom,
];
/// How long to wait for the first bytes before giving up
/// (the original shows "模型未能及時開始回應" in that case; its deadline is server-side: estimated).
pub const FIRST_RESPONSE_TIMEOUT_SECS: u64 = 120;
/// Connect deadline: 15 s.
pub const CONNECT_TIMEOUT_MS: u64 = 15_000;
/// Mid-stream silence that counts as a stall: 35 s.
pub const STREAM_IDLE_STALL_MS: u64 = 35_000;
/// Retry policy: 3 attempts, 1 s initial delay, 4 s max, backoff factor 2.
pub const RETRY_MAX_ATTEMPTS: u32 = 3;
pub const RETRY_INITIAL_DELAY_MS: u64 = 1_000;
pub const RETRY_MAX_DELAY_MS: u64 = 4_000;
pub const RETRY_BACKOFF_FACTOR: u64 = 2;
/// Longest server-paced Retry-After we honour (SAND-E0408 backendCapacityDeferred): estimated cap.
pub const RETRY_AFTER_CAP_MS: u64 = 30_000;
pub const MAX_OUTPUT_TOKENS_ANTHROPIC: u64 = 64000;
pub const ANTHROPIC_VERSION: &str = "2026-10-21";
/// OpenCode Go (opencode.ai/docs/go): one subscription, many open models. Each model is served
/// in its own API style — the public models list says which (`chat-completions` → {base}/openai/v1,
/// `messages` → {base}/anthropic/v1); every request carries a stable `x-opencode-session`.
pub const OPENCODE_GO_BASE: &str = "https://opencode.ai/inference/go";
impl ProviderKind {
pub fn key(self) -> &'static str {
match self {
ProviderKind::Xai => "xai",
ProviderKind::OpenAi => "openai",
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
ProviderKind::ChatGpt => "chatgpt",
ProviderKind::Anthropic => "anthropic",
ProviderKind::Gemini => "gemini",
ProviderKind::OpenRouter => "openrouter",
ProviderKind::OpenCodeGo => "opencode-go",
ProviderKind::Ollama => "ollama",
ProviderKind::Custom => "custom",
}
}
pub fn label(self) -> &'static str {
match self {
ProviderKind::Xai => "xAI Grok",
ProviderKind::OpenAi => "OpenAI",
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
ProviderKind::ChatGpt => "ChatGPT 方案",
ProviderKind::Anthropic => "Claude",
ProviderKind::Gemini => "Google Gemini",
ProviderKind::OpenRouter => "OpenRouter",
ProviderKind::OpenCodeGo => "OpenCode Go",
ProviderKind::Ollama => "Ollama(本機)",
ProviderKind::Custom => "自訂(OpenAI 相容)",
}
}
pub fn default_base_url(self) -> &'static str {
match self {
ProviderKind::Xai => "https://api.x.ai/v1",
ProviderKind::OpenAi => "https://api.openai.com/v1",
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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",
// The models list is {base}/v1/models; chat goes to {base}/openai/v1 or {base}/anthropic/v1.
ProviderKind::OpenCodeGo => OPENCODE_GO_BASE,
ProviderKind::Ollama => "http://localhost:11434/v1",
ProviderKind::Custom => "http://localhost:8080/v1",
}
}
pub fn suggested_model(self) -> &'static str {
match self {
ProviderKind::Xai => "grok-4",
ProviderKind::OpenAi => "gpt-5",
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// (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",
ProviderKind::OpenCodeGo => "kimi-k3",
ProviderKind::Ollama => "llama3.2",
ProviderKind::Custom => "local-model",
}
}
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
/// A quick model of the same provider for carrying out planned steps (no long thinking),
/// when the bot's own model is a slower, thinking one. None: every step uses the bot's model.
pub fn quick_model(self, main: &str) -> Option<&'static str> {
let m = main.to_lowercase();
let (quick, already) = match self {
ProviderKind::Xai => ("grok-4.20-0309-non-reasoning", m.contains("non-reasoning") || m.contains("fast") || m.contains("mini")),
ProviderKind::Anthropic => ("claude-haiku-5-5", m.contains("haiku")),
ProviderKind::Gemini => ("gemini-2.5-flash", m.contains("flash")),
ProviderKind::OpenAi => ("gpt-5-mini", m.contains("mini") || m.contains("nano")),
_ => return None,
};
(!already && !m.is_empty()).then_some(quick)
}
/// A few names to pick from before the real list is fetched.
pub fn starter_models(self) -> &'static [&'static str] {
match self {
ProviderKind::Xai => &["grok-4", "grok-4-fast", "grok-3-mini"],
ProviderKind::OpenAi => &["gpt-5", "gpt-5-mini", "gpt-4.1"],
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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"],
ProviderKind::OpenCodeGo => &["kimi-k3", "glm-5.3", "deepseek-v4-pro", "qwen3.8-max", "minimax-m3", "mimo-v2.6-pro"],
ProviderKind::Ollama => &["llama3.2", "qwen2.5", "gemma3"],
ProviderKind::Custom => &[],
}
}
pub fn needs_key(self) -> bool {
!matches!(self, ProviderKind::Ollama | ProviderKind::Custom)
}
pub fn env_var(self) -> Option<&'static str> {
match self {
ProviderKind::Xai => Some("XAI_API_KEY"),
ProviderKind::OpenAi => Some("OPENAI_API_KEY"),
ProviderKind::Anthropic => Some("ANTHROPIC_API_KEY"),
ProviderKind::Gemini => Some("GEMINI_API_KEY"),
ProviderKind::OpenRouter => Some("OPENROUTER_API_KEY"),
ProviderKind::OpenCodeGo => Some("OPENCODE_API_KEY"),
_ => None,
}
}
pub fn key_help(self) -> &'static str {
match self {
ProviderKind::Xai => "在 console.x.ai 取得 API 金鑰",
ProviderKind::OpenAi => "在 platform.openai.com 取得 API 金鑰",
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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 金鑰",
ProviderKind::OpenCodeGo => "在 opencode.ai 的 Console 訂閱 Go,再複製 API 金鑰",
ProviderKind::Ollama => "先安裝並開啟 Ollama,不需要金鑰",
ProviderKind::Custom => "任何 OpenAI 相容的服務(LM Studio、vLLM…)",
}
}
}
/// Everything one model call needs, copied so the worker thread owns it.
#[derive(Clone)]
pub struct ChatRequest {
pub kind: ProviderKind,
pub base_url: String,
pub api_key: String,
pub model: String,
pub system: String,
pub history: Vec<Message>,
/// Tool specs ({name, description, parameters}); empty for plain chat.
pub tools: Vec<Value>,
/// One id per conversation (OpenCode Go routes and caches by it).
pub session: String,
/// 思考模式: "" leaves it to the model, else "low" | "medium" | "high" (how long it thinks
/// before answering). Sent as each service names it; a service that refuses it gets the
/// request again without (see [`effort_refused`]).
pub effort: String,
}
/// 思考模式's values, as stored on a bot: (value, name shown).
pub const EFFORTS: [(&str, &str); 4] = [("", "自動(模型自己決定)"), ("low", "快速(想得少,回得快)"), ("medium", "平衡"), ("high", "深入(想得久,較慢)")];
/// The value to send, or None when the bot leaves it to the model (or holds something else).
fn effort_of(req: &ChatRequest) -> Option<&str> {
let e = req.effort.trim();
["low", "medium", "high"].contains(&e).then_some(e)
}
/// (address, model) pairs that answered 400 to a thinking setting: not sent to them again while
/// the app runs.
fn effort_refused() -> &'static std::sync::Mutex<std::collections::HashSet<(String, String)>> {
static R: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<(String, String)>>> = std::sync::OnceLock::new();
R.get_or_init(Default::default)
}
/// A refusal that is about the thinking setting itself (the model doesn't take one, or not
/// this level), not about the request.
fn refuses_effort(f: &Failure) -> bool {
let m = f.msg.to_lowercase();
!f.retryable && (m.contains("reasoning") || m.contains("effort") || m.contains("output_config"))
}
pub enum StreamEvent {
Text(String),
Thinking(String),
/// Any line from the provider (keeps the stall watchdog quiet).
Alive,
/// A retry is about to happen; the text says why.
Retrying(String),
/// The model asked for a tool; shown at once, run after the step ends.
ToolCall(ToolCall),
/// A tool's state changed (waiting for approval, running, done…).
ToolStatus(String, ToolStatus),
/// Ask the person before running a tool; answer on the sender.
NeedApproval(Approval),
/// One model step finished: replace the streaming reply with the full message.
StepDone(Message),
/// A tool result to append to the chat.
ToolResult(Message),
/// The next model step starts: add a fresh reply bubble.
NextStep(String),
/// The oldest `n` messages were folded into this summary.
/// Older messages were folded into this summary; `cut` is the count in the model's view and
/// `boundary` the timestamp of the first kept message (the window's own copy may be longer).
Compacted(usize, Message, i64),
/// A message the person sent mid-turn was handed to the model (add it to the chat).
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
/// (With the id of the typed message, for the work log.)
Steered(Message, String),
/// Do something in the app (routines, bots, settings) and answer on the sender.
AppAction(AppCall),
/// 表情回應: the bot put an emoji on the person's latest message.
React(String),
/// The bot sent a file into the chat (a file card under its reply).
Attach(crate::attach::Attachment),
/// 自己進化: after the turn, the way that worked was kept as a skill (with the time of the
/// reply it learned from, which gets a line saying so).
Learned(crate::memory::Skill, i64),
/// Old step results were set aside from the model's view (their call ids): the chat marks
/// them, so the model reads them the same way next turn.
Folded(Vec<String>),
fix: 模型說對話太長時自己騰出空間再試——先拿掉截圖、再收起舊結果、再摘要(一輪中間也能切);記下模型真正的上限,把圖當文字算的模型不再傳圖 一台 Linux 換成自訂端點的模型後,一張網頁截圖讓請求從約 1.8 萬 tokens 變成 178,553(上限 131,072):那個端點把圖的 base64 當文字算。AnyBot 一張圖只估 3,200、也沒算工具說明,所以沒先壓縮;模型說太長時,最新 6 則一律保留(截圖就在裡面),這一輪又只有一則指令沒地方摘要,直接報錯;下一輪截圖還在記憶體裡又送一次。 - 模型說太長:依序拿掉圖片(聊天裡的步驟截圖也放掉,下一輪不再送)→ 收起除了最新 2 步以外的長結果 → 摘要(只有一則指令的長回合在這一輪中間切,指令原文保留)→ 都試過才報錯,並說明指示、工具說明、對話各多大 - 從錯誤訊息讀出上限(husky、OpenAI、vLLM、Anthropic 的寫法),比 Bot 設定小就記下來(StreamEvent::ContextLimit) - 實際用量比估算每張圖多 2 萬 tokens 以上(圖被當文字算)時,拿掉圖片成功後這個模型不再傳圖(改用文字描述);看得到圖、只是剛好超過一點的模型照樣看螢幕 - 估算加進工具說明(約 1.2 萬 tokens) 測試:husky 那次的截圖情境、一則指令的長回合、看圖模型只超過一點點、各家錯誤訊息的上限與用量解析。Mac 451 個測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:57:51 +00:00
/// The model said how much it can read (its "too long" error named it): kept as the bot's
/// context size, so it is summarized in time from now on.
ContextLimit(u64),
/// The pictures were taken out of the chat to make room: the chat lets go of them too, so
/// the next turn doesn't send them again.
PicturesDropped,
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
/// AnyBot's own problems the look back after a turn found (memory::learned_issues): queued
/// in 待改進, never written into a skill.
Issues(Vec<String>),
/// 目標: the check after a turn has spoken (for the goal set at this time, ms).
Goal(i64, crate::goal::Judged),
feat: /plan 先規劃再動手、聊天裡請 Bot 管理連接器、/always-approve 一律放行;輸入框上方的狀態不再破版 /plan(照 Claude Code 的 plan mode、Cursor 的 Plan Mode、Codex 的 update_plan) - 「/plan 要做的事」:這一輪只給會看的工具(讀檔、搜尋、web_fetch、瀏覽器的打開/讀取/捲動、截圖、anybot_guide、問題卡),在執行那一層擋下其他步驟(回「計畫還沒核准」),不是只靠提示詞。 - Bot 用 submit_plan 交計畫:聊天裡一張「計畫」卡(摘要、步驟、怎麼確認做對了、注意),下面的問題卡「照這個計畫做嗎?」:開始照計畫做/先不要/打字寫要改哪裡。 - 核准後同一輪接著做:工具全開、系統指示換成照計畫做,第 1 步自動進行中;update_plan 每做完一步更新一次(整份清單、只有一步進行中),卡上打勾、輸入框上方「照計畫做 · 2/6 · 這一步」;全部做完留「計畫完成」那一行。 - 「/plan」看狀態、「/plan clear」取消;例行任務、訊息管道、團隊成員的訊息不受影響;群組不能用;支線不帶計畫;清除聊天或新對話一起清;分享 Bot 檔不含。手機:計畫卡、計畫列、取消計畫。 - 新功能地圖 plan.md;研究(Claude Code、Codex、Cursor、Gemini CLI…)的結論寫進提示:只寫建議的做法、通常 3 到 7 步、問題最多 3 題、打勾不要太勤。 聊天裡管理連接器(設定能做的聊天也要能做) - 新工具 manage_connectors(管理 App 能力):list、add、update(含開關)、reconnect、remove。改的就是大腦上 設定 › 整合 › 連接器 那一份,不會寫到手腳電腦的檔案(進化之神之前叫使用者去 nobledesktop 的 ~/.local/share/AnyBot 設)。 - 新增、修改、移除先跳卡片:指令(在大腦上執行)或網址、環境變數、標頭;TOKEN、KEY、SECRET、PASS、AUTH… 和密碼顯示「••••(已填)」。名稱重複、command 和 url 都給、網址不對、還有「{…}」、沒東西可改,在問之前就回給 Bot。 - 加好後等它連上(最多 90 秒)再回報幾個工具或原因;一輪裡連接器的工具變了,下一步起就換新(加完同一輪就能用)。 /always-approve(也可以 /yolo) - 使用者自己打(電腦、大腦的螢幕、手機的擁有者)或 設定 › 權限 ›「一律放行」:打開直接操作,之後所有要等「允許」的都自動允許(含一律詢問規則、付款/傳送/刪除的點擊、寄信、傳訊息、打電話、發文、保險庫卡片),自動審核略過;打開時在等的卡片一起放行。 - 照樣擋:安全規則一律拒絕的;別人傳來的訊息那一輪;問題卡、需要處理、計畫卡。Bot、例行任務、訊息管道打不開;管理員和成員打的變成「【名字】/always-approve」。管理員鎖了直接操作就打不開。 - 開著時每個聊天輸入框上方一條「一律放行」和「關閉」;「/always-approve off」關掉,直接操作是它打開的就一起關。 輸入框上方的狀態 - 好幾行的狀態(模型忙碌重試:錯誤、說明、幾秒後重試)以前疊出那一列、壓到輸入框;現在一行:「模型供應商目前負載過高,15 秒後重試(第 3 次,共 3 次)…」。 已驗證:cargo test 548 通過、1 個失敗(layout_audit 的 設定 › 電腦 被這台 Mac 的 Docker 位址 unix:///Users/daniel/.lima/anybot-gvisor 撐寬;把這次的改動 stash 掉一樣失敗,跟這次無關)。新測試:plan:: 7 個;agent 的計畫模式三個(只看到卡片說開始、先不要什麼都不做、修改後重交);app 的 /plan 從打字到計畫完成、Bot 從聊天加連接器(卡片不露 Token、同一輪就用它的工具算出 sum=5)、/always-approve(之前會問、之後不問直接在這台跑、陌生人的訊息照樣問、off 回原樣);mcp::manage_tests 4 個;狀態一行。截圖看過:計畫卡等你決定/照著做打勾、503 重試那一行。手機頁面 JS 語法檢查和計畫卡四種狀態的 HTML。 未驗證:真的模型走一次 /plan 和加 GitLab 連接器;手機實機;伺服器上的大腦(要 make update-server)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:55:37 +00:00
/// 計畫: the plan was approved, dropped, sent back, or its steps moved on.
Plan(crate::plan::Event),
Done,
Error(String),
}
pub struct Approval {
pub call_id: String,
pub tool: String,
pub reason: String,
/// What "always allow" would remember; empty when it can't be remembered.
pub grant: String,
pub reply: Sender<ApprovalAnswer>,
pub kind: ApprovalKind,
}
/// What the person is asked.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum ApprovalKind {
/// One action (run this command, edit this file…).
#[default]
Action,
/// This bot's computer tools are off: let it use them? ("always" turns them on for the bot.)
EnableTools,
/// 在這台電腦上執行 is off: let it work on this Mac? ("always" turns the setting on.)
EnableThisComputer,
/// 需要處理: a step only the person can do on a computer (signing in, a captcha…). `reason`
/// is what to do, `grant` the computer's name; Once = 「我完成了」, Reject = 「跳過」 (the
/// original's box hand-off card).
Handoff,
問題卡、搜尋: the bot asks with a card; every chat is searched; a refusal holds for the turn - 問題卡 (ask_person, src/ask.rs): up to 6 questions on a card above the input, one at a time — a choice (one click moves on), several choices, or a field that arrives filled for the person to correct; 「自己回答」 on every question, 上一題 and 略過. The turn waits; a message typed instead leaves the card unanswered. Travels as an approval of kind Question (questions as JSON) with a new answer Answered, so the window, a screen of another brain and the phone draw the same card. - 搜尋所有聊天 (src/find.rs): the sidebar's search also lists what the person and the bots said in every chat, past conversations included, and attachment names; newest first, 40 at most. A click opens the bot (bringing a past conversation back first), scrolls to the message and lights it for a moment. - 拒絕後停下: a step the person refused is refused for them when it comes back unchanged in the same turn — no second card, no second review — until they write again. - The bot's instructions: stop after a refusal instead of trying another way; before sending, posting, buying or deleting, check the person's own messages asked for exactly that, and ask with the card when they didn't. - 直接操作 no longer answers a hand-off (or a question) on the person's behalf. - The repeated-step check leaves questions to the person alone. - Screenshot views `ask` and `find`; FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:17:32 +00:00
/// 問題卡: the bot asks the person something (see ask.rs). `reason` is the questions as
/// JSON; the answer is Answered, and Reject = 「略過」.
Question,
}
pub struct AppCall {
pub call_id: String,
pub name: String,
pub args: String,
/// (result text, ok)
pub reply: Sender<(String, bool)>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ApprovalAnswer {
Once,
Always(String),
智慧模式 (/smart): 一问一决定,不是一步一卡 询问和一律放行中间的设定(CLAUDE.md 改善轮迴的第一块:聊天卡顿的主因是一步一卡)。 - 卡片多一个「这轮都准」: 同类操作这一轮只问一次(Job 就是一轮,按构造就是 per-turn; 下一轮会再问)。grant 非空的 Action 卡与连接器卡有这按钮;must-ask(付款/传送/删除的 点击、你的屏幕和 App、保险库、一律询问规则、hook)没有,也不被覆盖。 - 卡片逾时: 你几分钟没回,卡片自己回答——看档案/上网这类先做(步骤结果里写明),敏感操作 自动拒绝并告诉 Bot 别重试。/smart 中途开关都即时(窗口一个 Arc,Job 共享)。 - 审核缓存: 自动审核的模型判决这一轮按(规则,动作)缓存,重复同一步不再每次付 10–20 秒; 审查看不见档案全文时照旧自己问(没动)。 - 开关: /smart(/smart off、status)、设定›权限(滑块调时限,默认 300 秒)、输入列旁图标。 手机/远端只能关不能开(words_loosen + remote setting 只收紧);untrusted 回合永不智慧。 - 锁: 管理员锁住直接操作/本地执行时,智慧模式一起锁。 - feature-map: chat.md / safety.md / autonomy.md / settings.md 同步(featuremap 测试绿)。 已验证: cargo test 全绿 716(含 featuremap::、layout_audit::、approval/tool 锁未动) 未验证: 实机批准卡路径(新按钮、逾时行为)需人类实机点测并签名(CLAUDE.md 审批准则)
2026-11-19 06:59:29 +00:00
/// 智慧模式 「這輪都准」: allow this, and remember the grant for the rest of this turn only
/// (see smart.rs; the phone never sends it — widening, even per-turn, is typed at the computer).
Scope(String),
Reject,
問題卡、搜尋: the bot asks with a card; every chat is searched; a refusal holds for the turn - 問題卡 (ask_person, src/ask.rs): up to 6 questions on a card above the input, one at a time — a choice (one click moves on), several choices, or a field that arrives filled for the person to correct; 「自己回答」 on every question, 上一題 and 略過. The turn waits; a message typed instead leaves the card unanswered. Travels as an approval of kind Question (questions as JSON) with a new answer Answered, so the window, a screen of another brain and the phone draw the same card. - 搜尋所有聊天 (src/find.rs): the sidebar's search also lists what the person and the bots said in every chat, past conversations included, and attachment names; newest first, 40 at most. A click opens the bot (bringing a past conversation back first), scrolls to the message and lights it for a moment. - 拒絕後停下: a step the person refused is refused for them when it comes back unchanged in the same turn — no second card, no second review — until they write again. - The bot's instructions: stop after a refusal instead of trying another way; before sending, posting, buying or deleting, check the person's own messages asked for exactly that, and ask with the card when they didn't. - 直接操作 no longer answers a hand-off (or a question) on the person's behalf. - The repeated-step check leaves questions to the person alone. - Screenshot views `ask` and `find`; FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:17:32 +00:00
/// 問題卡: what the person answered, a JSON list with one string per question.
Answered(String),
}
/// What one model call produced.
#[derive(Default, Debug)]
pub struct StepOutput {
pub text: String,
pub thinking: String,
pub tool_calls: Vec<ToolCall>,
/// Claude's raw content blocks, kept to replay thinking signatures unchanged.
pub blocks: Vec<Value>,
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
/// 用量: what this step used, as the provider said (zero when it didn't).
pub usage: Usage,
}
/// What a model call used. `input` is the input not read from the prompt cache (OpenAI counts
/// cached tokens inside prompt_tokens; they are taken out here so both kinds read the same).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Usage {
#[serde(default)]
pub input: u64,
#[serde(default)]
pub output: u64,
#[serde(default)]
pub cache_read: u64,
#[serde(default)]
pub cache_write: u64,
/// What it cost in millionths of a dollar, when the provider says (OpenRouter does).
#[serde(default)]
pub cost_micros: u64,
}
impl Usage {
pub fn add(&mut self, o: &Usage) {
self.input += o.input;
self.output += o.output;
self.cache_read += o.cache_read;
self.cache_write += o.cache_write;
self.cost_micros += o.cost_micros;
}
pub fn is_empty(&self) -> bool {
*self == Usage::default()
}
/// An OpenAI-style `usage` object (OpenAI, xAI, OpenRouter, Ollama…).
pub fn of_openai(u: &Value) -> Usage {
let g = |v: &Value| v.as_u64().unwrap_or(0);
let cached = g(&u["prompt_tokens_details"]["cached_tokens"]).max(g(&u["cached_prompt_text_tokens"]));
Usage {
input: g(&u["prompt_tokens"]).saturating_sub(cached),
output: g(&u["completion_tokens"]),
cache_read: cached,
cache_write: 0,
cost_micros: u["cost"].as_f64().map(|c| (c * 1_000_000.0).round() as u64).unwrap_or(0),
}
}
}
/// Why a request failed, sorted the way the error catalog sorts them.
pub struct Failure {
pub msg: String,
pub retryable: bool,
pub retry_after_ms: Option<u64>,
}
impl Failure {
fn retry(msg: String) -> Self {
Failure { msg, retryable: true, retry_after_ms: None }
}
fn fatal(msg: String) -> Self {
Failure { msg, retryable: false, retry_after_ms: None }
}
}
/// Delay before retry `n` (1-based): 1 s, 2 s, 4 s… capped at `max_ms` (4 s while someone watches).
fn backoff_up_to(retry: u32, max_ms: u64) -> u64 {
(RETRY_INITIAL_DELAY_MS * RETRY_BACKOFF_FACTOR.saturating_pow(retry.saturating_sub(1))).min(max_ms)
}
/// 沒人在看的一輪 (a routine, a trigger, a message from a channel or a teammate): a busy or
/// failing model is tried this many times, waiting up to PATIENT_MAX_DELAY_MS between, before the
/// turn gives up — a ten-second hiccup at the provider used to fail a routine at 3 a.m. A turn the
/// person is watching keeps RETRY_MAX_ATTEMPTS (they can press 重試). Like grok-build's 15 tries.
pub const PATIENT_ATTEMPTS: u32 = 8;
pub const PATIENT_MAX_DELAY_MS: u64 = 30_000;
thread_local! {
static PATIENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// This thread's turn is one nobody is watching (set by agent::spawn for its turn).
pub fn set_patient(on: bool) {
PATIENT.with(|p| p.set(on));
}
/// (tries in all, longest wait) for this thread's model calls.
fn retry_budget() -> (u32, u64) {
if PATIENT.with(|p| p.get()) {
(PATIENT_ATTEMPTS, PATIENT_MAX_DELAY_MS)
} else {
(RETRY_MAX_ATTEMPTS, RETRY_MAX_DELAY_MS)
}
}
/// A wait spread by ±20% (many computers coming back from the same outage don't all ask again in
/// the same second).
pub fn jitter(ms: u64) -> u64 {
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0) as u64;
let spread = ms / 5;
if spread == 0 {
return ms;
}
ms - spread + nanos % (2 * spread + 1)
}
fn agent() -> ureq::Agent {
feat: 所有 HTTP 用戶端信任同一份憑證;連接器連同它帶起來的程式一起關;按停止馬上結束連接器的呼叫 工程基礎計畫 E5,參考 grok-build 的 clippy.toml(HTTP 用戶端只能從一個地方建)和 ProcessScope。 - net.rs:net::config() 是所有 HTTP 用戶端的起點,憑證是公開的加上這台電腦自己信任的(tunnel::trusted_roots);net::agent(秒數) 是常用的那種(整個請求的逾時、錯誤狀態當成回答,一種逾時一個、重複用)。18 個自己建 ureq 的地方全部換成 net::config(),各自的逾時、轉址、User-Agent 不變。以前只有連帳號伺服器的那條看這台電腦信任的憑證:公司自己簽憑證的連接器、模型服務、Webhook 在別處會失敗。帳號伺服器的用戶端改用 net::agent,拿掉它自己的那份快取。 - clippy.toml:disallowed-methods 擋 ureq::Agent::config_builder(net.rs 以外)。 - 連接器:關掉、移除、重新連線、連不上時用 tools::kill_tree 連同子行程一起關(npx/uvx/sh 底下真正的伺服器以前留著)。 - mcp::call_until:本機連接器的呼叫每 0.2 秒看一次停止,按停止馬上回「已停止」;伺服器晚到的答案下一次會跳過。用網址連的還是等它回或 120 秒(ureq 的請求停不下來)。 - 測試用的假連接器多一個 slow 工具(FAKE_SLOW=1 才列出,不影響其他測試的工具數)。 已驗證:cargo test 560 全過;cargo clippy 沒有 disallowed 的違規。新測試:按停止 0.3 秒後呼叫在 2 秒內結束、之後同一個連接器照樣能用(sum=3);用 sh 帶起來的連接器關掉後,它帶起來的 sleep 也沒了;所有用戶端的憑證至少是公開那一份。 未驗證:公司自己簽憑證的真的連接器(這台沒有)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:13:59 +00:00
let config = crate::net::config()
.http_status_as_error(false)
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
// Never follow HTTP redirects on model API calls: `x-api-key` is a custom header that
// `ureq` would forward unchanged to an untrusted redirect target, and 301/302 turns POST into GET.
.max_redirects(0)
.timeout_connect(Some(Duration::from_millis(CONNECT_TIMEOUT_MS)))
.timeout_recv_response(Some(Duration::from_secs(FIRST_RESPONSE_TIMEOUT_SECS)))
// A stream that goes silent (a NAT that dropped the mapping, a server that died without
// a FIN) must end: without a read timeout the lines() loop blocks forever, and every
// such turn leaks a thread and its socket. 5 minutes of total silence is a dead stream.
.timeout_per_read(Some(Duration::from_secs(300)))
.build();
config.into()
}
pub fn resolve_key(kind: ProviderKind, stored: &str) -> String {
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// 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();
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if cfg!(test) {
return String::new();
}
kind.env_var().and_then(|v| std::env::var(v).ok()).unwrap_or_default()
}
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
/// The key for a request to `base`: a key from the environment goes only to the service's own
/// 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 {
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
if kind == ProviderKind::ChatGpt {
return resolve_key(kind, stored);
}
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
if !stored.trim().is_empty() {
return stored.trim().to_string();
}
let custom = !stored_base.trim().is_empty() && stored_base.trim().trim_end_matches('/') != kind.default_base_url().trim_end_matches('/');
if custom {
return String::new();
}
resolve_key(kind, stored)
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
/// 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()
}
/// Claude models that take adaptive thinking (older ones reject it).
fn claude_adaptive(model: &str) -> bool {
["claude-opus-5", "claude-sonnet-5", "claude-haiku-5", "claude-fable-5", "claude-mythos-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-sonnet-4-6"]
.iter()
.any(|p| model.starts_with(p))
}
/// Claude models where the server can retry a declined request on another model.
fn claude_fallbacks(model: &str) -> bool {
["claude-opus-5-5", "claude-opus-5", "claude-fable-5-1", "claude-sonnet-5-5"].contains(&model)
}
/// An error body as words: a gateway's HTML error page (「錯誤 502:<!DOCTYPE HTML>…」 filled the
/// chat) becomes its text; anything else is kept as it is.
fn page_words(body: &str) -> String {
if !body.trim_start().starts_with('<') {
return body.to_string();
}
let no_style = body.rsplit("</style>").next().unwrap_or(body);
let mut out = String::new();
let mut in_tag = false;
for c in no_style.chars() {
match c {
'<' => {
in_tag = true;
out.push(' ');
}
'>' => in_tag = false,
_ if !in_tag => out.push(c),
_ => {}
}
}
out.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// An error the model sent inside its answer stream, in words: "at capacity" and the like are
/// waited out and tried again (it came through raw English, as the reply, and was never retried).
fn stream_failure(msg: &str) -> Failure {
let low = msg.to_lowercase();
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
// The same overflow, reported inside the stream instead of as an HTTP 400.
if ["prompt is too long", "maximum context", "context length", "context window", "too many tokens"].iter().any(|k| low.contains(k)) {
return Failure::fatal(format!("{CONTEXT_OVERFLOW}請清除聊天記錄或換一個模型。\n({msg})"));
}
if ["capacity", "overloaded", "rate limit", "too many requests", "try again", "temporarily", "unavailable", "timeout", "timed out"].iter().any(|k| low.contains(k)) {
Failure { msg: format!("模型供應商現在太忙,正在等一下再試。\n({msg})"), retryable: true, retry_after_ms: Some(BUSY_RETRY_MS) }
} else {
Failure::fatal(format!("模型回報錯誤,這一步沒有完成。\n({msg})"))
}
}
/// Wait before asking a busy model again (estimated; it says "a few minutes", 1–4 s was too soon).
const BUSY_RETRY_MS: u64 = 8_000;
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
/// How a "the conversation no longer fits this model" failure starts (SAND-E0404
/// contextWindowOverflow). The turn loop recognizes it by this and folds older messages into a
/// summary before asking once more, instead of giving up.
pub const CONTEXT_OVERFLOW: &str = "對話太長了,超過這個模型能讀的長度。";
fix: 模型說對話太長時自己騰出空間再試——先拿掉截圖、再收起舊結果、再摘要(一輪中間也能切);記下模型真正的上限,把圖當文字算的模型不再傳圖 一台 Linux 換成自訂端點的模型後,一張網頁截圖讓請求從約 1.8 萬 tokens 變成 178,553(上限 131,072):那個端點把圖的 base64 當文字算。AnyBot 一張圖只估 3,200、也沒算工具說明,所以沒先壓縮;模型說太長時,最新 6 則一律保留(截圖就在裡面),這一輪又只有一則指令沒地方摘要,直接報錯;下一輪截圖還在記憶體裡又送一次。 - 模型說太長:依序拿掉圖片(聊天裡的步驟截圖也放掉,下一輪不再送)→ 收起除了最新 2 步以外的長結果 → 摘要(只有一則指令的長回合在這一輪中間切,指令原文保留)→ 都試過才報錯,並說明指示、工具說明、對話各多大 - 從錯誤訊息讀出上限(husky、OpenAI、vLLM、Anthropic 的寫法),比 Bot 設定小就記下來(StreamEvent::ContextLimit) - 實際用量比估算每張圖多 2 萬 tokens 以上(圖被當文字算)時,拿掉圖片成功後這個模型不再傳圖(改用文字描述);看得到圖、只是剛好超過一點的模型照樣看螢幕 - 估算加進工具說明(約 1.2 萬 tokens) 測試:husky 那次的截圖情境、一則指令的長回合、看圖模型只超過一點點、各家錯誤訊息的上限與用量解析。Mac 451 個測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:57:51 +00:00
/// The model's own size, as its "too long" error states it: "the context limit on 'husky' for
/// you is 131072 tokens", "maximum context length is 128000 tokens", "210000 tokens > 200000
/// maximum". None when it doesn't say.
pub fn overflow_limit(msg: &str) -> Option<u64> {
let low = msg.to_lowercase().replace([',', '_'], "");
// Every number of four digits or more, with where it is.
let mut nums: Vec<(usize, usize, u64)> = vec![];
let b = low.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i].is_ascii_digit() {
let start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
if let Ok(n) = low[start..i].parse::<u64>() {
if (1_000..=10_000_000).contains(&n) {
nums.push((start, i, n));
}
}
} else {
i += 1;
}
}
let mut found: Vec<u64> = vec![];
for kw in ["limit", "maximum context length", "context length", "context window", "max context", "maximum", "上限"] {
for (at, _) in low.match_indices(kw) {
let after = at + kw.len();
// A number of tokens shortly after the word ("limit … is 131072 tokens") …
let of_tokens = |e: usize| low[e..].trim_start().starts_with("tok");
if let Some(n) = nums.iter().find(|(s, e, _)| *s >= after && *s - after <= 40 && of_tokens(*e)) {
found.push(n.2);
}
// … or right before it ("200000 maximum").
if let Some(n) = nums.iter().find(|(_, e, _)| *e <= at && at - *e <= 3) {
found.push(n.2);
}
}
}
found.into_iter().min()
}
/// How long the request was, as the "too long" error states it ("Prompt is 178553 tokens",
/// "resulted in 130512 tokens", "210000 tokens > 200000 maximum"): the largest number of tokens
/// it names other than the limit. None when it names no other.
pub fn overflow_prompt(msg: &str) -> Option<u64> {
let low = msg.to_lowercase().replace([',', '_'], "");
let limit = overflow_limit(msg);
let mut best: Option<u64> = None;
let b = low.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i].is_ascii_digit() {
let start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
let n = low[start..i].parse::<u64>().unwrap_or(0);
if (1_000..=100_000_000).contains(&n) && low[i..].trim_start().starts_with("tok") && Some(n) != limit {
best = best.max(Some(n));
}
} else {
i += 1;
}
}
best
}
/// This model is sent no pictures from now on (this run): one made a request too long for it
/// (a gateway that reads a screenshot as text — 160 000 tokens for one). Its screenshots are
/// described in words instead (看圖小幫手), like a model that can't see.
pub fn mark_pictures_too_costly(req: &ChatRequest) {
mark_blind(req);
}
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
/// The request didn't fit the model's context (a retry as-is would fail the same way).
pub fn is_context_overflow(msg: &str) -> bool {
msg.starts_with(CONTEXT_OVERFLOW)
}
fn http_error(status: u16, body: &str, retry_after: Option<u64>) -> Failure {
let detail = serde_json::from_str::<Value>(body)
.ok()
.and_then(|v| {
v.pointer("/error/message")
.or_else(|| v.pointer("/message"))
.or_else(|| v.get("error"))
.map(|m| m.as_str().map(str::to_string).unwrap_or_else(|| m.to_string()))
})
.unwrap_or_else(|| page_words(body).chars().take(300).collect());
let hint = match status {
feat: AnyBot 功能地圖——Bot 用 anybot_guide 認識 AnyBot 本身;修好地圖整理時找到的七個問題 功能地圖(照 Lauren Tan 的 feature map,poteto/verification-skill-example) - docs/feature-map/:20 區加索引,每區四段(子功能/使用者怎麼到/怎麼操作(Bot:、驗證:)/陷阱),內容逐條對照程式;索引寫共同前提、證據與略過的回報、全面檢查順序 - Bot 的系統提示多一行區塊目錄;新工具 anybot_guide 一次讀一區(唯讀) - cargo test featuremap:: 擋漏寫:Bot 能拿到的每個工具、browser/computer 的每個動作、設定視窗每個分頁和區塊、update_settings 的鍵;每區要有四段、不能太長 - 自動學技能:AnyBot 本身怎麼用不抄進技能,地圖錯漏記成待改進;園丁在重複的待改進旁提醒補地圖 - CLAUDE.md:改功能時同一個 commit 一起改地圖 - 側邊欄「分區」工具的說明寫清楚:不是群組聊天 修正 1. 別人傳來的訊息(訊息管道、團隊成員)那一輪不給 AnyBot 瀏覽器、保險庫和已送紀錄(瀏覽器帶著使用者的登入);硬叫也擋下,公開網頁仍可 web_fetch 2. 自動學會的技能加進那個 Bot 自己的技能清單(支線的算主 Bot 的) 3. 按停止一併停掉這個 Bot 的互動終端機(一般背景指令照舊) 4. 設定 › 整合 › 技能、頁面的「刪除」要再按一次確定 5. update_bot 先跳確認卡片,列出每一項要改成什麼 6. Bot 範本的頭像形狀改成存在的形狀,並加測試 7. 文字:直接操作的提示改「設定 → 權限」、金鑰錯誤改「設定 → 模型」、等核准逾時照實說是什麼在等 Mac 490 個測試通過。 Refs: cl3xk7 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:15:09 +00:00
401 | 403 => "金鑰無效或沒有權限,請到「設定 → 模型」檢查。",
404 => "找不到這個模型或網址,請檢查模型名稱。",
429 => "模型供應商已超載或用量已達上限。通常是暫時的,請稍後再試。",
500..=599 => "模型供應商目前負載過高。通常是暫時的。",
_ => "",
};
let lower = detail.to_lowercase();
// SAND-E0404 contextWindowOverflow: a retry would repeat it.
if (status == 400 || status == 413) && ["context", "too long", "too many tokens", "maximum context", "prompt is too long"].iter().any(|k| lower.contains(k)) {
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
return Failure::fatal(format!("{CONTEXT_OVERFLOW}請清除聊天記錄或換一個模型。\n({detail})"));
}
if status == 400 && lower.contains("tool") && (lower.contains("support") || lower.contains("not available")) {
return Failure::fatal(format!("這個模型不支援工具。請換一個支援工具的模型,或在 Bot 設定裡關掉「電腦操作」。\n({detail})"));
}
let msg = format!("錯誤 {status}:{detail}\n{hint}").trim().to_string();
// SAND-E0401 providerOverloaded / SAND-E0408 backendCapacityDeferred: retry.
if status == 429 || status == 408 || status == 529 || status >= 500 {
Failure { msg, retryable: true, retry_after_ms: retry_after }
} else {
Failure::fatal(msg)
}
}
fn retry_after_ms(resp: &ureq::http::Response<ureq::Body>) -> Option<u64> {
let v = resp.headers().get("retry-after")?.to_str().ok()?;
v.trim().parse::<f64>().ok().map(|s| (s * 1000.0) as u64).map(|ms| ms.min(RETRY_AFTER_CAP_MS))
}
/// One model call with the original's retry rules: retry overloads, resets and unreachable
/// backends up to 3 tries (1 s, 2 s, 4 s or Retry-After), but never once output reached the screen.
pub fn run_step(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, String> {
繁體中文、換電腦: what a model writes is put into Traditional Chinese whatever the setting's system; a work folder from another computer lands under this home - 繁體中文: converted at the one place every model call comes back (providers::run_step), decided from the request itself: the setting is 繁體中文, or it follows the system and the person writes Traditional. It used to be on only for the explicit setting, so a brain on an English server with 跟著系統 never converted, whatever the instructions said. Not when another language is chosen, nor when the latest message asks for Simplified. - Converted: the reply, the thinking, and steps whose words are for the person (question card, card, page, memory, routine). Left as written: code blocks and `inline code`, a line of Japanese, file names, commands, searches, recipients. - Taiwan wording after the characters: about 55 one-meaning computer terms (網絡→網路, 文件夾→資料夾, 默認→預設…), and zhconv's OpenCC tables on (设置里的 → 設定裡的). - The reply instruction says it too: no Simplified characters, no mainland wording. - 換電腦: a bot's work folder chosen on one computer (/Users/daniel on a Mac) no longer breaks every file and command step on another (Linux, another user). It is sent as ~/… with the folder as chosen alongside; the receiving computer uses the folder if it is there, else the same place under its own home, else its home. - FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:29:02 +00:00
// 繁體中文: what the model writes for the person, in Traditional Chinese whatever it wrote
// (see i18n::wants_hant) — as it streams, and in what the step comes to.
if !crate::i18n::wants_hant(&req.system, &req.history) {
return run_step_as_written(req, cancel, send);
}
use crate::i18n::hant;
let in_hant = |ev: StreamEvent| {
send(match ev {
StreamEvent::Text(t) => StreamEvent::Text(hant(&t)),
StreamEvent::Thinking(t) => StreamEvent::Thinking(hant(&t)),
StreamEvent::ToolCall(c) => StreamEvent::ToolCall(hant_call(c)),
other => other,
})
};
let mut out = run_step_as_written(req, cancel, &in_hant)?;
out.text = hant(&out.text);
out.thinking = hant(&out.thinking);
out.tool_calls = out.tool_calls.into_iter().map(hant_call).collect();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
// Keep Anthropic's `blocks` consistent with `text` and `tool_calls` (never touching `thinking`
// blocks, which carry cryptographic signatures).
for b in out.blocks.iter_mut() {
match b["type"].as_str() {
Some("text") => {
if let Some(t) = b["text"].as_str().map(hant) {
b["text"] = json!(t);
}
}
Some("tool_use") => {
let name = b["name"].as_str().unwrap_or("");
if WORDS_FOR_THE_PERSON.contains(&name) {
hant_json_fields(&mut b["input"]);
}
}
_ => {}
}
}
繁體中文、換電腦: what a model writes is put into Traditional Chinese whatever the setting's system; a work folder from another computer lands under this home - 繁體中文: converted at the one place every model call comes back (providers::run_step), decided from the request itself: the setting is 繁體中文, or it follows the system and the person writes Traditional. It used to be on only for the explicit setting, so a brain on an English server with 跟著系統 never converted, whatever the instructions said. Not when another language is chosen, nor when the latest message asks for Simplified. - Converted: the reply, the thinking, and steps whose words are for the person (question card, card, page, memory, routine). Left as written: code blocks and `inline code`, a line of Japanese, file names, commands, searches, recipients. - Taiwan wording after the characters: about 55 one-meaning computer terms (網絡→網路, 文件夾→資料夾, 默認→預設…), and zhconv's OpenCC tables on (设置里的 → 設定裡的). - The reply instruction says it too: no Simplified characters, no mainland wording. - 換電腦: a bot's work folder chosen on one computer (/Users/daniel on a Mac) no longer breaks every file and command step on another (Linux, another user). It is sent as ~/… with the folder as chosen alongside; the receiving computer uses the folder if it is there, else the same place under its own home, else its home. - FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:29:02 +00:00
Ok(out)
}
/// Steps whose words are for the person to read (a question card, a card, a page, a memory, a
/// routine's name and task): their arguments are converted too. Not the others — a file's
/// name, a command, a search or a mail's recipient must stay as written.
const WORDS_FOR_THE_PERSON: &[&str] = &[crate::ask::TOOL, "show_card", "write_page", "remember", "create_routine", "update_routine"];
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
/// Convert human-prose string fields inside a parsed JSON object (so `\n` is real newlines and
/// fenced code blocks ```` ``` ```` stay untouched), skipping identifiers, URLs, schedules and lookup keys.
fn hant_json_fields(v: &mut Value) {
const KEEP_AS_IS: &[&str] = &["id", "bot", "kind", "link", "url", "schedule", "timezone", "time", "computer", "replaces", "trigger"];
match v {
Value::String(s) => *s = crate::i18n::hant(s),
Value::Array(a) => a.iter_mut().for_each(hant_json_fields),
Value::Object(m) => {
for (k, val) in m.iter_mut() {
if !KEEP_AS_IS.contains(&k.as_str()) {
hant_json_fields(val);
}
}
}
_ => {}
}
}
繁體中文、換電腦: what a model writes is put into Traditional Chinese whatever the setting's system; a work folder from another computer lands under this home - 繁體中文: converted at the one place every model call comes back (providers::run_step), decided from the request itself: the setting is 繁體中文, or it follows the system and the person writes Traditional. It used to be on only for the explicit setting, so a brain on an English server with 跟著系統 never converted, whatever the instructions said. Not when another language is chosen, nor when the latest message asks for Simplified. - Converted: the reply, the thinking, and steps whose words are for the person (question card, card, page, memory, routine). Left as written: code blocks and `inline code`, a line of Japanese, file names, commands, searches, recipients. - Taiwan wording after the characters: about 55 one-meaning computer terms (網絡→網路, 文件夾→資料夾, 默認→預設…), and zhconv's OpenCC tables on (设置里的 → 設定裡的). - The reply instruction says it too: no Simplified characters, no mainland wording. - 換電腦: a bot's work folder chosen on one computer (/Users/daniel on a Mac) no longer breaks every file and command step on another (Linux, another user). It is sent as ~/… with the folder as chosen alongside; the receiving computer uses the folder if it is there, else the same place under its own home, else its home. - FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:29:02 +00:00
fn hant_call(mut c: ToolCall) -> ToolCall {
if WORDS_FOR_THE_PERSON.contains(&c.name.as_str()) {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if let Ok(mut v) = serde_json::from_str::<Value>(&c.args) {
hant_json_fields(&mut v);
if let Ok(s) = serde_json::to_string(&v) {
c.args = s;
}
}
繁體中文、換電腦: what a model writes is put into Traditional Chinese whatever the setting's system; a work folder from another computer lands under this home - 繁體中文: converted at the one place every model call comes back (providers::run_step), decided from the request itself: the setting is 繁體中文, or it follows the system and the person writes Traditional. It used to be on only for the explicit setting, so a brain on an English server with 跟著系統 never converted, whatever the instructions said. Not when another language is chosen, nor when the latest message asks for Simplified. - Converted: the reply, the thinking, and steps whose words are for the person (question card, card, page, memory, routine). Left as written: code blocks and `inline code`, a line of Japanese, file names, commands, searches, recipients. - Taiwan wording after the characters: about 55 one-meaning computer terms (網絡→網路, 文件夾→資料夾, 默認→預設…), and zhconv's OpenCC tables on (设置里的 → 設定裡的). - The reply instruction says it too: no Simplified characters, no mainland wording. - 換電腦: a bot's work folder chosen on one computer (/Users/daniel on a Mac) no longer breaks every file and command step on another (Linux, another user). It is sent as ~/… with the folder as chosen alongside; the receiving computer uses the folder if it is there, else the same place under its own home, else its home. - FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:29:02 +00:00
}
c
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
pub(crate) fn run_step_as_written(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, String> {
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
let out = run_step_unbooked(req, cancel, send);
// 用量: every model call is written down (usage.rs), whoever made it.
if let Ok(o) = &out {
crate::usage::note(req, &o.usage);
}
out
}
fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, String> {
// The bot's instructions and tool descriptions in this system's words ("this computer" on Linux).
#[cfg(not(target_os = "macos"))]
let localized = {
let mut r = req.clone();
r.system = crate::platform::localize(&r.system);
r.tools.iter_mut().for_each(crate::platform::localize_value);
r
};
#[cfg(not(target_os = "macos"))]
let req = &localized;
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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() {
feat: AnyBot 功能地圖——Bot 用 anybot_guide 認識 AnyBot 本身;修好地圖整理時找到的七個問題 功能地圖(照 Lauren Tan 的 feature map,poteto/verification-skill-example) - docs/feature-map/:20 區加索引,每區四段(子功能/使用者怎麼到/怎麼操作(Bot:、驗證:)/陷阱),內容逐條對照程式;索引寫共同前提、證據與略過的回報、全面檢查順序 - Bot 的系統提示多一行區塊目錄;新工具 anybot_guide 一次讀一區(唯讀) - cargo test featuremap:: 擋漏寫:Bot 能拿到的每個工具、browser/computer 的每個動作、設定視窗每個分頁和區塊、update_settings 的鍵;每區要有四段、不能太長 - 自動學技能:AnyBot 本身怎麼用不抄進技能,地圖錯漏記成待改進;園丁在重複的待改進旁提醒補地圖 - CLAUDE.md:改功能時同一個 commit 一起改地圖 - 側邊欄「分區」工具的說明寫清楚:不是群組聊天 修正 1. 別人傳來的訊息(訊息管道、團隊成員)那一輪不給 AnyBot 瀏覽器、保險庫和已送紀錄(瀏覽器帶著使用者的登入);硬叫也擋下,公開網頁仍可 web_fetch 2. 自動學會的技能加進那個 Bot 自己的技能清單(支線的算主 Bot 的) 3. 按停止一併停掉這個 Bot 的互動終端機(一般背景指令照舊) 4. 設定 › 整合 › 技能、頁面的「刪除」要再按一次確定 5. update_bot 先跳確認卡片,列出每一項要改成什麼 6. Bot 範本的頭像形狀改成存在的形狀,並加測試 7. 文字:直接操作的提示改「設定 → 權限」、金鑰錯誤改「設定 → 模型」、等核准逾時照實說是什麼在等 Mac 490 個測試通過。 Refs: cl3xk7 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:15:09 +00:00
return Err(format!("還沒有設定 {} 的 API 金鑰。請到「設定 → 模型」貼上金鑰。", req.kind.label()));
}
let produced = std::cell::Cell::new(false);
let tracked = |ev: StreamEvent| {
if matches!(ev, StreamEvent::Text(_) | StreamEvent::Thinking(_) | StreamEvent::ToolCall(_)) {
produced.set(true);
}
send(ev);
};
let mut attempt = 1;
// 沒人在看的一輪 waits longer (set_patient).
let (tries, longest) = retry_budget();
// Steps left without a result (stopped while waiting for the person) are closed off.
let repaired = ChatRequest { history: repair_history(&req.history), ..req.clone() };
let req = &repaired;
let mut blind_copy: Option<ChatRequest> = None;
loop {
// A model that can't see pictures gets the request without them: the person's pictures
// and the newest screenshot described by a model that can (看圖小幫手).
if !sees_images(req) && blind_copy.is_none() {
blind_copy = Some(if DESCRIBING.with(|d| d.get()) { without_images(req) } else { with_descriptions(req, cancel, send) });
}
let req = blind_copy.as_ref().unwrap_or(req);
let result = match req.kind {
ProviderKind::Anthropic => stream_anthropic(req, cancel, &tracked),
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
ProviderKind::ChatGpt => stream_responses(req, cancel, &tracked),
ProviderKind::OpenCodeGo => {
let mut r = req.clone();
if opencode_go_style(&req.base_url, &req.model) == "messages" {
r.base_url = format!("{}/anthropic/v1", req.base_url);
stream_anthropic(&r, cancel, &tracked)
} else {
r.base_url = format!("{}/openai/v1", req.base_url);
stream_openai_compatible(&r, cancel, &tracked)
}
}
_ => stream_openai_compatible(req, cancel, &tracked),
};
match result {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
// Nothing at all came back (no words, no tool call): a dropped stream or a hiccup. The
// turn used to end on 「(沒有回應內容)」; ask again instead.
Ok(out) if out.text.trim().is_empty() && out.tool_calls.is_empty() && !produced.get() && attempt < tries && !cancel.load(Ordering::Relaxed) => {
send(StreamEvent::Retrying(format!("模型這次沒有回任何內容,再問一次(第 {} 次,共 {tries} 次)…", attempt + 1)));
std::thread::sleep(Duration::from_millis(jitter(backoff_up_to(attempt, longest))));
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
attempt += 1;
}
Ok(out) => return Ok(out),
Err(f) if image_refused(&f.msg) && sees_images(req) && !produced.get() && !cancel.load(Ordering::Relaxed) => {
mark_blind(req);
send(StreamEvent::Retrying("這個模型不能看圖片,改成不附圖片再試一次…".into()));
}
Err(f) if f.retryable && !produced.get() && attempt < tries && !cancel.load(Ordering::Relaxed) => {
// (The provider's own Retry-After as it says; our own wait spread a little.)
let wait = f.retry_after_ms.unwrap_or_else(|| jitter(backoff_up_to(attempt, longest)));
send(StreamEvent::Retrying(format!("{}\n{:.0} 秒後重試(第 {} 次,共 {tries} 次)…", f.msg, wait as f64 / 1000.0, attempt + 1)));
let until = std::time::Instant::now() + Duration::from_millis(wait);
while std::time::Instant::now() < until {
if cancel.load(Ordering::Relaxed) {
return Ok(StepOutput::default());
}
std::thread::sleep(Duration::from_millis(100));
}
attempt += 1;
}
Err(f) => return Err(f.msg),
}
}
}
fn read_sse(body: ureq::Body, cancel: &AtomicBool, send: &dyn Fn(StreamEvent), on_data: impl FnMut(&str, &str) -> bool) -> Result<(), Failure> {
read_sse_from(body.into_reader(), cancel, send, on_data)
}
fn read_sse_from(r: impl std::io::Read, cancel: &AtomicBool, send: &dyn Fn(StreamEvent), mut on_data: impl FnMut(&str, &str) -> bool) -> Result<(), Failure> {
let reader = BufReader::new(r);
let mut event = String::new();
for line in reader.lines() {
if cancel.load(Ordering::Relaxed) {
return Ok(());
}
// SAND-E0403 streamReset: retryable.
let line = line.map_err(|e| Failure::retry(format!("連線中斷:{e}")))?;
send(StreamEvent::Alive);
if let Some(ev) = line.strip_prefix("event:") {
event = ev.trim().to_string();
} else if let Some(data) = line.strip_prefix("data:") {
if !on_data(&event, data.trim()) {
return Ok(());
}
} else if line.is_empty() {
event.clear();
}
}
Ok(())
}
/// Summaries become part of the system prompt; everything else stays in order.
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
/// A person's words and, after them, what AnyBot adds to every message (送出時間, memories).
fn with_context(m: &Message) -> String {
if m.context.is_empty() {
m.text.clone()
} else {
format!("{}\n\n{}", m.text, m.context)
}
}
fn system_with_summaries(req: &ChatRequest) -> String {
let mut s = req.system.clone();
for m in req.history.iter().filter(|m| m.summary) {
s.push_str("\n\n先前對話的摘要:\n");
s.push_str(&m.text);
}
s
}
/// Which messages still show their screenshots: the newest `KEEP_SCREENSHOTS`.
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
pub(crate) fn kept_images(history: &[Message]) -> Vec<usize> {
let mut idx: Vec<usize> = history.iter().enumerate().filter(|(_, m)| !m.images.is_empty() && !m.summary && m.role == Role::Tool).map(|(i, _)| i).collect();
let drop = idx.len().saturating_sub(crate::computer::KEEP_SCREENSHOTS);
idx.drain(..drop);
idx
}
const OLD_SCREENSHOT_NOTE: &str = "(較早的截圖已省略)";
/// Said in place of a screenshot when the model can't take pictures.
const BLIND_SCREENSHOT_NOTE: &str = "(截圖已拍好,但這個模型看不到圖片,所以沒有附上。請改用文字方式確認畫面,例如讀取視窗或網頁的文字。)";
/// What a helper is asked about a screenshot.
const SCREEN_ASK: &str = "這是一台電腦螢幕的截圖。請描述:開著哪些視窗或 App、畫面上的文字(照抄重要的字)、按鈕和欄位,以及它們大約的位置(以這張圖的像素座標,左上角是 0,0)。不要猜看不清楚的字。";
const BLIND_ATTACHMENT_NOTE: &str = "(使用者附了圖片,但這個模型看不到圖片。)";
/// Models (base url + name) that refused a picture: later requests leave pictures out.
static NO_VISION: std::sync::Mutex<Option<std::collections::HashSet<String>>> = std::sync::Mutex::new(None);
fn vision_key(req: &ChatRequest) -> String {
format!("{}|{}", req.base_url, req.model)
}
pub fn sees_images(req: &ChatRequest) -> bool {
!NO_VISION.lock().unwrap().as_ref().map(|s| s.contains(&vision_key(req))).unwrap_or(false)
}
fn mark_blind(req: &ChatRequest) {
NO_VISION.lock().unwrap().get_or_insert_with(Default::default).insert(vision_key(req));
}
/// The provider said this model can't take images ("At most 0 image(s)…", "does not support
/// image input", "unknown variant `image_url`"…).
pub fn image_refused(msg: &str) -> bool {
let l = msg.to_lowercase();
let about_images = l.contains("image") || l.contains("vision") || l.contains("multimodal") || l.contains("圖片") || l.contains("图片");
about_images && ["at most 0", "not support", "unsupported", "doesn't support", "does not support", "no vision", "not a vision", "not multimodal", "not a multimodal", "unknown variant", "invalid type", "only text", "text-only", "不支援", "不支持"].iter().any(|k| l.contains(k))
}
/// Every tool call needs its result right after it (providers refuse the conversation
/// otherwise). A step stopped or refused while it waited for the person has none: give it one.
/// Results whose call is gone are dropped.
pub fn repair_history(history: &[Message]) -> Vec<Message> {
let mut out: Vec<Message> = Vec::with_capacity(history.len());
let mut i = 0;
while i < history.len() {
let m = &history[i];
if m.role == Role::Tool {
// A result with no call right before it.
i += 1;
continue;
}
out.push(m.clone());
i += 1;
if m.role == Role::Assistant && !m.tool_calls.is_empty() {
let ids: Vec<&str> = m.tool_calls.iter().map(|c| c.id.as_str()).collect();
let mut seen = vec![];
while i < history.len() && history[i].role == Role::Tool {
let r = &history[i];
if ids.contains(&r.tool_call_id.as_str()) && !seen.contains(&r.tool_call_id) {
seen.push(r.tool_call_id.clone());
out.push(r.clone());
}
i += 1;
}
for c in &m.tool_calls {
if !seen.contains(&c.id) {
let why = if c.status == ToolStatus::Denied { "(使用者沒有允許這個步驟,所以沒有執行。)" } else { "(這個步驟被中止了,沒有執行完。)" };
out.push(Message::tool_result(&c.id, &c.name, why));
}
}
}
}
out
}
// ---------- 看圖小幫手 ----------
/// A model of the person's that sees pictures (another provider, or another model).
#[derive(Clone, Debug, PartialEq)]
pub struct Eyes {
pub kind: ProviderKind,
pub base_url: String,
pub api_key: String,
pub model: String,
}
static EYES: std::sync::Mutex<Vec<Eyes>> = std::sync::Mutex::new(Vec::new());
thread_local! {
/// Inside a helper's own call (it never asks a helper itself).
static DESCRIBING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// The models to ask, best first (the app sets this from the person's providers).
pub fn set_eyes(v: Vec<Eyes>) {
*EYES.lock().unwrap() = v;
}
/// The helper list, the description cache and the failure list are process-wide: tests that
/// touch them must run one at a time, from a clean slate, or they undo each other (the
/// describe cache hit in one test made another's helper never get called).
#[cfg(test)]
pub fn vision_test_guard() -> std::sync::MutexGuard<'static, ()> {
static L: std::sync::Mutex<()> = std::sync::Mutex::new(());
let g = L.lock().unwrap_or_else(|e| e.into_inner());
notes().lock().unwrap().clear();
failed_eyes().lock().unwrap().clear();
set_eyes(vec![]);
set_cloud_eyes_for(vec![]);
g
}
/// Models likely to see pictures, by provider.
pub fn seeing_models(kind: ProviderKind) -> &'static [&'static str] {
match kind {
ProviderKind::Xai => &["grok-4", "grok-4-fast"],
ProviderKind::Anthropic => &["claude-sonnet-5-5", "claude-haiku-5-5"],
ProviderKind::OpenAi => &["gpt-5-mini", "gpt-4.1"],
ProviderKind::Gemini => &["gemini-2.5-flash"],
ProviderKind::OpenRouter => &["openrouter/auto"],
_ => &[],
}
}
const EYES_PROMPT: &str = "你是「看圖小幫手」:替一個看不到圖片的 AI 助理看圖。用繁體中文把圖片完整描述出來,讓它不用看圖也能幫使用者:畫面是什麼、主要的東西和位置、所有看得到的文字(原文照抄,包括數字、表格、按鈕和錯誤訊息)、顏色或狀態等重點。只描述,不評論、不問問題、不說你是誰。";
/// Descriptions already made (by the picture), kept across restarts.
fn notes_path() -> std::path::PathBuf {
crate::model::State::path().with_file_name("image-notes.json")
}
fn notes() -> &'static std::sync::Mutex<std::collections::HashMap<String, (String, String)>> {
static N: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, (String, String)>>> = std::sync::OnceLock::new();
N.get_or_init(|| std::sync::Mutex::new(if cfg!(test) { Default::default() } else { std::fs::read(notes_path()).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() }))
}
/// Helpers that just failed (wrong model name, no credit, down…), skipped for a while.
fn failed_eyes() -> &'static std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>> {
static F: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> = std::sync::OnceLock::new();
F.get_or_init(Default::default)
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
fn picture_key(b64: &str, screen: bool) -> String {
let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
ctx.update(if screen { b"screen:" } else { b"attach:" });
ctx.update(b64.as_bytes());
let d = ctx.finish();
d.as_ref()[..12].iter().map(|b| format!("{b:02x}")).collect()
}
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
pub(crate) fn is_local_model(kind: ProviderKind, base_url: &str) -> bool {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if kind == ProviderKind::Ollama {
return true;
}
!crate::web::is_private_browser_url(base_url).eq(&false)
}
/// The local or LAN servers (their addresses) whose pictures a cloud model may describe: the
/// person turned it on for that provider (設定 › 模型, ProviderSettings::cloud_eyes).
static CLOUD_EYES_FOR: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
pub fn set_cloud_eyes_for(bases: Vec<String>) {
*CLOUD_EYES_FOR.lock().unwrap() = bases;
}
/// Pictures of a bot on this model stay with local helpers only: a local or LAN model, unless
/// the person let a cloud model look for it.
fn keeps_pictures_here(kind: ProviderKind, base_url: &str) -> bool {
let same = |a: &str| a.trim().trim_end_matches('/') == base_url.trim().trim_end_matches('/');
is_local_model(kind, base_url) && !CLOUD_EYES_FOR.lock().unwrap().iter().any(|b| same(b))
}
/// Ask the first helper that can see pictures to describe this one: (description, model).
/// Every picture is looked at once: the note is kept by the picture's own hash, so the same
/// picture in a later send costs nothing. A bot that needs more than the note gives it a fresh,
/// question-shaped look through describe_fresh (the look_image tool).
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
fn describe(picture: &str, ask: &str, screen: bool, not: &ChatRequest, cancel: &AtomicBool) -> Option<(String, String)> {
let key = picture_key(picture, screen);
if let Some(n) = notes().lock().unwrap().get(&key) {
return Some(n.clone());
}
let note = ask_eyes(picture, ask, not, cancel)?;
let mut all = notes().lock().unwrap();
if all.len() > 500 {
all.clear();
}
all.insert(key, note.clone());
if let (false, Ok(b)) = (cfg!(test), serde_json::to_vec(&*all)) {
let _ = crate::httpd::write_private(&notes_path(), &b);
}
Some(note)
}
/// One fresh look at a picture for a specific question: the cache is skipped (the question
/// changes, the picture doesn't), and the answer is not kept as the picture's note.
pub fn describe_fresh(picture: &str, ask: &str, not: &ChatRequest, cancel: &AtomicBool) -> Option<(String, String)> {
ask_eyes(picture, ask, not, cancel)
}
fn ask_eyes(picture: &str, ask: &str, not: &ChatRequest, cancel: &AtomicBool) -> Option<(String, String)> {
let keep_local = keeps_pictures_here(not.kind, &not.base_url);
let helpers: Vec<Eyes> = EYES.lock().unwrap().clone();
for e in helpers {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
// Privacy boundary: when the bot's own model is local/private (Ollama or LAN server),
// never send its screenshots or attachments out to an external cloud provider behind the
// person's back (only when they said so for that provider).
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if keep_local && !is_local_model(e.kind, &e.base_url) {
continue;
}
let req = ChatRequest {
kind: e.kind,
base_url: e.base_url.clone(),
api_key: e.api_key.clone(),
model: e.model.clone(),
system: EYES_PROMPT.into(),
history: vec![Message { images: vec![picture.to_string()], ..Message::user(ask) }],
tools: vec![],
session: String::new(), effort: String::new(),
};
let id = vision_key(&req);
let resting = failed_eyes().lock().unwrap().get(&id).map(|t| t.elapsed().as_secs() < 600).unwrap_or(false);
if (req.base_url == not.base_url && req.model == not.model) || !sees_images(&req) || resting || cancel.load(Ordering::Relaxed) {
continue;
}
DESCRIBING.with(|d| d.set(true));
let out = run_step(&req, cancel, &|_| {});
DESCRIBING.with(|d| d.set(false));
match out {
// It may have turned out not to see pictures after all (and answered without).
Ok(o) if sees_images(&req) && !o.text.trim().is_empty() => return Some((o.text.trim().to_string(), e.model.clone())),
_ => {
failed_eyes().lock().unwrap().insert(id, std::time::Instant::now());
}
}
}
None
}
/// The request for a model that can't see pictures: each of the person's pictures replaced by
/// what a helper saw in it; screenshots by a short note. Only the newest few attachment
/// messages carry their full description: older ones travel as a one-line caption (the model
/// can always ask for a fresh look with look_image), so a long chat with many pictures doesn't
/// carry every picture's essay on every send.
fn with_descriptions(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> ChatRequest {
let mut r = req.clone();
let mut told = false;
// The newest screenshot is described too (what the bot needs to act next); older ones stay a note.
let newest_shot = r.history.iter().rposition(|m| m.role == Role::Tool && !m.images.is_empty());
// The last two attachment messages keep the full description; older ones get a caption.
const KEEP_FULL: usize = 2;
let keep_full: std::collections::HashSet<usize> = r.history.iter().enumerate().filter(|(_, m)| !m.images.is_empty() && m.role == Role::User).map(|(i, _)| i).rev().take(KEEP_FULL).collect();
// Every picture in the chat, oldest first: an image's index for look_image counts from the newest back.
let all_keys: Vec<String> = r.history.iter().flat_map(|m| m.images.iter().map(|p| picture_key(p, m.role == Role::Tool))).collect();
let rank_of = |k: &str| all_keys.iter().rposition(|x| x == k).map(|pos| all_keys.len() - 1 - pos).unwrap_or(0);
for (i, m) in r.history.iter_mut().enumerate().filter(|(_, m)| !m.images.is_empty()) {
if m.role == Role::Tool {
let pictures = std::mem::take(&mut m.images);
let seen = if Some(i) == newest_shot {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if !told && !notes().lock().unwrap().contains_key(&picture_key(&pictures[0], true)) {
send(StreamEvent::Retrying("這個模型看不到圖片,正在請另一個看得懂圖的模型看這張截圖…".into()));
told = true;
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
describe(&pictures[0], SCREEN_ASK, true, req, cancel)
} else {
None
};
let add = match seen {
Some((d, model)) => format!("(截圖已拍好;你看不到圖片,以下是「{model}」看過這張截圖後的描述)\n{d}"),
None => BLIND_SCREENSHOT_NOTE.to_string(),
};
m.text = if m.text.is_empty() { add } else { format!("{}\n{add}", m.text) };
continue;
}
let pictures = std::mem::take(&mut m.images);
let msg_i = i;
let ask = format!("請描述這張圖片。使用者附上它時說:「{}」", m.text.chars().take(300).collect::<String>());
let mut added = String::new();
for (j, p) in pictures.iter().enumerate() {
let which = if pictures.len() > 1 { format!("第 {} 張圖片", j + 1) } else { "這張圖片".to_string() };
// An old attachment: the note stays out of the prompt, only its first line travels.
if !keep_full.contains(&msg_i) {
if let Some((d, _)) = notes().lock().unwrap().get(&picture_key(p, false)) {
let head: String = d.chars().take(140).collect::<String>().trim().to_string();
added.push_str(&format!("\n\n({which}是較早的圖片,只留摘要:「{head}…」需要圖裡的細節、小字或精確數字,用 look_image 工具重新看它(index={},從最近一張圖往回数)。)", rank_of(&picture_key(p, false))));
continue;
}
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if !told && !notes().lock().unwrap().contains_key(&picture_key(p, false)) {
send(StreamEvent::Retrying("這個模型看不到圖片,正在請另一個看得懂圖的模型先看一遍…".into()));
told = true;
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
added.push_str(&match describe(p, &ask, false, req, cancel) {
Some((d, model)) => format!("\n\n(你看不到圖片;以下是「{model}」看過{which}後的描述)\n{d}"),
None => format!("\n\n{BLIND_ATTACHMENT_NOTE}(帳號裡也沒有看得懂圖片的模型可以代看。可以請使用者到「設定 › 模型」加一個,例如 Grok、Claude、GPT 或 Gemini。)"),
});
}
m.text.push_str(&added);
}
r
}
/// The same request with pictures replaced by a short note.
fn without_images(req: &ChatRequest) -> ChatRequest {
let mut r = req.clone();
for m in r.history.iter_mut().filter(|m| !m.images.is_empty()) {
m.images.clear();
let note = if m.role == Role::Tool { BLIND_SCREENSHOT_NOTE } else { BLIND_ATTACHMENT_NOTE };
m.text = if m.text.is_empty() { note.to_string() } else { format!("{}\n{note}", m.text) };
}
r
}
pub fn openai_messages(req: &ChatRequest) -> Vec<Value> {
let mut messages = vec![];
let system = system_with_summaries(req);
if !system.trim().is_empty() {
messages.push(json!({"role": "system", "content": system}));
}
let kept = kept_images(&req.history);
// Tool messages carry text only; their screenshots follow as one user message after the run
// of tool results (a user message between tool results would break the call/answer pairs).
let mut pending: Vec<Value> = vec![];
let flush = |messages: &mut Vec<Value>, pending: &mut Vec<Value>| {
if !pending.is_empty() {
let mut parts = vec![json!({"type": "text", "text": "(上面工具的螢幕截圖)"})];
parts.append(pending);
messages.push(json!({"role": "user", "content": parts}));
}
};
for (i, m) in req.history.iter().enumerate().filter(|(_, m)| !m.summary) {
if m.role != Role::Tool {
flush(&mut messages, &mut pending);
}
match m.role {
Role::User if !m.images.is_empty() => {
// Attached pictures go with the person's words.
let mut parts = vec![json!({"type": "text", "text": if m.text.is_empty() { "(附件)".to_string() } else { m.text.clone() }})];
parts.extend(m.images.iter().map(|b| json!({"type": "image_url", "image_url": {"url": format!("data:image/jpeg;base64,{b}")}})));
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
if !m.context.is_empty() {
parts.push(json!({"type": "text", "text": m.context}));
}
messages.push(json!({"role": "user", "content": parts}));
}
Role::User => {
if !m.text.is_empty() {
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
messages.push(json!({"role": "user", "content": with_context(m)}));
}
}
Role::Assistant => {
if m.error && m.tool_calls.is_empty() {
continue;
}
if m.tool_calls.is_empty() {
if !m.text.is_empty() {
messages.push(json!({"role": "assistant", "content": m.text}));
}
} else {
let calls: Vec<Value> = m.tool_calls.iter().map(|c| json!({"id": c.id, "type": "function", "function": {"name": c.name, "arguments": if c.args.trim().is_empty() { "{}" } else { &c.args }}})).collect();
messages.push(json!({"role": "assistant", "content": if m.text.is_empty() { Value::Null } else { json!(m.text) }, "tool_calls": calls}));
}
}
Role::Tool => {
let shown = kept.contains(&i);
let text = if !m.images.is_empty() && !shown { format!("{}\n{OLD_SCREENSHOT_NOTE}", m.text) } else { m.text.clone() };
messages.push(json!({"role": "tool", "tool_call_id": m.tool_call_id, "content": text}));
if shown {
pending.extend(m.images.iter().map(|b| json!({"type": "image_url", "image_url": {"url": format!("data:image/jpeg;base64,{b}")}})));
}
}
}
}
flush(&mut messages, &mut pending);
messages
}
/// 思考模式 rides along as `reasoning_effort`; a model that answers 400 to it (many don't take
/// one) gets the same request without it, and isn't sent it again.
fn stream_openai_compatible(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
let key = (req.base_url.clone(), req.model.clone());
let effort = effort_of(req).filter(|_| !effort_refused().lock().unwrap().contains(&key));
match stream_openai_with(req, effort, cancel, send) {
Err(f) if effort.is_some() && refuses_effort(&f) => {
effort_refused().lock().unwrap().insert(key);
stream_openai_with(req, None, cancel, send)
}
r => r,
}
}
fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
let mut body = json!({"model": req.model, "messages": openai_messages(req), "stream": true});
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
// 用量: the last chunk says what the answer used (where the service is known to take this).
if matches!(req.kind, ProviderKind::OpenAi | ProviderKind::Xai | ProviderKind::OpenRouter) {
body["stream_options"] = json!({"include_usage": true});
}
if let Some(e) = effort {
body["reasoning_effort"] = json!(e);
}
if !req.tools.is_empty() {
body["tools"] = json!(req.tools.iter().map(|t| json!({"type": "function", "function": t})).collect::<Vec<_>>());
}
let url = format!("{}/chat/completions", req.base_url);
let mut headers: Vec<(String, String)> = vec![];
if !req.api_key.is_empty() {
headers.push(("Authorization".into(), format!("Bearer {}", req.api_key)));
}
if req.kind == ProviderKind::OpenRouter {
headers.push(("X-Title".into(), "AnyBot".into()));
}
if req.kind == ProviderKind::OpenCodeGo {
headers.push(("x-opencode-session".into(), opencode_session(req)));
}
// A brain on a server, a model on the person's own network: through their computer (the
// whole answer comes back at once, so no word-by-word streaming).
let via_hands: Option<Vec<u8>> = match crate::remote::model_hands_for(&url) {
Some(hand) => {
let (status, bytes) = crate::remote::model_via_hands(&hand, &url, &headers, &body.to_string()).map_err(Failure::retry)?;
if status >= 400 {
return Err(http_error(status, &String::from_utf8_lossy(&bytes), None));
}
Some(bytes)
}
None => None,
};
let resp = match via_hands {
Some(_) => None,
None => {
let mut r = agent().post(&url).header("Content-Type", "application/json");
for (k, v) in &headers {
r = r.header(k, v);
}
// SAND-E0418 turnBackendUnreachable: retryable.
let resp = r.send_json(&body).map_err(|e| Failure::retry(connect_error(req.kind, &e.to_string())))?;
let status = resp.status().as_u16();
if status >= 400 {
let ra = retry_after_ms(&resp);
let text = resp.into_body().read_to_string().unwrap_or_default();
return Err(http_error(status, &text, ra));
}
Some(resp)
}
};
let mut out = StepOutput::default();
// Tool calls arrive in pieces keyed by index.
let mut pending: Vec<(String, String, String)> = vec![];
let mut error = None;
let reader: Box<dyn std::io::Read> = match (resp, via_hands) {
(Some(r), _) => Box::new(r.into_body().into_reader()),
(None, b) => Box::new(std::io::Cursor::new(b.unwrap_or_default())),
};
read_sse_from(reader, cancel, send, |_ev, data| {
if data == "[DONE]" {
return false;
}
if let Ok(v) = serde_json::from_str::<Value>(data) {
if let Some(e) = v.get("error") {
error = Some(e.get("message").and_then(Value::as_str).unwrap_or("未知錯誤").to_string());
return false;
}
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
if let Some(u) = v.get("usage").filter(|u| u.is_object()) {
out.usage = Usage::of_openai(u);
}
let delta = &v["choices"][0]["delta"];
for k in ["reasoning_content", "reasoning"] {
if let Some(t) = delta.get(k).and_then(Value::as_str) {
if !t.is_empty() {
out.thinking.push_str(t);
send(StreamEvent::Thinking(t.to_string()));
}
}
}
if let Some(t) = delta.get("content").and_then(Value::as_str) {
if !t.is_empty() {
out.text.push_str(t);
send(StreamEvent::Text(t.to_string()));
}
}
if let Some(calls) = delta.get("tool_calls").and_then(Value::as_array) {
for c in calls {
let i = match c["index"].as_u64() {
Some(i) => i as usize,
// Some OpenAI-compatible proxies drop the index: a part carrying an
// id or a name starts a new call; an arguments-only part continues the
// last one (starting a fresh slot used to lose the call's tail).
None => {
let starts = c["id"].is_string() || c["function"]["name"].is_string();
if starts || pending.is_empty() {
pending.len()
} else {
pending.len() - 1
}
}
};
while pending.len() <= i {
pending.push(Default::default());
}
if let Some(id) = c["id"].as_str() {
pending[i].0 = id.to_string();
}
if let Some(n) = c["function"]["name"].as_str() {
pending[i].1.push_str(n);
}
if let Some(a) = c["function"]["arguments"].as_str() {
pending[i].2.push_str(a);
}
}
}
}
true
})?;
if let Some(e) = error {
return Err(stream_failure(&e));
}
for (i, (id, name, args)) in pending.into_iter().enumerate() {
if name.is_empty() {
continue;
}
let id = if id.is_empty() { format!("call_{i}") } else { id };
let call = ToolCall { id, name, args, status: ToolStatus::Waiting };
send(StreamEvent::ToolCall(call.clone()));
out.tool_calls.push(call);
}
Ok(out)
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// ---------- ChatGPT 方案: the Responses API on the person's plan ----------
/// The chat as Responses API input items (the system prompt goes in `instructions`: the plan's
/// route refuses system items). Built from the chat-completions shape, so both read the history
/// the same way (pictures kept, older screenshots noted, each result after its call).
pub fn responses_input(req: &ChatRequest) -> Vec<Value> {
let parts = |c: &Value| -> Value {
match c {
Value::String(s) => json!([{"type": "input_text", "text": s}]),
Value::Array(a) => json!(a
.iter()
.filter_map(|p| match p["type"].as_str() {
Some("text") => Some(json!({"type": "input_text", "text": p["text"]})),
Some("image_url") => Some(json!({"type": "input_image", "image_url": p["image_url"]["url"]})),
_ => None,
})
.collect::<Vec<_>>()),
_ => json!([]),
}
};
let mut items = vec![];
for m in openai_messages(req) {
match m["role"].as_str().unwrap_or("") {
"user" => items.push(json!({"role": "user", "content": parts(&m["content"])})),
"assistant" => {
if let Some(t) = m["content"].as_str().filter(|t| !t.is_empty()) {
items.push(json!({"role": "assistant", "content": t}));
}
for c in m["tool_calls"].as_array().into_iter().flatten() {
items.push(json!({"type": "function_call", "call_id": c["id"], "name": c["function"]["name"], "arguments": c["function"]["arguments"]}));
}
}
"tool" => items.push(json!({"type": "function_call_output", "call_id": m["tool_call_id"], "output": m["content"].as_str().unwrap_or("")})),
// (system: sent as `instructions`)
_ => {}
}
}
items
}
impl Usage {
/// A Responses API `usage` object (cached input taken out of `input`, like OpenAI's other one).
pub fn of_responses(u: &Value) -> Usage {
let g = |v: &Value| v.as_u64().unwrap_or(0);
let cached = g(&u["input_tokens_details"]["cached_tokens"]);
Usage { input: g(&u["input_tokens"]).saturating_sub(cached), output: g(&u["output_tokens"]), cache_read: cached, ..Default::default() }
}
}
/// The plan's own refusals (developers.openai.com/siwc/token-sharing-open-source/errors-and-recovery),
/// in words; None for anything else. A usage limit stops the request: it is never moved to
/// another way of paying, and not asked again by itself.
fn plan_failure(e: &Value, retry_after: Option<u64>) -> Option<Failure> {
let code = e["code"].as_str().unwrap_or("");
let said = e["message"].as_str().unwrap_or("");
let param = e["param"].as_str().unwrap_or("");
Some(match code {
"subscription_sharing_usage_limit_exceeded" => {
crate::chatgpt::set_limited(true);
Failure::fatal(format!(
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
"已達用量上限(ChatGPT 方案):你的 ChatGPT 方案,或你給 AnyBot 的上限,這段時間用完了。到 ChatGPT 設定的「用量」查看或調整(管理用量:{})。",
crate::chatgpt::USAGE_URL
))
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
"subscription_sharing_usage_unavailable" | "subscription_sharing_user_unavailable" => {
Failure { msg: "ChatGPT 方案暫時沒辦法用,等一下再試。".into(), retryable: true, retry_after_ms: Some(retry_after.unwrap_or(BUSY_RETRY_MS)) }
}
"subscription_sharing_user_not_eligible" => Failure::fatal(format!("這個 ChatGPT 帳號(或它的工作區)不能用方案的額度跑 AnyBot。可以改用 OpenAI 的 API 金鑰。\n({said})")),
"subscription_sharing_unsupported_capability" => Failure::fatal(format!("ChatGPT 方案不支援這個要求裡的「{param}」:換一個模型,或關掉這個 Bot 的這項設定。\n({said})")),
"subscription_sharing_route_not_supported" => Failure::fatal(format!("ChatGPT 方案不接受這種要求(AnyBot 送錯了地方)。\n({said})")),
"subscription_sharing_invalid_user" => Failure::fatal(format!("ChatGPT 的登入不能用了:請重新登入(設定 › 模型 › ChatGPT 方案)。\n({said})")),
c if c.starts_with("chatpass_v2_") => Failure::fatal(format!("ChatGPT 方案不接受這個 AnyBot 的授權:請重新登入(設定 › 模型 › ChatGPT 方案)。\n({said})")),
_ => return None,
})
}
fn plan_http_error(status: u16, body: &str, retry_after: Option<u64>) -> Failure {
let v: Value = serde_json::from_str(body).unwrap_or(Value::Null);
if let Some(f) = plan_failure(&v["error"], retry_after) {
return f;
}
let said = v["error"]["message"].as_str().map(String::from).unwrap_or_else(|| page_words(body).chars().take(300).collect());
match status {
401 => Failure::fatal(format!("ChatGPT 的登入不能用了:請重新登入(設定 › 模型 › ChatGPT 方案)。\n({said})")),
403 => Failure::fatal(format!("ChatGPT 方案不讓這個要求通過(例如你所在的地區不支援,或工作區的設定不允許)。\n({said})")),
503 => Failure { msg: format!("ChatGPT 方案暫時沒辦法用,等一下再試。\n({said})"), retryable: true, retry_after_ms: Some(retry_after.unwrap_or(BUSY_RETRY_MS)) },
_ => http_error(status, body, retry_after),
}
}
fn no_token(e: crate::chatgpt::NoToken) -> Failure {
Failure { msg: e.msg, retryable: e.retry, retry_after_ms: None }
}
/// 思考模式 rides along as `reasoning.effort`; a model that refuses it gets the request again
/// without it (as with the other OpenAI-style services).
fn stream_responses(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
let key = (crate::chatgpt::API_BASE.to_string(), req.model.clone());
let effort = effort_of(req).filter(|_| !effort_refused().lock().unwrap().contains(&key));
match stream_responses_with(req, effort, cancel, send) {
Err(f) if effort.is_some() && refuses_effort(&f) => {
effort_refused().lock().unwrap().insert(key);
stream_responses_with(req, None, cancel, send)
}
r => r,
}
}
fn stream_responses_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
// (The plan's route takes no temperature, output limit, metadata, previous_response_id…:
// only these. Nothing is stored at OpenAI; the whole chat goes every time.)
let mut body = json!({"model": req.model, "input": responses_input(req), "store": false, "stream": true});
let system = system_with_summaries(req);
if !system.trim().is_empty() {
body["instructions"] = json!(system);
}
if let Some(e) = effort {
body["reasoning"] = json!({"effort": e});
}
if !req.tools.is_empty() {
// (Not strict: AnyBot's schemas have optional fields, which strict mode refuses.)
body["tools"] = json!(req.tools.iter().map(|t| json!({"type": "function", "name": t["name"], "description": t["description"], "parameters": t["parameters"], "strict": false})).collect::<Vec<_>>());
}
// Used up: what nobody is watching waits until a request goes through again.
if crate::chatgpt::limited() && PATIENT.with(|p| p.get()) {
return Err(plan_failure(&json!({"code": "subscription_sharing_usage_limit_exceeded"}), None).unwrap_or_else(|| Failure::fatal(String::new())));
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// Only ever OpenAI's own address, whatever the settings say: the token goes nowhere else.
let url = format!("{}/responses", crate::chatgpt::api_base());
let mut token = crate::chatgpt::fresh_token().map_err(no_token)?;
let mut renewed = false;
let resp = loop {
// SAND-E0418 turnBackendUnreachable: retryable.
let resp = agent()
.post(&url)
.header("Content-Type", "application/json")
.header("Authorization", &format!("Bearer {token}"))
.send_json(&body)
.map_err(|e| Failure::retry(connect_error(req.kind, &e.to_string())))?;
let status = resp.status().as_u16();
// Refused before its time (signed in elsewhere, the clock): renewed once and asked again.
if status == 401 && !renewed {
renewed = true;
token = crate::chatgpt::renew_after(&token).map_err(no_token)?;
continue;
}
if status >= 400 {
let ra = retry_after_ms(&resp);
let text = resp.into_body().read_to_string().unwrap_or_default();
return Err(plan_http_error(status, &text, ra));
}
break resp;
};
let mut out = StepOutput::default();
let mut ended = false;
let mut error: Option<Failure> = None;
read_sse(resp.into_body(), cancel, send, |ev, data| {
let Ok(v) = serde_json::from_str::<Value>(data) else { return true };
let kind = v["type"].as_str().unwrap_or(ev).to_string();
match kind.as_str() {
"response.output_text.delta" => {
let t = v["delta"].as_str().unwrap_or("");
if !t.is_empty() {
out.text.push_str(t);
send(StreamEvent::Text(t.to_string()));
}
}
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => {
let t = v["delta"].as_str().unwrap_or("");
if !t.is_empty() {
out.thinking.push_str(t);
send(StreamEvent::Thinking(t.to_string()));
}
}
"response.reasoning_summary_part.added" if !out.thinking.is_empty() => {
out.thinking.push_str("\n\n");
send(StreamEvent::Thinking("\n\n".into()));
}
"response.output_item.done" if v["item"]["type"] == "function_call" => {
let it = &v["item"];
let args = it["arguments"].as_str().filter(|a| !a.trim().is_empty()).unwrap_or("{}");
let call = ToolCall { id: it["call_id"].as_str().unwrap_or("").into(), name: it["name"].as_str().unwrap_or("").into(), args: args.into(), status: ToolStatus::Waiting };
if !call.name.is_empty() {
send(StreamEvent::ToolCall(call.clone()));
out.tool_calls.push(call);
}
}
"response.completed" => {
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
if let Some(u) = v["response"].get("usage").filter(|u| u.is_object()) {
out.usage = Usage::of_responses(u);
}
ended = true;
return false;
}
// Only a completed answer counts: an incomplete one is said, and its steps aren't run.
"response.incomplete" => {
error = Some(Failure::fatal(match v["response"]["incomplete_details"]["reason"].as_str() {
Some("max_output_tokens") => "回答太長,已達長度上限,沒有完成。".to_string(),
Some("content_filter") => "模型拒絕回答這個要求。".to_string(),
r => format!("ChatGPT 的回答沒有完成({})。", r.unwrap_or("沒有說原因")),
}));
return false;
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
"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()));
}
crate::chatgpt::set_limited(false);
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
Ok(out)
}
/// The models this ChatGPT plan offers (the ones it lists, by their slug).
fn chatgpt_models() -> Result<Vec<String>, String> {
let token = crate::chatgpt::fresh_token().map_err(|e| e.msg)?;
let url = format!("{}/models", crate::chatgpt::api_base());
let resp = agent().get(&url).header("Authorization", &format!("Bearer {token}")).call().map_err(|e| connect_error(ProviderKind::ChatGpt, &e.to_string()))?;
let status = resp.status().as_u16();
let text = resp.into_body().read_to_string().map_err(|e| e.to_string())?;
if status >= 400 {
return Err(plan_http_error(status, &text, None).msg);
}
let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
// (Only the ones it lists, in its own order.)
let mut ids: Vec<String> = vec![];
for id in v["models"]
.as_array()
.into_iter()
.flatten()
.filter(|m| m["visibility"] == "list")
.filter_map(|m| m["slug"].as_str())
.chain(v["data"].as_array().into_iter().flatten().filter_map(|m| m["id"].as_str()))
{
if !ids.iter().any(|x| x == id) {
ids.push(id.to_string());
}
}
if ids.is_empty() {
return Err("ChatGPT 方案沒有列出任何模型".into());
}
Ok(ids)
}
pub fn anthropic_messages(req: &ChatRequest) -> Vec<Value> {
let mut messages: Vec<Value> = vec![];
let mut push = |role: &str, blocks: Vec<Value>| {
if blocks.is_empty() {
return;
}
// The API wants user/assistant turns to alternate; merge repeats.
if let Some(last) = messages.last_mut() {
if last["role"] == role {
last["content"].as_array_mut().unwrap().extend(blocks);
return;
}
}
messages.push(json!({"role": role, "content": blocks}));
};
let kept = kept_images(&req.history);
for (i, m) in req.history.iter().enumerate().filter(|(_, m)| !m.summary) {
match m.role {
Role::Tool if !m.images.is_empty() => {
let content = if kept.contains(&i) {
let mut c = vec![json!({"type": "text", "text": m.text})];
c.extend(m.images.iter().map(|b| json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": b}})));
json!(c)
} else {
json!(format!("{}\n{OLD_SCREENSHOT_NOTE}", m.text))
};
push("user", vec![json!({"type": "tool_result", "tool_use_id": m.tool_call_id, "content": content})]);
}
Role::User if !m.images.is_empty() => {
let mut b = vec![json!({"type": "text", "text": if m.text.is_empty() { "(附件)".to_string() } else { m.text.clone() }})];
b.extend(m.images.iter().map(|x| json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": x}})));
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
if !m.context.is_empty() {
b.push(json!({"type": "text", "text": m.context}));
}
push("user", b);
}
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
Role::User if !m.text.is_empty() => {
let mut b = vec![json!({"type": "text", "text": m.text})];
if !m.context.is_empty() {
b.push(json!({"type": "text", "text": m.context}));
}
push("user", b)
}
Role::User => {}
Role::Assistant => {
if !m.blocks.is_empty() {
push("assistant", m.blocks.clone());
} else if !m.error || !m.tool_calls.is_empty() {
let mut b = vec![];
if !m.text.is_empty() {
b.push(json!({"type": "text", "text": m.text}));
}
for c in &m.tool_calls {
b.push(json!({"type": "tool_use", "id": c.id, "name": c.name, "input": serde_json::from_str::<Value>(&c.args).unwrap_or(json!({}))}));
}
push("assistant", b);
}
}
Role::Tool => push("user", vec![json!({"type": "tool_result", "tool_use_id": m.tool_call_id, "content": m.text})]),
}
}
messages
}
/// Prompt caching: a breakpoint on the last block of the last message, so the whole history
/// prefix is cached too — history is append-only, so each step of a turn reads what the last
/// step wrote. Anthropic accepts at most four breakpoints; we use three (system, tools, tail).
fn cache_tail(mut messages: Vec<Value>) -> Vec<Value> {
if let Some(last) = messages.last_mut() {
match last.get_mut("content") {
Some(Value::Array(blocks)) => {
if let Some(b) = blocks.last_mut() {
if b.is_object() {
b["cache_control"] = json!({"type": "ephemeral"});
}
}
}
Some(Value::String(text)) => {
let t = std::mem::take(text);
last["content"] = json!([{"type": "text", "text": t, "cache_control": {"type": "ephemeral"}}]);
}
_ => {}
}
}
messages
}
fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, Failure> {
let mut body = json!({
"model": req.model,
"max_tokens": MAX_OUTPUT_TOKENS_ANTHROPIC,
"messages": [],
"stream": true,
});
let system = system_with_summaries(req);
if !system.trim().is_empty() {
// Prompt caching: system + tool schemas are most of every request and stay identical
// between the steps of a turn, so both get an ephemeral breakpoint (Anthropic caches
// the prefix up to each marked block; the cache is written on the first step of a turn
// and read on the rest, which is where a computer-use turn's tokens live).
body["system"] = json!([{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}]);
}
if claude_adaptive(&req.model) {
body["thinking"] = json!({"type": "adaptive", "display": "summarized"});
// 思考模式: these models always think; how deeply is `output_config.effort`.
if let Some(e) = effort_of(req) {
body["output_config"] = json!({"effort": e});
}
}
if !req.tools.is_empty() {
let mut tools: Vec<Value> = req.tools.iter().map(|t| json!({"name": t["name"], "description": t["description"], "input_schema": t["parameters"]})).collect();
// One breakpoint on the last tool marks the whole (stable, order-fixed) tools block.
if let Some(last) = tools.last_mut() {
last["cache_control"] = json!({"type": "ephemeral"});
}
body["tools"] = json!(tools);
}
body["messages"] = json!(cache_tail(anthropic_messages(req)));
let mut r = agent()
.post(&format!("{}/messages", req.base_url))
.header("Content-Type", "application/json")
.header("x-api-key", &req.api_key)
.header("anthropic-version", ANTHROPIC_VERSION);
if req.kind == ProviderKind::OpenCodeGo {
// Its Anthropic-style door takes the key as a bearer token too.
r = r.header("Authorization", &format!("Bearer {}", req.api_key)).header("x-opencode-session", &opencode_session(req));
}
if claude_fallbacks(&req.model) {
body["fallbacks"] = json!("default");
r = r.header("anthropic-beta", "server-side-fallback-2026-07-01");
}
// SAND-E0418 turnBackendUnreachable: retryable.
let resp = r.send_json(&body).map_err(|e| Failure::retry(connect_error(req.kind, &e.to_string())))?;
let status = resp.status().as_u16();
if status >= 400 {
let ra = retry_after_ms(&resp);
let text = resp.into_body().read_to_string().unwrap_or_default();
return Err(http_error(status, &text, ra));
}
let mut out = StepOutput::default();
let mut blocks: Vec<Value> = vec![];
let mut partial_json: Vec<String> = vec![];
let mut error = None;
read_sse(resp.into_body(), cancel, send, |ev, data| {
let Ok(v) = serde_json::from_str::<Value>(data) else { return true };
let kind = if ev.is_empty() { v["type"].as_str().unwrap_or("") } else { ev };
match kind {
"content_block_start" => {
let i = v["index"].as_u64().unwrap_or(blocks.len() as u64) as usize;
while blocks.len() <= i {
blocks.push(Value::Null);
partial_json.push(String::new());
}
blocks[i] = v["content_block"].clone();
}
"content_block_delta" => {
let i = v["index"].as_u64().unwrap_or(0) as usize;
let d = &v["delta"];
let block = blocks.get_mut(i);
match d["type"].as_str() {
Some("text_delta") => {
let t = d["text"].as_str().unwrap_or("");
out.text.push_str(t);
if let Some(b) = block {
let joined = format!("{}{}", b["text"].as_str().unwrap_or(""), t);
b["text"] = json!(joined);
}
send(StreamEvent::Text(t.to_string()));
}
Some("thinking_delta") => {
let t = d["thinking"].as_str().unwrap_or("");
out.thinking.push_str(t);
if let Some(b) = block {
let joined = format!("{}{}", b["thinking"].as_str().unwrap_or(""), t);
b["thinking"] = json!(joined);
}
send(StreamEvent::Thinking(t.to_string()));
}
Some("signature_delta") => {
if let Some(b) = block {
let joined = format!("{}{}", b["signature"].as_str().unwrap_or(""), d["signature"].as_str().unwrap_or(""));
b["signature"] = json!(joined);
}
}
Some("input_json_delta") => {
if let Some(p) = partial_json.get_mut(i) {
p.push_str(d["partial_json"].as_str().unwrap_or(""));
}
}
_ => {}
}
}
"content_block_stop" => {
let i = v["index"].as_u64().unwrap_or(0) as usize;
if let Some(b) = blocks.get_mut(i) {
if b["type"] == "tool_use" {
let raw = partial_json.get(i).cloned().unwrap_or_default();
let input: Value = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(json!({})) };
b["input"] = input.clone();
let call = ToolCall { id: b["id"].as_str().unwrap_or("").into(), name: b["name"].as_str().unwrap_or("").into(), args: input.to_string(), status: ToolStatus::Waiting };
send(StreamEvent::ToolCall(call.clone()));
out.tool_calls.push(call);
}
}
}
"message_start" => {
if let Some(u) = v["message"]["usage"].as_object() {
let g = |k: &str| u.get(k).and_then(|x| x.as_u64()).unwrap_or(0);
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
out.usage.input = g("input_tokens");
out.usage.cache_read = g("cache_read_input_tokens");
out.usage.cache_write = g("cache_creation_input_tokens");
out.usage.output = g("output_tokens");
}
}
"message_delta" => {
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
if let Some(n) = v["usage"]["output_tokens"].as_u64() {
out.usage.output = n;
}
if v["delta"]["stop_reason"] == "refusal" {
out.text.push_str("\n\n(模型拒絕回答這個要求。)");
send(StreamEvent::Text("\n\n(模型拒絕回答這個要求。)".into()));
} else if v["delta"]["stop_reason"] == "max_tokens" {
out.text.push_str("\n\n(回答太長,已達長度上限。)");
send(StreamEvent::Text("\n\n(回答太長,已達長度上限。)".into()));
}
}
"message_stop" => return false,
"error" => {
error = Some(v["error"]["message"].as_str().unwrap_or("未知錯誤").to_string());
return false;
}
_ => {}
}
true
})?;
if let Some(e) = error {
return Err(stream_failure(&e));
}
out.blocks = blocks.into_iter().filter(|b| !b.is_null()).collect();
Ok(out)
}
fn connect_error(kind: ProviderKind, e: &str) -> String {
if kind == ProviderKind::Ollama {
format!("連不上 Ollama:{e}\n請先開啟 Ollama,並用 `ollama pull` 下載模型。")
} else {
format!("連不上 {}:{e}", kind.label())
}
}
/// OpenCode Go: which API style each model speaks, from the public models list (fetched once).
static OPENCODE_STYLES: std::sync::Mutex<Option<std::collections::HashMap<String, String>>> = std::sync::Mutex::new(None);
fn remember_opencode_styles(_base: &str, list: &Value) {
let map = opencode_styles_of(list);
if !map.is_empty() {
*OPENCODE_STYLES.lock().unwrap() = Some(map);
}
}
/// {"data":[{"id":"qwen3.8-max","endpoint":{"messages":{…}}}, …]} → id → "messages" | "chat-completions" | …
perf+fix: 舊電腦也輕、連上才進去、送出不重複、小模型說了就做、智慧模式常開、提早壓縮 畫面省資源(舊 Intel Mac) - 聊天紀錄改成共用、寫入時才複製(src/shared.rs):側欄和聊天每一格不再複製整份聊天(約 13 MB/格) - Markdown 解析、程式碼上色依內容快取,只有串流中的那則重算 - 用內建顯示晶片(wgpu LowPower),雙 GPU 的 Mac 不再喚醒獨顯;WGPU_POWER_PREF 照樣優先 - 所有轉圈圖示限每秒 20 次(egui 內建 Spinner 跑滿刷新率);淡入、彩帶、跳轉高亮也限速 - 頭像共用一個眨眼時鐘、捲出畫面的不畫;你不在(視窗不在前面或 90 秒沒動)不眨眼 - ioreg 移出畫面執行緒;Bot 工作中每 5 秒存一次(原 2 秒) - 螢幕電腦的大腦副本每 5 秒在背景寫一次(原本每次同步都在畫面執行緒寫整份) - 手機狀態裡的指令輸出先截短再遮罩金鑰 連線(螢幕電腦 ↔ 大腦) - 連上、拿到最新資料才進去:之前整個視窗停在「正在連到「…」…」,連不上 10 秒以上可改回這台自己的 Bot - 重開只補差異:副本旁記下版本與這台在大腦的名字;第一次拉取帶 config=1、不等新消息 - 漏收一次回應只補差異(大腦保留上一份 Seen),不再整份重抓 - 送出不重複:POST 只在根本沒送出去時才重試;訊息與動作帶編號、斷線自己重送約 100 秒,大腦同一個只做一次;改動依 (client, seq) 只做一次,seq 從時鐘起算 - 斷一下還能送(排隊),真的送不到文字放回輸入框;按過的允許卡片 30 秒內不再跳出 - 獨立審查修正:動作編號加上這次啟動的標記(沿用 client 時不再撞號被當重送);等待頁以「收到第一個回答」為準、設定讀不出來照樣進去並說原因、等滿 10 秒就有離開鈕;整份重抓失敗會再要;上一次拉取失敗時帶 retry,大腦從上一份算差異;去重表滿了淘汰最舊的 - 手機頁在背景時不重畫訊息,回到前景再畫 小模型持續做(src/agent/followthrough.rs) - 回答說了要做什麼卻沒呼叫工具、或問「要我現在就開始嗎?」:告訴模型、下一步安靜地跑;動手才顯示,標記「〔到此為止〕」或又只說一次都不顯示;連兩次、一輪 12 次為限;最後一句提到刪除、付款、寄出、關機這類收不回來的事一律不提醒 - OpenCode Go 模型清單改讀新格式 api/recommended_api(舊的 endpoint 照讀) 智慧模式常開 - 預設開、/smart off 與手機都關不掉(只有管理員鎖時關);設定頁只剩逾時滑桿 30–1800 秒;輸入列不再有它的圖示 token 壓縮提早 - 門檻 70→60%(進行中 65%);估算改成英數 3.5 字元一 token;一個要求做很多步時主動把這一輪較早的步驟寫成摘要(至少 10 則),不等模型說太長 feature-map:chat.md 新增 chat-followthrough(含步驟)、chat-compact 6 成、chat-steps;autonomy.md 智慧模式一直開著(步驟改寫);account.md 連上才進去、重送與去重;settings/safety/phone 同步。FEATURES.md 同步。 已驗證: cargo test 739 通過、clippy 無新警告(含 featuremap:: 11 項、layout_audit::、新增 followthrough/shared/mirror 去重與漏收補差異測試);verify-anybot:chat.md「/ 指令」(/context 寫「到 60% 會自動」)、「說了就做」(只說「我把它整理成一頁做法文件。」後同一輪接著執行 echo ft-done 並收尾,模型那層收到提醒)、autonomy.md「智慧模式一直開著」(/smart off 回不能關,重開後 smart_mode 仍 true);審查修正後三步重跑結果相同;ctl down 無殘留;乾淨脈絡獨立審查 1 次(P0×1、P1×1 已修) 未驗證: 手機頁面畫面那一層(這台沒有 Google Chrome,無頭手機頁面開不起來,改走同一個大腦的手機 API);螢幕電腦連大腦的實際路徑(要帳號伺服器與第二台電腦:等待頁、重開續傳、斷線重送只在單元測試);真 Intel Mac 的 CPU/風扇與 LowPower GPU 實測;真的小模型(muse-spark 等)是否照提醒動手;動到審批路徑(智慧模式常開)需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:31 +00:00
/// (The list now says it as `"api": {"messages": {…}}` with a `recommended_api`; the older
/// `endpoint` is still read. Reading only `endpoint` found nothing in the new list, and every
/// model fell back to a guess by its name.)
pub fn opencode_styles_of(list: &Value) -> std::collections::HashMap<String, String> {
list["data"]
.as_array()
.into_iter()
.flatten()
.filter_map(|m| {
let id = m["id"].as_str()?;
perf+fix: 舊電腦也輕、連上才進去、送出不重複、小模型說了就做、智慧模式常開、提早壓縮 畫面省資源(舊 Intel Mac) - 聊天紀錄改成共用、寫入時才複製(src/shared.rs):側欄和聊天每一格不再複製整份聊天(約 13 MB/格) - Markdown 解析、程式碼上色依內容快取,只有串流中的那則重算 - 用內建顯示晶片(wgpu LowPower),雙 GPU 的 Mac 不再喚醒獨顯;WGPU_POWER_PREF 照樣優先 - 所有轉圈圖示限每秒 20 次(egui 內建 Spinner 跑滿刷新率);淡入、彩帶、跳轉高亮也限速 - 頭像共用一個眨眼時鐘、捲出畫面的不畫;你不在(視窗不在前面或 90 秒沒動)不眨眼 - ioreg 移出畫面執行緒;Bot 工作中每 5 秒存一次(原 2 秒) - 螢幕電腦的大腦副本每 5 秒在背景寫一次(原本每次同步都在畫面執行緒寫整份) - 手機狀態裡的指令輸出先截短再遮罩金鑰 連線(螢幕電腦 ↔ 大腦) - 連上、拿到最新資料才進去:之前整個視窗停在「正在連到「…」…」,連不上 10 秒以上可改回這台自己的 Bot - 重開只補差異:副本旁記下版本與這台在大腦的名字;第一次拉取帶 config=1、不等新消息 - 漏收一次回應只補差異(大腦保留上一份 Seen),不再整份重抓 - 送出不重複:POST 只在根本沒送出去時才重試;訊息與動作帶編號、斷線自己重送約 100 秒,大腦同一個只做一次;改動依 (client, seq) 只做一次,seq 從時鐘起算 - 斷一下還能送(排隊),真的送不到文字放回輸入框;按過的允許卡片 30 秒內不再跳出 - 獨立審查修正:動作編號加上這次啟動的標記(沿用 client 時不再撞號被當重送);等待頁以「收到第一個回答」為準、設定讀不出來照樣進去並說原因、等滿 10 秒就有離開鈕;整份重抓失敗會再要;上一次拉取失敗時帶 retry,大腦從上一份算差異;去重表滿了淘汰最舊的 - 手機頁在背景時不重畫訊息,回到前景再畫 小模型持續做(src/agent/followthrough.rs) - 回答說了要做什麼卻沒呼叫工具、或問「要我現在就開始嗎?」:告訴模型、下一步安靜地跑;動手才顯示,標記「〔到此為止〕」或又只說一次都不顯示;連兩次、一輪 12 次為限;最後一句提到刪除、付款、寄出、關機這類收不回來的事一律不提醒 - OpenCode Go 模型清單改讀新格式 api/recommended_api(舊的 endpoint 照讀) 智慧模式常開 - 預設開、/smart off 與手機都關不掉(只有管理員鎖時關);設定頁只剩逾時滑桿 30–1800 秒;輸入列不再有它的圖示 token 壓縮提早 - 門檻 70→60%(進行中 65%);估算改成英數 3.5 字元一 token;一個要求做很多步時主動把這一輪較早的步驟寫成摘要(至少 10 則),不等模型說太長 feature-map:chat.md 新增 chat-followthrough(含步驟)、chat-compact 6 成、chat-steps;autonomy.md 智慧模式一直開著(步驟改寫);account.md 連上才進去、重送與去重;settings/safety/phone 同步。FEATURES.md 同步。 已驗證: cargo test 739 通過、clippy 無新警告(含 featuremap:: 11 項、layout_audit::、新增 followthrough/shared/mirror 去重與漏收補差異測試);verify-anybot:chat.md「/ 指令」(/context 寫「到 60% 會自動」)、「說了就做」(只說「我把它整理成一頁做法文件。」後同一輪接著執行 echo ft-done 並收尾,模型那層收到提醒)、autonomy.md「智慧模式一直開著」(/smart off 回不能關,重開後 smart_mode 仍 true);審查修正後三步重跑結果相同;ctl down 無殘留;乾淨脈絡獨立審查 1 次(P0×1、P1×1 已修) 未驗證: 手機頁面畫面那一層(這台沒有 Google Chrome,無頭手機頁面開不起來,改走同一個大腦的手機 API);螢幕電腦連大腦的實際路徑(要帳號伺服器與第二台電腦:等待頁、重開續傳、斷線重送只在單元測試);真 Intel Mac 的 CPU/風扇與 LowPower GPU 實測;真的小模型(muse-spark 等)是否照提醒動手;動到審批路徑(智慧模式常開)需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:31 +00:00
let ep = m["endpoint"].as_object().or_else(|| m["api"].as_object())?;
// A model with a chat-completions door uses it (AnyBot's best-tested path); else the first.
let style = if ep.contains_key("chat-completions") { "chat-completions" } else if ep.contains_key("messages") { "messages" } else { ep.keys().next()? };
Some((id.to_string(), style.to_string()))
})
.collect()
}
/// The API style for a model: "messages" (Anthropic-style) or "chat-completions" (everything
/// else; OpenCode translates for models whose own style is Responses or Gemini).
pub fn opencode_go_style(base: &str, model: &str) -> String {
let known = OPENCODE_STYLES.lock().unwrap().as_ref().and_then(|m| m.get(model).cloned());
let style = known.or_else(|| {
let v: Value = agent().get(&format!("{base}/v1/models")).call().ok()?.into_body().read_json().ok()?;
remember_opencode_styles(base, &v);
OPENCODE_STYLES.lock().unwrap().as_ref().and_then(|m| m.get(model).cloned())
});
style.unwrap_or_else(|| {
// Offline guess from the published list: Claude, Qwen and MiniMax M3 are Anthropic-style.
let m = model.to_lowercase();
if m.starts_with("claude") || m.starts_with("qwen") || m == "minimax-m3" { "messages".into() } else { "chat-completions".into() }
})
}
fn opencode_session(req: &ChatRequest) -> String {
if req.session.is_empty() { "anybot".into() } else { req.session.clone() }
}
/// Ask the provider which models it offers.
pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result<Vec<String>, String> {
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// 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());
}
let url = if kind == ProviderKind::OpenCodeGo { format!("{base_url}/v1/models") } else { format!("{base_url}/models") };
let mut r = agent().get(&url);
if kind == ProviderKind::Anthropic {
r = r.header("x-api-key", api_key).header("anthropic-version", ANTHROPIC_VERSION);
} else if !api_key.is_empty() {
r = r.header("Authorization", &format!("Bearer {api_key}"));
}
let resp = r.call().map_err(|e| connect_error(kind, &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(http_error(status, &text, None).msg);
}
let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
if kind == ProviderKind::OpenCodeGo {
remember_opencode_styles(base_url, &v);
}
let list = v["data"].as_array().or_else(|| v["models"].as_array()).cloned().unwrap_or_default();
let mut ids: Vec<String> = list
.iter()
.filter_map(|m| m["id"].as_str().or_else(|| m["name"].as_str()))
.map(|s| s.trim_start_matches("models/").to_string())
.collect();
ids.sort();
ids.dedup();
if ids.is_empty() {
return Err("供應商沒有回傳任何模型".into());
}
Ok(ids)
}
#[cfg(test)]
mod tests {
fix: 模型說對話太長時自己騰出空間再試——先拿掉截圖、再收起舊結果、再摘要(一輪中間也能切);記下模型真正的上限,把圖當文字算的模型不再傳圖 一台 Linux 換成自訂端點的模型後,一張網頁截圖讓請求從約 1.8 萬 tokens 變成 178,553(上限 131,072):那個端點把圖的 base64 當文字算。AnyBot 一張圖只估 3,200、也沒算工具說明,所以沒先壓縮;模型說太長時,最新 6 則一律保留(截圖就在裡面),這一輪又只有一則指令沒地方摘要,直接報錯;下一輪截圖還在記憶體裡又送一次。 - 模型說太長:依序拿掉圖片(聊天裡的步驟截圖也放掉,下一輪不再送)→ 收起除了最新 2 步以外的長結果 → 摘要(只有一則指令的長回合在這一輪中間切,指令原文保留)→ 都試過才報錯,並說明指示、工具說明、對話各多大 - 從錯誤訊息讀出上限(husky、OpenAI、vLLM、Anthropic 的寫法),比 Bot 設定小就記下來(StreamEvent::ContextLimit) - 實際用量比估算每張圖多 2 萬 tokens 以上(圖被當文字算)時,拿掉圖片成功後這個模型不再傳圖(改用文字描述);看得到圖、只是剛好超過一點的模型照樣看螢幕 - 估算加進工具說明(約 1.2 萬 tokens) 測試:husky 那次的截圖情境、一則指令的長回合、看圖模型只超過一點點、各家錯誤訊息的上限與用量解析。Mac 451 個測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:57:51 +00:00
#[test]
fn a_too_long_error_says_how_much_the_model_reads() {
// jenny-Host's model, 2026-11-14 18:10.
assert_eq!(overflow_limit("Prompt is 178553 tokens; the context limit on 'husky' for you is 131072 tokens."), Some(131072));
// OpenAI / vLLM: the limit, not the other numbers.
assert_eq!(overflow_limit("This model's maximum context length is 128000 tokens. However, your messages resulted in 130512 tokens."), Some(128000));
assert_eq!(overflow_limit("This model's maximum context length is 32768 tokens. However, you requested 40000 tokens (35000 in the messages, 5000 in the completion)."), Some(32768));
// Anthropic: "N tokens > M maximum".
assert_eq!(overflow_limit("prompt is too long: 210000 tokens > 200000 maximum"), Some(200000));
assert_eq!(overflow_limit("context_length_exceeded: context window of 131,072 tokens"), Some(131072));
// How long the request was: the largest count that isn't the limit.
assert_eq!(overflow_prompt("Prompt is 178553 tokens; the context limit on 'husky' for you is 131072 tokens."), Some(178553));
assert_eq!(overflow_prompt("This model's maximum context length is 32768 tokens. However, you requested 40000 tokens (35000 in the messages, 5000 in the completion)."), Some(40000));
assert_eq!(overflow_prompt("prompt is too long: 210000 tokens > 200000 maximum"), Some(210000));
assert_eq!(overflow_prompt("context window of 131072 tokens"), None);
// Nothing said: nothing learned.
assert_eq!(overflow_limit("Prompt is too long"), None);
assert_eq!(overflow_limit("context length exceeded (request 2024-11-14)"), None);
}
use super::*;
use std::io::{Read, Write};
use std::net::TcpListener;
/// Serve one canned SSE reply on a local port and return its base URL.
pub fn fake_server(body: &'static str) -> String {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
let (mut s, _) = l.accept().unwrap();
// Read the whole request (headers + body) before answering.
let mut req = Vec::new();
let mut buf = [0u8; 4096];
loop {
let n = s.read(&mut buf).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&req).to_string();
if let Some(end) = text.find("\r\n\r\n") {
let len = text[..end]
.lines()
.find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))
.unwrap_or(0);
if req.len() >= end + 4 + len {
break;
}
}
}
let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n";
let _ = s.write_all(head.as_bytes());
let _ = s.write_all(body.as_bytes());
});
format!("http://127.0.0.1:{port}/v1")
}
fn run(kind: ProviderKind, body: &'static str) -> StepOutput {
let req = ChatRequest {
kind,
base_url: fake_server(body),
api_key: "test".into(),
model: "m".into(),
system: "s".into(),
history: vec![Message::user("hi")],
tools: crate::tools::specs(),
session: String::new(), effort: String::new(),
};
let cancel = AtomicBool::new(false);
match run_step(&req, &cancel, &|_| {}) {
Ok(o) => o,
Err(e) => panic!("{e}"),
}
}
#[test]
fn a_busy_model_mid_stream_is_waited_out() {
let f = stream_failure("The model is currently at capacity due to high demand. Please try again in a few minutes");
assert!(f.retryable && f.retry_after_ms == Some(BUSY_RETRY_MS) && f.msg.starts_with("模型供應商現在太忙"), "{}", f.msg);
let f = stream_failure("Invalid tool schema");
assert!(!f.retryable && f.msg.starts_with("模型回報錯誤"), "{}", f.msg);
}
#[test]
fn a_gateways_error_page_reads_as_words() {
let page = "<!DOCTYPE HTML>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<style type=\"text/css\">\n:root {\ncolor-scheme: light dark;\n}\n</style>\n<title>Error response</title>\n</head>\n<body>\n<h1>Error response</h1>\n<p>Error code: 502</p>\n<p>Message: Bad Gateway.</p>\n</body>\n</html>\n";
let f = http_error(502, page, None);
assert!(f.retryable);
assert!(!f.msg.contains('<') && !f.msg.contains("color-scheme"), "{}", f.msg);
assert!(f.msg.contains("Bad Gateway"), "{}", f.msg);
assert_eq!(page_words("upstream timed out"), "upstream timed out");
}
#[test]
fn backoff_matches_original() {
assert_eq!([backoff_up_to(1, RETRY_MAX_DELAY_MS), backoff_up_to(2, RETRY_MAX_DELAY_MS), backoff_up_to(3, RETRY_MAX_DELAY_MS)], [1000, 2000, 4000]);
assert_eq!(backoff_up_to(9, PATIENT_MAX_DELAY_MS), PATIENT_MAX_DELAY_MS);
for ms in [0, 1, 1000, 30_000] {
let j = jitter(ms);
assert!(j >= ms - ms / 5 && j <= ms + ms / 5, "{ms} → {j}");
}
assert!(http_error(429, "{}", None).retryable);
assert!(http_error(503, "{}", Some(2000)).retry_after_ms == Some(2000));
assert!(!http_error(401, "{}", None).retryable);
assert!(!http_error(400, "{\"error\":{\"message\":\"prompt is too long\"}}", None).retryable);
}
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
/// A conversation too long for the model is told apart from other failures (the turn folds
/// it into a summary and asks again), whether it comes as an HTTP 400 or inside the stream.
#[test]
fn an_overflow_is_recognized_as_one() {
assert!(is_context_overflow(&http_error(400, "{\"error\":{\"message\":\"This model's maximum context length is 128000 tokens\"}}", None).msg));
assert!(is_context_overflow(&http_error(413, "{\"error\":{\"message\":\"prompt is too long: 210000 tokens > 200000 maximum\"}}", None).msg));
assert!(is_context_overflow(&stream_failure("prompt is too long: 210000 tokens > 200000 maximum").msg));
assert!(!is_context_overflow(&http_error(401, "{}", None).msg));
assert!(!is_context_overflow(&http_error(400, "{\"error\":{\"message\":\"tools are not supported\"}}", None).msg));
assert!(!is_context_overflow(&stream_failure("overloaded").msg));
}
#[test]
fn openai_style_stream() {
let body = "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"hm\"}}]}\n\ndata: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n\ndata: {\"choices\":[{\"delta\":{\"content\":\"!\"}}]}\n\ndata: [DONE]\n\n";
let o = run(ProviderKind::Xai, body);
assert_eq!(o.text, "你好!");
assert_eq!(o.thinking, "hm");
}
#[test]
fn openai_tool_calls_in_pieces() {
let body = "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_a\",\"function\":{\"name\":\"read_file\",\"arguments\":\"{\\\"pa\"}}]}}]}\n\ndata: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"th\\\":\\\"a.txt\\\"}\"}}]}}]}\n\ndata: [DONE]\n\n";
let o = run(ProviderKind::OpenAi, body);
assert_eq!(o.tool_calls.len(), 1);
assert_eq!(o.tool_calls[0].name, "read_file");
assert_eq!(o.tool_calls[0].args, "{\"path\":\"a.txt\"}");
}
#[test]
fn claude_style_stream() {
let body = "event: message_start\ndata: {\"type\":\"message_start\"}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"ok\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"sig\"}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hello\"}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":2,\"content_block\":{\"type\":\"tool_use\",\"id\":\"tu1\",\"name\":\"list_dir\",\"input\":{}}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":2,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"path\\\": \\\"x\\\"}\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":2}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";
let o = run(ProviderKind::Anthropic, body);
assert_eq!(o.text, "Hello");
assert_eq!(o.thinking, "ok");
assert_eq!(o.tool_calls[0].name, "list_dir");
assert_eq!(o.blocks.len(), 3);
assert_eq!(o.blocks[0]["signature"], "sig");
assert_eq!(o.blocks[2]["input"]["path"], "x");
}
#[test]
fn history_keeps_tool_turns() {
let mut a = Message::assistant("", "x");
a.tool_calls = vec![ToolCall { id: "c1".into(), name: "list_dir".into(), args: "{}".into(), status: ToolStatus::Done }];
let mut s = Message::assistant("old stuff", "");
s.summary = true;
let req = ChatRequest {
kind: ProviderKind::Anthropic,
base_url: String::new(),
api_key: String::new(),
model: "m".into(),
system: "sys".into(),
history: vec![s, Message::user("hi"), a, Message::tool_result("c1", "list_dir", "a.txt"), Message::user("next")],
tools: vec![],
session: String::new(), effort: String::new(),
};
let m = anthropic_messages(&req);
assert_eq!(m.len(), 3);
assert_eq!(m[1]["content"][0]["type"], "tool_use");
assert_eq!(m[2]["content"][0]["type"], "tool_result");
assert_eq!(m[2]["content"][1]["text"], "next");
let o = openai_messages(&ChatRequest { kind: ProviderKind::OpenAi, ..req });
assert!(o[0]["content"].as_str().unwrap().contains("old stuff"));
assert_eq!(o[3]["role"], "tool");
}
#[test]
fn screenshots_reach_the_model_and_old_ones_drop() {
let n = crate::computer::KEEP_SCREENSHOTS + 1;
let mut history = vec![Message::user("look")];
for i in 0..n {
let mut a = Message::assistant("", "x");
a.tool_calls = vec![ToolCall { id: format!("s{i}"), name: "computer_use_screenshot".into(), args: "{}".into(), status: ToolStatus::Done }];
history.push(a);
let mut r = Message::tool_result(&format!("s{i}"), "computer_use_screenshot", "shot");
r.images = vec![format!("IMG{i}")];
history.push(r);
}
let req = ChatRequest { kind: ProviderKind::Anthropic, base_url: String::new(), api_key: String::new(), model: "m".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() };
let m = anthropic_messages(&req);
let all = serde_json::to_string(&m).unwrap();
assert!(!all.contains("IMG0") && all.contains(OLD_SCREENSHOT_NOTE));
assert!(all.contains(&format!("IMG{}", n - 1)) && all.contains("\"media_type\":\"image/jpeg\""));
let o = openai_messages(&ChatRequest { kind: ProviderKind::OpenAi, ..req });
// Each tool answer is followed by its picture as a user message (never between tool results).
for w in o.windows(2) {
if w[0]["role"] == "user" && w[0]["content"].is_array() && w[1]["role"] == "tool" {
panic!("picture between tool results");
}
}
let pics: Vec<&Value> = o.iter().filter(|x| x["role"] == "user" && x["content"].is_array()).collect();
assert_eq!(pics.len(), crate::computer::KEEP_SCREENSHOTS);
assert!(pics.last().unwrap()["content"][1]["image_url"]["url"].as_str().unwrap().starts_with("data:image/jpeg;base64,IMG"));
}
/// A server that records the request it gets, then answers with `body`.
fn recording_server(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let (mut s, _) = l.accept().unwrap();
let mut req = Vec::new();
let mut buf = [0u8; 8192];
loop {
let n = s.read(&mut buf).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&req).to_string();
if let Some(end) = text.find("\r\n\r\n") {
let len = text[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))).unwrap_or(0);
if req.len() >= end + 4 + len {
break;
}
}
}
let _ = tx.send(String::from_utf8_lossy(&req).to_string());
let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n");
let _ = s.write_all(body.as_bytes());
});
(format!("http://127.0.0.1:{port}"), rx)
}
/// 思考模式 goes out as each service names it; left to the model, nothing is sent; a model
/// that refuses the setting is asked again without it, and not sent it a second time.
#[test]
fn the_thinking_mode_is_sent_and_dropped_when_refused() {
let cancel = AtomicBool::new(false);
let ok = "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n\n";
let claude = "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";
let ask = |kind: ProviderKind, model: &str, effort: &str, body: &'static str| {
let (base, rx) = recording_server(body);
let req = ChatRequest { kind, base_url: format!("{base}/v1"), api_key: "k".into(), model: model.into(), system: "s".into(), history: vec![Message::user("hi")], tools: vec![], session: String::new(), effort: effort.into() };
assert_eq!(run_step(&req, &cancel, &|_| {}).unwrap().text, "ok");
// (The body goes out indented: compare without the spaces.)
rx.recv().unwrap().split_whitespace().collect::<String>()
};
let seen = ask(ProviderKind::OpenAi, "gpt-5", "high", ok);
assert!(seen.contains("\"reasoning_effort\":\"high\""), "{seen}");
assert!(!ask(ProviderKind::OpenAi, "gpt-5", "", ok).contains("reasoning_effort"));
assert!(!ask(ProviderKind::OpenAi, "gpt-5", "whatever", ok).contains("reasoning_effort"));
let seen = ask(ProviderKind::Anthropic, "claude-opus-5-5", "low", claude);
assert!(seen.contains("\"output_config\":{\"effort\":\"low\"}") && seen.contains("\"type\":\"adaptive\""), "{seen}");
assert!(!ask(ProviderKind::Anthropic, "claude-opus-5-5", "", claude).contains("output_config"));
assert!(!ask(ProviderKind::Anthropic, "claude-haiku-4-5", "low", claude).contains("output_config"), "a model without the setting isn't sent it");
// A server that answers 400 to the setting: the answer still comes, and the next
// request to that model leaves it out from the start.
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for _ in 0..3 {
let (mut s, _) = l.accept().unwrap();
let mut req = Vec::new();
let mut buf = [0u8; 8192];
loop {
let n = s.read(&mut buf).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&req).to_string();
if let Some(end) = text.find("\r\n\r\n") {
let len = text[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))).unwrap_or(0);
if req.len() >= end + 4 + len {
break;
}
}
}
let refused = String::from_utf8_lossy(&req).contains("reasoning_effort");
let _ = tx.send(refused);
if refused {
let b = "{\"error\":{\"message\":\"This model does not support parameter reasoning_effort.\"}}";
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());
} else {
let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n\n");
}
}
});
let req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "no-effort".into(), system: String::new(), history: vec![Message::user("hi")], tools: vec![], session: String::new(), effort: "medium".into() };
assert_eq!(run_step(&req, &cancel, &|_| {}).unwrap().text, "ok");
assert_eq!(run_step(&req, &cancel, &|_| {}).unwrap().text, "ok");
assert_eq!(rx.try_iter().collect::<Vec<bool>>(), vec![true, false, false]);
}
#[test]
fn opencode_go_routes_each_model_its_way() {
// The public list's shape (trimmed).
let list: Value = serde_json::from_str(r#"{"data":[
{"id":"kimi-k3","endpoint":{"chat-completions":{"base_url":"https://opencode.ai/inference/go/openai/v1"}}},
{"id":"qwen3.8-max","endpoint":{"messages":{"base_url":"https://opencode.ai/inference/go/anthropic/v1"}}},
{"id":"grok-4.7","endpoint":{"responses":{"base_url":"https://opencode.ai/inference/go/openai/v1"}}}]}"#).unwrap();
let styles = opencode_styles_of(&list);
perf+fix: 舊電腦也輕、連上才進去、送出不重複、小模型說了就做、智慧模式常開、提早壓縮 畫面省資源(舊 Intel Mac) - 聊天紀錄改成共用、寫入時才複製(src/shared.rs):側欄和聊天每一格不再複製整份聊天(約 13 MB/格) - Markdown 解析、程式碼上色依內容快取,只有串流中的那則重算 - 用內建顯示晶片(wgpu LowPower),雙 GPU 的 Mac 不再喚醒獨顯;WGPU_POWER_PREF 照樣優先 - 所有轉圈圖示限每秒 20 次(egui 內建 Spinner 跑滿刷新率);淡入、彩帶、跳轉高亮也限速 - 頭像共用一個眨眼時鐘、捲出畫面的不畫;你不在(視窗不在前面或 90 秒沒動)不眨眼 - ioreg 移出畫面執行緒;Bot 工作中每 5 秒存一次(原 2 秒) - 螢幕電腦的大腦副本每 5 秒在背景寫一次(原本每次同步都在畫面執行緒寫整份) - 手機狀態裡的指令輸出先截短再遮罩金鑰 連線(螢幕電腦 ↔ 大腦) - 連上、拿到最新資料才進去:之前整個視窗停在「正在連到「…」…」,連不上 10 秒以上可改回這台自己的 Bot - 重開只補差異:副本旁記下版本與這台在大腦的名字;第一次拉取帶 config=1、不等新消息 - 漏收一次回應只補差異(大腦保留上一份 Seen),不再整份重抓 - 送出不重複:POST 只在根本沒送出去時才重試;訊息與動作帶編號、斷線自己重送約 100 秒,大腦同一個只做一次;改動依 (client, seq) 只做一次,seq 從時鐘起算 - 斷一下還能送(排隊),真的送不到文字放回輸入框;按過的允許卡片 30 秒內不再跳出 - 獨立審查修正:動作編號加上這次啟動的標記(沿用 client 時不再撞號被當重送);等待頁以「收到第一個回答」為準、設定讀不出來照樣進去並說原因、等滿 10 秒就有離開鈕;整份重抓失敗會再要;上一次拉取失敗時帶 retry,大腦從上一份算差異;去重表滿了淘汰最舊的 - 手機頁在背景時不重畫訊息,回到前景再畫 小模型持續做(src/agent/followthrough.rs) - 回答說了要做什麼卻沒呼叫工具、或問「要我現在就開始嗎?」:告訴模型、下一步安靜地跑;動手才顯示,標記「〔到此為止〕」或又只說一次都不顯示;連兩次、一輪 12 次為限;最後一句提到刪除、付款、寄出、關機這類收不回來的事一律不提醒 - OpenCode Go 模型清單改讀新格式 api/recommended_api(舊的 endpoint 照讀) 智慧模式常開 - 預設開、/smart off 與手機都關不掉(只有管理員鎖時關);設定頁只剩逾時滑桿 30–1800 秒;輸入列不再有它的圖示 token 壓縮提早 - 門檻 70→60%(進行中 65%);估算改成英數 3.5 字元一 token;一個要求做很多步時主動把這一輪較早的步驟寫成摘要(至少 10 則),不等模型說太長 feature-map:chat.md 新增 chat-followthrough(含步驟)、chat-compact 6 成、chat-steps;autonomy.md 智慧模式一直開著(步驟改寫);account.md 連上才進去、重送與去重;settings/safety/phone 同步。FEATURES.md 同步。 已驗證: cargo test 739 通過、clippy 無新警告(含 featuremap:: 11 項、layout_audit::、新增 followthrough/shared/mirror 去重與漏收補差異測試);verify-anybot:chat.md「/ 指令」(/context 寫「到 60% 會自動」)、「說了就做」(只說「我把它整理成一頁做法文件。」後同一輪接著執行 echo ft-done 並收尾,模型那層收到提醒)、autonomy.md「智慧模式一直開著」(/smart off 回不能關,重開後 smart_mode 仍 true);審查修正後三步重跑結果相同;ctl down 無殘留;乾淨脈絡獨立審查 1 次(P0×1、P1×1 已修) 未驗證: 手機頁面畫面那一層(這台沒有 Google Chrome,無頭手機頁面開不起來,改走同一個大腦的手機 API);螢幕電腦連大腦的實際路徑(要帳號伺服器與第二台電腦:等待頁、重開續傳、斷線重送只在單元測試);真 Intel Mac 的 CPU/風扇與 LowPower GPU 實測;真的小模型(muse-spark 等)是否照提醒動手;動到審批路徑(智慧模式常開)需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:31 +00:00
// The list as OpenCode gives it now: `api` (and recommended_api) instead of `endpoint`.
let now: Value = serde_json::from_str(r#"{"data":[
{"id":"muse-spark-1.3-contributor","api":{"responses":{"base_url":"https://opencode.ai/inference/go/openai/v1"}},"recommended_api":"responses"},
{"id":"qwen4-max","api":{"messages":{"base_url":"https://opencode.ai/inference/go/anthropic/v1"}},"recommended_api":"messages"},
{"id":"glm-5.3","api":{"chat-completions":{}},"recommended_api":"chat-completions"}]}"#).unwrap();
let now = opencode_styles_of(&now);
assert_eq!(now.get("qwen4-max").map(String::as_str), Some("messages"));
assert_eq!(now.get("glm-5.3").map(String::as_str), Some("chat-completions"));
assert_eq!(now.get("muse-spark-1.3-contributor").map(String::as_str), Some("responses"));
assert_eq!(styles["kimi-k3"], "chat-completions");
assert_eq!(styles["qwen3.8-max"], "messages");
assert_eq!(styles["grok-4.7"], "responses");
remember_opencode_styles("", &list);
let cancel = AtomicBool::new(false);
let ask = |model: &str, body: &'static str| {
let (base, rx) = recording_server(body);
let req = ChatRequest { kind: ProviderKind::OpenCodeGo, base_url: base, api_key: "sk-go".into(), model: model.into(), system: "s".into(), history: vec![Message::user("hi")], tools: vec![], session: "anybot-bot-7".into(), effort: String::new() };
let out = run_step(&req, &cancel, &|_| {}).unwrap();
(out, rx.recv().unwrap())
};
let (out, seen) = ask("kimi-k3", "data: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n\ndata: [DONE]\n\n");
assert_eq!(out.text, "你好");
assert!(seen.starts_with("POST /openai/v1/chat/completions "), "{seen}");
let low = seen.to_lowercase();
assert!(low.contains("authorization: bearer sk-go") && low.contains("x-opencode-session: anybot-bot-7"), "{seen}");
let (out, seen) = ask("qwen3.8-max", "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"嗨\"}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n");
assert_eq!(out.text, "嗨");
assert!(seen.starts_with("POST /anthropic/v1/messages "), "{seen}");
let low = seen.to_lowercase();
assert!(low.contains("x-api-key: sk-go") && low.contains("x-opencode-session: anybot-bot-7"), "{seen}");
// Responses-style models go through OpenCode's chat-completions translation.
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let (_, seen) = ask("grok-4.7", "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n\n");
assert!(seen.starts_with("POST /openai/v1/chat/completions "), "{seen}");
}
/// Network: OpenCode Go's real model list (public) and the style of a few models.
#[test]
#[ignore]
fn opencode_go_live_list() {
// A wrong key is refused (so pasting a bad key shows 金鑰無效 right away).
assert!(list_models(ProviderKind::OpenCodeGo, OPENCODE_GO_BASE, "sk-wrong").unwrap_err().contains("401"));
// The styles come from the public list (no key).
assert_eq!(opencode_go_style(OPENCODE_GO_BASE, "qwen3.8-max"), "messages");
assert_eq!(opencode_go_style(OPENCODE_GO_BASE, "glm-5.3"), "chat-completions");
}
#[test]
fn a_model_that_cannot_see_gets_no_pictures() {
let _g = vision_test_guard();
assert!(image_refused("錯誤 400:At most 0 image(s) may be provided in one prompt. (parameter=image)"));
assert!(image_refused("This model does not support image input"));
assert!(image_refused("unknown variant `image_url`, expected `text`"));
assert!(image_refused("錯誤 400:spark-x2.6-4b is not a multimodal model"));
assert!(!image_refused("錯誤 400:Invalid credential"));
// The first request fails like the user's model did; the retry has no picture.
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let (tx, rx) = std::sync::mpsc::channel::<String>();
std::thread::spawn(move || {
for (n, s) in l.incoming().flatten().enumerate() {
let mut s = s;
let mut req = Vec::new();
let mut buf = [0u8; 65536];
loop {
let k = s.read(&mut buf).unwrap_or(0);
if k == 0 {
break;
}
req.extend_from_slice(&buf[..k]);
let text = String::from_utf8_lossy(&req).to_string();
if let Some(end) = text.find("\r\n\r\n") {
let len = text[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))).unwrap_or(0);
if req.len() >= end + 4 + len {
break;
}
}
}
let _ = tx.send(String::from_utf8_lossy(&req).to_string());
if n == 0 {
let body = r#"{"error":{"message":"At most 0 image(s) may be provided in one prompt. (parameter=image)"}}"#;
let _ = write!(s, "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
} else {
let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n\n");
}
}
});
let mut shot = Message::tool_result("c1", "computer_use_screenshot", "你的螢幕截圖");
shot.images = vec!["SHOTDATA".into()];
let mut asked = Message::assistant("", "");
asked.tool_calls = vec![ToolCall { id: "c1".into(), name: "computer_use_screenshot".into(), args: "{}".into(), status: ToolStatus::Done }];
let req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "blind-model".into(), system: String::new(), history: vec![Message::user("看一下畫面"), asked, shot], tools: vec![], session: String::new(), effort: String::new() };
let cancel = AtomicBool::new(false);
let out = run_step(&req, &cancel, &|_| {}).unwrap();
assert_eq!(out.text, "ok");
let first = rx.recv().unwrap();
let second = rx.recv().unwrap();
assert!(first.contains("SHOTDATA") && !second.contains("SHOTDATA") && second.contains("看不到圖片"), "{second}");
assert!(!sees_images(&req));
}
/// A fake model: refuses pictures when `blind`, else answers `reply`; hands over each request.
fn fake_model(blind: bool, reply: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let (tx, rx) = std::sync::mpsc::channel::<String>();
std::thread::spawn(move || {
for s in l.incoming().flatten() {
let mut s = s;
let mut req = Vec::new();
let mut buf = [0u8; 65536];
loop {
let k = s.read(&mut buf).unwrap_or(0);
if k == 0 {
break;
}
req.extend_from_slice(&buf[..k]);
let text = String::from_utf8_lossy(&req).to_string();
if let Some(end) = text.find("\r\n\r\n") {
let len = text[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))).unwrap_or(0);
if req.len() >= end + 4 + len {
break;
}
}
}
let text = String::from_utf8_lossy(&req).to_string();
let _ = tx.send(text.clone());
if blind && text.contains("image_url") {
let body = r#"{"error":{"message":"This model does not support image input"}}"#;
let _ = write!(s, "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
} else {
let chunk = serde_json::json!({"choices": [{"delta": {"content": reply}}]});
let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {chunk}\n\ndata: [DONE]\n\n");
}
}
});
(format!("http://127.0.0.1:{port}/v1"), rx)
}
#[test]
fn old_pictures_travel_as_a_caption_and_only_the_newest_keep_their_full_description() {
let _g = vision_test_guard();
let (blind_url, _rx) = fake_model(true, "ok");
set_eyes(vec![]);
// The oldest picture has a kept note; it must travel as a caption naming look_image.
notes().lock().unwrap().insert(picture_key("T0xE", false), ("舊圖裡是一張報表,十月營收 42 萬,其餘是小字說明。".into(), "eyes-model".into()));
let mut old = Message::user("第一張");
old.images = vec!["T0xE".into()];
let mut mid = Message::user("第二張");
mid.images = vec!["TUlE".into()];
let mut late = Message::user("第三張");
late.images = vec!["TEFURQ==".into()];
let req = ChatRequest { kind: ProviderKind::Custom, base_url: blind_url, api_key: String::new(), model: "text-only".into(), system: String::new(), history: vec![old, mid, late], tools: vec![], session: String::new(), effort: String::new() };
let out = with_descriptions(&req, &AtomicBool::new(false), &|_| {});
assert!(out.history[0].text.contains("只留摘要") && out.history[0].text.contains("舊圖裡是一張報表") && out.history[0].text.contains("look_image"), "{}", out.history[0].text);
// The newest attachment message is not captioned (no kept note: the blind note lands).
assert!(!out.history[1].text.contains("只留摘要") && !out.history[2].text.contains("只留摘要"), "{}", out.history[1].text);
assert!(out.history[1].images.is_empty() && out.history.iter().all(|m| m.images.is_empty()));
}
#[test]
fn a_model_that_sees_describes_pictures_for_one_that_cannot() {
let _g = vision_test_guard();
let (blind_url, blind_rx) = fake_model(true, "好的,我看到描述了");
let (eyes_url, eyes_rx) = fake_model(false, "一張報表截圖,上面寫著「十月營收 42 萬」。");
set_eyes(vec![
// Not there (a typo in a model name, a dead server…): the next one is asked.
Eyes { kind: ProviderKind::Custom, base_url: "http://127.0.0.1:9/v1".into(), api_key: String::new(), model: "gone".into() },
Eyes { kind: ProviderKind::Custom, base_url: eyes_url, api_key: String::new(), model: "eyes-model".into() },
]);
let mut photo = Message::user("幫我看這張圖");
photo.images = vec!["UElDVFVSRS1PTkU=".into()];
let req = ChatRequest { kind: ProviderKind::Custom, base_url: blind_url, api_key: String::new(), model: "text-only".into(), system: String::new(), history: vec![photo], tools: vec![], session: String::new(), effort: String::new() };
let said = std::sync::Mutex::new(vec![]);
let out = run_step(&req, &AtomicBool::new(false), &|e| {
if let StreamEvent::Retrying(m) = e {
said.lock().unwrap().push(m);
}
})
.unwrap();
assert_eq!(out.text, "好的,我看到描述了");
// The helper got the picture and what the person said with it.
let helper = eyes_rx.recv().unwrap();
assert!(helper.contains("UElDVFVSRS1PTkU=") && helper.contains("幫我看這張圖"));
// The blind model got the description instead of the picture.
let _refused = blind_rx.recv().unwrap();
let again = blind_rx.recv().unwrap();
assert!(!again.contains("UElDVFVSRS1PTkU=") && again.contains("十月營收 42 萬") && again.contains("eyes-model"), "{again}");
assert!(said.lock().unwrap().iter().any(|m| m.contains("看得懂圖")));
// The same picture later: described from memory, no second call to the helper.
let mut photo2 = Message::user("再看一次");
photo2.images = vec!["UElDVFVSRS1PTkU=".into()];
let req2 = ChatRequest { history: vec![photo2], ..req.clone() };
run_step(&req2, &AtomicBool::new(false), &|_| {}).unwrap();
assert!(blind_rx.recv().unwrap().contains("十月營收 42 萬"));
assert!(eyes_rx.recv_timeout(std::time::Duration::from_millis(300)).is_err());
set_eyes(vec![]);
}
#[test]
fn a_local_models_pictures_stay_unless_the_person_lets_a_cloud_model_look() {
let _g = vision_test_guard();
let lan = "http://100.82.106.34:54088/v1";
// A server on Tailscale, Ollama, this computer: kept here; a cloud model's: may go out.
assert!(keeps_pictures_here(ProviderKind::Custom, lan));
assert!(keeps_pictures_here(ProviderKind::Ollama, "http://localhost:11434/v1"));
assert!(!keeps_pictures_here(ProviderKind::Xai, "https://api.x.ai/v1"));
// Turned on for that server (設定 › 模型): its pictures may go to a cloud helper.
set_cloud_eyes_for(vec![format!("{lan}/")]);
assert!(!keeps_pictures_here(ProviderKind::Custom, lan));
assert!(keeps_pictures_here(ProviderKind::Custom, "http://192.168.1.20:8000/v1"), "only the one turned on");
set_cloud_eyes_for(vec![]);
assert!(keeps_pictures_here(ProviderKind::Custom, lan));
// Off, a cloud helper is never asked (nothing is sent: no description comes back).
set_eyes(vec![Eyes { kind: ProviderKind::Xai, base_url: "https://api.x.ai/v1".into(), api_key: "k".into(), model: "grok-4".into() }]);
let not = ChatRequest { kind: ProviderKind::Custom, base_url: lan.into(), api_key: String::new(), model: "husky".into(), system: String::new(), history: vec![], tools: vec![], session: String::new(), effort: String::new() };
assert!(ask_eyes("UElDVFVSRS1PTkU=", "看", &not, &AtomicBool::new(false)).is_none());
set_eyes(vec![]);
}
#[test]
fn steps_without_results_are_closed() {
let mut a = Message::assistant("", "");
a.tool_calls = vec![
ToolCall { id: "t1".into(), name: "shell".into(), args: "{}".into(), status: ToolStatus::Denied },
ToolCall { id: "t2".into(), name: "browser_fill_login".into(), args: "{}".into(), status: ToolStatus::Waiting },
];
let h = vec![Message::user("a"), a, Message::tool_result("t2", "browser_fill_login", "ok"), Message::tool_result("zz", "x", "stray"), Message::user("再一次")];
let r = repair_history(&h);
let roles: Vec<String> = r.iter().map(|m| format!("{:?}:{}", m.role, m.tool_call_id)).collect();
assert_eq!(roles, vec!["User:", "Assistant:", "Tool:t2", "Tool:t1", "User:"]);
assert!(r[3].text.contains("沒有允許"));
// The OpenAI-style body pairs every call with a result.
let req = ChatRequest { kind: ProviderKind::Custom, base_url: String::new(), api_key: String::new(), model: "m".into(), system: String::new(), history: r, tools: vec![], session: String::new(), effort: String::new() };
let msgs = openai_messages(&req);
let i = msgs.iter().position(|m| m["tool_calls"].is_array()).unwrap();
assert_eq!(msgs[i + 1]["role"], "tool");
assert_eq!(msgs[i + 2]["role"], "tool");
}
#[test]
fn cache_breakpoints_mark_the_stable_prefix() {
// cache_tail marks the last block of the last message, in both content shapes.
let m = cache_tail(vec![json!({"role": "user", "content": "hi"})]);
assert_eq!(m[0]["role"], "user");
assert_eq!(m[0]["content"][0]["cache_control"]["type"], "ephemeral");
let m = cache_tail(vec![json!({"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]})]);
assert_eq!(m[0]["content"][1]["cache_control"]["type"], "ephemeral");
assert!(m[0]["content"][0]["cache_control"].is_null());
assert_eq!(cache_tail(vec![]).len(), 0);
let m = cache_tail(vec![json!({"role": "user", "content": []})]);
assert!(m[0]["content"].as_array().unwrap().is_empty());
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// ---------- ChatGPT 方案 (the Responses API) ----------
/// The plan's 「used up」 mark is one for the program: the tests that stream on the plan take turns.
fn plan_turn() -> std::sync::MutexGuard<'static, ()> {
static T: std::sync::Mutex<()> = std::sync::Mutex::new(());
T.lock().unwrap_or_else(|e| e.into_inner())
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
fn plan_req(history: Vec<Message>, tools: Vec<Value>) -> ChatRequest {
// (Whatever the settings say, requests go to chatgpt::api_base(): a test points it at its own server.)
ChatRequest { kind: ProviderKind::ChatGpt, base_url: "https://evil.example/v1".into(), api_key: "stale-from-settings".into(), model: "gpt-6.1-sol".into(), system: "你是助手".into(), history, tools, session: String::new(), effort: String::new() }
}
#[test]
fn the_plan_gets_the_chat_as_responses_items() {
let mut asked = Message::assistant("我看一下", "x");
asked.tool_calls = vec![ToolCall { id: "c1".into(), name: "computer_use_screenshot".into(), args: "{}".into(), status: ToolStatus::Done }];
let mut shot = Message::tool_result("c1", "computer_use_screenshot", "拍好了");
shot.images = vec!["SHOT".into()];
let mut photo = Message::user("這是什麼");
photo.images = vec!["PHOTO".into()];
let req = plan_req(vec![photo, Message::assistant("一隻貓", "x"), Message::user("看螢幕"), asked, shot], vec![]);
let items = responses_input(&req);
// No system item (it goes in `instructions`).
assert!(items.iter().all(|i| i["role"] != "system"), "{items:?}");
assert_eq!(items[0]["content"][0], json!({"type": "input_text", "text": "這是什麼"}));
assert_eq!(items[0]["content"][1], json!({"type": "input_image", "image_url": "data:image/jpeg;base64,PHOTO"}));
assert_eq!(items[1], json!({"role": "assistant", "content": "一隻貓"}));
assert_eq!(items[3], json!({"role": "assistant", "content": "我看一下"}));
assert_eq!(items[4], json!({"type": "function_call", "call_id": "c1", "name": "computer_use_screenshot", "arguments": "{}"}));
assert_eq!(items[5], json!({"type": "function_call_output", "call_id": "c1", "output": "拍好了"}));
// The screenshot follows its result, as the person's picture.
assert_eq!(items[6]["role"], "user");
assert_eq!(items[6]["content"][1]["image_url"], "data:image/jpeg;base64,SHOT");
}
#[test]
fn the_plan_streams_words_and_tool_calls_with_its_own_token_and_address() {
let _turn = plan_turn();
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
use crate::testkit::{Fake, Format, Reply};
let fake = Fake::start(Format::Responses, vec![Reply::text("你好"), Reply::call("call_9", "list_dir", json!({"path": "."}))], None);
let dir = crate::chatgpt::tests::use_test_place("http://127.0.0.1:1");
crate::chatgpt::tests::sign_in_for_test("plan-token", 3_600_000);
crate::chatgpt::tests::use_test_api(Some(fake.base()));
let tools = vec![json!({"name": "list_dir", "description": "List", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}})];
let mut req = plan_req(vec![Message::user("hi")], tools);
req.effort = "high".into();
let cancel = AtomicBool::new(false);
let out = run_step_as_written(&req, &cancel, &|_| {}).unwrap();
assert_eq!(out.text, "你好");
assert_eq!(out.usage, Usage { input: 100, output: 7, cache_read: 20, ..Default::default() });
let raw = fake.raw.lock().unwrap()[0].clone();
assert!(raw.starts_with("POST /v1/responses "), "{raw}");
assert!(raw.to_lowercase().contains("authorization: bearer plan-token"), "{raw}");
let body = fake.bodies.lock().unwrap()[0].clone();
assert_eq!((body["store"].clone(), body["stream"].clone()), (json!(false), json!(true)));
assert_eq!(body["instructions"], "你是助手");
assert_eq!(body["reasoning"]["effort"], "high");
assert_eq!(body["tools"][0], json!({"type": "function", "name": "list_dir", "description": "List", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}, "strict": false}));
// None of what the plan's route refuses.
for k in ["temperature", "max_output_tokens", "previous_response_id", "metadata", "messages", "user"] {
assert!(body.get(k).is_none(), "{k} sent");
}
let out = run_step_as_written(&req, &cancel, &|_| {}).unwrap();
assert_eq!(out.tool_calls.len(), 1);
assert_eq!((out.tool_calls[0].id.as_str(), out.tool_calls[0].name.as_str()), ("call_9", "list_dir"));
assert_eq!(serde_json::from_str::<Value>(&out.tool_calls[0].args).unwrap(), json!({"path": "."}));
crate::chatgpt::tests::use_test_api(None);
crate::chatgpt::tests::leave_test_place(dir);
}
#[test]
fn a_used_up_plan_stops_and_says_where_to_look() {
let _turn = plan_turn();
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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("又能用了")));
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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"));
// Used up: what nobody watches isn't sent until one goes through again; a watched turn still asks.
assert!(crate::chatgpt::limited());
set_patient(true);
let e = run_step_as_written(&plan_req(vec![Message::user("例行")], vec![]), &AtomicBool::new(false), &|_| {}).unwrap_err();
set_patient(false);
assert!(e.contains("已達用量上限") && fake.requests() == 1, "{e}");
assert_eq!(run_step_as_written(&plan_req(vec![Message::user("hi")], vec![]), &AtomicBool::new(false), &|_| {}).unwrap().text, "又能用了");
assert!(!crate::chatgpt::limited());
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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() {
let _turn = plan_turn();
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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}");
// An incomplete answer isn't an answer: its steps aren't run.
let incomplete = [
format!("event: response.output_item.done\ndata: {}\n\n", json!({"type": "response.output_item.done", "item": {"type": "function_call", "call_id": "c1", "name": "shell", "arguments": "{}"}})),
format!("event: response.incomplete\ndata: {}\n\n", json!({"type": "response.incomplete", "response": {"incomplete_details": {"reason": "max_output_tokens"}}})),
]
.concat();
let fake2 = Fake::start(Format::Responses, vec![Reply::Raw(200, incomplete)], None);
crate::chatgpt::tests::use_test_api(Some(fake2.base()));
let e = run_step_as_written(&req, &AtomicBool::new(false), &|_| {}).unwrap_err();
assert!(e.contains("長度上限"), "{e}");
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
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);
}
}