AnyBot/src/setup.rs

1543 lines
61 KiB
Rust
Raw Normal View History

// `anybot setup`: join this computer to your AnyBot, as hands for your brain (or as a brain), from
// a terminal (over SSH, or on a computer without a window). As little to answer as possible:
//
// anybot setup https://anybot.example.com 482913 the line 「加一台電腦」 shows on the phone or in
// the app: nothing to answer at all
// anybot setup one screen: the address and the code (or the
// account and password instead)
// anybot setup --brain … this computer is a brain, not hands
//
// Then it saves the settings, makes AnyBot start with the computer (systemd; a virtual screen when
// there is none), and waits until the account server and the brain see it. For scripts:
// anybot setup --server URL --user NAME [--brain-name 雲端大腦] [--no-service]
// with the password in ANYBOT_ACCOUNT_PASSWORD.
use crate::model::State;
use crate::remote::{self, Settings};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use crossterm::style::{Attribute, Color, Print, ResetColor, SetAttribute, SetForegroundColor};
use crossterm::{cursor, execute, queue, terminal};
use std::io::{IsTerminal, Write};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::time::{Duration, Instant};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
const ACC: Color = Color::Cyan;
const GOOD: Color = Color::Green;
const WARN: Color = Color::Yellow;
const BAD: Color = Color::Red;
const DIM: Color = Color::DarkGrey;
const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const UNIT: &str = "anybot.service";
/// Write a file all at once, as far as the filesystem allows: tmp file + rename. A Ctrl+C in
/// the middle of installing used to leave a half-written launcher/unit behind, and systemd
/// then ran (or refused to run) a broken service with no easy way to see why.
fn write_atomic(path: &std::path::Path, body: String) -> std::io::Result<()> {
let tmp = path.with_extension("anybot-tmp");
std::fs::write(&tmp, body)?;
std::fs::rename(&tmp, path)?;
Ok(())
}
/// Quote a path for a systemd ExecStart line: a home folder with spaces (or a quote sign)
/// made the unit fail to start with no way to see why.
/// The launcher is started by systemd (`ExecStart=`) and by the terminal, so it must be executable.
fn make_executable(path: &std::path::Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
}
#[cfg(not(unix))]
let _ = path;
}
fn systemd_quote(p: &std::path::Path) -> String {
let mut out = String::from("\"");
for c in p.display().to_string().chars() {
match c {
'"' | '$' | '\\' | '`' => {
out.push('\\');
out.push(c);
}
c => out.push(c),
}
}
out.push('"');
out
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Role {
Hands,
Brain,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Step {
Form,
Brain,
Install,
Done,
}
#[derive(Clone, Debug)]
struct Peer {
id: String,
name: String,
online: bool,
last: String,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Mark {
Wait,
Run,
Ok,
Warn,
Fail,
}
/// Joining an account: its settings, the brain a code was made for, the brains to choose from.
type Joining = Result<(Settings, Option<Peer>, Vec<Peer>), String>;
enum Msg {
/// Joined the account; with a code, the brain it was made for.
Joined(Box<Joining>),
Progress(usize, Mark, String),
Finished(Vec<String>),
}
/// What this computer has.
#[derive(Clone)]
struct Env {
linux: bool,
display: String,
systemd: bool,
}
impl Env {
fn detect() -> Env {
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
// "wayland" when only Wayland is there (nothing to remember for a service).
let linux = cfg!(target_os = "linux");
// A Mac or Windows PC always has its screen.
let display = if !linux { "desktop".to_string() } else { var("DISPLAY").or_else(|| var("WAYLAND_DISPLAY").map(|_| "wayland".to_string())).unwrap_or_default() };
let systemd = linux
&& std::process::Command::new("systemctl")
.args(["--user", "is-system-running"])
.output()
.map(|o| {
let out = String::from_utf8_lossy(&o.stdout);
!out.trim().is_empty() && !out.contains("offline")
})
.unwrap_or(false);
Env { linux, display, systemd }
}
fn has_display(&self) -> bool {
!self.display.is_empty()
}
}
// ---------- drawing ----------
#[derive(Clone, Copy, Default)]
struct Sty {
fg: Option<Color>,
bold: bool,
}
type Span = (String, Sty);
type Line = Vec<Span>;
fn sp(s: impl Into<String>, fg: Option<Color>, bold: bool) -> Span {
(s.into(), Sty { fg, bold })
}
fn plain(s: impl Into<String>) -> Span {
sp(s, None, false)
}
fn dim(s: impl Into<String>) -> Span {
sp(s, Some(DIM), false)
}
fn strong(s: impl Into<String>) -> Span {
sp(s, None, true)
}
fn colored(s: impl Into<String>, c: Color) -> Span {
sp(s, Some(c), false)
}
fn width(l: &Line) -> usize {
l.iter().map(|(s, _)| s.width()).sum()
}
/// Break text to lines at most `w` wide (anywhere: Chinese has no spaces).
fn wrap(text: &str, w: usize) -> Vec<String> {
let mut out = vec![];
for para in text.split('\n') {
let mut cur = String::new();
let mut cw = 0;
for ch in para.chars() {
let c = ch.width().unwrap_or(0);
if cw + c > w && !cur.is_empty() {
// A line never starts with closing punctuation: take the last character along.
let closing = |c: char| "。,、;:」)!?』,.;:!?)".contains(c);
let mut carry = String::new();
if closing(ch) {
while let Some(p) = cur.pop() {
carry.insert(0, p);
if !closing(p) || cur.is_empty() {
break;
}
}
}
out.push(std::mem::take(&mut cur));
cw = carry.width();
cur = carry;
}
cur.push(ch);
cw += c;
}
out.push(cur);
}
out
}
fn para(text: &str, indent: usize, w: usize, f: fn(String) -> Span) -> Vec<Line> {
wrap(text, w.saturating_sub(indent).max(10)).into_iter().map(|t| vec![plain(" ".repeat(indent)), f(t)]).collect()
}
/// Cut a line to `w` columns.
fn clip(l: Line, w: usize) -> Line {
let mut out = vec![];
let mut used = 0;
for (s, st) in l {
let mut keep = String::new();
for ch in s.chars() {
let c = ch.width().unwrap_or(0);
if used + c > w {
break;
}
keep.push(ch);
used += c;
}
out.push((keep, st));
if used >= w {
break;
}
}
out
}
// ---------- the setup ----------
struct Wiz {
env: Env,
step: Step,
role: Role,
/// Sign in with the account and password instead of a code.
password: bool,
url: String,
code: String,
user: String,
pass: String,
focus: usize,
joined: Option<Settings>,
peers: Vec<Peer>,
sel: usize,
brain: Option<Peer>,
busy: Option<String>,
rx: Option<Receiver<Msg>>,
tx: Sender<Msg>,
spin: usize,
error: String,
progress: Vec<(String, Mark, String)>,
tips: Vec<String>,
ok: bool,
quit: bool,
service: bool,
name: Option<String>,
}
impl Wiz {
fn new(role: Role) -> Wiz {
let saved = State::load().remote;
let (tx, rx) = channel();
let env = Env::detect();
Wiz {
role,
password: false,
step: Step::Form,
url: saved.relay_url.clone(),
code: String::new(),
user: saved.relay_user.clone(),
pass: String::new(),
focus: if saved.relay_url.is_empty() { 0 } else { 1 },
joined: None,
peers: vec![],
sel: 0,
brain: None,
busy: None,
rx: Some(rx),
tx,
spin: 0,
error: String::new(),
progress: vec![],
tips: vec![],
ok: false,
quit: 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
service: env.systemd || cfg!(target_os = "macos") || cfg!(target_os = "windows"),
env,
name: None,
}
}
/// The rows of the form: text fields, then the switch to the other way of signing in.
fn rows(&self) -> usize {
if self.password {
4
} else {
3
}
}
fn title(&self) -> (String, String) {
match self.step {
Step::Form => (
match self.role {
Role::Hands => "把這台電腦接到你的 AnyBot".into(),
Role::Brain => "把這台設成大腦".into(),
},
if self.password { "用手機登入 AnyBot 的那個網址和帳號。".into() } else { "在手機或電腦的 AnyBot 按「加一台電腦」,會看到網址和配對碼。".into() },
),
Step::Brain => ("要給哪個大腦用?".into(), "帳號裡有好幾台,選一台:只有它能用這台電腦。".into()),
Step::Install => ("正在設定…".into(), String::new()),
Step::Done => (if self.ok { "好了".into() } else { "沒有完成".into() }, String::new()),
}
}
fn field(&self, label: &str, value: &str, focused: bool, secret: bool, hint: &str) -> Line {
let shown = if secret { "●".repeat(value.chars().count()) } else { value.to_string() };
let mut l = vec![if focused { colored("❯ ", ACC) } else { plain(" ") }, sp(format!("{label}{}", " ".repeat(8usize.saturating_sub(label.width()))), Some(if focused { ACC } else { DIM }), focused)];
if shown.is_empty() && !focused {
l.push(dim(hint));
} else {
l.push(strong(shown));
if focused {
l.push(colored("▌", ACC));
if value.is_empty() && !hint.is_empty() {
l.push(dim(format!(" {hint}")));
}
}
}
l
}
fn body(&self, w: usize) -> Vec<Line> {
let mut b: Vec<Line> = vec![];
match self.step {
Step::Form => {
b.push(self.field("網址", &self.url, self.focus == 0, false, "https://…"));
if self.password {
b.push(self.field("帳號", &self.user, self.focus == 1, false, ""));
b.push(self.field("密碼", &self.pass, self.focus == 2, true, ""));
} else {
b.push(self.field("配對碼", &self.code, self.focus == 1, false, "6 位數字"));
}
b.push(vec![]);
let on = self.focus == self.rows() - 1;
let other = if self.password { "改用配對碼 ›" } else { "沒有配對碼?用帳號密碼登入 ›" };
b.push(vec![if on { colored("❯ ", ACC) } else { plain(" ") }, sp(other, Some(if on { ACC } else { DIM }), false)]);
}
Step::Brain => {
for (i, p) in self.peers.iter().enumerate() {
let on = self.sel == i;
let status = if p.online { colored("在線上", GOOD) } else { dim(format!("離線({})", p.last)) };
let name = format!("{} ", p.name);
let pad = 28usize.saturating_sub(name.width());
b.push(vec![if on { colored("❯ ", ACC) } else { plain(" ") }, sp(if p.online { "● " } else { "○ " }, Some(if p.online { GOOD } else { DIM }), false), sp(name, if on { Some(ACC) } else { None }, true), plain(" ".repeat(pad)), status]);
}
}
Step::Install | Step::Done => b.extend(progress_lines(&self.progress, &self.tips, self.spin, w)),
}
if let Some(what) = &self.busy {
b.push(vec![]);
b.push(vec![colored(SPIN[self.spin % SPIN.len()], ACC), plain(" "), colored(what.clone(), ACC)]);
}
if !self.error.is_empty() {
b.push(vec![]);
for (i, l) in wrap(&self.error, w.saturating_sub(2)).into_iter().enumerate() {
b.push(vec![colored(if i == 0 { "✗ " } else { " " }, BAD), colored(l, BAD)]);
}
}
b
}
fn keys(&self) -> &'static str {
if self.busy.is_some() || self.step == Step::Install {
return "Ctrl+C 離開";
}
match self.step {
Step::Form => "Enter 連線 ↑↓ 換欄位 Esc 離開",
Step::Brain => "↑↓ 選擇 Enter 確定",
_ => "Enter 離開",
}
}
fn render(&self, out: &mut impl Write) -> std::io::Result<()> {
let (cols, rows) = terminal::size().unwrap_or((80, 24));
let (title, sub) = self.title();
let lines = card_page(cols as usize, &title, &sub, |w| self.body(w), self.keys());
draw(out, lines, cols as usize, rows as usize)
}
// ----- moving along -----
fn start(&mut self, what: &str, job: impl FnOnce() -> Msg + Send + 'static) {
self.error.clear();
self.busy = Some(what.to_string());
let tx = self.tx.clone();
std::thread::spawn(move || {
let _ = tx.send(job());
});
}
fn submit(&mut self) {
let base = base_settings(self.name.clone());
let url = self.url.clone();
if self.password {
let (user, pass) = (self.user.trim().to_string(), self.pass.clone());
if user.is_empty() || pass.is_empty() {
self.error = "請輸入帳號和密碼".into();
return;
}
self.start("正在登入…", move || Msg::Joined(Box::new(join_with_password(&base, &url, &user, &pass))));
} else {
let code: String = self.code.chars().filter(|c| c.is_ascii_digit()).collect();
if code.len() != 6 {
self.error = "配對碼是 6 位數字".into();
self.focus = 1;
return;
}
// (Whole, as typed: a key may ride behind the digits; pair_claim keeps it here.)
let code = self.code.clone();
self.start("正在連線…", move || Msg::Joined(Box::new(remote::pair_claim(&base, &url, &code).map(|s| (s.clone(), brain_of(&s), vec![])))));
}
}
fn install(&mut self) {
self.step = Step::Install;
let plan = Plan { role: self.role, settings: self.joined.clone().unwrap_or_default(), brain: self.brain.clone(), env: self.env.clone(), service: self.service };
self.progress = plan.steps().into_iter().map(|s| (s, Mark::Wait, String::new())).collect();
let tx = self.tx.clone();
std::thread::spawn(move || plan.run(&tx));
}
fn on_msg(&mut self, m: Msg) {
match m {
Msg::Joined(r) => {
self.busy = None;
match *r {
Ok((s, brain, choices)) => {
self.joined = Some(s);
self.pass.clear();
if self.role == Role::Hands && brain.is_none() && choices.len() > 1 {
self.sel = choices.iter().position(|p| p.online).unwrap_or(0);
self.peers = choices;
self.step = Step::Brain;
} else {
self.brain = brain;
self.install();
}
}
Err(e) => self.error = e,
}
}
Msg::Progress(i, mark, note) => {
if let Some(p) = self.progress.get_mut(i) {
p.1 = mark;
p.2 = note;
}
}
Msg::Finished(tips) => {
self.ok = !self.progress.iter().any(|p| p.1 == Mark::Fail);
self.tips = tips;
self.step = Step::Done;
}
}
}
fn key(&mut self, code: KeyCode, mods: KeyModifiers) {
if mods.contains(KeyModifiers::CONTROL) && matches!(code, KeyCode::Char('c') | KeyCode::Char('d')) {
self.quit = true;
return;
}
if self.busy.is_some() || self.step == Step::Install {
return;
}
if self.step == Step::Done {
if matches!(code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q')) {
self.quit = true;
}
return;
}
if self.step == Step::Brain {
let n = self.peers.len().max(1);
match code {
KeyCode::Up => self.sel = (self.sel + n - 1) % n,
KeyCode::Down => self.sel = (self.sel + 1) % n,
KeyCode::Enter => {
self.brain = self.peers.get(self.sel).cloned();
self.install();
}
_ => {}
}
return;
}
let rows = self.rows();
match code {
KeyCode::Esc => self.quit = true,
KeyCode::Up | KeyCode::BackTab => self.focus = (self.focus + rows - 1) % rows,
KeyCode::Down | KeyCode::Tab => self.focus = (self.focus + 1) % rows,
KeyCode::Enter if self.focus == rows - 1 => {
// The switch between a code and the password.
self.password = !self.password;
self.error.clear();
self.focus = 1;
}
KeyCode::Enter if self.focus + 2 < rows && !self.field_done() => self.focus += 1,
KeyCode::Enter => self.submit(),
KeyCode::Char('u') if mods.contains(KeyModifiers::CONTROL) => {
if let Some(f) = self.text_field() {
f.clear();
}
}
KeyCode::Char(c) if !mods.contains(KeyModifiers::CONTROL) => self.type_text(&c.to_string()),
KeyCode::Backspace => {
if let Some(f) = self.text_field() {
f.pop();
}
}
_ => {}
}
}
/// Every text field is filled (Enter connects from anywhere then).
fn field_done(&self) -> bool {
!self.url.trim().is_empty() && if self.password { !self.user.trim().is_empty() && !self.pass.is_empty() } else { !self.code.trim().is_empty() }
}
fn text_field(&mut self) -> Option<&mut String> {
match (self.password, self.focus) {
(_, 0) => Some(&mut self.url),
(false, 1) => Some(&mut self.code),
(true, 1) => Some(&mut self.user),
(true, 2) => Some(&mut self.pass),
_ => None,
}
}
fn type_text(&mut self, s: &str) {
let s: String = s.chars().filter(|c| !c.is_control()).collect();
// A pasted 「anybot setup 網址 配對碼」 line (or the 「curl … | sh -s -- hands 網址 配對碼」 one)
// fills both.
let words: Vec<&str> = s.split_whitespace().collect();
let n = words.len();
if n >= 2 && words[n - 1].chars().all(|c| c.is_ascii_digit()) && words[n - 2].contains("://") && !self.password {
self.url = words[n - 2].to_string();
self.code = words[n - 1].to_string();
self.focus = 1;
return;
}
if let Some(f) = self.text_field() {
f.push_str(&s);
}
}
}
/// The brain a pairing code was made for.
fn brain_of(s: &Settings) -> Option<Peer> {
(!s.hands_for.is_empty()).then(|| Peer { id: s.hands_for.clone(), name: s.hands_for_name.clone(), online: true, last: String::new() })
}
/// Sign in with the password; the brain is picked when there is only one to pick.
fn join_with_password(base: &Settings, url: &str, user: &str, pass: &str) -> Result<(Settings, Option<Peer>, Vec<Peer>), String> {
let url = remote::check_server(url)?;
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
// (No field for a 兩步驗證 code on these pages: the pairing code is the way in then.)
let s = remote::relay_join(base, &url, user, pass, false, "", "").map_err(|e| if e.starts_with(remote::NEED_CODE) { format!("{e}這裡請改用配對碼:在手機或電腦的 AnyBot 按「加一台電腦」。") } else { e })?;
let list = list_brains(&s).unwrap_or_default();
let online: Vec<&Peer> = list.iter().filter(|p| p.online).collect();
let brain = if list.len() == 1 { list.first().cloned() } else if online.len() == 1 { Some(online[0].clone()) } else { None };
Ok((s, brain, list))
}
/// A page: the name on top, one card, the keys below.
fn card_page(cols: usize, title: &str, sub: &str, body: impl Fn(usize) -> Vec<Line>, keys: &str) -> Vec<Line> {
let w = cols.saturating_sub(4).clamp(36, 78);
let inner = w - 4;
let mut lines: Vec<Line> = vec![vec![], vec![plain(" "), colored("◆ ", ACC), strong("AnyBot")], vec![]];
let mut card: Vec<Line> = vec![vec![], vec![strong(title)]];
if !sub.is_empty() {
card.extend(para(sub, 0, inner, dim));
}
card.push(vec![]);
card.extend(body(inner));
card.push(vec![]);
let edge = |l: &str, r: &str| vec![plain(" "), dim(format!("{l}{}{r}", "─".repeat(w - 2)))];
lines.push(edge("╭", "╮"));
for l in card {
let l = clip(l, inner);
let pad = inner.saturating_sub(width(&l));
let mut row = vec![plain(" "), dim("│ ")];
row.extend(l);
row.push(plain(" ".repeat(pad)));
row.push(dim(" │"));
lines.push(row);
}
lines.push(edge("╰", "╯"));
lines.push(vec![plain(" "), dim(keys)]);
lines
}
fn draw(out: &mut impl Write, lines: Vec<Line>, cols: usize, rows: usize) -> std::io::Result<()> {
queue!(out, terminal::BeginSynchronizedUpdate, terminal::Clear(terminal::ClearType::All))?;
for (y, l) in lines.into_iter().enumerate().take(rows) {
queue!(out, cursor::MoveTo(0, y as u16))?;
print_line(out, l, cols)?;
}
queue!(out, terminal::EndSynchronizedUpdate)?;
out.flush()
}
fn print_line(out: &mut impl Write, l: Line, cols: usize) -> std::io::Result<()> {
for (s, st) in clip(l, cols) {
if let Some(c) = st.fg {
queue!(out, SetForegroundColor(c))?;
}
if st.bold {
queue!(out, SetAttribute(Attribute::Bold))?;
}
queue!(out, Print(s), SetAttribute(Attribute::Reset), ResetColor)?;
}
Ok(())
}
/// The steps with their marks, then the tips.
fn progress_lines(progress: &[(String, Mark, String)], tips: &[String], spin: usize, w: usize) -> Vec<Line> {
let mut b: Vec<Line> = vec![];
for (label, mark, note) in progress {
let icon = match mark {
Mark::Wait => dim("·"),
Mark::Run => colored(SPIN[spin % SPIN.len()], ACC),
Mark::Ok => colored("✓", GOOD),
Mark::Warn => colored("!", WARN),
Mark::Fail => colored("✗", BAD),
};
b.push(vec![icon, plain(" "), sp(label.clone(), if *mark == Mark::Wait { Some(DIM) } else { None }, *mark == Mark::Run)]);
if !note.is_empty() {
let f: fn(String) -> Span = match mark {
Mark::Fail => |s| colored(s, BAD),
Mark::Warn => |s| colored(s, WARN),
_ => dim,
};
b.extend(para(note, 2, w, f));
}
}
if !tips.is_empty() {
b.push(vec![]);
for t in tips {
if let Some((k, v)) = t.split_once('\t') {
b.push(vec![dim(format!("{k}{}", " ".repeat(10usize.saturating_sub(k.width())))), colored(v.to_string(), ACC)]);
} else {
b.extend(para(t, 0, w, plain));
}
}
}
b
}
/// The account's AnyBots that can be a brain (not this one, not one showing another's bots).
fn list_brains(s: &Settings) -> Result<Vec<Peer>, String> {
let all = remote::peers(s)?;
let mut v: Vec<Peer> = all
.iter()
.filter(|h| h["id"].as_str() != Some(s.host_id.as_str()) && h["uses"].as_str().unwrap_or("").is_empty() && h["hands"].as_bool() != Some(true))
.map(|h| Peer {
id: h["id"].as_str().unwrap_or("").into(),
name: h["name"].as_str().unwrap_or("").into(),
online: h["online"].as_bool().unwrap_or(false),
last: h["last_seen_text"].as_str().unwrap_or("").into(),
})
.collect();
v.sort_by_key(|p| !p.online);
Ok(v)
}
// ---------- doing it ----------
struct Plan {
role: Role,
settings: Settings,
brain: Option<Peer>,
env: Env,
service: bool,
}
impl Plan {
fn steps(&self) -> Vec<String> {
let mut v = vec!["儲存設定".to_string(), "開機自動執行".into(), "連上帳號伺服器".into()];
if let (Role::Hands, Some(b)) = (self.role, &self.brain) {
v.push(format!("大腦「{}」", b.name));
}
v
}
fn run(&self, tx: &Sender<Msg>) {
let say = |i: usize, m: Mark, n: &str| {
let _ = tx.send(Msg::Progress(i, m, n.to_string()));
};
// 1. Settings (this AnyBot's own file; the service reads it).
say(0, Mark::Run, "");
if self.service {
stop_running();
}
// No other AnyBot may be using this folder while the settings are written (a window
// would overwrite them with its own copy). The service was just stopped: give it a
// moment to let go.
let folder = match crate::lock::take(Duration::from_secs(10)) {
Ok(l) => l,
Err(e) => {
say(0, Mark::Fail, &e);
let _ = tx.send(Msg::Finished(vec!["關掉另一個 AnyBot 之後,再執行一次 anybot setup。".into()]));
return;
}
};
let mut st = State::load();
let mut r = self.settings.clone();
match self.role {
Role::Hands => {
r.device_link = true;
match &self.brain {
Some(b) => {
r.hands_for = b.id.clone();
r.hands_for_name = b.name.clone();
}
None => {
r.hands_for.clear();
r.hands_for_name.clear();
}
}
}
Role::Brain => {
// A brain shows its own bots and lends its hands to no one.
r.brain_id.clear();
r.brain_name.clear();
r.hands_for.clear();
r.hands_for_name.clear();
r.device_link = false;
}
}
st.remote = r.clone();
st.save();
// Let go before the service starts again (it takes the folder next).
drop(folder);
say(0, Mark::Ok, "");
// 2. Start with the computer (Linux systemd, macOS launchd, Windows 登入工作).
say(1, Mark::Run, "");
let started = if !self.service {
say(1, Mark::Warn, "沒有設開機自動執行。要連上請開 AnyBot,或執行 anybot --serve。");
false
} else {
match self.install_service() {
Ok(note) => {
say(1, Mark::Ok, &note);
true
}
Err(e) => {
say(1, Mark::Fail, &e);
false
}
}
};
// 3. The account server sees it.
if started {
say(2, Mark::Run, "");
let t0 = Instant::now();
let mut seen = false;
while t0.elapsed() < Duration::from_secs(40) {
if let Ok(all) = remote::peers(&r) {
if all.iter().any(|h| h["id"].as_str() == Some(r.host_id.as_str()) && h["online"].as_bool() == Some(true)) {
seen = true;
break;
}
}
std::thread::sleep(Duration::from_secs(1));
}
if seen {
say(2, Mark::Ok, &format!("已連線({} 秒)", t0.elapsed().as_secs().max(1)));
} else {
say(2, Mark::Fail, &format!("40 秒內沒有連上。看看紀錄:{}", log_hint()));
}
} else {
say(2, Mark::Warn, "啟動 AnyBot 後就會連上。");
}
// 4. The brain is there.
if let (Role::Hands, Some(b)) = (self.role, &self.brain) {
say(3, Mark::Run, "");
let online = remote::peers(&r).ok().and_then(|all| all.iter().find(|h| h["id"].as_str() == Some(b.id.as_str())).map(|h| h["online"].as_bool() == Some(true)));
match online {
Some(true) => say(3, Mark::Ok, "在線上。大腦約一分鐘內就會看到這台,它的 Bot 就能用這台了。"),
Some(false) => say(3, Mark::Warn, "目前離線;它開機連上後就能用這台。"),
None => say(3, Mark::Warn, "帳號裡找不到它了(被移除了?)"),
}
}
let mut tips = vec![];
match self.role {
Role::Hands => tips.push(format!("在大腦上跟 Bot 說「用 {} 的瀏覽器打開…」或「看一下 {} 的畫面」試試。", r.host_name, r.host_name)),
Role::Brain => tips.push("其他電腦:AnyBot › 設定 › 一般 › 手機與帳號,登入同一個帳號,在「大腦」選這台。沒有視窗的 Linux:anybot setup 選「手腳」。".into()),
}
if started {
tips.push(String::new());
tips.push(format!("看狀態\t{}", status_hint()));
tips.push(format!("看紀錄\t{}", log_hint()));
}
tips.push("改設定\tanybot setup".into());
if started && self.env.linux && self.env.systemd && !lingering() {
tips.push(String::new());
tips.push(format!("登出或重開機後也要繼續跑,請執行一次:sudo loginctl enable-linger {}", std::env::var("USER").unwrap_or_default()));
}
if cfg!(target_os = "macos") && self.role == Role::Hands {
tips.push("權限\t系統設定 › 隱私權與安全性:螢幕錄製、輔助使用,打開 AnyBot(只問一次)".into());
}
if cfg!(target_os = "windows") && self.role == Role::Hands {
tips.push("畫面\tBot 操控的是你登入中的桌面。鎖定或登出後點不到,登入就會恢復。".into());
}
let _ = tx.send(Msg::Finished(tips));
}
/// Start with the computer: systemd, launchd, or a Windows logon task. Linux without
/// systemd still gets a launcher and is started once.
fn install_service(&self) -> Result<String, String> {
let exe = std::env::current_exe().and_then(|p| p.canonicalize()).map_err(|e| format!("找不到 AnyBot 程式:{e}"))?;
if cfg!(target_os = "macos") {
return install_launchd(&exe);
}
if cfg!(target_os = "windows") {
return install_schtasks(&exe);
}
self.install_systemd(&exe)
}
/// A small launcher and a systemd user service that runs it.
fn install_systemd(&self, exe: &std::path::Path) -> Result<String, String> {
let home = dirs::home_dir().ok_or("找不到家目錄")?;
let bin = home.join(".local/bin");
std::fs::create_dir_all(&bin).map_err(|e| format!("建立 {} 失敗:{e}", bin.display()))?;
let launcher = bin.join("anybot-run");
write_atomic(&launcher, launcher_script(self.role, exe, &self.env)).map_err(|e| format!("寫入 {} 失敗:{e}", launcher.display()))?;
make_executable(&launcher);
let units = home.join(".config/systemd/user");
std::fs::create_dir_all(&units).map_err(|e| e.to_string())?;
// An older setup (deploy/linux/hands.sh) used another service name.
if units.join("anybot-hands.service").exists() {
let _ = systemctl(&["disable", "--now", "anybot-hands.service"]);
let _ = std::fs::remove_file(units.join("anybot-hands.service"));
}
let what = match self.role {
Role::Hands => "手腳",
Role::Brain => "大腦",
};
let unit = format!(
"[Unit]\nDescription=AnyBot({what})\nAfter=network-online.target graphical-session.target\nWants=network-online.target\n\n[Service]\nExecStart={}\nRestart=always\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n",
systemd_quote(&launcher)
);
write_atomic(&units.join(UNIT), unit).map_err(|e| e.to_string())?;
if !self.env.systemd {
let _ = std::process::Command::new(&launcher).spawn();
return Ok(format!("這台沒有 systemd,已先啟動一次({})。請把這支加進開機(OpenRC、cron @reboot)。", launcher.display()));
}
systemctl(&["daemon-reload"])?;
systemctl(&["enable", UNIT])?;
systemctl(&["restart", UNIT])?;
let _ = std::process::Command::new("sudo").args(["-n", "loginctl", "enable-linger", &std::env::var("USER").unwrap_or_default()]).status();
Ok(format!("systemd 使用者服務「anybot」,已啟動({})", launcher.display()))
}
}
fn log_hint() -> &'static str {
if cfg!(target_os = "macos") {
"tail -f ~/Library/Logs/anybot-serve.log"
} else if cfg!(target_os = "windows") {
"工作排程器 › AnyBot › 歷程記錄"
} else {
"journalctl --user -u anybot -n 50"
}
}
fn status_hint() -> &'static str {
if cfg!(target_os = "macos") {
"launchctl print gui/$(id -u)/com.anybot.serve"
} else if cfg!(target_os = "windows") {
"schtasks /Query /TN AnyBot"
} else {
"systemctl --user status anybot"
}
}
fn uid() -> String {
std::process::Command::new("id").arg("-u").output().ok().and_then(|o| String::from_utf8(o.stdout).ok()).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "0".into())
}
fn stop_running() {
if cfg!(target_os = "linux") {
let _ = systemctl(&["stop", UNIT]);
} else if cfg!(target_os = "macos") {
let _ = std::process::Command::new("launchctl").args(["bootout", &format!("gui/{}/com.anybot.serve", uid())]).status();
} else if cfg!(target_os = "windows") {
let _ = std::process::Command::new("schtasks").args(["/End", "/TN", "AnyBot"]).status();
}
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
fn launchd_plist(exe: &std::path::Path) -> String {
let home = dirs::home_dir().map(|h| h.display().to_string()).unwrap_or_else(|| "/tmp".into());
let log = xml_escape(&format!("{home}/Library/Logs/anybot-serve.log"));
let bin = xml_escape(&exe.display().to_string());
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>com.anybot.serve</string>
<key>ProgramArguments</key>
<array><string>{bin}</string><string>--serve</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardErrorPath</key><string>{log}</string>
<key>StandardOutPath</key><string>{log}</string>
</dict></plist>
"#
)
}
fn install_launchd(exe: &std::path::Path) -> Result<String, String> {
let home = dirs::home_dir().ok_or("找不到家目錄")?;
let dir = home.join("Library/LaunchAgents");
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let _ = std::fs::create_dir_all(home.join("Library/Logs"));
let plist = dir.join("com.anybot.serve.plist");
write_atomic(&plist, launchd_plist(exe)).map_err(|e| e.to_string())?;
let uid = uid();
let target = format!("gui/{uid}/com.anybot.serve");
let _ = std::process::Command::new("launchctl").args(["bootout", &target]).status();
let boot = std::process::Command::new("launchctl").args(["bootstrap", &format!("gui/{uid}")]).arg(&plist).status();
if boot.map(|s| s.success()).unwrap_or(false) {
let _ = std::process::Command::new("launchctl").args(["enable", &target]).status();
let _ = std::process::Command::new("launchctl").args(["kickstart", "-k", &target]).status();
return Ok(format!("開機自動執行(launchd {})。權限請開給這個 App,不要開給另一份 anybot。", plist.display()));
}
let load = std::process::Command::new("launchctl").args(["load", "-w"]).arg(&plist).status();
if load.map(|s| s.success()).unwrap_or(false) {
return Ok(format!("開機自動執行(launchctl load {})", plist.display()));
}
Err("launchctl 沒能載入。請登入圖形介面後再執行 anybot setup。".into())
}
fn schtasks_tr(exe: &std::path::Path) -> String {
format!("\"{}\" --serve", exe.display())
}
fn install_schtasks(exe: &std::path::Path) -> Result<String, String> {
let tr = schtasks_tr(exe);
let o = std::process::Command::new("schtasks").args(["/Create", "/F", "/TN", "AnyBot", "/SC", "ONLOGON", "/RL", "LIMITED", "/IT", "/TR", &tr]).output().map_err(|e| format!("執行 schtasks 失敗:{e}"))?;
if !o.status.success() {
let err = String::from_utf8_lossy(&o.stderr);
let out = String::from_utf8_lossy(&o.stdout);
return Err(format!("工作排程器失敗:{}{}", err.trim(), out.trim()));
}
let _ = std::process::Command::new("schtasks").args(["/Run", "/TN", "AnyBot"]).status();
Ok("登入後自動執行(工作排程器 AnyBot)。操控的是這個已登入的桌面。".into())
}
/// `anybot setup --refresh-service` (install.sh runs it after an update): write the start script
/// again — a newer AnyBot may start differently — and restart. The computer stays joined as it was,
/// and a screen remembered at setup stays.
fn refresh_service() -> i32 {
let exe = match std::env::current_exe().and_then(|p| p.canonicalize()) {
Ok(e) => e,
Err(e) => {
eprintln!("✗ 找不到 AnyBot 程式:{e}");
return 1;
}
};
if cfg!(target_os = "macos") {
return match install_launchd(&exe) {
Ok(n) => {
println!("{n}");
0
}
Err(e) => {
eprintln!("✗ {e}");
1
}
};
}
if cfg!(target_os = "windows") {
return match install_schtasks(&exe) {
Ok(n) => {
println!("{n}");
0
}
Err(e) => {
eprintln!("✗ {e}");
1
}
};
}
let Some(home) = dirs::home_dir() else { return 1 };
let launcher = home.join(".local/bin/anybot-run");
let Ok(old) = std::fs::read_to_string(&launcher) else {
println!("這台沒有設成開機自動執行,不用更新服務。");
return 0;
};
let role = if old.contains("accessibility bus") { Role::Hands } else { Role::Brain };
let display = old.lines().find_map(|l| l.strip_prefix("export DISPLAY=\"${DISPLAY:-").and_then(|r| r.strip_suffix("}\""))).unwrap_or("").to_string();
let env = Env { linux: cfg!(target_os = "linux"), display, systemd: true };
if let Err(e) = write_atomic(&launcher, launcher_script(role, &exe, &env)) {
eprintln!("✗ 寫入 {} 失敗:{e}", launcher.display());
return 1;
}
// systemd starts it directly: a launcher written without the execute bit fails the unit
// with status=203/EXEC and the service spins in a restart loop.
make_executable(&launcher);
match systemctl(&["restart", UNIT]) {
Ok(_) => {
println!("已更新並重新啟動 AnyBot 服務。");
0
}
Err(e) => {
eprintln!("✗ 重新啟動失敗:{e}");
1
}
}
}
fn launcher_script(role: Role, exe: &std::path::Path, env: &Env) -> String {
let q = |s: &str| format!("'{}'", s.replace('\'', "'\\''"));
let mut s = String::from("#!/bin/sh\n# Started by systemd (anybot.service); written by `anybot setup`.\n");
s += "export LANG=\"${LANG:-C.UTF-8}\"\n";
if let Ok(d) = std::env::var("ANYBOT_DATA_DIR") {
s += &format!("export ANYBOT_DATA_DIR={}\n", q(&d));
}
let bin = q(&exe.display().to_string());
if role == Role::Hands {
s += "# The accessibility bus, so bots can read apps' buttons instead of only looking at pixels.\n";
s += "export NO_AT_BRIDGE=0 GTK_A11Y=atspi QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1\n";
let real_screen = std::env::args().any(|a| a == "--real-screen");
if env.has_display() && env.display != "wayland" && env.display != "desktop" {
s += &format!("# The screen this computer had when it was set up.\nexport DISPLAY=\"${{DISPLAY:-{}}}\"\n", env.display);
if let Ok(x) = std::env::var("XAUTHORITY") {
s += &format!("export XAUTHORITY=\"${{XAUTHORITY:-{x}}}\"\n");
}
} else if !real_screen {
// Set up without a screen (over SSH, or on Wayland): the bots get a virtual screen of
// their own, even when a desktop session is logged in here — nobody would be there to
// answer its 「允許分享螢幕」 dialog. `anybot setup --real-screen` uses the desktop.
s += "unset DISPLAY WAYLAND_DISPLAY XDG_SESSION_TYPE\n";
}
s += "if [ -z \"$DISPLAY\" ] && [ -z \"$WAYLAND_DISPLAY\" ] && command -v xvfb-run >/dev/null; then\n";
s += " # No screen: a virtual one, a window manager, and a session bus for the accessibility bus.\n";
s += &format!(" exec xvfb-run -a -s \"-screen 0 1440x900x24\" dbus-run-session -- sh -c 'command -v openbox >/dev/null && (openbox >/dev/null 2>&1 &); exec \"$0\" --serve' {bin}\n");
s += "fi\n";
}
s += &format!("exec {bin} --serve\n");
s
}
fn systemctl(args: &[&str]) -> Result<(), String> {
let o = std::process::Command::new("systemctl").arg("--user").args(args).output().map_err(|e| format!("執行 systemctl 失敗:{e}"))?;
if o.status.success() {
Ok(())
} else {
Err(format!("systemctl {} 失敗:{}", args.join(" "), String::from_utf8_lossy(&o.stderr).trim()))
}
}
fn lingering() -> bool {
let user = std::env::var("USER").unwrap_or_default();
std::process::Command::new("loginctl").args(["show-user", &user, "-p", "Linger"]).output().map(|o| String::from_utf8_lossy(&o.stdout).contains("Linger=yes")).unwrap_or(true)
}
fn provider_from_name(s: &str) -> Option<crate::providers::ProviderKind> {
use crate::providers::ProviderKind::*;
match s.trim().to_ascii_lowercase().as_str() {
"xai" | "grok" => Some(Xai),
"openai" | "open-ai" => Some(OpenAi),
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
"chatgpt" | "chatgpt-plan" | "chatgpt_plan" => Some(ChatGpt),
"anthropic" | "claude" => Some(Anthropic),
"gemini" | "google" => Some(Gemini),
"openrouter" => Some(OpenRouter),
"opencode" | "opencode-go" | "opencode_go" => Some(OpenCodeGo),
"ollama" => Some(Ollama),
"custom" => Some(Custom),
_ => None,
}
}
/// `anybot setup --seed`: the installer's first-run config. Writes the model key and, if there
/// is no bot yet, makes the first one. Does not ask.
fn seed_first() -> i32 {
use crate::model::{Bot, State};
let name = std::env::var("ANYBOT_PROVIDER").unwrap_or_default();
let Some(kind) = provider_from_name(&name) else {
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
eprintln!("✗ 請設 ANYBOT_PROVIDER(openai、chatgpt、anthropic、xai、gemini、openrouter、opencode、ollama、custom)");
return 2;
};
let key = std::env::var("ANYBOT_API_KEY").unwrap_or_default();
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// ChatGPT 方案 has no key: the account is signed in afterwards (設定 › 模型, or ask a bot).
if kind == crate::providers::ProviderKind::ChatGpt {
eprintln!("ChatGPT 方案不用金鑰:裝好後到 設定 › 模型 › ChatGPT 方案 按「使用 ChatGPT 繼續」(大腦在伺服器時,從螢幕電腦或手機登入)。");
} else if kind.needs_key() && key.is_empty() {
eprintln!("✗ 請設 ANYBOT_API_KEY");
return 2;
}
let _folder = match crate::lock::take(Duration::from_secs(10)) {
Ok(l) => l,
Err(e) => {
eprintln!("✗ {e}");
return 1;
}
};
let mut st = State::load();
{
let ps = st.provider_mut(kind);
if !key.is_empty() {
ps.api_key = key;
}
if let Ok(base) = std::env::var("ANYBOT_BASE_URL") {
if !base.trim().is_empty() {
ps.base_url = base;
}
}
let model = std::env::var("ANYBOT_MODEL").unwrap_or_default();
if !model.is_empty() {
ps.default_model = model;
}
}
let model = {
let chosen = std::env::var("ANYBOT_MODEL").unwrap_or_default();
if chosen.is_empty() { kind.suggested_model().to_string() } else { chosen }
};
if st.bots.is_empty() {
let bot_name = std::env::var("ANYBOT_BOT_NAME").unwrap_or_else(|_| "Bot".into());
st.bots.push(Bot {
id: 1,
name: bot_name,
description: String::new(),
instructions: String::new(),
shape: "squircle".into(),
color: "black".into(),
provider: kind,
model,
step_model: String::new(),
thinking: String::new(),
pinned: false,
folder: String::new(),
perf+fix: 舊電腦也輕、連上才進去、送出不重複、小模型說了就做、智慧模式常開、提早壓縮 畫面省資源(舊 Intel Mac) - 聊天紀錄改成共用、寫入時才複製(src/shared.rs):側欄和聊天每一格不再複製整份聊天(約 13 MB/格) - Markdown 解析、程式碼上色依內容快取,只有串流中的那則重算 - 用內建顯示晶片(wgpu LowPower),雙 GPU 的 Mac 不再喚醒獨顯;WGPU_POWER_PREF 照樣優先 - 所有轉圈圖示限每秒 20 次(egui 內建 Spinner 跑滿刷新率);淡入、彩帶、跳轉高亮也限速 - 頭像共用一個眨眼時鐘、捲出畫面的不畫;你不在(視窗不在前面或 90 秒沒動)不眨眼 - ioreg 移出畫面執行緒;Bot 工作中每 5 秒存一次(原 2 秒) - 螢幕電腦的大腦副本每 5 秒在背景寫一次(原本每次同步都在畫面執行緒寫整份) - 手機狀態裡的指令輸出先截短再遮罩金鑰 連線(螢幕電腦 ↔ 大腦) - 連上、拿到最新資料才進去:之前整個視窗停在「正在連到「…」…」,連不上 10 秒以上可改回這台自己的 Bot - 重開只補差異:副本旁記下版本與這台在大腦的名字;第一次拉取帶 config=1、不等新消息 - 漏收一次回應只補差異(大腦保留上一份 Seen),不再整份重抓 - 送出不重複:POST 只在根本沒送出去時才重試;訊息與動作帶編號、斷線自己重送約 100 秒,大腦同一個只做一次;改動依 (client, seq) 只做一次,seq 從時鐘起算 - 斷一下還能送(排隊),真的送不到文字放回輸入框;按過的允許卡片 30 秒內不再跳出 - 獨立審查修正:動作編號加上這次啟動的標記(沿用 client 時不再撞號被當重送);等待頁以「收到第一個回答」為準、設定讀不出來照樣進去並說原因、等滿 10 秒就有離開鈕;整份重抓失敗會再要;上一次拉取失敗時帶 retry,大腦從上一份算差異;去重表滿了淘汰最舊的 - 手機頁在背景時不重畫訊息,回到前景再畫 小模型持續做(src/agent/followthrough.rs) - 回答說了要做什麼卻沒呼叫工具、或問「要我現在就開始嗎?」:告訴模型、下一步安靜地跑;動手才顯示,標記「〔到此為止〕」或又只說一次都不顯示;連兩次、一輪 12 次為限;最後一句提到刪除、付款、寄出、關機這類收不回來的事一律不提醒 - OpenCode Go 模型清單改讀新格式 api/recommended_api(舊的 endpoint 照讀) 智慧模式常開 - 預設開、/smart off 與手機都關不掉(只有管理員鎖時關);設定頁只剩逾時滑桿 30–1800 秒;輸入列不再有它的圖示 token 壓縮提早 - 門檻 70→60%(進行中 65%);估算改成英數 3.5 字元一 token;一個要求做很多步時主動把這一輪較早的步驟寫成摘要(至少 10 則),不等模型說太長 feature-map:chat.md 新增 chat-followthrough(含步驟)、chat-compact 6 成、chat-steps;autonomy.md 智慧模式一直開著(步驟改寫);account.md 連上才進去、重送與去重;settings/safety/phone 同步。FEATURES.md 同步。 已驗證: cargo test 739 通過、clippy 無新警告(含 featuremap:: 11 項、layout_audit::、新增 followthrough/shared/mirror 去重與漏收補差異測試);verify-anybot:chat.md「/ 指令」(/context 寫「到 60% 會自動」)、「說了就做」(只說「我把它整理成一頁做法文件。」後同一輪接著執行 echo ft-done 並收尾,模型那層收到提醒)、autonomy.md「智慧模式一直開著」(/smart off 回不能關,重開後 smart_mode 仍 true);審查修正後三步重跑結果相同;ctl down 無殘留;乾淨脈絡獨立審查 1 次(P0×1、P1×1 已修) 未驗證: 手機頁面畫面那一層(這台沒有 Google Chrome,無頭手機頁面開不起來,改走同一個大腦的手機 API);螢幕電腦連大腦的實際路徑(要帳號伺服器與第二台電腦:等待頁、重開續傳、斷線重送只在單元測試);真 Intel Mac 的 CPU/風扇與 LowPower GPU 實測;真的小模型(muse-spark 等)是否照提醒動手;動到審批路徑(智慧模式常開)需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:31 +00:00
messages: Default::default(),
unread: false,
tools_enabled: true,
workdir: crate::model::default_workdir(),
allow_rules: vec![],
members: vec![],
perf+fix: 舊電腦也輕、連上才進去、送出不重複、小模型說了就做、智慧模式常開、提早壓縮 畫面省資源(舊 Intel Mac) - 聊天紀錄改成共用、寫入時才複製(src/shared.rs):側欄和聊天每一格不再複製整份聊天(約 13 MB/格) - Markdown 解析、程式碼上色依內容快取,只有串流中的那則重算 - 用內建顯示晶片(wgpu LowPower),雙 GPU 的 Mac 不再喚醒獨顯;WGPU_POWER_PREF 照樣優先 - 所有轉圈圖示限每秒 20 次(egui 內建 Spinner 跑滿刷新率);淡入、彩帶、跳轉高亮也限速 - 頭像共用一個眨眼時鐘、捲出畫面的不畫;你不在(視窗不在前面或 90 秒沒動)不眨眼 - ioreg 移出畫面執行緒;Bot 工作中每 5 秒存一次(原 2 秒) - 螢幕電腦的大腦副本每 5 秒在背景寫一次(原本每次同步都在畫面執行緒寫整份) - 手機狀態裡的指令輸出先截短再遮罩金鑰 連線(螢幕電腦 ↔ 大腦) - 連上、拿到最新資料才進去:之前整個視窗停在「正在連到「…」…」,連不上 10 秒以上可改回這台自己的 Bot - 重開只補差異:副本旁記下版本與這台在大腦的名字;第一次拉取帶 config=1、不等新消息 - 漏收一次回應只補差異(大腦保留上一份 Seen),不再整份重抓 - 送出不重複:POST 只在根本沒送出去時才重試;訊息與動作帶編號、斷線自己重送約 100 秒,大腦同一個只做一次;改動依 (client, seq) 只做一次,seq 從時鐘起算 - 斷一下還能送(排隊),真的送不到文字放回輸入框;按過的允許卡片 30 秒內不再跳出 - 獨立審查修正:動作編號加上這次啟動的標記(沿用 client 時不再撞號被當重送);等待頁以「收到第一個回答」為準、設定讀不出來照樣進去並說原因、等滿 10 秒就有離開鈕;整份重抓失敗會再要;上一次拉取失敗時帶 retry,大腦從上一份算差異;去重表滿了淘汰最舊的 - 手機頁在背景時不重畫訊息,回到前景再畫 小模型持續做(src/agent/followthrough.rs) - 回答說了要做什麼卻沒呼叫工具、或問「要我現在就開始嗎?」:告訴模型、下一步安靜地跑;動手才顯示,標記「〔到此為止〕」或又只說一次都不顯示;連兩次、一輪 12 次為限;最後一句提到刪除、付款、寄出、關機這類收不回來的事一律不提醒 - OpenCode Go 模型清單改讀新格式 api/recommended_api(舊的 endpoint 照讀) 智慧模式常開 - 預設開、/smart off 與手機都關不掉(只有管理員鎖時關);設定頁只剩逾時滑桿 30–1800 秒;輸入列不再有它的圖示 token 壓縮提早 - 門檻 70→60%(進行中 65%);估算改成英數 3.5 字元一 token;一個要求做很多步時主動把這一輪較早的步驟寫成摘要(至少 10 則),不等模型說太長 feature-map:chat.md 新增 chat-followthrough(含步驟)、chat-compact 6 成、chat-steps;autonomy.md 智慧模式一直開著(步驟改寫);account.md 連上才進去、重送與去重;settings/safety/phone 同步。FEATURES.md 同步。 已驗證: cargo test 739 通過、clippy 無新警告(含 featuremap:: 11 項、layout_audit::、新增 followthrough/shared/mirror 去重與漏收補差異測試);verify-anybot:chat.md「/ 指令」(/context 寫「到 60% 會自動」)、「說了就做」(只說「我把它整理成一頁做法文件。」後同一輪接著執行 echo ft-done 並收尾,模型那層收到提醒)、autonomy.md「智慧模式一直開著」(/smart off 回不能關,重開後 smart_mode 仍 true);審查修正後三步重跑結果相同;ctl down 無殘留;乾淨脈絡獨立審查 1 次(P0×1、P1×1 已修) 未驗證: 手機頁面畫面那一層(這台沒有 Google Chrome,無頭手機頁面開不起來,改走同一個大腦的手機 API);螢幕電腦連大腦的實際路徑(要帳號伺服器與第二台電腦:等待頁、重開續傳、斷線重送只在單元測試);真 Intel Mac 的 CPU/風扇與 LowPower GPU 實測;真的小模型(muse-spark 等)是否照提醒動手;動到審批路徑(智慧模式常開)需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:31 +00:00
threads: Default::default(),
memories: vec![],
speak_replies: false,
voice: String::new(),
voice_rate: 1.0,
voice_lang: String::new(),
demos: vec![],
context_tokens: crate::agent::DEFAULT_CONTEXT_TOKENS,
feat: 追進度、送 token 減量、首字等待依請求大小、摘要分段必成、換模型不掉東西 追進度(follow_up,src/followup.rs、src/app/followup_ui.rs) - Bot 啟動要等的事後登記檢查指令與 done_when(可選 fail_when、then),就結束這一輪;大腦定期在那台電腦上跑檢查(不叫模型) - 有進展時聊天記一行(最多每 10 分鐘);好了、失敗、15 分鐘沒變、超時、檢查連續失敗就叫醒 Bot 接著做 - 登記時檢查指令照 shell 規則審批一次(被擋的不登記);存在 Bot 身上,重開照樣追;只有大腦跑 - 系統指示:要等的事不要 sleep、不要說「我去盯」就結束;主動回報。說了就做的提醒也指向 follow_up 送 token 減量 - 收起的步驟,它的長參數(例如三千字 SSH 腳本)送給模型時也只留開頭(fold_called_args);估算同步 - 滾動收起:舊結果累積到可讀長度 15% 就整批收起,一批一次,快取只斷一次 模型怪怪的 - 第一個字的等待依請求大小(120 秒起,每多 1,000 token 多 2 秒,最多 10 分鐘),看門狗同步 - 等不到任何回應時不再原樣重送:先收小對話(收起結果、寫摘要)再問一次 壓縮 - 摘要分段寫(每段 40,000 字內,結果只帶 600 字),模型寫不出來時 AnyBot 本地整理一份,收縮一定成功 換模型 - 換過去的第一輪先收起舊結果;別的模型的思考區塊不送(會被拒);可讀長度改成每個模型各記(model_limits) feature-map:goal.md 新增 goal-followup(含步驟);chat.md 改寫 chat-compact、chat-stall;models.md 新增 models-switch。FEATURES.md 同步。 已驗證: cargo test 753 通過(新增 followup 5 項、a_follow_up_reports_and_wakes_its_bot_when_done、calls_of_set_aside_steps_go_shortened、old_results_are_set_aside_before_the_chat_is_full、a_long_stretch_is_summarized_in_pieces、a_summary_the_model_cant_write_is_written_here、a_switched_model_starts_from_a_lean_request、首字等待兩項),clippy 無新警告;verify-anybot:goal.md「追進度」(登記後同一輪結束,背景檢查看到 DL_DONE 把 Bot 叫回來,follow_ups 歸零)、chat.md「說了就做」「/ 指令」,ctl down 無殘留 未驗證: 手機頁面畫面(這台沒有 Google Chrome);真的自架模型的首字等待與收小重試(要真的慢模型);跨機器(SSH、帳號裡別台電腦)的檢查實跑;models.md「從手機換回來」步驟(要無頭 Chrome);新增 App 工具 follow_up 與其審批需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:28:52 +00:00
model_limits: Default::default(),
follow_ups: vec![],
routines: vec![],
last_turn: None,
goal: None,
feat: /plan 先規劃再動手、聊天裡請 Bot 管理連接器、/always-approve 一律放行;輸入框上方的狀態不再破版 /plan(照 Claude Code 的 plan mode、Cursor 的 Plan Mode、Codex 的 update_plan) - 「/plan 要做的事」:這一輪只給會看的工具(讀檔、搜尋、web_fetch、瀏覽器的打開/讀取/捲動、截圖、anybot_guide、問題卡),在執行那一層擋下其他步驟(回「計畫還沒核准」),不是只靠提示詞。 - Bot 用 submit_plan 交計畫:聊天裡一張「計畫」卡(摘要、步驟、怎麼確認做對了、注意),下面的問題卡「照這個計畫做嗎?」:開始照計畫做/先不要/打字寫要改哪裡。 - 核准後同一輪接著做:工具全開、系統指示換成照計畫做,第 1 步自動進行中;update_plan 每做完一步更新一次(整份清單、只有一步進行中),卡上打勾、輸入框上方「照計畫做 · 2/6 · 這一步」;全部做完留「計畫完成」那一行。 - 「/plan」看狀態、「/plan clear」取消;例行任務、訊息管道、團隊成員的訊息不受影響;群組不能用;支線不帶計畫;清除聊天或新對話一起清;分享 Bot 檔不含。手機:計畫卡、計畫列、取消計畫。 - 新功能地圖 plan.md;研究(Claude Code、Codex、Cursor、Gemini CLI…)的結論寫進提示:只寫建議的做法、通常 3 到 7 步、問題最多 3 題、打勾不要太勤。 聊天裡管理連接器(設定能做的聊天也要能做) - 新工具 manage_connectors(管理 App 能力):list、add、update(含開關)、reconnect、remove。改的就是大腦上 設定 › 整合 › 連接器 那一份,不會寫到手腳電腦的檔案(進化之神之前叫使用者去 nobledesktop 的 ~/.local/share/AnyBot 設)。 - 新增、修改、移除先跳卡片:指令(在大腦上執行)或網址、環境變數、標頭;TOKEN、KEY、SECRET、PASS、AUTH… 和密碼顯示「••••(已填)」。名稱重複、command 和 url 都給、網址不對、還有「{…}」、沒東西可改,在問之前就回給 Bot。 - 加好後等它連上(最多 90 秒)再回報幾個工具或原因;一輪裡連接器的工具變了,下一步起就換新(加完同一輪就能用)。 /always-approve(也可以 /yolo) - 使用者自己打(電腦、大腦的螢幕、手機的擁有者)或 設定 › 權限 ›「一律放行」:打開直接操作,之後所有要等「允許」的都自動允許(含一律詢問規則、付款/傳送/刪除的點擊、寄信、傳訊息、打電話、發文、保險庫卡片),自動審核略過;打開時在等的卡片一起放行。 - 照樣擋:安全規則一律拒絕的;別人傳來的訊息那一輪;問題卡、需要處理、計畫卡。Bot、例行任務、訊息管道打不開;管理員和成員打的變成「【名字】/always-approve」。管理員鎖了直接操作就打不開。 - 開著時每個聊天輸入框上方一條「一律放行」和「關閉」;「/always-approve off」關掉,直接操作是它打開的就一起關。 輸入框上方的狀態 - 好幾行的狀態(模型忙碌重試:錯誤、說明、幾秒後重試)以前疊出那一列、壓到輸入框;現在一行:「模型供應商目前負載過高,15 秒後重試(第 3 次,共 3 次)…」。 已驗證:cargo test 548 通過、1 個失敗(layout_audit 的 設定 › 電腦 被這台 Mac 的 Docker 位址 unix:///Users/daniel/.lima/anybot-gvisor 撐寬;把這次的改動 stash 掉一樣失敗,跟這次無關)。新測試:plan:: 7 個;agent 的計畫模式三個(只看到卡片說開始、先不要什麼都不做、修改後重交);app 的 /plan 從打字到計畫完成、Bot 從聊天加連接器(卡片不露 Token、同一輪就用它的工具算出 sum=5)、/always-approve(之前會問、之後不問直接在這台跑、陌生人的訊息照樣問、off 回原樣);mcp::manage_tests 4 個;狀態一行。截圖看過:計畫卡等你決定/照著做打勾、503 重試那一行。手機頁面 JS 語法檢查和計畫卡四種狀態的 HTML。 未驗證:真的模型走一次 /plan 和加 GitLab 連接器;手機實機;伺服器上的大腦(要 make update-server)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:55:37 +00:00
plan: None,
修正卡死: ⌘ 一按視窗就鎖死、圖表縮小凍結、打字每鍵寫檔;複製中文亂碼;頭像不再擋住思考動畫 卡住當機 - ⌘1–⌘9(Win/Linux 為 Ctrl)在 ctx.input 裡又呼叫 ctx.input,egui 的 Context 被鎖兩次, 按住 ⌘(⌘C、⌘V、⌘Tab)視窗就永遠不動;改為只讀一次(bot_jump_key),加回歸測試 - 圖表 x 軸格線固定每 1 一條,縮小後一幀要畫上百萬條(凍結、記憶體爆);改為最多約 40 條, 滾輪不再被圖表吃掉(⌘/Ctrl+滾輪或雙指縮放) - 草稿每打一個字就同步重寫整個 state.json(含 fsync);改為停手 1.5 秒後才存,結尾空白也 不再造成每幀存檔 複製(三個系統) - Mac:pbcopy 從 Finder/Dock 開時沒有 UTF-8 語系,中文變亂碼;指定 UTF-8 - ⌘C 攔截只拿 CopyText,不再丟掉開連結、複製圖片、Linux 中鍵選取等指令(且只在 Mac 攔) - Windows:改用 Win32 剪貼簿(arboard,獨立執行緒),不再走 clip.exe(缺 BOM、多一個 NUL) - Linux:依 WAYLAND_DISPLAY/DISPLAY 選 wl-copy 或 xclip/xsel,都沒有時退回視窗剪貼簿 其他 - 頁面目錄點了不跳(標題位置從未記錄);目錄搜尋框按 Esc 會關掉整頁 - 圖表:單一系列欄名被 String::max 換成「數值」;同尺寸無標題的圖共用縮放;inf/NaN 不入圖 - KPI 卡片寬度未扣內距而超出欄寬 - 「還原上一個答案」在送出新訊息後會插錯位置;重試錯誤回覆不再存可還原的版本 - 手機:長輪詢回來時已切到別的聊天,不再把上一個聊天的訊息畫進來 - 輸入框上方頭像:思考時頭稍微縮小,三顆小球繞著頭轉(後面的從頭後經過、前面的壓在頭上並描邊), 不再被頭像蓋住 - 刪除未使用的 src/app/ui_kit.rs 驗證:macOS cargo test 374 通過(relay 18 通過);Windows/Linux cargo check 通過 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 06:19:59 +00:00
draft: String::new(),
Bot 之間溝通:ask_bot 問同事並等回答、群組 @點名、共用頁面/「關於你」記憶/教技能;修正插話丟附件、Enter 核准失效等 問同事(ask_bot) - A 問 B 並等它回答:問題放進 B 自己的聊天,B 用自己的模型、工具、記憶和電腦做,最後的回覆交回 A - 最多轉 3 手、不能互等(避免卡死)、對方忙就排隊(10 分鐘逾時)、停止 A 時 B 也停 - message_bot 也加轉手上限;別的 Bot 叫的不算使用者的話(改不了自己的設定) 群組 @點名 - 「@名字」只叫被點到的成員回答;成員在回覆裡 @ 別人就接著說(一輪最多 8 則) - 電腦和手機的輸入框打 @ 會列出成員 - 修正:每個成員帶自己的記憶;成員回覆的每一步都記得是誰說的 共用資源 - Bot 可以讀其他 Bot 的頁面(只能讀,改要請作者改) - 共用的「關於你」記憶:每個 Bot 都帶著,記憶頁可切換查看、編輯;外人的訊息不帶 - teach_skill:把自己會的技能教給同事(先問你);同事名冊列出每個 Bot 會的技能 修正 - 插話(Bot 工作中傳訊息)會帶附件:聊天有檔案卡片,模型看得到圖片;當機復原也帶著 - 輸入框有焦點、框是空的時 Enter 允許待核准的步驟(原本被當成空白送出吃掉) - 大腦的螢幕連不到大腦時,引用、附件、記憶不會先被用掉 - 「還原上一個答案」存在 Bot 上:重開還在,連大腦的畫面和手機都能還原;停止的回合也留著 - Bot 忙時被叫醒(例行任務、message_bot、觸發器)改成排隊開自己的一輪,不再壓成純文字插話 - 停止時結果已回來的步驟標成完成;輸入法剛選字的那一格不送出 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 13:34:03 +00:00
regen_undo: vec![],
/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
team: false,
branches: vec![],
branch_of: 0,
Bot 個人檔案:soul、擅長、技能、能力、可用電腦、同事名冊;例行任務每輪開新對話(省 token) 每個 Bot 是獨立的個體(src/profile.rs、src/app/profile_ui.rs) - 新欄位:soul(只有自己讀,放在提示最前面)、擅長、不找它做的事、會的技能、能力、可以用的電腦 - 同事名冊:每個 Bot 的提示裡一行一個其他 Bot(簡介、擅長、不找它、在哪幾台電腦),不含別人的 soul 和記憶;順序固定,吃得到快取 - 能力 11 類(上網、瀏覽器、螢幕、檔案與指令、Mac App、連接器、電話簡訊 X、例行任務、頁面、 合作、管理 App):沒勾的工具不提供、規則不寫進提示;硬叫會被 agent 擋下並說該找誰 - 技能:說明只列自己會的,use_skill 只讀得到自己的;自己學會的自動算它的 - 可以用的電腦:自己的電腦一定可以;預設電腦不在名單時回到自己的電腦,不誤報「沒有連線」; 其他畫面也拿得到完整電腦清單來勾;匯出 Bot 不帶電腦名單和草稿 - 舊 Bot 全部勾選(None = 全部),行為不變 - 例行任務:每輪只從那則訊息讀起(Message::fresh),提醒先讀頁面/查記憶;聊天畫面不變, 使用者自己的下一則照樣看整段 - 順手修:角色說明結尾的「。」不再變成「。。」 - 實測(照建議勾能力):明日之星固定內容 ~21.7k → ~11.5k token、FSD ~25.5k → ~13.2k; 例行任務每輪歷史最多 ~70k → 幾百 連接器(MCP) - 實測三個連接器都能用(本機用 AnyBot 自己的 MCP client):time(get_current_time)、 fetch(讀 example.com)、SccMCP(82 個工具,唯讀的 system_status 查詢成功;超過 20 個走 find / use,搜尋得到) - 測試:有「連接器」能力的 Bot 拿得到(大的走 find/use、提示有說明),沒有的拿不到,硬叫三種 方式都被擋 - 測試用的假模型伺服器改成讀完整個請求再回,平行跑測試時不再偶發斷線 驗證:macOS cargo test 389 通過(連跑三次);Windows/Linux cargo check 通過 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:14:51 +00:00
soul: String::new(),
strengths: String::new(),
not_for: String::new(),
skills: None,
abilities: None,
computers: None,
default_computer: crate::model::default_computer(),
});
st.primary_bot = 1;
st.selected = 1;
st.next_id = 2;
println!("已建立第一個 Bot,模型是 {}。", kind.label());
} else {
println!("已寫入 {} 的金鑰。既有的 Bot 沒有改。", kind.label());
}
if st.save() { 0 } else {
eprintln!("✗ 寫不進設定檔");
1
}
}
// ---------- entry ----------
/// Flags that take a value (so the value isn't read as the address or the code).
const VALUED: [&str; 4] = ["--server", "--user", "--name", "--brain-name"];
pub fn run(args: &[String]) -> i32 {
let flag = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).cloned();
if args.iter().any(|a| a == "-h" || a == "--help") {
println!("anybot setup:把這台電腦接到你的 AnyBot。\n\n anybot setup 網址 配對碼 (手機或電腦的 AnyBot 按「加一台電腦」會給你這一行)\n anybot setup 一個畫面:填網址和配對碼(或帳號密碼)\n 加 --brain 這台當大腦,不當手腳\n 加 --no-service 不設開機自動執行\n 加 --real-screen 讓 Bot 用這台登入中的桌面(預設用自己的虛擬螢幕)\n anybot setup --seed 寫入第一次的模型(ANYBOT_PROVIDER、ANYBOT_API_KEY)\n\n給程式用:anybot setup --server 網址 --user 帳號 [--brain-name 大腦名字],密碼放在 ANYBOT_ACCOUNT_PASSWORD。");
return 0;
}
if args.iter().any(|a| a == "--refresh-service") {
return refresh_service();
}
if args.iter().any(|a| a == "--seed") {
return seed_first();
}
let role = if args.iter().any(|a| a == "--brain") { Role::Brain } else { Role::Hands };
let mut pos = vec![];
let mut skip = false;
for a in args {
if skip {
skip = false;
} else if VALUED.contains(&a.as_str()) {
skip = true;
} else if !a.starts_with("--") {
pos.push(a.clone());
}
}
let service = !args.iter().any(|a| a == "--no-service");
let name = flag("--name");
if flag("--server").is_some() || flag("--user").is_some() {
return run_script(role, &flag("--server").unwrap_or_default(), &flag("--user").unwrap_or_default(), flag("--brain-name"), name, service);
}
if pos.len() >= 2 {
return run_code(role, &pos[0], &pos[1], name, service);
}
let name_for_screen = name.clone();
if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
eprintln!("✗ 請用:anybot setup 網址 配對碼(在手機或電腦的 AnyBot 按「加一台電腦」)");
return 1;
}
run_screen(role, service, name_for_screen)
}
/// The one-screen form, then the progress.
fn run_screen(role: Role, service: bool, name: Option<String>) -> i32 {
let mut w = Wiz::new(role);
w.name = name;
安全、修正: 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
w.service = service && (w.env.systemd || cfg!(target_os = "macos") || cfg!(target_os = "windows"));
let mut out = std::io::stdout();
if terminal::enable_raw_mode().is_err() {
eprintln!("✗ 這個終端機不能用互動畫面。請用:anybot setup 網址 配對碼");
return 1;
}
let _ = execute!(out, terminal::EnterAlternateScreen, cursor::Hide, event::EnableBracketedPaste);
let rx = w.rx.take().expect("channel");
let mut dirty = true;
while !w.quit {
if dirty {
if w.render(&mut out).is_err() {
break;
}
dirty = false;
}
if event::poll(Duration::from_millis(90)).unwrap_or(false) {
match event::read() {
Ok(Event::Key(k)) if k.kind != KeyEventKind::Release => w.key(k.code, k.modifiers),
Ok(Event::Paste(s)) => w.type_text(&s),
_ => {}
}
dirty = true;
}
while let Ok(m) = rx.try_recv() {
w.on_msg(m);
dirty = true;
}
if w.busy.is_some() || w.step == Step::Install {
w.spin += 1;
dirty = true;
}
}
let _ = execute!(out, event::DisableBracketedPaste, cursor::Show, terminal::LeaveAlternateScreen);
let _ = terminal::disable_raw_mode();
if w.step != Step::Done {
println!("沒有改任何設定。");
return 1;
}
// What happened stays in the terminal.
let mut lines = vec![vec![], vec![plain(" "), colored("◆ ", ACC), strong("AnyBot")], vec![]];
lines.extend(progress_lines(&w.progress, &w.tips, 0, 72).into_iter().map(|l| [vec![plain(" ")], l].concat()));
for l in lines {
let _ = print_line(&mut out, l, 200);
println!();
}
if w.ok {
0
} else {
1
}
}
/// Print a line now (colors only in a terminal).
fn say(l: Line) {
let mut out = std::io::stdout();
if out.is_terminal() {
let _ = print_line(&mut out, l, 400);
} else {
print!("{}", l.into_iter().map(|(s, _)| s).collect::<String>());
}
println!();
}
/// Shows a spinner on this line while `job` runs (in a terminal).
fn waiting<T: Send + 'static>(what: &str, job: impl FnOnce() -> T + Send + 'static) -> T {
let (tx, rx) = channel();
std::thread::spawn(move || {
let _ = tx.send(job());
});
let tty = std::io::stdout().is_terminal();
let mut n = 0;
loop {
if let Ok(v) = rx.recv_timeout(Duration::from_millis(100)) {
if tty {
print!("\r\x1b[K");
let _ = std::io::stdout().flush();
}
return v;
}
if tty {
let mut out = std::io::stdout();
print!("\r\x1b[K ");
let _ = print_line(&mut out, vec![colored(SPIN[n % SPIN.len()], ACC), plain(" "), colored(what.to_string(), ACC)], 200);
let _ = out.flush();
}
n += 1;
}
}
fn header() {
say(vec![]);
say(vec![plain(" "), colored("◆ ", ACC), strong("AnyBot")]);
say(vec![]);
}
fn base_settings(name: Option<String>) -> Settings {
let mut base = State::load().remote;
if let Some(n) = name.filter(|n| !n.trim().is_empty()) {
base.host_name = n.trim().chars().take(60).collect();
}
if base.host_name.is_empty() {
base.host_name = remote::default_host_name();
}
base
}
/// `anybot setup 網址 配對碼`: nothing to answer.
fn run_code(role: Role, url: &str, code: &str, name: Option<String>, service: bool) -> i32 {
header();
let base = base_settings(name);
let (url, code) = (url.to_string(), code.to_string());
let r = waiting("正在連線…", move || remote::pair_claim(&base, &url, &code));
let s = match r {
Ok(s) => s,
Err(e) => {
say(vec![plain(" "), colored("✗ ", BAD), colored(e, BAD)]);
say(vec![plain(" "), dim("在手機或電腦的 AnyBot 按「加一台電腦」拿新的一行再試。")]);
return 1;
}
};
say(vec![plain(" "), colored("✓ ", GOOD), plain(format!("加入帳號 {}(這台叫「{}」)", s.relay_user, s.host_name))]);
let brain = brain_of(&s);
finish(role, s, brain, service)
}
/// Scripts: the account and password.
fn run_script(role: Role, server: &str, user: &str, brain_name: Option<String>, name: Option<String>, service: bool) -> i32 {
header();
let pass = std::env::var("ANYBOT_ACCOUNT_PASSWORD").unwrap_or_default();
if server.is_empty() || user.is_empty() || pass.is_empty() {
say(vec![plain(" "), colored("✗ 請給 --server 和 --user,密碼放在 ANYBOT_ACCOUNT_PASSWORD", BAD)]);
return 1;
}
let base = base_settings(name);
let (server, user2) = (server.to_string(), user.to_string());
let (s, mut brain, list) = match waiting("正在登入…", move || join_with_password(&base, &server, &user2, &pass)) {
Ok(v) => v,
Err(e) => {
say(vec![plain(" "), colored("✗ ", BAD), colored(e, BAD)]);
return 1;
}
};
say(vec![plain(" "), colored("✓ ", GOOD), plain(format!("登入帳號 {user}(這台叫「{}」)", s.host_name))]);
if let Some(want) = brain_name {
match list.into_iter().find(|p| p.name == want) {
Some(p) => brain = Some(p),
None => {
say(vec![plain(" "), colored(format!("✗ 帳號裡沒有叫「{want}」的 AnyBot"), BAD)]);
return 1;
}
}
}
finish(role, s, brain, service)
}
/// Save, start with the computer, check; printed line by line.
fn finish(role: Role, s: Settings, brain: Option<Peer>, service: bool) -> i32 {
let env = Env::detect();
let plan = Plan { role, settings: s, brain, service, env };
let steps = plan.steps();
let (tx, rx) = channel();
std::thread::spawn(move || plan.run(&tx));
let mut failed = false;
let mut current = String::new();
loop {
let m = if std::io::stdout().is_terminal() && !current.is_empty() {
let what = current.clone();
let rx2 = &rx;
// Spin until the next message.
let mut n = 0;
loop {
match rx2.recv_timeout(Duration::from_millis(100)) {
Ok(m) => {
print!("\r\x1b[K");
break Some(m);
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
let mut out = std::io::stdout();
print!("\r\x1b[K ");
let _ = print_line(&mut out, vec![colored(SPIN[n % SPIN.len()], ACC), plain(" "), plain(what.clone())], 200);
let _ = out.flush();
n += 1;
}
Err(_) => break None,
}
}
} else {
rx.recv().ok()
};
let Some(m) = m else { break };
match m {
Msg::Progress(i, Mark::Run, _) => current = steps.get(i).cloned().unwrap_or_default(),
Msg::Progress(i, mark, note) if mark != Mark::Wait => {
current.clear();
failed |= mark == Mark::Fail;
let (icon, c) = match mark {
Mark::Ok => ("✓ ", GOOD),
Mark::Warn => ("! ", WARN),
_ => ("✗ ", BAD),
};
say(vec![plain(" "), colored(icon, c), plain(steps.get(i).cloned().unwrap_or_default())]);
if !note.is_empty() {
say(vec![plain(" "), if mark == Mark::Ok { dim(note) } else { colored(note, c) }]);
}
}
Msg::Finished(tips) => {
say(vec![]);
for t in tips {
match t.split_once('\t') {
Some((k, v)) => say(vec![plain(" "), dim(format!("{k}{}", " ".repeat(10usize.saturating_sub(k.width())))), colored(v.to_string(), ACC)]),
None => say(vec![plain(" "), plain(t)]),
}
}
say(vec![]);
break;
}
_ => {}
}
}
if failed {
1
} else {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wraps_chinese_by_width() {
let lines = wrap("讓大腦的 Bot 使用這台電腦", 10);
assert!(lines.iter().all(|l| l.width() <= 10), "{lines:?}");
assert_eq!(lines.concat(), "讓大腦的 Bot 使用這台電腦");
let l = wrap("一二三四五。", 5);
assert!(!l[1].starts_with('。'), "{l:?}");
let l = wrap("一二三四(五)。", 5);
assert!(l.iter().all(|x| !x.starts_with(')') && !x.starts_with('。')), "{l:?}");
}
#[test]
fn launcher_makes_a_screen_when_there_is_none() {
let env = Env { linux: true, display: String::new(), systemd: true };
let s = launcher_script(Role::Hands, std::path::Path::new("/home/a b/anybot"), &env);
assert!(s.contains("xvfb-run") && s.contains("'/home/a b/anybot'") && s.ends_with("exec '/home/a b/anybot' --serve\n"));
let brain = launcher_script(Role::Brain, std::path::Path::new("/x/anybot"), &env);
assert!(!brain.contains("xvfb-run"));
}
#[test]
fn every_screen_fits_a_narrow_terminal() {
let mut w = Wiz::new(Role::Hands);
w.peers = vec![Peer { id: "1".into(), name: "很長很長很長很長很長很長很長很長的大腦名字".into(), online: true, last: String::new() }];
w.error = "配對碼不對,或已經過期(10 分鐘內有效,只能用一次)".into();
for step in [Step::Form, Step::Brain, Step::Install, Step::Done] {
w.step = step;
for pw in [false, true] {
w.password = pw;
for l in w.body(40) {
assert!(width(&clip(l, 40)) <= 40);
}
}
}
}
#[test]
fn a_pasted_line_fills_the_form() {
let mut w = Wiz::new(Role::Hands);
w.focus = 0;
w.url.clear();
w.type_text("anybot setup https://anybot.example.com 482913");
assert_eq!((w.url.as_str(), w.code.as_str()), ("https://anybot.example.com", "482913"));
let mut w = Wiz::new(Role::Hands);
w.focus = 0;
w.url.clear();
w.type_text(&crate::remote::pair_line("https://anybot.example.com/", "135790"));
assert_eq!((w.url.as_str(), w.code.as_str()), ("https://anybot.example.com", "135790"));
let mut w = Wiz::new(Role::Hands);
w.focus = 0;
w.url.clear();
w.type_text(&crate::remote::pair_block("https://anybot.example.com/", "135790"));
assert_eq!((w.url.as_str(), w.code.as_str()), ("https://anybot.example.com", "135790"));
}
#[test]
fn provider_names_and_autostart_quoting() {
assert!(provider_from_name("OpenAI").is_some());
assert!(provider_from_name("nope").is_none());
let plist = launchd_plist(std::path::Path::new("/Applications/AnyBot.app/Contents/MacOS/AnyBot"));
assert!(plist.contains("<string>--serve</string>") && plist.contains("AnyBot"));
let tr = schtasks_tr(std::path::Path::new(r"C:\Users\a b\anybot.exe"));
assert!(tr.contains("anybot.exe") && tr.contains("--serve") && tr.contains('"'), "{tr}");
}
}