feat: 紀錄檔、當掉報告、秘密遮罩
參考 xai-org/grok-build(每個 session 的 debug log、xai-crash-handler、xai-grok-secrets 的 sanitizer)。工程基礎計畫的 E2–E4。 - 紀錄檔(logfile.rs):AnyBot 自己說的話寫到資料夾的 logs/anybot-YYYY-MM-DD.log(時間、等級、來源;一天一個、留 7 天、一天上限 20 MB),終端機照舊印,伺服器的 docker logs 不變。ANYBOT_LOG 設等級(預設 info),其他套件只收 warn 以上。36 個執行中的 eprintln! 改成 log::info!/warn!/error!;終端機給人看的(用法、setup 的 ✗、更新進度、截圖、測試)照舊。cargo test 不開紀錄檔。 - 當掉報告:panic hook 寫 logs/crash-時間.txt(版本、執行緒、位置、訊息、backtrace);下次打開在主要 Bot 的聊天留一行並記進待改進,每份只說一次(改名 .seen.txt);螢幕電腦跳提示。 - 秘密遮罩(secrets.rs):glpat-、ghp_/github_pat_、sk-、xai-、AKIA/ASIA、xox、AIza、私鑰區塊、Bearer/Basic、JWT,名字像 TOKEN/SECRET/PASSWORD/API_KEY 的變數值 → ••••(留前綴)。用在紀錄檔、當掉報告、手機上的步驟細節和結果。工作紀錄(oplog)不遮:當掉後要照原本的參數重做;Bot 看到的不遮。 - regex、log 改成直接相依(本來就在建置裡,沒有新的下載)。 已驗證:cargo test 557 全過;新測試 secrets:: 3 個(每種格式、變數名留著、一般文字不動)、logfile:: 4 個(等級和來源、一行的格式和遮罩、每天換檔/上限只說一次/七天前的刪掉、當掉報告遮過且只說一次)。隔離的 --serve(沒有金鑰、DOCKER_HOST 指向不存在、自己的 HOME 和資料夾)跑 10 秒:logs/anybot-2026-11-17.log 有啟動版本、手機密碼提醒、記憶整理、收到停止訊號四行,終端機一樣。 未驗證:真的 panic 寫出報告後重開看到那一行(測試直接呼叫寫報告和讀報告的函式,沒有讓程式真的當掉)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8133789bf5
commit
e039368d6b
|
|
@ -365,6 +365,7 @@ dependencies = [
|
|||
"image",
|
||||
"jieba-rs",
|
||||
"libc",
|
||||
"log",
|
||||
"memmap2",
|
||||
"mermaid-rs-renderer",
|
||||
"objc2 0.6.5",
|
||||
|
|
@ -373,6 +374,7 @@ dependencies = [
|
|||
"portable-pty",
|
||||
"pulldown-cmark",
|
||||
"rcgen",
|
||||
"regex",
|
||||
"resvg",
|
||||
"ring",
|
||||
"rodio",
|
||||
|
|
|
|||
|
|
@ -70,6 +70,9 @@ pulldown-cmark = { version = "0.13", default-features = false }
|
|||
# vercel-labs/agent-desktop, Apache-2.0, pinned to a release.
|
||||
agent-desktop-core = { git = "https://github.com/vercel-labs/agent-desktop", tag = "v1.1.0" }
|
||||
argon2 = "0.5"
|
||||
# 秘密遮罩 (secrets.rs) and the log file (logfile.rs): both were already in the build through other crates.
|
||||
regex = "1"
|
||||
log = "0.4"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 2
|
||||
|
|
|
|||
|
|
@ -1491,6 +1491,12 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
- 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。
|
||||
- **在聊天裡請 Bot 加**(設定畫面能做的,聊天也能做):有「管理 App」能力的 Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器。改的就是大腦上「設定 › 整合 › 連接器」那一份(Bot 的這一輪本來就在大腦上跑),所以每台螢幕電腦和手機都看得到,不會寫到手腳電腦(例如 nobledesktop 上的 ~/.local/share/AnyBot)那邊的檔案。新增、修改、移除先跳「允許…管理連接器嗎?」卡片,列出要執行的指令或網址、環境變數和標頭;名字像金鑰的(TOKEN、KEY、SECRET、PASS、AUTH…)和密碼顯示成「••••(已填)」。加好後等它連上(最多 90 秒)再回報「已連上,N 個工具」或連不上的原因;連上的工具同一輪的下一步就能用(例如「加上 GitLab,然後列出我的 MR」一次做完)。名稱重複、command 和 url 都給、網址不是 http(s)、還有「{…}」沒填、要改卻沒東西可改,都在問你之前就回給 Bot 說原因。
|
||||
|
||||
### 紀錄檔、當掉報告、秘密遮罩
|
||||
|
||||
- **紀錄檔**:AnyBot 自己說的話(連線、記憶整理、模型換用、讀不到檔…)寫進資料夾的 `logs/anybot-YYYY-MM-DD.log`,每行有時間、等級、從哪裡來;一天一個檔、留 7 天、一天最多 20 MB(超過寫一行說明就不再寫,終端機照常)。終端機(伺服器的 docker logs)照舊印。ANYBOT_LOG 設等級(預設 info);其他套件只收 warn 以上。以前從 Finder 打開的 AnyBot 說的話沒有地方看。
|
||||
- **當掉報告**:任何一條執行緒 panic 時寫 `logs/crash-時間.txt`(版本、執行緒、檔案和行號、訊息、完整 backtrace)。下次打開在主要 Bot 的聊天留一行(幾次、哪裡、報告在哪),記進「待改進」;每份只說一次(看過的改名成 .seen.txt)。螢幕電腦是跳一則提示(它的聊天是大腦的)。
|
||||
- **秘密遮罩**:GitLab glpat-、GitHub ghp_/github_pat_、OpenAI/Anthropic sk-、xAI xai-、AWS AKIA、Slack xox、Google AIza、私鑰區塊、Bearer/Basic 標頭、JWT,以及名字像 TOKEN、SECRET、PASSWORD、API_KEY 的變數值,在紀錄檔、當掉報告、手機上的步驟細節和結果都換成 ••••(保留前綴,看得出是哪一種)。工作紀錄不遮(當掉後重做那一步要原本的參數),Bot 自己看到的也不遮(它可能正要用那個 Token 設定連接器)。
|
||||
|
||||
### 記憶、技能、範本
|
||||
|
||||
- **記憶**:每個 Bot 有三種記憶。完整設計(存在哪、分數怎麼算、送給模型的內容、每晚整理、API)見 [docs/memory.md](docs/memory.md)。
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「
|
|||
## 子功能
|
||||
|
||||
- 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。
|
||||
- 紀錄檔:AnyBot 自己的訊息寫在資料夾的 `logs/anybot-日期.log`(一天一個、留 7 天、一天最多 20 MB),同時照舊印在終端機(伺服器的 `make server-logs` 看得到)。等級用環境變數 ANYBOT_LOG(error、warn、info 預設、debug)。寫進去前先遮掉金鑰、Token、密碼(glpat-、ghp_、sk-、xai-、AKIA、Bearer、JWT、私鑰、名字像 TOKEN/SECRET/PASSWORD 的變數值 → ••••);手機上的步驟細節也一樣遮。
|
||||
- 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。
|
||||
- 園丁每日報告(平日 8:44 起):過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。
|
||||
- 園丁每週報告(週一 8:49 起):一週內失敗 2 成以上,或平均每次 60 步、30 分鐘以上的例行任務,列出跑幾次、幾次沒成功、共幾步幾分鐘。
|
||||
- 沒事不報;報告寫在主要 Bot 的聊天裡。時間照使用者的時區。
|
||||
|
|
@ -23,6 +25,8 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「
|
|||
|
||||
## 陷阱
|
||||
|
||||
- 工作紀錄(oplog)不遮金鑰:當掉後要照原本的參數重做那一步,遮了會壞;手機、紀錄檔、當掉報告才遮。
|
||||
|
||||
- 報告一天只做一次:時間到了之後、AnyBot 開著的時候才做;那天 AnyBot 一直沒開,就不會補做。
|
||||
- 每週報告只看有執行紀錄的例行任務;加紀錄功能之前跑的不算。
|
||||
- 待改進是給改 AnyBot 的人看的,Bot 不會自己修;清單滿 50 條,最舊的會被擠掉。
|
||||
|
|
|
|||
|
|
@ -16,17 +16,17 @@
|
|||
- 做法:`cfg(test)` 下 `cloudbox` 不啟動 VM、不跑 `docker`(除非 `ANYBOT_TEST_REAL_BOX=1`,只給標 ignored 的實機測試用),呼叫時直接回「測試裡沒有 Bot 的電腦」。
|
||||
- 做完:一個測試故意叫 Bot 的電腦跑指令,要立刻失敗而不是去開 VM。
|
||||
|
||||
### E2. 紀錄檔 ⬜
|
||||
### E2. 紀錄檔 ✅
|
||||
- 現況:72 個 `eprintln!`,App 從 Finder 打開時看不到;伺服器靠 docker logs。
|
||||
- 做法:`log.rs`:寫到資料夾的 `logs/anybot.log`(每天一個檔、留 7 天、單檔上限),同時照舊印到 stderr;等級用 `ANYBOT_LOG`(error/warn/info/debug)。`eprintln!` 全換成 `log::info!`/`warn!` 等巨集。寫進去前先過 E4 的遮罩。
|
||||
- 做完:打開 App 做一輪,`logs/` 有當天的檔;`make server-logs` 照樣看得到。
|
||||
|
||||
### E3. 當掉報告 ⬜
|
||||
### E3. 當掉報告 ✅
|
||||
- 做法:panic hook 把版本、執行緒、訊息、位置、backtrace 寫到 `logs/crash-<時間>.txt`(先遮罩);下次啟動在主要 Bot 的聊天留一行「AnyBot 上次在 … 當掉了(…),報告在 …」,並記一條「待改進」。
|
||||
- 做完:測試觸發 panic hook 會寫出報告;下次啟動讀到報告會留言、只留一次。
|
||||
|
||||
### E4. 秘密遮罩 ⬜
|
||||
- 做法:`secrets.rs`:GitLab `glpat-`、GitHub `ghp_/gho_/github_pat_`、OpenAI/Anthropic/xAI `sk-`/`xai-`、AWS `AKIA…`、Slack `xox…`、Google `AIza…`、PEM 私鑰、`Bearer …`、JWT、`TOKEN=…/KEY=…/SECRET=…/PASSWORD=…` 的值 → `••••`。用在:紀錄檔、當掉報告、工作紀錄(oplog)、給手機和螢幕電腦的聊天副本裡的步驟結果。
|
||||
### E4. 秘密遮罩 ✅
|
||||
- 做法:`secrets.rs`:GitLab `glpat-`、GitHub `ghp_/gho_/github_pat_`、OpenAI/Anthropic/xAI `sk-`/`xai-`、AWS `AKIA…`、Slack `xox…`、Google `AIza…`、PEM 私鑰、`Bearer …`、JWT、`TOKEN=…/KEY=…/SECRET=…/PASSWORD=…` 的值 → `••••`。用在:紀錄檔、當掉報告、手機上的步驟細節和結果。工作紀錄(oplog)不遮:當掉後重做那一步要原本的參數。
|
||||
- 做完:每一種格式都有測試;手機看到的步驟結果不含 Token。
|
||||
|
||||
### E5. 一個 HTTP 用戶端、子行程成群管理、lint 規則 ⬜
|
||||
|
|
|
|||
16
src/agent.rs
16
src/agent.rs
|
|
@ -329,22 +329,22 @@ fn learn(job: &Job, history: &[Message], cancel: &AtomicBool, send: &dyn Fn(Stre
|
|||
let out = match providers::run_step(&req, cancel, &|_| {}) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("AnyBot:整理做法時模型沒有回應:{e}");
|
||||
log::warn!("AnyBot:整理做法時模型沒有回應:{e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let issues = crate::memory::learned_issues(&out.text);
|
||||
if !issues.is_empty() {
|
||||
eprintln!("AnyBot:Bot 回報了 {} 個 AnyBot 自己的問題", issues.len());
|
||||
log::info!("AnyBot:Bot 回報了 {} 個 AnyBot 自己的問題", issues.len());
|
||||
send(StreamEvent::Issues(issues));
|
||||
}
|
||||
match (crate::memory::learned_skill(&out.text), turn.last()) {
|
||||
(Some(mut k), Some(reply)) => {
|
||||
k.steps = crate::memory::replay_steps(turn, &crate::memory::learned_replay(&out.text), &crate::memory::learned_blanks(&out.text));
|
||||
eprintln!("AnyBot:學到做法「{}」", k.name);
|
||||
log::info!("AnyBot:學到做法「{}」", k.name);
|
||||
send(StreamEvent::Learned(k, reply.at));
|
||||
}
|
||||
_ => eprintln!("AnyBot:這次的做法沒有存:{}", out.text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(200).collect::<String>()),
|
||||
_ => log::info!("AnyBot:這次的做法沒有存:{}", out.text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(200).collect::<String>()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1052,7 +1052,7 @@ fn maybe_compact(job: &Job, history: &mut Vec<Message>, percent: u64, cancel: &A
|
|||
let set_aside = fold_results(history);
|
||||
if !set_aside.is_empty() {
|
||||
let now = history_tokens(&job.req.system, history) + tools;
|
||||
eprintln!("AnyBot:對話很長,先收起 {} 個較早的步驟結果(約 {used} → {now} token)", set_aside.len());
|
||||
log::info!("AnyBot:對話很長,先收起 {} 個較早的步驟結果(約 {used} → {now} token)", set_aside.len());
|
||||
send(StreamEvent::Folded(set_aside));
|
||||
if percent > 0 && now * 100 < job.context_tokens * percent {
|
||||
return None;
|
||||
|
|
@ -1163,7 +1163,7 @@ fn make_room(job: &Job, history: &mut Vec<Message>, room: &mut Room, cancel: &At
|
|||
RoomWay::Pictures => {
|
||||
let n = drop_pictures(history);
|
||||
if n > 0 {
|
||||
eprintln!("AnyBot:對話太長,先拿掉 {n} 張圖片再試");
|
||||
log::info!("AnyBot:對話太長,先拿掉 {n} 張圖片再試");
|
||||
send(StreamEvent::Retrying(format!("對話太長了,先拿掉 {n} 張截圖再試一次…")));
|
||||
send(StreamEvent::PicturesDropped);
|
||||
}
|
||||
|
|
@ -1408,7 +1408,7 @@ impl StepPlan {
|
|||
self.main_next = true;
|
||||
self.troubles += 1;
|
||||
if self.troubles >= QUICK_TROUBLE_MAX && self.quick.take().is_some() {
|
||||
eprintln!("AnyBot:這一回合出了 {} 次問題,剩下的步驟改用 Bot 自己的模型", self.troubles);
|
||||
log::info!("AnyBot:這一回合出了 {} 次問題,剩下的步驟改用 Bot 自己的模型", self.troubles);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1793,7 +1793,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
|||
// Too long is the chat's problem, not the quick model's: folded below.
|
||||
Err(e) if providers::is_context_overflow(&e) => Err(e),
|
||||
Err(e) => {
|
||||
eprintln!("AnyBot:快速模型 {q} 不能用({e}),這一回合改用 {}", job.req.model);
|
||||
log::warn!("AnyBot:快速模型 {q} 不能用({e}),這一回合改用 {}", job.req.model);
|
||||
plan.quick_failed();
|
||||
providers::run_step(&main_req, &cancel, &send)
|
||||
}
|
||||
|
|
|
|||
65
src/app.rs
65
src/app.rs
|
|
@ -2289,7 +2289,7 @@ impl App {
|
|||
/// when the person presses it (resume_turn). This only notes them in the log.
|
||||
fn resume_interrupted(&mut self, _ctx: &egui::Context) {
|
||||
for t in std::mem::take(&mut self.interrupted) {
|
||||
eprintln!(
|
||||
log::info!(
|
||||
"AnyBot:Bot {} 的回合 {} 在 AnyBot 關掉時被中斷了({};可能已執行的步驟 {} 個;放回聊天的訊息 {} 則)",
|
||||
t.bot_id,
|
||||
t.op,
|
||||
|
|
@ -2358,6 +2358,33 @@ impl App {
|
|||
}
|
||||
}
|
||||
|
||||
/// 當掉報告 (logfile.rs): what panicked since the last start, told once — in the main bot's
|
||||
/// chat and in 待改進 (on a screen of a brain, whose chats are the brain's: a notice).
|
||||
fn tell_crashes(&mut self) {
|
||||
static TOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
if TOLD.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let reports = crate::logfile::take_crash_reports();
|
||||
if reports.is_empty() {
|
||||
return;
|
||||
}
|
||||
let now = crate::routines::now();
|
||||
let mut lines = vec![];
|
||||
for (when, at, what, path) in &reports {
|
||||
crate::garden::note_issue(&mut self.state.improvements, &format!("AnyBot 內部出錯:{what}({at})"), "AnyBot", now);
|
||||
lines.push(format!("{when} 在 {at}:{what}(報告:{})", path.display()));
|
||||
}
|
||||
let text = format!("AnyBot 上次執行時內部出錯 {} 次,已記進 設定 › 更新 ›「待改進」:\n{}", reports.len(), lines.join("\n"));
|
||||
if self.mir.on || !self.state.remote.brain_id.is_empty() {
|
||||
self.notice = Some(text);
|
||||
} else {
|
||||
let id = self.state.primary_bot;
|
||||
self.goal_note(id, &text);
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// Run due routines (a routine firing is a "wake" turn).
|
||||
fn tick_routines(&mut self, ctx: &egui::Context) {
|
||||
if self.demo || self.last_tick.elapsed() < std::time::Duration::from_secs(1) {
|
||||
|
|
@ -5911,6 +5938,10 @@ impl App {
|
|||
// document folders; hands never.
|
||||
let hands = !self.state.remote.hands_for.is_empty();
|
||||
crate::embed::set_wanted(!self.demo && !hands && (!self.mir.on || !self.state.doc_folders.is_empty()));
|
||||
// 當掉報告: a panic last time is told once (logfile.rs).
|
||||
if !self.demo {
|
||||
self.tell_crashes();
|
||||
}
|
||||
// A screen of another AnyBot's brain: its bots work there, not here.
|
||||
if self.mir.on {
|
||||
self.remote_tick(ctx);
|
||||
|
|
@ -5967,7 +5998,7 @@ impl App {
|
|||
if sweep_files {
|
||||
let n = crate::attach::sweep(&kept, &pages);
|
||||
if n > 0 {
|
||||
eprintln!("AnyBot:清掉 {n} 個聊天已經不用的檔案");
|
||||
log::info!("AnyBot:清掉 {n} 個聊天已經不用的檔案");
|
||||
}
|
||||
}
|
||||
let r = crate::memstore::tidy(None, &tz, crate::model::now_ms());
|
||||
|
|
@ -5977,7 +6008,7 @@ impl App {
|
|||
crate::cloudbox::sweep_temp();
|
||||
let copy = crate::store::backup_memory(7);
|
||||
crate::memstore::meta_set("last_tidy", &today);
|
||||
eprintln!("AnyBot:記憶整理好了({} 條做過的事壓成每週一行,{} 行每週的壓成每月一行,清掉 {} 條最近刪除;備份 {})", r.events, r.weeks, r.purged, copy.map(|p| p.display().to_string()).unwrap_or_else(|| "沒有成功".into()));
|
||||
log::info!("AnyBot:記憶整理好了({} 條做過的事壓成每週一行,{} 行每週的壓成每月一行,清掉 {} 條最近刪除;備份 {})", r.events, r.weeks, r.purged, copy.map(|p| p.display().to_string()).unwrap_or_else(|| "沒有成功".into()));
|
||||
RUNNING.store(false, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
|
@ -6013,7 +6044,7 @@ impl App {
|
|||
if r.is_err() && std::env::var("ANYBOT_ACCOUNT_CREATE").map(|v| v == "1").unwrap_or(false) {
|
||||
let invite = std::env::var("ANYBOT_RELAY_INVITE").unwrap_or_default();
|
||||
if let Ok(s) = crate::remote::relay_join(&self.state.remote, url, user, &pw, true, &invite, &code) {
|
||||
eprintln!("AnyBot:已建立帳號 {user}");
|
||||
log::info!("AnyBot:已建立帳號 {user}");
|
||||
r = Ok(s);
|
||||
}
|
||||
}
|
||||
|
|
@ -6021,10 +6052,10 @@ impl App {
|
|||
Ok(s) => {
|
||||
self.state.remote = s;
|
||||
self.dirty = true;
|
||||
eprintln!("AnyBot:已加入帳號 {user}({url})");
|
||||
log::info!("AnyBot:已加入帳號 {user}({url})");
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("AnyBot:登入帳號失敗(30 秒後再試):{e}");
|
||||
log::warn!("AnyBot:登入帳號失敗(30 秒後再試):{e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
@ -6033,12 +6064,12 @@ impl App {
|
|||
match crate::remote::restore(url, user, &pw, &code).and_then(|b| serde_json::from_slice::<State>(&b).map_err(|e| e.to_string())) {
|
||||
Ok(mut st) => {
|
||||
st.remote = self.state.remote.clone();
|
||||
eprintln!("AnyBot:已從帳號備份接手 {} 個 Bot", st.bots.len());
|
||||
log::info!("AnyBot:已從帳號備份接手 {} 個 Bot", st.bots.len());
|
||||
self.state = st;
|
||||
self.dirty = true;
|
||||
let _ = std::fs::write(&marker, chrono::Utc::now().to_rfc3339());
|
||||
}
|
||||
Err(e) => eprintln!("AnyBot:沒有接手備份:{e}"),
|
||||
Err(e) => log::warn!("AnyBot:沒有接手備份:{e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6056,7 +6087,7 @@ impl App {
|
|||
// 連接器: the window connects them as it draws (there is no drawing here), so a question
|
||||
// asked here had none of them. Connected before it starts.
|
||||
for (name, why) in crate::mcp::sync(&app.state.mcp_servers) {
|
||||
eprintln!("連接器「{name}」連不上:{why}");
|
||||
log::warn!("連接器「{name}」連不上:{why}");
|
||||
}
|
||||
let id = app.state.primary_bot;
|
||||
let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0);
|
||||
|
|
@ -6151,15 +6182,15 @@ impl App {
|
|||
if let Some(url) = std::env::var("ANYBOT_VOICE_URL").ok().map(|u| u.trim().to_string()).filter(|u| !u.is_empty()) {
|
||||
let var = |k: &str| std::env::var(k).unwrap_or_default();
|
||||
if crate::speech::own_server(&mut app.state.voice, &url, &var("ANYBOT_VOICE_LISTEN_MODEL"), &var("ANYBOT_VOICE_SPEAK_MODEL"), &var("ANYBOT_VOICE_VOICE")) {
|
||||
eprintln!("AnyBot:語音用這台伺服器的語音服務({url})");
|
||||
log::info!("AnyBot:語音用這台伺服器的語音服務({url})");
|
||||
app.dirty = true;
|
||||
}
|
||||
// Its model is downloaded when asked (once; then each start finds it at once).
|
||||
let model = var("ANYBOT_VOICE_LISTEN_MODEL");
|
||||
if !model.is_empty() {
|
||||
std::thread::spawn(move || match crate::speech::fetch_model(&url, &model) {
|
||||
Ok(()) => eprintln!("AnyBot:語音服務的模型就緒({model})"),
|
||||
Err(e) => eprintln!("AnyBot:{e}"),
|
||||
Ok(()) => log::info!("AnyBot:語音服務的模型就緒({model})"),
|
||||
Err(e) => log::warn!("AnyBot:{e}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -6167,14 +6198,14 @@ impl App {
|
|||
app.background(ctx);
|
||||
if let Some(port) = crate::remote::lan_port() {
|
||||
for a in crate::remote::addresses(port) {
|
||||
eprintln!("AnyBot:手機可以打開 {a}");
|
||||
log::info!("AnyBot:手機可以打開 {a}");
|
||||
}
|
||||
}
|
||||
if !app.state.remote.relay_url.is_empty() {
|
||||
eprintln!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url);
|
||||
log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url);
|
||||
}
|
||||
if app.state.remote.password.is_empty() && app.state.remote.host_token.is_empty() && std::env::var("ANYBOT_ACCOUNT").is_err() {
|
||||
eprintln!("AnyBot:還沒有設定手機密碼或帳號。用 ANYBOT_PHONE_PASSWORD=… 或 ANYBOT_ACCOUNT=網址|帳號 + ANYBOT_ACCOUNT_PASSWORD=… 啟動。");
|
||||
log::warn!("AnyBot:還沒有設定手機密碼或帳號。用 ANYBOT_PHONE_PASSWORD=… 或 ANYBOT_ACCOUNT=網址|帳號 + ANYBOT_ACCOUNT_PASSWORD=… 啟動。");
|
||||
}
|
||||
let mut last_try = Instant::now();
|
||||
let mut last_brain = Instant::now() - std::time::Duration::from_secs(60);
|
||||
|
|
@ -6189,7 +6220,7 @@ impl App {
|
|||
if !want.trim().is_empty() && !app.state.remote.host_token.is_empty() && app.state.remote.brain_name != want && last_brain.elapsed().as_secs() >= 20 {
|
||||
last_brain = Instant::now();
|
||||
if let Some((id, name, _)) = crate::remote::devices_online(&app.state.remote).into_iter().find(|(_, n, _)| n == want.trim()) {
|
||||
eprintln!("AnyBot:用「{name}」當大腦,這台當手腳");
|
||||
log::info!("AnyBot:用「{name}」當大腦,這台當手腳");
|
||||
app.mir.want = Some((id, name));
|
||||
app.state.remote.device_link = true;
|
||||
}
|
||||
|
|
@ -6200,7 +6231,7 @@ impl App {
|
|||
// Told to stop (docker stop, systemd, Ctrl-C): what the bots started stops, the
|
||||
// connectors close, the chats are saved — nothing is left running behind.
|
||||
if STOPPING.load(Ordering::SeqCst) {
|
||||
eprintln!("AnyBot:收到停止訊號,正在收尾…");
|
||||
log::info!("AnyBot:收到停止訊號,正在收尾…");
|
||||
eframe::App::on_exit(&mut app);
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -201,12 +201,12 @@ impl App {
|
|||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("AnyBot:用 {} 檢查目標沒有回應:{e}", req.model);
|
||||
log::warn!("AnyBot:用 {} 檢查目標沒有回應:{e}", req.model);
|
||||
judged = Judged::Failed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}");
|
||||
log::info!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}");
|
||||
let _ = tx.send((bot_id, 0, StreamEvent::Goal(g.since, judged)));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -450,7 +450,8 @@ impl App {
|
|||
if t.get("label").is_some() {
|
||||
t["name"] = json!(c.name);
|
||||
if let Some(r) = results.get(c.id.as_str()) {
|
||||
t["result"] = json!(clip(r.trim(), 600));
|
||||
// (秘密遮罩: what a step printed may hold a key; the phone shows it masked.)
|
||||
t["result"] = json!(clip(&crate::secrets::mask(r.trim()), 600));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -187,7 +187,7 @@ fn local() -> Option<Arc<crate::m2v::Model>> {
|
|||
}
|
||||
Err(e) => {
|
||||
// A broken copy (a disk filled up halfway): fetch it again.
|
||||
eprintln!("AnyBot:本機語意模型讀不了({e}),重新下載");
|
||||
log::warn!("AnyBot:本機語意模型讀不了({e}),重新下載");
|
||||
let _ = std::fs::remove_file(dir.join("dims.json"));
|
||||
None
|
||||
}
|
||||
|
|
@ -261,10 +261,10 @@ fn ensure_local() {
|
|||
match &r {
|
||||
Ok(()) => {
|
||||
*FETCH_ERR.lock().unwrap() = None;
|
||||
eprintln!("AnyBot:本機語意模型就緒({})", model_dir().display());
|
||||
log::info!("AnyBot:本機語意模型就緒({})", model_dir().display());
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("AnyBot:本機語意模型下載失敗:{e}");
|
||||
log::warn!("AnyBot:本機語意模型下載失敗:{e}");
|
||||
*FETCH_ERR.lock().unwrap() = Some((e.clone(), Instant::now()));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ fn take_at(p: &Path, wait: Duration) -> Result<DataLock, String> {
|
|||
Err(e) => {
|
||||
// A folder the lock can't be made in can't hold the chats either; say so, but don't
|
||||
// refuse to start over the lock alone.
|
||||
eprintln!("AnyBot:沒辦法建立 {}({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display());
|
||||
log::warn!("AnyBot:沒辦法建立 {}({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display());
|
||||
return Ok(DataLock { _file: None });
|
||||
}
|
||||
};
|
||||
|
|
@ -59,7 +59,7 @@ fn take_at(p: &Path, wait: Duration) -> Result<DataLock, String> {
|
|||
Err(std::fs::TryLockError::WouldBlock) => return Err(busy_message(p, &mut f)),
|
||||
Err(std::fs::TryLockError::Error(e)) => {
|
||||
// A file system without locks (some network shares): go on unchecked.
|
||||
eprintln!("AnyBot:{} 不能上鎖({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display());
|
||||
log::warn!("AnyBot:{} 不能上鎖({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display());
|
||||
return Ok(DataLock { _file: None });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,236 @@
|
|||
//! 紀錄檔與當掉報告: what AnyBot says about itself goes to `logs/anybot-YYYY-MM-DD.log` in its data
|
||||
//! folder (one file a day, the last LOG_DAYS days kept, at most LOG_MAX_BYTES a day) as well as to
|
||||
//! stderr, as before — an AnyBot opened from Finder had nowhere to say anything, and a server's
|
||||
//! only record was `docker logs`. The level is ANYBOT_LOG (error, warn, info — the default —,
|
||||
//! debug). Other crates' lines come in at warn and above only. Every line goes through the
|
||||
//! secret mask (secrets.rs) first.
|
||||
//!
|
||||
//! A panic anywhere (the window, a bot's turn, a background thread) leaves
|
||||
//! `logs/crash-<time>.txt`: the version, the thread, where and what, and a backtrace, masked. The
|
||||
//! next start says so once in the main bot's chat and in 待改進 (`take_crash_reports`).
|
||||
//!
|
||||
//! Like grok-build's per-session debug log and xai-crash-handler. Not under `cargo test`: tests
|
||||
//! never call `init`.
|
||||
|
||||
use ::log::{Level, LevelFilter, Log, Metadata, Record};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Days of log files kept.
|
||||
pub const LOG_DAYS: i64 = 7;
|
||||
/// A day's log file stops growing here (a loop writing a line a millisecond can't fill the disk).
|
||||
pub const LOG_MAX_BYTES: u64 = 20 * 1024 * 1024;
|
||||
|
||||
/// The folder the log files and crash reports are in.
|
||||
pub fn dir() -> PathBuf {
|
||||
crate::model::State::path().parent().map(Path::to_path_buf).unwrap_or_else(std::env::temp_dir).join("logs")
|
||||
}
|
||||
|
||||
struct Today {
|
||||
date: String,
|
||||
file: std::fs::File,
|
||||
bytes: u64,
|
||||
/// The cap was reached today (said once in the file).
|
||||
full: bool,
|
||||
}
|
||||
|
||||
struct FileLog {
|
||||
level: LevelFilter,
|
||||
dir: PathBuf,
|
||||
today: Mutex<Option<Today>>,
|
||||
}
|
||||
|
||||
/// The level ANYBOT_LOG asks for (info when unset or not understood).
|
||||
pub fn level_of(v: Option<&str>) -> LevelFilter {
|
||||
match v.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
|
||||
Some("off") => LevelFilter::Off,
|
||||
Some("error") => LevelFilter::Error,
|
||||
Some("warn" | "warning") => LevelFilter::Warn,
|
||||
Some("debug") => LevelFilter::Debug,
|
||||
Some("trace") => LevelFilter::Trace,
|
||||
_ => LevelFilter::Info,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a line is kept: AnyBot's own at the level asked for, other crates' at warn and above.
|
||||
fn keeps(level: LevelFilter, target: &str, l: Level) -> bool {
|
||||
l <= level && (target.starts_with("anybot") || l <= Level::Warn)
|
||||
}
|
||||
|
||||
/// One line as the file keeps it (the time, the level, where from, the masked words).
|
||||
pub fn line(at: &chrono::DateTime<chrono::Local>, l: Level, target: &str, msg: &str) -> String {
|
||||
let target = target.strip_prefix("anybot::").unwrap_or(target);
|
||||
format!("{} {:<5} {target}: {}\n", at.format("%Y-%m-%d %H:%M:%S%.3f"), l, crate::secrets::mask(msg).replace('\n', "\n "))
|
||||
}
|
||||
|
||||
impl FileLog {
|
||||
fn write(&self, text: &str) {
|
||||
let now = chrono::Local::now();
|
||||
let date = now.format("%Y-%m-%d").to_string();
|
||||
let mut g = self.today.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if g.as_ref().map(|t| t.date != date).unwrap_or(true) {
|
||||
let path = self.dir.join(format!("anybot-{date}.log"));
|
||||
*g = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok().map(|file| {
|
||||
let bytes = file.metadata().map(|m| m.len()).unwrap_or(0);
|
||||
Today { date, file, bytes, full: false }
|
||||
});
|
||||
prune(&self.dir, now.date_naive());
|
||||
}
|
||||
let Some(t) = g.as_mut() else { return };
|
||||
if t.bytes + text.len() as u64 > LOG_MAX_BYTES {
|
||||
if !t.full {
|
||||
t.full = true;
|
||||
let _ = t.file.write_all(format!("(今天的紀錄超過 {} MB,之後的不寫進檔案,stderr 照常)\n", LOG_MAX_BYTES / 1024 / 1024).as_bytes());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if t.file.write_all(text.as_bytes()).is_ok() {
|
||||
t.bytes += text.len() as u64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Log for FileLog {
|
||||
fn enabled(&self, m: &Metadata) -> bool {
|
||||
keeps(self.level, m.target(), m.level())
|
||||
}
|
||||
|
||||
fn log(&self, r: &Record) {
|
||||
if !self.enabled(r.metadata()) {
|
||||
return;
|
||||
}
|
||||
let msg = r.args().to_string();
|
||||
// stderr as before (a server's `docker logs`, a terminal), masked too.
|
||||
eprintln!("{}", crate::secrets::mask(&msg));
|
||||
self.write(&line(&chrono::Local::now(), r.level(), r.target(), &msg));
|
||||
}
|
||||
|
||||
fn flush(&self) {
|
||||
if let Some(t) = self.today.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
let _ = t.file.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Log files older than LOG_DAYS (by the date in their name) go.
|
||||
fn prune(dir: &Path, today: chrono::NaiveDate) {
|
||||
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
let day = name.strip_prefix("anybot-").and_then(|n| n.strip_suffix(".log")).and_then(|d| chrono::NaiveDate::parse_from_str(d, "%Y-%m-%d").ok());
|
||||
if day.is_some_and(|d| (today - d).num_days() >= LOG_DAYS) {
|
||||
let _ = std::fs::remove_file(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the log file and the crash reports (once, first thing in `main`).
|
||||
pub fn init() {
|
||||
let dir = dir();
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let level = level_of(std::env::var("ANYBOT_LOG").ok().as_deref());
|
||||
if ::log::set_boxed_logger(Box::new(FileLog { level, dir: dir.clone(), today: Mutex::new(None) })).is_ok() {
|
||||
::log::set_max_level(level);
|
||||
}
|
||||
install_crash_hook(dir);
|
||||
}
|
||||
|
||||
/// What a crash report says (masked): the version, the thread, where, what, and the backtrace.
|
||||
pub fn crash_report(version: &str, thread: &str, at: &str, what: &str, backtrace: &str) -> String {
|
||||
crate::secrets::mask(&format!("AnyBot {version}\n時間:{}\n執行緒:{thread}\n位置:{at}\n訊息:{what}\n\n{backtrace}\n", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"))).into_owned()
|
||||
}
|
||||
|
||||
fn install_crash_hook(dir: PathBuf) {
|
||||
let before = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let what = info.payload().downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| info.payload().downcast_ref::<String>().cloned()).unwrap_or_default();
|
||||
let at = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_default();
|
||||
let thread = std::thread::current().name().unwrap_or("(沒有名字)").to_string();
|
||||
let report = crash_report(&crate::version::full(crate::version::exe_modified()), &thread, &at, &what, &std::backtrace::Backtrace::force_capture().to_string());
|
||||
let path = dir.join(format!("crash-{}.txt", chrono::Local::now().format("%Y%m%d-%H%M%S%.3f")));
|
||||
let _ = std::fs::write(&path, report);
|
||||
::log::error!("AnyBot 內部出錯({thread},{at}):{what}。報告:{}", path.display());
|
||||
before(info);
|
||||
}));
|
||||
}
|
||||
|
||||
/// Crash reports not told yet: (when, where, what, the report's path). Each is told once: it is
|
||||
/// renamed `….seen.txt` here.
|
||||
pub fn take_crash_reports() -> Vec<(String, String, String, PathBuf)> {
|
||||
take_crash_reports_in(&dir())
|
||||
}
|
||||
|
||||
pub fn take_crash_reports_in(dir: &Path) -> Vec<(String, String, String, PathBuf)> {
|
||||
let mut out = vec![];
|
||||
let mut names: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("crash-") && n.ends_with(".txt") && !n.ends_with(".seen.txt"))).collect();
|
||||
names.sort();
|
||||
for p in names {
|
||||
let text = std::fs::read_to_string(&p).unwrap_or_default();
|
||||
let field = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).unwrap_or("").trim().to_string();
|
||||
let seen = p.with_file_name(p.file_name().and_then(|n| n.to_str()).unwrap_or("crash.txt").replace(".txt", ".seen.txt"));
|
||||
let _ = std::fs::rename(&p, &seen);
|
||||
out.push((field("時間:"), field("位置:"), field("訊息:"), seen));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn levels_and_whose_lines_are_kept() {
|
||||
assert_eq!(level_of(None), LevelFilter::Info);
|
||||
assert_eq!(level_of(Some(" DEBUG ")), LevelFilter::Debug);
|
||||
assert_eq!(level_of(Some("nonsense")), LevelFilter::Info);
|
||||
assert!(keeps(LevelFilter::Info, "anybot::agent", Level::Info));
|
||||
assert!(!keeps(LevelFilter::Info, "anybot::agent", Level::Debug));
|
||||
assert!(!keeps(LevelFilter::Info, "rustls::client", Level::Info), "other crates: warn and up");
|
||||
assert!(keeps(LevelFilter::Info, "rustls::client", Level::Warn));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_is_timed_leveled_and_masked() {
|
||||
let at = chrono::Local::now();
|
||||
let l = line(&at, Level::Warn, "anybot::mcp", "連不上:GITLAB_TOKEN=glpat-abcdefghijklmnopqrstu\n第二行");
|
||||
assert!(l.contains(" WARN mcp: 連不上:GITLAB_TOKEN=••••\n 第二行\n"), "{l}");
|
||||
assert!(!l.contains("glpat-abcdefghij"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_rolls_daily_is_capped_and_old_days_go() {
|
||||
let d = std::env::temp_dir().join(format!("anybot-log-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::write(d.join("anybot-2000-01-01.log"), "old").unwrap();
|
||||
std::fs::write(d.join("keep.txt"), "not a log").unwrap();
|
||||
let f = FileLog { level: LevelFilter::Info, dir: d.clone(), today: Mutex::new(None) };
|
||||
f.write("第一行\n");
|
||||
let today = d.join(format!("anybot-{}.log", chrono::Local::now().format("%Y-%m-%d")));
|
||||
assert_eq!(std::fs::read_to_string(&today).unwrap(), "第一行\n");
|
||||
assert!(!d.join("anybot-2000-01-01.log").exists() && d.join("keep.txt").exists());
|
||||
f.today.lock().unwrap().as_mut().unwrap().bytes = LOG_MAX_BYTES - 2;
|
||||
f.write("太長了\n");
|
||||
f.write("還是太長\n");
|
||||
let text = std::fs::read_to_string(&today).unwrap();
|
||||
assert_eq!(text.matches("超過").count(), 1, "{text}");
|
||||
assert!(!text.contains("太長了"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crash_report_is_told_once_and_masked() {
|
||||
let d = std::env::temp_dir().join(format!("anybot-crash-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let r = crash_report("v0.1.0-test", "main", "src/app.rs:12", "index out of bounds; token sk-abcdefghijklmnopqrstuvwxyz", " 0: anybot::main");
|
||||
assert!(r.contains("位置:src/app.rs:12") && r.contains("sk-••••") && !r.contains("sk-abcdefghijklmnop"), "{r}");
|
||||
std::fs::write(d.join("crash-20261117-104200.000.txt"), &r).unwrap();
|
||||
let got = take_crash_reports_in(&d);
|
||||
assert_eq!(got.len(), 1);
|
||||
assert_eq!((got[0].1.as_str(), got[0].2.as_str()), ("src/app.rs:12", "index out of bounds; token sk-••••"));
|
||||
assert!(got[0].3.ends_with("crash-20261117-104200.000.seen.txt") && got[0].3.exists());
|
||||
assert!(take_crash_reports_in(&d).is_empty(), "told once");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
|
|
@ -72,6 +72,8 @@ mod garden;
|
|||
mod goal;
|
||||
mod plan;
|
||||
mod always;
|
||||
mod secrets;
|
||||
mod logfile;
|
||||
mod store;
|
||||
mod docindex;
|
||||
mod drops;
|
||||
|
|
@ -311,6 +313,8 @@ fn main() -> eframe::Result<()> {
|
|||
println!("AnyBot {}", version::full(version::exe_modified()));
|
||||
return Ok(());
|
||||
}
|
||||
// 紀錄檔與當掉報告 (logfile.rs): logs/ in the data folder, and a report if anything panics.
|
||||
logfile::init();
|
||||
// `anybot --update-box` (make update-box): 更新 Bot 的電腦 from a terminal, by this AnyBot —
|
||||
// or the one running on this data folder (cloudbox::update_box_cli).
|
||||
if args.get(1).map(String::as_str) == Some("--update-box") {
|
||||
|
|
@ -415,7 +419,7 @@ fn main() -> eframe::Result<()> {
|
|||
// No window: keep the bots working and answer the phone (always-on Mac or server).
|
||||
if args.iter().any(|a| a == "--serve") {
|
||||
// The first line of the log says which build is running (make server-logs, journalctl).
|
||||
eprintln!("AnyBot {}", version::full(version::exe_modified()));
|
||||
log::info!("AnyBot {}", version::full(version::exe_modified()));
|
||||
let ctx = egui::Context::default();
|
||||
let _folder = take_folder_or_exit();
|
||||
app::App::serve(&ctx);
|
||||
|
|
|
|||
|
|
@ -961,7 +961,7 @@ impl State {
|
|||
// nothing is saved over it this run.
|
||||
Err(e) => {
|
||||
let aside = p.with_extension(format!("json.unreadable-{stamp}"));
|
||||
eprintln!("AnyBot:讀不到 {}({e})。原檔會留著,不會被新的設定蓋掉。", p.display());
|
||||
log::error!("AnyBot:讀不到 {}({e})。原檔會留著,不會被新的設定蓋掉。", p.display());
|
||||
if std::fs::rename(p, &aside).is_err() {
|
||||
KEEP_UNREAD_SAVE.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -154,7 +154,7 @@ impl OpLog {
|
|||
f.sync_data()
|
||||
});
|
||||
if let Err(e) = written {
|
||||
eprintln!("AnyBot:寫不進工作紀錄 {}:{e}", self.path.display());
|
||||
log::error!("AnyBot:寫不進工作紀錄 {}:{e}", self.path.display());
|
||||
}
|
||||
// The same line, mirrored into the queryable trail (SQLite). Best-effort: an
|
||||
// audit that never breaks a turn.
|
||||
|
|
|
|||
|
|
@ -147,7 +147,7 @@ pub fn runs_when_opened(p: &Path) -> bool {
|
|||
pub fn open_with_system(target: &str) {
|
||||
let mut c = system_open(target);
|
||||
if let Err(e) = crate::computer::spawn_reaped(&mut c) {
|
||||
eprintln!("anybot: couldn't open {target}: {e}");
|
||||
log::warn!("anybot: couldn't open {target}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -381,7 +381,7 @@ pub(crate) fn tool_detail(name: &str, args: &str) -> String {
|
|||
} else {
|
||||
crate::tools::describe(name, args)
|
||||
};
|
||||
d.chars().take(120).collect()
|
||||
crate::secrets::mask(&d).chars().take(120).collect()
|
||||
}
|
||||
|
||||
/// One message as the phone shows it (tool results are folded away like in the window).
|
||||
|
|
@ -1538,7 +1538,7 @@ pub fn lan_fingerprint() -> Option<String> {
|
|||
fn lan_tls(port: u16) -> Option<(std::net::TcpListener, Arc<rustls::ServerConfig>, String)> {
|
||||
let dir = crate::model::State::path().parent()?.to_path_buf();
|
||||
let hosts: Vec<String> = addresses(port).iter().filter_map(|a| host_port(a).map(|(h, _)| h)).collect();
|
||||
let (cert, key) = crate::lantls::identity(&dir, &hosts).map_err(|e| eprintln!("區網 HTTPS 的憑證做不出來:{e}")).ok()?;
|
||||
let (cert, key) = crate::lantls::identity(&dir, &hosts).map_err(|e| log::warn!("區網 HTTPS 的憑證做不出來:{e}")).ok()?;
|
||||
let print = crate::lantls::fingerprint(&cert);
|
||||
let cfg = crate::lantls::config(cert, key).ok()?;
|
||||
let behind = std::net::TcpListener::bind("127.0.0.1:0").ok()?;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,109 @@
|
|||
//! 秘密遮罩: keys, tokens and passwords written as text are replaced with •••• before the text is
|
||||
//! kept somewhere it doesn't need them — the log file, a crash report, the steps the phone shows.
|
||||
//! What a known format looks like (GitLab glpat-, GitHub ghp_/github_pat_, sk-, xai-, AWS AKIA,
|
||||
//! Slack xox, Google AIza, a private key block, a Bearer header, a JWT) and any `NAME=value`
|
||||
//! whose name says it is a secret (…TOKEN, …SECRET, …PASSWORD, …API_KEY…). Like grok-build's
|
||||
//! xai-grok-secrets sanitizer.
|
||||
//!
|
||||
//! Not used on what a step needs to run again: the work log (oplog) replays a step after a crash
|
||||
//! with the arguments it had, so a masked key there would break it. The model sees what it was
|
||||
//! given (it may need a token to set a connector up).
|
||||
|
||||
use regex::{Captures, Regex};
|
||||
use std::borrow::Cow;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// What a secret becomes.
|
||||
pub const MASK: &str = "••••";
|
||||
|
||||
struct Rule {
|
||||
re: Regex,
|
||||
/// The group kept in front of the mask (a format's prefix, a variable's name and its `=`).
|
||||
keep: usize,
|
||||
}
|
||||
|
||||
fn rules() -> &'static [Rule] {
|
||||
static R: OnceLock<Vec<Rule>> = OnceLock::new();
|
||||
R.get_or_init(|| {
|
||||
let r = |p: &str, keep: usize| Rule { re: Regex::new(p).expect("secret pattern"), keep };
|
||||
vec![
|
||||
// A private key block: the whole block.
|
||||
r(r"(-----BEGIN [A-Z ]*PRIVATE KEY-----)[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----", 1),
|
||||
r(r"\b(glpat-)[A-Za-z0-9_\-.]{20,}", 1),
|
||||
r(r"\b(gh[pousr]_)[A-Za-z0-9]{30,}", 1),
|
||||
r(r"\b(github_pat_)[A-Za-z0-9_]{40,}", 1),
|
||||
r(r"\b(sk-(?:ant-|proj-)?)[A-Za-z0-9_\-]{20,}", 1),
|
||||
r(r"\b(xai-)[A-Za-z0-9]{20,}", 1),
|
||||
r(r"\b((?:AKIA|ASIA))[0-9A-Z]{16}\b", 1),
|
||||
r(r"\b(xox[abprs]-)[A-Za-z0-9\-]{10,}", 1),
|
||||
r(r"\b(AIza)[0-9A-Za-z_\-]{35}", 1),
|
||||
r(r"\b(eyJ)[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}", 1),
|
||||
r(r"(?i)\b(Bearer\s+)[A-Za-z0-9._\-~+/]{12,}=*", 1),
|
||||
r(r"(?i)\b(Basic\s+)[A-Za-z0-9+/]{12,}=*", 1),
|
||||
// NAME=value / NAME: value / "name": "value" with a name that says secret.
|
||||
r(r#"(?i)((?:["']?)[A-Z0-9_\-]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CLIENT_?SECRET)[A-Z0-9_\-]*["']?\s*[=:]\s*["']?)[^\s"',;&]{6,}"#, 1),
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/// The text with every secret it shows replaced (borrowed when there was none).
|
||||
pub fn mask(text: &str) -> Cow<'_, str> {
|
||||
let mut out: Cow<str> = Cow::Borrowed(text);
|
||||
for rule in rules() {
|
||||
if rule.re.is_match(&out) {
|
||||
let next = rule.re.replace_all(&out, |c: &Captures| format!("{}{MASK}", c.get(rule.keep).map(|m| m.as_str()).unwrap_or(""))).into_owned();
|
||||
out = Cow::Owned(next);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the text shows a secret.
|
||||
#[cfg(test)]
|
||||
pub fn has_secret(text: &str) -> bool {
|
||||
rules().iter().any(|r| r.re.is_match(text))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_formats_are_masked_with_their_prefix_kept() {
|
||||
let cases = [
|
||||
("token glpat-AbCdEfGhIjKlMnOpQrSt12 ok", "token glpat-•••• ok"),
|
||||
("ghp_0123456789abcdefghijABCDEFGHIJ012345", "ghp_••••"),
|
||||
("github_pat_11ABCDEFG0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGH", "github_pat_••••"),
|
||||
("key sk-proj-abcdefghijklmnopqrstuvwx1234", "key sk-proj-••••"),
|
||||
("sk-ant-api03-abcdefghijklmnopqrstuvwxyz", "sk-ant-••••"),
|
||||
("xai-ABCDEFGHIJKLMNOPQRSTUVWXYZ012345", "xai-••••"),
|
||||
("AKIAIOSFODNN7EXAMPLE", "AKIA••••"),
|
||||
("xoxb-1234567890-abcdefghij", "xoxb-••••"),
|
||||
("AIzaSyA-0123456789abcdefghijklmnopqrstu", "AIza••••"),
|
||||
("Authorization: Bearer abc.DEF_ghi-jkl123", "Authorization: Bearer ••••"),
|
||||
("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U", "eyJ••••"),
|
||||
];
|
||||
for (input, want) in cases {
|
||||
assert_eq!(mask(input), want, "{input}");
|
||||
assert!(has_secret(input), "{input}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_named_variable_keeps_its_name() {
|
||||
assert_eq!(mask("GITLAB_PERSONAL_ACCESS_TOKEN=_hZFE6ya-m2LjH4qWrtyuW86MQ"), "GITLAB_PERSONAL_ACCESS_TOKEN=••••");
|
||||
assert_eq!(mask(r#"{"password": "hunter2-long"}"#), r#"{"password": "••••"}"#);
|
||||
assert_eq!(mask("export OPENAI_API_KEY='abcdef123456' && run"), "export OPENAI_API_KEY='••••' && run");
|
||||
assert_eq!(mask("DB_PASSWORD: s3cr3t!x"), "DB_PASSWORD: ••••");
|
||||
let pem = "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXk\nAAAA\n-----END OPENSSH PRIVATE KEY-----";
|
||||
assert_eq!(mask(pem), "-----BEGIN OPENSSH PRIVATE KEY-----••••");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_text_is_left_alone() {
|
||||
for s in ["已新增連接器「gitlab」,正在連線。", "tokens: 1234 used", "password", "the key is in the drawer", "sk-short", "Bearer x", "GITLAB_API_URL=https://gitlab.example.com/api/v4"] {
|
||||
assert!(matches!(mask(s), Cow::Borrowed(_)), "{s}");
|
||||
assert!(!has_secret(s), "{s}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue