AnyBot/src/memory.rs

1331 lines
74 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 記憶、技能、範本 (the original: user bot memories, agent skills and template skills/bots).
// - Memories belong to a bot: facts it was asked to keep across chats.
// - Skills are shared, named procedures; the bot sees their names and loads one when it needs it.
// - Templates start a new bot with a ready role and instructions.
use serde::{Deserialize, Serialize};
/// Most memories a bot keeps; the oldest go first (estimated).
pub const MAX_MEMORIES: usize = 200;
/// 關於你: the memory store's shelf for what every bot knows about the person (no bot has id 0).
pub const ABOUT_YOU: u64 = 0;
/// The most of 關於你 a bot's instructions carry (the newest; the rest is found by search_memory).
pub const ABOUT_YOU_IN_PROMPT: usize = 40;
/// Longest memory (estimated).
pub const MAX_MEMORY_CHARS: usize = 500;
fn skill_enabled_default() -> bool {
true
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Skill {
pub name: String,
pub description: String,
pub instructions: String,
/// The steps that worked, to do again as they were (replay_skill): no model in between,
/// each control found again by what it is, the first mismatch hands back to the bot.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub steps: Vec<ReplayStep>,
/// Whether bots see and load this skill (on by default).
#[serde(default = "skill_enabled_default")]
pub enabled: bool,
/// Local package folder (`<data>/skills/<slug>`) when backed by a folder skill.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub dir: String,
/// Bundled relative files inside `dir` (`scripts/...`, `references/...`, `assets/...`).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<String>,
/// Origin label (`builtin:<slug>`, `owner/repo/...`, `"learned"`, …).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub source: String,
}
impl Default for Skill {
fn default() -> Self {
Self {
name: String::new(),
description: String::new(),
instructions: String::new(),
steps: vec![],
enabled: true,
dir: String::new(),
resources: vec![],
source: String::new(),
}
}
}
/// One step of a skill to do again: the tool and its arguments, and for a step that acted on a
/// numbered control, what that control was (「按鈕「Close」」), since numbers change from look to
/// look. `targets` has one entry per action of a computer_use_batch ("" where none).
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct ReplayStep {
pub tool: String,
pub args: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub targets: Vec<String>,
}
pub struct Template {
pub name: &'static str,
pub description: &'static str,
pub instructions: &'static str,
pub shape: &'static str,
pub color: &'static str,
}
pub const TEMPLATES: [Template; 5] = [
Template { name: "研究助理", description: "上網找資料、整理重點、附上來源", instructions: "先釐清問題,再用 web_fetch 或瀏覽器找至少兩個可靠來源。回答先給結論,再列重點,每個重點附來源網址。不確定的地方直接說不確定。", shape: "circle", color: "green" },
Template { name: "寫作夥伴", description: "幫你構思、改寫和潤稿", instructions: "先問清楚讀者和語氣。改稿時保留作者的意思,列出改了什麼和為什麼。用繁體中文、台灣用語。", shape: "cloud", color: "purple" },
Template { name: "電腦助手", description: "在自己的電腦上跑指令、整理檔案、操作網頁", instructions: "預設在你自己的電腦上做事。動手前先看清楚(list_dir、read_file、截圖),每一步確認結果。要動到使用者的 Mac 時先說明要做什麼。", shape: "gem", color: "blue" },
Template { name: "客服助理", description: "在 Slack、Discord、Telegram 或 Teams 回覆客人", instructions: "回答簡短、有禮貌。不確定的事不要編,說會請同事確認。不要透露內部資料或使用者的私人資訊。", shape: "pill", color: "orange" },
Template { name: "開發助手", description: "看程式、跑測試、追 GitHub 上的事", instructions: "改程式前先讀相關檔案和測試。每次修改後跑測試,回報結果。PR 或 CI 的事件來時,先看紀錄再下結論。", shape: "hexagon", color: "black" },
];
/// ---- Skill files (P7): a skill you can keep in a file, share, and install ----
///
/// A `.md` file in `<data>/skills/`: front matter (`name:`, `description:`), the instructions
/// as the body, and an optional ```steps fence (the ReplayStep list a replay follows).
pub fn skill_dir() -> std::path::PathBuf {
// Tests never touch the person's data folder.
if cfg!(test) {
return crate::oplog::dir().join("skills");
}
crate::model::State::path().parent().map(|p| p.join("skills")).unwrap_or_else(old_skill_dir)
}
/// Where skill files were kept before (inside the work log's folder, which no document
/// mentioned): still read, so a skill installed then is not lost.
fn old_skill_dir() -> std::path::PathBuf {
crate::oplog::dir().join("skills")
}
fn skill_dirs() -> Vec<std::path::PathBuf> {
let (old, new) = (old_skill_dir(), skill_dir());
if old == new { vec![new] } else { vec![old, new] }
}
#[cfg(test)]
pub fn skill_to_file(s: &Skill) -> String {
crate::skills::render_skill_markdown(s)
}
pub fn parse_skill_file(text: &str) -> Option<Skill> {
crate::skills::parse_skill_markdown(text)
}
/// Save one skill package (`<data>/skills/<slug>/SKILL.md`; validated first). Returns the skill's name.
pub fn install_skill_text(text: &str) -> Result<String, String> {
let s = parse_skill_file(text).ok_or("這不是一張技能檔(開頭要有 name:)")?;
crate::skills::write_skill_package(&s, &[])?;
Ok(s.name)
}
/// Every skill package or legacy `.md` file with the skill in it (the old folder first: the
/// same name in `skill_dir` is the newer one and wins the merge).
fn skill_files() -> Vec<(std::path::PathBuf, Skill)> {
let mut out = vec![];
for dir in skill_dirs() {
out.extend(crate::skills::load_skills_in_dir(&dir));
}
out
}
pub fn load_skill_files() -> Vec<Skill> {
skill_files().into_iter().map(|(_, s)| s).collect()
}
/// Take a deleted skill's folder package or `.md` files off the shelf, whatever they are called
/// (a file left there brought the skill back at the next start). Returns how many went.
pub fn remove_skill_files(name: &str) -> usize {
let name = name.trim();
let mut removed = 0;
for (p, s) in skill_files() {
if s.name == name {
let ok = if p.is_dir() { std::fs::remove_dir_all(&p).is_ok() } else { std::fs::remove_file(&p).is_ok() };
if ok {
removed += 1;
}
}
}
let slug = crate::skills::slug_of(name);
if slug != "skill" || name.eq_ignore_ascii_case("skill") {
let slug_dir = skill_dir().join(slug);
if slug_dir.is_dir() && std::fs::remove_dir_all(&slug_dir).is_ok() {
removed += 1;
}
}
removed
}
/// Files win for instructions/resources, while preserving the person's enabled/disabled switch
/// and source tag from `state.json`.
pub fn merge_skill_files(skills: &mut Vec<Skill>) -> usize {
let mut n = 0;
for mut f in load_skill_files() {
match skills.iter_mut().find(|s| s.name == f.name) {
Some(old) => {
f.enabled = old.enabled;
if f.source.is_empty() && !old.source.is_empty() {
f.source = old.source.clone();
}
*old = f;
}
None => skills.push(f),
}
n += 1;
}
n
}
/// C8: 示範即教學 — turn the most recent finished turn that answered `prompt` into a skill,
/// keeping the steps that worked and threw nothing away. Looking steps (screenshots, reads) are
/// dropped: a replay looks for itself. Steps that point at a number on the screen (ref) are
/// dropped too — numbers only live as long as the look that made them.
pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option<Skill> {
let key: String = prompt.chars().take(40).collect();
let mut op = String::new();
for r in recs.iter().rev() {
if let crate::oplog::Record::OperationStarted { op: o, prompt: Some(p), .. } = r {
if p.text.chars().take(40).collect::<String>() == key {
op = o.clone();
break;
}
}
}
if op.is_empty() {
return None;
}
let mut done: Vec<(String, bool)> = vec![]; // index-parallel with steps: (call_id, finished ok)
let mut steps: Vec<(String, String)> = vec![];
for r in recs {
match r {
crate::oplog::Record::ToolStarted { op: o, call_id, name, args, .. } if o == &op => {
let a: serde_json::Value = serde_json::from_str(args).unwrap_or_default();
let looks = matches!(
name.as_str(),
"computer_use_screenshot" | "computer_use_zoom" | "computer_use_look" | "browser_screenshot" | "browser_read" | "browser_elements"
) || (name == "computer" && matches!(a["action"].as_str().unwrap_or(""), "screenshot" | "zoom" | "look" | "scroll" | "move"));
let numbered = a["ref"].is_number() || !a["actions"].is_null();
if !looks && !numbered {
steps.push((name.clone(), args.clone()));
done.push((call_id.clone(), true));
}
}
crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == &op => {
if status != "done" {
if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) {
e.1 = false;
}
}
}
_ => {}
}
}
let kept: Vec<ReplayStep> = steps
.into_iter()
.enumerate()
.filter(|(i, _)| done.get(*i).is_some_and(|(_, ok)| *ok))
.map(|(_, (tool, args))| ReplayStep { tool, args, targets: vec![] })
.take(24)
.collect();
if kept.is_empty() {
return None;
}
let name: String = prompt.chars().take(24).collect();
Some(Skill {
name,
description: format!("示範學會:{prompt}"),
instructions: format!("照著做過一次的那條路做完这件事:{prompt}"),
steps: kept,
source: "learned".into(),
..Default::default()
})
}
/// Add a memory (no duplicates; the oldest drop off past the limit).
pub fn remember(list: &mut Vec<String>, fact: &str) -> Result<String, String> {
let f: String = fact.trim().chars().take(MAX_MEMORY_CHARS).collect();
if f.is_empty() {
return Err("要記住什麼?".into());
}
if list.iter().any(|m| m == &f) {
return Ok(format!("已經記得:{f}"));
}
list.push(f.clone());
let n = list.len();
if n > MAX_MEMORIES {
list.drain(..n - MAX_MEMORIES);
}
Ok(format!("記住了:{f}"))
}
/// Forget by the memory's own words, by its number in the whole list (1-based: the list in
/// the settings, never the few lines a prompt carries), or by text it contains.
pub fn forget(list: &mut Vec<String>, what: &str) -> Result<String, String> {
let w = what.trim();
let idx = list.iter().position(|m| !w.is_empty() && m == w).or_else(|| match w.parse::<usize>() {
Ok(n) if n >= 1 && n <= list.len() => Some(n - 1),
_ => list.iter().position(|m| !w.is_empty() && m.contains(w)),
});
match idx {
Some(i) => Ok(format!("忘記了:{}", list.remove(i))),
None => Err(format!("沒有記得「{w}」這件事")),
}
}
/// Add a skill, or replace the one with the same name. True when it is new.
pub fn upsert_skill(list: &mut Vec<Skill>, k: Skill) -> bool {
match list.iter_mut().find(|x| x.name == k.name) {
Some(x) => {
*x = k;
false
}
None => {
list.push(k);
true
}
}
}
// ---------- 自己進化: a job's way that worked becomes a skill ----------
// The bot forgot everything between chats: a post with a picture on Threads took it 39 steps,
// and the next one would have taken as many. After a longer job the model looks back at the
// steps and writes down the short path that worked (or improves the skill it followed); the
// next time it reads that first.
/// Steps on computers and pages a job needs before it is worth looking back on (estimated).
pub const LEARN_MIN_STEPS: usize = 5;
/// Longest learned skill (estimated; a skill is read whole before each such job).
const MAX_SKILL_CHARS: usize = 4000;
/// A turn that did enough real work, and didn't already save a skill itself.
pub fn worth_learning(turn: &[crate::model::Message]) -> bool {
let calls: Vec<&str> = turn.iter().flat_map(|m| m.tool_calls.iter().map(|c| c.name.as_str())).collect();
!calls.contains(&"save_skill") && calls.iter().filter(|n| !crate::appctl::is_app_tool(n) && **n != "react").count() >= LEARN_MIN_STEPS
}
pub const LEARN_SYSTEM: &str = "你在幫一個會操作電腦的 Bot 整理經驗,讓它下次做同樣的事更快、不再犯同樣的錯。下面是它剛做完的一件事:使用者的要求、每一步和結果、最後的回覆,還有它已經有的技能。
先判斷要不要存。使用者希望它從做過的事學會、下次不用重新摸索:只要這件事是在某個網站或程式上動手操作(填表、發文、回留言、按讚、上傳下載、改設定、跑一套固定的檢查),就要存,就算這次只做了一次。只有閒聊、單純回答問題、只是查資料讀內容,才不用存。這次沒做成功的,不要存成做法;但如果已經有這件事的技能,可以把「這樣做行不通」補進去。
要存的話,寫一份「下次照著做就會成功」的技能:
- 寫這次真的成功的那條最短路徑,一步一行,寫出用哪個工具、在哪台電腦、哪個網址或程式(每一步結果開頭 [ ] 裡的名字,就是那一步用的電腦)。
- 繞路和失敗的嘗試不要寫成步驟;把「哪裡會卡、要怎麼避開」寫成「注意:」。
- 用畫面上看得到的名字指東西(例如 browser_click 的 text 寫「Attach media」、browser_type 的 text 寫欄位名「Customer name」),不要寫元素編號或座標,那些每次都會變。browser_open 的結果就有這一頁的元素清單,不用另外截圖。
- 寫通用的做法,不要寫這次的內容(這篇文的文字、這張圖的檔名);使用者表達過的偏好(語氣、格式、一定要附圖、用哪台電腦)要寫進去。
- 已經有做同一件事的技能,就用同一個名稱,把舊的和這次學到的合併成更好的一版:舊的對的保留,錯的改掉。這次照著技能做而且很順,就不用再存。
同一個網站的操作知識(有什麼功能、使用者怎麼點到、用哪個工具怎麼操作、陷阱)放在「<網站名> 網站地圖」這份技能,固定四段:## 功能、## 怎麼到、## 怎麼操作、## 陷阱;做事的技能只寫這件事特有的部分(帳號、篩選規則、語氣、數量),開頭寫「先 use_skill 讀「<網站名> 網站地圖」」。這次學到的是網站本身的事、而且已經有這個網站的地圖,就用地圖的名稱存,把新的陷阱合併進地圖,不要抄進做事的技能。
AnyBot 自己的問題另外寫,不要寫進技能:工具回錯的結果、工具明明開著卻說找不到、某個工具一用就出錯、要繞路才做得到(例如只能用剪貼簿貼上多行字)、Bot 一直誤用某個工具——這些寫進 tool_issues,一句一件,寫出哪個工具、發生什麼事;技能裡不要寫「絕對不要用某工具」「某工具壞了」這種句子,那是 AnyBot 要修的。網站本身的規矩和陷阱(要先等頁面載入、某按鈕找不到要換一個字找)才寫進技能的「注意:」。只發生一次、下次不太會再遇到的小失誤,兩邊都不用寫。
只回一個 JSON,不要別的字:
不用存:{\"save\": false, \"why\": \"一句話說為什麼\", \"tool_issues\": []}
要存:{\"save\": true, \"name\": \"短名稱\", \"description\": \"一行:什麼時候用\", \"instructions\": \"做法\", \"replay\": [步驟編號], \"tool_issues\": []}
replay:下次做同一件事時可以原樣照做的步驟編號(上面清單的號碼,照順序)。只列這次真的成功、必要、會改變東西的步驟(不含截圖、讀取這類只是看的步驟,不含失敗或繞路的步驟);內容每次會不一樣的工作(發文的文字、要回覆的留言、檔名)不要列,給空陣列 []。";
fn cut(s: &str, n: usize) -> String {
let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= n { flat } else { format!("{}…", flat.chars().take(n).collect::<String>()) }
}
/// What the model looks back on: the request, each step with its result, the answer and the
/// skills there are.
/// The numbered steps the model looks back on, each with the call it was (None for words the
/// person typed in between, and for the "…省略…" line).
fn brief_steps(turn: &[crate::model::Message]) -> Vec<(String, Option<crate::model::ToolCall>)> {
use crate::model::Role;
let mut steps: Vec<(String, Option<crate::model::ToolCall>)> = vec![];
for (i, m) in turn.iter().enumerate() {
if m.role == Role::User && i > 0 {
steps.push((format!("(使用者中途說:{})", cut(&m.text, 300)), None));
}
for c in &m.tool_calls {
let result = turn.iter().find(|r| r.role == Role::Tool && r.tool_call_id == c.id).map(|r| r.text.as_str()).unwrap_or("");
let failed = if c.status == crate::model::ToolStatus::Failed { "(失敗)" } else { "" };
steps.push((format!("{} {} → {}{failed}", c.name, cut(&c.args, 160), cut(result, 220)), Some(c.clone())));
}
}
const KEEP: usize = 40;
if steps.len() > KEEP * 2 {
let gone = steps.len() - KEEP * 2;
steps.splice(KEEP..steps.len() - KEEP, [(format!("…(中間省略 {gone} 步)…"), None)]);
}
steps
}
pub fn learn_brief(turn: &[crate::model::Message], skills: &[Skill]) -> String {
let steps: Vec<String> = brief_steps(turn).into_iter().map(|(s, _)| s).collect();
let ask = turn.first().map(|m| cut(&m.text, 800)).unwrap_or_default();
let answer = turn.iter().rev().find(|m| m.role == crate::model::Role::Assistant && !m.text.trim().is_empty()).map(|m| cut(&m.text, 600)).unwrap_or_default();
let mut s = format!("使用者的要求:\n{ask}\n\n每一步(工具 參數 → 結果):\n");
for (i, st) in steps.iter().enumerate() {
s.push_str(&format!("{}. {st}\n", i + 1));
}
s.push_str(&format!("\n最後的回覆:\n{answer}\n\n已經有的技能:"));
if skills.is_empty() {
s.push_str("(沒有)");
}
let mut room = 8000usize;
for k in skills {
let body = cut(&k.instructions, 2000.min(room));
room = room.saturating_sub(body.chars().count());
s.push_str(&format!("\n- {}:{}\n 做法:{body}", k.name, k.description));
}
s
}
/// The skill in the model's answer, when it chose to save one.
/// AnyBot's own problems the look back found (tool_issues): kept for whoever fixes AnyBot, never
/// in a skill — the Threads skills had grown "never use browser_fill_contact" rules that the
/// system, not the bot, had to fix (encode lessons in structure).
pub fn learned_issues(text: &str) -> Vec<String> {
let t = text.trim();
let Some(json) = t.find('{').and_then(|a| t.rfind('}').filter(|b| *b >= a).map(|b| &t[a..=b])) else { return vec![] };
let v: serde_json::Value = serde_json::from_str(json).unwrap_or_default();
v["tool_issues"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).map(|s| s.trim().chars().take(ISSUE_CHARS).collect::<String>()).filter(|s| !s.is_empty()).take(MAX_ISSUES_PER_TURN).collect()).unwrap_or_default()
}
/// Longest tool issue kept, and how many one turn may report.
const ISSUE_CHARS: usize = 200;
const MAX_ISSUES_PER_TURN: usize = 5;
pub fn learned_skill(text: &str) -> Option<Skill> {
let t = text.trim();
let json = t.find('{').and_then(|a| t.rfind('}').filter(|b| *b >= a).map(|b| &t[a..=b]))?;
let v: serde_json::Value = serde_json::from_str(json).ok()?;
if v["save"].as_bool() != Some(true) {
return None;
}
let name: String = v["name"].as_str()?.trim().chars().take(40).collect();
let instructions: String = v["instructions"].as_str()?.trim().chars().take(MAX_SKILL_CHARS).collect();
if name.is_empty() || instructions.is_empty() {
return None;
}
Some(Skill {
name,
description: v["description"].as_str().unwrap_or("").trim().chars().take(120).collect(),
instructions,
source: "learned".into(),
..Default::default()
})
}
/// The step numbers the model picked to do again as they were (its "replay").
pub fn learned_replay(text: &str) -> Vec<usize> {
let t = text.trim();
let Some(json) = t.find('{').and_then(|a| t.rfind('}').filter(|b| *b >= a).map(|b| &t[a..=b])) else { return vec![] };
let v: serde_json::Value = serde_json::from_str(json).unwrap_or_default();
v["replay"].as_array().map(|a| a.iter().filter_map(|n| n.as_u64().map(|n| n as usize)).collect()).unwrap_or_default()
}
/// The control a numbered step acted on, in words, from the newest list before it in the turn
/// ("[12] 按鈕「Close」" → 按鈕「Close」).
fn control_named(turn: &[crate::model::Message], before_call: &str, r: &str) -> String {
use crate::model::Role;
let n = r.trim().trim_matches(['[', ']', '#', 'e']);
if n.is_empty() {
return String::new();
}
let upto = turn.iter().position(|m| m.tool_calls.iter().any(|c| c.id == before_call)).unwrap_or(turn.len());
let prefix = format!("[{n}] ");
turn[..upto].iter().rev().filter(|m| m.role == Role::Tool).find_map(|m| m.text.lines().find_map(|l| l.trim_start().strip_prefix(&prefix).map(|d| d.trim().to_string()))).unwrap_or_default()
}
/// The skill's steps from the model's picks: each step's call, with the controls it acted on by
/// number written down as what they were. Steps that only look are left out whatever was picked.
pub fn replay_steps(turn: &[crate::model::Message], picks: &[usize]) -> Vec<ReplayStep> {
let steps = brief_steps(turn);
let mut out = vec![];
for &k in picks {
let Some((_, Some(c))) = k.checked_sub(1).and_then(|i| steps.get(i)) else { continue };
if c.status == crate::model::ToolStatus::Failed || matches!(c.name.as_str(), "computer_use_screenshot" | "computer_use_zoom" | "browser_read" | "browser_screenshot" | "browser_elements" | "use_skill" | "replay_skill") {
continue;
}
let v: serde_json::Value = serde_json::from_str(&c.args).unwrap_or_default();
let targets: Vec<String> = if c.name == "computer_use_batch" {
v["actions"].as_array().map(|a| a.iter().map(|x| x["ref"].as_str().map(|r| control_named(turn, &c.id, r)).unwrap_or_default()).collect()).unwrap_or_default()
} else {
match v["ref"].as_str().map(String::from).or_else(|| v["ref"].as_u64().map(|n| n.to_string())) {
Some(r) => vec![control_named(turn, &c.id, &r)],
None => vec![],
}
};
// A numbered step whose control can't be named can't be found again: not a step to replay.
if targets.iter().zip(v["actions"].as_array().map(|a| a.iter().map(|x| !x["ref"].is_null()).collect::<Vec<_>>()).unwrap_or_else(|| vec![!v["ref"].is_null()])).any(|(t, had)| had && t.is_empty()) {
return vec![];
}
out.push(ReplayStep { tool: c.name.clone(), args: c.args.clone(), targets: if targets.iter().all(String::is_empty) { vec![] } else { targets } });
}
out
}
/// The line under the bot's reply that says it learned (or improved) a skill.
pub fn learned_note(name: &str, fresh: bool) -> String {
if fresh {
format!("\n\n(學會了新做法「{name}」,下次做這件事會照著做。)")
} else {
format!("\n\n(把做法「{name}」更新了,下次會照新的做。)")
}
}
// ---------- 記憶: what rides along with a message ----------
//
// Little by default. The person's pinned memories (核心記憶) are in every chat's instructions;
// anything else rides on the message it answers — the ones the person picked in the composer,
// or, when nobody picked (a routine, a channel, a quick send), at most AUTO_MAX that clearly
// answer it. The bot looks further itself with search_memory. What a message carried is kept on
// it (Message::memories), shown under it, and sent the same way every turn after.
/// Shown as a suggestion under the composer.
pub const SHOW_SCORE: f32 = 0.15;
/// Ticked in advance.
pub const PICK_SCORE: f32 = 0.5;
/// Carried when nobody picked.
pub const AUTO_SCORE: f32 = 0.55;
pub const AUTO_MAX: usize = 3;
/// Suggestions under the composer, at most.
pub const SUGGEST_MAX: usize = 8;
/// The memories `text` may want, best first (pinned ones aren't offered: they always ride).
pub fn suggest(bot: u64, text: &str) -> Vec<crate::memstore::Hit> {
crate::memstore::search(bot, text, &["fact", "event", "rollup"], 24).into_iter().filter(|h| h.score >= SHOW_SCORE && !h.m.pinned).take(SUGGEST_MAX).collect()
}
/// The suggestions as the composers (desktop and phone) read them.
pub fn suggest_json(bot: u64, text: &str) -> serde_json::Value {
let t = std::time::Instant::now();
let hits = suggest(bot, text);
let items: Vec<serde_json::Value> = hits
.iter()
.map(|h| {
let mut v = h.m.json();
v["score"] = serde_json::json!((h.score as f64 * 100.0).round() / 100.0);
v["pick"] = serde_json::json!(h.score >= PICK_SCORE);
v["tokens"] = serde_json::json!(crate::agent::estimate_tokens(&h.m.text) + 2);
v
})
.collect();
serde_json::json!({"hits": items, "ms": (t.elapsed().as_secs_f64() * 10000.0).round() / 10.0})
}
/// Old name: the memories that answer a request, as text (best first, worth showing).
#[cfg(test)]
pub fn recall(bot: u64, query: &str, list: &[String], limit: usize) -> Vec<String> {
crate::store::memory_index(bot, list);
crate::store::recall(bot, query, limit)
}
/// What the newest message carries, decided once at the start of its turn: the person's picks
/// (`picked`), or the few that clearly answer it. Never a pinned one (already in the
/// instructions) nor one an earlier message in view carried (`already`): the model still has
/// it. Each one carried counts as used.
pub fn carry(bot: u64, text: &str, picked: Option<&[String]>, already: &std::collections::HashSet<String>) -> Vec<String> {
let pinned: std::collections::HashSet<String> = crate::memstore::pinned(bot).into_iter().map(|m| m.text).collect();
let keep = |t: &str| !t.trim().is_empty() && !already.contains(t) && !pinned.contains(t);
let mut out: Vec<String> = vec![];
let mut ids: Vec<i64> = vec![];
match picked {
Some(p) => {
for t in p {
// Only what this bot really remembers: a pick is a memory's words, not free text.
if keep(t) && !out.contains(t) {
if let Some(m) = crate::memstore::find(bot, t).filter(|m| m.deleted == 0) {
out.push(t.clone());
ids.push(m.id);
}
}
}
}
None => {
for h in suggest(bot, text).into_iter().filter(|h| h.score >= AUTO_SCORE) {
if out.len() >= AUTO_MAX {
break;
}
if keep(&h.m.text) && !out.contains(&h.m.text) {
ids.push(h.m.id);
out.push(h.m.text);
}
}
}
}
crate::memstore::used(&ids);
out
}
/// What the model reads after a person's message, the same every time it is sent: when it was
/// sent (in the person's zone) and the memories it carried.
pub fn context_of(m: &crate::model::Message, timezone: &str) -> String {
use chrono::{Datelike, TimeZone};
let mut s = String::new();
if m.at > 0 {
if let Some(t) = crate::routines::tz_of(timezone).timestamp_millis_opt(m.at).single() {
let wd = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"][t.weekday().num_days_from_monday() as usize];
s.push_str(&format!("〔送出時間:{}({wd}){}〕", t.format("%Y-%m-%d"), t.format("%H:%M")));
}
}
if !m.memories.is_empty() {
if !s.is_empty() {
s.push('\n');
}
s.push_str("〔相關記憶(AnyBot 依這則訊息找出來的,不一定都用得上):");
for x in &m.memories {
s.push_str(&format!("\n- {x}"));
}
s.push('〕');
}
s
}
/// For an answer made long after its message was sent: what time it is now.
pub fn now_line(now: i64, timezone: &str) -> String {
use chrono::{Datelike, TimeZone};
match crate::routines::tz_of(timezone).timestamp_millis_opt(now).single() {
Some(t) => {
let wd = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"][t.weekday().num_days_from_monday() as usize];
format!("〔現在時間:{}({wd}){}〕", t.format("%Y-%m-%d"), t.format("%H:%M"))
}
None => String::new(),
}
}
/// The instructions' part about memory: the pinned ones (they never change between messages,
/// so the model's cache holds), and how the rest arrives.
pub fn prompt_section(pinned: &[String], about_you: &[String], skills: &[Skill]) -> String {
let mut s = String::new();
// 關於你: every bot carries the same lines, in the order kept (the cache holds).
if !about_you.is_empty() {
let from = about_you.len().saturating_sub(ABOUT_YOU_IN_PROMPT);
s.push_str("\n\n關於使用者(所有 Bot 共用的「關於你」,哪個 Bot 記下的都算):\n");
for m in &about_you[from..] {
s.push_str(&format!("- {m}\n"));
}
if from > 0 {
s.push_str(&format!("(還有 {from} 條比較舊的,用 search_memory 找)\n"));
}
}
if !pinned.is_empty() {
// No numbers: forget takes a memory's words.
s.push_str("\n\n你一直記得的事(使用者釘選的核心記憶):\n");
for m in pinned {
s.push_str(&format!("- {m}\n"));
}
}
s.push_str("\n\n記憶:使用者訊息後面的〔送出時間:…〕是那則訊息送出的時間(後面另有〔現在時間:…〕時,現在以它為準),〔相關記憶:…〕是 AnyBot 替那則訊息找出來(或使用者自己勾選)的舊記憶,不是使用者打的字。要更多過去的事(偏好、上次怎麼做、說過的決定、做過的事)就用 search_memory 查,查不到再問。\n像人一樣記:重要的記,小事不記。你自己判斷,不用等使用者說「記住」,也不要問「要我記下來嗎」。要記的是使用者教你的和告訴你的、之後還用得到的事:他教你怎麼操作或怎麼做一件事(步驟多的用 save_skill 存成技能,一句話講得完的規則用 remember)、他告訴你的事(偏好和習慣、關於他和身邊的人的事實、說定的做法和決定)、他糾正你的地方。不確定重不重要就不要記;閒聊、隨口問的問題、只有這次用得到的、一次性的要求、你做了什麼(AnyBot 會自己記成做過的事)、從記憶裡讀到的、你猜的,都不要記。一句寫一件事,寫成以後單獨看也懂的句子。記了就在回答最後帶一句「(記下了:…)」,不要另外解釋。和舊的那條講同一件事但內容變了(搬家、改喜好、更正),把舊的那條放在 replaces 取代它;remember 說已經有很像的一條時,照它給的三種情況自己選,不要問使用者。使用者說「忘記…」時用 forget。\n關於使用者本人、每個 Bot 都該知道的事(他的名字、家人、住哪、工作、喜歡怎麼被回答、長期的偏好和習慣),remember 時把 about_person 設成 true,記在共用的「關於你」,其他 Bot 也會知道,不用各記一次;只跟你自己的工作有關的(某個網站怎麼操作、你負責的事的做法)照舊記你自己的。");
let active: Vec<&Skill> = skills.iter().filter(|k| k.enabled).collect();
if !active.is_empty() {
s.push_str("\n\n你會的技能(專業工具指南與以前做成功的做法)。開始做一件事之前先看這裡:只要任務符合某個技能的描述,務必先呼叫 use_skill 讀出完整做法再動手,不要憑空摸索:\n");
for k in &active {
let mut tags = vec![];
if !k.resources.is_empty() {
tags.push(format!("含 {} 個隨附腳本/參考檔", k.resources.len()));
}
if !k.steps.is_empty() {
tags.push(format!("可重播,{} 步", k.steps.len()));
}
let extra = if tags.is_empty() { String::new() } else { format!("({})", tags.join(";")) };
s.push_str(&format!("- {}:{}{extra}\n", k.name, k.description));
}
if active.iter().any(|k| !k.steps.is_empty()) {
s.push_str("標著「可重播」的技能:要做的事和技能一模一樣(同一個網站或程式、同樣的設定,沒有每次不同的內容)時,直接用 replay_skill,AnyBot 會照存下的步驟一步一步做,每一步先在畫面上找到同一個東西,對不上就停下來交給你;有一點不同就照做法自己做。\n");
}
}
s.push_str("\n使用者教你一套可以重複用的做法、或請你建立新技能時,可以用 save_skill 存成技能(可附帶 scripts/ 或 references/ 檔案)。存好的技能算你的;別的 Bot 要用,可以用 teach_skill 教它,或請使用者在它的設定裡勾選。");
s
}
/// 「/名稱 …」 at the start of a message: the skill the person named (picked from the / list
/// under the composer, or typed). Only a skill that is on; the longest name wins, so a name
/// with a space in it is found too.
pub fn named_skill<'a>(text: &str, skills: &'a [Skill]) -> Option<&'a Skill> {
let rest = text.trim_start().strip_prefix('/')?;
skills
.iter()
.filter(|k| k.enabled && !k.name.is_empty())
.filter(|k| rest.strip_prefix(k.name.as_str()).is_some_and(|after| after.chars().next().is_none_or(char::is_whitespace)))
.max_by_key(|k| k.name.len())
}
/// What the model reads after a message that names a skill.
pub fn named_skill_line(k: &Skill) -> String {
format!("〔使用者用 /{0} 指定了技能「{0}」:先用 use_skill 讀出它的完整做法,再照著做這件事〕", k.name)
}
/// The composer's / list for a draft like 「/pp」: the skills that are on, those whose name
/// starts with what is typed first, then names containing it, then descriptions. None once the
/// draft is not a / at its start, or a space ends the name (the person has moved on).
pub fn slash_matches<'a>(draft: &str, skills: &'a [Skill]) -> Option<Vec<&'a Skill>> {
let q = draft.strip_prefix('/')?;
if q.chars().any(char::is_whitespace) {
return None;
}
let q = q.to_lowercase();
let mut hits: Vec<(u8, &Skill)> = skills
.iter()
.filter(|k| k.enabled && !k.name.is_empty())
.filter_map(|k| {
let name = k.name.to_lowercase();
let rank = if name.starts_with(&q) {
0
} else if name.contains(&q) {
1
} else if k.description.to_lowercase().contains(&q) {
2
} else {
return None;
};
Some((rank, k))
})
.collect();
hits.sort_by_key(|(rank, _)| *rank);
Some(hits.into_iter().map(|(_, k)| k).collect())
}
/// Near enough to be the same memory said again (words or meaning).
const SAME_SCORE: f32 = 0.85;
/// Shared words over all words (words and two-character pairs) from which two lines are one.
const SAME_WORDS: f32 = 0.6;
/// The remember tool: a new fact, unless one very like it is there already — then the bot is
/// told which, and updates it by naming it in `replaces` (the old one is superseded: it stays in
/// the trash for a while and is never carried again).
pub fn remember_tool(bot: u64, list: &mut Vec<String>, fact: &str, replaces: &str, separate: bool) -> Result<String, String> {
let f: String = fact.trim().chars().take(MAX_MEMORY_CHARS).collect();
if f.is_empty() {
return Err("要記住什麼?".into());
}
let replaces = replaces.trim();
let old = if replaces.is_empty() {
None
} else {
let alive = |m: &crate::memstore::Mem| m.deleted == 0 && m.kind == "fact";
crate::memstore::find(bot, replaces).filter(alive).or_else(|| crate::memstore::search(bot, replaces, &["fact"], 1).into_iter().find(|h| h.score >= SAME_SCORE).map(|h| h.m))
};
if !replaces.is_empty() && old.is_none() {
return Err(format!("沒有記得「{replaces}」這件事,所以沒有改。要新增的話,不要填 replaces。"));
}
if old.is_none() {
if let Some(m) = crate::memstore::find(bot, &f).filter(|m| m.deleted == 0) {
return Ok(format!("已經記得:{}", m.text));
}
// One that says nearly the same (both ways: a line that only shares its subject with
// the new one is another fact). The bot decides which it is; the person isn't asked.
if !separate {
let same = crate::memstore::search(bot, &f, &["fact"], 6).into_iter().map(|h| h.m).find(|m| alike(&f, m));
if let Some(m) = same {
return Err(format!(
"還沒記:已經有很像的一條「{}」。你自己判斷,不要問使用者:① 其實是同一件事:不用再記。② 新的是更新或更正:再呼叫一次 remember,replaces 設成「{}」。③ 是另一件不同的事,兩條都要留:再呼叫一次 remember,separate 設成 true。",
m.text, m.text
));
}
}
}
let note = remember(list, &f)?;
let id = crate::memstore::add(bot, &f, "fact");
match (old, id) {
(Some(o), Some(id)) => {
crate::memstore::trash(o.id, id);
list.retain(|x| *x != o.text);
Ok(format!("記住了:{f}(取代了「{}」)", o.text))
}
_ => Ok(note),
}
}
/// The new words and a kept memory say nearly the same thing: most of their words are shared
/// (counted both ways), the old line is wholly inside the new one, or the local model says so.
fn alike(new: &str, m: &crate::memstore::Mem) -> bool {
let (shared, old_inside) = crate::memstore::likeness(new, &m.text);
shared >= SAME_WORDS || old_inside >= 0.9 || same_meaning(m, new)
}
/// The local model thinks the two say the same thing (cos ≥ 0.85).
fn same_meaning(m: &crate::memstore::Mem, text: &str) -> bool {
if !crate::embed::enabled() {
return false;
}
match crate::embed::embed(&[m.text.clone(), text.to_string()]) {
Some(v) if v.len() == 2 => crate::embed::cosine(&v[0], &v[1]) >= 0.85,
_ => false,
}
}
/// The forget tool: by the memory's words (or words in it); it goes to the trash, restorable.
pub fn forget_tool(bot: u64, list: &mut Vec<String>, what: &str) -> Result<String, String> {
let w = what.trim();
let text = match forget(list, w) {
Ok(t) => t.trim_start_matches("忘記了:").to_string(),
Err(e) => match crate::memstore::find(bot, w).filter(|m| m.deleted == 0).or_else(|| crate::memstore::search(bot, w, &["fact"], 1).into_iter().find(|h| h.score >= 0.9).map(|h| h.m)) {
Some(m) => m.text,
None => return Err(e),
},
};
if let Some(m) = crate::memstore::find(bot, &text) {
crate::memstore::trash(m.id, 0);
}
Ok(format!("忘記了:{text}(30 天內可以在「記憶 › 最近刪除」還原)"))
}
/// The search_memory tool: memories that answer `query`, with their dates.
pub fn search_tool(bot: u64, query: &str, kind: &str) -> String {
let kinds: &[&str] = match kind {
"fact" => &["fact"],
"event" => &["event", "rollup"],
_ => &["fact", "event", "rollup"],
};
// Its own, and (a bot's search) what every bot knows about the person.
let mut hits: Vec<crate::memstore::Hit> = crate::memstore::search(bot, query, kinds, 12);
if bot != ABOUT_YOU && kinds.contains(&"fact") {
hits.extend(crate::memstore::search(ABOUT_YOU, query, &["fact"], 6));
hits.sort_by(|a, b| b.score.total_cmp(&a.score));
hits.truncate(12);
}
let hits: Vec<crate::memstore::Hit> = hits.into_iter().filter(|h| h.score >= SHOW_SCORE).collect();
if hits.is_empty() {
return format!("記憶裡沒有和「{}」有關的事。", query.trim());
}
let tz = crate::routines::person_tz();
let mut s = format!("和「{}」有關的記憶(相關的在前):\n", query.trim());
for h in &hits {
use chrono::TimeZone;
let day = tz.timestamp_millis_opt(h.m.created).single().map(|t| t.format("%Y-%m-%d").to_string()).unwrap_or_default();
let kind = match h.m.kind.as_str() {
"fact" => "記得的事",
"rollup" => "整理過的做過的事",
_ => "做過的事",
};
let kind = if h.m.bot == ABOUT_YOU && bot != ABOUT_YOU { "關於你(共用)" } else { kind };
s.push_str(&format!("- [{day} · {kind}{}] {}\n", if h.m.pinned { " · 釘選" } else { "" }, h.m.text));
}
s
}
// ---------- the memory page's API (desktop, phone, screens) ----------
fn mem_page_json(p: crate::memstore::Page) -> serde_json::Value {
serde_json::json!({"items": p.items.iter().map(|m| m.json()).collect::<Vec<_>>(), "total": p.total})
}
/// Reads: answered on any thread (the HTTP one: a headless brain's own loop sleeps between
/// rounds, and a person typing shouldn't wait for it). None: not a read.
pub fn api_read(b: &serde_json::Value) -> Option<serde_json::Value> {
if !matches!(b["op"].as_str(), Some("suggest" | "search" | "list" | "stats" | "overview")) {
return None;
}
// (Which shelf is said outright: a call that forgot to say isn't 關於你.)
let Some(bot) = b["bot"].as_u64() else { return Some(serde_json::json!({"error": "沒有說是哪個 Bot 的記憶"})) };
let s = |k: &str| b[k].as_str().unwrap_or("").to_string();
Some(match b["op"].as_str().unwrap_or("") {
"suggest" | "search" => suggest_json(bot, &s("q")),
"list" => {
let t = std::time::Instant::now();
let mut v = mem_page_json(crate::memstore::list(bot, &s("filter"), &s("q"), b["offset"].as_u64().unwrap_or(0) as usize, b["limit"].as_u64().unwrap_or(50).min(200) as usize));
v["ms"] = serde_json::json!((t.elapsed().as_secs_f64() * 10000.0).round() / 10.0);
v
}
"stats" => overview(bot, false),
"overview" => overview(bot, true),
_ => return None,
})
}
/// The page's header: counts, sizes, the engine, and (when asked) what could be cleaned up.
fn overview(bot: u64, with_suggestions: bool) -> serde_json::Value {
let mut v = serde_json::json!({"stats": crate::memstore::stats(bot), "engine": crate::embed::status(), "files": crate::store::sizes().iter().map(|(n, b)| serde_json::json!({"name": n, "bytes": b})).collect::<Vec<_>>()});
if with_suggestions {
v["suggestions"] = crate::memstore::suggestions(bot, crate::model::now_ms());
}
v
}
/// Writes: on the app's thread, with the state, because a fact also lives in the bot's list
/// (state.json, what mirrors sync). Everything changed answers {ok, text} or {error}.
pub fn api_write(state: &mut crate::model::State, b: &serde_json::Value) -> serde_json::Value {
use serde_json::json;
let s = |k: &str| b[k].as_str().unwrap_or("").trim().to_string();
let fail = |e: &str| json!({"error": e});
// (Which shelf is said outright: a call that forgot to say isn't 關於你.)
let Some(bot) = b["bot"].as_u64() else { return fail("沒有說是哪個 Bot 的記憶") };
let list = if bot == ABOUT_YOU {
&mut state.about_you
} else {
match state.bot_mut(bot) {
Some(x) => &mut x.memories,
None => return fail("找不到這個 Bot"),
}
};
let mine = |id: i64| crate::memstore::get(id).filter(|m| m.bot == bot);
let ids = |k: &str| -> Vec<i64> { b[k].as_array().map(|a| a.iter().filter_map(|x| x.as_i64()).collect()).unwrap_or_default() };
match b["op"].as_str().unwrap_or("") {
"add" => match remember(list, &s("text")) {
Ok(t) => {
let id = crate::memstore::add(bot, &s("text"), "fact");
if b["pinned"].as_bool() == Some(true) {
if let Some(id) = id {
crate::memstore::set_pinned(id, true);
}
}
json!({"ok": true, "text": t, "id": id})
}
Err(e) => fail(&e),
},
"pin" => match mine(b["id"].as_i64().unwrap_or(0)) {
Some(m) => {
let on = b["on"].as_bool().unwrap_or(!m.pinned);
crate::memstore::set_pinned(m.id, on);
json!({"ok": true, "text": if on { "釘選了:每次聊天都會帶著" } else { "取消釘選" }})
}
None => fail("找不到這一條"),
},
"edit" => match mine(b["id"].as_i64().unwrap_or(0)) {
Some(m) => match crate::memstore::edit(m.id, &s("text").chars().take(MAX_MEMORY_CHARS).collect::<String>()) {
Ok((old, new)) => {
if m.kind == "fact" {
match list.iter().position(|x| *x == old.text) {
Some(i) if !list.contains(&new.text) => list[i] = new.text.clone(),
Some(i) => {
list.remove(i);
}
None if !list.contains(&new.text) => list.push(new.text.clone()),
None => {}
}
}
json!({"ok": true, "text": if new.id != old.id { "和另一條一樣,合併了" } else { "改好了" }, "id": new.id})
}
Err(e) => fail(&e),
},
None => fail("找不到這一條"),
},
"forget" => {
let mut n = 0;
for id in ids("ids").into_iter().chain(b["id"].as_i64()) {
if let Some(m) = mine(id).filter(|m| m.deleted == 0) {
crate::memstore::trash(m.id, 0);
list.retain(|x| *x != m.text);
n += 1;
}
}
json!({"ok": true, "text": format!("忘記了 {n} 條(30 天內可以在「最近刪除」還原)")})
}
"restore" => match mine(b["id"].as_i64().unwrap_or(0)) {
Some(m) => {
crate::memstore::restore(m.id);
if m.kind == "fact" && !list.contains(&m.text) {
let _ = remember(list, &m.text);
}
json!({"ok": true, "text": "還原了"})
}
None => fail("找不到這一條"),
},
// 合併: keep one (with the words given, if any); the others are superseded by it.
"merge" => {
let Some(keep) = mine(b["keep"].as_i64().unwrap_or(0)) else { return fail("找不到要留下的那條") };
let text = s("text");
let keep = if !text.is_empty() && text != keep.text {
match crate::memstore::edit(keep.id, &text) {
Ok((old, new)) => {
list.retain(|x| *x != old.text);
if new.kind == "fact" && !list.contains(&new.text) {
list.push(new.text.clone());
}
new
}
Err(e) => return fail(&e),
}
} else {
keep
};
let mut n = 0;
for id in ids("drop") {
if let Some(m) = mine(id).filter(|m| m.id != keep.id && m.deleted == 0) {
crate::memstore::trash(m.id, keep.id);
list.retain(|x| *x != m.text);
n += 1;
}
}
json!({"ok": true, "text": format!("合併了 {} 條", n + 1)})
}
"tidy" => {
let r = crate::memstore::tidy(Some(bot), &state.timezone, crate::model::now_ms());
json!({"ok": true, "text": format!("整理好了:{} 條做過的事壓成每週一行,{} 行每週的壓成每月一行", r.events, r.weeks)})
}
"empty_trash" => {
let n = crate::memstore::purge(Some(bot), i64::MAX);
json!({"ok": true, "text": format!("清掉了 {n} 條")})
}
_ => fail("不認得的操作"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn anybots_own_problems_are_reported_apart_from_the_skill() {
let out = r#"{"save": true, "name": "Threads 回覆", "description": "回覆貼文", "instructions": "1. 開貼文", "replay": [], "tool_issues": ["browser_fill_contact 被誤用來打字", " ", "多行字只能用剪貼簿貼上"]}"#;
assert_eq!(learned_issues(out), vec!["browser_fill_contact 被誤用來打字", "多行字只能用剪貼簿貼上"]);
assert!(learned_skill(out).is_some());
assert!(learned_issues(r#"{"save": false, "why": "閒聊"}"#).is_empty());
assert!(learned_issues("不是 JSON").is_empty());
assert!(LEARN_SYSTEM.contains("tool_issues") && LEARN_SYSTEM.contains("不要寫進技能"));
assert!(LEARN_SYSTEM.contains("網站地圖") && LEARN_SYSTEM.contains("## 陷阱"));
}
#[test]
fn the_shelf_is_searched_not_carried_whole() {
let list = vec!["我喜歡靠窗的座位".to_string(), "週五下午不開會".to_string()];
// A bot that has heard of 座位 gets just the line that answers.
let r = recall(4244, "有沒有靠窗的位子", &list, 10);
assert!(r.contains(&list[0]) && !r.contains(&list[1]), "{r:?}");
// Nothing answers: nothing rides along (little by default — no "newest few" anymore).
assert_eq!(recall(5556, "完全不相干的查詢", &[], 10), Vec::<String>::new());
assert!(recall(5557, "寫一首關於海的詩", &list, 10).is_empty());
}
#[test]
fn a_message_carries_little_and_never_twice() {
let bot = 4250;
let mut list = vec![];
for f in ["我喜歡靠窗的座位,長途航班也是", "咖啡不加糖", "週五下午不開會", "我住在台南"] {
remember_tool(bot, &mut list, f, "", false).unwrap();
}
let none = std::collections::HashSet::new();
// Nobody picked: only what clearly answers (≥ AUTO_SCORE), at most AUTO_MAX.
let got = carry(bot, "靠窗的座位", None, &none);
assert!(got.len() <= AUTO_MAX && got.iter().any(|m| m.contains("靠窗")) && !got.iter().any(|m| m.contains("咖啡")), "{got:?}");
// A long request that only touches two memories: offered under the composer, unticked,
// and not carried on its own (little by default).
let s = suggest_json(bot, "幫我訂下週去台南的高鐵票,要靠窗");
let hits = s["hits"].as_array().unwrap();
assert!(hits.iter().any(|h| h["text"].as_str().unwrap().contains("台南")) && hits.iter().any(|h| h["text"].as_str().unwrap().contains("靠窗")), "{s}");
assert!(hits.iter().all(|h| h["pick"] == false && h["score"].as_f64().unwrap() >= SHOW_SCORE as f64), "{s}");
assert!(carry(bot, "幫我訂下週去台南的高鐵票,要靠窗", None, &none).is_empty());
// Already carried by an earlier message in view: not again.
let already: std::collections::HashSet<String> = got.iter().cloned().collect();
assert!(carry(bot, "靠窗的座位", None, &already).is_empty());
// The person's picks are taken as they are (but never what is pinned: it's always there).
let id = crate::memstore::find(bot, "咖啡不加糖").unwrap().id;
crate::memstore::set_pinned(id, true);
let picked = carry(bot, "隨便", Some(&["週五下午不開會".to_string(), "咖啡不加糖".to_string()]), &none);
assert_eq!(picked, vec!["週五下午不開會".to_string()]);
// Carried means used.
assert!(crate::memstore::find(bot, "週五下午不開會").unwrap().uses >= 1);
// Suggestions: scores, and the strong ones ticked.
let s = suggest_json(bot, "有沒有靠窗的位子");
let top = &s["hits"][0];
assert!(top["text"].as_str().unwrap().contains("靠窗") && top["pick"] == true, "{s}");
assert!(s["hits"].as_array().unwrap().iter().all(|h| h["text"] != "咖啡不加糖"), "pinned isn't offered: {s}");
}
#[test]
fn remember_says_when_it_already_knows_and_replaces_on_request() {
let bot = 4251;
let mut list = vec![];
assert!(remember_tool(bot, &mut list, "週五下午不要排會議", "", false).unwrap().starts_with("記住了"));
// Said again in other words: not a second line; the bot is told which one to update.
let e = remember_tool(bot, &mut list, "週五下午不要排會議喔", "", false).unwrap_err();
assert!(e.contains("已經有很像的一條「週五下午不要排會議」") && e.contains("replaces"), "{e}");
assert_eq!(list.len(), 1);
// An update names the old one: the old is superseded (trash, pointing at the new).
let ok = remember_tool(bot, &mut list, "週五下午可以排會議了", "週五下午不要排會議", false).unwrap();
assert!(ok.contains("取代了"), "{ok}");
assert_eq!(list, vec!["週五下午可以排會議了".to_string()]);
let old = crate::memstore::find(bot, "週五下午不要排會議").unwrap();
let new = crate::memstore::find(bot, "週五下午可以排會議了").unwrap();
assert!(old.deleted > 0 && old.superseded_by == new.id);
assert!(carry(bot, "週五下午排個會議", None, &std::collections::HashSet::new()).iter().all(|m| *m != old.text), "superseded never rides");
// Remembered again after being forgotten: it comes back from the trash.
forget_tool(bot, &mut list, "週五下午可以排會議了").unwrap();
assert!(crate::memstore::find(bot, "週五下午可以排會議了").unwrap().deleted > 0);
remember_tool(bot, &mut list, "週五下午可以排會議了", "", false).unwrap();
assert_eq!(crate::memstore::find(bot, "週五下午可以排會議了").unwrap().deleted, 0);
// search_memory answers with dates.
let r = search_tool(bot, "會議", "fact");
assert!(r.contains("週五下午可以排會議了") && r.contains("記得的事") && r.contains("20"), "{r}");
}
#[test]
fn the_page_reads_counts_and_suggestions() {
// (Every read the page makes, once: one of them used to take the database twice and hang.)
let bot = 4252;
crate::memstore::seed_demo(bot, crate::model::now_ms());
let v = api_read(&serde_json::json!({"op": "overview", "bot": bot})).unwrap();
assert!(v["stats"]["facts"].as_i64().unwrap() >= 7 && v["stats"]["pinned"] == 2 && v["stats"]["pinned_tokens"].as_i64().unwrap() > 10, "{v}");
assert_eq!(v["suggestions"]["dupes"].as_array().unwrap().len(), 1, "{v}");
assert!(v["suggestions"]["stale"].as_array().unwrap().iter().any(|m| m["text"].as_str().unwrap().contains("Windows 7")), "{v}");
assert!(v["suggestions"]["old_events"].as_i64().unwrap() >= 5, "{v}");
let l = api_read(&serde_json::json!({"op": "list", "bot": bot, "filter": "pinned"})).unwrap();
assert_eq!(l["total"], 2, "{l}");
let l = api_read(&serde_json::json!({"op": "list", "bot": bot, "filter": "all", "q": "高鐵"})).unwrap();
assert!(l["items"][0]["text"].as_str().unwrap().contains("高鐵"), "{l}");
assert_eq!(api_read(&serde_json::json!({"op": "list", "bot": bot, "filter": "trash"})).unwrap()["total"], 1);
assert!(api_read(&serde_json::json!({"op": "pin"})).is_none(), "a change isn't a read");
}
#[test]
fn a_message_reads_the_same_every_turn() {
let m = crate::model::Message { memories: vec!["我喜歡靠窗".into()], memories_set: true, ..crate::model::Message { at: 1_762_826_400_000, ..crate::model::Message::user("訂票") } };
let a = context_of(&m, "Asia/Taipei");
assert_eq!(a, "〔送出時間:2025-11-11(週二)10:00〕\n〔相關記憶(AnyBot 依這則訊息找出來的,不一定都用得上):\n- 我喜歡靠窗〕");
assert_eq!(context_of(&m, "Asia/Taipei"), a);
}
#[test]
fn the_steps_that_worked_are_kept_with_what_they_acted_on() {
use crate::model::{Message, Role, ToolCall, ToolStatus};
let call = |id: &str, name: &str, args: &str| Message { role: Role::Assistant, tool_calls: vec![ToolCall { id: id.into(), name: name.into(), args: args.into(), status: ToolStatus::Done }], ..Default::default() };
let turn = vec![
Message::user("把自動更新打開"),
call("a", "computer_use_screenshot", "{}"),
Message::tool_result("a", "computer_use_screenshot", "螢幕截圖。\n[3] 按鈕「Close」\n[5] 勾選框「自動更新」:0"),
call("b", "computer_use_click", r#"{"ref":"5"}"#),
Message::tool_result("b", "computer_use_click", "已點 #5(勾選框「自動更新」:0)。"),
call("c", "shell", r#"{"command":"defaults read x"}"#),
Message::tool_result("c", "shell", "1"),
];
let brief = learn_brief(&turn, &[]);
assert!(brief.contains("1. computer_use_screenshot") && brief.contains("2. computer_use_click") && brief.contains("3. shell"), "{brief}");
let steps = replay_steps(&turn, &[1, 2, 3]);
// The look is left out; the click remembers what it clicked.
assert_eq!(steps.len(), 2);
assert_eq!(steps[0].tool, "computer_use_click");
assert_eq!(steps[0].targets, vec!["勾選框「自動更新」:0".to_string()]);
assert!(steps[1].targets.is_empty());
assert_eq!(learned_replay(r#"{"save": true, "name": "x", "instructions": "y", "replay": [2, 3]}"#), vec![2, 3]);
assert!(learned_replay(r#"{"save": true, "name": "x", "instructions": "y"}"#).is_empty());
// A numbered step whose control can't be named: nothing to replay safely.
assert!(replay_steps(&turn[..1].iter().cloned().chain([call("d", "computer_use_click", r#"{"ref":"77"}"#)]).collect::<Vec<_>>(), &[1]).is_empty());
}
#[test]
fn remember_and_forget() {
let mut m = vec![];
assert!(remember(&mut m, "我喜歡靠窗的座位").unwrap().starts_with("記住了"));
assert!(remember(&mut m, "我喜歡靠窗的座位").unwrap().starts_with("已經記得"));
remember(&mut m, "週五不開會").unwrap();
assert_eq!(forget(&mut m, "1").unwrap(), "忘記了:我喜歡靠窗的座位");
assert!(forget(&mut m, "不存在").is_err());
assert_eq!(forget(&mut m, "週五").unwrap(), "忘記了:週五不開會");
for i in 0..(MAX_MEMORIES + 5) {
remember(&mut m, &format!("事 {i}")).unwrap();
}
assert_eq!(m.len(), MAX_MEMORIES);
assert_eq!(m[0], "事 5");
let p = prompt_section(&m[..1], &[], &[
Skill { name: "週報".into(), description: "整理每週進度".into(), instructions: "…".into(), ..Default::default() },
Skill { name: "已停用技能".into(), description: "不該出現".into(), instructions: "…".into(), enabled: false, ..Default::default() },
]);
assert!(p.contains("- 事 5\n") && !p.contains("1. 事 5") && p.contains("- 週報:整理每週進度") && !p.contains("已停用技能") && p.contains("use_skill") && p.contains("search_memory"));
// A memory that is itself a number is forgotten by its words, not as a place in the list.
let mut m = vec!["甲".to_string(), "2".to_string(), "丙".to_string(), "乙".to_string()];
assert_eq!(forget(&mut m, "2").unwrap(), "忘記了:2");
assert_eq!(forget(&mut m, "2").unwrap(), "忘記了:丙");
// The whole line wins over a line that merely contains it.
let mut m = vec!["不喝咖啡因".to_string(), "咖啡".to_string()];
assert_eq!(forget(&mut m, "咖啡").unwrap(), "忘記了:咖啡");
}
fn call(id: &str, name: &str, args: &str, failed: bool) -> crate::model::ToolCall {
crate::model::ToolCall { id: id.into(), name: name.into(), args: args.into(), status: if failed { crate::model::ToolStatus::Failed } else { crate::model::ToolStatus::Done } }
}
fn result(id: &str, text: &str) -> crate::model::Message {
crate::model::Message { role: crate::model::Role::Tool, tool_call_id: id.into(), text: text.into(), ..Default::default() }
}
/// A post with a picture: five real steps, one of them failed, the person corrects it midway.
fn post_turn() -> Vec<crate::model::Message> {
use crate::model::Message;
let step = |c: crate::model::ToolCall| Message { tool_calls: vec![c], ..Message::assistant("", "b") };
vec![
Message::user("幫我發一篇 Threads,記得附圖"),
step(call("1", "browser_open", r#"{"url":"https://www.threads.com/"}"#, false)),
result("1", "已打開 https://www.threads.com/\n[13] 按鈕「Create」"),
step(call("2", "browser_click", r#"{"ref":"13"}"#, false)),
result("2", "已點 [13]。新出現的文字:New thread"),
Message { steer: true, ..Message::user("語氣要輕鬆一點") },
step(call("3", "browser_type", r#"{"ref":"12","value":"今天天氣好"}"#, false)),
result("3", "已在 [12] 輸入。"),
step(call("4", "browser_upload", r#"{"path":"/home/bot/x.jpg"}"#, true)),
result("4", "這台電腦上沒有這個檔案"),
step(call("5", "browser_upload", r#"{"path":"/home/bot/bot-6/附件/x.jpg"}"#, false)),
result("5", "已把 /home/bot/bot-6/附件/x.jpg 放進上傳欄位。"),
step(call("6", "remember", r#"{"fact":"x"}"#, false)),
result("6", "記住了"),
Message::assistant("發好了:https://www.threads.com/@me/post/1", "b"),
]
}
#[test]
fn a_long_enough_job_is_looked_back_on() {
let turn = post_turn();
assert!(worth_learning(&turn));
// App steps (remember) don't count; four real steps aren't enough.
assert!(!worth_learning(&turn[..10]));
// A job that saved a skill itself is left alone.
let mut saved = turn.clone();
saved[12].tool_calls[0].name = "save_skill".into();
assert!(!worth_learning(&saved));
}
#[test]
fn the_look_back_has_every_step_and_the_skills() {
let skills = [Skill { name: "Threads 發文".into(), description: "在 Threads 發文".into(), instructions: "1. browser_open https://www.threads.com/".into(), ..Default::default() }];
let b = learn_brief(&post_turn(), &skills);
assert!(b.starts_with("使用者的要求:\n幫我發一篇 Threads,記得附圖"), "{b}");
assert!(b.contains("1. browser_open {\"url\":\"https://www.threads.com/\"} → 已打開 https://www.threads.com/ [13] 按鈕「Create」"), "{b}");
assert!(b.contains("(使用者中途說:語氣要輕鬆一點)"), "{b}");
assert!(b.contains("browser_upload {\"path\":\"/home/bot/x.jpg\"} → 這台電腦上沒有這個檔案(失敗)"), "{b}");
assert!(b.contains("最後的回覆:\n發好了"), "{b}");
assert!(b.contains("- Threads 發文:在 Threads 發文\n 做法:1. browser_open"), "{b}");
// A very long job keeps its start and its end.
let mut long = vec![crate::model::Message::user("做很多事")];
for i in 0..200 {
long.push(crate::model::Message { tool_calls: vec![call(&i.to_string(), "browser_click", "{}", false)], ..crate::model::Message::assistant("", "b") });
}
let b = learn_brief(&long, &[]);
assert!(b.contains("(中間省略 120 步)") && b.contains("81. browser_click") && !b.contains("82. "), "{b}");
}
#[test]
fn a_learned_skill_is_read_from_the_answer() {
let k = learned_skill("好的\n{\"save\": true, \"name\": \" Threads 發文附圖 \", \"description\": \"在 Threads 發一篇附圖的文\", \"instructions\": \"1. browser_open https://www.threads.com/\"}").unwrap();
assert_eq!((k.name.as_str(), k.description.as_str()), ("Threads 發文附圖", "在 Threads 發一篇附圖的文"));
assert!(learned_skill(r#"{"save": false}"#).is_none());
assert!(learned_skill(r#"{"save": true, "name": "", "instructions": "x"}"#).is_none());
assert!(learned_skill("不用存").is_none());
assert!(learned_skill("} {").is_none());
let mut list = vec![];
assert!(upsert_skill(&mut list, k.clone()));
assert!(!upsert_skill(&mut list, Skill { instructions: "新的".into(), ..k }));
assert_eq!((list.len(), list[0].instructions.as_str()), (1, "新的"));
assert!(learned_note("Threads 發文附圖", true).contains("學會了新做法「Threads 發文附圖」"));
}
/// The composer's / list and what a sent 「/名稱」 names: only skills that are on, a name with
/// a space in it whole, and nothing once the name is followed by more of a word.
#[test]
fn a_slash_names_a_skill() {
let k = |name: &str, description: &str, enabled: bool| Skill { name: name.into(), description: description.into(), enabled, ..Default::default() };
let skills = vec![k("pdf", "PDF 檔", true), k("pptx", "簡報投影片", true), k("web-design", "網頁與儀表板", true), k("訂 pizza", "在網站上訂披薩", true), k("pptx-old", "舊的", false)];
let names = |d: &str| slash_matches(d, &skills).map(|v| v.iter().map(|k| k.name.clone()).collect::<Vec<_>>());
assert_eq!(names("/").unwrap(), ["pdf", "pptx", "web-design", "訂 pizza"], "every skill that is on, in its order");
assert_eq!(names("/P").unwrap(), ["pdf", "pptx", "訂 pizza"], "name first; case doesn't matter");
assert_eq!(names("/簡報").unwrap(), ["pptx"], "a description finds it too");
assert_eq!(names("/design").unwrap(), ["web-design"]);
assert_eq!(names("/pptx 做五頁"), None, "a space: the name is done, the list goes");
assert_eq!(names("幫我 /pdf"), None, "only a / at the start");
assert!(names("/zzz").unwrap().is_empty());
let named = |t: &str| named_skill(t, &skills).map(|k| k.name.clone());
assert_eq!(named("/pptx 把週報做成簡報").as_deref(), Some("pptx"));
assert_eq!(named(" /pdf").as_deref(), Some("pdf"), "the name alone, spaces before it");
assert_eq!(named("/訂 pizza 兩個大的").as_deref(), Some("訂 pizza"), "a name with a space");
assert_eq!(named("/pptxx 做簡報"), None, "more of a word is another name");
assert_eq!(named("/pptx-old 做簡報"), None, "a skill that is off");
assert_eq!(named("/Users/me/a.pdf"), None);
assert!(named_skill_line(&skills[1]).contains("use_skill") && named_skill_line(&skills[1]).contains("「pptx」"));
}
#[test]
fn a_skill_round_trips_through_a_file() {
let sk = Skill {
name: "每日打卡".into(),
description: "在下載資料夾記一天".into(),
instructions: "打開終端機記個日期".into(),
steps: vec![ReplayStep { tool: "shell".into(), args: "{\"cmd\":\"date +%F\"}".into(), targets: vec![] }],
..Default::default()
};
let text = skill_to_file(&sk);
let back = parse_skill_file(&text).unwrap();
assert_eq!(back.name, "每日打卡");
assert_eq!(back.steps, sk.steps);
// The words come back as written, with or without a steps block after them.
assert_eq!((back.description.as_str(), back.instructions.as_str()), ("在下載資料夾記一天", "打開終端機記個日期"));
let plain = parse_skill_file(&skill_to_file(&Skill { steps: vec![], ..sk.clone() })).unwrap();
assert_eq!(plain.instructions, "打開終端機記個日期");
// Both folder packages (`skills/<slug>/SKILL.md`) and `.md` files in the repo read cleanly.
let shipped = crate::skills::load_skills_in_dir(std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/skills")));
assert!(shipped.len() >= 8, "expected built-in skills in repo, got {}", shipped.len());
for (p, s) in shipped {
assert!(!s.instructions.is_empty() && !s.instructions.starts_with('-'), "{p:?}: {}", s.instructions);
}
assert!(parse_skill_file("no front matter at all").is_none());
}
#[test]
fn a_finished_turn_can_become_a_skill() {
use crate::oplog::{Prompt, Record, Replay};
let recs = vec![
Record::OperationStarted { op: "o1".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "每天記一下日期".into() }) },
Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "computer".into(), args: "{\"action\":\"screenshot\"}".into(), replay: Replay::Safe, at: 2 },
Record::ToolFinished { op: "o1".into(), call_id: "c1".into(), status: "done".into(), at: 3 },
Record::ToolStarted { op: "o1".into(), call_id: "c2".into(), name: "shell".into(), args: "{\"cmd\":\"date\"}".into(), replay: Replay::Safe, at: 4 },
Record::ToolFinished { op: "o1".into(), call_id: "c2".into(), status: "done".into(), at: 5 },
Record::ToolStarted { op: "o1".into(), call_id: "c3".into(), name: "shell".into(), args: "{\"cmd\":\"rm\"}".into(), replay: Replay::Safe, at: 6 },
Record::ToolFinished { op: "o1".into(), call_id: "c3".into(), status: "failed".into(), at: 7 },
Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer".into(), args: "{\"action\":\"click\",\"ref\":3}".into(), replay: Replay::Safe, at: 8 },
Record::ToolFinished { op: "o1".into(), call_id: "c4".into(), status: "done".into(), at: 9 },
];
let sk = skillify("每天記一下日期", &recs).unwrap();
// only the shell date step survives: looks and numbered clicks are dropped, failures too
assert_eq!(sk.steps.len(), 1);
assert_eq!(sk.steps[0].tool, "shell");
assert!(sk.steps[0].args.contains("date"));
assert!(skillify("沒這回合", &recs).is_none());
}
#[test]
fn remember_tells_the_same_thing_from_another_fact() {
let bot = 4261;
let mut list = vec![];
// A line that only shares its subject with a kept one is another fact: kept, unasked.
for (old, new) in [("女兒小安對花生過敏", "我對花生過敏"), ("我住在台南,常搭高鐵去台北開會", "我住在台北"), ("咖啡不加糖,要熱的", "茶不加糖")] {
remember_tool(bot, &mut list, old, "", false).unwrap();
let r = remember_tool(bot, &mut list, new, "", false);
assert!(matches!(&r, Ok(t) if t.starts_with("記住了")), "{new}: {r:?}");
}
assert_eq!(list.len(), 6);
// Nearly the same words: the bot is given the three ways out, and may keep both.
let e = remember_tool(bot, &mut list, "茶不加糖喔", "", false).unwrap_err();
assert!(e.contains("「茶不加糖」") && e.contains("replaces") && e.contains("separate") && e.contains("不要問使用者"), "{e}");
assert_eq!(list.len(), 6);
assert!(remember_tool(bot, &mut list, "茶不加糖喔", "", true).unwrap().starts_with("記住了"));
assert_eq!(list.len(), 7);
// The old line wholly inside the new one: the new adds a detail (an update to choose).
assert!(remember_tool(bot, &mut list, "我對花生過敏,連花生油也不行", "", false).is_err());
}
#[test]
fn small_talk_carries_nothing_and_each_bot_keeps_its_own() {
let bot = 4262;
for e in ["11-01:謝謝 → 不客氣!", "11-02:繼續 → 好,我接著做第三步", "11-03:好的謝謝 → 不會", "11-04:幫我訂高鐵 → 訂好了"] {
crate::store::memory_event(bot, e);
}
let none = std::collections::HashSet::new();
// Words that say nothing don't meet the earlier times they were said; nor do % and _.
for q in ["謝謝", "繼續", "好的", "好的謝謝", "ok", "__", "%%", "100%"] {
assert!(carry(bot, q, None, &none).is_empty(), "{q}: {:?}", carry(bot, q, None, &none));
}
assert_eq!(carry(bot, "高鐵", None, &none), vec!["11-04:幫我訂高鐵 → 訂好了".to_string()]);
// The page's own search box still finds the words as typed.
assert_eq!(crate::memstore::list(bot, "all", "謝謝", 0, 10).total, 2);
// forget is for 記得的事: a line of 做過的事 that has the word stays.
let mut list = vec![];
assert!(forget_tool(bot, &mut list, "高鐵").is_err());
assert_eq!(crate::memstore::find(bot, "11-04:幫我訂高鐵 → 訂好了").unwrap().deleted, 0);
// Another bot reads none of this, and a pick has to be one of the bot's own memories.
assert!(carry(4263, "高鐵", None, &none).is_empty());
assert!(crate::memstore::search(4263, "高鐵", &["fact", "event", "rollup"], 5).is_empty());
let picks = vec!["11-04:幫我訂高鐵 → 訂好了".to_string(), "隨便寫的一句,不是記憶".to_string()];
assert_eq!(carry(bot, "x", Some(&picks), &none), vec![picks[0].clone()]);
assert!(carry(4263, "x", Some(&picks), &none).is_empty());
assert_eq!(now_line(1_762_826_400_000, "Asia/Taipei"), "〔現在時間:2025-11-11(週二)10:00〕");
}
}