合併: 可靠性一批(自動審核的固定樣式規則、摘要照段落寫與 /compact /context、目標評審自己查證)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
bddef7a56f
16
FEATURES.md
16
FEATURES.md
|
|
@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
|
|||
|
||||
### 「/」清單只放指令
|
||||
|
||||
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
|
||||
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
|
||||
- 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。
|
||||
|
||||
### 上線前補上的防護(安全和資源)
|
||||
|
|
@ -1510,6 +1510,16 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。
|
||||
- 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。
|
||||
|
||||
### 自動審核的固定樣式規則
|
||||
|
||||
- 「無需詢問直接允許」「一律詢問」除了用一般的話寫,也可以寫固定樣式:`shell(git *)`、`file(~/Projects/**)`、`connector(gitlab__*)`、`web(domain:example.com)`、`tool(browser_click)`(* 任何字,? 一個字;檔案的 * 只在一層、** 跨資料夾)。
|
||||
- 樣式在模型之前判斷,每次都一樣,不花模型的錢也不用等:符合「一律詢問」樣式的一定問,模型說允許也沒用(網頁上的字騙不了它);符合允許樣式的直接允許,但如果還有用話寫的「一律詢問」,先讓模型看那幾條;都不符合就照舊把用話寫的規則交給模型。指令要每一段(&&、|、; 分開的)都符合才算允許,有 $()、反引號藏指令的不會被樣式允許。直接操作模式下,「一律詢問」的樣式一樣擋得住。(參考 grok-build 的 Bash(git *) 規則。)
|
||||
|
||||
### 摘要(/context、/compact)
|
||||
|
||||
- 對話太長時(到模型可讀的 70%)把較早的內容整理成摘要。摘要照段落寫:使用者要的、已經決定的、做過的事和結果(指令、路徑、網址、數字照原樣)、還沒完成的、注意(試過不行的)。整理得太短(一大段對話不到 200 字)會再要一次。摘要下面由 AnyBot 自己(不是模型)附上使用者最近 12 句原話(每句最多 400 字)和還在跑的背景指令(#編號和指令),這些不會被摘要弄丟。參考 grok-build 的分段摘要和摘要後的提醒。
|
||||
- 「/context」:這個對話(模型看得到的部分)約幾 token、模型可讀多少、幾 %。「/compact」:現在就整理(Bot 在做事時不行),在背景用快速模型做,好了留一行「已整理:較早的 N 則訊息換成一段摘要」。
|
||||
|
||||
### 用量(/usage)
|
||||
|
||||
- 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。
|
||||
|
|
@ -1548,10 +1558,10 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
- **/goal 目標**(照 Claude Code 的 /goal 做):給 Bot 一個「做到什麼程度才算完成」的條件,它就一輪接一輪做下去,不用每一步都叫它。關鍵是**做事的模型不能自己宣布完成**:每一輪結束後,另一個模型(Bot 的「執行步驟用的模型」,通常是快速模型;設成「關閉」就用 Bot 自己的模型)只看這段對話(Bot 說的話、用了哪些工具、工具回了什麼),判斷條件成立了沒有。
|
||||
- **用法**:「/goal 所有測試都通過,而且 clippy 沒有新的警告」設定並馬上開始做(已經有目標就換掉);「/goal」看目前的目標、做了多久、檢查了幾輪、最近一次檢查的理由;「/goal clear」清除(stop、off、reset、none、cancel、清除、取消、停止也可以)。在 / 清單最上面,標「指令和技能」。電腦、大腦的螢幕、手機打的都算,由大腦處理;訊息管道(Slack、Telegram…)和團隊成員打的不算指令,別人不能替你設目標。條件最多 4000 字;群組聊天還不能設目標。「清除聊天記錄」和「開始新對話」會連目標一起清掉;分享 Bot 的檔案不含目標。
|
||||
- **檢查的結果**:還沒達成 → AnyBot 自己送出一則標「目標」的「還沒達成:(理由)」開始下一輪,理由就是下一步該做什麼;達成 → 聊天裡一行「目標達成:…(N 輪 · 多久)」,目標清掉,這個聊天上撒一下彩帶(慶祝動畫,設定 › 一般可關);做不到 → 「目標做不到,已清除:…」;Bot 在等你回答或動手(登入、付款、做決定)→「目標暫停,等你回覆:…」,不會一直空轉。
|
||||
- **煞車**(比 Claude Code 嚴,因為 AnyBot 一輪可以做很多步、用的是你自己的金鑰):一個目標做 20 輪還沒達成就暫停問你;連續 3 輪都沒有用任何工具(只是在說話)就暫停;這一輪出錯、你按了停止(兩輪之間正在檢查時按也算)、檢查的模型沒回應、AnyBot 重新啟動過,也都是暫停。重新啟動後按中斷卡片上的「繼續」,目標也跟著接下去。暫停時目標還在,**傳一句話(例如「繼續」)就接著做**,用完 20 輪的再給 20 輪;不要了就 /goal clear。
|
||||
- **煞車**(比 Claude Code 嚴,因為 AnyBot 一輪可以做很多步、用的是你自己的金鑰):一個目標做 20 輪還沒達成就暫停問你;連續 3 輪都沒有用任何工具(只是在說話)就暫停;連續兩輪檢查說差的是同一件事(用字稍有不同也算)就暫停「同樣的問題連續兩次」,再做一輪多半還是卡在那裡(參考 grok-build);這一輪出錯、你按了停止(兩輪之間正在檢查時按也算)、檢查的模型沒回應、AnyBot 重新啟動過,也都是暫停。重新啟動後按中斷卡片上的「繼續」,目標也跟著接下去。暫停時目標還在,**傳一句話(例如「繼續」)就接著做**,用完 20 輪的再給 20 輪;不要了就 /goal clear。
|
||||
- **看得到的地方**:輸入框上方一行「目標進行中 · 12 分 · 3 輪」(檢查時是「正在檢查有沒有達成…」,暫停時是「目標暫停 · 原因」),滑過去看條件和最近一次的理由,右邊「清除目標」;窄視窗時字會縮成「…」,不會擠掉按鈕。AnyBot 自己的那幾行(達成、暫停、狀態)在聊天中間用小字顯示,不是 Bot 的話,**不會送給模型**,也不算檢查的證據。手機一樣,大腦的螢幕看到的是大腦同步過來的。
|
||||
- **通知**:目標進行中的每一輪不再各通知一次「完成了」;達成、做不到、暫停時才通知(你不在電腦前時,手機也會收到),例如「Master 達成目標了」「Master 在等你回覆」。
|
||||
- **模型讀到的**:你的「/goal …」後面多一行,說明這是目標、每輪會有另一個模型檢查,所以要用實際的結果證明(指令輸出、測試結果、檔案內容、畫面),需要你做什麼就直接問;「還沒達成」那則後面也提醒它接著做。檢查用的模型讀的是從設定目標那則訊息起的對話(太長就讀最新的約 24000 字;每個工具結果留開頭和結尾,測試的總結通常在最後),並知道已經第幾輪、做了多久,所以條件裡寫「最多 10 輪」也算數。
|
||||
- **模型讀到的**:你的「/goal …」後面多一行,說明這是目標、每輪會有另一個模型檢查,所以要用實際的結果證明(指令輸出、測試結果、檔案內容、畫面),需要你做什麼就直接問;「還沒達成」那則後面也提醒它接著做。檢查用的模型讀的是從設定目標那則訊息起的對話(太長就讀最新的約 24000 字;每個工具結果留開頭和結尾,測試的總結通常在最後),並知道已經第幾輪、做了多久,所以條件裡寫「最多 10 輪」也算數。對話裡的證據不夠時,檢查的模型可以自己查證,最多 3 次、只能看:在 Bot 做事的那台電腦上讀檔(read_file)、看資料夾(list_dir),或讀公開網頁(web_fetch);要求用其他工具(執行指令、寫檔…)會被拒絕,不會真的做。它被要求每一輪用同一個標準:只看目標本身寫的條件,不因為 Bot 做得比上一輪多就提高要求,也不加目標沒寫的條件。
|
||||
- **權限不變**:要你核准的步驟照樣停下來等;要放著讓它自己做完,Bot 要開「直接操作」或「自動審核」(Claude Code 也要配 auto mode)。
|
||||
- **終端機**:`anybot --ask "/goal …"` 會一直做到達成、做不到或暫停才結束(像 `claude -p "/goal …"`),最長 ANYBOT_ASK_SECS 秒(預設 900)。
|
||||
- **`anybot --ask` 給腳本用**:`--json` 每則訊息一行 JSON(type message/approval/learned/done;done 有 ok、code、steps、secs、timed_out、answer,金鑰遮過);`--bot 名字` 問哪個 Bot;`--data-dir 資料夾`(跟 ANYBOT_DATA_DIR 一樣,在讀任何東西之前就設好);`--approve once` 要核准的自動允許一次(問題卡和「需要處理」照樣略過),不給就自動拒絕。結束碼:0 這一輪順利、1 失敗或時間到、130 Ctrl-C(會先停下 Bot)、2 指令寫錯或資料夾裡還沒有 Bot。核准改走跟按鈕一樣的路:以前 App 操作(刪例行任務這類)的核准在這裡會一直等到時間到。
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
## 子功能
|
||||
|
||||
- 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。
|
||||
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md)),打「@」列出其他 Bot。
|
||||
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要),打「@」列出其他 Bot。
|
||||
- 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。
|
||||
- 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。
|
||||
- 停止:工作中、輸入框空著時,送出鈕變成「停止」。
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@
|
|||
## 子功能
|
||||
|
||||
- 設定:「/goal 條件」(最多 4,000 字)。「/goal」看目前的目標,「/goal clear」(或 stop、取消)清除。
|
||||
- 評審:每輪結束後,另一家供應商的模型(不是本機 Ollama,也不是 Bot 自己那家;都沒有才用自己的)讀這段對話判斷:達成、還沒(理由會帶進下一輪)、做不到、在等使用者回覆。
|
||||
- 評審:每輪結束後,另一家供應商的模型(不是本機 Ollama,也不是 Bot 自己那家;都沒有才用自己的)讀這段對話判斷:達成、還沒(理由會帶進下一輪)、做不到、在等使用者回覆。證據不夠時它可以自己查證,最多 3 次,只能看不能改:在 Bot 做事的那台電腦上 `read_file`、`list_dir`,或 `web_fetch` 讀公開網頁;要它做別的會被拒絕。每一輪用同一個標準,不因為 Bot 做得比上一輪多就提高要求。
|
||||
- 只看證據:評審看到的 Bot 自己的話,標成「bot 的說法(不是證據)」;另外附系統從工具紀錄算出的統計(共幾步、幾步失敗、成功送出幾次、送到哪裡),兩者對不上以系統為準。
|
||||
- 下一輪:沒達成時,系統自己送出一則「[目標]還沒達成:理由」開始下一輪。
|
||||
- 煞車:做滿 20 輪先停下來問;連續 3 輪沒有用任何工具(只是在跟評審說話)就停;Bot 在等使用者回答時停;評審沒有回應時停。使用者傳任何一句話就接著做(滿 20 輪的話再給 20 輪)。
|
||||
- 煞車:做滿 20 輪先停下來問;連續 3 輪沒有用任何工具(只是在跟評審說話)就停;連續兩輪評審說差的是同一件事(字稍微不同也算)就停,看起來卡住了;Bot 在等使用者回答時停;評審沒有回應時停。使用者傳任何一句話就接著做(滿 20 輪的話再給 20 輪)。
|
||||
- 達成或做不到:聊天裡留一行結果(花了幾輪),目標清掉。達成、做不到或停下來時,使用者不在電腦前(而且通知開著)會跳通知,手機也收得到。
|
||||
|
||||
## 使用者怎麼到
|
||||
|
|
@ -20,7 +20,7 @@
|
|||
## 怎麼操作
|
||||
|
||||
- Bot:沒有專用工具,照常做事就好。不要用說的宣稱完成,評審只認工具留下的結果;送出類的工作,系統會自己數送出幾次、記下送到哪裡。需要使用者回答就直接問,目標會停下來等。
|
||||
- 驗證:設一個做得到的目標(例如「在工作資料夾建立 hello.txt,內容是 hi」),要看到它自己做完、評審判達成、目標列消失;設一個做不到的,要看到「目標做不到,已清除」;Bot 說做完但工具紀錄沒有,評審不能判達成。自動測試:`cargo test goal::`、`cargo test evidence::`。
|
||||
- 驗證:設一個做得到的目標(例如「在工作資料夾建立 hello.txt,內容是 hi」),要看到它自己做完、評審判達成、目標列消失;設一個做不到的,要看到「目標做不到,已清除」;Bot 說做完但工具紀錄沒有,評審不能判達成;評審查證時不會改到任何檔案。自動測試:`cargo test goal::`、`cargo test evidence::`、`cargo test the_judge_looks_for_itself`。
|
||||
|
||||
## 陷阱
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
|
|||
- 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的(「一律詢問」規則、付款/傳送/刪除的點擊、寄信、傳訊息、AppleScript、打電話、簡訊、在 X 發文、保險庫卡片)也不問,自動審核也略過。仍然擋:安全規則一律拒絕的(下面那串);別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方有一條「一律放行 · Bot 做事不再問你」和「關閉」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。
|
||||
- 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的;畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。
|
||||
- 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。
|
||||
- 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:符合「一律詢問」的樣式一定問(模型說允許也沒用);符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。
|
||||
- 安全規則(你的電腦上):
|
||||
- 一律拒絕:sudo、su、rm -rf /、rm -rf ~、mkfs、dd、shutdown、reboot、diskutil erase、chmod -R 777 /。
|
||||
- 私密檔案不能讀也不能改:AnyBot 自己的資料、.git、.ssh、.gnupg、鑰匙圈、.aws、.env、.pem、.key、id_rsa 這類金鑰、credentials 等。
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@
|
|||
- 做法:有人在看的一輪照舊(共 3 次);沒人在看的(例行任務、事件觸發、訊息管道、團隊成員)共 8 次、最長等 30 秒、±20% 抖動;Retry-After 照給的等(上限照舊 30 秒)。已經開始輸出就不重試(不變)。
|
||||
- 做完:假模型注入 503 五次後成功:沒人看的一輪成功,有人看的照舊 3 次後失敗。
|
||||
|
||||
### R2. 固定樣式的規則先判斷 ⬜
|
||||
### R2. 固定樣式的規則先判斷 ✅(shell、file、connector、web、tool 五種;browser(click:付款*) 沒做——付款/傳送/刪除的點擊本來就每次問)
|
||||
- 做法:「無需詢問直接允許」「一律詢問」多一種寫法:`shell(git *)`、`file(~/Projects/**)`、`connector(gitlab__*)`、`web(domain:example.com)`、`browser(click:付款*)`。先用樣式判斷(拒絕 > 詢問 > 允許;連在一起的指令每一段都要符合才算允許),判斷不了的才交給模型;模型說允許不能蓋過樣式的詢問。
|
||||
- 做完:表格測試;`git status && rm -rf x` 不會因為 `shell(git *)` 被允許。
|
||||
|
||||
|
|
@ -75,11 +75,11 @@
|
|||
- 做法:指令輸出、連接器結果、網頁內容超過上限時,完整內容存到 Bot 的資料夾 `outputs/`,截短的那份寫「完整內容在 …」;舊結果收起時也一樣(不再叫 Bot「再跑一次」)。
|
||||
- 做完:一個 50 萬字的輸出,Bot 拿到頭尾和檔案路徑,檔案內容完整。
|
||||
|
||||
### R4. 摘要的品質、手動 /compact、/context ⬜
|
||||
### R4. 摘要的品質、手動 /compact、/context ✅(計畫進度本來就每一輪在系統指示裡,摘要不另外寫)
|
||||
- 做法:摘要用分段的提示(目標、做了什麼、檔案、未完成、使用者原話全留);摘要太短就重做一次;摘要後提醒還在跑的背景指令和計畫進度。`/compact` 現在就整理,`/context` 看用了多少。
|
||||
- 做完:測試涵蓋太短重做、背景指令提醒。
|
||||
|
||||
### R5. 目標評審能自己看 ⬜
|
||||
### R5. 目標評審能自己看 ✅(截圖先不給:評審用的常常是別家的模型,看圖的能力不一定有;讀檔和網頁已經夠查證)
|
||||
- 做法:評審可以用只看的工具(讀檔、web_fetch、截圖)查證;同一個「還沒達成」理由連兩次就暫停問;提示加「不要每輪提高標準」。
|
||||
- 做完:評審用工具讀檔確認的測試;同理由兩次暫停的測試。
|
||||
|
||||
|
|
|
|||
|
|
@ -1656,7 +1656,7 @@ input.addEventListener("keydown", (e) => {
|
|||
input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } });
|
||||
const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false};
|
||||
/** AnyBot's own / commands (goal.rs on the brain). */
|
||||
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
|
||||
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
|
||||
const GOAL_TAG = "[目標]";
|
||||
/** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name
|
||||
* contains it, then description. None once a space ends the name, or while the bot works. */
|
||||
|
|
@ -1754,7 +1754,7 @@ async function send() {
|
|||
const memories = b.busy ? undefined : memPicks();
|
||||
memReset();
|
||||
input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash();
|
||||
const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor)\s*$/i.test(text);
|
||||
const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text);
|
||||
if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; }
|
||||
// 先顯示: while it works the words aren't in the chat yet — shown at once all the same.
|
||||
const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null;
|
||||
|
|
|
|||
191
src/agent.rs
191
src/agent.rs
|
|
@ -206,7 +206,26 @@ pub const REVIEW_FAILED_NOTE: &str = "(自動審核沒有回應,所以先問
|
|||
|
||||
/// Ask the model whether an action matches the person's rules. "Ask first" wins on conflict
|
||||
/// (NFRGrQ: 規則衝突時,「先詢問」優先); built-in safety checks have already run before this.
|
||||
fn review_action(job: &Job, review: &Review, action: &str, cancel: &AtomicBool) -> ReviewVerdict {
|
||||
/// 自動審核: the pattern rules first (gate::patterns — the same every time; an ask pattern can't be
|
||||
/// talked out of), then the sentence rules by the model. A pattern allow still yields to a
|
||||
/// sentence 「一律詢問」 the model finds.
|
||||
fn review_action(job: &Job, review: &Review, name: &str, args: &str, action: &str, cancel: &AtomicBool) -> ReviewVerdict {
|
||||
use crate::gate::{is_pattern, patterns, PatternVerdict};
|
||||
let words = |v: &[String]| v.iter().filter(|r| !is_pattern(r)).cloned().collect::<Vec<_>>();
|
||||
match patterns(name, args, &review.allow, &review.ask) {
|
||||
PatternVerdict::Ask(rule) => ReviewVerdict::Ask(rule),
|
||||
PatternVerdict::Allow(rule) => match words(&review.ask) {
|
||||
ask if ask.is_empty() => ReviewVerdict::Allow(rule),
|
||||
ask => match review_by_model(job, &Review { allow: vec![], ask }, action, cancel) {
|
||||
ReviewVerdict::NoMatch | ReviewVerdict::Allow(_) => ReviewVerdict::Allow(rule),
|
||||
other => other,
|
||||
},
|
||||
},
|
||||
PatternVerdict::NoMatch => review_by_model(job, &Review { allow: words(&review.allow), ask: words(&review.ask) }, action, cancel),
|
||||
}
|
||||
}
|
||||
|
||||
fn review_by_model(job: &Job, review: &Review, action: &str, cancel: &AtomicBool) -> ReviewVerdict {
|
||||
if review.allow.is_empty() && review.ask.is_empty() {
|
||||
return ReviewVerdict::NoMatch;
|
||||
}
|
||||
|
|
@ -941,7 +960,7 @@ pub fn estimate_tokens(s: &str) -> u64 {
|
|||
ascii / 4 + other
|
||||
}
|
||||
|
||||
fn history_tokens(system: &str, h: &[Message]) -> u64 {
|
||||
pub fn history_tokens(system: &str, h: &[Message]) -> u64 {
|
||||
// Pictures as they are sent: a step's screenshot only while it is one of the newest
|
||||
// KEEP_SCREENSHOTS (older ones go as a note, see providers::kept_images); counting every one
|
||||
// of a fifty-step task made compaction come early and shrink results the bot still needed.
|
||||
|
|
@ -1033,6 +1052,86 @@ pub fn fold_results(history: &mut [Message]) -> Vec<String> {
|
|||
/// (fold_results); only if that isn't enough, fold older messages into one summary, written by
|
||||
/// the quick model when the bot has one (it is a tidy-up, not thinking). `percent` 0: the model
|
||||
/// itself said the chat is too long — do both. Returns how many messages the summary replaced.
|
||||
/// 摘要 (R4): what the summary is asked to keep, in sections, so the model after it can go on
|
||||
/// without the original (grok-build's sectioned compaction prompt).
|
||||
const SUMMARY_SYSTEM: &str = "你負責把一段對話整理成摘要,讓接著做的模型不看原文也能接下去。照下面的段落寫,每段用條列,沒有內容的段落寫「(無)」,不要加入對話裡沒有的東西:
|
||||
## 使用者要的
|
||||
(目標、偏好、限制)
|
||||
## 已經決定的
|
||||
## 做過的事和結果
|
||||
(成功和失敗的都寫;指令、檔案路徑、網址、數字照原樣)
|
||||
## 還沒完成的
|
||||
(下一步做什麼)
|
||||
## 注意
|
||||
(試過不行的做法、不要再做的事)";
|
||||
|
||||
/// A summary shorter than this (of a long stretch) is asked for once more.
|
||||
const SUMMARY_MIN_CHARS: usize = 200;
|
||||
/// The person's own words kept word for word under a summary: the newest this many, each clipped.
|
||||
const SUMMARY_PERSON_WORDS: usize = 12;
|
||||
const SUMMARY_PERSON_CHARS: usize = 400;
|
||||
|
||||
thread_local! {
|
||||
/// The bot whose turn runs on this thread (its background commands are named under a summary).
|
||||
static TURN_BOT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The summary of `part` by the quick model (the bot's own when it has none): the sections, a
|
||||
/// second try when it came back too short, then the person's own words as they wrote them and
|
||||
/// the background commands still running (both from AnyBot, not the model: they can't be lost).
|
||||
pub fn summarize(base: &ChatRequest, quick: Option<&str>, part: &[Message], cancel: &AtomicBool, quiet: &dyn Fn(StreamEvent)) -> Option<String> {
|
||||
let flat = flatten(part);
|
||||
let ask = |extra: &str| {
|
||||
let req = ChatRequest {
|
||||
system: SUMMARY_SYSTEM.into(),
|
||||
history: vec![Message::user(&format!("請整理下面這段對話:{extra}\n\n{flat}"))],
|
||||
tools: vec![],
|
||||
model: quick.map(String::from).unwrap_or_else(|| base.model.clone()),
|
||||
effort: String::new(),
|
||||
..base.clone()
|
||||
};
|
||||
providers::run_step(&req, cancel, quiet).ok().map(|o| o.text.trim().to_string())
|
||||
};
|
||||
let mut text = ask("")?;
|
||||
if text.chars().count() < SUMMARY_MIN_CHARS && flat.chars().count() > SUMMARY_MIN_CHARS * 10 && !cancel.load(Ordering::Relaxed) {
|
||||
if let Some(again) = ask("(上一次整理得太短,請照段落寫完整)").filter(|t| t.chars().count() > text.chars().count()) {
|
||||
text = again;
|
||||
}
|
||||
}
|
||||
if text.is_empty() || cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
Some(with_what_must_stay(&text, part, TURN_BOT.with(|b| b.get())))
|
||||
}
|
||||
|
||||
/// The bot whose summaries this thread writes (its background commands are named under them).
|
||||
pub fn set_turn_bot(bot: u64) {
|
||||
TURN_BOT.with(|b| b.set(bot));
|
||||
}
|
||||
|
||||
/// Under a summary: the person's own words (the newest, word for word) and the bot's background
|
||||
/// commands still running.
|
||||
pub fn with_what_must_stay(summary: &str, part: &[Message], bot: u64) -> String {
|
||||
let mut out = summary.to_string();
|
||||
let said: Vec<String> = part.iter().filter(|m| m.role == Role::User && !m.wake && !m.summary && !m.text.trim().is_empty()).map(|m| m.text.trim().chars().take(SUMMARY_PERSON_CHARS).collect::<String>()).collect();
|
||||
if !said.is_empty() {
|
||||
out.push_str("\n\n## 使用者的原話(最近的,照原文)");
|
||||
for w in said.iter().skip(said.len().saturating_sub(SUMMARY_PERSON_WORDS)) {
|
||||
out.push_str(&format!("\n- 「{}」", w.replace('\n', " ")));
|
||||
}
|
||||
}
|
||||
if bot != 0 {
|
||||
let running = tools::running_for(&bot.to_string());
|
||||
if !running.is_empty() {
|
||||
out.push_str("\n\n## 還在跑的背景指令(用 read_terminal 看)");
|
||||
for (id, cmd) in running {
|
||||
out.push_str(&format!("\n- #{id}:{}", cmd.chars().take(120).collect::<String>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn maybe_compact(job: &Job, history: &mut Vec<Message>, percent: u64, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option<usize> {
|
||||
// (The tools' descriptions go with every request too: ~12 000 tokens for a bot with all.)
|
||||
let tools = tools_tokens(&job.req.tools);
|
||||
|
|
@ -1052,11 +1151,6 @@ fn maybe_compact(job: &Job, history: &mut Vec<Message>, percent: u64, cancel: &A
|
|||
let cut = compaction_cut(history)?;
|
||||
send(StreamEvent::Retrying("對話很長了,正在把較早的內容整理成摘要…".into()));
|
||||
let req = ChatRequest {
|
||||
system: "你負責把一段對話整理成摘要,讓之後的對話能接著進行。請用條列寫下:使用者的目標與偏好、已經做出的決定、重要的事實與數字、提到的檔案路徑與指令結果、還沒完成的事。不要加入對話裡沒有的內容。".into(),
|
||||
history: vec![Message::user(&format!("請整理下面這段對話:\n\n{}", flatten(&history[..cut])))],
|
||||
tools: vec![],
|
||||
model: job.step_model.clone().unwrap_or_else(|| job.req.model.clone()),
|
||||
effort: String::new(),
|
||||
..job.req.clone()
|
||||
};
|
||||
let quiet = |ev: StreamEvent| {
|
||||
|
|
@ -1065,11 +1159,8 @@ fn maybe_compact(job: &Job, history: &mut Vec<Message>, percent: u64, cancel: &A
|
|||
}
|
||||
};
|
||||
job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 });
|
||||
let out = providers::run_step(&req, cancel, &quiet).ok()?;
|
||||
if out.text.trim().is_empty() || cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let summary = Message { role: Role::Assistant, text: out.text.trim().to_string(), summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() };
|
||||
let text = summarize(&req, job.step_model.as_deref(), &history[..cut], cancel, &quiet)?;
|
||||
let summary = Message { role: Role::Assistant, text, summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() };
|
||||
// The window shows the chat unfiltered (group chats drop some messages on the way here);
|
||||
// the timestamp of the first kept message is the landmark it can find the cut by.
|
||||
let boundary = history[cut].at;
|
||||
|
|
@ -1224,25 +1315,15 @@ fn turn_cut(h: &[Message]) -> Option<(usize, usize)> {
|
|||
fn compact_within_turn(job: &Job, history: &mut Vec<Message>, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option<usize> {
|
||||
let (ask, cut) = turn_cut(history)?;
|
||||
send(StreamEvent::Retrying("對話太長了,正在把這一輪較早的步驟整理成摘要…".into()));
|
||||
let req = ChatRequest {
|
||||
system: "你負責把一段對話整理成摘要,讓之後的對話能接著進行。請用條列寫下:使用者的目標與偏好、已經做出的決定、已經完成的步驟和結果(哪些成功、哪些失敗)、重要的事實與數字、提到的檔案路徑與網址、還沒完成的事。不要加入對話裡沒有的內容。".into(),
|
||||
history: vec![Message::user(&format!("請整理下面這段對話:\n\n{}", flatten(&history[..cut])))],
|
||||
tools: vec![],
|
||||
model: job.step_model.clone().unwrap_or_else(|| job.req.model.clone()),
|
||||
effort: String::new(),
|
||||
..job.req.clone()
|
||||
};
|
||||
let req = ChatRequest { ..job.req.clone() };
|
||||
let quiet = |ev: StreamEvent| {
|
||||
if matches!(ev, StreamEvent::Alive | StreamEvent::Retrying(_)) {
|
||||
send(StreamEvent::Alive);
|
||||
}
|
||||
};
|
||||
job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 });
|
||||
let out = providers::run_step(&req, cancel, &quiet).ok()?;
|
||||
if out.text.trim().is_empty() || cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let summary = Message { role: Role::Assistant, text: out.text.trim().to_string(), summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() };
|
||||
let text = summarize(&req, job.step_model.as_deref(), &history[..cut], cancel, &quiet)?;
|
||||
let summary = Message { role: Role::Assistant, text, summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() };
|
||||
let request = history[ask].clone();
|
||||
history.splice(..cut, [summary, request]);
|
||||
Some(cut)
|
||||
|
|
@ -1607,6 +1688,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
|||
let _screens = ScreensBack(bot_id);
|
||||
let mut job = job;
|
||||
crate::providers::set_patient(job.unattended);
|
||||
TURN_BOT.with(|b| b.set(bot_id));
|
||||
let send = |ev: StreamEvent| {
|
||||
let _ = tx.send((bot_id, ev));
|
||||
ctx.request_repaint();
|
||||
|
|
@ -3104,7 +3186,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
|||
// call to check (it cost every look at the person's Mac 10–20 s).
|
||||
let looks = matches!(call.name.as_str(), "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "browser_read" | "read_file" | "list_dir" | "search");
|
||||
let verdict = match review {
|
||||
Some(rv) if !rv.ask.is_empty() && !looks => review_action(&job, &Review { allow: vec![], ask: rv.ask.clone() }, &reason, &cancel),
|
||||
Some(rv) if !rv.ask.is_empty() && !looks => review_action(&job, &Review { allow: vec![], ask: rv.ask.clone() }, &call.name, &call.args, &reason, &cancel),
|
||||
_ => ReviewVerdict::NoMatch,
|
||||
};
|
||||
match verdict {
|
||||
|
|
@ -3124,7 +3206,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
|||
}
|
||||
}
|
||||
}
|
||||
(Decision::Ask { reason, grant }, Some(rv)) => match review_action(&job, rv, &reason, &cancel) {
|
||||
(Decision::Ask { reason, grant }, Some(rv)) => match review_action(&job, rv, &call.name, &call.args, &reason, &cancel) {
|
||||
ReviewVerdict::Allow(rule) => {
|
||||
review_note = format!("(自動審核:符合「{rule}」,直接允許)\n");
|
||||
Decision::Allow
|
||||
|
|
@ -5477,6 +5559,54 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
|||
assert!(matches!(evs.last(), Some(StreamEvent::Done)));
|
||||
}
|
||||
|
||||
/// R2: in 直接操作, an 「一律詢問」 pattern stops the step and asks — decided without a model
|
||||
/// call (the fake model is asked for the turn's two steps only), and named on the card.
|
||||
#[test]
|
||||
fn an_ask_pattern_stops_direct_mode_without_asking_a_model() {
|
||||
let call = serde_json::json!({"command": "echo hi > made.txt", "computer": crate::model::THIS_COMPUTER_NAME});
|
||||
let (port, seen) = fake_http(vec![sse_call("c1", "shell", call), sse_text("好,不做")]);
|
||||
let w = std::env::temp_dir().join(format!("anybot-pattern-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
std::fs::create_dir_all(&w).unwrap();
|
||||
let job = Job {
|
||||
req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("做一個檔案")], tools: tools::specs(), session: String::new(), effort: String::new() },
|
||||
computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }],
|
||||
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
||||
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
||||
local_execution: true,
|
||||
direct: Arc::new(AtomicBool::new(true)),
|
||||
review: Some(Review { allow: vec![], ask: vec!["shell(echo *)".into()] }),
|
||||
..test_job()
|
||||
};
|
||||
let (evs, asked) = drive(job, ApprovalAnswer::Reject);
|
||||
assert_eq!(asked.len(), 1, "{asked:?}");
|
||||
assert!(asked[0].contains("符合你的「一律詢問」規則:shell(echo *)"), "{}", asked[0]);
|
||||
assert_eq!(seen.lock().unwrap().len(), 2, "no model call to review it");
|
||||
assert!(!w.join("made.txt").exists());
|
||||
assert!(matches!(evs.last(), Some(StreamEvent::Done)));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
|
||||
/// R4: a summary that comes back too short is asked for once more; under it, the person's
|
||||
/// own words as they wrote them (the newest) — from AnyBot, so they can't be lost.
|
||||
#[test]
|
||||
fn a_summary_keeps_the_persons_words_and_is_not_too_short() {
|
||||
use crate::testkit::{Fake, Reply};
|
||||
let long = "## 使用者要的\n- 把部落格搬到新主機\n".repeat(20);
|
||||
let fake = Fake::openai(vec![Reply::text("太短"), Reply::text(&long)]);
|
||||
let req = ChatRequest { kind: ProviderKind::Custom, base_url: fake.base(), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![], tools: vec![], session: String::new(), effort: String::new() };
|
||||
let mut part = vec![];
|
||||
for i in 0..30 {
|
||||
part.push(Message::user(&format!("第 {i} 件事:請把這個資料夾裡的檔案整理好,留下最新的版本,其他移到封存。")));
|
||||
part.push(Message::assistant(&format!("好,第 {i} 件做完了,移了 3 個檔案到封存。"), "m"));
|
||||
}
|
||||
let out = summarize(&req, None, &part, &AtomicBool::new(false), &|_| {}).unwrap();
|
||||
assert!(out.starts_with("## 使用者要的"), "the longer, second answer: {out}");
|
||||
assert_eq!(fake.requests(), 2);
|
||||
assert!(out.contains("## 使用者的原話(最近的,照原文)") && out.contains("「第 29 件事") && !out.contains("「第 17 件事"), "the newest 12: {out}");
|
||||
assert_eq!(fake.bodies.lock().unwrap()[0]["messages"][0]["content"].as_str().map(|s| s.contains("## 還沒完成的")), Some(true), "the sections are asked for");
|
||||
}
|
||||
|
||||
/// 問題卡: the turn waits on the card; the answers come back numbered, a skip says so.
|
||||
#[test]
|
||||
fn a_question_card_waits_and_brings_back_the_answers() {
|
||||
|
|
@ -5636,7 +5766,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
|||
/// step is asked again (with the summary), instead of the turn failing.
|
||||
#[test]
|
||||
fn an_overflow_folds_the_chat_and_asks_again() {
|
||||
let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), sse_text("摘要:問過六個問題"), sse_text("好了")]);
|
||||
let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), sse_text(&format!("摘要:問過六個問題。{}", "(這段摘要夠長,不會被要求再寫一次)".repeat(12))), sse_text("好了")]);
|
||||
let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: long_chat(), tools: vec![], session: String::new(), effort: String::new() }, ..test_job() };
|
||||
let (evs, _) = drive(job, ApprovalAnswer::Reject);
|
||||
assert!(matches!(evs.last(), Some(StreamEvent::Done)), "{:?}", evs.iter().filter_map(|e| if let StreamEvent::Error(e) = e { Some(e.clone()) } else { None }).collect::<Vec<_>>());
|
||||
|
|
@ -5647,7 +5777,8 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
|||
assert_eq!(texts, vec!["好了"]);
|
||||
let seen = seen.lock().unwrap();
|
||||
assert_eq!(seen.len(), 3);
|
||||
assert!(seen[2].contains("摘要:問過六個問題") && !seen[2].contains("第 0 個問題"), "{}", seen[2]);
|
||||
// The folded answers are gone; the person's own words stay, word for word, under the summary.
|
||||
assert!(seen[2].contains("摘要:問過六個問題") && !seen[2].contains("第 0 個回答") && seen[2].contains("## 使用者的原話") && seen[2].contains("「第 0 個問題」"), "{}", seen[2]);
|
||||
}
|
||||
|
||||
/// jenny-Host, 2026-11-14 18:10: one screenshot took a request to a gateway that reads it as
|
||||
|
|
@ -5683,7 +5814,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
|||
/// earlier steps are summarized inside it — the request stays, the newest steps stay.
|
||||
#[test]
|
||||
fn a_long_turn_with_one_request_is_summarized_inside_itself() {
|
||||
let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), (400, OVERFLOW_BODY.into()), sse_text("摘要:前面的步驟做完了"), sse_text("完成")]);
|
||||
let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), (400, OVERFLOW_BODY.into()), sse_text(&format!("摘要:前面的步驟做完了。{}", "(這段摘要夠長,不會被要求再寫一次)".repeat(12))), sse_text("完成")]);
|
||||
let mut history = vec![Message::user("把十件事做完")];
|
||||
for i in 0..10 {
|
||||
let call = ToolCall { id: format!("c{i}"), name: "shell".into(), args: serde_json::json!({"command": format!("echo step-{i}")}).to_string(), status: ToolStatus::Done };
|
||||
|
|
|
|||
73
src/app.rs
73
src/app.rs
|
|
@ -43,6 +43,7 @@ mod voice_ui;
|
|||
mod drops_ui;
|
||||
mod memory_ui;
|
||||
mod goal_ui;
|
||||
mod context_ui;
|
||||
mod doctor_ui;
|
||||
mod plan_ui;
|
||||
mod mood_ui;
|
||||
|
|
@ -211,6 +212,9 @@ pub struct App {
|
|||
want_direct: std::cell::Cell<bool>,
|
||||
/// 診斷 (/doctor) reports finished on their thread: (the chat it was asked in, the report).
|
||||
doctor_out: Arc<Mutex<Vec<(u64, String)>>>,
|
||||
/// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)).
|
||||
#[allow(clippy::type_complexity)]
|
||||
compact_out: Arc<Mutex<Vec<(u64, Option<(usize, Message, i64)>)>>>,
|
||||
/// Bots whose running turn came from someone else's message (a channel, a teammate):
|
||||
/// 一律放行 doesn't answer for them.
|
||||
strangers: std::collections::HashSet<u64>,
|
||||
|
|
@ -490,6 +494,7 @@ impl App {
|
|||
want_direct: Default::default(),
|
||||
strangers: Default::default(),
|
||||
doctor_out: Default::default(),
|
||||
compact_out: Default::default(),
|
||||
managed: if demo { policy::Managed::default() } else { policy::read() },
|
||||
settings_was_open: false,
|
||||
exe_built: crate::version::exe_modified(),
|
||||
|
|
@ -1421,7 +1426,7 @@ impl App {
|
|||
}
|
||||
// 先顯示: while it works (or the words travel to the brain) they aren't in the chat
|
||||
// yet — the person sees them at once all the same. (A command here draws its own line.)
|
||||
let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some() || crate::always::command(&text).is_some() || crate::usage::command(&text));
|
||||
let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some() || crate::always::command(&text).is_some() || crate::usage::command(&text) || matches!(text.trim(), "/context" | "/compact"));
|
||||
if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command {
|
||||
self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now()));
|
||||
}
|
||||
|
|
@ -1476,6 +1481,18 @@ impl App {
|
|||
self.usage_note(bot_id);
|
||||
return;
|
||||
}
|
||||
// 對話的長度: 「/context」 how full it is, 「/compact」 fold the older part now.
|
||||
match text.trim() {
|
||||
"/context" => {
|
||||
self.context_note(bot_id);
|
||||
return;
|
||||
}
|
||||
"/compact" => {
|
||||
self.compact_now(bot_id);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.goal_heard(bot_id);
|
||||
// While it works, a new message steers the running turn (the original's `turnSteer`:
|
||||
// it doesn't count as a new turn) and reaches the model at its next step.
|
||||
|
|
@ -5631,7 +5648,7 @@ impl App {
|
|||
}
|
||||
});
|
||||
});
|
||||
hint(ui, "為每種操作寫一條簡短的自然語言規則。規則衝突時,「先詢問」優先。這些規則只對你生效。內建的安全檢查一律有效。", p);
|
||||
hint(ui, "為每種操作寫一條簡短的自然語言規則。規則衝突時,「先詢問」優先。這些規則只對你生效。內建的安全檢查一律有效。也可以寫成固定樣式,每次判斷都一樣、不用等模型:shell(git *)、file(~/Projects/**)、connector(gitlab__*)、web(domain:example.com)、tool(browser_click)。", p);
|
||||
if !self.state.auto_review {
|
||||
hint(ui, "自動審核關閉時不會使用規則", p);
|
||||
}
|
||||
|
|
@ -5969,8 +5986,9 @@ impl App {
|
|||
if !self.demo {
|
||||
self.tell_crashes();
|
||||
}
|
||||
// 診斷: a 「/doctor」 that finished.
|
||||
// 診斷: a 「/doctor」 that finished; a 「/compact」 too.
|
||||
self.doctor_tick();
|
||||
self.compact_tick();
|
||||
// A screen of another AnyBot's brain: its bots work there, not here.
|
||||
if self.mir.on {
|
||||
self.remote_tick(ctx);
|
||||
|
|
@ -8069,6 +8087,53 @@ mod tests {
|
|||
assert_eq!(app.state.bot(id).unwrap().name, name);
|
||||
}
|
||||
|
||||
/// R4: 「/context」 says how full the chat is; 「/compact」 folds the older part into a summary
|
||||
/// now (the person's words kept under it) and says so — the chat stays whole, the model reads
|
||||
/// from the summary on.
|
||||
#[test]
|
||||
fn context_and_compact_from_the_chat() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-compact.png")));
|
||||
let fake = crate::testkit::Fake::openai(vec![crate::testkit::Reply::text(&"## 使用者要的\n- 整理資料夾\n".repeat(30))]);
|
||||
app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = fake.base();
|
||||
let id = app.state.bots[0].id;
|
||||
{
|
||||
let b = app.state.bot_mut(id).unwrap();
|
||||
b.provider = crate::providers::ProviderKind::Custom;
|
||||
b.model = "m".into();
|
||||
b.step_model = "off".into();
|
||||
b.messages.clear();
|
||||
for i in 0..20 {
|
||||
b.messages.push(Message { at: 1_000 + i * 2, ..Message::user(&format!("第 {i} 個問題")) });
|
||||
b.messages.push(Message { at: 1_001 + i * 2, ..Message::assistant(&format!("第 {i} 個回答"), "m") });
|
||||
}
|
||||
}
|
||||
let say = |app: &mut super::App, t: &str| {
|
||||
app.drafts.insert(id, t.into());
|
||||
app.send(&ctx, id);
|
||||
};
|
||||
say(&mut app, "/context");
|
||||
assert!(app.state.bot(id).unwrap().messages.last().is_some_and(|m| m.note && m.text.contains("token") && m.text.contains("/compact")));
|
||||
let before = app.state.bot(id).unwrap().messages.len();
|
||||
say(&mut app, "/compact");
|
||||
let mut done = false;
|
||||
for _ in 0..200 {
|
||||
app.compact_tick();
|
||||
if app.state.bot(id).unwrap().messages.iter().any(|m| m.note && m.text.starts_with("已整理")) {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
assert!(done, "the summary came back");
|
||||
let b = app.state.bot(id).unwrap();
|
||||
let s = b.messages.iter().find(|m| m.summary).expect("a summary in the chat");
|
||||
assert!(s.text.starts_with("## 使用者要的") && s.text.contains("## 使用者的原話") && s.text.contains("「第"), "{}", s.text);
|
||||
// (Nothing leaves the chat: the model reads from the summary on.)
|
||||
let view = b.messages.len() - crate::model::model_view_start(&b.messages);
|
||||
assert!(b.messages.len() > before && view < before / 2, "the model's view got short ({view} of {})", b.messages.len());
|
||||
}
|
||||
|
||||
/// E10: `anybot --ask` reads its options anywhere among the words, and says by its exit
|
||||
/// code how the turn went.
|
||||
#[test]
|
||||
|
|
@ -8495,7 +8560,7 @@ mod tests {
|
|||
let mut bot = app.state.bots[0].clone();
|
||||
bot.skills = Some(vec!["週報".into()]);
|
||||
let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::<Vec<_>>();
|
||||
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor"]);
|
||||
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact"]);
|
||||
assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word");
|
||||
assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1134,7 +1134,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool {
|
|||
}
|
||||
|
||||
/// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs).
|
||||
pub const SLASH_COMMANDS: [(&str, &str); 6] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟")];
|
||||
pub const SLASH_COMMANDS: [(&str, &str); 8] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要")];
|
||||
|
||||
/// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone).
|
||||
/// A status of several lines — a retry: the error, what it means, when it tries again — used to
|
||||
|
|
|
|||
|
|
@ -0,0 +1,86 @@
|
|||
// 對話的長度 (R4): 「/context」 says how much of what the model can read this chat uses, and
|
||||
// 「/compact」 folds its older part into a summary now (on a thread, by the quick model), the same
|
||||
// way a turn does it at COMPACT_THRESHOLD_PERCENT (agent::summarize).
|
||||
|
||||
use super::*;
|
||||
|
||||
impl App {
|
||||
/// 「/context」: a line in this chat.
|
||||
pub(super) fn context_note(&mut self, bot_id: u64) {
|
||||
let Some(b) = self.state.bot(bot_id) else { return };
|
||||
let start = crate::model::model_view_start(&b.messages);
|
||||
let used = agent::history_tokens("", &b.messages[start..]);
|
||||
let limit = b.context_tokens.max(4_000);
|
||||
let text = format!(
|
||||
"這個對話(模型看得到的部分)約 {} token,{} 可讀 {} token,約 {}%(系統指示和工具說明另外大約幾千到一萬多 token)。到 {}% 會自動把較早的內容整理成摘要;要現在整理打 /compact。",
|
||||
used,
|
||||
b.model,
|
||||
limit,
|
||||
used * 100 / limit,
|
||||
agent::COMPACT_THRESHOLD_PERCENT
|
||||
);
|
||||
self.goal_note(bot_id, &text);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// 「/compact」: the older part of this chat into a summary now (compact_tick takes it in).
|
||||
pub(super) fn compact_now(&mut self, bot_id: u64) {
|
||||
let Some(b) = self.state.bot(bot_id).cloned() else { return };
|
||||
if self.streams.contains_key(&bot_id) {
|
||||
self.goal_note(bot_id, &format!("{} 正在做事:等它做完再 /compact(太長時它自己也會整理)。", b.name));
|
||||
return;
|
||||
}
|
||||
let start = crate::model::model_view_start(&b.messages);
|
||||
let view: Vec<Message> = b.messages[start..].iter().filter(|m| !m.note).cloned().collect();
|
||||
let Some(cut) = agent::compaction_cut(&view) else {
|
||||
self.goal_note(bot_id, "對話還很短,不用整理。");
|
||||
return;
|
||||
};
|
||||
let ps = self.state.provider(b.provider);
|
||||
let req = ChatRequest {
|
||||
kind: b.provider,
|
||||
base_url: providers::resolve_base(b.provider, &ps.base_url),
|
||||
api_key: providers::resolve_key_for(b.provider, &ps.api_key, &ps.base_url),
|
||||
model: b.model.clone(),
|
||||
system: String::new(),
|
||||
history: vec![],
|
||||
tools: vec![],
|
||||
session: format!("anybot-bot-{bot_id}"),
|
||||
effort: String::new(),
|
||||
};
|
||||
let quick = match b.step_model.trim() {
|
||||
"off" => None,
|
||||
"" => b.provider.quick_model(&b.model).map(String::from),
|
||||
m if m == b.model => None,
|
||||
m => Some(m.to_string()),
|
||||
};
|
||||
self.goal_note(bot_id, "正在把較早的對話整理成摘要…");
|
||||
let (out, repaint) = (self.compact_out.clone(), self.repaint_fn());
|
||||
std::thread::spawn(move || {
|
||||
agent::set_turn_bot(bot_id);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let got = agent::summarize(&req, quick.as_deref(), &view[..cut], &cancel, &|_| {});
|
||||
out.lock().unwrap().push((bot_id, got.map(|text| (cut, Message { role: Role::Assistant, text, summary: true, via: b.model.clone(), at: crate::model::now_ms(), ..Default::default() }, view[cut].at))));
|
||||
repaint();
|
||||
});
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// A finished 「/compact」: the summary takes the older part's place (as a turn's does).
|
||||
pub(super) fn compact_tick(&mut self) {
|
||||
let done = std::mem::take(&mut *self.compact_out.lock().unwrap());
|
||||
for (bot_id, got) in done {
|
||||
match got {
|
||||
Some((n, summary, boundary)) => {
|
||||
if let Some(b) = self.state.bot_mut(bot_id) {
|
||||
crate::model::fold_in(&mut b.messages, n, summary, boundary);
|
||||
}
|
||||
self.goal_note(bot_id, &format!("已整理:較早的 {n} 則訊息換成一段摘要(你說過的話照原文留在摘要下面)。"));
|
||||
}
|
||||
None => self.goal_note(bot_id, "沒有整理成:模型沒有回應,稍後再試。"),
|
||||
}
|
||||
self.dirty = true;
|
||||
self.save_now = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -11,6 +11,33 @@
|
|||
use super::*;
|
||||
use crate::goal::{self, Command, Goal, Judged, Next};
|
||||
|
||||
/// The judge's answer, after up to JUDGE_LOOKS rounds of looking for itself with the read-only
|
||||
/// tools (anything else it asks for is refused, not run).
|
||||
pub(super) fn judge_with_looks(req: &ChatRequest, target: Option<&crate::tools::Target>, bot_id: u64, cancel: &AtomicBool) -> Result<String, String> {
|
||||
let mut req = req.clone();
|
||||
for round in 0..=goal::JUDGE_LOOKS {
|
||||
if round == goal::JUDGE_LOOKS {
|
||||
// Out of looks: it says now, without tools.
|
||||
req.tools.clear();
|
||||
req.history.push(Message::user("查證的次數用完了。現在只回 JSON。"));
|
||||
}
|
||||
let out = providers::run_step(&req, cancel, &|_| {})?;
|
||||
if out.tool_calls.is_empty() {
|
||||
return Ok(out.text);
|
||||
}
|
||||
req.history.push(Message { tool_calls: out.tool_calls.clone(), blocks: out.blocks.clone(), ..Message::assistant(&out.text, &req.model) });
|
||||
for c in &out.tool_calls {
|
||||
let (text, _) = match (c.name.as_str(), target) {
|
||||
("web_fetch", _) => crate::web::run("web_fetch", &c.args, cancel),
|
||||
(n, Some(t)) if goal::JUDGE_TOOLS.contains(&n) => crate::tools::run_on(n, &c.args, t, cancel, &crate::tools::RunIds { conversation: bot_id.to_string(), request: format!("judge-{}", c.id) }),
|
||||
_ => (format!("檢查目標時不能用「{}」:只能用 {}。", c.name, goal::JUDGE_TOOLS.join("、")), false),
|
||||
};
|
||||
req.history.push(Message::tool_result(&c.id, &c.name, &crate::tools::head_tail(&text)));
|
||||
}
|
||||
}
|
||||
Err("檢查目標時一直在查證,沒有給答案".into())
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// 「/goal …」: show, clear, or set the goal and start on it.
|
||||
pub(super) fn goal_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: Command, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) {
|
||||
|
|
@ -185,6 +212,17 @@ impl App {
|
|||
session: format!("anybot-goal-{bot_id}"),
|
||||
effort: String::new(),
|
||||
};
|
||||
// It may look for itself (R5): read files and folders where the bot works, read public
|
||||
// pages — nothing that changes anything.
|
||||
let targets = self.targets_for(b);
|
||||
let roles = self.roles_for(b, &targets);
|
||||
let (chosen, _) = Self::chosen_computer(b, &targets, &roles);
|
||||
let target = targets.iter().find(|t| t.name == chosen).cloned();
|
||||
let tools: Vec<serde_json::Value> = match &target {
|
||||
Some(t) => crate::tools::specs_for(std::slice::from_ref(&t.name), &t.name).into_iter().chain(crate::web::specs_for(&[], "")).filter(|s| goal::JUDGE_TOOLS.contains(&s["name"].as_str().unwrap_or(""))).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
let own = ChatRequest { tools, ..own };
|
||||
// A model of another family when the person has one: a bot's own model grades its own
|
||||
// work too kindly (pstack's judges are from a different family). Its own, if that fails.
|
||||
let mut tries: Vec<ChatRequest> = self.judge_elsewhere(b.provider).map(|(kind, base_url, api_key, model)| ChatRequest { kind, base_url, api_key, model, ..own.clone() }).into_iter().collect();
|
||||
|
|
@ -195,9 +233,9 @@ impl App {
|
|||
let cancel = AtomicBool::new(false);
|
||||
let mut judged = Judged::Failed("沒有可以檢查的模型".into());
|
||||
for req in &tries {
|
||||
match providers::run_step(req, &cancel, &|_| {}) {
|
||||
Ok(o) => {
|
||||
judged = goal::read_verdict(&o.text);
|
||||
match judge_with_looks(req, target.as_ref(), bot_id, &cancel) {
|
||||
Ok(text) => {
|
||||
judged = goal::read_verdict(&text);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
|
|
@ -333,6 +371,31 @@ pub(super) fn note_index(msgs: &[Message], streaming: bool) -> usize {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// R5: the judge looks for itself (a file where the bot works) before it answers; a step
|
||||
/// that would change something is refused, not run.
|
||||
#[test]
|
||||
fn the_judge_looks_for_itself_read_only() {
|
||||
use crate::testkit::{Fake, Reply};
|
||||
let w = std::env::temp_dir().join(format!("anybot-judge-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
std::fs::create_dir_all(&w).unwrap();
|
||||
std::fs::write(w.join("report.txt"), "全部 340 個測試通過").unwrap();
|
||||
let fake = Fake::openai(vec![
|
||||
Reply::call("j1", "read_file", serde_json::json!({"path": "report.txt"})),
|
||||
Reply::call("j2", "shell", serde_json::json!({"command": "touch made.txt"})),
|
||||
Reply::text(r#"{"verdict":"met","reason":"report.txt 寫全部通過"}"#),
|
||||
]);
|
||||
let t = crate::tools::Target { name: "這台".into(), place: crate::tools::Place::Local { workdir: w.clone() } };
|
||||
let req = ChatRequest { kind: crate::providers::ProviderKind::Custom, base_url: fake.base(), api_key: String::new(), model: "m".into(), system: goal::JUDGE_SYSTEM.into(), history: vec![Message::user("目標:所有測試都通過")], tools: vec![], session: String::new(), effort: String::new() };
|
||||
let text = judge_with_looks(&req, Some(&t), 1, &AtomicBool::new(false)).unwrap();
|
||||
assert!(text.contains("\"met\""), "{text}");
|
||||
let bodies = fake.bodies.lock().unwrap().clone();
|
||||
assert!(bodies[1].to_string().contains("全部 340 個測試通過"), "the file it read went back to it");
|
||||
assert!(bodies[2].to_string().contains("檢查目標時不能用「shell」"), "refused");
|
||||
assert!(!w.join("made.txt").exists(), "nothing was changed");
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_note_never_splits_a_step_from_its_result() {
|
||||
let user = Message::user("做事");
|
||||
|
|
|
|||
|
|
@ -557,6 +557,17 @@ impl App {
|
|||
self.usage_note(bot);
|
||||
return;
|
||||
}
|
||||
match text.trim() {
|
||||
"/context" => {
|
||||
self.context_note(bot);
|
||||
return;
|
||||
}
|
||||
"/compact" => {
|
||||
self.compact_now(bot);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// (From the phone or a screen: the brain checks itself.)
|
||||
if crate::doctor::command(&text) {
|
||||
self.doctor_start(bot);
|
||||
|
|
|
|||
132
src/gate.rs
132
src/gate.rs
|
|
@ -188,3 +188,135 @@ mod tests {
|
|||
assert_eq!(a("computer_use_click", none, deny.clone(), true, true, &[]).decision, deny, "a refusal stays a refusal");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 固定樣式的規則 (R2) ----------
|
||||
// 「無需詢問直接允許」 and 「一律詢問」 rules may be written as a pattern instead of a sentence:
|
||||
// shell(git *) a command (every part of `a && b | c` for an allow; any part for an ask)
|
||||
// file(~/Projects/**) a file or folder a step reads or changes (** any depth, * one name)
|
||||
// connector(gitlab__*) a connector's tool (server__tool)
|
||||
// web(domain:example.com) a page opened or fetched on that site (or below it)
|
||||
// tool(browser_click) a step by its tool's name
|
||||
// They are decided here, the same every time, before the model reads the sentence rules: an ask
|
||||
// pattern can't be talked out of by anything the model read (grok-build's deny > ask > allow
|
||||
// rules, checked before its model).
|
||||
|
||||
/// What the pattern rules say about a step.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum PatternVerdict {
|
||||
Ask(String),
|
||||
Allow(String),
|
||||
NoMatch,
|
||||
}
|
||||
|
||||
/// A rule written as a pattern (else it is a sentence for the model).
|
||||
pub fn is_pattern(rule: &str) -> bool {
|
||||
let r = rule.trim();
|
||||
["shell(", "file(", "connector(", "web(", "tool("].iter().any(|p| r.starts_with(p)) && r.ends_with(')')
|
||||
}
|
||||
|
||||
/// `*` any run of characters, `?` one; with `slash_stops`, `*` stays within one path name and
|
||||
/// `**` crosses folders.
|
||||
pub fn glob(pat: &str, text: &str, slash_stops: bool) -> bool {
|
||||
fn go(p: &[char], t: &[char], slash_stops: bool) -> bool {
|
||||
match p.first() {
|
||||
None => t.is_empty(),
|
||||
Some('*') if p.get(1) == Some(&'*') => (0..=t.len()).any(|i| go(&p[2..], &t[i..], slash_stops)),
|
||||
Some('*') => (0..=t.len()).take_while(|&i| i == 0 || !(slash_stops && t[i - 1] == '/')).any(|i| go(&p[1..], &t[i..], slash_stops)),
|
||||
Some('?') => !t.is_empty() && go(&p[1..], &t[1..], slash_stops),
|
||||
Some(c) => t.first() == Some(c) && go(&p[1..], &t[1..], slash_stops),
|
||||
}
|
||||
}
|
||||
let (p, t): (Vec<char>, Vec<char>) = (pat.chars().collect(), text.chars().collect());
|
||||
go(&p, &t, slash_stops)
|
||||
}
|
||||
|
||||
fn host_of(url: &str) -> String {
|
||||
url.split("://").nth(1).unwrap_or(url).split(['/', ':', '?', '#']).next().unwrap_or("").to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// Whether `rule` (a pattern) is about this step; `all` for an allow (every part of a command
|
||||
/// must match), any part for an ask.
|
||||
fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) -> bool {
|
||||
let r = rule.trim();
|
||||
let Some((kind, inner)) = r.split_once('(').map(|(k, rest)| (k, rest.strip_suffix(')').unwrap_or(rest).trim())) else { return false };
|
||||
let s = |k: &str| args[k].as_str().unwrap_or("").trim().to_string();
|
||||
match kind {
|
||||
"shell" if name == "shell" => {
|
||||
let cmd = s("command");
|
||||
match tools::split_commands(&cmd) {
|
||||
Some(parts) if !parts.is_empty() => {
|
||||
let hit = |p: &String| glob(inner, p.trim(), false);
|
||||
if all { parts.iter().all(hit) } else { parts.iter().any(hit) }
|
||||
}
|
||||
// Hidden commands ($(), backticks): an allow can't vouch for what it can't see; an
|
||||
// ask still looks at the whole line.
|
||||
_ => !all && glob(inner, &cmd, false),
|
||||
}
|
||||
}
|
||||
"file" if matches!(name, "read_file" | "edit_file" | "list_dir" | "search" | "write_file") => {
|
||||
let path = s("path");
|
||||
let home = |p: &str| tools::expand_home(p).display().to_string();
|
||||
!path.is_empty() && (glob(inner, &path, true) || glob(&home(inner), &home(&path), true))
|
||||
}
|
||||
"connector" => {
|
||||
let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() };
|
||||
tool.strip_prefix("mcp__").is_some_and(|t| glob(inner, t, false))
|
||||
}
|
||||
"web" if matches!(name, "web_fetch" | "browser_open") => {
|
||||
let host = host_of(&s("url"));
|
||||
let want = inner.strip_prefix("domain:").unwrap_or(inner).trim().to_ascii_lowercase();
|
||||
!host.is_empty() && (host == want || host.ends_with(&format!(".{want}")))
|
||||
}
|
||||
"tool" => glob(inner, name, false),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern rules' word on a step: any ask pattern about it asks (over any allow); else an
|
||||
/// allow pattern that covers it allows; else they say nothing (the sentences go to the model).
|
||||
pub fn patterns(name: &str, args: &str, allow: &[String], ask: &[String]) -> PatternVerdict {
|
||||
let v = tools::args_of(args);
|
||||
if let Some(r) = ask.iter().filter(|r| is_pattern(r)).find(|r| pattern_matches(r, name, &v, false)) {
|
||||
return PatternVerdict::Ask(r.trim().to_string());
|
||||
}
|
||||
if let Some(r) = allow.iter().filter(|r| is_pattern(r)).find(|r| pattern_matches(r, name, &v, true)) {
|
||||
return PatternVerdict::Allow(r.trim().to_string());
|
||||
}
|
||||
PatternVerdict::NoMatch
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pattern_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn globs() {
|
||||
assert!(glob("git *", "git status", false) && !glob("git *", "gitk", false));
|
||||
assert!(glob("npm ?un *", "npm run build", false));
|
||||
assert!(glob("/a/**", "/a/b/c.txt", true) && glob("/a/*", "/a/b", true) && !glob("/a/*", "/a/b/c", true));
|
||||
}
|
||||
|
||||
/// R2 as a table: the same answer every time, an ask over an allow, a chained command allowed
|
||||
/// only when every part is.
|
||||
#[test]
|
||||
fn pattern_rules_decide_before_the_model() {
|
||||
let rules = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let allow = rules(&["shell(git *)", "file(~/Projects/**)", "connector(gitlab__get_*)", "web(domain:example.com)", "只是一句話的規則"]);
|
||||
let ask = rules(&["shell(git push*)", "tool(browser_click)"]);
|
||||
let p = |name: &str, args: serde_json::Value| patterns(name, &args.to_string(), &allow, &ask);
|
||||
let sh = |c: &str| serde_json::json!({"command": c});
|
||||
assert_eq!(p("shell", sh("git status")), PatternVerdict::Allow("shell(git *)".into()));
|
||||
assert_eq!(p("shell", sh("git status && git log")), PatternVerdict::Allow("shell(git *)".into()));
|
||||
assert_eq!(p("shell", sh("git status && rm -rf x")), PatternVerdict::NoMatch, "every part, or no allow");
|
||||
assert_eq!(p("shell", sh("git add . && git push origin main")), PatternVerdict::Ask("shell(git push*)".into()), "an ask over an allow");
|
||||
assert_eq!(p("shell", sh("echo $(git status)")), PatternVerdict::NoMatch, "a hidden command is never allowed by a pattern");
|
||||
assert_eq!(p("read_file", serde_json::json!({"path": "~/Projects/a/b.rs"})), PatternVerdict::Allow("file(~/Projects/**)".into()));
|
||||
assert_eq!(p("read_file", serde_json::json!({"path": "~/Documents/x"})), PatternVerdict::NoMatch);
|
||||
assert_eq!(p("mcp__gitlab__get_issue", serde_json::json!({})), PatternVerdict::Allow("connector(gitlab__get_*)".into()));
|
||||
assert_eq!(p(crate::mcp::USE_TOOL, serde_json::json!({"tool": "mcp__gitlab__delete_project"})), PatternVerdict::NoMatch);
|
||||
assert_eq!(p("web_fetch", serde_json::json!({"url": "https://docs.example.com/a"})), PatternVerdict::Allow("web(domain:example.com)".into()));
|
||||
assert_eq!(p("web_fetch", serde_json::json!({"url": "https://example.com.evil.net/"})), PatternVerdict::NoMatch);
|
||||
assert_eq!(p("browser_click", serde_json::json!({})), PatternVerdict::Ask("tool(browser_click)".into()));
|
||||
assert!(is_pattern("shell(ls)") && !is_pattern("刪除檔案前先問我") && !is_pattern("shell ls"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
55
src/goal.rs
55
src/goal.rs
|
|
@ -136,8 +136,32 @@ pub const JUDGE_SYSTEM: &str = "你是驗收員。使用者給一個 bot 設了
|
|||
- 確定永遠做不到才判 impossible(要的東西不存在、被明確拒絕而且沒有別的路);只是還沒做完、遇到能修的錯誤,都是 not_met。
|
||||
- reason 一句話,用使用者的語言:met 寫是哪個證據;not_met 寫還差什麼、下一步做什麼;waiting 寫在等使用者什麼;impossible 寫為什麼。
|
||||
|
||||
- 每一輪用同一個標準:只看目標本身寫的條件。不要因為 bot 做得比上一輪多就提高要求,也不要加入目標沒寫的條件。
|
||||
- 對話裡的證據不夠時,可以用工具自己查證(read_file、list_dir 看 bot 做事的那台電腦,web_fetch 讀公開網頁),最多 3 次;工具只能看、不能改。查完一定要回 JSON。
|
||||
|
||||
只回一個 JSON,不要別的字:{\"verdict\":\"met|not_met|waiting|impossible\",\"reason\":\"…\"}";
|
||||
|
||||
/// What the judge may use to look for itself (read only), at most JUDGE_LOOKS rounds.
|
||||
pub const JUDGE_TOOLS: [&str; 3] = ["read_file", "list_dir", "web_fetch"];
|
||||
pub const JUDGE_LOOKS: usize = 3;
|
||||
|
||||
/// Two of the judge's reasons say the same thing (its words differ a little each time): their
|
||||
/// character pairs overlap this much.
|
||||
const SAME_REASON: f64 = 0.7;
|
||||
|
||||
/// Whether two reasons say the same (most of their character pairs in common).
|
||||
pub fn same_reason(a: &str, b: &str) -> bool {
|
||||
let pairs = |s: &str| {
|
||||
let c: Vec<char> = s.chars().filter(|c| !c.is_whitespace() && !c.is_ascii_punctuation() && !",。、;:「」()!?".contains(*c)).collect();
|
||||
c.windows(2).map(|w| (w[0], w[1])).collect::<std::collections::HashSet<_>>()
|
||||
};
|
||||
let (x, y) = (pairs(a), pairs(b));
|
||||
if x.is_empty() || y.is_empty() {
|
||||
return false;
|
||||
}
|
||||
x.intersection(&y).count() as f64 / x.union(&y).count() as f64 >= SAME_REASON
|
||||
}
|
||||
|
||||
/// The judge's answer, read loosely (a model may wrap the JSON in words or a code fence). An
|
||||
/// answer that can't be read counts as not yet met: the turn cap still stops it.
|
||||
pub fn read_verdict(text: &str) -> Judged {
|
||||
|
|
@ -223,7 +247,14 @@ pub fn after_verdict(g: &mut Goal, judged: Judged, now: i64) -> Next {
|
|||
}
|
||||
};
|
||||
g.turns += 1;
|
||||
// The same gap twice in a row: another turn would most likely find it again (grok-build pauses
|
||||
// a goal when its gaps repeat).
|
||||
let again = verdict == Verdict::NotYet && !g.reason.is_empty() && same_reason(&g.reason, &reason);
|
||||
g.reason = reason.clone();
|
||||
if again {
|
||||
g.paused = "同樣的問題連續兩次".into();
|
||||
return Next::Pause { note: format!("目標暫停:連續兩輪檢查都說差同一件事,看起來卡住了:{reason}\n傳一句話(提示一下做法,或說「繼續」)就接著做;不要了就用 /goal clear。"), title: "的目標暫停了" };
|
||||
}
|
||||
let took = format!("{} 輪 · {}", g.turns, elapsed(now - g.since));
|
||||
match verdict {
|
||||
Verdict::Met => Next::Over { note: format!("目標達成:{}\n{reason}({took})", g.condition), title: "達成目標了" },
|
||||
|
|
@ -339,6 +370,22 @@ fn head_tail(s: &str, head: usize, tail: usize) -> String {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// R5: the same gap said twice in a row (in words that differ a little) pauses the goal.
|
||||
#[test]
|
||||
fn the_same_reason_twice_pauses() {
|
||||
assert!(same_reason("還差 2 個測試失敗:goal::tests 的時間格式", "還差2個測試失敗(goal::tests 的時間格式)"));
|
||||
assert!(!same_reason("還差 2 個測試失敗", "clippy 還有新的警告"));
|
||||
assert!(!same_reason("", "x"));
|
||||
let mut g = Goal::new("所有測試都通過", 0);
|
||||
assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::NotYet, "還差 2 個測試失敗:時間格式".into()), 1), Next::Again { .. }));
|
||||
assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::NotYet, "clippy 還有新的警告".into()), 2), Next::Again { .. }), "a different gap: on");
|
||||
match after_verdict(&mut g, Judged::Said(Verdict::NotYet, "clippy 還有新的警告。".into()), 3) {
|
||||
Next::Pause { note, .. } => assert!(note.contains("連續兩輪") && !g.active(), "{note}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(JUDGE_SYSTEM.contains("不要因為 bot 做得比上一輪多就提高要求"));
|
||||
}
|
||||
|
||||
/// The judge reads the bot's words as words, and the system's own count of what was sent.
|
||||
#[test]
|
||||
fn the_judge_gets_the_systems_count_not_only_the_bots_word() {
|
||||
|
|
@ -390,7 +437,13 @@ mod tests {
|
|||
#[test]
|
||||
fn not_yet_goes_again_until_the_brakes() {
|
||||
let mut g = Goal::new("測試通過", 0);
|
||||
let not_yet = || Judged::Said(Verdict::NotYet, "還有 1 個失敗".into());
|
||||
// Each check names a different gap (the same one twice pauses: the_same_reason_twice_pauses).
|
||||
let gaps = ["還有 1 個失敗", "clippy 有新的警告", "README 少了安裝說明", "版本號沒有更新", "CHANGELOG 沒寫", "格式檢查沒過", "建置腳本找不到", "文件連結壞了"];
|
||||
let n = std::cell::Cell::new(0);
|
||||
let not_yet = || {
|
||||
n.set(n.get() + 1);
|
||||
Judged::Said(Verdict::NotYet, gaps[(n.get() - 1) % gaps.len()].into())
|
||||
};
|
||||
g.after_turn(true);
|
||||
assert_eq!(after_verdict(&mut g, not_yet(), 60_000), Next::Again { text: "[目標]還沒達成:還有 1 個失敗".into() });
|
||||
assert_eq!((g.turns, g.reason.as_str(), g.active()), (1, "還有 1 個失敗", true));
|
||||
|
|
|
|||
|
|
@ -1394,6 +1394,14 @@ fn room_for_terminal() -> bool {
|
|||
|
||||
const NO_ROOM: &str = "背景已經有太多指令在跑了,這個沒有留在背景(已停掉)。先看看哪些不用了:對它們用 write_terminal 的 stop: true 停掉,再試一次。";
|
||||
|
||||
/// A bot's background commands still running: (id, command).
|
||||
pub fn running_for(conversation: &str) -> Vec<(u64, String)> {
|
||||
let t = terminals().lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut v: Vec<(u64, String)> = t.iter().filter(|(_, x)| x.conversation == conversation && x.exit.lock().map(|e| e.is_none()).unwrap_or(false)).map(|(id, x)| (*id, x.command.clone())).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
fn terminals() -> &'static Mutex<HashMap<u64, Terminal>> {
|
||||
static T: OnceLock<Mutex<HashMap<u64, Terminal>>> = OnceLock::new();
|
||||
T.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
|
|
|
|||
Loading…
Reference in New Issue