diff --git a/FEATURES.md b/FEATURES.md index a4bfb1b..9a74588 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -486,7 +486,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 「/」清單只放指令 -- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 +- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 ### 上線前補上的防護(安全和資源) @@ -1493,6 +1493,12 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 - **在聊天裡請 Bot 加**(設定畫面能做的,聊天也能做):有「管理 App」能力的 Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器。改的就是大腦上「設定 › 整合 › 連接器」那一份(Bot 的這一輪本來就在大腦上跑),所以每台螢幕電腦和手機都看得到,不會寫到手腳電腦(例如 nobledesktop 上的 ~/.local/share/AnyBot)那邊的檔案。新增、修改、移除先跳「允許…管理連接器嗎?」卡片,列出要執行的指令或網址、環境變數和標頭;名字像金鑰的(TOKEN、KEY、SECRET、PASS、AUTH…)和密碼顯示成「••••(已填)」。加好後等它連上(最多 90 秒)再回報「已連上,N 個工具」或連不上的原因;連上的工具同一輪的下一步就能用(例如「加上 GitLab,然後列出我的 MR」一次做完)。名稱重複、command 和 url 都給、網址不是 http(s)、還有「{…}」沒填、要改卻沒東西可改,都在問你之前就回給 Bot 說原因。 +### 用量(/usage) + +- 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。 +- OpenAI、xAI、OpenRouter 的請求加上 stream_options.include_usage,最後一段會說用了多少;Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,這裡拆開,兩家看起來一樣。 +- 「/usage」在聊天裡留一行:最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成,依 Bot 和依模型各列前 8 名。不猜價錢:供應商沒說的花費就不寫。 + ### 紀錄檔、當掉報告、秘密遮罩 - **紀錄檔**:AnyBot 自己說的話(連線、記憶整理、模型換用、讀不到檔…)寫進資料夾的 `logs/anybot-YYYY-MM-DD.log`,每行有時間、等級、從哪裡來;一天一個檔、留 7 天、一天最多 20 MB(超過寫一行說明就不再寫,終端機照常)。終端機(伺服器的 docker logs)照舊印。ANYBOT_LOG 設等級(預設 info);其他套件只收 warn 以上。以前從 Finder 打開的 AnyBot 說的話沒有地方看。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index c3b6bd3..3d30221 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -5,7 +5,7 @@ ## 子功能 - 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。 -- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md)),打「@」列出其他 Bot。 +- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費),打「@」列出其他 Bot。 - 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。 - 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - 停止:工作中、輸入框空著時,送出鈕變成「停止」。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 9b364fe..054bfb0 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -42,7 +42,7 @@ - 做法:`testkit.rs`(`cfg(test)`):一個假模型伺服器,OpenAI 和 Anthropic 兩種格式,照劇本回文字或工具呼叫,能注入 429/5xx(帶 Retry-After)、斷線、空回應;記下每個請求。把 agent.rs 和 app.rs 測試裡三份各自的假伺服器換成它。 - 做完:舊測試全換過來照樣過;新增注入錯誤的重試測試(接 P1)。 -### E8. 每一輪的用量和花費 ⬜ +### E8. 每一輪的用量和花費 ✅(花費只寫供應商有回報的,不猜價錢) - 做法:每一步記下輸入、輸出、快取讀寫 token(供應商回什麼記什麼),寫進工作紀錄;一輪結束加總。`/usage`(或對話詳細資訊)看最近一天、一週,每個 Bot、每個模型。 - 做完:跑一輪後工作紀錄有用量;`/usage` 列得出來。 diff --git a/mobile/index.html b/mobile/index.html index a89beeb..ccedb8e 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1656,7 +1656,7 @@ input.addEventListener("keydown", (e) => { input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } }); const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false}; /** AnyBot's own / commands (goal.rs on the brain). */ -const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; +const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; const GOAL_TAG = "[目標]"; /** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name * contains it, then description. None once a space ends the name, or while the bot works. */ @@ -1754,7 +1754,7 @@ async function send() { const memories = b.busy ? undefined : memPicks(); memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); - const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text); + const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/usage\s*$/i.test(text); if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } // 先顯示: while it works the words aren't in the chat yet — shown at once all the same. const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null; diff --git a/src/agent.rs b/src/agent.rs index d03db80..6f4edd6 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1781,7 +1781,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let mut out = loop { // A replay step: no model. if let Some(c) = scripted.clone() { - break providers::StepOutput { text: String::new(), thinking: String::new(), tool_calls: vec![c], blocks: vec![] }; + break providers::StepOutput { tool_calls: vec![c], ..Default::default() }; } attempt += 1; job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "assistant".into(), attempt }); diff --git a/src/app.rs b/src/app.rs index 006ced7..9892b09 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1410,7 +1410,7 @@ impl App { } // 先顯示: while it works (or the words travel to the brain) they aren't in the chat // yet — the person sees them at once all the same. (A command here draws its own line.) - let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some() || crate::always::command(&text).is_some()); + let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some() || crate::always::command(&text).is_some() || crate::usage::command(&text)); if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command { self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now())); } @@ -1460,6 +1460,11 @@ impl App { self.always_command(ctx, bot_id, cmd); return; } + // 用量: 「/usage」 — what the models used, a line in this chat. + if crate::usage::command(&text) { + self.usage_note(bot_id); + return; + } self.goal_heard(bot_id); // While it works, a new message steers the running turn (the original's `turnSteer`: // it doesn't count as a new turn) and reaches the model at its next step. @@ -2572,6 +2577,16 @@ impl App { self.state.direct_mode && self.managed.direct.allows() && self.managed.local.allows() } + /// 「/usage」: the last day and week of model use (usage.rs), as a line in this chat. + fn usage_note(&mut self, bot_id: u64) { + let now = crate::model::now_ms(); + let entries = crate::usage::since(now - 7 * 86_400_000); + let names: std::collections::HashMap = self.state.bots.iter().map(|b| (b.id, b.name.clone())).collect(); + let text = crate::usage::summary(&entries, now, &|id| names.get(&id).cloned()); + self.goal_note(bot_id, &text); + self.dirty = true; + } + /// 一律放行 as it applies: on, and not locked by an admin. fn always_on(&self) -> bool { self.state.always_approve && self.managed.direct.allows() && self.managed.local.allows() @@ -8310,7 +8325,7 @@ mod tests { let mut bot = app.state.bots[0].clone(); bot.skills = Some(vec!["週報".into()]); let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::>(); - assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve"]); + assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage"]); assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word"); assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 0f82649..4228885 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -1133,7 +1133,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool { } /// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs). -pub const SLASH_COMMANDS: [(&str, &str); 4] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)")]; +pub const SLASH_COMMANDS: [(&str, &str); 5] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token")]; /// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone). /// A status of several lines — a retry: the error, what it means, when it tries again — used to diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 0be16f0..d016638 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -553,6 +553,10 @@ impl App { self.always_command(ctx, bot, cmd); return; } + if crate::usage::command(&text) { + self.usage_note(bot); + return; + } self.goal_heard(bot); } if self.streams.contains_key(&bot) { diff --git a/src/main.rs b/src/main.rs index 98eda6d..f0b97b8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -75,6 +75,7 @@ mod always; mod secrets; mod logfile; mod net; +mod usage; #[cfg(test)] mod testkit; mod store; diff --git a/src/providers.rs b/src/providers.rs index 1cf1525..c4b5fb5 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -318,6 +318,52 @@ pub struct StepOutput { pub tool_calls: Vec, /// Claude's raw content blocks, kept to replay thinking signatures unchanged. pub blocks: Vec, + /// 用量: what this step used, as the provider said (zero when it didn't). + pub usage: Usage, +} + +/// What a model call used. `input` is the input not read from the prompt cache (OpenAI counts +/// cached tokens inside prompt_tokens; they are taken out here so both kinds read the same). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Usage { + #[serde(default)] + pub input: u64, + #[serde(default)] + pub output: u64, + #[serde(default)] + pub cache_read: u64, + #[serde(default)] + pub cache_write: u64, + /// What it cost in millionths of a dollar, when the provider says (OpenRouter does). + #[serde(default)] + pub cost_micros: u64, +} + +impl Usage { + pub fn add(&mut self, o: &Usage) { + self.input += o.input; + self.output += o.output; + self.cache_read += o.cache_read; + self.cache_write += o.cache_write; + self.cost_micros += o.cost_micros; + } + + pub fn is_empty(&self) -> bool { + *self == Usage::default() + } + + /// An OpenAI-style `usage` object (OpenAI, xAI, OpenRouter, Ollama…). + pub fn of_openai(u: &Value) -> Usage { + let g = |v: &Value| v.as_u64().unwrap_or(0); + let cached = g(&u["prompt_tokens_details"]["cached_tokens"]).max(g(&u["cached_prompt_text_tokens"])); + Usage { + input: g(&u["prompt_tokens"]).saturating_sub(cached), + output: g(&u["completion_tokens"]), + cache_read: cached, + cache_write: 0, + cost_micros: u["cost"].as_f64().map(|c| (c * 1_000_000.0).round() as u64).unwrap_or(0), + } + } } /// Why a request failed, sorted the way the error catalog sorts them. @@ -641,6 +687,15 @@ fn hant_call(mut c: ToolCall) -> ToolCall { } pub(crate) fn run_step_as_written(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { + let out = run_step_unbooked(req, cancel, send); + // 用量: every model call is written down (usage.rs), whoever made it. + if let Ok(o) = &out { + crate::usage::note(req, &o.usage); + } + out +} + +fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { // The bot's instructions and tool descriptions in this system's words ("this computer" on Linux). #[cfg(not(target_os = "macos"))] let localized = { @@ -1154,6 +1209,10 @@ fn stream_openai_compatible(req: &ChatRequest, cancel: &AtomicBool, send: &dyn F fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { let mut body = json!({"model": req.model, "messages": openai_messages(req), "stream": true}); + // 用量: the last chunk says what the answer used (where the service is known to take this). + if matches!(req.kind, ProviderKind::OpenAi | ProviderKind::Xai | ProviderKind::OpenRouter) { + body["stream_options"] = json!({"include_usage": true}); + } if let Some(e) = effort { body["reasoning_effort"] = json!(e); } @@ -1218,6 +1277,9 @@ fn stream_openai_with(req: &ChatRequest, effort: Option<&str>, cancel: &AtomicBo error = Some(e.get("message").and_then(Value::as_str).unwrap_or("未知錯誤").to_string()); return false; } + if let Some(u) = v.get("usage").filter(|u| u.is_object()) { + out.usage = Usage::of_openai(u); + } let delta = &v["choices"][0]["delta"]; for k in ["reasoning_content", "reasoning"] { if let Some(t) = delta.get(k).and_then(Value::as_str) { @@ -1368,15 +1430,6 @@ fn cache_tail(mut messages: Vec) -> Vec { messages } -/// (input_tokens, cache_read_input_tokens, cache_creation_input_tokens) summed over the -/// session's Claude answers: the cache hit rate is the number that tells whether the -/// breakpoints work (see `anybot` diagnostics / make doctor). -static CACHE_STATS: std::sync::Mutex<(u64, u64, u64)> = std::sync::Mutex::new((0, 0, 0)); - -#[allow(dead_code)] -pub fn cache_stats() -> (u64, u64, u64) { - *CACHE_STATS.lock().unwrap_or_else(|e| e.into_inner()) -} fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { let mut body = json!({ @@ -1499,13 +1552,16 @@ fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Stream "message_start" => { if let Some(u) = v["message"]["usage"].as_object() { let g = |k: &str| u.get(k).and_then(|x| x.as_u64()).unwrap_or(0); - let mut s = CACHE_STATS.lock().unwrap_or_else(|e| e.into_inner()); - s.0 += g("input_tokens"); - s.1 += g("cache_read_input_tokens"); - s.2 += g("cache_creation_input_tokens"); + out.usage.input = g("input_tokens"); + out.usage.cache_read = g("cache_read_input_tokens"); + out.usage.cache_write = g("cache_creation_input_tokens"); + out.usage.output = g("output_tokens"); } } "message_delta" => { + if let Some(n) = v["usage"]["output_tokens"].as_u64() { + out.usage.output = n; + } if v["delta"]["stop_reason"] == "refusal" { out.text.push_str("\n\n(模型拒絕回答這個要求。)"); send(StreamEvent::Text("\n\n(模型拒絕回答這個要求。)".into())); diff --git a/src/testkit.rs b/src/testkit.rs index 3ada89d..1f75783 100644 --- a/src/testkit.rs +++ b/src/testkit.rs @@ -196,6 +196,33 @@ mod tests { } } + /// 用量: what a step used comes back from both streams (OpenAI's cached tokens taken out of + /// its input; a cost when the provider gives one), and only the services known to take it + /// are asked for it. + #[test] + fn usage_comes_back_from_both_streams() { + use crate::providers::Usage; + let oa = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":120,\"completion_tokens\":7,\"prompt_tokens_details\":{\"cached_tokens\":100},\"cost\":0.0015}}\n\ndata: [DONE]\n\n"; + let f = Fake::start(Format::OpenAi, vec![Reply::Raw(200, oa.into()), Reply::text("x")], None); + let cancel = AtomicBool::new(false); + let out = crate::providers::run_step(&req(ProviderKind::OpenRouter, f.base()), &cancel, &|_| {}).unwrap(); + assert_eq!(out.usage, Usage { input: 20, output: 7, cache_read: 100, cache_write: 0, cost_micros: 1_500 }); + crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|_| {}).unwrap(); + let bodies = f.bodies.lock().unwrap().clone(); + assert_eq!(bodies[0]["stream_options"]["include_usage"], true); + assert!(bodies[1].get("stream_options").is_none(), "an unknown service isn't sent it"); + let an = [ + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":50,\"cache_read_input_tokens\":400,\"cache_creation_input_tokens\":30,\"output_tokens\":1}}}\n\n", + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n", + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":12}}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ] + .concat(); + let f = Fake::start(Format::Anthropic, vec![Reply::Raw(200, an)], None); + let out = crate::providers::run_step(&req(ProviderKind::Anthropic, f.base()), &cancel, &|_| {}).unwrap(); + assert_eq!(out.usage, Usage { input: 50, output: 12, cache_read: 400, cache_write: 30, cost_micros: 0 }); + } + /// An answer with nothing in it (no words, no call) is asked again, in either format. #[test] fn an_empty_answer_is_asked_again() { diff --git a/src/usage.rs b/src/usage.rs new file mode 100644 index 0000000..95db9a2 --- /dev/null +++ b/src/usage.rs @@ -0,0 +1,186 @@ +//! 用量: every model call (a bot's step, its quick model, a summary, a check, a goal's judge…) is +//! written down as one line in `usage/YYYY-MM.jsonl` in the data folder — when, which provider +//! and model, which bot and what for (from the request's session name, e.g. `anybot-bot-12`, +//! `anybot-check-12`), and the tokens it used, with the cost when the provider says it. +//! 「/usage」 sums the last day and the last week, by bot and by model. Like grok-build's +//! `grok usage`. Nothing here guesses prices: a cost shows only when the provider gave one. + +use crate::providers::{ChatRequest, Usage}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::PathBuf; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Entry { + /// When (ms). + pub at: i64, + pub provider: String, + pub model: String, + /// The request's session name: whose call and what for. + #[serde(default)] + pub session: String, + #[serde(flatten)] + pub usage: Usage, +} + +impl Entry { + /// The bot it was for (0: none), and what for: a step, a check, a goal's judge… + pub fn whose(&self) -> (u64, &'static str) { + let s = self.session.as_str(); + for (prefix, what) in [("anybot-bot-", "回合"), ("anybot-check-", "發布前檢查"), ("anybot-goal-", "目標檢查"), ("anybot-btw-", "支線")] { + if let Some(id) = s.strip_prefix(prefix).and_then(|r| r.parse::().ok()) { + return (id, what); + } + } + (0, "其他") + } +} + +fn dir() -> PathBuf { + crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("usage") +} + +fn file_for(at: chrono::DateTime) -> PathBuf { + dir().join(format!("{}.jsonl", at.format("%Y-%m"))) +} + +/// Write down what one model call used (nothing when the provider said nothing). +pub fn note(req: &ChatRequest, u: &Usage) { + if u.is_empty() { + return; + } + let now = chrono::Local::now(); + let e = Entry { at: now.timestamp_millis(), provider: req.kind.label().to_string(), model: req.model.clone(), session: req.session.clone(), usage: *u }; + let _ = std::fs::create_dir_all(dir()); + if let (Ok(mut f), Ok(line)) = (std::fs::OpenOptions::new().create(true).append(true).open(file_for(now)), serde_json::to_string(&e)) { + let _ = writeln!(f, "{line}"); + } +} + +/// What was written down since `since` (ms): this month's file and last month's. +pub fn since(since: i64) -> Vec { + let now = chrono::Local::now(); + let last_month = now.checked_sub_months(chrono::Months::new(1)).unwrap_or(now); + let mut out = vec![]; + for f in [file_for(last_month), file_for(now)] { + for line in std::fs::read_to_string(f).unwrap_or_default().lines() { + if let Ok(e) = serde_json::from_str::(line) { + if e.at >= since { + out.push(e); + } + } + } + } + out +} + +fn k(n: u64) -> String { + match n { + 0..=999 => n.to_string(), + 1_000..=999_999 => format!("{:.1}k", n as f64 / 1_000.0), + _ => format!("{:.2}M", n as f64 / 1_000_000.0), + } +} + +fn line(u: &Usage) -> String { + let mut s = format!("輸入 {}、輸出 {}", k(u.input + u.cache_read + u.cache_write), k(u.output)); + let read = u.input + u.cache_read + u.cache_write; + if u.cache_read > 0 && read > 0 { + s.push_str(&format!("(快取讀了 {}%)", u.cache_read * 100 / read)); + } + if u.cost_micros > 0 { + s.push_str(&format!(",花了 US${:.2}", u.cost_micros as f64 / 1_000_000.0)); + } + s +} + +/// 「/usage」: the last day and the last week, by bot and by model. `name`: a bot's name by id. +pub fn summary(entries: &[Entry], now_ms: i64, name: &dyn Fn(u64) -> Option) -> String { + const DAY: i64 = 86_400_000; + let total = |from: i64| { + let mut u = Usage::default(); + let mut n = 0; + for e in entries.iter().filter(|e| e.at >= from) { + u.add(&e.usage); + n += 1; + } + (u, n) + }; + let (day, nd) = total(now_ms - DAY); + let (week, nw) = total(now_ms - 7 * DAY); + if nw == 0 { + return "最近 7 天還沒有用量紀錄(模型服務有回報用量才記得到)。".into(); + } + let mut s = format!("用量(模型服務回報的 token)\n最近 24 小時:{nd} 次呼叫,{}\n最近 7 天:{nw} 次呼叫,{}", line(&day), line(&week)); + let mut by_bot: BTreeMap = BTreeMap::new(); + let mut by_model: BTreeMap = BTreeMap::new(); + for e in entries.iter().filter(|e| e.at >= now_ms - 7 * DAY) { + let (id, what) = e.whose(); + let who = if id == 0 { what.to_string() } else { format!("{}({what})", name(id).unwrap_or_else(|| format!("Bot {id}"))) }; + by_bot.entry(who).or_default().add(&e.usage); + by_model.entry(format!("{} · {}", e.provider, e.model)).or_default().add(&e.usage); + } + let mut top = |title: &str, m: BTreeMap| { + let mut rows: Vec<(String, Usage)> = m.into_iter().collect(); + rows.sort_by_key(|(_, u)| std::cmp::Reverse(u.input + u.cache_read + u.cache_write + u.output)); + s.push_str(&format!("\n\n{title}(7 天):")); + for (who, u) in rows.iter().take(8) { + s.push_str(&format!("\n- {who}:{}", line(u))); + } + }; + top("依 Bot", by_bot); + top("依模型", by_model); + s +} + +/// 「/usage」 (nothing after it). +pub fn command(text: &str) -> bool { + text.trim() == "/usage" +} + +#[cfg(test)] +mod tests { + use super::*; + + fn e(at: i64, session: &str, model: &str, input: u64, output: u64, cache_read: u64) -> Entry { + Entry { at, provider: "Claude".into(), model: model.into(), session: session.into(), usage: Usage { input, output, cache_read, ..Default::default() } } + } + + #[test] + fn whose_call_it_was_comes_from_the_session() { + assert_eq!(e(0, "anybot-bot-12", "m", 1, 1, 0).whose(), (12, "回合")); + assert_eq!(e(0, "anybot-check-3", "m", 1, 1, 0).whose(), (3, "發布前檢查")); + assert_eq!(e(0, "anybot-goal-7", "m", 1, 1, 0).whose(), (7, "目標檢查")); + assert_eq!(e(0, "", "m", 1, 1, 0).whose(), (0, "其他")); + } + + #[test] + fn the_summary_adds_up_the_day_and_the_week() { + let now = 30 * 86_400_000; + let list = vec![ + e(now - 3_600_000, "anybot-bot-1", "claude-x", 1_000, 200, 9_000), + e(now - 2 * 86_400_000, "anybot-bot-1", "claude-x", 500, 100, 0), + e(now - 3_600_000, "anybot-check-2", "grok-mini", 300, 10, 0), + e(now - 20 * 86_400_000, "anybot-bot-1", "claude-x", 99_999, 1, 0), + ]; + let s = summary(&list, now, &|id| (id == 1).then(|| "進化之神".to_string())); + assert!(s.contains("最近 24 小時:2 次呼叫,輸入 10.3k、輸出 210(快取讀了 87%)"), "{s}"); + assert!(s.contains("最近 7 天:3 次呼叫"), "{s}"); + assert!(s.contains("- 進化之神(回合):輸入 10.5k、輸出 300") && s.contains("- Bot 2(發布前檢查)"), "{s}"); + assert!(s.contains("- Claude · claude-x") && !s.contains("100.0k"), "older than a week is left out: {s}"); + assert!(summary(&[], now, &|_| None).contains("還沒有用量紀錄")); + } + + #[test] + fn a_call_is_written_down_and_read_back() { + let req = ChatRequest { kind: crate::providers::ProviderKind::Anthropic, base_url: String::new(), api_key: String::new(), model: "claude-test".into(), system: String::new(), history: vec![], tools: vec![], session: "anybot-bot-42".into(), effort: String::new() }; + let t0 = chrono::Local::now().timestamp_millis(); + note(&req, &Usage { input: 7, output: 3, cost_micros: 1_500, ..Default::default() }); + note(&req, &Usage::default()); + let got: Vec = since(t0).into_iter().filter(|e| e.model == "claude-test").collect(); + assert_eq!(got.len(), 1, "nothing written for a call that said nothing"); + assert_eq!((got[0].whose(), got[0].usage.cost_micros), ((42, "回合"), 1_500)); + assert!(command(" /usage ") && !command("/usage x") && !command("/usages")); + } +}