AnyBot/src/providers.rs

2127 lines
105 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,
Anthropic,
Gemini,
OpenRouter,
OpenCodeGo,
Ollama,
Custom,
}
pub const ALL_PROVIDERS: [ProviderKind; 8] = [
ProviderKind::Xai,
ProviderKind::OpenAi,
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",
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",
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",
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",
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"],
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 金鑰",
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,
/// 目標: the check after a turn has spoken (for the goal set at this time, ms).
Goal(i64, crate::goal::Judged),
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),
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>,
}
/// 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 4 s.
pub fn backoff_delay_ms(retry: u32) -> u64 {
(RETRY_INITIAL_DELAY_MS * RETRY_BACKOFF_FACTOR.pow(retry.saturating_sub(1))).min(RETRY_MAX_DELAY_MS)
}
fn agent() -> ureq::Agent {
let config = ureq::Agent::config_builder()
.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 {
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 {
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)
}
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 {
401 | 403 => "金鑰無效或沒有權限,請到「設定 → AI 供應商」檢查。",
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> {
// 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;
if req.kind.needs_key() && req.api_key.is_empty() {
return Err(format!("還沒有設定 {} 的 API 金鑰。請到「設定 → AI 供應商」貼上金鑰。", 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;
// 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),
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 < RETRY_MAX_ATTEMPTS && !cancel.load(Ordering::Relaxed) => {
send(StreamEvent::Retrying(format!("模型這次沒有回任何內容,再問一次(第 {} 次,共 {} 次)…", attempt + 1, RETRY_MAX_ATTEMPTS)));
std::thread::sleep(Duration::from_millis(backoff_delay_ms(attempt)));
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 < RETRY_MAX_ATTEMPTS && !cancel.load(Ordering::Relaxed) => {
let wait = f.retry_after_ms.unwrap_or_else(|| backoff_delay_ms(attempt));
send(StreamEvent::Retrying(format!("{}\n{:.0} 秒後重試(第 {} 次,共 {} 次)…", f.msg, wait as f64 / 1000.0, attempt + 1, RETRY_MAX_ATTEMPTS)));
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", "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![]);
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()
}
安全、修正: 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 is_local_model(kind: ProviderKind, base_url: &str) -> bool {
if kind == ProviderKind::Ollama {
return true;
}
!crate::web::is_private_browser_url(base_url).eq(&false)
}
/// 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)> {
安全、修正: 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
let keep_local = is_local_model(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.
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});
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;
}
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)
}
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
}
/// (input_tokens, cache_read_input_tokens, cache_creation_input_tokens) summed over the
/// session's Claude answers: the cache hit rate is the number that tells whether the
/// breakpoints work (see `anybot` diagnostics / make doctor).
static CACHE_STATS: std::sync::Mutex<(u64, u64, u64)> = std::sync::Mutex::new((0, 0, 0));
安全、修正: 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
#[allow(dead_code)]
pub fn cache_stats() -> (u64, u64, u64) {
*CACHE_STATS.lock().unwrap_or_else(|e| e.into_inner())
}
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);
let mut s = CACHE_STATS.lock().unwrap_or_else(|e| e.into_inner());
s.0 += g("input_tokens");
s.1 += g("cache_read_input_tokens");
s.2 += g("cache_creation_input_tokens");
}
}
"message_delta" => {
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" | …
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()?;
let ep = m["endpoint"].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> {
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_delay_ms(1), backoff_delay_ms(2), backoff_delay_ms(3)], [1000, 2000, 4000]);
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);
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: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 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());
}
}