From 6a6d905ede903a0daed17b610098f32381a27c89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 17:37:53 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix:=20=E9=80=A3=E6=8E=A5=E5=99=A8=E7=9A=84?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E4=B9=9F=E7=85=A7=E3=80=8C=E4=B8=80=E5=BE=8B?= =?UTF-8?q?=E8=A9=A2=E5=95=8F=E3=80=8D=E5=92=8C=E8=87=AA=E5=8B=95=E5=AF=A9?= =?UTF-8?q?=E6=A0=B8=E2=80=94=E2=80=94=E7=9B=B4=E6=8E=A5=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E8=AE=93=E9=80=A3=E6=8E=A5=E5=99=A8=E4=B8=80?= =?UTF-8?q?=E5=BE=8B=E7=9B=B4=E6=8E=A5=E5=81=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 連接器(MCP)的步驟由 steps.rs 的 Connector 自己決定問不問:「一律允許」過或直接操作開著就做, 其他一律問。它從來不經自動審核(review_action 只有 OnComputer 叫),所以: - 直接操作時,連接器的步驟連「一律詢問」規則都不看就做(autonomy-still-asks 說會問; 預設那條「用我的帳號發文、留言,或傳訊息給別人」對 Slack、GitLab 這類連接器正是要擋的); - `connector(…)` 樣式規則(autonomy-patterns)對連接器完全沒作用:詢問的不問、允許的照樣問; - 用一般的話寫的規則也不給審核員看。 修好前的證據:新加的 4 個測試在舊程式全失敗(app 層的那個:用設定的開關打開直接操作、 「一律詢問」寫 connector(calc-direct__add),結果 sum=5、沒跳卡片)。 修法(一處):OnComputer 的第 7 步(自動審核/直接操作)抽成 steps.rs 的 reviewed(), OnComputer 照舊用它(行為不變),Connector 也用它:第 6 步「一律允許」過的照舊直接做, 沒有的交給 reviewed()——符合「一律詢問」就問、沒有「一律允許」;符合允許就做,結果最後寫 「(自動審核:符合…,直接允許)」;直接操作只看「一律詢問」。用 use_connector_tool 叫的照它 真正的工具名稱比對(簡稱 "add" 也擋得住);審核員讀全部的參數,卡片照舊只列前 160 字(多的寫「…」)。 一律放行照舊全放。 鎖檔:tool_specs_are_locked、approval_decisions_are_characterized 都沒有 diff(工具定義和 decide() 沒動;連接器的決定不在那張表裡)。 交人決定(沒改):「一律允許」過的連接器(每個連接器一條 mcp:名稱,整個連接器的工具都算)不再看規則, 跟指令、檔案一樣照第 6 步先於第 7 步。一般的卡(不符合規則的工具)有「一律允許」,按了之後同一個連接器 符合「一律詢問」樣式的工具也不再問;地圖的 autonomy-patterns 和陷阱照實寫了。要改成樣式規則蓋過 連接器的「一律允許」是產品決定。 獨立審查(乾淨脈絡、照 autonomy/safety/connectors 審 diff):沒有 P0;P1 是 autonomy-patterns 那句 「一定問」沒寫「一律允許」過的例外——已改。P2 已改:審核員只看到前 160 字的參數、直接操作變慢補一條陷阱。 P2 沒改(範圍外,記著):中文名稱的連接器樣式要寫代碼;hook 的「ask」加上規則的卡會跳兩張; hook 的「allow」省不掉連接器的卡;區網的手機能移除「一律詢問」規則。 功能地圖:autonomy 的「審核、樣式規則」從走不到改成真的步驟「連接器照規則問」(手機開的自動審核+ connector(echo__e0)+審核員),直接操作那一半寫走不到(區網 403)和最接近的測試;connectors、 safety 的陷阱和關卡順序、FEATURES.md 第 16 節和連接器權限跟著改。 已驗證: 全部 cargo test(不帶金鑰、DOCKER_HOST 指到不存在)673 通過,含新的 a_connector_ask_rule_stops_direct_mode、 a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules、a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins、 rules_about_other_things_leave_a_connector_alone、direct_mode_still_asks_a_connector_step_its_ask_rule_names; clippy -D warnings、lint-sh、verify-approval-routing run.sh --replay(跟基準一樣); verify-anybot:autonomy 每一步可跑的照 md 原文冷跑全過(target/verify-anybot/20261118-173659,最後的程式), connectors、safety 也冷跑全過(-172146、-172210,卡片截斷那一行改之前;它們的參數都不到 160 字), 另一輪實跑一律放行照樣放行(-171612) 未驗證: 直接操作那一半和「無需詢問直接允許」規則的實機(直接連線的手機打不開直接操作、加不了允許規則, 要電腦上的視窗或帳號連線),改由 app 層測試用設定的開關走;桌面視窗的卡片樣子(沒開 desktop-shot); 真的遠端連接器;--ignored 的實機測試(要實機 Mac) 未簽: 動到審批路徑——要人類簽名才能合併,沒有合併、沒有推 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- FEATURES.md | 5 +- docs/feature-map/autonomy.md | 13 ++-- docs/feature-map/connectors.md | 4 +- docs/feature-map/safety.md | 2 +- src/agent.rs | 111 +++++++++++++++++++++++++++ src/agent/steps.rs | 135 ++++++++++++++++++--------------- src/app.rs | 37 +++++++++ 7 files changed, 235 insertions(+), 72 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 4f2ab6e..1ce49c8 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -823,7 +823,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 滑鼠和鍵盤:「操作你的滑鼠和鍵盤:…」,可以一律允許。 - 讀你瀏覽器的分頁:「讀取你瀏覽器目前分頁的內容(包含已登入的頁面):目前的分頁」,可以一律允許。單純打開連結不用問。 - 檔案和指令:照第 19 節的安全規則決定。被擋下時顯示「被安全規則擋下:{原因}」。 -7. **自動審核或直接操作**:見第 15 節和第 8 節。 + - 連接器的工具:每個連接器第一次問「使用連接器「X」的工具:…」,可以一律允許。 +7. **自動審核或直接操作**:見第 15 節和第 8 節(連接器的工具也是)。 8. **一般請求** - 允許一次。 - 一律允許:記到 Bot 的「一律允許」清單,例如「修改檔案」或「git commit」。 @@ -1500,7 +1501,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 都沒寫:本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`(自己設了同名變數的話用自己的);遠端伺服器收到 `Authorization: Basic …`(自己有 Authorization 標頭的話不加)。 - 密碼跟金鑰一樣:螢幕只看得到「已設定」,不會拿到內容;在螢幕上改指令或網址時,大腦會把密碼清掉(不然會被送到新的位址)。 - **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。 -- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。 +- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;符合「一律詢問」的照樣問、沒有「一律允許」——直接操作模式下也一樣(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」規則都不看)。用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀全部的參數,卡片只列前 160 字。一律允許過的連接器直接做,不再看規則(第 16 節第 6 步在第 7 步之前)。 - 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。按停止時,本機連接器的呼叫馬上結束(以前要等到它回或 120 秒);用網址連的照樣等。 - 連接器關掉、移除、重新連線或連不上時,連同它帶起來的所有程式一起關(npx/uvx/sh 底下真正的伺服器以前會一直留著)。 - **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index aad2732..2d20766 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -6,9 +6,9 @@ - `autonomy-direct` 直接操作:打開時一次做完——打開「在這台電腦上執行」、自動審核、所有 Bot 的電腦工具;「一律詢問」規則是空的就填三條預設(刪除檔案或資料夾/付款、購買或轉帳/用我的帳號發文、留言,或傳訊息給別人);進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。 - `autonomy-yolo` 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的也不問,自動審核也略過。仍然擋:安全規則一律拒絕的;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方、臉的同一行右邊有一個紅色閃電圖示(不另外佔一行;新對話沒有臉時自己一小行):滑過去看「一律放行 · Bot 做事不再問你」和還會擋什麼,點一下有「關閉一律放行」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 -- `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的;畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 -- `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。 -- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:符合「一律詢問」的樣式一定問(模型說允許也沒用);符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。 +- `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具也算);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 +- `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具也經過它。 +- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:沒「一律允許」過的步驟,符合「一律詢問」的樣式一定問(模型說允許也沒用);符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。 - `autonomy-hooks` Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 自己出錯(結束碼不對、逾時、JSON 看不懂)就當它不在,紀錄檔寫原因。 - `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機關得掉,但打不開直接操作、新增不了「無需詢問直接允許」規則和連接器(「這項設定會讓 Bot 不用問就動手,不能從區網連線…打開」);要在電腦上的 AnyBot,或用帳號連線。 @@ -31,9 +31,10 @@ - **hook 照樣問、擋下一步**(covers `autonomy-hooks`、`autonomy-yolo`):一律放行開著,請 Bot 加一個擋 `shell` 的 hook,按允許,再請它跑指令。指令:`$CTL phone send '加 hook [[call manage_hooks {"action":"add","event":"PreToolUse","matcher":"shell","command":"echo 這一步被 hook 擋下 >&2; exit 2"}]]' && $CTL phone wait '#ask .ask' && $CTL phone shot autonomy-hook-card && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "manage_hooks") | .status] == ["done"]' && $CTL datafile hooks/hooks.json && $CTL phone send '跑 [[call shell {"command":"echo hi"}]]' && $CTL phone wait-text 'hook 擋下了這一步' --in '#msgs'`。看到:一律放行也跳「新增一個 hook:每次「PreToolUse」…」的卡片;hooks.json 有那條;指令沒跑,「沒有執行:使用者設定的 hook 擋下了這一步。它說:這一步被 hook 擋下」。 - **看狀態、關掉**(covers `autonomy-yolo`):打「/always-approve status」「/always-approve off」,再請它改名。指令:`$CTL phone send '/always-approve status' && $CTL phone wait-text '現在是一律放行' --in '#msgs' && $CTL phone send '/always-approve off' && $CTL phone wait-text '已關閉一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == false' && $CTL phone send '再改 [[call update_bot {"name":"關掉後的名字"}]]' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了這個操作' --in '#msgs'`。看到:「現在是一律放行…」「已關閉一律放行:…「直接操作」也關了」;改名又跳卡片。 - **手機打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):重新整理,帳戶選單 › 設定 › 權限,按「直接操作」。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '刪除檔案或資料夾' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '不能從區網連線' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」裡三條預設規則;按開關、確認「打開」後跳出「這項設定會讓 Bot 不用問就動手,不能從區網連線…」,直接操作還是關的。 +- **連接器照規則問**(covers `autonomy-review`、`autonomy-patterns`):自動審核還開著(一律放行打開的),在「一律詢問(優先)」新增 `connector(echo__e0)`;回聊天加兩個工具的 echo([connectors](connectors.md)),叫 e0 按「拒絕」;審核員說都不符合時叫 e1、按「允許一次」;說詢問時再叫 e1。指令:`$CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'connector(echo__e0)' && $CTL phone click '#ask-ok' && $CTL phone wait-text 'connector(echo__e0)' --in '#list' && $CTL phone shot autonomy-connector-rule && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '加 [[call manage_connectors {"action":"add","name":"echo","command":"node -e eval(process.env.MCP_JS) 2","env":{"MCP_JS":"require(\"readline\").createInterface({input:process.stdin}).on(\"line\",l=>{let m=JSON.parse(l);m.id!=null&&console.log(JSON.stringify({id:m.id,result:m.method==\"tools/list\"?{tools:[...Array(+process.argv[1]||1)].map((_,i)=>({name:\"e\"+i}))}:{content:[{type:\"text\",text:\"echo \"+m.params?.arguments?.text}]}}))})"}}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text '已連上,2 個工具' && $CTL phone send '[[call mcp__echo__e0 {"text":"hi"}]]' && $CTL phone wait-text '規則:connector(echo__e0)' --in '#ask' && $CTL phone shot autonomy-connector-ask && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL model-reply 你是動作審核員 '{"verdict":"none","rule":""}' && $CTL phone send '[[call mcp__echo__e1 {"text":"ok"}]]' && $CTL phone wait '#ask button[data-a="always"]' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text 'echo ok' --in '#msgs' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"用我的帳號發文、留言,或傳訊息給別人"}' && $CTL phone send '[[call mcp__echo__e1 {"text":"again"}]]' && $CTL phone wait-text '規則:用我的帳號發文' --in '#ask' && $CTL phone shot autonomy-connector-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL state '.bots[0].allow_rules'`。看到:「…想要用連接器」卡片「使用連接器「echo」的工具:e0 …(符合你的「一律詢問」規則:connector(echo__e0))」只有「允許」「拒絕」;e1 是一般的卡(有「一律允許」),允許後回「echo ok」;審核員讀到「要審核的動作:使用連接器「echo」的工具:e1 …」,說詢問就跳寫著那條規則的卡;allow_rules 還是 []。 - **桌面的閃電圖示**(covers `autonomy-yolo`):指令:要開視窗——第一步之後 `$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot autonomy-yolo ANYBOT_SHOT_REAL=1 && $CTL serve`。看到:臉的同一行右邊一個紅色閃電圖示。 -- **審核、樣式規則**(covers `autonomy-review`、`autonomy-patterns`、`autonomy-still-asks`):指令:走不到——scratch 裡會問的是 App 操作工具和連接器的工具,都直接問、不經自動審核(經過的是你的電腦的指令和檔案,scratch 沒有那台)。看到:最接近的真路是下面的自動測試(審核的 system 開頭是「你是動作審核員」,可用 `model-reply` 指定)。 -- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`)、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 +- **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 +- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 ## 陷阱 @@ -41,5 +42,7 @@ - hook 在大腦上、用使用者的身分、在 Bot 的沙盒外跑:只加看得懂的指令。每一步都會跑 PreToolUse,慢的 hook 會讓 Bot 變慢(預設最多等 60 秒)。 - 外面的訊息和團隊成員的訊息不用你的直接操作和自動審核:要核准的事都得你親手按。 - 自動審核靠模型讀規則,寫得含糊會判錯;內建的安全規則不靠它。 +- 「一律允許」過的(例如某個連接器,整個連接器的工具都算)直接做,不再看自動審核和「一律詢問」規則:要它每次照規則問,先在 Bot 設定移除那條「一律允許」。 +- 直接操作開著、「一律詢問」有用話寫的規則時,沒「一律允許」過的連接器每一步都先等審核模型看一次(慢一點);例行任務碰到符合的會停下來等你。 - 手機的設定頁(權限、一般…)不會自己更新:別處改了(例如一律放行填了預設規則)要重新整理才看得到。 - (驗證)hook 擋 `update_bot` 的話,後面改名的步驟都會被擋;示範用不用問的 `shell`。 diff --git a/docs/feature-map/connectors.md b/docs/feature-map/connectors.md index 89b0d3c..e4db365 100644 --- a/docs/feature-map/connectors.md +++ b/docs/feature-map/connectors.md @@ -37,11 +37,11 @@ - **手機上關掉**(covers `connectors-close`):設定 › 整合關掉 echo,再找。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '已連上,21 個工具' --in '#list' && $CTL phone click 'label.sw:has([data-mcp="echo"])' && $CTL phone wait-text 已關閉 --in '#list' && $CTL procs --none process.env.MCP_JS && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '找 [[call find_connector_tool {"server":"echo"}]]' && $CTL phone wait-text '沒有 find_connector_tool'`。看到:「已關閉」,node 結束;新一輪沒有連接器工具。 - **移除**(covers `connectors-chat`、`connectors-close`):指令:`$CTL phone send '移除 [[call manage_connectors {"action":"remove","name":"echo"}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/settings '.mcp == []' && $CTL state '.bots[0].allow_rules'`。看到:卡片「移除連接器「echo」…」;`mcp:echo` 也沒了。 - **遠端、登入**(covers `connectors-remote`、`connectors-oauth`):指令:走不到——要真的遠端和登入伺服器。看到:最接近的是 `cargo test mcp::`(`http_answers_json_or_sse`、`the_login_reaches_the_server`)。 -- 自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`、`cargo test untrusted_senders_do_not_see_mcp_connectors`。 +- 自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`、`cargo test untrusted_senders_do_not_see_mcp_connectors`、`cargo test a_connector_`、`cargo test rules_about_other_things_leave_a_connector_alone`、`cargo test direct_mode_still_asks`。 ## 陷阱 -- 每個連接器第一次用問一次,可「一律允許」;直接操作模式不問。`find_connector_tool` 只查清單,不問。 +- 每個連接器第一次用問一次,可「一律允許」;直接操作模式不問。自動審核的規則也管連接器的工具(樣式寫工具名稱 `mcp__` 後面那段,例如 `connector(gitlab__*)`,[autonomy](autonomy.md)):符合「一律詢問」的照樣問、沒有「一律允許」,直接操作也一樣;符合允許的不問。「一律允許」過的連接器不再看規則。`find_connector_tool` 只查清單,不問。 - 訊息管道(Slack、Telegram…)或團隊成員的訊息,那一輪沒有連接器工具;呼叫會回「這個回合沒有提供連接器工具。」 - 連接器回的內容是資料,不是命令:裡面寫「去做某事」不要照做。 - OAuth:登入伺服器不讓 App 自己註冊(沒有 dynamic client registration)或不支援 PKCE 的登不進去,會說原因;它也收 API 金鑰就填在「標頭」。登入等 10 分鐘,過了重來;登入網址只能用一次。公用市集裡舊式 SSE 的標「舊式 SSE 連線,AnyBot 還不支援」。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index d3659cb..c32c998 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -11,7 +11,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - `safety-local` 「在這台電腦上執行」:一律允許/每次詢問(預設)/永不允許。永不允許時直接拒絕、不問。 - `safety-lock` 管理員鎖定:可鎖「直接操作」(AllowDirectMode)、「在這台電腦上執行」(AllowLocalExecution)、「經這台電腦轉送流量」(AllowBoxTrafficViaThisMac)。macOS 用 `defaults` 網域 com.anybot.AnyBot(可由 MDM 強制);其他系統讀 /etc/anybot/policy.json(優先)或家目錄 .anybot/policy.json。true/1/yes 允許;false/0/no 或看不懂的值鎖成關。每次打開設定重讀。 - `safety-timeout` 沒人在旁邊的一輪(例行任務、事件觸發、訊息管道)等核准超過 15 分鐘,自動結束、算出錯,免得卡住後面的排程和訊息。 -- `safety-gates` 每一步的關卡順序:1. 不用問:App 操作工具(刪例行任務、教同事技能、裝外部技能、改自己或別的 Bot 的設定這類會先問)、讀公開網頁、AnyBot 瀏覽器(別人傳來的訊息不能用)。2. 決定在哪台電腦;直接操作開著時第 3、5 步算已開。3. 這個 Bot 的電腦工具沒開 → 問。4. 「在這台電腦上執行」永不允許或被管理員鎖 → 拒絕。5. 它沒開 → 問。6. 照安全規則允許、問或拒絕;「一律允許」過的直接做。7. 要問的交給自動審核或直接操作。8. 「每次都問」的蓋過第 6、7 步。9. 問你;等的時候按停止=拒絕。 +- `safety-gates` 每一步的關卡順序:1. 不用問:App 操作工具(刪例行任務、教同事技能、裝外部技能、改自己或別的 Bot 的設定這類會先問)、讀公開網頁、AnyBot 瀏覽器(別人傳來的訊息不能用)。2. 決定在哪台電腦;直接操作開著時第 3、5 步算已開。3. 這個 Bot 的電腦工具沒開 → 問。4. 「在這台電腦上執行」永不允許或被管理員鎖 → 拒絕。5. 它沒開 → 問。6. 照安全規則允許、問或拒絕(連接器的工具:每個連接器第一次問);「一律允許」過的直接做。7. 要問的交給自動審核或直接操作(連接器的工具也是)。8. 「每次都問」的蓋過第 6、7 步。9. 問你;等的時候按停止=拒絕。 ## 使用者怎麼到 diff --git a/src/agent.rs b/src/agent.rs index e0e5178..6ea7043 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -4615,6 +4615,117 @@ echo 'done送出了' > done.html; (setsid pyt let _ = std::fs::remove_dir_all(&w); } + /// A turn whose model makes the steps in `replies` (and the reviewer's answers between them) + /// with the fake calc connector `server` connected, then says a last word; each card is + /// answered `answer`. Returns each card's question and the grant its 「一律允許」 would keep, + /// the step results, and every request the model got. + #[allow(clippy::type_complexity)] + fn connector_turn(server: &str, mut replies: Vec<(u16, String)>, direct: bool, review: Option, grants: &[&str], answer: ApprovalAnswer) -> (Vec<(String, String)>, Vec, Vec) { + let _one = crate::mcp::test_lock(); + assert!(crate::mcp::sync(&[crate::mcp::fake_server(server, 0)]).is_empty()); + replies.push(sse_text("好")); + let (port, seen) = fake_http(replies); + 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: crate::mcp::specs(), session: String::new(), effort: String::new() }, + direct: Arc::new(AtomicBool::new(direct)), + review, + grants: grants.iter().map(|g| g.to_string()).collect(), + ..test_job() + }; + let (tx, rx) = channel(); + spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + let (mut asked, mut results) = (vec![], vec![]); + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { + (_, StreamEvent::NeedApproval(a)) => { + asked.push((a.reason.clone(), a.grant.clone())); + let _ = a.reply.send(answer.clone()); + } + (_, StreamEvent::ToolResult(m)) => results.push(m.text.clone()), + (_, StreamEvent::Done) => break, + (_, StreamEvent::Error(e)) => panic!("{e}"), + _ => {} + } + } + crate::mcp::sync(&[]); + let seen = seen.lock().unwrap().clone(); + (asked, results, seen) + } + + /// 直接操作 with an 「一律詢問」 pattern about a connector's tool (autonomy-still-asks, + /// autonomy-patterns): the step stops and asks, with no 「一律允許」 and no model call — called + /// by its own name or through use_connector_tool (even by its short name). + #[test] + fn a_connector_ask_rule_stops_direct_mode() { + let add = crate::mcp::tool_name("calc-ask", "add"); + let replies = vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2})), sse_call("c2", crate::mcp::USE_TOOL, serde_json::json!({"tool": "add", "arguments": {"a": 3, "b": 4}}))]; + let review = Review { allow: vec![], ask: vec!["connector(calc-ask__add)".into()] }; + let (asked, results, seen) = connector_turn("calc-ask", replies, true, Some(review), &[], ApprovalAnswer::Reject); + assert_eq!(asked.len(), 2, "{asked:?}"); + for (reason, grant) in &asked { + assert!(reason.contains("符合你的「一律詢問」規則:connector(calc-ask__add)"), "{reason}"); + assert_eq!(grant, "", "a rule's question offers no 「一律允許」"); + } + assert!(results.iter().all(|r| !r.contains("sum=")), "{results:?}"); + assert_eq!(seen.len(), 3, "no model call to review it"); + } + + /// 直接操作's 「一律詢問」 rules written as sentences: the reviewer reads a connector's step like + /// any other — every argument, also past the card's first 160 characters — and its ask stops it. + #[test] + fn a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules() { + let add = crate::mcp::tool_name("calc-words", "add"); + let args = serde_json::json!({"a": 1, "b": 2, "note": format!("{}TAIL-SEND-TO-ALL", "x".repeat(200))}); + let replies = vec![sse_call("c1", &add, args), sse_text(r#"{"verdict":"ask","rule":"傳訊息給別人前先問我"}"#)]; + let review = Review { allow: vec![], ask: vec!["傳訊息給別人前先問我".into()] }; + let (asked, results, seen) = connector_turn("calc-words", replies, true, Some(review), &[], ApprovalAnswer::Reject); + assert_eq!(asked.len(), 1, "{asked:?}"); + assert!(asked[0].0.contains("符合你的「一律詢問」規則:傳訊息給別人前先問我") && asked[0].1.is_empty(), "{asked:?}"); + assert!(asked[0].0.contains("xxx…(符合") && !asked[0].0.contains("TAIL-SEND-TO-ALL"), "the card shows the start: {}", asked[0].0); + assert!(seen.len() == 3 && seen[1].contains("你是動作審核員") && seen[1].contains("calc-words") && seen[1].contains("TAIL-SEND-TO-ALL"), "the reviewer saw the whole step: {seen:?}"); + assert!(results.iter().all(|r| !r.contains("sum=")), "{results:?}"); + } + + /// 自動審核 with an 「無需詢問直接允許」 pattern for a connector: it runs without a card and the + /// result says which rule let it; an 「一律詢問」 pattern over it still asks, with no 「一律允許」. + #[test] + fn a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins() { + let add = crate::mcp::tool_name("calc-allow", "add"); + let call = || vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2}))]; + let review = Review { allow: vec!["connector(calc-allow__*)".into()], ask: vec![] }; + let (asked, results, seen) = connector_turn("calc-allow", call(), false, Some(review), &[], ApprovalAnswer::Reject); + assert!(asked.is_empty(), "{asked:?}"); + assert!(results[0].contains("sum=3") && results[0].contains("自動審核:符合「connector(calc-allow__*)」"), "{results:?}"); + assert_eq!(seen.len(), 2, "a pattern needs no model call"); + let review = Review { allow: vec!["connector(calc-allow__*)".into()], ask: vec!["connector(calc-allow__add)".into()] }; + let (asked, results, _) = connector_turn("calc-allow", call(), false, Some(review), &[], ApprovalAnswer::Reject); + assert_eq!(asked.len(), 1, "{asked:?}"); + assert!(asked[0].0.contains("符合你的「一律詢問」規則:connector(calc-allow__add)") && asked[0].1.is_empty(), "{asked:?}"); + assert!(!results[0].contains("sum="), "{results:?}"); + } + + /// The other way round: rules about other connectors, commands or files don't stop a + /// connector's step — 直接操作 runs it with no model call; without it the card is the usual one + /// (「一律允許」 this connector), as with 自動審核 off; a connector already 「一律允許」 goes ahead + /// (gate step 6 before step 7, as for a command). + #[test] + fn rules_about_other_things_leave_a_connector_alone() { + let add = crate::mcp::tool_name("calc-free", "add"); + let call = || vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2}))]; + let others = Review { allow: vec!["connector(other__*)".into()], ask: vec!["connector(other__*)".into(), "shell(*)".into(), "file(**)".into(), "tool(browser_click)".into()] }; + let (asked, results, seen) = connector_turn("calc-free", call(), true, Some(others.clone()), &[], ApprovalAnswer::Reject); + assert!(asked.is_empty() && results[0].contains("sum=3") && seen.len() == 2, "direct: {asked:?} {results:?}"); + for review in [Some(others), None] { + let (asked, results, _) = connector_turn("calc-free", call(), false, review, &[], ApprovalAnswer::Once); + assert_eq!(asked.len(), 1, "{asked:?}"); + assert!(asked[0].0.starts_with("使用連接器「calc-free」的工具:add") && asked[0].1 == "mcp:calc-free", "the usual card: {asked:?}"); + assert!(results[0].contains("sum=3"), "{results:?}"); + } + let mine = Review { allow: vec![], ask: vec!["connector(calc-free__add)".into()] }; + let (asked, results, _) = connector_turn("calc-free", call(), false, Some(mine), &["mcp:calc-free"], ApprovalAnswer::Reject); + assert!(asked.is_empty() && results[0].contains("sum=3"), "{asked:?} {results:?}"); + } + /// 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] diff --git a/src/agent/steps.rs b/src/agent/steps.rs index ae2c5db..87a74ee 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -1479,9 +1479,55 @@ impl TurnTool for ConnectorFind { } } -/// MCP connectors: asked once per server (or always allowed), like the original's -/// MCP allow-list; direct mode doesn't ask. A tool run through use_connector_tool -/// is that tool: the same question, the same call. +/// Step 7 (gate.rs), for every step that has the person's rules to answer to (OnComputer's and +/// a connector's): what would be asked goes to 自動審核 — when the rules say yes it goes ahead +/// (JOecNC), when an "always ask" rule matches it stops and asks (Pca/iV), with no 「一律允許」. +/// In 直接操作 it goes ahead unless an "always ask" rule matches (`looks`: only looking, which no +/// such rule can be about, isn't checked). Returns the decision, whether the question must be +/// put (a switch's yes or a hook's allow can't save it), and the note for the step's result. +fn reviewed(job: &Job, name: &str, args: &str, decision: Decision, looks: bool, cancel: &AtomicBool) -> (Decision, bool, String) { + let asks_by_rule = |reason: &str, rule: &str| (Decision::Ask { reason: format!("{reason}(符合你的「一律詢問」規則:{rule})"), grant: String::new() }, true, String::new()); + match (decision, &job.review) { + (Decision::Ask { reason, .. }, review) if job.direct.load(Ordering::Relaxed) => { + let verdict = match review { + Some(rv) if !rv.ask.is_empty() && !looks => review_action(job, &Review { allow: vec![], ask: rv.ask.clone() }, name, args, &reason, cancel), + _ => ReviewVerdict::NoMatch, + }; + match verdict { + ReviewVerdict::Ask(rule) => asks_by_rule(&reason, &rule), + // Nobody could check the person's "always ask" rules: ask, never go ahead. + ReviewVerdict::Failed => (Decision::Ask { reason: format!("{reason}{REVIEW_FAILED_NOTE}"), grant: String::new() }, true, String::new()), + // (No note on the result: the model doesn't need it, and it was on every step.) + _ => (Decision::Allow, false, String::new()), + } + } + (Decision::Ask { reason, grant }, Some(rv)) => match review_action(job, rv, name, args, &reason, cancel) { + ReviewVerdict::Allow(rule) => (Decision::Allow, false, format!("(自動審核:符合「{rule}」,直接允許)\n")), + ReviewVerdict::Ask(rule) => asks_by_rule(&reason, &rule), + ReviewVerdict::NoMatch => (Decision::Ask { reason, grant }, false, String::new()), + ReviewVerdict::Failed => (Decision::Ask { reason: format!("{reason}{REVIEW_FAILED_NOTE}"), grant }, true, String::new()), + }, + (d, _) => (d, false, String::new()), + } +} + +/// A connector's question with its arguments cut to their first 160 characters for the card +/// (`step`: the question as the reviewer read it, ending in the whole `args`, at the start of +/// `reason`; what follows it, a rule's note, stays). +fn card_args(reason: String, step: &str, args: &str) -> String { + match reason.strip_prefix(step) { + Some(rest) if args.chars().count() > 160 => { + let head = &step[..step.len() - args.len()]; + format!("{head}{}…{rest}", args.chars().take(160).collect::()) + } + _ => reason, + } +} + +/// MCP connectors: asked once per server, unless 「一律允許」 (gate step 6); else the person's +/// rules have their say as for any step (`reviewed`: 自動審核, and 直接操作 stops at an "always +/// ask" rule — it once let every connector step through unchecked). A tool run through +/// use_connector_tool is that tool: the same question, the same rules, the same call. pub(super) struct Connector; impl TurnTool for Connector { @@ -1510,22 +1556,32 @@ impl TurnTool for Connector { }; let (server, tool) = crate::mcp::resolve(&mcp_name).unwrap_or_default(); let grant = format!("mcp:{server}"); - let args_short: String = mcp_args.chars().take(160).collect(); - let mut allowed = job.direct.load(Ordering::Relaxed) || s.grants.contains(&grant); - if !allowed { - match s.ask_person(ApprovalKind::Action, format!("使用連接器「{server}」的工具:{tool} {args_short}"), grant.clone()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true, + // The reviewer reads every argument (nothing hides past the card's first 160 characters); + // the card shows the start. + let step = format!("使用連接器「{server}」的工具:{tool} {mcp_args}"); + let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: step.clone(), grant } }; + // (By the name it runs as: use_connector_tool's short name must not slip past a rule.) + let (decision, _, note) = reviewed(job, &mcp_name, &mcp_args, decision, false, cancel); + let allowed = match decision { + Decision::Allow => true, + Decision::Deny(_) => false, + Decision::Ask { reason, grant } => match s.ask_person(ApprovalKind::Action, card_args(reason, &step, &mcp_args), grant) { + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => true, ApprovalAnswer::Always(g) => { keep_grant(s.grants, g); - allowed = true; + true } - ApprovalAnswer::Reject => {} - } - } + ApprovalAnswer::Reject => false, + }, + }; if cancel.load(Ordering::Relaxed) { return Flow::End; } let (output, status, img) = if allowed { + // (After the connector's words, outside the part marked as theirs.) + if !note.is_empty() { + s.step_note.set(format!("\n{}", note.trim_end())); + } s.started(); let (o, ok, img) = crate::mcp::call_until(&mcp_name, &mcp_args, cancel); (o, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img) @@ -1665,56 +1721,11 @@ impl TurnTool for OnComputer { } _ => Decision::Allow, }; - // 自動審核: when the rules say yes, continue without asking (JOecNC); - // when an "always ask" rule matches, stop and ask (Pca/iV). - let mut review_note = String::new(); - let mut must_ask = false; - let direct = job.direct.load(Ordering::Relaxed); - let decision = match (decision, &job.review) { - // Direct mode: go ahead, unless an "always ask" rule matches. - (Decision::Ask { reason, grant }, review) if direct => { - // Only looking (a screenshot, a page or file read) changes nothing, so no - // "always ask" rule (deleting, paying, posting…) can be about it: no model - // 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() }, &call.name, &call.args, &reason, cancel), - _ => ReviewVerdict::NoMatch, - }; - match verdict { - ReviewVerdict::Ask(rule) => { - must_ask = true; - Decision::Ask { reason: format!("{reason}(符合你的「一律詢問」規則:{rule})"), grant: String::new() } - } - // Nobody could check the person's "always ask" rules: ask, never go ahead. - ReviewVerdict::Failed => { - must_ask = true; - Decision::Ask { reason: format!("{reason}{REVIEW_FAILED_NOTE}"), grant: String::new() } - } - // (No note on the result: the model doesn't need it, and it was on every step.) - _ => { - let _ = grant; - Decision::Allow - } - } - } - (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 - } - ReviewVerdict::Ask(rule) => { - must_ask = true; - Decision::Ask { reason: format!("{reason}(符合你的「一律詢問」規則:{rule})"), grant: String::new() } - } - ReviewVerdict::NoMatch => Decision::Ask { reason, grant }, - ReviewVerdict::Failed => { - must_ask = true; - Decision::Ask { reason: format!("{reason}{REVIEW_FAILED_NOTE}"), grant } - } - }, - (d, _) => d, - }; + // Only looking (a screenshot, a page or file read) changes nothing, so no + // "always ask" rule (deleting, paying, posting…) can be about it: no model + // 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 (decision, mut must_ask, mut review_note) = reviewed(job, &call.name, &call.args, decision, looks, cancel); // A click or key-submit whose target says money, sending, deleting: asked every // time, on every computer (local, remote device, or box), in direct mode too. // Harness policy: the model (and anything it read on a page) cannot grant its way past this one. diff --git a/src/app.rs b/src/app.rs index 9cc99f9..10df44a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -8868,6 +8868,43 @@ mod tests { crate::mcp::sync(&[]); } + /// 直接操作 turned on by its own switch (as 設定 › 權限 does), with an 「一律詢問」 rule about a + /// connector's tool: the step waits on a card that names the rule and offers no 「一律允許」 (it + /// used to run unasked); 一律放行 (/always-approve) still lets it through. + #[test] + fn direct_mode_still_asks_a_connector_step_its_ask_rule_names() { + let _l = crate::mcp::test_lock(); + let fake = crate::mcp::fake_server("calc-direct", 0); + assert!(crate::mcp::sync(std::slice::from_ref(&fake)).is_empty()); + let add = crate::mcp::tool_name("calc-direct", "add"); + let call = |id: &str| serde_json::json!({"tool_calls": [{"index": 0, "id": id, "function": {"name": add, "arguments": r#"{"a":2,"b":3}"#}}]}); + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-direct-mcp.png"))); + app.state.mcp_servers = vec![fake]; + let id = app.state.bots[0].id; + scripted_bot(&mut app, id, vec![call("c1"), serde_json::json!({"content": "好,不算"}), call("c2"), serde_json::json!({"content": "是 5"})]); + app.state.always_approve = false; + app.state.review_ask_rules = vec!["connector(calc-direct__add)".into()]; + app.enable_direct_mode(); + assert!(app.state.direct_mode && app.state.auto_review); + app.wake(&ctx, id, Message { memories_set: true, ..Message::user("算 2+3") }); + assert!(pump(&mut app, &ctx, |a| a.approvals.contains_key(&id)), "直接操作 ran it unasked: {:?}", app.state.bot(id).unwrap().messages.iter().rev().take(3).map(|m| m.text.chars().take(160).collect::()).collect::>()); + let a = &app.approvals[&id]; + assert!(a.reason.contains("符合你的「一律詢問」規則:connector(calc-direct__add)") && a.grant.is_empty(), "{} [{}]", a.reason, a.grant); + app.answer(&ctx, id, ApprovalAnswer::Reject); + assert!(pump(&mut app, &ctx, |a| !a.streams.contains_key(&id))); + // 一律放行: nothing is asked, it runs. + app.drafts.insert(id, "/always-approve".into()); + app.send(&ctx, id); + assert!(app.state.always_approve); + app.wake(&ctx, id, Message { memories_set: true, ..Message::user("再算一次") }); + assert!(pump(&mut app, &ctx, |a| !a.streams.contains_key(&id) || a.approvals.contains_key(&id))); + assert!(!app.approvals.contains_key(&id), "一律放行 asked: {:?}", app.approvals.get(&id).map(|a| a.reason.clone())); + let results: Vec = app.state.bot(id).unwrap().messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.text.clone()).collect(); + assert!(results.len() == 2 && results[0].contains("使用者拒絕了這個操作") && results[1].contains("sum=5"), "{results:?}"); + crate::mcp::sync(&[]); + } + /// 計畫 (/plan): typed, the bot hands in a plan on a card and waits; 開始照計畫做 and it goes on /// in the same turn, its steps move on, and a plan whose steps are all done says so and is gone. /// 「/plan」 says how it stands; 「/plan clear」 cancels; 先不要 drops it. From 3e1f960488218f63fc8051cae4a0a5a40a168dce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 19:18:38 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix:=20=E9=80=A3=E6=8E=A5=E5=99=A8=E3=80=8C?= =?UTF-8?q?=E4=B8=80=E5=BE=8B=E5=85=81=E8=A8=B1=E3=80=8D=E9=81=8E=E4=B9=9F?= =?UTF-8?q?=E7=85=A7=E6=A8=A3=E5=BC=8F=E7=9A=84=E3=80=8C=E4=B8=80=E5=BE=8B?= =?UTF-8?q?=E8=A9=A2=E5=95=8F=E3=80=8D=E5=95=8F=EF=BC=9B=E5=AF=A9=E6=A0=B8?= =?UTF-8?q?=E5=93=A1=E8=AE=80=E5=8F=83=E6=95=B8=E6=9C=89=E4=B8=8A=E9=99=90?= =?UTF-8?q?=EF=BC=9Bhook=20=E5=92=8C=E8=A6=8F=E5=89=87=E5=90=8C=E4=B8=80?= =?UTF-8?q?=E5=BC=B5=E5=8D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用者的決定:樣式寫的「一律詢問」(`connector(…)`,只比對、不問模型)蓋過連接器的「一律允許」。 以前 `mcp:slack` 一律允許過,`connector(slack__post_message)` 就擋不住。現在: - steps.rs 的 connector_decision(連接器一步的第 6–8 關,一個地方):先比對「一律詢問」樣式—— 符合就跳卡片寫那條規則、沒有「一律允許」(一律允許過、直接操作開著都一樣);再看一律允許; 其他照舊交給 reviewed()(自動審核/直接操作)。 - 用一般的話寫的規則不看一律允許過的連接器(使用者選的:不要每一步都問模型);地圖、FEATURES、 SECURITY 照實寫:直接操作的三條預設擋不住一律允許過的連接器,要擋就寫成樣式。以前的一律允許照樣有效。 - 一律放行、自動審核關著:不比對(跟其他步驟一樣)。 審查的 P2 一起改: - 審核員讀的參數有上限:4000 字以內全部,更長的給前 3000、後 1000,中間寫省略了幾字 (整段塞進去會撐爆模型的上下文、審核失敗);卡片照舊前 160 字。 - hook 的「ask」跟規則放在同一張卡(以前 run_call 先問一張、Connector 再問一張);run_call 的 通用 hook 詢問不再管 Connector。 - 新增 `connector(…)` 規則對不上任何連接器的工具(顯示名稱、大小寫、中文名稱的代號、64 字截斷) 時說出來:mcp::rule_names_nothing;電腦的設定頁在那條規則下面寫,手機新增時跳「已新增。不過…」。 Bot 沒有能加規則的工具,不用改。 - 地圖的用字:autonomy-still-asks、autonomy-review、autonomy-patterns 寫出一律允許過的例外; connectors 的陷阱不再一句寫「直接操作不問」又寫「直接操作也一樣」。 - connectors 加真的步驟「一律允許也照樣式問」;autonomy 原本的連接器步驟搬過去(autonomy 快到 9,000 字),autonomy 留走不到的步驟指過去。 特性表(新的 connector_decisions_are_characterized,38 列):一律允許 有/無 × 直接操作 有/無 × 規則(關著、詢問樣式、允許樣式、兩種樣式、別的連接器的樣式、話寫的規則〔審核員說詢問/都不符合/ 答不出來〕、允許樣式+話寫的詢問),加上 hook 兩列;每列寫 Allow/Allow+note/Ask[一律允許會記的] 和原因、問了模型幾次。tool_specs_are_locked、approval_decisions_are_characterized 沒有 diff。 沒改 remote.rs(loosens_guard 沒碰)。 已驗證: 全部 cargo test(不帶金鑰、DOCKER_HOST 指到不存在)679 通過;新的 an_ask_pattern_wins_over_a_connectors_grant、 a_hook_ask_and_a_rule_make_one_card_for_a_connector_step 在改之前失敗(一律允許過照跑、兩張卡), a_failed_review_asks_about_a_connector_step、the_reviewer_reads_a_huge_argument_by_its_ends、 a_connector_rule_that_names_nothing_is_said_so、connector_decisions_are_characterized、phone 的 rule_add 提醒; clippy -D warnings、lint-sh、verify-approval-routing run.sh --replay(跟基準一樣); verify-anybot:connectors 每一步可跑的照 md 原文冷跑全過(target/verify-anybot/20261118-180143: 打錯大小寫的規則跳提醒、一律允許過的 e0 照樣跳卡片、只有允許/拒絕,allow_rules 還是 ["mcp:echo"]), autonomy 也全過(-180216) 未驗證: 電腦設定頁那行提醒的樣子(要開視窗);直接操作那一半的實機(區網的手機打不開,用 app 層測試); --ignored 的實機測試 未簽: 審批路徑——要人類簽名才能合併,沒有合併、沒有推 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- FEATURES.md | 4 +- SECURITY.md | 3 +- docs/feature-map/autonomy.md | 13 +-- docs/feature-map/connectors.md | 5 +- docs/feature-map/safety.md | 2 +- mobile/index.html | 2 +- src/agent.rs | 197 +++++++++++++++++++++++++++++++-- src/agent/steps.rs | 83 ++++++++++---- src/app.rs | 4 + src/app/remote_ui.rs | 7 ++ src/mcp.rs | 23 ++++ 11 files changed, 296 insertions(+), 47 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 1ce49c8..3cfb6a8 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -823,7 +823,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 滑鼠和鍵盤:「操作你的滑鼠和鍵盤:…」,可以一律允許。 - 讀你瀏覽器的分頁:「讀取你瀏覽器目前分頁的內容(包含已登入的頁面):目前的分頁」,可以一律允許。單純打開連結不用問。 - 檔案和指令:照第 19 節的安全規則決定。被擋下時顯示「被安全規則擋下:{原因}」。 - - 連接器的工具:每個連接器第一次問「使用連接器「X」的工具:…」,可以一律允許。 + - 連接器的工具:每個連接器第一次問「使用連接器「X」的工具:…」,可以一律允許;一律允許過的,符合樣式的「一律詢問」照樣問。 7. **自動審核或直接操作**:見第 15 節和第 8 節(連接器的工具也是)。 8. **一般請求** - 允許一次。 @@ -1501,7 +1501,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 都沒寫:本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`(自己設了同名變數的話用自己的);遠端伺服器收到 `Authorization: Basic …`(自己有 Authorization 標頭的話不加)。 - 密碼跟金鑰一樣:螢幕只看得到「已設定」,不會拿到內容;在螢幕上改指令或網址時,大腦會把密碼清掉(不然會被送到新的位址)。 - **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。 -- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;符合「一律詢問」的照樣問、沒有「一律允許」——直接操作模式下也一樣(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」規則都不看)。用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀全部的參數,卡片只列前 160 字。一律允許過的連接器直接做,不再看規則(第 16 節第 6 步在第 7 步之前)。 +- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。自動審核開著時:符合樣式的「一律詢問」(例如 `connector(slack__post_message)`)每次問、沒有「一律允許」——直接操作模式下、連接器一律允許過也一樣(只比對樣式,不問模型)。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;用一般的話寫的「一律詢問」由審核員判斷。一律允許過的連接器不再給審核員看:用一般的話寫的規則,包括直接操作填的三條預設(「用我的帳號發文、留言,或傳訊息給別人」…),擋不住它,要擋就寫成樣式。(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」都不看。)用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀參數的前 3000 字和最後 1000 字(更長的中間省略),卡片只列前 160 字。hook 的「ask」跟規則放在同一張卡。新增 `connector(…)` 規則時對不上任何連接器的工具(寫成顯示的名稱、大小寫不對、中文名稱要寫代碼、超過 64 字被截掉),設定頁和手機會說。 - 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。按停止時,本機連接器的呼叫馬上結束(以前要等到它回或 120 秒);用網址連的照樣等。 - 連接器關掉、移除、重新連線或連不上時,連同它帶起來的所有程式一起關(npx/uvx/sh 底下真正的伺服器以前會一直留著)。 - **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 diff --git a/SECURITY.md b/SECURITY.md index 532e6cf..5c7e0e8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,7 +54,8 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - gVisor 是加分不是標配:純 Docker 的 box 與主機共享核心。 - 備份安全性以你的帳號密碼強度為上限。 - relay 是自架元件:它被攻破時洩露的是雜湊、session 清單與備份密文,不是明文。 +- 「一律允許」過的連接器只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它。 ## 硬化建議 -磁碟加密(FileVault/LUKS);供應商金鑰開額度上限與 2FA;relay 只開 HTTPS 並開 2FA;box 主機裝 gVisor;把「一律詢問」開在你常用的敏感 App 上。 +磁碟加密(FileVault/LUKS);供應商金鑰開額度上限與 2FA;relay 只開 HTTPS 並開 2FA;box 主機裝 gVisor;把「一律詢問」開在你常用的敏感 App 上;要擋連接器的某個動作,寫成固定樣式(例如 `connector(slack__post_message)`),一律允許過也擋得住。 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index 2d20766..50ed378 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -6,9 +6,9 @@ - `autonomy-direct` 直接操作:打開時一次做完——打開「在這台電腦上執行」、自動審核、所有 Bot 的電腦工具;「一律詢問」規則是空的就填三條預設(刪除檔案或資料夾/付款、購買或轉帳/用我的帳號發文、留言,或傳訊息給別人);進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。 - `autonomy-yolo` 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的也不問,自動審核也略過。仍然擋:安全規則一律拒絕的;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方、臉的同一行右邊有一個紅色閃電圖示(不另外佔一行;新對話沒有臉時自己一小行):滑過去看「一律放行 · Bot 做事不再問你」和還會擋什麼,點一下有「關閉一律放行」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 -- `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具也算);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 -- `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具也經過它。 -- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:沒「一律允許」過的步驟,符合「一律詢問」的樣式一定問(模型說允許也沒用);符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。 +- `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具也算;「一律允許」過的連接器只比對樣式);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 +- `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具也經過它,「一律允許」過的除外。 +- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟和連接器的工具(「一律允許」過也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。`connector(…)` 對不上任何連接器的工具時,新增的地方會說。 - `autonomy-hooks` Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 自己出錯(結束碼不對、逾時、JSON 看不懂)就當它不在,紀錄檔寫原因。 - `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機關得掉,但打不開直接操作、新增不了「無需詢問直接允許」規則和連接器(「這項設定會讓 Bot 不用問就動手,不能從區網連線…打開」);要在電腦上的 AnyBot,或用帳號連線。 @@ -31,10 +31,9 @@ - **hook 照樣問、擋下一步**(covers `autonomy-hooks`、`autonomy-yolo`):一律放行開著,請 Bot 加一個擋 `shell` 的 hook,按允許,再請它跑指令。指令:`$CTL phone send '加 hook [[call manage_hooks {"action":"add","event":"PreToolUse","matcher":"shell","command":"echo 這一步被 hook 擋下 >&2; exit 2"}]]' && $CTL phone wait '#ask .ask' && $CTL phone shot autonomy-hook-card && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "manage_hooks") | .status] == ["done"]' && $CTL datafile hooks/hooks.json && $CTL phone send '跑 [[call shell {"command":"echo hi"}]]' && $CTL phone wait-text 'hook 擋下了這一步' --in '#msgs'`。看到:一律放行也跳「新增一個 hook:每次「PreToolUse」…」的卡片;hooks.json 有那條;指令沒跑,「沒有執行:使用者設定的 hook 擋下了這一步。它說:這一步被 hook 擋下」。 - **看狀態、關掉**(covers `autonomy-yolo`):打「/always-approve status」「/always-approve off」,再請它改名。指令:`$CTL phone send '/always-approve status' && $CTL phone wait-text '現在是一律放行' --in '#msgs' && $CTL phone send '/always-approve off' && $CTL phone wait-text '已關閉一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == false' && $CTL phone send '再改 [[call update_bot {"name":"關掉後的名字"}]]' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了這個操作' --in '#msgs'`。看到:「現在是一律放行…」「已關閉一律放行:…「直接操作」也關了」;改名又跳卡片。 - **手機打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):重新整理,帳戶選單 › 設定 › 權限,按「直接操作」。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '刪除檔案或資料夾' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '不能從區網連線' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」裡三條預設規則;按開關、確認「打開」後跳出「這項設定會讓 Bot 不用問就動手,不能從區網連線…」,直接操作還是關的。 -- **連接器照規則問**(covers `autonomy-review`、`autonomy-patterns`):自動審核還開著(一律放行打開的),在「一律詢問(優先)」新增 `connector(echo__e0)`;回聊天加兩個工具的 echo([connectors](connectors.md)),叫 e0 按「拒絕」;審核員說都不符合時叫 e1、按「允許一次」;說詢問時再叫 e1。指令:`$CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'connector(echo__e0)' && $CTL phone click '#ask-ok' && $CTL phone wait-text 'connector(echo__e0)' --in '#list' && $CTL phone shot autonomy-connector-rule && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '加 [[call manage_connectors {"action":"add","name":"echo","command":"node -e eval(process.env.MCP_JS) 2","env":{"MCP_JS":"require(\"readline\").createInterface({input:process.stdin}).on(\"line\",l=>{let m=JSON.parse(l);m.id!=null&&console.log(JSON.stringify({id:m.id,result:m.method==\"tools/list\"?{tools:[...Array(+process.argv[1]||1)].map((_,i)=>({name:\"e\"+i}))}:{content:[{type:\"text\",text:\"echo \"+m.params?.arguments?.text}]}}))})"}}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text '已連上,2 個工具' && $CTL phone send '[[call mcp__echo__e0 {"text":"hi"}]]' && $CTL phone wait-text '規則:connector(echo__e0)' --in '#ask' && $CTL phone shot autonomy-connector-ask && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL model-reply 你是動作審核員 '{"verdict":"none","rule":""}' && $CTL phone send '[[call mcp__echo__e1 {"text":"ok"}]]' && $CTL phone wait '#ask button[data-a="always"]' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text 'echo ok' --in '#msgs' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"用我的帳號發文、留言,或傳訊息給別人"}' && $CTL phone send '[[call mcp__echo__e1 {"text":"again"}]]' && $CTL phone wait-text '規則:用我的帳號發文' --in '#ask' && $CTL phone shot autonomy-connector-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL state '.bots[0].allow_rules'`。看到:「…想要用連接器」卡片「使用連接器「echo」的工具:e0 …(符合你的「一律詢問」規則:connector(echo__e0))」只有「允許」「拒絕」;e1 是一般的卡(有「一律允許」),允許後回「echo ok」;審核員讀到「要審核的動作:使用連接器「echo」的工具:e1 …」,說詢問就跳寫著那條規則的卡;allow_rules 還是 []。 - **桌面的閃電圖示**(covers `autonomy-yolo`):指令:要開視窗——第一步之後 `$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot autonomy-yolo ANYBOT_SHOT_REAL=1 && $CTL serve`。看到:臉的同一行右邊一個紅色閃電圖示。 -- **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 -- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 +- **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:連接器的樣式(「一律允許」過也問)在 [connectors](connectors.md) 的「一律允許也照樣式問」;最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 +- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 ## 陷阱 @@ -42,7 +41,7 @@ - hook 在大腦上、用使用者的身分、在 Bot 的沙盒外跑:只加看得懂的指令。每一步都會跑 PreToolUse,慢的 hook 會讓 Bot 變慢(預設最多等 60 秒)。 - 外面的訊息和團隊成員的訊息不用你的直接操作和自動審核:要核准的事都得你親手按。 - 自動審核靠模型讀規則,寫得含糊會判錯;內建的安全規則不靠它。 -- 「一律允許」過的(例如某個連接器,整個連接器的工具都算)直接做,不再看自動審核和「一律詢問」規則:要它每次照規則問,先在 Bot 設定移除那條「一律允許」。 +- 「一律允許」過的連接器(整個連接器的工具都算)只再比對樣式寫的「一律詢問」;用一般的話寫的,包括直接操作填的三條預設,擋不住它:要擋就寫成樣式,例如 `connector(slack__post_message)`。指令、檔案「一律允許」過的不再看規則。 - 直接操作開著、「一律詢問」有用話寫的規則時,沒「一律允許」過的連接器每一步都先等審核模型看一次(慢一點);例行任務碰到符合的會停下來等你。 - 手機的設定頁(權限、一般…)不會自己更新:別處改了(例如一律放行填了預設規則)要重新整理才看得到。 - (驗證)hook 擋 `update_bot` 的話,後面改名的步驟都會被擋;示範用不用問的 `shell`。 diff --git a/docs/feature-map/connectors.md b/docs/feature-map/connectors.md index e4db365..fa84d26 100644 --- a/docs/feature-map/connectors.md +++ b/docs/feature-map/connectors.md @@ -33,15 +33,16 @@ - **加連接器要先問**(covers `connectors-chat`、`connectors-local`、`connectors-password`、`connectors-instructions`):請 Bot 加 echo,允許。指令:`$CTL phone send '加 [[call manage_connectors {"action":"add","name":"echo","command":"node -e eval(process.env.MCP_JS)","env":{"MCP_JS":"require(\"readline\").createInterface({input:process.stdin}).on(\"line\",l=>{let m=JSON.parse(l),a=m.params?.arguments;m.id!=null&&console.log(JSON.stringify({id:m.id,result:m.method==\"tools/list\"?{tools:[...Array(+process.argv[1]||1)].map((_,i)=>({name:\"e\"+i}))}:{content:[{type:\"text\",text:\"echo \"+a?.text+\" \"+process.env.MCP_USERNAME}]}}))})"},"username":"alice","password":"pw","instructions":"ECHO-說明"}]]' && $CTL phone wait-text '••••(已填)' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text '已連上,1 個工具' && $CTL model-reply ECHO-說明 說明有帶到 && $CTL phone send '說明呢' && $CTL phone wait-text 說明有帶到 && $CTL model-reply --clear`。看到:卡片「新增連接器「echo」(加在大腦的…)」列指令、環境變數、「帳號:alice · 密碼:••••(已填)」、說明;允許後同一輪回「已連上,1 個工具」;說明進了 system。 - **第一次用要問**(covers `connectors-call`、`connectors-tools`、`connectors-password`):叫 e0,按「一律允許」再叫。指令:`$CTL phone send '叫 [[call mcp__echo__e0 {"text":"hi"}]]' && $CTL phone click '#ask button[data-a="always"]' && $CTL phone wait-text 'echo hi alice' && $CTL phone send '再叫 [[call mcp__echo__e0 {"text":"again"}]]' && $CTL phone wait-text 'echo again alice' && $CTL state '.bots[0].allow_rules'`。看到:卡片「使用連接器「echo」的工具:e0 …」有「一律允許」;結果標成 ``、帶著 alice;第二次不問;Bot 記著 `mcp:echo`。 +- **一律允許也照樣式問**(covers `connectors-call`):自動審核打開,「一律詢問」先加大小寫打錯的 `connector(Echo__e0)`、再加 `connector(echo__e0)`,回聊天叫已經一律允許的 e0,按「拒絕」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone click 'label.sw:has([data-sset="auto_review"])' && $CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'connector(Echo__e0)' && $CTL phone click '#ask-ok' && $CTL phone wait-text '對不上任何連接器的工具' && $CTL phone shot connectors-rule-warn && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'connector(echo__e0)' && $CTL phone click '#ask-ok' && $CTL wait-api /api/settings '.ask_rules == ["connector(Echo__e0)","connector(echo__e0)"]' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call mcp__echo__e0 {"text":"rule"}]]' && $CTL phone wait-text '規則:connector(echo__e0)' --in '#ask' && $CTL phone shot connectors-rule-ask && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了這個操作' --in '#msgs' && $CTL state '.bots[0].allow_rules'`。看到:打錯的那條加了,但跳出「已新增。不過「connector(Echo__e0)」對不上任何連接器的工具:比對的是工具名稱 mcp__ 後面那段…現在有:echo__*」;一律允許過的 e0 照樣跳卡片「…(符合你的「一律詢問」規則:connector(echo__e0))」,只有「允許」「拒絕」;沒有執行,allow_rules 還是 ["mcp:echo"]。 - **超過 20 個**(covers `connectors-tools`、`connectors-chat`):改成 21 個:直接叫不到,先找再用。指令:`$CTL phone send '改 [[call manage_connectors {"action":"update","name":"echo","command":"node -e eval(process.env.MCP_JS) 21"}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text '21 個工具' && $CTL phone send '叫 [[call mcp__echo__e0 {}]]' && $CTL phone wait-text '沒有 mcp__echo__e0' && $CTL phone send '找 [[call find_connector_tool {"server":"echo"}]]' && $CTL phone wait-text mcp__echo__e10 && $CTL phone send '用 [[call use_connector_tool {"tool":"mcp__echo__e20","arguments":{"text":"many"}}]]' && $CTL phone wait-text 'echo many'`。看到:卡片寫「密碼清掉…」;之後只有找和用。 - **手機上關掉**(covers `connectors-close`):設定 › 整合關掉 echo,再找。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '已連上,21 個工具' --in '#list' && $CTL phone click 'label.sw:has([data-mcp="echo"])' && $CTL phone wait-text 已關閉 --in '#list' && $CTL procs --none process.env.MCP_JS && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '找 [[call find_connector_tool {"server":"echo"}]]' && $CTL phone wait-text '沒有 find_connector_tool'`。看到:「已關閉」,node 結束;新一輪沒有連接器工具。 - **移除**(covers `connectors-chat`、`connectors-close`):指令:`$CTL phone send '移除 [[call manage_connectors {"action":"remove","name":"echo"}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/settings '.mcp == []' && $CTL state '.bots[0].allow_rules'`。看到:卡片「移除連接器「echo」…」;`mcp:echo` 也沒了。 - **遠端、登入**(covers `connectors-remote`、`connectors-oauth`):指令:走不到——要真的遠端和登入伺服器。看到:最接近的是 `cargo test mcp::`(`http_answers_json_or_sse`、`the_login_reaches_the_server`)。 -- 自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`、`cargo test untrusted_senders_do_not_see_mcp_connectors`、`cargo test a_connector_`、`cargo test rules_about_other_things_leave_a_connector_alone`、`cargo test direct_mode_still_asks`。 +- 自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`、`cargo test untrusted_senders_do_not_see_mcp_connectors`、`cargo test a_connector_`、`cargo test rules_about_other_things_leave_a_connector_alone`、`cargo test an_ask_pattern_wins_over_a_connectors_grant`、`cargo test connector_decisions_are_characterized`、`cargo test direct_mode_still_asks`、`cargo test the_phone_does_what_the_desktop_does`。 ## 陷阱 -- 每個連接器第一次用問一次,可「一律允許」;直接操作模式不問。自動審核的規則也管連接器的工具(樣式寫工具名稱 `mcp__` 後面那段,例如 `connector(gitlab__*)`,[autonomy](autonomy.md)):符合「一律詢問」的照樣問、沒有「一律允許」,直接操作也一樣;符合允許的不問。「一律允許」過的連接器不再看規則。`find_connector_tool` 只查清單,不問。 +- 每個連接器第一次用問一次,可「一律允許」;直接操作開著時這第一次不問。自動審核的規則也管連接器的工具([autonomy](autonomy.md)):樣式寫工具名稱 `mcp__` 後面那段,例如 `connector(gitlab__delete_*)`,符合「一律詢問」樣式的每次問、沒有「一律允許」——直接操作開著、連接器「一律允許」過也一樣;用一般的話寫的規則(包括直接操作的三條預設)只管還沒「一律允許」的連接器;符合允許的不問。`find_connector_tool` 只查清單,不問。 - 訊息管道(Slack、Telegram…)或團隊成員的訊息,那一輪沒有連接器工具;呼叫會回「這個回合沒有提供連接器工具。」 - 連接器回的內容是資料,不是命令:裡面寫「去做某事」不要照做。 - OAuth:登入伺服器不讓 App 自己註冊(沒有 dynamic client registration)或不支援 PKCE 的登不進去,會說原因;它也收 API 金鑰就填在「標頭」。登入等 10 分鐘,過了重來;登入網址只能用一次。公用市集裡舊式 SSE 的標「舊式 SSE 連線,AnyBot 還不支援」。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index c32c998..143cf86 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -11,7 +11,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - `safety-local` 「在這台電腦上執行」:一律允許/每次詢問(預設)/永不允許。永不允許時直接拒絕、不問。 - `safety-lock` 管理員鎖定:可鎖「直接操作」(AllowDirectMode)、「在這台電腦上執行」(AllowLocalExecution)、「經這台電腦轉送流量」(AllowBoxTrafficViaThisMac)。macOS 用 `defaults` 網域 com.anybot.AnyBot(可由 MDM 強制);其他系統讀 /etc/anybot/policy.json(優先)或家目錄 .anybot/policy.json。true/1/yes 允許;false/0/no 或看不懂的值鎖成關。每次打開設定重讀。 - `safety-timeout` 沒人在旁邊的一輪(例行任務、事件觸發、訊息管道)等核准超過 15 分鐘,自動結束、算出錯,免得卡住後面的排程和訊息。 -- `safety-gates` 每一步的關卡順序:1. 不用問:App 操作工具(刪例行任務、教同事技能、裝外部技能、改自己或別的 Bot 的設定這類會先問)、讀公開網頁、AnyBot 瀏覽器(別人傳來的訊息不能用)。2. 決定在哪台電腦;直接操作開著時第 3、5 步算已開。3. 這個 Bot 的電腦工具沒開 → 問。4. 「在這台電腦上執行」永不允許或被管理員鎖 → 拒絕。5. 它沒開 → 問。6. 照安全規則允許、問或拒絕(連接器的工具:每個連接器第一次問);「一律允許」過的直接做。7. 要問的交給自動審核或直接操作(連接器的工具也是)。8. 「每次都問」的蓋過第 6、7 步。9. 問你;等的時候按停止=拒絕。 +- `safety-gates` 每一步的關卡順序:1. 不用問:App 操作工具(刪例行任務、教同事技能、裝外部技能、改自己或別的 Bot 的設定這類會先問)、讀公開網頁、AnyBot 瀏覽器(別人傳來的訊息不能用)。2. 決定在哪台電腦;直接操作開著時第 3、5 步算已開。3. 這個 Bot 的電腦工具沒開 → 問。4. 「在這台電腦上執行」永不允許或被管理員鎖 → 拒絕。5. 它沒開 → 問。6. 照安全規則允許、問或拒絕(連接器的工具:每個連接器第一次問);「一律允許」過的直接做(連接器符合樣式的「一律詢問」照樣問)。7. 要問的交給自動審核或直接操作(連接器的工具也是)。8. 「每次都問」的蓋過第 6、7 步。9. 問你;等的時候按停止=拒絕。 ## 使用者怎麼到 diff --git a/mobile/index.html b/mobile/index.html index 0409585..7cb1368 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2493,7 +2493,7 @@ function wireSettings(kind, st) { if (k === "direct_mode" && x.checked && !await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) { x.checked = false; return; } if (!await act("setting", {key: k, value: x.checked})) x.checked = !x.checked; else again(); }); - on("[data-addrule]", "onclick", async (x) => { const t = await ask(x.dataset.addrule === "ask" ? "一律詢問的規則" : "無需詢問的規則", "", x.dataset.addrule === "ask" ? "例如:發文、寄信、付款前先問我" : "例如:讀取網頁和檔案"); if (t && await act("setting", {key: "rule_add", list: x.dataset.addrule, value: t}, "已新增")) again(); }); + on("[data-addrule]", "onclick", async (x) => { const t = await ask(x.dataset.addrule === "ask" ? "一律詢問的規則" : "無需詢問的規則", "", x.dataset.addrule === "ask" ? "例如:發文、寄信、付款前先問我" : "例如:讀取網頁和檔案"); if (t && await act("setting", {key: "rule_add", list: x.dataset.addrule, value: t})) again(); }); on("[data-rmrule]", "onclick", async (x) => { if (await act("setting", {key: "rule_remove", list: x.dataset.rmrule, value: x.dataset.r}, "已移除")) again(); }); on("[data-ch]", "onchange", async (x) => { if (!await act("channel", {id: +x.dataset.ch, enabled: x.checked})) x.checked = !x.checked; else again(); }); on("[data-chrm]", "onclick", async (x) => { if (await confirmSheet("移除這個管道?", "", "移除") && await act("channel", {id: +x.dataset.chrm, remove: true}, "已移除")) again(); }); diff --git a/src/agent.rs b/src/agent.rs index 6ea7043..8e61920 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1874,9 +1874,9 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { browser: Default::default(), }; let tool = steps::tool_for(&s); - // A hook's 「ask」: OnComputer puts it with its own question; every other tool asks here - // (a connector already allowed, an app action, a file sent out… would have gone ahead). - if tool.name() != "OnComputer" { + // A hook's 「ask」: OnComputer and Connector put it with their own question (one card); every + // other tool asks here (an app action, a file sent out… would have gone ahead). + if !matches!(tool.name(), "OnComputer" | "Connector") { if let Some(why) = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, w)| w) { let answer = s.ask_person(ApprovalKind::Action, format!("{}(你的 hook 要先問:{})", s.what(), if why.is_empty() { "沒有說原因" } else { why.as_str() }), String::new()); if s.cancel.load(Ordering::Relaxed) { @@ -4620,7 +4620,13 @@ echo 'done送出了' > done.html; (setsid pyt /// answered `answer`. Returns each card's question and the grant its 「一律允許」 would keep, /// the step results, and every request the model got. #[allow(clippy::type_complexity)] - fn connector_turn(server: &str, mut replies: Vec<(u16, String)>, direct: bool, review: Option, grants: &[&str], answer: ApprovalAnswer) -> (Vec<(String, String)>, Vec, Vec) { + fn connector_turn(server: &str, replies: Vec<(u16, String)>, direct: bool, review: Option, grants: &[&str], answer: ApprovalAnswer) -> (Vec<(String, String)>, Vec, Vec) { + connector_turn_of(1, server, replies, direct, review, grants, answer) + } + + /// [`connector_turn`] as bot `bot` (whose hooks a test may set). + #[allow(clippy::type_complexity)] + fn connector_turn_of(bot: u64, server: &str, mut replies: Vec<(u16, String)>, direct: bool, review: Option, grants: &[&str], answer: ApprovalAnswer) -> (Vec<(String, String)>, Vec, Vec) { let _one = crate::mcp::test_lock(); assert!(crate::mcp::sync(&[crate::mcp::fake_server(server, 0)]).is_empty()); replies.push(sse_text("好")); @@ -4633,7 +4639,7 @@ echo 'done送出了' > done.html; (setsid pyt ..test_job() }; let (tx, rx) = channel(); - spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + spawn(job, bot, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); let (mut asked, mut results) = (vec![], vec![]); loop { match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { @@ -4706,8 +4712,7 @@ echo 'done送出了' > done.html; (setsid pyt /// The other way round: rules about other connectors, commands or files don't stop a /// connector's step — 直接操作 runs it with no model call; without it the card is the usual one - /// (「一律允許」 this connector), as with 自動審核 off; a connector already 「一律允許」 goes ahead - /// (gate step 6 before step 7, as for a command). + /// (「一律允許」 this connector), as with 自動審核 off. #[test] fn rules_about_other_things_leave_a_connector_alone() { let add = crate::mcp::tool_name("calc-free", "add"); @@ -4721,9 +4726,181 @@ echo 'done送出了' > done.html; (setsid pyt assert!(asked[0].0.starts_with("使用連接器「calc-free」的工具:add") && asked[0].1 == "mcp:calc-free", "the usual card: {asked:?}"); assert!(results[0].contains("sum=3"), "{results:?}"); } - let mine = Review { allow: vec![], ask: vec!["connector(calc-free__add)".into()] }; - let (asked, results, _) = connector_turn("calc-free", call(), false, Some(mine), &["mcp:calc-free"], ApprovalAnswer::Reject); - assert!(asked.is_empty() && results[0].contains("sum=3"), "{asked:?} {results:?}"); + } + + /// The person's decision: a connector already 「一律允許」 (every tool of it) still answers to + /// the 「一律詢問」 patterns — only compared, no model call — with or without 直接操作: a card + /// naming the rule, no 「一律允許」. Sentence rules (the three defaults too) don't stop it, and + /// with 自動審核 off nothing is compared. + #[test] + fn an_ask_pattern_wins_over_a_connectors_grant() { + let add = crate::mcp::tool_name("calc-grant", "add"); + let call = || vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2}))]; + let granted = &["mcp:calc-grant"]; + for direct in [false, true] { + let mine = Review { allow: vec![], ask: vec!["connector(calc-grant__add)".into()] }; + let (asked, results, seen) = connector_turn("calc-grant", call(), direct, Some(mine), granted, ApprovalAnswer::Reject); + assert_eq!(asked.len(), 1, "direct={direct}: {asked:?}"); + assert!(asked[0].0.contains("符合你的「一律詢問」規則:connector(calc-grant__add)") && asked[0].1.is_empty(), "{asked:?}"); + assert!(!results[0].contains("sum=") && seen.len() == 2, "not run, no model call: {results:?}"); + } + let words = Review { allow: vec![], ask: crate::model::DEFAULT_ASK_RULES.iter().map(|r| r.to_string()).collect() }; + let (asked, results, seen) = connector_turn("calc-grant", call(), true, Some(words), granted, ApprovalAnswer::Reject); + assert!(asked.is_empty() && results[0].contains("sum=3") && seen.len() == 2, "sentences aren't read for a granted connector: {asked:?} {results:?}"); + let (asked, results, _) = connector_turn("calc-grant", call(), false, None, granted, ApprovalAnswer::Reject); + assert!(asked.is_empty() && results[0].contains("sum=3"), "自動審核 off: {asked:?} {results:?}"); + } + + /// A connector step's decision on fixed rules, as Allow / Allow+note (自動審核 let it, the result + /// says so) / Ask[the grant 「一律允許」 would keep] with why (rule=…, failed, hook), and how many + /// times the reviewer model was asked — 「一律允許」 for the connector or not × 直接操作 or not × + /// the person's rules. Locking these locks how connector steps are approved (the person's + /// decision: an 「一律詢問」 pattern wins over a grant; sentences aren't read for a granted one). + #[test] + fn connector_decisions_are_characterized() { + use crate::testkit::{Fake, Format, Reply}; + let _one = crate::mcp::test_lock(); + assert!(crate::mcp::sync(&[crate::mcp::fake_server("calc-ch", 0)]).is_empty()); + let add = crate::mcp::tool_name("calc-ch", "add"); + let says = |text: &str| Fake::start(Format::OpenAi, vec![], Some(Reply::text(text))); + let (ask, none, garbled) = (says(r#"{"verdict":"ask","rule":"傳訊息給別人前先問我"}"#), says(r#"{"verdict":"none","rule":""}"#), says("嗯…讓我想想")); + let rules = |allow: &[&str], ask: &[&str]| Some(Review { allow: allow.iter().map(|r| r.to_string()).collect(), ask: ask.iter().map(|r| r.to_string()).collect() }); + let words = "傳訊息給別人前先問我"; + let sets: Vec<(&str, Option, &Fake)> = vec![ + ("off", None, &none), + ("ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none), + ("allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none), + ("both-patterns", rules(&["connector(calc-ch__*)"], &["connector(calc-ch__add)"]), &none), + ("other-connector", rules(&["connector(other__*)"], &["connector(other__*)"]), &none), + ("sentence:ask", rules(&[], &[words]), &ask), + ("sentence:none", rules(&[], &[words]), &none), + ("sentence:garbled", rules(&[], &[words]), &garbled), + ("allow-pattern+sentence:ask", rules(&["connector(calc-ch__*)"], &[words]), &ask), + ]; + let shape = |d: &Decision, note: &str| match d { + Decision::Allow if note.is_empty() => "Allow".to_string(), + Decision::Allow => "Allow+note".to_string(), + Decision::Deny(_) => "Deny".to_string(), + Decision::Ask { reason, grant } => { + let why = if let Some(r) = reason.split("規則:").nth(1) { + format!(" rule={}", r.split(')').next().unwrap_or("")) + } else if reason.contains(REVIEW_FAILED_NOTE) { + " failed".into() + } else { + String::new() + }; + let hook = if reason.contains("你的 hook 要先問") { " +hook" } else { "" }; + format!("Ask[{grant}]{why}{hook}") + } + }; + let mut got = vec![]; + for (set, review, fake) in &sets { + for granted in [false, true] { + for direct in [false, true] { + let job = Job { req: ChatRequest { base_url: fake.base(), model: "m".into(), ..test_job().req }, review: review.clone(), direct: Arc::new(AtomicBool::new(direct)), ..test_job() }; + let grants: Vec = if granted { vec!["mcp:calc-ch".into()] } else { vec![] }; + let before = fake.requests(); + let (d, note) = steps::connector_decision(&job, &grants, &add, r#"{"a":1,"b":2}"#, None, &AtomicBool::new(false)); + got.push(format!("{set} granted={granted} direct={direct}: {} model={}", shape(&d, ¬e), fake.requests() - before)); + } + } + } + // A hook's 「ask」 on the same card. + for (set, review, granted) in [("hook", None, true), ("hook+ask-pattern", rules(&[], &["connector(calc-ch__add)"]), false)] { + let job = Job { req: ChatRequest { base_url: none.base(), model: "m".into(), ..test_job().req }, review, ..test_job() }; + let grants: Vec = if granted { vec!["mcp:calc-ch".into()] } else { vec![] }; + let (d, note) = steps::connector_decision(&job, &grants, &add, r#"{"a":1,"b":2}"#, Some("先給我看"), &AtomicBool::new(false)); + got.push(format!("{set} granted={granted} direct=false: {} model=0", shape(&d, ¬e))); + } + crate::mcp::sync(&[]); + let rule_a = " rule=connector(calc-ch__add)"; + let rule_w = format!(" rule={words}"); + let want: Vec = [ + ("off", ["Ask[mcp:calc-ch] model=0", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("ask-pattern", [0; 4].map(|_| format!("Ask[]{rule_a} model=0"))), + ("allow-pattern", ["Allow+note model=0", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("both-patterns", [0; 4].map(|_| format!("Ask[]{rule_a} model=0"))), + ("other-connector", ["Ask[mcp:calc-ch] model=0", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("sentence:ask", [format!("Ask[]{rule_w} model=1"), format!("Ask[]{rule_w} model=1"), "Allow model=0".into(), "Allow model=0".into()]), + ("sentence:none", ["Ask[mcp:calc-ch] model=1", "Allow model=1", "Allow model=0", "Allow model=0"].map(String::from)), + ("sentence:garbled", ["Ask[mcp:calc-ch] failed model=1", "Ask[] failed model=1", "Allow model=0", "Allow model=0"].map(String::from)), + ("allow-pattern+sentence:ask", [format!("Ask[]{rule_w} model=1"), format!("Ask[]{rule_w} model=1"), "Allow model=0".into(), "Allow model=0".into()]), + ] + .into_iter() + .flat_map(|(set, four)| [(false, false), (false, true), (true, false), (true, true)].into_iter().zip(four).map(move |((g, d), w)| format!("{set} granted={g} direct={d}: {w}"))) + .chain(["hook granted=true direct=false: Ask[] +hook model=0".to_string(), format!("hook+ask-pattern granted=false direct=false: Ask[]{rule_a} +hook model=0")]) + .collect(); + assert_eq!(got, want); + } + + /// A huge argument reaches the reviewer by its two ends, saying how much was left out (whole, + /// it filled the model's context and the review failed); a short one whole. + #[test] + fn the_reviewer_reads_a_huge_argument_by_its_ends() { + let big = format!("HEAD{}TAIL", "x".repeat(10_000)); + let r = steps::for_reviewer(&big); + assert!(r.starts_with("HEAD") && r.ends_with("TAIL") && r.contains("…(中間省略 6008 字)…") && r.chars().count() < 4_100, "{}", r.chars().count()); + assert_eq!(steps::for_reviewer(r#"{"a":1}"#), r#"{"a":1}"#); + } + + /// A 「connector(…)」 rule is checked against what it is compared with (the part of a tool's + /// name after mcp__): a connected tool, a connector not connected now; else the person is told. + #[test] + fn a_connector_rule_that_names_nothing_is_said_so() { + let _one = crate::mcp::test_lock(); + let calc = crate::mcp::fake_server("calc-name", 0); + assert!(crate::mcp::sync(std::slice::from_ref(&calc)).is_empty()); + let off = crate::mcp::Server { name: "公司系統".into(), ..calc.clone() }; + let servers = vec![calc.clone(), off.clone()]; + let key = crate::mcp::server_key("公司系統"); + let says = |r: &str| crate::mcp::rule_names_nothing(r, &servers); + assert_eq!(says("connector(calc-name__add)"), None); + assert_eq!(says("connector(calc-name__*)"), None); + assert_eq!(says(&format!("connector({key}__*)")), None, "not connected: its key is enough"); + assert_eq!(says("付款前先問我"), None, "a sentence"); + assert_eq!(says("shell(git *)"), None); + for wrong in ["connector(Calc-name__add)", "connector(calc-name__nope)", "connector(公司系統__*)"] { + let w = says(wrong).unwrap_or_default(); + assert!(w.contains("對不上") && w.contains("calc-name__*") && w.contains(&format!("{key}__*")), "{wrong}: {w}"); + } + crate::mcp::sync(&[]); + } + + /// A reviewer that gives no verdict on a connector's step: it is asked about, never run + /// unchecked — the usual card (with 「一律允許」) without 直接操作, none in it — saying why. + #[test] + fn a_failed_review_asks_about_a_connector_step() { + let add = crate::mcp::tool_name("calc-fail", "add"); + let words = || Some(Review { allow: vec![], ask: vec!["付款前先問我".into()] }); + for (direct, grant) in [(false, "mcp:calc-fail"), (true, "")] { + let replies = vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2})), sse_text("嗯…讓我想想")]; + let (asked, results, seen) = connector_turn("calc-fail", replies, direct, words(), &[], ApprovalAnswer::Reject); + assert_eq!(asked.len(), 1, "direct={direct}: {asked:?}"); + assert!(asked[0].0.contains(REVIEW_FAILED_NOTE) && asked[0].1 == grant, "direct={direct}: {asked:?}"); + assert!(!results[0].contains("sum=") && seen.len() == 3, "{results:?}"); + } + } + + /// A PreToolUse hook that says 「ask」 about a connector's step, with an 「一律詢問」 rule about it + /// too: one card saying both, no 「一律允許」 (it was two cards, one after the other). + #[cfg(unix)] + #[test] + fn a_hook_ask_and_a_rule_make_one_card_for_a_connector_step() { + use crate::hooks::{Config, Group, Hook, Hooks}; + let mut c = Config::default(); + let hook = Hook { kind: "command".into(), command: r#"echo '{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"連接器先給我看"}}'"#.into(), url: String::new(), headers: Default::default(), timeout: Some(10) }; + c.hooks.insert("PreToolUse".into(), vec![Group { matcher: "mcp__.*".into(), hooks: vec![hook] }]); + let bot = 7_702; + crate::hooks::test_hooks().lock().unwrap().insert(bot, Hooks { admin: Config::default(), mine: c }); + let add = crate::mcp::tool_name("calc-hook", "add"); + let mine = Review { allow: vec![], ask: vec!["connector(calc-hook__add)".into()] }; + let (asked, results, _) = connector_turn_of(bot, "calc-hook", vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2}))], true, Some(mine), &[], ApprovalAnswer::Reject); + let (plain, _, _) = connector_turn_of(bot, "calc-hook", vec![sse_call("c1", &add, serde_json::json!({"a": 1, "b": 2}))], false, None, &["mcp:calc-hook"], ApprovalAnswer::Reject); + crate::hooks::test_hooks().lock().unwrap().remove(&bot); + assert_eq!(asked.len(), 1, "one card: {asked:?}"); + assert!(asked[0].0.contains("connector(calc-hook__add)") && asked[0].0.contains("你的 hook 要先問:連接器先給我看") && asked[0].1.is_empty(), "{asked:?}"); + assert!(!results[0].contains("sum="), "{results:?}"); + assert!(plain.len() == 1 && plain[0].0.contains("你的 hook 要先問") && plain[0].1.is_empty(), "a granted connector, the hook still asks: {plain:?}"); } /// R4: a summary that comes back too short is asked for once more; under it, the person's diff --git a/src/agent/steps.rs b/src/agent/steps.rs index 87a74ee..f4f3ff1 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -1511,23 +1511,66 @@ fn reviewed(job: &Job, name: &str, args: &str, decision: Decision, looks: bool, } } -/// A connector's question with its arguments cut to their first 160 characters for the card -/// (`step`: the question as the reviewer read it, ending in the whole `args`, at the start of -/// `reason`; what follows it, a rule's note, stays). -fn card_args(reason: String, step: &str, args: &str) -> String { - match reason.strip_prefix(step) { - Some(rest) if args.chars().count() > 160 => { - let head = &step[..step.len() - args.len()]; - format!("{head}{}…{rest}", args.chars().take(160).collect::()) - } - _ => reason, +/// The person's 「一律詢問」 patterns (gate::patterns: only compared, no model call) over what lets a +/// step go without asking — a connector's 「一律允許」: a pattern that names the step asks, naming +/// the rule, with no 「一律允許」 (the person's decision: what they wrote out wins over a grant). +/// Sentence rules aren't read here: they would cost a model call on every granted step. +fn ask_pattern(job: &Job, name: &str, args: &str, reason: &str) -> Option { + match crate::gate::patterns(name, args, &[], &job.review.as_ref()?.ask) { + crate::gate::PatternVerdict::Ask(rule) => Some(Decision::Ask { reason: format!("{reason}(符合你的「一律詢問」規則:{rule})"), grant: String::new() }), + _ => None, } } -/// MCP connectors: asked once per server, unless 「一律允許」 (gate step 6); else the person's -/// rules have their say as for any step (`reviewed`: 自動審核, and 直接操作 stops at an "always -/// ask" rule — it once let every connector step through unchecked). A tool run through -/// use_connector_tool is that tool: the same question, the same rules, the same call. +/// How many characters of a step's arguments the reviewer reads: a huge argument (a file's +/// contents) would fill its context, and a review that fails asks anyway. +const REVIEW_ARGS: usize = 4000; + +/// Arguments as the reviewer reads them: whole up to [`REVIEW_ARGS`], else the start and the end +/// with how much was left out between them. +pub(super) fn for_reviewer(args: &str) -> String { + let n = args.chars().count(); + if n <= REVIEW_ARGS { + return args.to_string(); + } + let head: String = args.chars().take(REVIEW_ARGS * 3 / 4).collect(); + let tail: String = args.chars().skip(n - REVIEW_ARGS / 4).collect(); + format!("{head}…(中間省略 {} 字)…{tail}", n - REVIEW_ARGS) +} + +/// A connector step's decision, gates 6–8 for it (`name`, `args`: the tool it runs as, so +/// use_connector_tool's short name can't slip past a rule): an 「一律詢問」 pattern asks, even over +/// the connector's 「一律允許」; 「一律允許」 goes ahead; else 自動審核 or 直接操作 (`reviewed`) — +/// the reviewer reads the arguments ([`for_reviewer`]), the card their first 160 characters. A +/// hook's 「ask」 (`hook_ask`, its reason) goes on the same card, never with 「一律允許」. Returns +/// the decision and the note for the result. +pub(super) fn connector_decision(job: &Job, grants: &[String], name: &str, args: &str, hook_ask: Option<&str>, cancel: &AtomicBool) -> (Decision, String) { + let (server, tool) = crate::mcp::resolve(name).unwrap_or_default(); + let grant = format!("mcp:{server}"); + let what = format!("使用連接器「{server}」的工具:{tool} "); + let card = format!("{what}{}{}", args.chars().take(160).collect::(), if args.chars().count() > 160 { "…" } else { "" }); + let (decision, note) = match ask_pattern(job, name, args, &card) { + Some(d) => (d, String::new()), + None if grants.contains(&grant) => (Decision::Allow, String::new()), + None => { + let read = format!("{what}{}", for_reviewer(args)); + match reviewed(job, name, args, Decision::Ask { reason: read.clone(), grant }, false, cancel) { + (Decision::Ask { reason, grant }, _, note) => (Decision::Ask { reason: reason.strip_prefix(&read).map(|rest| format!("{card}{rest}")).unwrap_or(reason), grant }, note), + (d, _, note) => (d, note), + } + } + }; + let hook = |why: &str| format!("(你的 hook 要先問:{})", if why.is_empty() { "沒有說原因" } else { why }); + match (hook_ask, decision) { + (Some(why), Decision::Allow) => (Decision::Ask { reason: format!("{card}{}", hook(why)), grant: String::new() }, String::new()), + (Some(why), Decision::Ask { reason, .. }) => (Decision::Ask { reason: format!("{reason}{}", hook(why)), grant: String::new() }, String::new()), + (_, d) => (d, note), + } +} + +/// MCP connectors: asked once per server unless 「一律允許」, the person's rules having their say +/// as for any step ([`connector_decision`]). A tool run through use_connector_tool is that tool: +/// the same question, the same rules, the same call. pub(super) struct Connector; impl TurnTool for Connector { @@ -1554,18 +1597,12 @@ impl TurnTool for Connector { return Flow::Next; } }; - let (server, tool) = crate::mcp::resolve(&mcp_name).unwrap_or_default(); - let grant = format!("mcp:{server}"); - // The reviewer reads every argument (nothing hides past the card's first 160 characters); - // the card shows the start. - let step = format!("使用連接器「{server}」的工具:{tool} {mcp_args}"); - let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: step.clone(), grant } }; - // (By the name it runs as: use_connector_tool's short name must not slip past a rule.) - let (decision, _, note) = reviewed(job, &mcp_name, &mcp_args, decision, false, cancel); + let hook_ask = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, why)| why); + let (decision, note) = connector_decision(job, s.grants, &mcp_name, &mcp_args, hook_ask.as_deref(), cancel); let allowed = match decision { Decision::Allow => true, Decision::Deny(_) => false, - Decision::Ask { reason, grant } => match s.ask_person(ApprovalKind::Action, card_args(reason, &step, &mcp_args), grant) { + Decision::Ask { reason, grant } => match s.ask_person(ApprovalKind::Action, reason, grant) { ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => true, ApprovalAnswer::Always(g) => { keep_grant(s.grants, g); diff --git a/src/app.rs b/src/app.rs index 10df44a..44ab3c5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5993,6 +5993,10 @@ impl App { }); }); }); + // A connector(…) rule that names no connector's tool: said where it is. + if let Some(w) = crate::mcp::rule_names_nothing(r, &self.state.mcp_servers) { + hint(ui, w, p); + } } if let Some(i) = remove { rules.remove(i); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index fc6cdaa..566ed44 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1552,9 +1552,12 @@ impl App { if text.is_empty() { return fail("規則是空的"); } + let unknown = crate::mcp::rule_names_nothing(&text, &self.state.mcp_servers); if !list.contains(&text) { list.push(text); } + self.dirty = true; + return done(&unknown.map(|w| format!("已新增。不過{w}")).unwrap_or_else(|| "已新增".into())); } else { list.retain(|r| *r != text); } @@ -2120,6 +2123,10 @@ mod phone_act_tests { assert!(act(&mut app, "delete_bot", json!({"bot": b}), "admin")["error"].is_string()); assert_eq!(act(&mut app, "setting", json!({"key": "rule_add", "list": "ask", "value": "付款前先問我"}), "owner")["ok"], true); assert!(app.state.review_ask_rules.contains(&"付款前先問我".to_string())); + // A connector(…) rule no connector answers to: added, and the person is told why it won't match. + let warned = act(&mut app, "setting", json!({"key": "rule_add", "list": "ask", "value": "connector(Nobody__*)"}), "owner"); + assert!(warned["ok"] == true && warned["text"].as_str().is_some_and(|t| t.starts_with("已新增。不過") && t.contains("對不上")), "{warned}"); + assert_eq!(act(&mut app, "setting", json!({"key": "rule_remove", "list": "ask", "value": "connector(Nobody__*)"}), "owner")["ok"], true); assert_eq!(act(&mut app, "setting", json!({"key": "rule_remove", "list": "ask", "value": "付款前先問我"}), "owner")["ok"], true); assert!(!app.state.review_ask_rules.contains(&"付款前先問我".to_string())); // 群組聊天 as the desktop's menu makes it. diff --git a/src/mcp.rs b/src/mcp.rs index 1405ad3..e743049 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -650,6 +650,29 @@ pub fn forget(name: &str) { } /// The connected servers' tools. +/// What to tell the person adding a 「connector(…)」 rule that no connector tool answers to — it +/// is compared with the part of a tool's name after `mcp__`: the connector's key (its name when +/// plain ASCII, else a code like s1a2b3c), two underscores, the tool, cut at 64 characters, case +/// counting. None: a connected tool answers to it, it names a connector not connected now (its +/// tools aren't known), or it isn't a connector rule. +pub fn rule_names_nothing(rule: &str, servers: &[Server]) -> Option { + let inner = rule.trim().strip_prefix("connector(")?.strip_suffix(')')?.trim(); + let known = tools(); + if known.iter().any(|t| crate::gate::glob(inner, &tool_name(&t.server, &t.name)[PREFIX.len()..], false)) { + return None; + } + let server_part = inner.split("__").next().unwrap_or(inner); + if servers.iter().any(|s| !known.iter().any(|t| t.server == s.name) && crate::gate::glob(server_part, &server_key(&s.name), false)) { + return None; + } + let have: Vec = servers.iter().take(6).map(|s| format!("{}__*", server_key(&s.name))).collect(); + Some(if have.is_empty() { + format!("「{rule}」現在對不上任何連接器:還沒有連接器。") + } else { + format!("「{rule}」對不上任何連接器的工具:比對的是工具名稱 mcp__ 後面那段(連接器的代號__工具),大小寫要一樣。現在有:{}", have.join("、")) + }) +} + pub fn tools() -> Vec { conns().lock().unwrap().values().flat_map(|c| c.tools.lock().unwrap().clone()).collect() } From 4303646e5168137661ec6660fc5c0531d2568cb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 19:26:53 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix:=20AnyBot=20=E7=80=8F=E8=A6=BD=E5=99=A8?= =?UTF-8?q?=E7=9A=84=E6=AD=A5=E9=A9=9F=E4=B9=9F=E7=85=A7=E4=BD=A0=E7=9A=84?= =?UTF-8?q?=E3=80=8C=E4=B8=80=E5=BE=8B=E8=A9=A2=E5=95=8F=E3=80=8D=E5=92=8C?= =?UTF-8?q?=E8=87=AA=E5=8B=95=E5=AF=A9=E6=A0=B8=E2=80=94=E2=80=94=E6=A8=A3?= =?UTF-8?q?=E5=BC=8F=E8=A6=8F=E5=89=87=E4=B8=80=E5=BE=8B=E6=AF=94=E5=B0=8D?= =?UTF-8?q?=EF=BC=8C=E7=9B=B4=E6=8E=A5=E6=93=8D=E4=BD=9C=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E7=95=A5=E9=81=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit InBotsBrowser(AnyBot 自己的瀏覽器、web_fetch)從來不經自動審核,所以: - `tool(browser_click)`、`web(domain:…)` 這些樣式規則對 AnyBot 瀏覽器完全沒作用(地圖拿它們當例子); - 直接操作時,本機或內部網路的網址、從別台電腦上傳檔案直接做,連「一律詢問」都不看; - 「一律允許」過的本機網址(browser:private)也不看規則。 修好前的證據:an_ask_pattern_stops_the_bots_browser、private_pages_and_uploads_go_through_the_persons_rules 在舊程式失敗(點擊、開網址、web_fetch 都直接跑;一律允許過的內部網址沒問)。測試用帳號裡別台電腦的 瀏覽器(連不到就失敗)和 web_fetch 本機網址(本來就擋),舊程式也不會在這台開真的瀏覽器。 修法(steps.rs 的 InBotsBrowser,跟連接器同一套): - 安全規則先(中繼資料、鎖定時的本機網址),再比對「一律詢問」樣式(ask_pattern:只比對、不問模型)—— 本來不用問、一律允許過的瀏覽器步驟和 web_fetch 也比;符合就一張卡寫那條規則、沒有「一律允許」, 按了允許就不再跳下面那張。 - 本來就要問的(本機網址、上傳:這台的工作資料夾外、別台電腦的檔案)交給 reviewed():自動審核的 允許樣式不跳卡片(結果最後寫「自動審核:符合…」),話寫的規則給審核員看;直接操作只看「一律詢問」 (以前直接跳過)。一律允許過的不再給審核員看,跟連接器一樣。 - 不用問的步驟不給審核員看:點一下不會多等一次模型。 - 卡片沒有電腦名稱時不再寫「(在 上)」。 地圖:browser 加真的步驟「照你的「一律詢問」」(樣式卡、web_fetch 也問、內部網址給審核員看, 全部拒絕、沒開瀏覽器)和陷阱;autonomy、safety、FEATURES 第 16 節、SECURITY 照實寫。 沒碰 src/botbrowser.rs、src/remote.rs(loosens_guard 沒碰);tool_specs_are_locked、 approval_decisions_are_characterized 沒有 diff。 已驗證: 全部 cargo test(不帶金鑰、DOCKER_HOST 指到不存在)682 通過,含新的 an_ask_pattern_stops_the_bots_browser、 private_pages_and_uploads_go_through_the_persons_rules、the_bots_browser_is_not_held_up_by_rules_about_other_things; clippy -D warnings、lint-sh、verify-approval-routing run.sh --replay(跟基準一樣); verify-anybot:browser 每一步可跑的照 md 原文冷跑全過(target/verify-anybot/20261118-192608: 「在瀏覽器打開 http://127.0.0.1:9/(符合你的「一律詢問」規則:web(domain:127.0.0.1))」只有允許/拒絕, web_fetch 也問,192.168.1.5 先給審核員看,全部 denied、沒開瀏覽器),autonomy 也全過(-192347) 未驗證: 直接操作那一半的實機(區網的手機打不開,靠 agent 測試);真的開網頁、點、上傳(scratch 沒有 Docker, 在這台開會出現真的瀏覽器);動到瀏覽器那條路要人跑的 --ignored 實機測試(沒跑): agent::tests::{a_brain_without_chrome_browses_on_its_box, a_finished_job_closes_its_tabs, the_box_browser_uses_the_box_disk, the_words_on_a_form_reach_its_controls, two_jobs_keep_to_their_own_tabs}、 botbrowser::tests::{a_finished_job_quits_its_chrome, a_finished_job_quits_its_firefox, a_persons_firefox_profile, reads_a_real_page}、 browser::tests::{a_send_is_seen_with_the_post_it_answers_and_its_own_address, drives_a_dashboard, lines_go_in_whole_and_numbers_stay_put, numbers_controls_inside_web_components} 未簽: 審批路徑、瀏覽器——要人類跑 --ignored 並簽名才能合併,沒有合併、沒有推 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- FEATURES.md | 2 +- SECURITY.md | 2 +- docs/feature-map/autonomy.md | 10 ++-- docs/feature-map/browser.md | 6 ++- docs/feature-map/safety.md | 2 +- src/agent.rs | 99 ++++++++++++++++++++++++++++++++++++ src/agent/steps.rs | 90 +++++++++++++++++++++----------- 7 files changed, 170 insertions(+), 41 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 3cfb6a8..269a165 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -803,7 +803,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 0. **不需要許可的** - App 操作工具(第 26 節),只有「刪除例行任務」會先問。 - 讀公開網頁。 - - AnyBot 自己的瀏覽器。 + - AnyBot 自己的瀏覽器——但自動審核開著時,符合樣式的「一律詢問」(`tool(browser_click)`、`web(domain:…)`,`web_fetch` 也算)照樣問、沒有「一律允許」(只比對,不問模型);要問的那幾步(本機或內部網路的網址、上傳檔案)照第 7 步交給自動審核或直接操作,直接操作時「一律詢問」照樣擋(以前瀏覽器完全不經自動審核,直接操作連本機網址都不看規則)。 1. **決定在哪台電腦做** - 操作螢幕和讀你自己的瀏覽器:一律在「你的電腦」。 - 其他工具:用 Bot 指定的電腦,沒指定就用預設電腦。 diff --git a/SECURITY.md b/SECURITY.md index 5c7e0e8..a0bce90 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,7 +54,7 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - gVisor 是加分不是標配:純 Docker 的 box 與主機共享核心。 - 備份安全性以你的帳號密碼強度為上限。 - relay 是自架元件:它被攻破時洩露的是雜湊、session 清單與備份密文,不是明文。 -- 「一律允許」過的連接器只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它。 +- 「一律允許」過的連接器、AnyBot 瀏覽器本來不用問的步驟,只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)`、`tool(browser_click)`、`web(domain:…)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它們。 ## 硬化建議 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index 50ed378..0ea0d50 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -6,9 +6,9 @@ - `autonomy-direct` 直接操作:打開時一次做完——打開「在這台電腦上執行」、自動審核、所有 Bot 的電腦工具;「一律詢問」規則是空的就填三條預設(刪除檔案或資料夾/付款、購買或轉帳/用我的帳號發文、留言,或傳訊息給別人);進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。 - `autonomy-yolo` 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的也不問,自動審核也略過。仍然擋:安全規則一律拒絕的;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方、臉的同一行右邊有一個紅色閃電圖示(不另外佔一行;新對話沒有臉時自己一小行):滑過去看「一律放行 · Bot 做事不再問你」和還會擋什麼,點一下有「關閉一律放行」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 -- `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具也算;「一律允許」過的連接器只比對樣式);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 -- `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具也經過它,「一律允許」過的除外。 -- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟和連接器的工具(「一律允許」過也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。`connector(…)` 對不上任何連接器的工具時,新增的地方會說。 +- `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具、AnyBot 瀏覽器開本機網址和上傳也算;「一律允許」過的只比對樣式);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 +- `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具、AnyBot 瀏覽器要問的步驟(本機網址、上傳)也經過它,「一律允許」過的除外。 +- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟、連接器的工具、AnyBot 瀏覽器的步驟和 `web_fetch`(「一律允許」過、本來不用問的也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。`connector(…)` 對不上任何連接器的工具時,新增的地方會說。 - `autonomy-hooks` Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 自己出錯(結束碼不對、逾時、JSON 看不懂)就當它不在,紀錄檔寫原因。 - `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機關得掉,但打不開直接操作、新增不了「無需詢問直接允許」規則和連接器(「這項設定會讓 Bot 不用問就動手,不能從區網連線…打開」);要在電腦上的 AnyBot,或用帳號連線。 @@ -32,8 +32,8 @@ - **看狀態、關掉**(covers `autonomy-yolo`):打「/always-approve status」「/always-approve off」,再請它改名。指令:`$CTL phone send '/always-approve status' && $CTL phone wait-text '現在是一律放行' --in '#msgs' && $CTL phone send '/always-approve off' && $CTL phone wait-text '已關閉一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == false' && $CTL phone send '再改 [[call update_bot {"name":"關掉後的名字"}]]' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了這個操作' --in '#msgs'`。看到:「現在是一律放行…」「已關閉一律放行:…「直接操作」也關了」;改名又跳卡片。 - **手機打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):重新整理,帳戶選單 › 設定 › 權限,按「直接操作」。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '刪除檔案或資料夾' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '不能從區網連線' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」裡三條預設規則;按開關、確認「打開」後跳出「這項設定會讓 Bot 不用問就動手,不能從區網連線…」,直接操作還是關的。 - **桌面的閃電圖示**(covers `autonomy-yolo`):指令:要開視窗——第一步之後 `$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot autonomy-yolo ANYBOT_SHOT_REAL=1 && $CTL serve`。看到:臉的同一行右邊一個紅色閃電圖示。 -- **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:連接器的樣式(「一律允許」過也問)在 [connectors](connectors.md) 的「一律允許也照樣式問」;最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 -- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 +- **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:連接器的樣式(「一律允許」過也問)在 [connectors](connectors.md) 的「一律允許也照樣式問」,瀏覽器的樣式和審核員在 [browser](browser.md) 的「照你的「一律詢問」」;最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 +- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`、`an_ask_pattern_stops_the_bots_browser`、`private_pages_and_uploads_go_through_the_persons_rules`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 ## 陷阱 diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index c620e8e..3b3160e 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -30,10 +30,11 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - **公開網頁以外不讀**(covers `browser-fetch`):請 Bot 用 `web_fetch` 讀本機網址。指令:`$CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text 'web_fetch 只讀公開的網頁' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | {name, status}]'`。看到:「web_fetch 只讀公開的網頁,「127.0.0.1」是這台電腦或內部網路的位址。要看本機或區網上的服務,用 shell(例如 curl)或 browser_open。」;步驟 failed。 - **中繼資料擋下、本機網址先問**(covers `browser-actions`):`open` 雲端中繼資料,再 `open` 本機網址、按「拒絕」。指令:`$CTL phone send '[[call browser {"action":"open","url":"http://169.254.169.254/latest/meta-data/"}]]' && $CTL phone wait-text '禁止在瀏覽器開啟雲端中繼資料' --in '#msgs' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '在瀏覽器開啟本機或內部網路網址' --in '#ask' && $CTL phone shot browser-private && $CTL api GET '/api/state?since=0' --jq '.approvals[0] | {tool, can_always}' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了開啟這個內部網址' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open") | .status]'`。看到:中繼資料沒有卡片就「被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)…」;本機網址跳卡片「在瀏覽器開啟本機或內部網路網址:http://127.0.0.1:9/」(可以一律允許);拒絕後兩步都是 denied。 +- **照你的「一律詢問」**(covers `browser-actions`、`browser-fetch`):打開自動審核,「一律詢問」加 `web(domain:127.0.0.1)` 和一句「打開內部網站前先問我」;`open` 本機網址、`web_fetch` 它,再 `open` 另一個內部網址,都按「拒絕」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone click 'label.sw:has([data-sset="auto_review"])' && $CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'web(domain:127.0.0.1)' && $CTL phone click '#ask-ok' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' '打開內部網站前先問我' && $CTL phone click '#ask-ok' && $CTL wait-api /api/settings '.ask_rules | length == 2' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"打開內部網站前先問我"}' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone shot browser-rule && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://192.168.1.5/"}]]' && $CTL phone wait-text '規則:打開內部網站前先問我' --in '#ask' && $CTL phone shot browser-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open" or .name == "web_fetch") | .status]'`。看到:本機網址不再是平常那張(可以一律允許)的卡,而是「在瀏覽器打開 http://127.0.0.1:9/(符合你的「一律詢問」規則:web(domain:127.0.0.1))」,只有「允許」「拒絕」;`web_fetch` 也停下來問;192.168.1.5 是平常的內部網址卡,但先給審核員看(「要審核的動作:在瀏覽器開啟本機或內部網路網址:http://192.168.1.5/」),說詢問就寫那條規則;每一步都是 denied,沒有開瀏覽器。 - **已送帳本、設定檔**(covers `browser-gate`、`browser-profiles`):請 Bot 查送過什麼、列設定檔。指令:`$CTL phone send '[[call browser {"action":"sent"}]]' && $CTL phone wait-text '帳本裡最近 30 天沒有送出紀錄' --in '#msgs' && $CTL phone send '[[call browser {"action":"profiles"}]]' && $CTL phone click '.step.done .h' --text 瀏覽器設定檔 && $CTL phone wait-text '預設(使用中)' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .result][-2:]'`。看到:「帳本裡最近 30 天沒有送出紀錄(AnyBot 從開始記帳本那天起才有…)」;「AnyBot 瀏覽器的設定檔:預設(使用中)、你的瀏覽器。每個設定檔有自己的登入。…」;兩步都沒開瀏覽器。 - **真的開網頁、打字、送出**(covers `browser-actions`、`browser-refs`、`browser-type`、`browser-wait`、`browser-gate`、`browser-own`、`browser-close`、`browser-profiles`):指令:走不到——Bot 的電腦的瀏覽器要 Docker;改開在這台 Mac 會在使用者的螢幕上開真的瀏覽器。看到:最接近的真路是無頭的實機測試(下面):`click` 輸入框回「游標已在…裡」、`type` 多行整段進去、編號不變;在回覆框送出有【系統】那行和留言網址,同一篇再送被擋,搜尋框按 Enter 不算送出。 - **桌面的設定檔區塊**(covers `browser-profiles`、`browser-close`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot browser ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`。看到:設定 › 電腦「AnyBot 瀏覽器設定檔」的使用中設定檔、「開啟視窗」、「做完就關掉瀏覽器」、「發布前檢查」。 -- 自動測試:`cargo test browser::`、`cargo test publish::`、`cargo test evidence::`;實機(無頭 Chrome,或 Brave/Firefox;暫存資料夾、自己的連接埠):`ANYBOT_DATA_DIR=<暫存資料夾> ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new cargo test lines_go_in_whole_and_numbers_stay_put -- --ignored`,`a_send_is_seen_with_the_post_it_answers_and_its_own_address` 照同樣跑(Firefox 加 `ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1`、`HOME` 也換掉)。 +- 自動測試:`cargo test browser::`、`cargo test publish::`、`cargo test evidence::`、`cargo test an_ask_pattern_stops_the_bots_browser`、`cargo test private_pages_and_uploads_go_through_the_persons_rules`、`cargo test the_bots_browser_is_not_held_up_by_rules_about_other_things`;實機(無頭 Chrome,或 Brave/Firefox;暫存資料夾、自己的連接埠):`ANYBOT_DATA_DIR=<暫存資料夾> ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new cargo test lines_go_in_whole_and_numbers_stay_put -- --ignored`,`a_send_is_seen_with_the_post_it_answers_and_its_own_address` 照同樣跑(Firefox 加 `ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1`、`HOME` 也換掉)。 ## 陷阱 @@ -45,7 +46,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 下拉選單用 `select`,`option` 填選項上看得到的字(給 `value` 也行,對下拉選單 `type` 也會改成選選項);什麼都沒給會報錯。 - `fill` 是保險庫的填入;指著頁面上一個欄位(有 `ref`/`text`、沒有 kind/id/site)時當成 `type`(有 `option` 時當 `select`),不會跑去保險庫。 - `eval` 只能讀頁面:不能發請求、讀 cookie 或儲存、送出表單、換頁(會被拒絕);直接呼叫網站內部 API 會被當成機器人。 -- 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外)。 +- 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外,但符合「一律詢問」規則的照樣問)。 +- 自動審核開著時,「一律詢問」寫成樣式(`tool(browser_click)`、`web(domain:example.com)`)的,AnyBot 瀏覽器的步驟和 `web_fetch` 每次都停下來問,本來不用問、一律允許過的也一樣;用一般的話寫的只看本來就要問的(本機網址、上傳檔案)。 - 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。 - 送出後頁面上沒看到(例如從動態牆送出),結果寫「還沒確認」:不要因此再送一次,回原貼文看。 - 網頁要上傳檔案(Threads、IG 加相片、表單附件):用 `upload` 直接放進頁面的檔案欄位。用螢幕去點「加入相片」會跳出 Bot 電腦的檔案視窗(「取消」「Open」在最上面),還要在裡面找檔案、按 Open。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index 143cf86..4f241fa 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -11,7 +11,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - `safety-local` 「在這台電腦上執行」:一律允許/每次詢問(預設)/永不允許。永不允許時直接拒絕、不問。 - `safety-lock` 管理員鎖定:可鎖「直接操作」(AllowDirectMode)、「在這台電腦上執行」(AllowLocalExecution)、「經這台電腦轉送流量」(AllowBoxTrafficViaThisMac)。macOS 用 `defaults` 網域 com.anybot.AnyBot(可由 MDM 強制);其他系統讀 /etc/anybot/policy.json(優先)或家目錄 .anybot/policy.json。true/1/yes 允許;false/0/no 或看不懂的值鎖成關。每次打開設定重讀。 - `safety-timeout` 沒人在旁邊的一輪(例行任務、事件觸發、訊息管道)等核准超過 15 分鐘,自動結束、算出錯,免得卡住後面的排程和訊息。 -- `safety-gates` 每一步的關卡順序:1. 不用問:App 操作工具(刪例行任務、教同事技能、裝外部技能、改自己或別的 Bot 的設定這類會先問)、讀公開網頁、AnyBot 瀏覽器(別人傳來的訊息不能用)。2. 決定在哪台電腦;直接操作開著時第 3、5 步算已開。3. 這個 Bot 的電腦工具沒開 → 問。4. 「在這台電腦上執行」永不允許或被管理員鎖 → 拒絕。5. 它沒開 → 問。6. 照安全規則允許、問或拒絕(連接器的工具:每個連接器第一次問);「一律允許」過的直接做(連接器符合樣式的「一律詢問」照樣問)。7. 要問的交給自動審核或直接操作(連接器的工具也是)。8. 「每次都問」的蓋過第 6、7 步。9. 問你;等的時候按停止=拒絕。 +- `safety-gates` 每一步的關卡順序:1. 不用問:App 操作工具(刪例行任務、教同事技能、裝外部技能、改自己或別的 Bot 的設定這類會先問)、讀公開網頁、AnyBot 瀏覽器(別人傳來的訊息不能用;符合樣式的「一律詢問」照樣問)。2. 決定在哪台電腦;直接操作開著時第 3、5 步算已開。3. 這個 Bot 的電腦工具沒開 → 問。4. 「在這台電腦上執行」永不允許或被管理員鎖 → 拒絕。5. 它沒開 → 問。6. 照安全規則允許、問或拒絕(連接器的工具:每個連接器第一次問);「一律允許」過的直接做(連接器符合樣式的「一律詢問」照樣問)。7. 要問的交給自動審核或直接操作(連接器的工具也是)。8. 「每次都問」的蓋過第 6、7 步。9. 問你;等的時候按停止=拒絕。 ## 使用者怎麼到 diff --git a/src/agent.rs b/src/agent.rs index 8e61920..211fbee 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -4751,6 +4751,105 @@ echo 'done送出了' > done.html; (setsid pyt assert!(asked.is_empty() && results[0].contains("sum=3"), "自動審核 off: {asked:?} {results:?}"); } + /// A turn of AnyBot-browser steps on another computer of the account (「筆電」): what runs + /// there fails at once here (no account to reach it), so nothing opens a real browser even when + /// a step isn't stopped. Each card is answered `answer`. Returns each card's question and grant, + /// the step results, and every request the model got. + #[allow(clippy::type_complexity)] + fn browser_turn(mut replies: Vec<(u16, String)>, direct: bool, review: Option, grants: &[&str], answer: ApprovalAnswer) -> (Vec<(String, String)>, Vec, Vec) { + replies.push(sse_text("好")); + let (port, seen) = fake_http(replies); + 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: crate::web::specs_for(&["筆電".to_string()], "筆電"), session: String::new(), effort: String::new() }, + computers: vec![tools::Target { name: "筆電".into(), place: tools::Place::Device { host: "h-test".into(), dir: String::new() } }], + default_computer: "筆電".into(), + direct: Arc::new(AtomicBool::new(direct)), + review, + grants: grants.iter().map(|g| g.to_string()).collect(), + ..test_job() + }; + let (tx, rx) = channel(); + spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + let (mut asked, mut results) = (vec![], vec![]); + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { + (_, StreamEvent::NeedApproval(a)) => { + asked.push((a.reason.clone(), a.grant.clone())); + let _ = a.reply.send(answer.clone()); + } + (_, StreamEvent::ToolResult(m)) => results.push(m.text.clone()), + (_, StreamEvent::Done) => break, + (_, StreamEvent::Error(e)) => panic!("{e}"), + _ => {} + } + } + let seen = seen.lock().unwrap().clone(); + (asked, results, seen) + } + + /// 「一律詢問」 patterns about AnyBot-browser steps — `tool(browser_click)`, `web(domain:…)` on an + /// open or a web_fetch — stop them, with or without 直接操作, naming the rule, no 「一律允許」, + /// no model call (they used to run: the browser never went through the person's rules). + #[test] + fn an_ask_pattern_stops_the_bots_browser() { + for direct in [false, true] { + let mine = Review { allow: vec![], ask: vec!["tool(browser_click)".into(), "web(domain:example.com)".into(), "web(domain:127.0.0.1)".into()] }; + let replies = vec![ + sse_call("c1", "browser", serde_json::json!({"action": "click", "ref": "3"})), + sse_call("c2", "browser", serde_json::json!({"action": "open", "url": "https://shop.example.com/cart"})), + sse_call("c3", "web_fetch", serde_json::json!({"url": "http://127.0.0.1:9/"})), + ]; + let (asked, results, seen) = browser_turn(replies, direct, Some(mine), &[], ApprovalAnswer::Reject); + assert_eq!(asked.len(), 3, "direct={direct}: {asked:?} {results:?}"); + for ((reason, grant), rule) in asked.iter().zip(["tool(browser_click)", "web(domain:example.com)", "web(domain:127.0.0.1)"]) { + assert!(reason.contains(&format!("符合你的「一律詢問」規則:{rule}")) && grant.is_empty(), "{reason} [{grant}]"); + } + assert!(results.iter().all(|r| r.contains("使用者拒絕了這個操作")), "{results:?}"); + assert_eq!(seen.len(), 4, "no model call to review them"); + } + } + + /// The page this computer's network calls home (a private address): 「一律允許」 for it + /// (`browser:private`) or 直接操作 no longer skip the person's rules — an 「一律詢問」 pattern + /// still asks; in 直接操作 the sentence rules are read by the reviewer; 自動審核's allow pattern + /// lets it go without the card. The same for a file uploaded from another computer. + #[test] + fn private_pages_and_uploads_go_through_the_persons_rules() { + let open = || sse_call("c1", "browser", serde_json::json!({"action": "open", "url": "http://192.168.1.5/admin"})); + let mine = || Some(Review { allow: vec![], ask: vec!["web(domain:192.168.1.5)".into()] }); + let (asked, _, _) = browser_turn(vec![open()], false, mine(), &["browser:private"], ApprovalAnswer::Reject); + assert!(asked.len() == 1 && asked[0].0.contains("web(domain:192.168.1.5)") && asked[0].1.is_empty(), "a granted private page: {asked:?}"); + let words = || Some(Review { allow: vec![], ask: vec!["打開內部網站前先問我".into()] }); + let verdict = || sse_text(r#"{"verdict":"ask","rule":"打開內部網站前先問我"}"#); + let (asked, _, seen) = browser_turn(vec![open(), verdict()], true, words(), &[], ApprovalAnswer::Reject); + assert!(asked.len() == 1 && asked[0].0.contains("在瀏覽器開啟本機或內部網路網址") && asked[0].0.contains("規則:打開內部網站前先問我") && asked[0].1.is_empty(), "直接操作: {asked:?}"); + assert!(seen.len() == 3 && seen[1].contains("你是動作審核員") && seen[1].contains("192.168.1.5"), "the reviewer read it: {seen:?}"); + let upload = sse_call("c1", "browser", serde_json::json!({"action": "upload", "ref": "4", "path": "/Users/me/report.pdf"})); + let (asked, _, _) = browser_turn(vec![upload, verdict()], true, words(), &[], ApprovalAnswer::Reject); + assert!(asked.len() == 1 && asked[0].0.contains("上傳到網頁") && asked[0].0.contains("規則:打開內部網站前先問我"), "an upload in 直接操作: {asked:?}"); + let allow = Some(Review { allow: vec!["web(domain:192.168.1.5)".into()], ask: vec![] }); + let (asked, results, _) = browser_turn(vec![open()], false, allow, &[], ApprovalAnswer::Reject); + assert!(asked.is_empty() && results[0].contains("自動審核:符合「web(domain:192.168.1.5)」"), "{asked:?} {results:?}"); + } + + /// The other way round: a browser step that needs no permission isn't held up by sentence rules + /// (no model call on every click) or by patterns about other things; with no rules, the private + /// page's card is the one it always was (「一律允許」 offered), and 直接操作 skips it. + #[test] + fn the_bots_browser_is_not_held_up_by_rules_about_other_things() { + let click = || sse_call("c1", "browser", serde_json::json!({"action": "click", "ref": "3"})); + for direct in [false, true] { + let others = Some(Review { allow: vec![], ask: vec!["付款前先問我".into(), "tool(browser_type)".into(), "web(domain:other.example)".into(), "shell(*)".into()] }); + let (asked, results, seen) = browser_turn(vec![click()], direct, others, &[], ApprovalAnswer::Reject); + assert!(asked.is_empty() && seen.len() == 2 && !results[0].contains("拒絕"), "direct={direct}: {asked:?} {results:?}"); + } + let open = || sse_call("c1", "browser", serde_json::json!({"action": "open", "url": "http://192.168.1.5/"})); + let (asked, _, _) = browser_turn(vec![open()], false, None, &[], ApprovalAnswer::Reject); + assert!(asked.len() == 1 && asked[0].0.starts_with("在瀏覽器開啟本機或內部網路網址:http://192.168.1.5/") && asked[0].1 == "browser:private", "{asked:?}"); + let (asked, _, _) = browser_turn(vec![open()], true, None, &[], ApprovalAnswer::Reject); + assert!(asked.is_empty(), "直接操作 with no rules: {asked:?}"); + } + /// A connector step's decision on fixed rules, as Allow / Allow+note (自動審核 let it, the result /// says so) / Ask[the grant 「一律允許」 would keep] with why (rule=…, failed, hook), and how many /// times the reviewer model was asked — 「一律允許」 for the connector or not × 直接操作 or not × diff --git a/src/agent/steps.rs b/src/agent/steps.rs index f4f3ff1..efc5cd7 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -540,35 +540,53 @@ impl TurnTool for InBotsBrowser { // bot goes as it is. The path is made whole here, so the browser takes the // very file that was checked. let mut call_args = call.args.clone(); - if call.name == "browser_open" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new")) { - let raw_url = tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string(); - if !raw_url.is_empty() { - if let Ok(norm) = web::normalize_url(&raw_url) { - if web::is_forbidden_browser_url(&norm) { - s.finish("被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。", ToolStatus::Denied, None); + // The page this step opens, made whole: the safety rules first. + let opens = (call.name == "browser_open" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new"))) + .then(|| tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string()) + .filter(|u| !u.is_empty()) + .and_then(|u| web::normalize_url(&u).ok()); + let private = opens.as_deref().is_some_and(|norm| !matches!(place, BrowserAt::Box) && web::is_private_browser_url(norm)); + if opens.as_deref().is_some_and(web::is_forbidden_browser_url) { + s.finish("被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。", ToolStatus::Denied, None); + return Flow::Next; + } + if private && matches!(place, BrowserAt::Here) && job.local_locked { + s.finish("被安全規則擋下:「在這台電腦上執行」已鎖定,不能開啟本機或內部網路位址。", ToolStatus::Denied, None); + return Flow::Next; + } + // The person's 「一律詢問」 patterns (only compared, no model call) over a browser step that + // needs no permission or was 「一律允許」, as for a connector: one card naming the rule; a yes + // to it is the yes to this step (no second card below). What would be asked anyway goes + // through `reviewed` (自動審核, 直接操作) — never sentences on every click. + let on_line = if on.is_empty() { String::new() } else { format!("\n(在 {on} 上)") }; + let mut said_yes = false; + if let Some(Decision::Ask { reason, grant }) = ask_pattern(job, &call.name, &call.args, &format!("{} {}", web::label(&call.name), s.what())) { + if s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) == ApprovalAnswer::Reject { + s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None); + return Flow::Next; + } + if cancel.load(Ordering::Relaxed) { + return Flow::End; + } + said_yes = true; + } + let mut review_note = String::new(); + if let (true, false, Some(norm)) = (private, said_yes, opens.as_deref()) { + let grant = "browser:private".to_string(); + let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("在瀏覽器開啟本機或內部網路網址:{norm}"), grant } }; + let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + review_note = note; + if let Decision::Ask { reason, grant } = decision { + match s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) { + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {} + ApprovalAnswer::Always(g) => keep_grant(s.grants, g), + ApprovalAnswer::Reject => { + s.finish("使用者拒絕了開啟這個內部網址。", ToolStatus::Denied, None); return Flow::Next; } - if !matches!(place, BrowserAt::Box) && web::is_private_browser_url(&norm) { - if matches!(place, BrowserAt::Here) && job.local_locked { - s.finish("被安全規則擋下:「在這台電腦上執行」已鎖定,不能開啟本機或內部網路位址。", ToolStatus::Denied, None); - return Flow::Next; - } - let direct = job.direct.load(Ordering::Relaxed); - let grant = "browser:private".to_string(); - if !direct && !s.grants.contains(&grant) { - let (atx, arx) = channel(); - send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); - send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("在瀏覽器開啟本機或內部網路網址:{norm}\n(在 {on} 上)"), grant: grant.clone(), reply: atx, kind: ApprovalKind::Action })); - match wait_answer(arx, cancel, said_no) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {} - ApprovalAnswer::Always(g) => keep_grant(s.grants, g), - ApprovalAnswer::Reject => { - s.finish("使用者拒絕了開啟這個內部網址。", ToolStatus::Denied, None); - return Flow::Next; - } - } - } - } + } + if cancel.load(Ordering::Relaxed) { + return Flow::End; } } } @@ -593,14 +611,17 @@ impl TurnTool for InBotsBrowser { } else { match tools::decide_file_out(&here, &path, s.grants) { Decision::Allow if !direct && !(*s.tools_on && *s.local_on) => Decision::Ask { reason: format!("把「{}」上的檔案上傳到網頁:{}", here.name, named.display()), grant: String::new() }, - Decision::Ask { .. } if direct => Decision::Allow, Decision::Ask { grant, .. } => Decision::Ask { reason: format!("把工作資料夾以外的檔案上傳到網頁:{}", named.display()), grant }, d => d, } }; + // (直接操作 and 自動審核 as for any step: an 「一律詢問」 rule still stops it.) + let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + review_note = note; let refused = match decision { Decision::Allow => None, Decision::Deny(r) => Some(format!("被安全規則擋下:{r}")), + Decision::Ask { .. } if said_yes => None, Decision::Ask { reason, grant } => { let (atx, arx) = channel(); send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); @@ -631,12 +652,14 @@ impl TurnTool for InBotsBrowser { s.finish("被安全規則擋下:這個檔案是私密或系統檔案,Bot 不能上傳。", ToolStatus::Denied, None); return Flow::Next; } - let direct = job.direct.load(Ordering::Relaxed); let grant = format!("upload-device:{on}"); - if !direct && !s.grants.contains(&grant) { + let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("把「{on}」上的檔案上傳到網頁:{path}"), grant } }; + let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + review_note = note; + if let (Decision::Ask { reason, grant }, false) = (decision, said_yes) { let (atx, arx) = channel(); send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); - send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("把「{on}」上的檔案上傳到網頁:{path}\n(在 {on} 上)"), grant, reply: atx, kind: ApprovalKind::Action })); + send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("{reason}\n(在 {on} 上)"), grant, reply: atx, kind: ApprovalKind::Action })); match wait_answer(arx, cancel, said_no) { ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {} ApprovalAnswer::Always(g) => keep_grant(s.grants, g), @@ -715,6 +738,11 @@ impl TurnTool for InBotsBrowser { } // Which computer's browser it was, like every other step. let output = if on.is_empty() { output } else { format!("[{on}] {output}") }; + // 自動審核 let it go: said after the page's words, outside the part marked as the page's. + if !review_note.is_empty() { + let before = step_note.take(); + step_note.set(format!("{before}\n{}", review_note.trim_end())); + } s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img); Flow::Next } From 68971e86691890ef2c7d9243bdbe8a8da4e51967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 20:06:35 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix:=20=E7=B6=B2=E5=9D=80=E7=85=A7=E7=80=8F?= =?UTF-8?q?=E8=A6=BD=E5=99=A8=E7=9A=84=E8=AE=80=E6=B3=95=E6=AF=94=E5=B0=8D?= =?UTF-8?q?=EF=BC=88web(domain:=E2=80=A6)=E3=80=81=E5=85=A7=E9=83=A8?= =?UTF-8?q?=E7=B6=B2=E5=9D=80=E5=8D=A1=EF=BC=89=EF=BC=9B=E5=AF=A9=E6=A0=B8?= =?UTF-8?q?=E5=93=A1=E5=8F=AA=E8=AE=80=E5=85=A9=E7=AB=AF=E6=99=82=E7=85=A7?= =?UTF-8?q?=E6=A8=A3=E5=95=8F=EF=BC=9B=E4=B8=8A=E5=82=B3=E7=9A=84=E9=96=8B?= =?UTF-8?q?=E9=97=9C=E5=8D=A1=E4=B8=8D=E7=B5=A6=E5=AF=A9=E6=A0=B8=E7=9C=81?= =?UTF-8?q?=E6=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第三輪審查(6a6d905..4303646)的四個 P1,加上能收的 P2。 P1-1 `web(domain:…)` 比對的不是瀏覽器打開的那個網站:gate.rs 自己切網址,`me@example.com`、 `example.com.`、`example.com\cart`、`browser_tabs` 帶網址開新分頁都對不上(0 張卡)。 P1-2 同一個根:web.rs 的 normalize_url/host_port 用 rsplit('@')、不把 `\` 當 `/`, `http://127.0.0.1\@a.com/`、`http://192.168.1.1\.example.com/` 被當成公開網址,內部網址卡不跳。 修法:web::parse_url 用 WHATWG 的 `url` crate(Cargo.lock 本來就有,改成直接依賴)——`\` 是 `/`、 帳號@ 不是主機、小寫、punycode、結尾的點、各種寫法的 IP;normalize_url、host_port、web::host_of 都用它, gate 的 web(…) 用 host_of 比主機(規則的網域也同樣讀),比對清單加上 browser_tabs 帶網址。 InBotsBrowser 把解析過的網址交給瀏覽器(open、新分頁、web_fetch),檢查的就是打開的;web_fetch 轉址的每一站也照解析過的去要。地圖寫清楚:只比對用網址打開或讀的那一步,點連結、轉址、上一頁不算。 P1-3 審核員只讀長參數的兩端:模型可以把要擋的東西塞在中間,審核員說允許就不跳卡片。修法:參數被截過、 而且這一步真的給模型看了(model_reads,跟 review_action 一樣的判斷)時,審核員的允許、直接操作下的 「都不符合」都改成跳卡片:「參數很長,自動審核只讀了開頭和結尾,所以先問你」(沒有直接操作時照舊可以 一律允許,跟審核失敗一樣)。選這個而不是把上限拉高:上限拉多高,中間都還是可能藏東西。 P1-4 從這台上傳檔案、電腦工具或「在這台電腦上執行」沒開時,那張卡被送進 reviewed(),允許規則就省掉了。 修法:抽成 here_upload_decision——開關沒開的那張卡(工作資料夾內外都是)一律跳、不給審核,別的 yes (樣式卡的允許)也省不掉它;開關開著才照檔案規則和 reviewed()。 P2: - browser.md 的陷阱和自動審核說的對齊(本機網址:一律允許、直接操作、自動審核的允許都可以不問, 「一律詢問」照樣問)。 - 「對不上任何東西」的提醒(gate::rule_warning)擴到 web(…)(沒寫 domain:、用 *、寫了 https:// 或路徑、 不是網站)和 tool(…)(不是哪一步的名字,例如 tool(browser) 要寫 tool(browser_*));featuremap 的 every_tool 搬出測試,提醒用同一份工具清單。 - hook 的「ask」跟瀏覽器的樣式卡放在同一張(run_call 的通用 hook 詢問不再管 InBotsBrowser)。 沒改,記著(略過樣式規則的路):伺服器大腦上的 open_for_person、/goal 評審自己呼叫的 web_fetch、 在使用者自己的瀏覽器 browser_open(OnComputer,不用問的不比對)、別人傳來的訊息那一輪的 web_fetch (沒有自動審核)。vault.rs 的 host_of 也是自己切網址,沒動。沒碰 src/remote.rs、src/botbrowser.rs。 特性表 connector_decisions_are_characterized 多 20 列(38 → 58):審核員說允許、長參數 × 審核員允許/ 都不符合/允許樣式/詢問樣式。tool_specs_are_locked、approval_decisions_are_characterized 沒有 diff。 已驗證: 全部 cargo test 686 通過(不帶金鑰、DOCKER_HOST 指到不存在、ANYBOT_VAULT_KEY_FILE 放暫存、 PATH 前面放假的 security 記下每次呼叫:這次 0 次);把四個修法和 hook 合併各自改回去, addresses_are_read_as_a_browser_reads_them、pattern_rules_decide_before_the_model、an_ask_pattern_stops_the_bots_browser、 connector_decisions_are_characterized、an_upload_with_the_switches_off_always_asks、 a_hook_ask_and_a_rule_make_one_card_for_a_browser_step 都失敗,改回來都過;clippy -D warnings、lint-sh、 verify-approval-routing run.sh --replay(跟基準一樣);verify-anybot:browser 每一步可跑的照 md 原文冷跑全過 (target/verify-anybot/20261118-200336:「在瀏覽器打開 http://127.0.0.1/@a.com/(符合你的「一律詢問」規則: web(domain:127.0.0.1))」,192.168.1.5\.example.com 跳內部網址卡、先給審核員看;全部拒絕、沒有開瀏覽器) 未驗證: 真的瀏覽器打開解析過的網址(scratch 沒有 Docker,這台開會出現真的瀏覽器);直接操作那一半的實機; 電腦設定頁提醒那一行的樣子;--ignored 的瀏覽器實機測試(清單見 4303646) 未簽: 審批路徑、瀏覽器——要人類跑 --ignored 並簽名才能合併,沒有合併、沒有推 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- Cargo.lock | 1 + Cargo.toml | 2 + FEATURES.md | 4 +- SECURITY.md | 2 +- docs/feature-map/autonomy.md | 4 +- docs/feature-map/browser.md | 8 +-- src/agent.rs | 126 +++++++++++++++++++++++++++++------ src/agent/steps.rs | 117 ++++++++++++++++++++++++-------- src/app.rs | 4 +- src/app/remote_ui.rs | 2 +- src/featuremap.rs | 44 ++++++------ src/gate.rs | 77 ++++++++++++++++++--- src/web.rs | 99 ++++++++++++++++++--------- 13 files changed, 368 insertions(+), 122 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d409a4..f7bc525 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -387,6 +387,7 @@ dependencies = [ "unicode-normalization", "unicode-width", "ureq", + "url", "vt100", "wayland-client", "wayland-protocols", diff --git a/Cargo.toml b/Cargo.toml index 7a1c16f..d766feb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,8 @@ name = "anybot" path = "src/main.rs" [dependencies] +# WHATWG URL parsing: the host a browser opens is the host the rules check (`\` is `/`, user@ isn't the host, IDNA, IPs in any spelling). +url = "2.5.8" zhconv = { version = "0.4", default-features = false, features = ["mediawiki"] } eframe = "0.37" # 正式圖表:座標軸、网格、hover 十字準線與數值、框選縮放(和 eframe 同步發版) diff --git a/FEATURES.md b/FEATURES.md index 269a165..22a61d1 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -803,7 +803,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 0. **不需要許可的** - App 操作工具(第 26 節),只有「刪除例行任務」會先問。 - 讀公開網頁。 - - AnyBot 自己的瀏覽器——但自動審核開著時,符合樣式的「一律詢問」(`tool(browser_click)`、`web(domain:…)`,`web_fetch` 也算)照樣問、沒有「一律允許」(只比對,不問模型);要問的那幾步(本機或內部網路的網址、上傳檔案)照第 7 步交給自動審核或直接操作,直接操作時「一律詢問」照樣擋(以前瀏覽器完全不經自動審核,直接操作連本機網址都不看規則)。 + - AnyBot 自己的瀏覽器——但自動審核開著時,符合樣式的「一律詢問」(`tool(browser_click)`、`web(domain:…)`,`web_fetch` 也算)照樣問、沒有「一律允許」(只比對,不問模型)。`web(domain:…)` 比對用網址打開或讀的那一步(`open`、帶網址開新分頁、`web_fetch`),網址照瀏覽器的讀法(WHATWG:大小寫、結尾的點、帳號@、反斜線、IDN、各種寫法的 IP),瀏覽器拿到的就是比對過的那個網址;點連結、轉址、上一頁到的網頁不比對。要問的那幾步(本機或內部網路的網址、上傳檔案)照第 7 步交給自動審核或直接操作,直接操作時「一律詢問」照樣擋(以前瀏覽器完全不經自動審核,直接操作連本機網址都不看規則)。從這台上傳檔案而電腦工具或「在這台電腦上執行」沒開時,那張卡(第 3、5 步)不給自動審核省掉。本機或內部網路網址的判斷也改成瀏覽器的讀法:以前 `http://127.0.0.1\@a.com/` 這種寫法會被當成公開網址、不問就開。 1. **決定在哪台電腦做** - 操作螢幕和讀你自己的瀏覽器:一律在「你的電腦」。 - 其他工具:用 Bot 指定的電腦,沒指定就用預設電腦。 @@ -1501,7 +1501,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 都沒寫:本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`(自己設了同名變數的話用自己的);遠端伺服器收到 `Authorization: Basic …`(自己有 Authorization 標頭的話不加)。 - 密碼跟金鑰一樣:螢幕只看得到「已設定」,不會拿到內容;在螢幕上改指令或網址時,大腦會把密碼清掉(不然會被送到新的位址)。 - **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。 -- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。自動審核開著時:符合樣式的「一律詢問」(例如 `connector(slack__post_message)`)每次問、沒有「一律允許」——直接操作模式下、連接器一律允許過也一樣(只比對樣式,不問模型)。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;用一般的話寫的「一律詢問」由審核員判斷。一律允許過的連接器不再給審核員看:用一般的話寫的規則,包括直接操作填的三條預設(「用我的帳號發文、留言,或傳訊息給別人」…),擋不住它,要擋就寫成樣式。(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」都不看。)用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀參數的前 3000 字和最後 1000 字(更長的中間省略),卡片只列前 160 字。hook 的「ask」跟規則放在同一張卡。新增 `connector(…)` 規則時對不上任何連接器的工具(寫成顯示的名稱、大小寫不對、中文名稱要寫代碼、超過 64 字被截掉),設定頁和手機會說。 +- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。自動審核開著時:符合樣式的「一律詢問」(例如 `connector(slack__post_message)`)每次問、沒有「一律允許」——直接操作模式下、連接器一律允許過也一樣(只比對樣式,不問模型)。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;用一般的話寫的「一律詢問」由審核員判斷。一律允許過的連接器不再給審核員看:用一般的話寫的規則,包括直接操作填的三條預設(「用我的帳號發文、留言,或傳訊息給別人」…),擋不住它,要擋就寫成樣式。(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」都不看。)用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀參數的前 3000 字和最後 1000 字(更長的中間省略),卡片只列前 160 字。hook 的「ask」跟規則放在同一張卡。新增 `connector(…)` 規則時對不上任何連接器的工具(寫成顯示的名稱、大小寫不對、中文名稱要寫代碼、超過 64 字被截掉),設定頁和手機會說;`web(…)` 沒寫成 `web(domain:網站)`、`tool(…)` 不是哪一步的名字(例如 `tool(browser)`)也會說。審核員只讀了長參數的開頭和結尾時,它說允許(或直接操作下說都不符合)也照樣跳卡片:「參數很長,自動審核只讀了開頭和結尾,所以先問你」。 - 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。按停止時,本機連接器的呼叫馬上結束(以前要等到它回或 120 秒);用網址連的照樣等。 - 連接器關掉、移除、重新連線或連不上時,連同它帶起來的所有程式一起關(npx/uvx/sh 底下真正的伺服器以前會一直留著)。 - **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 diff --git a/SECURITY.md b/SECURITY.md index a0bce90..bc202a2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,7 +54,7 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - gVisor 是加分不是標配:純 Docker 的 box 與主機共享核心。 - 備份安全性以你的帳號密碼強度為上限。 - relay 是自架元件:它被攻破時洩露的是雜湊、session 清單與備份密文,不是明文。 -- 「一律允許」過的連接器、AnyBot 瀏覽器本來不用問的步驟,只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)`、`tool(browser_click)`、`web(domain:…)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它們。 +- 「一律允許」過的連接器、AnyBot 瀏覽器本來不用問的步驟,只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)`、`tool(browser_click)`、`web(domain:…)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它們。`web(domain:…)` 只看用網址打開或讀的那一步:點連結、網頁轉址、上一頁到的網頁看不到。 ## 硬化建議 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index 0ea0d50..220989e 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -8,7 +8,7 @@ - `autonomy-yolo` 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的也不問,自動審核也略過。仍然擋:安全規則一律拒絕的;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方、臉的同一行右邊有一個紅色閃電圖示(不另外佔一行;新對話沒有臉時自己一小行):滑過去看「一律放行 · Bot 做事不再問你」和還會擋什麼,點一下有「關閉一律放行」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 - `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具、AnyBot 瀏覽器開本機網址和上傳也算;「一律允許」過的只比對樣式);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 - `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具、AnyBot 瀏覽器要問的步驟(本機網址、上傳)也經過它,「一律允許」過的除外。 -- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟、連接器的工具、AnyBot 瀏覽器的步驟和 `web_fetch`(「一律允許」過、本來不用問的也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。`connector(…)` 對不上任何連接器的工具時,新增的地方會說。 +- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(用網址打開或讀那個網站和它底下的網址;點連結、轉址到的不算)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟、連接器的工具、AnyBot 瀏覽器的步驟和 `web_fetch`(「一律允許」過、本來不用問的也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。樣式對不上任何東西時(`connector(…)` 沒有那個工具、`web(…)` 沒寫成 `web(domain:網站)`、`tool(…)` 不是哪一步的名字,例如要寫 `tool(browser_*)` 不是 `tool(browser)`),新增的地方會說。 - `autonomy-hooks` Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 自己出錯(結束碼不對、逾時、JSON 看不懂)就當它不在,紀錄檔寫原因。 - `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機關得掉,但打不開直接操作、新增不了「無需詢問直接允許」規則和連接器(「這項設定會讓 Bot 不用問就動手,不能從區網連線…打開」);要在電腦上的 AnyBot,或用帳號連線。 @@ -33,7 +33,7 @@ - **手機打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):重新整理,帳戶選單 › 設定 › 權限,按「直接操作」。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '刪除檔案或資料夾' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '不能從區網連線' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」裡三條預設規則;按開關、確認「打開」後跳出「這項設定會讓 Bot 不用問就動手,不能從區網連線…」,直接操作還是關的。 - **桌面的閃電圖示**(covers `autonomy-yolo`):指令:要開視窗——第一步之後 `$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot autonomy-yolo ANYBOT_SHOT_REAL=1 && $CTL serve`。看到:臉的同一行右邊一個紅色閃電圖示。 - **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:連接器的樣式(「一律允許」過也問)在 [connectors](connectors.md) 的「一律允許也照樣式問」,瀏覽器的樣式和審核員在 [browser](browser.md) 的「照你的「一律詢問」」;最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 -- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`、`an_ask_pattern_stops_the_bots_browser`、`private_pages_and_uploads_go_through_the_persons_rules`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 +- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`、`an_ask_pattern_stops_the_bots_browser`、`private_pages_and_uploads_go_through_the_persons_rules`、`pattern_rules_that_name_nothing_are_said_so`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 ## 陷阱 diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index 3b3160e..d4c2f32 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -30,11 +30,11 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - **公開網頁以外不讀**(covers `browser-fetch`):請 Bot 用 `web_fetch` 讀本機網址。指令:`$CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text 'web_fetch 只讀公開的網頁' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | {name, status}]'`。看到:「web_fetch 只讀公開的網頁,「127.0.0.1」是這台電腦或內部網路的位址。要看本機或區網上的服務,用 shell(例如 curl)或 browser_open。」;步驟 failed。 - **中繼資料擋下、本機網址先問**(covers `browser-actions`):`open` 雲端中繼資料,再 `open` 本機網址、按「拒絕」。指令:`$CTL phone send '[[call browser {"action":"open","url":"http://169.254.169.254/latest/meta-data/"}]]' && $CTL phone wait-text '禁止在瀏覽器開啟雲端中繼資料' --in '#msgs' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '在瀏覽器開啟本機或內部網路網址' --in '#ask' && $CTL phone shot browser-private && $CTL api GET '/api/state?since=0' --jq '.approvals[0] | {tool, can_always}' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了開啟這個內部網址' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open") | .status]'`。看到:中繼資料沒有卡片就「被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)…」;本機網址跳卡片「在瀏覽器開啟本機或內部網路網址:http://127.0.0.1:9/」(可以一律允許);拒絕後兩步都是 denied。 -- **照你的「一律詢問」**(covers `browser-actions`、`browser-fetch`):打開自動審核,「一律詢問」加 `web(domain:127.0.0.1)` 和一句「打開內部網站前先問我」;`open` 本機網址、`web_fetch` 它,再 `open` 另一個內部網址,都按「拒絕」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone click 'label.sw:has([data-sset="auto_review"])' && $CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'web(domain:127.0.0.1)' && $CTL phone click '#ask-ok' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' '打開內部網站前先問我' && $CTL phone click '#ask-ok' && $CTL wait-api /api/settings '.ask_rules | length == 2' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"打開內部網站前先問我"}' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone shot browser-rule && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://192.168.1.5/"}]]' && $CTL phone wait-text '規則:打開內部網站前先問我' --in '#ask' && $CTL phone shot browser-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open" or .name == "web_fetch") | .status]'`。看到:本機網址不再是平常那張(可以一律允許)的卡,而是「在瀏覽器打開 http://127.0.0.1:9/(符合你的「一律詢問」規則:web(domain:127.0.0.1))」,只有「允許」「拒絕」;`web_fetch` 也停下來問;192.168.1.5 是平常的內部網址卡,但先給審核員看(「要審核的動作:在瀏覽器開啟本機或內部網路網址:http://192.168.1.5/」),說詢問就寫那條規則;每一步都是 denied,沒有開瀏覽器。 +- **照你的「一律詢問」**(covers `browser-actions`、`browser-fetch`):打開自動審核,「一律詢問」加 `web(domain:127.0.0.1)` 和一句「打開內部網站前先問我」;`open` 本機網址、用反斜線寫的同一個(`http://127.0.0.1\@a.com/`)、`web_fetch` 它,再 `open` 用反斜線寫的另一個內部網址,都按「拒絕」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone click 'label.sw:has([data-sset="auto_review"])' && $CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'web(domain:127.0.0.1)' && $CTL phone click '#ask-ok' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' '打開內部網站前先問我' && $CTL phone click '#ask-ok' && $CTL wait-api /api/settings '.ask_rules | length == 2' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"打開內部網站前先問我"}' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone shot browser-rule && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1\\@a.com/"}]]' && $CTL phone wait-text '在瀏覽器打開 http://127.0.0.1/@a.com/(符合你的「一律詢問」規則:web(domain:127.0.0.1))' --in '#ask' && $CTL phone shot browser-backslash && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://192.168.1.5\\.example.com/"}]]' && $CTL phone wait-text '在瀏覽器開啟本機或內部網路網址:http://192.168.1.5/.example.com/' --in '#ask' && $CTL phone wait-text '規則:打開內部網站前先問我' --in '#ask' && $CTL phone shot browser-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open" or .name == "web_fetch") | .status]'`。看到:本機網址不再是平常那張(可以一律允許)的卡,而是「在瀏覽器打開 http://127.0.0.1:9/(符合你的「一律詢問」規則:web(domain:127.0.0.1))」,只有「允許」「拒絕」;反斜線寫的照瀏覽器的讀法是 127.0.0.1,卡片寫的就是會打開的「http://127.0.0.1/@a.com/」;`web_fetch` 也停下來問;`192.168.1.5\.example.com` 一樣是內部網址(卡片寫「http://192.168.1.5/.example.com/」),先給審核員看(「要審核的動作:在瀏覽器開啟本機或內部網路網址:…」),說詢問就寫那條規則;每一步都是 denied,沒有開瀏覽器。 - **已送帳本、設定檔**(covers `browser-gate`、`browser-profiles`):請 Bot 查送過什麼、列設定檔。指令:`$CTL phone send '[[call browser {"action":"sent"}]]' && $CTL phone wait-text '帳本裡最近 30 天沒有送出紀錄' --in '#msgs' && $CTL phone send '[[call browser {"action":"profiles"}]]' && $CTL phone click '.step.done .h' --text 瀏覽器設定檔 && $CTL phone wait-text '預設(使用中)' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .result][-2:]'`。看到:「帳本裡最近 30 天沒有送出紀錄(AnyBot 從開始記帳本那天起才有…)」;「AnyBot 瀏覽器的設定檔:預設(使用中)、你的瀏覽器。每個設定檔有自己的登入。…」;兩步都沒開瀏覽器。 - **真的開網頁、打字、送出**(covers `browser-actions`、`browser-refs`、`browser-type`、`browser-wait`、`browser-gate`、`browser-own`、`browser-close`、`browser-profiles`):指令:走不到——Bot 的電腦的瀏覽器要 Docker;改開在這台 Mac 會在使用者的螢幕上開真的瀏覽器。看到:最接近的真路是無頭的實機測試(下面):`click` 輸入框回「游標已在…裡」、`type` 多行整段進去、編號不變;在回覆框送出有【系統】那行和留言網址,同一篇再送被擋,搜尋框按 Enter 不算送出。 - **桌面的設定檔區塊**(covers `browser-profiles`、`browser-close`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot browser ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`。看到:設定 › 電腦「AnyBot 瀏覽器設定檔」的使用中設定檔、「開啟視窗」、「做完就關掉瀏覽器」、「發布前檢查」。 -- 自動測試:`cargo test browser::`、`cargo test publish::`、`cargo test evidence::`、`cargo test an_ask_pattern_stops_the_bots_browser`、`cargo test private_pages_and_uploads_go_through_the_persons_rules`、`cargo test the_bots_browser_is_not_held_up_by_rules_about_other_things`;實機(無頭 Chrome,或 Brave/Firefox;暫存資料夾、自己的連接埠):`ANYBOT_DATA_DIR=<暫存資料夾> ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new cargo test lines_go_in_whole_and_numbers_stay_put -- --ignored`,`a_send_is_seen_with_the_post_it_answers_and_its_own_address` 照同樣跑(Firefox 加 `ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1`、`HOME` 也換掉)。 +- 自動測試:`cargo test browser::`、`cargo test publish::`、`cargo test evidence::`、`cargo test an_ask_pattern_stops_the_bots_browser`、`cargo test private_pages_and_uploads_go_through_the_persons_rules`、`cargo test the_bots_browser_is_not_held_up_by_rules_about_other_things`、`cargo test addresses_are_read_as_a_browser_reads_them`、`cargo test an_upload_with_the_switches_off_always_asks`、`cargo test a_hook_ask_and_a_rule_make_one_card_for_a_browser_step`;實機(無頭 Chrome,或 Brave/Firefox;暫存資料夾、自己的連接埠):`ANYBOT_DATA_DIR=<暫存資料夾> ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new cargo test lines_go_in_whole_and_numbers_stay_put -- --ignored`,`a_send_is_seen_with_the_post_it_answers_and_its_own_address` 照同樣跑(Firefox 加 `ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1`、`HOME` 也換掉)。 ## 陷阱 @@ -46,8 +46,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 下拉選單用 `select`,`option` 填選項上看得到的字(給 `value` 也行,對下拉選單 `type` 也會改成選選項);什麼都沒給會報錯。 - `fill` 是保險庫的填入;指著頁面上一個欄位(有 `ref`/`text`、沒有 kind/id/site)時當成 `type`(有 `option` 時當 `select`),不會跑去保險庫。 - `eval` 只能讀頁面:不能發請求、讀 cookie 或儲存、送出表單、換頁(會被拒絕);直接呼叫網站內部 API 會被當成機器人。 -- 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外,但符合「一律詢問」規則的照樣問)。 -- 自動審核開著時,「一律詢問」寫成樣式(`tool(browser_click)`、`web(domain:example.com)`)的,AnyBot 瀏覽器的步驟和 `web_fetch` 每次都停下來問,本來不用問、一律允許過的也一樣;用一般的話寫的只看本來就要問的(本機網址、上傳檔案)。 +- 雲端中繼資料位址永遠打不開;本機或內部網路的網址先問使用者(可以一律允許)——直接操作開著、或自動審核的「無需詢問直接允許」符合時不問,符合「一律詢問」的照樣問。網址照瀏覽器的讀法判斷:大小寫、結尾的點、`帳號@`、反斜線、十進位寫的 IP 都看得出是哪台。 +- 自動審核開著時,「一律詢問」的樣式本來不用問、一律允許過的也照樣問:`tool(…)` 比對每一步的名字(`tool(browser_click)`、`tool(browser_*)`);`web(domain:example.com)` 比對用網址打開或讀的那一步(`open`、帶網址開新分頁、`web_fetch`),點連結、網頁自己轉址、上一頁到的網頁不比對。用一般的話寫的只看本來就要問的(本機網址、上傳檔案)。從這台上傳檔案時 Bot 的電腦工具或「在這台電腦上執行」沒開,一律跳卡片,規則省不掉。 - 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。 - 送出後頁面上沒看到(例如從動態牆送出),結果寫「還沒確認」:不要因此再送一次,回原貼文看。 - 網頁要上傳檔案(Threads、IG 加相片、表單附件):用 `upload` 直接放進頁面的檔案欄位。用螢幕去點「加入相片」會跳出 Bot 電腦的檔案視窗(「取消」「Open」在最上面),還要在裡面找檔案、按 Open。 diff --git a/src/agent.rs b/src/agent.rs index 211fbee..dfdfe60 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1874,9 +1874,9 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { browser: Default::default(), }; let tool = steps::tool_for(&s); - // A hook's 「ask」: OnComputer and Connector put it with their own question (one card); every - // other tool asks here (an app action, a file sent out… would have gone ahead). - if !matches!(tool.name(), "OnComputer" | "Connector") { + // A hook's 「ask」: OnComputer, Connector and InBotsBrowser put it with their own question (one + // card); every other tool asks here (an app action, a file sent out… would have gone ahead). + if !matches!(tool.name(), "OnComputer" | "Connector" | "InBotsBrowser") { if let Some(why) = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, w)| w) { let answer = s.ask_person(ApprovalKind::Action, format!("{}(你的 hook 要先問:{})", s.what(), if why.is_empty() { "沒有說原因" } else { why.as_str() }), String::new()); if s.cancel.load(Ordering::Relaxed) { @@ -4794,18 +4794,25 @@ echo 'done送出了' > done.html; (setsid pyt fn an_ask_pattern_stops_the_bots_browser() { for direct in [false, true] { let mine = Review { allow: vec![], ask: vec!["tool(browser_click)".into(), "web(domain:example.com)".into(), "web(domain:127.0.0.1)".into()] }; + let open = |id: &str, url: &str| sse_call(id, "browser", serde_json::json!({"action": "open", "url": url})); let replies = vec![ sse_call("c1", "browser", serde_json::json!({"action": "click", "ref": "3"})), - sse_call("c2", "browser", serde_json::json!({"action": "open", "url": "https://shop.example.com/cart"})), + open("c2", "https://shop.example.com/cart"), sse_call("c3", "web_fetch", serde_json::json!({"url": "http://127.0.0.1:9/"})), + // The host a browser opens, however the address is written (the reviewer's probes). + open("c4", "https://me@example.com/cart"), + open("c5", "https://shop.example.com./cart"), + open("c6", "https://example.com\\cart"), + sse_call("c7", "browser_tabs", serde_json::json!({"action": "new", "url": "https://shop.example.com/cart"})), ]; let (asked, results, seen) = browser_turn(replies, direct, Some(mine), &[], ApprovalAnswer::Reject); - assert_eq!(asked.len(), 3, "direct={direct}: {asked:?} {results:?}"); - for ((reason, grant), rule) in asked.iter().zip(["tool(browser_click)", "web(domain:example.com)", "web(domain:127.0.0.1)"]) { + assert_eq!(asked.len(), 7, "direct={direct}: {asked:?} {results:?}"); + for ((reason, grant), rule) in asked.iter().zip(["tool(browser_click)", "web(domain:example.com)", "web(domain:127.0.0.1)", "web(domain:example.com)", "web(domain:example.com)", "web(domain:example.com)", "web(domain:example.com)"]) { assert!(reason.contains(&format!("符合你的「一律詢問」規則:{rule}")) && grant.is_empty(), "{reason} [{grant}]"); } + assert!(asked[5].0.contains("https://example.com/cart"), "the card shows the address that would open: {}", asked[5].0); assert!(results.iter().all(|r| r.contains("使用者拒絕了這個操作")), "{results:?}"); - assert_eq!(seen.len(), 4, "no model call to review them"); + assert_eq!(seen.len(), 8, "no model call to review them"); } } @@ -4850,6 +4857,69 @@ echo 'done送出了' > done.html; (setsid pyt assert!(asked.is_empty(), "直接操作 with no rules: {asked:?}"); } + /// An upload of a file of this computer while the bot's computer tools or 在這台電腦上執行 are + /// off: the switches' question is a card whatever 自動審核 says (gate steps 3 and 5 before 7) — + /// an allow rule saved it before. With them on, the allow rule lets it go; 直接操作 counts as on. + #[test] + fn an_upload_with_the_switches_off_always_asks() { + let w = std::env::temp_dir().join(format!("anybot-upload-{}", std::process::id())); + std::fs::create_dir_all(&w).unwrap(); + std::fs::write(w.join("a.txt"), "x").unwrap(); + let here = tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }; + let allow = Some(Review { allow: vec!["tool(browser_upload)".into()], ask: vec![] }); + let job = |direct: bool| Job { review: allow.clone(), direct: Arc::new(AtomicBool::new(direct)), ..test_job() }; + let args = serde_json::json!({"ref": "4", "path": "a.txt"}).to_string(); + let decide = |job: &Job, switches_on: bool| steps::here_upload_decision(job, &args, &here, "a.txt", &w.join("a.txt"), &[], false, switches_on, &AtomicBool::new(false)); + let (d, switch, note) = decide(&job(false), false); + assert!(matches!(&d, Decision::Ask { grant, .. } if grant.is_empty()) && switch && note.is_empty(), "switches off: {d:?}"); + let (d, switch, note) = decide(&job(false), true); + assert!(d == Decision::Allow && !switch && note.is_empty(), "switches on, a file in the work folder: {d:?}"); + // A file outside the work folder is asked about by the file rules: 自動審核's allow lets it go. + let out = std::env::temp_dir().join(format!("anybot-upload-out-{}.txt", std::process::id())); + std::fs::write(&out, "y").unwrap(); + let path = out.display().to_string(); + let (d, switch, note) = steps::here_upload_decision(&job(false), &args, &here, &path, &out, &[], false, true, &AtomicBool::new(false)); + assert!(d == Decision::Allow && !switch && note.contains("tool(browser_upload)"), "outside, switches on: {d:?} {note}"); + let (d, switch, _) = steps::here_upload_decision(&job(false), &args, &here, &path, &out, &[], false, false, &AtomicBool::new(false)); + assert!(matches!(d, Decision::Ask { .. }) && switch, "outside, switches off: {d:?}"); + let (d, _, _) = decide(&job(true), true); + assert_eq!(d, Decision::Allow, "直接操作"); + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_dir_all(&w); + } + + /// A hook's 「ask」 about an AnyBot-browser step goes on the same card as a pattern rule's (one + /// card, no 「一律允許」); alone it is a card of its own, as before. + #[cfg(unix)] + #[test] + fn a_hook_ask_and_a_rule_make_one_card_for_a_browser_step() { + use crate::hooks::{Config, Group, Hook, Hooks}; + let mut c = Config::default(); + let hook = Hook { kind: "command".into(), command: r#"echo '{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"瀏覽器先給我看"}}'"#.into(), url: String::new(), headers: Default::default(), timeout: Some(10) }; + c.hooks.insert("PreToolUse".into(), vec![Group { matcher: "browser_.*".into(), hooks: vec![hook] }]); + crate::hooks::test_hooks().lock().unwrap().insert(1, Hooks { admin: Config::default(), mine: c }); + let click = || sse_call("c1", "browser", serde_json::json!({"action": "click", "ref": "3"})); + let mine = Some(Review { allow: vec![], ask: vec!["tool(browser_click)".into()] }); + let (both, _, _) = browser_turn(vec![click()], false, mine, &[], ApprovalAnswer::Reject); + let (alone, _, _) = browser_turn(vec![click()], false, None, &[], ApprovalAnswer::Reject); + crate::hooks::test_hooks().lock().unwrap().remove(&1); + assert!(both.len() == 1 && both[0].0.contains("規則:tool(browser_click)") && both[0].0.contains("你的 hook 要先問:瀏覽器先給我看") && both[0].1.is_empty(), "{both:?}"); + assert!(alone.len() == 1 && alone[0].0.contains("你的 hook 要先問:瀏覽器先給我看") && alone[0].1.is_empty(), "{alone:?}"); + } + + /// Pattern rules nothing is compared with are said so where they are added: a connector's + /// that names no tool, a web(…) not written as web(domain:site), a tool(…) by a name no step runs as. + #[test] + fn pattern_rules_that_name_nothing_are_said_so() { + let w = |r: &str| crate::gate::rule_warning(r, &[]); + for ok in ["web(domain:example.com)", "web(domain:Bücher.example)", "tool(browser_click)", "tool(browser_*)", "tool(web_fetch)", "tool(shell)", "tool(computer_use_click)", "shell(git *)", "file(~/x/**)", "付款前先問我"] { + assert_eq!(w(ok), None, "{ok}"); + } + for (bad, says) in [("tool(browser)", "browser_click"), ("tool(computer)", "computer_use_click"), ("web(example.com)", "web(domain:"), ("web(domain:*.example.com)", "不用 *"), ("web(domain:https://example.com/a)", "整個 example.com"), ("web(domain:not a site)", "看起來不是網站")] { + assert!(w(bad).is_some_and(|t| t.contains(says)), "{bad}: {:?}", w(bad)); + } + } + /// A connector step's decision on fixed rules, as Allow / Allow+note (自動審核 let it, the result /// says so) / Ask[the grant 「一律允許」 would keep] with why (rule=…, failed, hook), and how many /// times the reviewer model was asked — 「一律允許」 for the connector or not × 直接操作 or not × @@ -4863,18 +4933,27 @@ echo 'done送出了' > done.html; (setsid pyt let add = crate::mcp::tool_name("calc-ch", "add"); let says = |text: &str| Fake::start(Format::OpenAi, vec![], Some(Reply::text(text))); let (ask, none, garbled) = (says(r#"{"verdict":"ask","rule":"傳訊息給別人前先問我"}"#), says(r#"{"verdict":"none","rule":""}"#), says("嗯…讓我想想")); + let allow = says(r#"{"verdict":"allow","rule":"計算不用問"}"#); + let short = r#"{"a":1,"b":2}"#.to_string(); + // An argument longer than the reviewer reads, what a rule would name in the middle. + let long = format!(r#"{{"a":"{}","to":"SECRET-IN-THE-MIDDLE","z":"{}"}}"#, "x".repeat(3500), "y".repeat(3500)); let rules = |allow: &[&str], ask: &[&str]| Some(Review { allow: allow.iter().map(|r| r.to_string()).collect(), ask: ask.iter().map(|r| r.to_string()).collect() }); let words = "傳訊息給別人前先問我"; - let sets: Vec<(&str, Option, &Fake)> = vec![ - ("off", None, &none), - ("ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none), - ("allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none), - ("both-patterns", rules(&["connector(calc-ch__*)"], &["connector(calc-ch__add)"]), &none), - ("other-connector", rules(&["connector(other__*)"], &["connector(other__*)"]), &none), - ("sentence:ask", rules(&[], &[words]), &ask), - ("sentence:none", rules(&[], &[words]), &none), - ("sentence:garbled", rules(&[], &[words]), &garbled), - ("allow-pattern+sentence:ask", rules(&["connector(calc-ch__*)"], &[words]), &ask), + let sets: Vec<(&str, Option, &Fake, &String)> = vec![ + ("off", None, &none, &short), + ("ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none, &short), + ("allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none, &short), + ("both-patterns", rules(&["connector(calc-ch__*)"], &["connector(calc-ch__add)"]), &none, &short), + ("other-connector", rules(&["connector(other__*)"], &["connector(other__*)"]), &none, &short), + ("sentence:ask", rules(&[], &[words]), &ask, &short), + ("sentence:none", rules(&[], &[words]), &none, &short), + ("sentence:garbled", rules(&[], &[words]), &garbled, &short), + ("allow-pattern+sentence:ask", rules(&["connector(calc-ch__*)"], &[words]), &ask, &short), + ("sentence-allow:allow", rules(&["計算不用問"], &[]), &allow, &short), + ("cut sentence-allow:allow", rules(&["計算不用問"], &[]), &allow, &long), + ("cut sentence:none", rules(&[], &[words]), &none, &long), + ("cut allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none, &long), + ("cut ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none, &long), ]; let shape = |d: &Decision, note: &str| match d { Decision::Allow if note.is_empty() => "Allow".to_string(), @@ -4889,17 +4968,18 @@ echo 'done送出了' > done.html; (setsid pyt String::new() }; let hook = if reason.contains("你的 hook 要先問") { " +hook" } else { "" }; - format!("Ask[{grant}]{why}{hook}") + let cut = if reason.contains(steps::REVIEW_CUT_NOTE) { " cut" } else { "" }; + format!("Ask[{grant}]{why}{hook}{cut}") } }; let mut got = vec![]; - for (set, review, fake) in &sets { + for (set, review, fake, args) in &sets { for granted in [false, true] { for direct in [false, true] { let job = Job { req: ChatRequest { base_url: fake.base(), model: "m".into(), ..test_job().req }, review: review.clone(), direct: Arc::new(AtomicBool::new(direct)), ..test_job() }; let grants: Vec = if granted { vec!["mcp:calc-ch".into()] } else { vec![] }; let before = fake.requests(); - let (d, note) = steps::connector_decision(&job, &grants, &add, r#"{"a":1,"b":2}"#, None, &AtomicBool::new(false)); + let (d, note) = steps::connector_decision(&job, &grants, &add, args, None, &AtomicBool::new(false)); got.push(format!("{set} granted={granted} direct={direct}: {} model={}", shape(&d, ¬e), fake.requests() - before)); } } @@ -4924,6 +5004,12 @@ echo 'done送出了' > done.html; (setsid pyt ("sentence:none", ["Ask[mcp:calc-ch] model=1", "Allow model=1", "Allow model=0", "Allow model=0"].map(String::from)), ("sentence:garbled", ["Ask[mcp:calc-ch] failed model=1", "Ask[] failed model=1", "Allow model=0", "Allow model=0"].map(String::from)), ("allow-pattern+sentence:ask", [format!("Ask[]{rule_w} model=1"), format!("Ask[]{rule_w} model=1"), "Allow model=0".into(), "Allow model=0".into()]), + ("sentence-allow:allow", ["Allow+note model=1", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + // The reviewer read only the ends: its yes, or 直接操作's "no rule is about it", asks. + ("cut sentence-allow:allow", ["Ask[mcp:calc-ch] cut model=1", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("cut sentence:none", ["Ask[mcp:calc-ch] model=1", "Ask[] cut model=1", "Allow model=0", "Allow model=0"].map(String::from)), + ("cut allow-pattern", ["Allow+note model=0", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("cut ask-pattern", [0; 4].map(|_| format!("Ask[]{rule_a} model=0"))), ] .into_iter() .flat_map(|(set, four)| [(false, false), (false, true), (true, false), (true, true)].into_iter().zip(four).map(move |((g, d), w)| format!("{set} granted={g} direct={d}: {w}"))) diff --git a/src/agent/steps.rs b/src/agent/steps.rs index efc5cd7..2f0bac0 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -497,6 +497,35 @@ impl TurnTool for SentLog { } } +/// An upload of a file of this computer to a page in AnyBot's browser: what the person +/// attached for this bot goes; 在這台電腦上執行 locked refuses; with the bot's computer tools or +/// 在這台電腦上執行 off (`switches_on` false, 直接操作 counts as on) the switches' question is +/// asked as it is — gate steps 3 and 5 come before 自動審核 (step 7), so no rule saves it; else +/// the file rules (tools::decide_file_out), then `reviewed` (自動審核, 直接操作). Returns the +/// decision, whether it is the switches' question (no other yes saves it), and the note. +#[allow(clippy::too_many_arguments)] +pub(super) fn here_upload_decision(job: &Job, args: &str, here: &tools::Target, path: &str, named: &std::path::Path, grants: &[String], given: bool, switches_on: bool, cancel: &AtomicBool) -> (Decision, bool, String) { + if given { + return (Decision::Allow, false, String::new()); + } + if job.local_locked { + return (Decision::Deny(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能上傳「{}」上的檔案。", here.name)), false, String::new()); + } + let outside = |grant: String| Decision::Ask { reason: format!("把工作資料夾以外的檔案上傳到網頁:{}", named.display()), grant }; + match tools::decide_file_out(here, path, grants) { + Decision::Allow if !switches_on => (Decision::Ask { reason: format!("把「{}」上的檔案上傳到網頁:{}", here.name, named.display()), grant: String::new() }, true, String::new()), + Decision::Ask { grant, .. } if !switches_on => (outside(grant), true, String::new()), + d => { + let d = match d { + Decision::Ask { grant, .. } => outside(grant), + d => d, + }; + let (d, _, note) = reviewed(job, "browser_upload", args, d, false, cancel); + (d, false, note) + } + } +} + /// Public web pages need no computer and no permission — and neither does AnyBot's own /// browser (like the reference assistant's own browser). A step naming a computer with no /// browser there is said so, not run elsewhere. @@ -540,11 +569,18 @@ impl TurnTool for InBotsBrowser { // bot goes as it is. The path is made whole here, so the browser takes the // very file that was checked. let mut call_args = call.args.clone(); - // The page this step opens, made whole: the safety rules first. - let opens = (call.name == "browser_open" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new"))) - .then(|| tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string()) - .filter(|u| !u.is_empty()) - .and_then(|u| web::normalize_url(&u).ok()); + // The page this step opens or fetches by its address, as a browser reads it (web::parse_url): + // the browser is handed that very address, and the safety rules, the private-network card + // and the person's rules all check it — what is checked is what opens. + let by_address = call.name == "browser_open" || call.name == "web_fetch" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new")); + let url_given = tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string(); + let canonical = by_address.then(|| web::normalize_url(&url_given).ok()).flatten(); + if let Some(c) = &canonical { + let mut v = tools::args_of(&call.args); + v["url"] = serde_json::Value::String(c.clone()); + call_args = v.to_string(); + } + let opens = canonical.clone().filter(|_| call.name != "web_fetch"); let private = opens.as_deref().is_some_and(|norm| !matches!(place, BrowserAt::Box) && web::is_private_browser_url(norm)); if opens.as_deref().is_some_and(web::is_forbidden_browser_url) { s.finish("被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。", ToolStatus::Denied, None); @@ -555,13 +591,22 @@ impl TurnTool for InBotsBrowser { return Flow::Next; } // The person's 「一律詢問」 patterns (only compared, no model call) over a browser step that - // needs no permission or was 「一律允許」, as for a connector: one card naming the rule; a yes - // to it is the yes to this step (no second card below). What would be asked anyway goes - // through `reviewed` (自動審核, 直接操作) — never sentences on every click. + // needs no permission or was 「一律允許」, as for a connector — and a hook's 「ask」 on the same + // card: one card naming the rule; a yes to it is the yes to this step (no second card below, + // except the switches' own). What would be asked anyway goes through `reviewed` (自動審核, + // 直接操作) — never sentences on every click. let on_line = if on.is_empty() { String::new() } else { format!("\n(在 {on} 上)") }; + let step_words = format!("{} {}", web::label(&call.name), canonical.clone().unwrap_or_else(|| s.what())); + let hook_ask = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, why)| format!("(你的 hook 要先問:{})", if why.is_empty() { "沒有說原因" } else { why.as_str() })); + let first = match (ask_pattern(job, &call.name, &call_args, &step_words), hook_ask) { + (Some(Decision::Ask { reason, .. }), Some(hook)) => Some(format!("{reason}{hook}")), + (Some(Decision::Ask { reason, .. }), None) => Some(reason), + (_, Some(hook)) => Some(format!("{step_words}{hook}")), + _ => None, + }; let mut said_yes = false; - if let Some(Decision::Ask { reason, grant }) = ask_pattern(job, &call.name, &call.args, &format!("{} {}", web::label(&call.name), s.what())) { - if s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) == ApprovalAnswer::Reject { + if let Some(reason) = first { + if s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), String::new()) == ApprovalAnswer::Reject { s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None); return Flow::Next; } @@ -574,7 +619,7 @@ impl TurnTool for InBotsBrowser { if let (true, false, Some(norm)) = (private, said_yes, opens.as_deref()) { let grant = "browser:private".to_string(); let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("在瀏覽器開啟本機或內部網路網址:{norm}"), grant } }; - let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + let (decision, _, note) = reviewed(job, &call.name, &call_args, decision, false, cancel); review_note = note; if let Decision::Ask { reason, grant } = decision { match s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) { @@ -603,25 +648,14 @@ impl TurnTool for InBotsBrowser { tools::Place::Local { workdir } => tools::resolve(workdir, &path), _ => std::path::PathBuf::from(&path), }; - let direct = job.direct.load(Ordering::Relaxed); - let decision = if crate::attach::is_given(bot_id, &named) { - Decision::Allow - } else if job.local_locked { - Decision::Deny(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能上傳「{}」上的檔案。", here.name)) - } else { - match tools::decide_file_out(&here, &path, s.grants) { - Decision::Allow if !direct && !(*s.tools_on && *s.local_on) => Decision::Ask { reason: format!("把「{}」上的檔案上傳到網頁:{}", here.name, named.display()), grant: String::new() }, - Decision::Ask { grant, .. } => Decision::Ask { reason: format!("把工作資料夾以外的檔案上傳到網頁:{}", named.display()), grant }, - d => d, - } - }; - // (直接操作 and 自動審核 as for any step: an 「一律詢問」 rule still stops it.) - let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + let given = crate::attach::is_given(bot_id, &named); + let switches_on = job.direct.load(Ordering::Relaxed) || (*s.tools_on && *s.local_on); + let (decision, switch_asks, note) = here_upload_decision(job, &call_args, &here, &path, &named, s.grants, given, switches_on, cancel); review_note = note; let refused = match decision { Decision::Allow => None, Decision::Deny(r) => Some(format!("被安全規則擋下:{r}")), - Decision::Ask { .. } if said_yes => None, + Decision::Ask { .. } if said_yes && !switch_asks => None, Decision::Ask { reason, grant } => { let (atx, arx) = channel(); send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); @@ -654,7 +688,7 @@ impl TurnTool for InBotsBrowser { } let grant = format!("upload-device:{on}"); let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("把「{on}」上的檔案上傳到網頁:{path}"), grant } }; - let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + let (decision, _, note) = reviewed(job, &call.name, &call_args, decision, false, cancel); review_note = note; if let (Decision::Ask { reason, grant }, false) = (decision, said_yes) { let (atx, arx) = channel(); @@ -1554,8 +1588,28 @@ fn ask_pattern(job: &Job, name: &str, args: &str, reason: &str) -> Option bool { + use crate::gate::{is_pattern, patterns, PatternVerdict}; + let Some(rv) = &job.review else { return false }; + let words = |v: &[String]| v.iter().any(|r| !is_pattern(r)); + if job.direct.load(Ordering::Relaxed) { + return matches!(patterns(name, args, &[], &rv.ask), PatternVerdict::NoMatch) && words(&rv.ask); + } + match patterns(name, args, &rv.allow, &rv.ask) { + PatternVerdict::Ask(_) => false, + PatternVerdict::Allow(_) => words(&rv.ask), + PatternVerdict::NoMatch => words(&rv.ask) || words(&rv.allow), + } +} + /// Arguments as the reviewer reads them: whole up to [`REVIEW_ARGS`], else the start and the end -/// with how much was left out between them. +/// with how much was left out between them (and then its yes is not enough: REVIEW_CUT_NOTE). pub(super) fn for_reviewer(args: &str) -> String { let n = args.chars().count(); if n <= REVIEW_ARGS { @@ -1582,8 +1636,13 @@ pub(super) fn connector_decision(job: &Job, grants: &[String], name: &str, args: None if grants.contains(&grant) => (Decision::Allow, String::new()), None => { let read = format!("{what}{}", for_reviewer(args)); - match reviewed(job, name, args, Decision::Ask { reason: read.clone(), grant }, false, cancel) { + // The reviewer read only the two ends of a long argument: its yes (or, in 直接操作, its + // "no rule is about it") doesn't cover the middle, which the model chose to put there. + let cut = args.chars().count() > REVIEW_ARGS && model_reads(job, name, args); + let direct = job.direct.load(Ordering::Relaxed); + match reviewed(job, name, args, Decision::Ask { reason: read.clone(), grant: grant.clone() }, false, cancel) { (Decision::Ask { reason, grant }, _, note) => (Decision::Ask { reason: reason.strip_prefix(&read).map(|rest| format!("{card}{rest}")).unwrap_or(reason), grant }, note), + (Decision::Allow, _, _) if cut => (Decision::Ask { reason: format!("{card}{REVIEW_CUT_NOTE}"), grant: if direct { String::new() } else { grant } }, String::new()), (d, _, note) => (d, note), } } diff --git a/src/app.rs b/src/app.rs index 44ab3c5..d45af7a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5993,8 +5993,8 @@ impl App { }); }); }); - // A connector(…) rule that names no connector's tool: said where it is. - if let Some(w) = crate::mcp::rule_names_nothing(r, &self.state.mcp_servers) { + // A pattern rule nothing it is compared with answers to: said where it is. + if let Some(w) = crate::gate::rule_warning(r, &self.state.mcp_servers) { hint(ui, w, p); } } diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 566ed44..1b4afdd 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1552,7 +1552,7 @@ impl App { if text.is_empty() { return fail("規則是空的"); } - let unknown = crate::mcp::rule_names_nothing(&text, &self.state.mcp_servers); + let unknown = crate::gate::rule_warning(&text, &self.state.mcp_servers); if !list.contains(&text) { list.push(text); } diff --git a/src/featuremap.rs b/src/featuremap.rs index 83ee473..79a3255 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -128,6 +128,27 @@ pub fn read(topic: &str) -> Result { .ok_or_else(|| format!("沒有「{t}」這一區。可以讀:{}", AREAS.iter().map(|a| a.slug).collect::>().join("、"))) } +/// Every tool a bot can be given, from where the window puts them together (app.rs), as it is +/// offered (the one `browser` and `computer` tools among them). +pub fn every_tool() -> Vec { + let names = |specs: &[Value]| specs.iter().filter_map(|t| t["name"].as_str().map(String::from)).collect::>(); + let one = vec!["x".to_string()]; + let mut all = names(&crate::appctl::specs()); + all.extend(names(&crate::tools::specs_for(&one, "x"))); + all.extend(names(&crate::web::specs_for(&one, "x"))); + all.extend(names(&crate::computer::specs_for(&one, "x", true))); + all.extend(names(&crate::macapps::specs())); + all.extend(names(&crate::phone::specs())); + all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true }))); + all.extend(crate::ask::spec()["name"].as_str().map(String::from)); + all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL, crate::outputs::TOOL].map(String::from)); + all.extend(crate::teach::view_step_spec()["name"].as_str().map(String::from)); + all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from)); + all.sort(); + all.dedup(); + all +} + #[cfg(test)] mod tests { use super::*; @@ -142,33 +163,10 @@ mod tests { bot_view(AREAS.iter().find(|a| a.slug == slug).unwrap().text) } - fn names(specs: &[Value]) -> Vec { - specs.iter().filter_map(|t| t["name"].as_str().map(String::from)).collect() - } - fn actions(specs: &[Value], tool: &str) -> Vec { specs.iter().filter(|t| t["name"] == tool).flat_map(|t| t["parameters"]["properties"]["action"]["enum"].as_array().cloned().unwrap_or_default()).filter_map(|a| a.as_str().map(String::from)).collect() } - /// Every tool a bot can be given, from where the window puts them together (app.rs). - fn every_tool() -> Vec { - let one = vec!["x".to_string()]; - let mut all = names(&crate::appctl::specs()); - all.extend(names(&crate::tools::specs_for(&one, "x"))); - all.extend(names(&crate::web::specs_for(&one, "x"))); - all.extend(names(&crate::computer::specs_for(&one, "x", true))); - all.extend(names(&crate::macapps::specs())); - all.extend(names(&crate::phone::specs())); - all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true }))); - all.push(crate::ask::spec()["name"].as_str().unwrap().to_string()); - all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL, crate::outputs::TOOL].map(String::from)); - all.push(crate::teach::view_step_spec()["name"].as_str().unwrap().to_string()); - all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from)); - all.sort(); - all.dedup(); - all - } - #[test] fn every_tool_a_bot_can_be_given_is_on_the_map() { let map = map_text(); diff --git a/src/gate.rs b/src/gate.rs index e82b3b0..d858bb8 100644 --- a/src/gate.rs +++ b/src/gate.rs @@ -230,10 +230,6 @@ pub fn glob(pat: &str, text: &str, slash_stops: bool) -> bool { 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 { @@ -263,16 +259,69 @@ fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) 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}"))) + // Every way a step opens or fetches a page by its address (a new tab with one too): the + // host as the browser reads it (web::host_of — `\`, user@, case, a trailing dot, IDNA, + // IPs in any spelling), the rule's domain read the same way. (Pages reached by a click, a + // redirect or 上一頁 aren't opened by address: no rule sees them.) + "web" if matches!(name, "web_fetch" | "browser_open") || (name == "browser_tabs" && s("action") == "new") => { + let want = inner.strip_prefix("domain:").unwrap_or(inner).trim(); + match (crate::web::host_of(&s("url")), crate::web::host_of(want)) { + (Some(host), Some(want)) => host == want || host.ends_with(&format!(".{want}")), + _ => false, + } } "tool" => glob(inner, name, false), _ => false, } } +/// Every name a `tool(…)` pattern is compared with: the tools as steps run (the one `browser` and +/// `computer` tools are opened up into browser_click, computer_use_click…), connectors' too. +fn tool_names() -> Vec { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let mut v = FIXED + .get_or_init(|| { + let mut v = crate::featuremap::every_tool(); + v.extend(crate::browser::NAMES.iter().chain(crate::computer::NAMES.iter()).chain(crate::web::NAMES.iter()).map(|n| n.to_string())); + v.extend(["browser_fill_login", "browser_fill_card", "browser_fill_contact"].map(String::from)); + v.retain(|n| n != crate::browser::TOOL && n != crate::computer::TOOL); + v + }) + .clone(); + v.extend(crate::mcp::tools().iter().map(|t| crate::mcp::tool_name(&t.server, &t.name))); + v +} + +/// What to tell the person adding a rule written as a pattern that nothing it is compared with +/// answers to — said where the rule is added (the settings page, the phone). None: it can match, +/// or it is a sentence for the model, or a shell / file pattern (any command or path may come). +pub fn rule_warning(rule: &str, servers: &[crate::mcp::Server]) -> Option { + let r = rule.trim(); + if !is_pattern(r) { + return None; + } + let (kind, inner) = r.split_once('(').map(|(k, rest)| (k, rest.strip_suffix(')').unwrap_or(rest).trim()))?; + match kind { + "connector" => crate::mcp::rule_names_nothing(r, servers), + "web" => { + let Some(domain) = inner.strip_prefix("domain:").map(str::trim) else { + return Some(format!("「{r}」要寫成 web(domain:網站),例如 web(domain:example.com)。")); + }; + if domain.contains('*') { + Some(format!("「{r}」不用 *:web(domain:example.com) 已經包含它底下的網址(shop.example.com 也算)。")) + } else if crate::web::host_of(domain).is_none() { + Some(format!("「{r}」的「{domain}」看起來不是網站,例如 web(domain:example.com)。")) + } else if domain.contains('/') || domain.contains('@') { + Some(format!("「{r}」只比對網站,會當成整個 {}(不寫 https://、帳號和路徑)。", crate::web::host_of(domain).unwrap_or_default())) + } else { + None + } + } + "tool" => (!tool_names().iter().any(|n| glob(inner, n, false))).then(|| format!("「{r}」對不上任何工具的名字:比對的是每一步真正的名字,例如 browser_click、browser_open、web_fetch、shell、computer_use_click(瀏覽器的全部寫 tool(browser_*))。")), + _ => None, + } +} + /// 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 { @@ -317,6 +366,18 @@ mod pattern_tests { 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); + // The host as a browser reads it: user@, a trailing dot, case, a backslash, a new tab by address. + for (name, args) in [ + ("web_fetch", serde_json::json!({"url": "https://x@example.com/"})), + ("web_fetch", serde_json::json!({"url": "https://EXAMPLE.com./"})), + ("browser_open", serde_json::json!({"url": "https://shop.example.com\\cart"})), + ("browser_tabs", serde_json::json!({"action": "new", "url": "https://me@shop.example.com./cart"})), + ] { + assert_eq!(p(name, args.clone()), PatternVerdict::Allow("web(domain:example.com)".into()), "{name} {args}"); + } + assert_eq!(p("web_fetch", serde_json::json!({"url": "https://example.com@evil.net/"})), PatternVerdict::NoMatch, "evil.net is the host"); + assert_eq!(p("browser_tabs", serde_json::json!({"action": "select", "index": 1})), PatternVerdict::NoMatch); + assert_eq!(patterns("browser_open", r#"{"url":"https://xn--bcher-kva.example/"}"#, &[], &["web(domain:Bücher.example)".into()]), PatternVerdict::Ask("web(domain:Bücher.example)".into()), "the rule's domain read the same way"); 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")); } diff --git a/src/web.rs b/src/web.rs index 85688e5..1b4ebfd 100644 --- a/src/web.rs +++ b/src/web.rs @@ -165,26 +165,47 @@ pub fn run(name: &str, args: &str, cancel: &AtomicBool) -> (String, bool) { } } -pub fn normalize_url(u: &str) -> Result { +/// A web address as a browser reads it (WHATWG URL, the `url` crate): `\` is `/`, `user@` is not +/// the host, the host lowercased and in punycode, an IP in any spelling made plain. Everything that +/// checks an address (the private-network card, the rules, web_fetch's own check) reads it this +/// way, and the browser is handed the address as parsed — what is checked is what opens. (Taking +/// the host apart by hand let `http://127.0.0.1\@a.com/` past the private-network card.) +pub fn parse_url(u: &str) -> Result { let u = u.trim(); if u.is_empty() { return Err("請給網址".into()); } - let full = if u.starts_with("http://") || u.starts_with("https://") { u.to_string() } else { format!("https://{u}") }; - // Check the host part after the scheme (a fixed [8..] cut one byte short for http://). - let rest = full.split_once("://").map(|(_, r)| r).unwrap_or(&full); - let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); - let host_only = authority.rsplit('@').next().unwrap_or(authority); - let bare = if let Some(v6) = host_only.strip_prefix('[') { - v6.split_once(']').map(|(a, _)| a).unwrap_or(host_only) - } else { - host_only.split(':').next().unwrap_or(host_only) + let bad = || format!("「{u}」看起來不是網址"); + let has_scheme = ["http://", "https://"].iter().any(|p| u.get(..p.len()).is_some_and(|h| h.eq_ignore_ascii_case(p))); + let full = if has_scheme { u.to_string() } else { format!("https://{u}") }; + if full.contains(char::is_whitespace) { + return Err(bad()); } - .trim_end_matches('.'); - if full.contains(char::is_whitespace) || (!bare.contains('.') && !bare.contains(':') && !bare.eq_ignore_ascii_case("localhost")) { - return Err(format!("「{u}」看起來不是網址")); + let parsed = url::Url::parse(&full).map_err(|_| bad())?; + match parsed.host() { + Some(url::Host::Domain(d)) if d.trim_end_matches('.').contains('.') || d.trim_end_matches('.') == "localhost" => Ok(parsed), + Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) => Ok(parsed), + _ => Err(bad()), } - Ok(full) +} + +/// [`parse_url`], written out (the form handed to the browser). +pub fn normalize_url(u: &str) -> Result { + parse_url(u).map(|p| p.to_string()) +} + +/// The host a browser would open for this address: lowercased, punycode, no trailing dot, an IP +/// plain (an IPv6 one without brackets). None when it isn't a web address. +pub fn host_of(u: &str) -> Option { + parse_url(u).ok().and_then(|p| host_text(&p)) +} + +fn host_text(p: &url::Url) -> Option { + Some(match p.host()? { + url::Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(), + url::Host::Ipv4(a) => a.to_string(), + url::Host::Ipv6(a) => a.to_string(), + }) } // ---------- web_fetch ---------- @@ -247,22 +268,11 @@ pub fn is_private_browser_url(url: &str) -> bool { public_only(&full).is_err() } -/// The host and port of a web address (the brackets off an IPv6 one). +/// The host and port of a web address as a browser reads it ([`parse_url`]; an IPv6 host without +/// brackets). fn host_port(url: &str) -> Option<(String, u16)> { - let (scheme, rest) = url.split_once("://")?; - let auth = rest.split(['/', '?', '#']).next()?.rsplit('@').next()?; - let default = if scheme.eq_ignore_ascii_case("https") { 443 } else { 80 }; - let (host, port) = match auth.strip_prefix('[') { - Some(v6) => { - let (h, after) = v6.split_once(']')?; - (h, after.strip_prefix(':').map(str::parse).transpose().ok()?.unwrap_or(default)) - } - None => match auth.rsplit_once(':') { - Some((h, p)) => (h, if p.is_empty() { default } else { p.parse().ok()? }), - None => (auth, default), - }, - }; - (!host.is_empty()).then(|| (host.to_string(), port)) + let p = parse_url(url).ok()?; + Some((host_text(&p)?, p.port_or_known_default()?)) } /// web_fetch runs with nothing asked, so it reads the public web only: a page (or a redirect) @@ -344,7 +354,8 @@ pub fn get_public_bytes(url: &str, limit: u64) -> Result<(String, u16, String, V Some(_) if hops >= MAX_REDIRECTS => return Err(format!("{url} 一直轉址,讀不到內容。")), Some(to) => { hops += 1; - url = to; + // (As parsed: the stop that is checked is the one asked for.) + url = normalize_url(&to)?; } None => break resp, } @@ -802,6 +813,34 @@ mod tests { assert!(normalize_url("").is_err()); } + /// Addresses are read the way a browser reads them (WHATWG): a backslash is a slash, `user@` + /// isn't the host, case, a trailing dot, punycode and an IP in any spelling don't change which + /// host it is — so the private-network card and the person's rules see the host that opens, + /// and the browser is handed that same address. (By hand, `http://127.0.0.1\@a.com/` and + /// `http://192.168.1.1\.example.com/` passed as public; `me@example.com` as host `me@example.com`.) + #[test] + fn addresses_are_read_as_a_browser_reads_them() { + for private in ["http://127.0.0.1\\@a.com/", "http://192.168.1.1\\.example.com/", "http://me@127.0.0.1/", "http://localhost./", "http://2130706433/", "http://0x7f.1/", "http://[::1]:8080/", "http://[::ffff:127.0.0.1]/", "HTTP://192.168.1.5/"] { + assert!(is_private_browser_url(private), "{private}"); + } + assert!(is_forbidden_browser_url(&normalize_url("http://169.254.169.254\\@a.com/latest").unwrap())); + assert!(is_forbidden_browser_url(&normalize_url("http://2852039166/").unwrap()), "169.254.169.254 written as one number"); + for (given, host) in [ + ("https://me@example.com/cart", "example.com"), + ("https://shop.EXAMPLE.com./cart", "shop.example.com"), + ("https://example.com\\cart", "example.com"), + ("https://bücher.example/", "xn--bcher-kva.example"), + ("example.com:8443/x", "example.com"), + ("http://[::1]:8080/", "::1"), + ("http://2130706433/", "127.0.0.1"), + ] { + assert_eq!(host_of(given).as_deref(), Some(host), "{given}"); + } + assert_eq!(normalize_url("http://127.0.0.1\\@a.com/").unwrap(), "http://127.0.0.1/@a.com/", "what is checked is what opens"); + assert_eq!(normalize_url("https://me@example.com\\cart").unwrap(), "https://me@example.com/cart"); + assert!(normalize_url("ftp://example.com/").is_err() && normalize_url("javascript:alert(1)").is_err() && normalize_url("intranet").is_err()); + } + #[test] fn front_browser_follows_window_order() { let json = r#"[{"owner":"Window Server","layer":24,"alpha":1,"w":1920,"h":30},