diff --git a/FEATURES.md b/FEATURES.md index 553e559..f7e1ed0 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1339,8 +1339,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 記憶、技能、範本 - **記憶**:每個 Bot 有三種記憶。完整設計(存在哪、分數怎麼算、送給模型的內容、每晚整理、API)見 [docs/memory.md](docs/memory.md)。 - - 「記得的事」:跟 Bot 說「記住我喜歡靠窗的座位」,它會用 remember 記下來;「忘記…」用 forget。每個 Bot 最多 200 條、每條 500 字(估計值)。已經有很像的一條時不會重複記,Bot 要更新舊的那條就用 `replaces` 指出來,舊的不會再帶。 - - 「做過的事」:每回合做完自動記一行(你問了什麼、結果是什麼)。 + - 「記得的事」:跟 Bot 說「記住我喜歡靠窗的座位」,它會用 remember 記下來;「忘記…」用 forget。每個 Bot 最多 200 條、每條 500 字(估計值)。要不要記由 Bot 自己判斷(之後還用得到的才記),不會問你,記了只在回答最後帶一句「(記下了:…)」。已經有很像的一條時不會重複記,由 Bot 自己決定:同一件事就不記、是更新就用 `replaces` 取代舊的(舊的不會再帶)、是不同的事就兩條都留。每個 Bot 只有自己的記憶。 + - 「做過的事」:有動手做事的回合(改了東西,或查資料 5 步以上)做完自動記一行(你問了什麼、結果是什麼)。閒聊和簡單問答不記。 - 「整理過的」:每晚凌晨 3 點後,在大腦上把超過 30 天的做過的事壓成每週一行,例如「11/3–11/9 做過的事(14 件):整理照片 ×3、追蹤 FSD ×5…」;每週那行超過半年再壓成每月一行。壓掉的原文放進「最近刪除」30 天。記得的事永遠不會自動刪。 - **帶多少**:釘選的記憶每次都帶;其他的只帶跟這則訊息有關的,打字時就在輸入框上方看得到,可以自己勾(第 6 節)。沒人勾時自動挑,最多 3 條。帶過的同一段聊天裡不再重複帶。 - **翻記憶**(search_memory):帶來的不夠時,Bot 自己查,回傳附日期。只是看,不用核准。 @@ -1530,7 +1530,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) | 「傳訊息給其他 Bot」 | 把工作交給另一個 Bot 並叫醒它 | 不用 | 「已交給「名稱」,它的回覆會出現在它自己的聊天裡。」對方收到「📨 來自「發送者」:內容」 | | 「查看電腦」 | 列出能用的電腦和狀態 | 不用 | 例如「你的電腦:這台 Mac,已允許」 | | 「修改設定」 | 改主題、強調色、時區 | 不用 | 「已更新:主題 → …」 | -| 「記住」 | 記下一件事;已經有很像的就不記,請 Bot 用 `replaces` 更新舊的那條 | 不用 | 「記住了:…」「已經記得:…」或「記住了:…(取代了「…」)」 | +| 「記住」 | 記下一件事;已經有很像的就先不記,由 Bot 決定不記、用 `replaces` 取代舊的,或用 `separate` 兩條都留 | 不用 | 「記住了:…」「已經記得:…」或「記住了:…(取代了「…」)」 | | 「忘記」 | 把一件記得的事放進「最近刪除」 | 不用 | 「忘記了:…(30 天內可以在「記憶 › 最近刪除」還原)」 | | 「翻記憶」 | 用意思和字找記得的事、做過的事(search_memory) | 不用 | 每條附日期 | diff --git a/docs/memory.md b/docs/memory.md index f3249b8..0bcdeff 100644 --- a/docs/memory.md +++ b/docs/memory.md @@ -1,6 +1,6 @@ # 記憶怎麼運作 -每個 Bot 有自己的記憶:你要它記住的事,和它幫你做過的事。這份文件說明記憶存在哪裡、怎麼找、每次送給模型的是什麼,以及怎麼整理。 +每個 Bot 有自己的記憶:你要它記住的事,和它幫你做過的事。每個 Bot 只讀寫自己的記憶,看不到別的 Bot 的。這份文件說明記憶存在哪裡、怎麼找、每次送給模型的是什麼,以及怎麼整理。 設計的四個原則: @@ -25,7 +25,7 @@ | 種類 | 從哪裡來 | 會不會自動刪 | |---|---|---| | 記得的事(`fact`) | 你說「記住…」,Bot 用 remember 記下;或在記憶頁自己新增 | 永遠不會 | -| 做過的事(`event`) | 每回合做完自動寫一行,例如「11-08:幫我發一篇 Threads… → 發好了…」 | 30 天後壓成每週一行 | +| 做過的事(`event`) | 有動手做事的回合做完自動寫一行,例如「11-08:幫我發一篇 Threads… → 發好了…」 | 30 天後壓成每週一行 | | 整理過的(`rollup`) | 每晚整理產生,例如「11/3–11/9 做過的事(14 件):整理照片 ×3、追蹤 FSD ×5…」 | 每週那行過了 180 天,再壓成每月一行 | 每條記憶另外記錄: @@ -38,6 +38,8 @@ 「記得的事」每個 Bot 最多 200 條、每條最多 500 字。 +**做過的事只記有做事的回合**:這一回合有改變東西的步驟(改檔案、發文、填表、設定、建例行任務…),或查資料查了 5 步以上,才寫一行。閒聊、簡單問答、查一次資料不記。 + ## 存在哪裡 | 檔案(在 AnyBot 資料夾裡) | 內容 | @@ -92,6 +94,8 @@ 釘選的、被取代的、在「最近刪除」裡的,都不會出現在建議裡(釘選的本來就每次都帶)。 +整句剛好出現在某條記憶裡時直接給滿分,但只限這句話有實際的詞。「謝謝」「繼續」「好的」這類應答詞不算,否則會把以前每一次說「謝謝」的做過的事都帶上。記憶頁的搜尋框不受這個限制,打什麼就找什麼。 + ## 每次送給模型的內容 ### 系統指示(每次都一樣) @@ -112,13 +116,14 @@ VPN 連不上了,怎麼辦 ``` - 這段在 `group_history` 組,放在不存檔的 `Message.context`,送出時才接上。事件記錄、技能學習、稽核看到的都只有你打的字。 +- 隔了 10 分鐘以上才回覆的訊息(隔天按「重新產生」、中斷後接續),最後一則後面會多一行〔現在時間:…〕,模型以它為準。 - 送出時間用的是訊息自己的時間,記憶用的是存在訊息上的 `Message.memories`,兩個都不會再變。所以同一段聊天下一回合再送,前段一個字都不差,模型服務的提示快取會中。 ### 哪幾條記憶跟著這則訊息 開始回覆時決定,決定後存回訊息(`memories`,以及 `memories_set` 表示選過了),之後不再改: -1. 你在輸入框勾過,就照你勾的,連「全部拿掉」也算。 +1. 你在輸入框勾過,就照你勾的,連「全部拿掉」也算。只收這個 Bot 真的有的記憶,其他文字會被丟掉。 2. 沒人勾過(手機沒等到卡片、例行任務、訊息管道),大腦自己挑:總分 ≥ 0.55,最多 3 條。 3. 目前看得到的歷史(最新的摘要之後)裡已經帶過的,不再重複帶。 4. 每帶一次,那條的「帶過幾次」加 1,「上次帶入」更新。 @@ -127,19 +132,29 @@ VPN 連不上了,怎麼辦 | 工具 | 做什麼 | |---|---| -| `remember(fact, replaces?)` | 記住一件事 | -| `forget(what)` | 忘記一件事,放進「最近刪除」,30 天內可以還原 | +| `remember(fact, replaces?, separate?)` | 記住一件事 | +| `forget(what)` | 忘記一件記得的事,放進「最近刪除」,30 天內可以還原。不會動到做過的事 | | `search_memory(query, kind?)` | 翻記憶。`kind` 是 `all`、`fact` 或 `event`。回傳的每條都附日期。只是看,不用核准 | +**要不要記由 Bot 自己判斷,不問你。** 系統指示告訴它: + +- 像人一樣:重要的記,小事不記。要記的是你教它的和你告訴它的、之後還用得到的事。不用等你說「記住」。 + - 你教它怎麼操作或怎麼做一件事:步驟多的存成技能(save_skill),一句話講得完的規則用 remember。 + - 你告訴它的事:偏好和習慣、關於你和身邊的人的事實、說定的做法和決定。 + - 你糾正它的地方。 +- 不確定重不重要就不記。閒聊、隨口問的問題、只有這次用得到的、一次性的要求、它自己做了什麼、從記憶裡讀到的、猜的,都不記。 +- 不問「要我記下來嗎」。記了只在回答最後帶一句「(記下了:…)」。 + remember 不會記重複的: -- 字幾乎一樣,或語意很像(cos ≥ 0.85):不新增,回傳已經有的那條,請 Bot 判斷新的是不是更新或更正。是的話,再呼叫一次 remember,把 `replaces` 設成舊的那條。 +- 「很像」要兩邊都像才算:兩句的詞(含連續兩字)有六成以上相同,或舊的那句整句包含在新的裡,或語意很像(cos ≥ 0.85)。只是主題相同不算,例如已經有「女兒小安對花生過敏」,「我對花生過敏」照樣記。 +- 很像時先不新增,回傳已經有的那條,由 Bot 三選一:同一件事就不記;是更新或更正,再呼叫一次並把 `replaces` 設成舊的那條;是不同的兩件事,再呼叫一次並把 `separate` 設成 true。 - 被取代的舊記憶放進「最近刪除」,標上被哪一條取代,之後不會再帶。 - 以前刪掉的事再 remember 一次,會把原來那條還原。 ## 每晚整理 -在存記憶的那台(大腦)上,照使用者的時區,每天凌晨 3 點後做一次。全部在本機算,不呼叫模型。 +只在存記憶的那台(大腦)上做,螢幕和手腳不做。照使用者的時區,每天凌晨 3 點後做一次。全部在本機算,不呼叫模型。 - **做過的事超過 30 天**:每週(週一到週日)壓成一行。內容相近的放在一起數次數,次數多的排前面,整行最多 400 字,放不下的寫「…還有 N 件」。 - **每週那行超過 180 天**:每月再壓成一行,例如「2026 年 4 月做過的事(14 件):整理照片 ×3、修 Docker…」。 @@ -165,7 +180,7 @@ remember 不會記重複的: - `tokenizer.json` 轉成 `vocab.bin` - `model.safetensors` 一邊下載一邊量化成 `table.i8`(int8,每列一個縮放值) - 另存 `dims.json` -- 總共下載約 530 MB,存下來約 137 MB。設定頁顯示下載進度,失敗了過幾分鐘會再試。 +- 總共下載約 530 MB,存下來約 137 MB。設定頁顯示下載進度,失敗了過幾分鐘會再試。整個下載沒有時間上限,只有連續 60 秒收不到資料才算失敗。 - 環境變數 `ANYBOT_HF_BASE` 可以換成 Hugging Face 的鏡像站(例如 `https://hf-mirror.com`)。 - 第一次要用時才載入(34 毫秒),閒置 10 分鐘就放掉。載入時程式多用約 190 MB 記憶體,一句話約 1.5 微秒。 @@ -190,7 +205,7 @@ remember 不會記重複的: | 路徑 | 誰用 | |---|---| -| `/api/memory` | 手機,只限擁有者 | +| `/api/memory` | 手機,只限擁有者。團隊成員讀聊天時,訊息不附帶了哪些記憶;成員送出的 `memories` 也不收 | | `/api/sync/memory` | 螢幕(`mirror` 角色,當作擁有者) | 讀取直接在 HTTP 執行緒回答。沒有視窗的大腦主迴圈每圈會睡 250 毫秒,交給它會讓打字搜尋變慢: @@ -235,7 +250,7 @@ remember 不會記重複的: - 篩選:全部/記得的事/做過的事/釘選/最近刪除。 - 整理建議卡,一鍵套用。 - 每條顯示種類、日期、帶過幾次、上次帶入;可以釘選、編輯、忘記,在「最近刪除」裡可以還原。 -- **輸入框上方的記憶小卡片**:打字停 300 毫秒就搜尋,最多 8 張。分數高的預先勾好,旁邊寫「帶 N 條,約 T token」或「這次不帶」。點一下卡片就加入或拿掉;滑過去看得到全文、種類、日期和相關度。 +- **輸入框上方的記憶小卡片**:打字停 300 毫秒就搜尋,最多 8 張。Bot 工作中不顯示(那時送出的是插話,不帶記憶)。分數高的預先勾好,旁邊寫「帶 N 條,約 T token」或「這次不帶」。點一下卡片就加入或拿掉;滑過去看得到全文、種類、日期和相關度。 - **你的訊息下面**:「帶了 N 條記憶」,點開看是哪幾條,也可以從這裡打開記憶頁。 ### 手機版 @@ -262,7 +277,9 @@ remember 不會記重複的: - 分數與門檻:`the_shelf_answers_with_scores`、`a_message_carries_little_and_never_twice` - 繁體中文斷詞:`traditional_text_cuts_into_words_that_meet`、`the_memory_index_answers_in_chinese` -- remember 去重與 `replaces`:`remember_says_when_it_already_knows_and_replaces_on_request` +- remember 去重與 `replaces`:`remember_says_when_it_already_knows_and_replaces_on_request`、`remember_tells_the_same_thing_from_another_fact` +- 只記有做事的回合:`only_a_turn_that_did_something_is_remembered` +- 應答詞不帶記憶、各 Bot 只讀自己的、forget 不動做過的事:`small_talk_carries_nothing_and_each_bot_keeps_its_own` - 兩回合送出的前段一樣:`two_turns_send_the_same_beginning`、`a_message_reads_the_same_every_turn` - 帶過的不重複帶:`a_memory_rides_once_per_chat` - 每週、每月壓縮與最近刪除:`old_events_fold_into_weeks_then_months`、`folded_lines_read_back`、`forgetting_is_a_trash_you_can_take_back` diff --git a/mobile/index.html b/mobile/index.html index 64aa337..9620f1f 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1252,7 +1252,7 @@ async function send() { if (S.quote) { text = S.quote.raw.split("\n").map((l) => "> " + l).join("\n") + "\n\n" + text; S.quote = null; renderQuote(); } const attachments = S.pending.map((p) => p.path); // 記憶 ticked above the composer (none of it if the shelf never answered: the brain chooses). - const memories = memPicks(); + const memories = b.busy ? undefined : memPicks(); memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); if (!b.busy) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } @@ -1495,7 +1495,9 @@ function memPicks() { const s = S.memSug; return s.bot === S.open && s.asked ? s function memReset() { clearTimeout(S.memSug.timer); S.memSug = {bot: 0, asked: "", hits: [], toggled: {}, timer: null}; renderMemChips(); } function renderMemChips() { const s = S.memSug, el = $("memchips"); - if (!isOwner() || s.bot !== S.open || !s.hits.length || !input.value.trim()) { el.innerHTML = ""; return; } + // (Not while the bot works: what is sent then joins the running turn, which carries none.) + const busy = (S.bots.find((x) => x.id === S.open) || {}).busy; + if (!isOwner() || busy || s.bot !== S.open || !s.hits.length || !input.value.trim()) { el.innerHTML = ""; return; } const on = s.hits.filter(memOn), tok = on.reduce((a, h) => a + (h.tokens || 0), 0); el.innerHTML = `${ic("bookmark", 13)} 帶入記憶` + s.hits.map((h) => ``).join("") + `${on.length ? `帶 ${on.length} 條,約 ${tok} token` : "這次不帶"}`; el.querySelectorAll("[data-mc]").forEach((x) => x.onclick = () => { const h = s.hits.find((y) => y.id === +x.dataset.mc); if (h) { s.toggled[h.id] = !memOn(h); renderMemChips(); } }); diff --git a/src/agent.rs b/src/agent.rs index e81f71a..65a8954 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -181,8 +181,23 @@ fn parse_verdict(text: &str) -> ReviewVerdict { /// after Done: the person isn't kept waiting. /// The event log (P6): one line per finished turn — who asked what, what came out — written /// without anyone's asking, so "我上個月說的那個報表" answers from the memory index months later. +/// Like a person's memory: a turn is kept as 做過的事 when something was done in it — a step +/// that changed something somewhere (a file, a page, a post, a setting, a routine), or a long +/// piece of looking things up. Small talk, a quick answer, one search: not worth a line. (What +/// the person tells the bot to keep is another matter: that is `remember`, the bot's own call.) +pub(crate) fn worth_noting(turn: &[Message]) -> bool { + let calls: Vec<&str> = turn.iter().flat_map(|m| m.tool_calls.iter().map(|c| c.name.as_str())).collect(); + let quiet = |n: &str| only_looks(n) || matches!(n, "remember" | "forget" | "search_memory" | "search_documents" | "use_skill" | "react" | "show_card" | "list_routines" | "list_bots" | "list_computers"); + calls.iter().any(|n| !quiet(n)) || calls.len() >= NOTE_MIN_LOOKS +} +/// This many steps of only looking are a piece of work too (a long research). +const NOTE_MIN_LOOKS: usize = 5; + fn memory_note(job: &Job, history: &[Message]) { let Some(start) = history.iter().rposition(|m| m.role == Role::User && !m.steer) else { return }; + if !worth_noting(&history[start..]) { + return; + } let ask = history[start].text.trim(); if ask.is_empty() { return; @@ -3736,4 +3751,18 @@ echo 'done送出了' > done.html; (setsid pyt let result = evs.iter().find_map(|e| if let StreamEvent::ToolResult(m) = e { Some(m.text.clone()) } else { None }).unwrap(); assert!(result.contains("這一步你指定了「王小明的Mac mini」") && result.contains("here.txt"), "{result}"); } + /// 做過的事 is for what was done: small talk and a quick look-up leave no line. + #[test] + fn only_a_turn_that_did_something_is_remembered() { + let turn = |names: &[&str]| -> Vec { + let calls = names.iter().map(|n| crate::model::ToolCall { id: "c".into(), name: n.to_string(), args: "{}".into(), status: ToolStatus::Done }).collect(); + vec![Message::user("x"), Message { tool_calls: calls, ..Message::assistant("好", "m") }] + }; + assert!(!worth_noting(&turn(&[])), "a chat"); + assert!(!worth_noting(&turn(&["web_fetch"])), "one look-up"); + assert!(!worth_noting(&turn(&["remember", "search_memory"])), "memory's own steps"); + assert!(worth_noting(&turn(&["read_file", "edit_file"])), "something changed"); + assert!(worth_noting(&turn(&["create_routine"]))); + assert!(worth_noting(&turn(&["web_fetch", "web_fetch", "read_file", "search", "web_fetch"])), "a long piece of research"); + } } diff --git a/src/app.rs b/src/app.rs index e2b986d..8c0fd05 100644 --- a/src/app.rs +++ b/src/app.rs @@ -973,7 +973,17 @@ impl App { } sys }, - history: group_history(&conv.messages, speaker, &self.state), + history: { + let mut h = group_history(&conv.messages, speaker, &self.state); + // An answer made long after its message (重新產生 the next day, a turn picked up + // after a crash): the model's clock is the message's 送出時間, so say what it is now. + let now = crate::model::now_ms(); + if let Some(m) = h.last_mut().filter(|m| m.role == Role::User && m.at > 0 && now - m.at > STALE_CLOCK_MS) { + let line = crate::memory::now_line(now, &self.state.timezone); + m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) }; + } + h + }, tools: tool_specs, session: format!("anybot-bot-{bot_id}"), }; @@ -2715,7 +2725,8 @@ impl App { ui.add_space(4.0); } // 記憶: what this draft may want to carry, searched once typing rests. - if bot.members.is_empty() { + // (Not while it works: what is typed then joins the running turn, which carries none.) + if bot.members.is_empty() && !streaming { self.mem_suggest_tick(ctx, bot.id, &draft); self.mem_chips(ui, bot.id); } @@ -3877,7 +3888,8 @@ impl App { self.watchdog(); self.poll_fetches(); self.poll_import(); - if !self.demo && !hands { + // (Where the memories are: the brain. A screen's own file is empty.) + if !self.demo && !hands && !self.mir.on { self.memory_nightly(); } } @@ -4359,6 +4371,9 @@ pub fn message_max_width(container: f32) -> f32 { /// members' answers as labelled words (their tool steps and private blocks left out). /// The memories the model already has in this chat: carried by a message of the person's in /// what it reads (from the newest summary on). +/// A message this old isn't "now" any more for the model that answers it. +const STALE_CLOCK_MS: i64 = 10 * 60_000; + fn carried_in_view(messages: &[Message]) -> std::collections::HashSet { messages[crate::model::model_view_start(messages)..].iter().filter(|m| m.role == Role::User).flat_map(|m| m.memories.iter().cloned()).collect() } @@ -4917,7 +4932,11 @@ mod tests { if let Some(b) = st.bot_mut(bot) { b.messages = vec![Message { memories: vec!["我喜歡靠窗的座位".into()], memories_set: true, ..Message::user("訂去程") }, Message::assistant("好", "x")]; } - let m = person_message(&st, bot, "訂回程", vec![], Some(vec!["我喜歡靠窗的座位".into(), "週五下午不開會".into()])); + for f in ["我喜歡靠窗的座位", "週五下午不開會"] { + crate::memstore::add(bot, f, "fact"); + } + // (A pick that isn't one of the bot's memories is dropped: 「不是記憶的一句話」.) + let m = person_message(&st, bot, "訂回程", vec![], Some(vec!["我喜歡靠窗的座位".into(), "週五下午不開會".into(), "不是記憶的一句話".into()])); assert_eq!(m.memories, vec!["週五下午不開會".to_string()]); assert!(m.memories_set); // Nothing picked (the person didn't look): left for the start of the turn to choose. diff --git a/src/appctl.rs b/src/appctl.rs index 27b3ba7..36b6226 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -73,7 +73,7 @@ fn schedule_schema() -> Value { pub fn specs() -> Vec { vec![ json!({"name": "list_routines", "description": "List this bot's routines (scheduled, repeating tasks).", "parameters": {"type": "object", "properties": {}}}), - json!({"name": "remember", "description": "Keep a fact or preference the person wants you to remember across chats. If one very like it is already kept, nothing is added and you are told which one; when the new fact updates or corrects an old one (moved city, changed preference), call again with that old memory's words in `replaces`: the old one is retired and never carried again.", "parameters": {"type": "object", "properties": {"fact": {"type": "string"}, "replaces": {"type": "string", "description": "The words of the kept memory this one updates or corrects (optional)."}}, "required": ["fact"]}}), + json!({"name": "remember", "description": "Keep a fact or preference the person wants you to remember across chats. Use it on your own judgment for what will matter later (preferences, facts about the person, decisions, corrections): don't ask first, and don't keep one-off requests. If one very like it is already kept, nothing is added and you are told which one; you decide: the same thing (do nothing), an update or correction (call again with that old memory's words in `replaces`: the old one is retired and never carried again), or a different fact that should stand beside it (call again with `separate`: true).", "parameters": {"type": "object", "properties": {"fact": {"type": "string"}, "replaces": {"type": "string", "description": "The words of the kept memory this one updates or corrects (optional)."}, "separate": {"type": "boolean", "description": "true: keep this as its own memory even though a similar one exists (they are different facts)."}}, "required": ["fact"]}}), json!({"name": "forget", "description": "Forget a remembered fact: give the fact's own words (or words in it).", "parameters": {"type": "object", "properties": {"what": {"type": "string"}}, "required": ["what"]}}), json!({"name": "search_memory", "description": "Look through everything this bot remembers — what the person asked you to keep (facts, preferences, decisions) and what you did for them before (one line per past task, older ones folded by week and month) — by meaning as well as words. Use it when the memories that came with the message aren't enough: 「上次怎麼做的」, 「我說過喜歡哪家」, 「上個月那份報表」. Answers with dates.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "What to look for, in the person's words."}, "kind": {"type": "string", "enum": ["all", "fact", "event"], "description": "fact = things to remember, event = things done before; default all."}}, "required": ["query"]}}), json!({"name": "save_skill", "description": "Save a reusable procedure as a skill every bot can use (replaces one with the same name).", "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "description": {"type": "string", "description": "One line: when to use it"}, "instructions": {"type": "string", "description": "The full steps"}}, "required": ["name", "description", "instructions"]}}), @@ -423,7 +423,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome .join("\n")), "remember" => { let Some(b) = state.bot_mut(bot_id) else { return err("找不到這個 Bot".into()) }; - match crate::memory::remember_tool(bot_id, &mut b.memories, &s("fact").unwrap_or_default(), &s("replaces").unwrap_or_default()) { + match crate::memory::remember_tool(bot_id, &mut b.memories, &s("fact").unwrap_or_default(), &s("replaces").unwrap_or_default(), v.get("separate").and_then(Value::as_bool).unwrap_or(false)) { Ok(t) => ok(t), Err(e) => err(e), } diff --git a/src/embed.rs b/src/embed.rs index 0f651d8..8ca62f9 100644 --- a/src/embed.rs +++ b/src/embed.rs @@ -207,7 +207,8 @@ fn fetch_local() -> Result<(), String> { let dir = model_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("建不了資料夾:{e}"))?; let url = |f: &str| format!("{}/{LOCAL_MODEL}/resolve/main/{f}", hub()); - let net: ureq::Agent = ureq::Agent::config_builder().timeout_connect(Some(Duration::from_secs(30))).timeout_recv_body(Some(Duration::from_secs(120))).build().into(); + // No limit on the whole download (512 MB on a slow line takes a while): only on silence. + let net: ureq::Agent = ureq::Agent::config_builder().timeout_connect(Some(Duration::from_secs(30))).timeout_recv_response(Some(Duration::from_secs(60))).timeout_per_read(Some(Duration::from_secs(60))).build().into(); let why = |e: ureq::Error| format!("連不到 Hugging Face:{e}"); let mut r = net.get(&url("tokenizer.json")).call().map_err(why)?; let tok = r.body_mut().with_config().limit(64 << 20).read_to_vec().map_err(|e| format!("字表沒下載完:{e}"))?; diff --git a/src/memory.rs b/src/memory.rs index f1843a1..59c7fbe 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -515,9 +515,10 @@ pub fn carry(bot: u64, text: &str, picked: Option<&[String]>, already: &std::col 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) { - out.push(t.clone()); - if let Some(m) = crate::memstore::find(bot, t).or_else(|| crate::memstore::find(0, t)) { + if let Some(m) = crate::memstore::find(bot, t).filter(|m| m.deleted == 0) { + out.push(t.clone()); ids.push(m.id); } } @@ -563,6 +564,18 @@ pub fn context_of(m: &crate::model::Message, timezone: &str) -> String { 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], skills: &[Skill]) -> String { @@ -574,7 +587,7 @@ pub fn prompt_section(pinned: &[String], skills: &[Skill]) -> String { s.push_str(&format!("- {m}\n")); } } - s.push_str("\n\n記憶:使用者訊息後面的〔送出時間:…〕是那則訊息送出的時間,〔相關記憶:…〕是 AnyBot 替那則訊息找出來(或使用者自己勾選)的舊記憶,不是使用者打的字。要更多過去的事(偏好、上次怎麼做、說過的決定、做過的事)就用 search_memory 查,查不到再問。使用者說「記住…」「以後都…」時用 remember;和舊的那條說法不同或更正時,把舊的放在 replaces。說「忘記…」時用 forget。"); + s.push_str("\n\n記憶:使用者訊息後面的〔送出時間:…〕是那則訊息送出的時間(後面另有〔現在時間:…〕時,現在以它為準),〔相關記憶:…〕是 AnyBot 替那則訊息找出來(或使用者自己勾選)的舊記憶,不是使用者打的字。要更多過去的事(偏好、上次怎麼做、說過的決定、做過的事)就用 search_memory 查,查不到再問。\n像人一樣記:重要的記,小事不記。你自己判斷,不用等使用者說「記住」,也不要問「要我記下來嗎」。要記的是使用者教你的和告訴你的、之後還用得到的事:他教你怎麼操作或怎麼做一件事(步驟多的用 save_skill 存成技能,一句話講得完的規則用 remember)、他告訴你的事(偏好和習慣、關於他和身邊的人的事實、說定的做法和決定)、他糾正你的地方。不確定重不重要就不要記;閒聊、隨口問的問題、只有這次用得到的、一次性的要求、你做了什麼(AnyBot 會自己記成做過的事)、從記憶裡讀到的、你猜的,都不要記。一句寫一件事,寫成以後單獨看也懂的句子。記了就在回答最後帶一句「(記下了:…)」,不要另外解釋。和舊的那條講同一件事但內容變了(搬家、改喜好、更正),把舊的那條放在 replaces 取代它;remember 說已經有很像的一條時,照它給的三種情況自己選,不要問使用者。使用者說「忘記…」時用 forget。"); if !skills.is_empty() { s.push_str("\n\n你會的技能(以前做成功的做法)。開始做一件事之前先看這裡:有符合的,先用 use_skill 讀出完整做法再照著做,不要重新摸索:\n"); for k in skills { @@ -591,11 +604,13 @@ pub fn prompt_section(pinned: &[String], skills: &[Skill]) -> String { /// 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, fact: &str, replaces: &str) -> Result { +pub fn remember_tool(bot: u64, list: &mut Vec, fact: &str, replaces: &str, separate: bool) -> Result { let f: String = fact.trim().chars().take(MAX_MEMORY_CHARS).collect(); if f.is_empty() { return Err("要記住什麼?".into()); @@ -614,9 +629,16 @@ pub fn remember_tool(bot: u64, list: &mut Vec, fact: &str, replaces: &st if let Some(m) = crate::memstore::find(bot, &f).filter(|m| m.deleted == 0) { return Ok(format!("已經記得:{}", m.text)); } - let same = crate::memstore::search(bot, &f, &["fact"], 3).into_iter().find(|h| h.score >= SAME_SCORE || same_meaning(bot, &h.m, &f)); - if let Some(h) = same { - return Err(format!("沒有新增:已經有很像的一條「{}」。如果新的是更新或更正,再呼叫一次 remember,把 replaces 設成「{}」;如果其實是同一件事,就不用再記。", h.m.text, h.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)?; @@ -631,9 +653,15 @@ pub fn remember_tool(bot: u64, list: &mut Vec, fact: &str, replaces: &st } } +/// 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(bot: u64, m: &crate::memstore::Mem, text: &str) -> bool { - let _ = bot; +fn same_meaning(m: &crate::memstore::Mem, text: &str) -> bool { if !crate::embed::enabled() { return false; } @@ -648,7 +676,7 @@ pub fn forget_tool(bot: u64, list: &mut Vec, what: &str) -> Result 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", "event", "rollup"], 1).into_iter().find(|h| h.score >= 0.9).map(|h| h.m)) { + 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), }, @@ -727,7 +755,7 @@ pub fn api_write(state: &mut crate::model::State, b: &serde_json::Value) -> serd let s = |k: &str| b[k].as_str().unwrap_or("").trim().to_string(); let fail = |e: &str| json!({"error": e}); let Some(list) = state.bot_mut(bot).map(|x| &mut x.memories) else { return fail("找不到這個 Bot") }; - let mine = |id: i64| crate::memstore::get(id).filter(|m| m.bot == bot || m.bot == 0); + let mine = |id: i64| crate::memstore::get(id).filter(|m| m.bot == bot); let ids = |k: &str| -> Vec { 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")) { @@ -751,7 +779,7 @@ pub fn api_write(state: &mut crate::model::State, b: &serde_json::Value) -> serd None => fail("找不到這一條"), }, "edit" => match mine(b["id"].as_i64().unwrap_or(0)) { - Some(m) => match crate::memstore::edit(m.id, &s("text")) { + Some(m) => match crate::memstore::edit(m.id, &s("text").chars().take(MAX_MEMORY_CHARS).collect::()) { Ok((old, new)) => { if m.kind == "fact" { match list.iter().position(|x| *x == old.text) { @@ -850,7 +878,7 @@ mod tests { let bot = 4250; let mut list = vec![]; for f in ["我喜歡靠窗的座位,長途航班也是", "咖啡不加糖", "週五下午不開會", "我住在台南"] { - remember_tool(bot, &mut list, f, "").unwrap(); + 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. @@ -884,13 +912,13 @@ mod tests { fn remember_says_when_it_already_knows_and_replaces_on_request() { let bot = 4251; let mut list = vec![]; - assert!(remember_tool(bot, &mut list, "週五下午不要排會議", "").unwrap().starts_with("記住了")); + 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, "週五下午不要排會議喔", "").unwrap_err(); + 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, "週五下午可以排會議了", "週五下午不要排會議").unwrap(); + 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(); @@ -900,7 +928,7 @@ mod tests { // 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, "週五下午可以排會議了", "").unwrap(); + 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"); @@ -1107,5 +1135,52 @@ mod tests { 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〕"); + } } diff --git a/src/memstore.rs b/src/memstore.rs index a7cc900..176d7ec 100644 --- a/src/memstore.rs +++ b/src/memstore.rs @@ -164,8 +164,9 @@ fn is_cjk(c: char) -> bool { const STOP: &[&str] = &[ "没有", "有没有", "帮我", "一下", "可以", "什么", "怎么", "怎么样", "这个", "那个", "一个", "我们", "你们", "他们", "现在", "还是", "然后", "因为", "所以", "如果", "但是", "已经", "应该", "需要", "知道", "觉得", "是不是", "不是", "就是", "还有", "这样", "那样", "一些", "请问", "谢谢", "好的", "帮忙", "麻烦", "哪里", "为什么", "多少", "记得", "记住", + "继续", "谢谢你", "感谢", "不用", "不客气", "没问题", "了解", "收到", "知道了", "好了", "可以了", "对的", "没错", "是的", "不是", "再来", "下一步", "然后呢", "辛苦了", "告诉", "看看", "一样", "东西", "时候", "的话", "不要", "不会", "能不能", "可不可以", "要不要", "有点", "一点", "我的", "你的", "自己", - "the", "a", "an", "is", "are", "was", "to", "of", "and", "or", "for", "in", "on", "it", "my", "me", "you", "what", "how", "can", "do", "please", "this", "that", "with", + "the", "a", "an", "is", "are", "was", "to", "of", "and", "or", "for", "in", "on", "it", "my", "me", "you", "what", "how", "can", "do", "please", "this", "that", "with", "ok", "okay", "yes", "no", "thanks", "thank", "continue", "go", "next", ]; fn tokens(simplified: &str) -> Vec { @@ -247,9 +248,9 @@ pub fn find(bot: u64, text: &str) -> Option { crate::store::with_conn(|c| c.query_row(&format!("SELECT {COLS} FROM memories WHERE bot=?1 AND text=?2"), params![bot as i64, text], row).ok()).flatten() } -/// 釘選: the memories carried in every chat (the bot's own and the person's shared ones, bot 0). +/// 釘選: the memories carried in every chat. A bot's own only: no bot reads another's. pub fn pinned(bot: u64) -> Vec { - crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot IN (?1, 0) AND deleted=0 AND pinned=1 ORDER BY created"), params![bot as i64])).unwrap_or_default() + crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted=0 AND pinned=1 ORDER BY created"), params![bot as i64])).unwrap_or_default() } fn kinds_sql(kinds: &[&str]) -> String { @@ -268,12 +269,21 @@ fn meaning_score(cos: f32) -> f32 { /// The memories that answer `query`, best first, each with its 0–1 score. pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { + search_as(bot, query, kinds, limit, false) +} + +/// `literal`: the person typed these words to find them (the memory page's search box), so the +/// words themselves count even when they are ones a chat message wouldn't be searched by. +pub fn search_as(bot: u64, query: &str, kinds: &[&str], limit: usize, literal: bool) -> Vec { let q = query.trim(); if q.is_empty() { return vec![]; } let terms = terms_of(q); let qs = simple(q); + if qs.chars().count() < 2 { + return vec![]; + } let qv = if crate::embed::enabled() { crate::embed::embed(&[q.to_string()]).and_then(|mut v| v.pop()) } else { None }; let ks = kinds_sql(kinds); let Some(scored) = crate::store::with_conn(|c| { @@ -281,10 +291,10 @@ pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { let mut words: HashMap = HashMap::new(); if !terms.is_empty() { // How rare each word is here: a word on every line says little. - let n: i64 = c.query_row(&format!("SELECT COUNT(*) FROM memories WHERE bot IN (?1,0) AND deleted=0 AND kind IN {ks}"), params![bot], |r| r.get(0)).unwrap_or(0); + let n: i64 = c.query_row(&format!("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND kind IN {ks}"), params![bot], |r| r.get(0)).unwrap_or(0); let df = |t: &str| -> i64 { c.query_row( - &format!("SELECT COUNT(*) FROM memories_words w JOIN memories m ON m.id=w.rowid WHERE memories_words MATCH ?1 AND m.bot IN (?2,0) AND m.deleted=0 AND m.kind IN {ks}"), + &format!("SELECT COUNT(*) FROM memories_words w JOIN memories m ON m.id=w.rowid WHERE memories_words MATCH ?1 AND m.bot=?2 AND m.deleted=0 AND m.kind IN {ks}"), params![fts_quote(t), bot], |r| r.get(0), ) @@ -302,7 +312,7 @@ pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { let total: f32 = weight.iter().zip(&terms).filter(|(_, (_, f))| *f >= 1.0).map(|(w, _)| w.1).sum::().max(1e-6); let expr = terms.iter().map(|(t, _)| fts_quote(t)).collect::>().join(" OR "); if let Ok(mut st) = c.prepare(&format!( - "SELECT m.id, w.words, m.text FROM memories_words w JOIN memories m ON m.id=w.rowid WHERE memories_words MATCH ?1 AND m.bot IN (?2,0) AND m.deleted=0 AND m.kind IN {ks} ORDER BY bm25(memories_words) LIMIT 300" + "SELECT m.id, w.words, m.text FROM memories_words w JOIN memories m ON m.id=w.rowid WHERE memories_words MATCH ?1 AND m.bot=?2 AND m.deleted=0 AND m.kind IN {ks} ORDER BY bm25(memories_words) LIMIT 300" )) { if let Ok(it) = st.query_map(params![expr, bot], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?))) { for (id, ws, text) in it.flatten() { @@ -320,7 +330,7 @@ pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { } } let mut s = (got / total).min(1.0); - if qs.chars().count() >= 2 && simple(&text).contains(&qs) { + if simple(&text).contains(&qs) { s = 1.0; } words.insert(id, s); @@ -328,9 +338,10 @@ pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { } } } - // The whole query inside a line (a short or oddly cut query). - if qs.chars().count() >= 2 { - if let Ok(mut st) = c.prepare(&format!("SELECT id FROM memories WHERE bot IN (?1,0) AND deleted=0 AND kind IN {ks} AND (text LIKE '%'||?2||'%' OR text LIKE '%'||?3||'%') LIMIT 100")) { + // The whole query inside a line (a short or oddly cut query) — when it says something: + // 「謝謝」 or 「繼續」 would meet every earlier 「謝謝」 in 做過的事. + if !terms.is_empty() || literal { + if let Ok(mut st) = c.prepare(&format!("SELECT id FROM memories WHERE bot=?1 AND deleted=0 AND kind IN {ks} AND (instr(text, ?2) > 0 OR instr(text, ?3) > 0) LIMIT 100")) { if let Ok(it) = st.query_map(params![bot, q, qs], |r| r.get::<_, i64>(0)) { for id in it.flatten() { words.insert(id, 1.0); @@ -340,7 +351,7 @@ pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { } let mut meaning: HashMap = HashMap::new(); if let Some(v) = &qv { - if let Ok(mut st) = c.prepare(&format!("SELECT id, vec FROM memories WHERE bot IN (?1,0) AND deleted=0 AND kind IN {ks} AND vec IS NOT NULL")) { + if let Ok(mut st) = c.prepare(&format!("SELECT id, vec FROM memories WHERE bot=?1 AND deleted=0 AND kind IN {ks} AND vec IS NOT NULL")) { if let Ok(it) = st.query_map(params![bot], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec>(1)?))) { for (id, b) in it.flatten() { let w = crate::embed::blob_to_f32s(&b); @@ -387,8 +398,7 @@ pub fn list(bot: u64, filter: &str, q: &str, offset: usize, limit: usize) -> Pag let q = q.trim(); let b = bot as i64; if filter == "trash" { - let like = format!("%{q}%"); - let all = crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted>0 AND (?2='' OR text LIKE ?3) ORDER BY deleted DESC"), params![b, q, like])).unwrap_or_default(); + let all = crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted>0 AND (?2='' OR instr(text, ?2) > 0) ORDER BY deleted DESC"), params![b, q])).unwrap_or_default(); let total = all.len(); return Page { items: all.into_iter().skip(offset).take(limit).collect(), total }; } @@ -399,7 +409,7 @@ pub fn list(bot: u64, filter: &str, q: &str, offset: usize, limit: usize) -> Pag _ => (&["fact", "event", "rollup"], false), }; if !q.is_empty() { - let mut hits: Vec = search(bot, q, kinds, 400).into_iter().filter(|h| h.score >= 0.15 && h.m.bot == bot).map(|h| h.m).collect(); + let mut hits: Vec = search_as(bot, q, kinds, 400, true).into_iter().filter(|h| h.score >= 0.15).map(|h| h.m).collect(); if pinned_only { hits.retain(|m| m.pinned); } @@ -566,6 +576,16 @@ fn vec_of(c: &Connection, id: i64) -> Option> { // ---------- cleaning up ---------- +/// How alike two lines are by their words, both ways: (shared / all, how much of `old` is in +/// `new`). 「我對花生過敏」 is inside 「女兒小安對花生過敏」 and still another fact: only the first +/// number, or an old line wholly inside the new one (the new adds a detail), says "the same". +pub fn likeness(new: &str, old: &str) -> (f32, f32) { + let a: HashSet = words_of(new).into_iter().collect(); + let b: HashSet = words_of(old).into_iter().collect(); + let inside = if b.len() >= 3 { b.intersection(&a).count() as f32 / b.len() as f32 } else { 0.0 }; + (jaccard(&a, &b), inside) +} + fn word_set(c: &Connection, id: i64) -> HashSet { c.query_row("SELECT words FROM memories_words WHERE rowid=?1", params![id], |r| r.get::<_, String>(0)).map(|w| w.split(' ').filter(|x| !x.is_empty()).map(String::from).collect()).unwrap_or_default() } diff --git a/src/remote.rs b/src/remote.rs index 0b0cdec..52fb697 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -439,6 +439,16 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let id: u64 = id.parse().unwrap_or(0); let v = hub().view.lock().unwrap(); match v.messages.get(&id) { + // 記憶 are the owner's: a member reads the chat without what each message carried. + Some(m) if role != "owner" => { + let mut m = serde_json::to_value(m).unwrap_or(Value::Null); + for x in m.as_array_mut().into_iter().flatten() { + if let Some(o) = x.as_object_mut() { + o.remove("memories"); + } + } + Resp::json(&json!({"version": v.version, "messages": m})) + } Some(m) => Resp::json(&json!({"version": v.version, "messages": m})), None => Resp::error(404, "找不到這個 Bot"), } @@ -480,7 +490,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // 團隊: the bot knows who is talking when it isn't the owner. let who = req.header("x-anybot-user"); let text = if role != "owner" && !who.is_empty() { format!("【{who}】{text}") } else { text }; - Cmd::Send { bot, text, attachments, from: String::new(), memories: picks_of(&b) } + Cmd::Send { bot, text, attachments, from: String::new(), memories: if role == "owner" { picks_of(&b) } else { None } } } "stop" => Cmd::Stop { bot }, "answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string() },