AnyBot/src/outputs.rs

114 lines
5.7 KiB
Rust
Raw Normal View History

//! 完整結果: a step's result that is too long for the chat (a command's output, a connector's
//! answer) keeps its start and its end for the model, and the whole of it is kept here, in the
//! data folder's `outputs/`, by an id made from its content. The note in the middle says the id,
//! and the bot reads any part with `read_result`. An older result set aside to make room
//! (agent::folded_text) points here too. Before, the bot was told to do the step again to see the
//! rest — wrong for a step that changes something or answers differently the second time, and
//! the middle of a long log was simply gone. Like grok-build saving big MCP results to a file.
//!
//! Kept LIFE_DAYS days; one result at most KEEP_MAX_BYTES.
use serde_json::{json, Value};
use std::path::PathBuf;
/// The tool the bot reads a kept result with.
pub const TOOL: &str = "read_result";
/// Days a kept result stays.
pub const LIFE_DAYS: u64 = 7;
/// The most of one result kept (a 2 GB log isn't copied whole).
pub const KEEP_MAX_BYTES: usize = 20 * 1024 * 1024;
/// The most `read_result` gives at once.
pub const READ_MAX_CHARS: usize = 20_000;
fn dir() -> PathBuf {
crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("outputs")
}
/// Keep the whole text; its id (the same text always gets the same id: keeping it again is free).
pub fn keep(text: &str) -> String {
let id = format!("r{}", &crate::httpd::sha256_hex(text)[..12]);
let path = dir().join(format!("{id}.txt"));
if !path.exists() {
let _ = std::fs::create_dir_all(dir());
let mut end = text.len().min(KEEP_MAX_BYTES);
while !text.is_char_boundary(end) {
end -= 1;
}
let _ = crate::httpd::write_private(&path, &text.as_bytes()[..end]);
}
id
}
/// What the middle of a shortened result says.
pub fn note(left_out: usize, id: &str) -> String {
format!("…(中間省略 {left_out} 個字;完整內容用 {TOOL} 讀:id={id})…")
}
/// Part of a kept result: from the `from`-th character, at most `chars` of them.
pub fn read(id: &str, from: usize, chars: usize) -> Result<String, String> {
let id = id.trim();
if !id.starts_with('r') || id.len() != 13 || !id[1..].chars().all(|c| c.is_ascii_hexdigit()) {
return Err(format!("id「{id}」不對:用結果裡寫的那個(像 r1a2b3c4d5e6f)。"));
}
let text = std::fs::read_to_string(dir().join(format!("{id}.txt"))).map_err(|_| format!("找不到 {id}:可能超過 {LIFE_DAYS} 天被清掉了,要的話再做一次那一步。"))?;
let total = text.chars().count();
if from >= total {
return Err(format!("{id} 只有 {total} 個字,從第 {from} 個字開始沒有內容了。"));
}
let chars = chars.clamp(1, READ_MAX_CHARS);
let part: String = text.chars().skip(from).take(chars).collect();
let end = from + part.chars().count();
let more = if end < total { format!("(還有 {} 個字:from={end} 接著讀)", total - end) } else { "(到結尾了)".into() };
Ok(format!("[{id}] 第 {from}–{end} 個字,共 {total} 個字{more}\n{part}"))
}
/// Results older than LIFE_DAYS go (at start).
pub fn prune() {
let life = std::time::Duration::from_secs(LIFE_DAYS * 86_400);
for e in std::fs::read_dir(dir()).into_iter().flatten().flatten() {
if e.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > life) {
let _ = std::fs::remove_file(e.path());
}
}
}
pub fn spec() -> Value {
json!({"name": TOOL,
"description": "Read the whole of a long step result that was shortened (its middle left out) or set aside earlier to make room. Give the id the result names (read_result id=…), where to start (a character offset; 0 is the beginning) and how much (at most 20,000 characters at a time). Use it instead of doing a step again just to see the rest.",
"parameters": {"type": "object", "properties": {
"id": {"type": "string", "description": "The id in the shortened result, e.g. r1a2b3c4d5e6f."},
"from": {"type": "integer", "description": "Character offset to start at (default 0)."},
"chars": {"type": "integer", "description": "How many characters (default and at most 20000)."}},
"required": ["id"]}})
}
/// `read_result`'s answer for the bot.
pub fn run(args: &str) -> (String, bool) {
let v: Value = serde_json::from_str(args).unwrap_or(Value::Null);
match read(v["id"].as_str().unwrap_or(""), v["from"].as_u64().unwrap_or(0) as usize, v["chars"].as_u64().unwrap_or(READ_MAX_CHARS as u64) as usize) {
Ok(t) => (t, true),
Err(e) => (e, false),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_kept_result_is_read_back_in_parts() {
let text: String = (0..30_000).map(|i| char::from(b'a' + (i % 26) as u8)).collect::<String>() + "最後一段";
let id = keep(&text);
assert_eq!(keep(&text), id, "the same text, the same id");
let first = read(&id, 0, 100).unwrap();
assert!(first.contains("第 0–100 個字,共 30004 個字") && first.contains("from=100 接著讀"), "{first}");
let last = read(&id, 29_990, 50).unwrap();
assert!(last.ends_with("最後一段") && last.contains("到結尾了"), "{last}");
assert!(read(&id, 40_000, 10).unwrap_err().contains("只有 30004 個字"));
assert!(read("../../etc/passwd", 0, 10).is_err() && read("rzzzzzzzzzzzz", 0, 10).is_err());
assert!(read("r000000000000", 0, 10).unwrap_err().contains("找不到"));
let (out, ok) = run(&json!({"id": id, "from": 26}).to_string());
assert!(ok && out.contains("\nabcd"), "{out}");
}
}