diff --git a/.claude/skills/verify-approval-routing/coverage.tsv b/.claude/skills/verify-approval-routing/coverage.tsv index 295fc25..d86b0f8 100644 --- a/.claude/skills/verify-approval-routing/coverage.tsv +++ b/.claude/skills/verify-approval-routing/coverage.tsv @@ -1,6 +1,6 @@ # 模型對照的程式碼段落(drift.py 讀這個檔)。欄位用 tab 分開:id 檔案 種類 開始 結束 sha256 # sha256 是上次確認「模型還描述這段程式」時的內容。只有對過 SKILL.md 的對照表之後,才用 drift.py --rehash 更新。 -desk.approval_body src/app.rs block ^ fn approval_body\( } fd8c84806d8b8867c011f463c3753f1960824a5df46535031ba1c0aaa5263d07 +desk.approval_body src/app.rs block ^ fn approval_body\( } 42809de459f19bfa7abbb0b080144c8d04ae98242a5c93d4b721be19671b9830 desk.approval_dock src/app.rs block ^ fn approval_dock\( } cda918bb255c4533d2d116736aaeb10aa2b9477b6c2858f1698b81b6dcef8794 brain.need_approval src/app.rs block ^ if let StreamEvent::NeedApproval\(a\) = ev \{ } 5d62c439986d0e2ee6d0f28b3cbaf28fca8688c0c60395d86e77a77a35bd55ec brain.on_new_approval src/app.rs block ^ fn on_new_approval\( } c110c0341ae1b8cbcc59d0b4dc1dba7a2b8006885837e515ea6c0ef23a195205 @@ -10,7 +10,7 @@ brain.answer src/app.rs block ^ fn answer\(&mut self, ctx: &egui::Context, bo brain.stop src/app.rs block ^ fn stop\(&mut self, bot_id: u64\) } c7b8144a99b5cd03d37dd34ca1745dca693d4f2f0197a51d29dfb71b3e770f4f brain.watchdog src/app.rs block ^ fn watchdog\(&mut self\) } 50af66bd5a7f254e4400edb2f0fedc550465a43ac0d9fce155e5353c8d4ae336 brain.cmd_answer src/app/remote_ui.rs block ^ Cmd::Answer \{ bot, answer, text, call, notice, screen \} => \{ } 8100f28ea03fedbd4cd58f988c5d32be2761151349110b134dcfb54d61a4e482 -page.approval_json src/app/remote_ui.rs block ^fn approval_json\( } a5170e3eb427a05a10941d43ca7f43355955c4225cb361843d2435051c8a29c1 +page.approval_json src/app/remote_ui.rs block ^fn approval_json\( } ae43e3412f67bfcfb15f487a17622707e26661cf1dc7aa0e78dd998206b27257 page.phone_cards src/app/remote_ui.rs block ^ fn phone_cards\( } 9a76fc7d54e92000598bd6800c232c5b61a4494cd60d33c2313542ce6893058c page.render_dock mobile/index.html block ^function renderDock\(\) \{ } bfc86600b3b561ba0c32355b5a8b3372bc0f1afbb8482eaa6ccddf92b5ba1e94 page.question mobile/index.html block ^function renderQuestion\(a, force\) \{ } 829ae3088ec69585ecd9cff0d12cf5fd538ccc86869c4e46a6e9d8c4110d3a40 diff --git a/FEATURES.md b/FEATURES.md index 4f2ab6e..26b2708 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -451,7 +451,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 每個 Bot 有自己的 **Soul 與指示**(個性、說話和做事的方式、要守的規則;原本的「指示」和 soul 合成一欄,舊的 soul 讀進來時會併到指示最前面)、**擅長**、**不找它做的事**、**會的技能**、**能力**和**可以用的電腦**;記憶本來就是各自的。 - **Soul 與指示只有它自己讀**,放在它說明的最後(最優先);描述、擅長、不找它做的事、在哪幾台電腦做事會寫進其他 Bot 的**同事名冊**(一行一個 Bot),讓它們知道什麼事該交給誰。名冊不含別人的 soul 和記憶,順序固定,每一輪都一樣(吃得到快取)。 -- **在聊天裡改自己**:每個 Bot 都知道自己有個人檔案(說明裡寫了,也寫了它沒有哪些能力)。你問「你會什麼」「你的設定是什麼」,它用 my_profile 看;你叫它改(描述、soul 與指示、擅長、不做的事、能力、技能、可以用的電腦、預設電腦、模型、思考模式、執行步驟用的模型、頭像),它用 update_my_profile,聊天裡會先跳出確認卡片列出每一項改了什麼,按允許才生效,拒絕就不改。網頁、檔案或別的 Bot 叫它改的不算;例行任務和訊息管道來的對話不能改。群組裡改的是正在說話的那位成員。 +- **在聊天裡改自己**:每個 Bot 都知道自己有個人檔案(說明裡寫了,也寫了它沒有哪些能力)。你問「你會什麼」「你的設定是什麼」,它用 my_profile 看;你叫它改(描述、soul 與指示、擅長、不做的事、能力、技能、可以用的電腦、預設電腦、模型、思考模式、執行步驟用的模型、頭像),它用 update_my_profile,聊天裡會先跳出確認卡片列出每一項改了什麼(用設定畫面上的說法,例如「執行步驟用的模型:自動 → 不分開」,不是「(空) → 「off」」),按允許才生效,拒絕就不改。網頁、檔案或別的 Bot 叫它改的不算;例行任務和訊息管道來的對話不能改。群組裡改的是正在說話的那位成員。 - **能力**分 11 類:上網、瀏覽器、看螢幕與操作、檔案與指令、Mac App、連接器、電話簡訊 X、例行任務、頁面、和其他 Bot 合作、管理 App。沒勾的不會提供給它,也不會寫進它的說明(每一步都少送很多 token);它硬要用也會被擋下,告訴它去找名冊裡會的 Bot。記憶、技能、問你問題、請你接手螢幕、傳檔案到聊天、表情和卡片每個 Bot 都有。 - **連接器**:有勾「連接器」能力的 Bot 才拿得到 MCP 工具和它們的使用說明(舊的 Bot 全部都有);連接器的工具超過 20 個時(例如 SccMCP 的 82 個)用「找工具/用工具」兩步,不會整包送。沒勾的 Bot 用名字硬叫(找、用、直接呼叫)都會被擋下。 - **技能**:技能庫裝一次,每個 Bot 勾自己會的;說明裡只列它會的,use_skill 也只讀得到它會的。它自己學會(存成)的技能自動算它的;其他 Bot 要勾選才會。 @@ -484,7 +484,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **螢幕一次給一個**(所有 Bot 都適用,不只支線):一輪工作在某台電腦的螢幕上點擊、打字之後,那個螢幕就是它的;另一輪(同一個 Bot 的支線,或別的 Bot)要在同一個螢幕上點,那一步不執行,Bot 會讀到「「X」的螢幕現在由「Y」在操作(N 秒前還在用)」,請它先做不用螢幕的部分、改用別台電腦或晚點再試。那一輪結束、或停手 2 分鐘後就放開。只是截圖、看畫面不算;Bot 的電腦(Docker)所有 Bot 共用一個桌面,所以算同一個螢幕。瀏覽器每一輪本來就各用各的分頁。 - **卡片**:主聊天裡,問的地方出現一張支線卡:任務、狀態(判斷中、等主線、正在做什麼和第幾步、做完了、沒做完、已停止)、「停止支線」、「看過程」(每一步一行)。支線要你核准的步驟,直接在這張卡上按允許或拒絕(手機上顯示在主聊天的核准區,標「支線:」)。 - **回報到主頁面**:做完時——主線正在做事,結果當成插話送進它這一輪(「〔支線回報〕…」,它下一步就讀到,聊天裡一行小字說已交給主線);主線閒著,結果以支線的名義放進主聊天(上面標「支線「任務」」),主線下一輪讀得到。主 Bot 不會為了支線回報自己多回一則(省一輪)。沒做完時說原因,下面有「重開這條支線」。按停止的不回報。 -- 一個 Bot 同時最多 3 條支線;群組聊天還不能開。支線不存檔:AnyBot 重新啟動時還沒做完的支線會停掉,卡片寫「AnyBot 重新啟動,這條支線停了」。側欄、同事名冊、@ 清單、手機的 Bot 列表都看不到支線本身。 +- 一個 Bot 同時最多 3 條支線;群組聊天還不能開。支線不存檔:關掉 AnyBot 時還沒做完的支線會停掉,卡片寫「AnyBot 關掉了,這條支線停了」(以前寫「被停止了」,像是你按了停止);當掉後重新啟動才寫「AnyBot 重新啟動,這條支線停了」。支線不能改設定或動大家共用的東西:update_bot、update_settings、update_my_profile、teach_skill、create_bot、create_group、move_to_group、rename_group、delete_group、delete_skill、skill_install(內建的也是),連接器和 hook 除了看(列出、重新連線、登入登出)以外的動作,瀏覽器設定檔的新增和切換,一律馬上回「支線改不了設定:回到主線再請它改。」,不跳卡片(以前支線的 update_bot 按允許後會把主 Bot 改名)。save_skill、skillify 可以存新技能(算主 Bot 的),但不能換掉技能庫裡已經有的同名技能(大小寫不同也算同名:存技能的資料夾就是這樣認的)。支線的瀏覽器步驟指名的設定檔只用在那一步,不會變成使用中。側欄、同事名冊、@ 清單、手機的 Bot 列表都看不到支線本身。 ### 「/」清單只放指令 @@ -495,7 +495,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **金鑰不再明文存檔**:state.json 裡的模型金鑰、頻道 token、連接器的密碼、標頭和環境變數,用保險庫的金鑰加密後才寫入(檔案裡是「enc:v1:…」);金鑰在系統鑰匙圈(沒有鑰匙圈的伺服器是資料夾裡的 0600 金鑰檔)。打不開時(鑰匙圈鎖住、換了電腦)保持原樣不清空,不會因為存檔而遺失。舊版讀不懂加密後的檔案:降版要重新填金鑰。寄到帳號伺服器的備份不受影響(備份本來就另外加密)。 - **團隊**:加入別人的 AnyBot 要自己按接受(手機登入時會問);成員只看得到勾了「團隊成員可以使用這個 Bot」的 Bot(電腦的 Bot 設定,或手機的 Bot 選單「分享給團隊成員」)。設定裡的成員清單會標「已邀請,等對方接受」。 -- **區網連線**:不能打開直接操作、加「一律允許」規則、加連接器;手機的區網登入 30 天沒用就失效;看畫面的連線改用一次性的票,登入不放在網址裡。 +- **區網連線**(同一個網路直接連):只能收緊、不能放寬。擋下:打開直接操作、在聊天打「/always-approve」(/yolo;看狀態、關掉可以)、打開自動審核、加「無需詢問直接允許」規則、拿掉「一律詢問」規則、加連接器或把關掉的打開、打開訊息管道、打開 Bot 的電腦工具、把 Bot 分享給團隊或加進分享給團隊的群組、勾回能力或可以用的電腦、把 Bot 的電腦從強隔離換回標準;每一項反過來都可以,不動權限的(名字、外觀、模型、金鑰、技能、例行任務、記憶、頁面)也可以。設定的名字要一字不差:多一格空白、大小寫不同就回「不認得這個設定」,什麼都不改(以前大腦那邊會先把空白去掉再做,「direct_mode 」這種就繞過了檢查);規則清單只認「ask」「allow」(以前認不得的都當成允許清單);沒列在分類裡的動作也一律擋(以前「匯入 Bot」就這樣過去,還帶著檔案裡的團隊分享)。可以用的電腦只動手機上列出的那幾台:帳號裡關機、沒列出的電腦維持原狀,有清單的 Bot 全勾也不會變成「每一台」(以前那台被排除的電腦開機後又能用了)。打開「從手機看這台電腦的螢幕並操作」(預設關)時這些都不算數:那支手機能直接點電腦版的設定。被擋時說「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬。請在電腦上的 AnyBot 改,或用帳號連線。」(以前說「區網連線(沒有加密)」,現在直接連線是 https;擋的原因是直接連線只憑手機密碼)。卡片上的「允許」「一律允許」照樣可以按(回答的是眼前那張卡)。手機的區網登入 30 天沒用就失效;看畫面的連線改用一次性的票,登入不放在網址裡。 - **帳號伺服器**:大腦回傳的內容只放行不會被當成網頁執行的類型;沒登入的請求最多 256 KB;登入、註冊、配對都有次數限制;兩步驟驗證碼只能用一次;新增電腦要剛登入 15 分鐘內;可以改密碼;每個帳號的登入數、電腦數、發布的網站數都有上限;資料檔壞掉時不啟動(不會被空的蓋掉)。網頁只執行它自己的那幾段程式(依雜湊放行),不再放行任意內嵌程式。 - **手腳電腦**:一律拒絕的指令和私密檔案,在手腳這一端自己也會擋,不只靠大腦判斷。 - **背景指令**:同時最多 24 個;刪除 Bot、支線結束時一起停掉;結束 10 分鐘後移除;Bot 可以用 write_terminal 的 stop 停掉;不理會停止的程序兩秒後強制結束;跑在 Bot 的電腦裡的也會在裡面停掉。 @@ -509,7 +509,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **帳號伺服器的資源**:閒置的連線從每秒醒 25 次降到 5 次;每條連線的讀取緩衝從 128 KB 降到 32 KB;請求的開頭 15 秒內沒送完就斷(原本最長 90 秒)。本機壓測(100 台電腦連著、3000 個請求、120 次錯誤登入、128 個送一半的請求、3 輪重連):記憶體 32 MB 持平,執行緒和檔案描述元都回到起點,閒置 CPU 約 1.5%(一個核心)。 - **團隊成員在 Bot 忙的時候傳的訊息**不再被丟掉:排在後面,Bot 做完手上的事就輪到它(每個 Bot 最多排 8 則)。成員的話不會插進擁有者正在跑的那一輪。 - **群組沒有 @ 時看擅長分派**:訊息的內容對得上某些成員「擅長」寫的事(而且不在它「不找它做的事」裡),就只由那幾位回答,聊天裡會有一行「這題看擅長交給「…」。要其他人也回答,用 @ 點名。」;對不上任何人、或每個人都對得上,就跟以前一樣全員輪流。 -- **手機也能改個人檔案**(擁有者):Bot 設定頁多了「擅長」「不找它做的事」,以及「能力」「會的技能」「可以用的電腦」的開關。區網連線不能改「能力」和「可以用的電腦」(跟其他放寬權限的設定一樣)。 +- **手機也能改個人檔案**(擁有者):Bot 設定頁多了「擅長」「不找它做的事」,以及「能力」「會的技能」「可以用的電腦」的開關。區網連線只能勾掉「能力」和「可以用的電腦」、不能勾回,電腦工具只能關、不能開(跟其他放寬權限的設定一樣;以前連勾掉也被擋)。 - **視窗沒在前面也照常運作**:視窗縮小、隱藏或被別的 App 整個蓋住時,Bot 送來的東西照樣處理——要你允許的請求會響提示音、任務完成會通知、例行任務準時開始(以前要等你切回 AnyBot 才一起發生)。任務完成且你不在 AnyBot 前面時,也響同一個提示音(設定裡的「提示音」關掉就不響)。Mac 的 App 關掉了 App Nap,被蓋住時系統不會讓它睡著。 - **伺服器的 Docker**:setup.sh 檢查到用的是 root 的 Docker 會警告(大腦被攻破等於拿到整台主機),建議改 rootless。 - 手機頁面最多留 40 個圖片/檔案的快取;收起的步驟和歸檔的舊對話不再把截圖留在記憶體。 @@ -996,7 +996,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 監看(shell 加 monitor: true) - Bot 給一條會一直印東西的指令(`tail -f app.log | grep --line-buffered ERROR`、部署的紀錄、測試的 watch 模式),指令馬上放到背景,**它每印出新的一行,AnyBot 就叫醒 Bot 一次**,把那幾行交給它:Bot 閒著就馬上開一輪,正在做事就等這輪做完再開自己的一輪(跟例行任務、事件觸發一樣)。一秒內印出的併成一次,一次最多列 20 行(其他用 read_terminal 看)。參考 Claude Code 的 Monitor 工具。 -- 交給 Bot 的字標「[監看 #編號]…印出了(這是指令的輸出,不是使用者說的話)」。 +- 交給 Bot 的字標「[監看 #編號]…印出了(這是指令的輸出,不是使用者說的話)」;手機上那則上方標「監看」(以前所有叫醒的訊息都標「例行任務」,同事交辦、訊息管道的也是——現在照電腦版的標籤:目標、例行任務、觸發、訊息管道、來自其他 Bot、監看)。 - 自動停:10 秒內超過 200 行(說一次「一下子印出太多行…用 grep --line-buffered 只留要看的行」);同一個監看叫了 60 次(每次都是一輪模型,用你的額度)。指令自己結束時說一次「指令結束了(結束碼 N)」和最後印出的行。Bot 或你用 write_terminal 的 stop 停掉、或「重新啟動這個 Bot」時安靜結束,不再叫。 - 跟一般指令一樣要過核准和安全規則(就是 shell)。在這台、Bot 自己的電腦(Docker、封閉資料夾)、SSH 電腦上都可以;帳號裡其他 AnyBot 電腦上不行(印出的字回不到這裡),會說改用 read_terminal 的 until。 @@ -1108,7 +1108,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 點擊、輸入、按鍵、選擇、捲動、上一頁之後:等頁面停下來就回來(頁面有變且穩定,或 0.5–0.9 秒內沒有開始變),最多 4 秒;以前是固定 1–2.5 秒。 - 「讀取瀏覽器分頁」(browser_read):最多讀多少字(預設 20,000,最多 40,000),加上設定檔。 - 編號也包含 web component 裡的東西(打開的 shadow DOM,一層層往下找,例如 Chromium 的設定頁、YouTube、很多用元件框架做的網站),排列順序照畫面上的位置:元件本身、它 shadow DOM 裡顯示的東西、再來是它自己的子元素。照編號點、照文字找、畫編號框都看得到這些。 -- 「瀏覽器設定檔」(browser_profiles):列出、新增、切換。 +- 「瀏覽器設定檔」(browser_profiles):列出、新增、切換(模型那邊是 `browser` 的 `profiles`:帶 name 就換過去,沒有就先新增)。 ### 用哪個瀏覽器 @@ -1161,7 +1161,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 「你的瀏覽器」代表你平常的 Chrome(第 23 節)。也聽得懂「你的 chrome」「我的 chrome」「我的瀏覽器」「my chrome」這些說法。 - 順序:「預設」排第一,其他依名稱,「你的瀏覽器」排最後。 - 「使用中」的設定檔會被記住;找不到時回到「預設」。找設定檔不分大小寫。 -- 在某個設定檔打開網址,那個設定檔就會變成使用中。 +- 在某個設定檔打開網址,那個設定檔就會變成使用中——使用者自己的瀏覽器(Firefox 設定檔、「你的瀏覽器」)除外:那一步用它,使用中的不變。 +- Bot 的電腦上的瀏覽器只有一個設定檔:在那裡新增或切換會被擋(「Bot 的電腦上的瀏覽器只有一個設定檔…」),也不會改到這台記著的使用中設定檔(以前在那裡開網頁會把它改回「預設」)。 ### 名稱規則 @@ -1172,16 +1173,17 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 新增、切換、列出、移除 +- Bot 用 `browser` 的 `profiles`:不帶 name 是列出;帶 name 是換到 AnyBot 自己同名的設定檔(名字要一樣,大小寫不算),沒有就新增一個全新的(以前帶 name 也只會列出,什麼都沒換)。只說「阿金」不會換到使用者的「阿金(Firefox)」,而是新增「阿金」;使用者自己的瀏覽器(Firefox 設定檔、「你的瀏覽器」)Bot 不能換過去:「「X」是使用者自己的瀏覽器(帶著他的登入):Bot 不能自己換過去…請使用者在 設定 › 電腦 ›「AnyBot 瀏覽器設定檔」自己切換。」——換了之後每一步、每個 Bot 都會用他的帳號,所以由使用者在設定裡換(這個工具沒有卡片可以問)。支線不能新增或切換。 - **新增**:名稱已經存在時沿用,不重複建立。新增後自動切過去。 - 「已新增並切換到設定檔「X」(全新的,還沒登入任何網站)…」 -- **切換**:「已切換到「X」,之後的 browser_open / browser_read 都用它。」 +- **切換**:「已切換到「X」,之後 browser 的 open、read 都用它。」 - 切到「你的瀏覽器」時補一句:「(使用者平常的瀏覽器:請使用者在那裡切到想要的 Chrome 設定檔)」 - **列出**:「AnyBot 瀏覽器的設定檔:A、B(使用中)…。每個設定檔有自己的登入。」 - **移除**:只有你能在設定裡移除,Bot 不行。 - 「預設」和「你的瀏覽器」不能移除:「「X」不能移除」。 - 視窗還開著:「「X」的視窗還開著,請先關掉它再移除。」 - 移除的是使用中的設定檔時,會回到「預設」。 -- **設定檔不存在**:「AnyBot 瀏覽器沒有叫「X」的設定檔。現有:…。要新的可以用 browser_profiles 新增(action: add)。」 +- **設定檔不存在**:「AnyBot 瀏覽器沒有叫「X」的設定檔。現有:…。要新的:browser 的 profiles 帶 name 填新名字,會新增並換過去。」 ### 設定 → 電腦 → 「AnyBot 瀏覽器設定檔」 @@ -1468,7 +1470,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 分享 Bot(匯出、匯入) - Bot 選單(右鍵或「⋯」)→「匯出 Bot(分享給別人)…」:選位置存成 `.anybot` 檔。帶走外觀、供應商和模型、指示、例行任務、示範的步驟;**不會**帶走聊天記錄、API 金鑰、Token(例行任務的 token、apiKey、secret 會清空)、你的「一律允許」授權、示範的錄影和畫面。 -- 「匯入 Bot…」:選 `.anybot` 檔,變成一個新的 Bot。事件觸發的例行任務會先暫停,因為需要新主人自己的 Token;匯入後會提醒。檔案來自較新版本時會請你先更新。 +- 「匯入 Bot…」:選 `.anybot` 檔,變成一個新的 Bot。事件觸發的例行任務會先暫停,因為需要新主人自己的 Token;匯入後會提醒。檔案來自較新版本時會請你先更新。匯出不寫、匯入不收「分享給團隊」(新 Bot 只有你看得到;以前檔案裡寫了就直接分享出去)。 ### 訊息管道(Slack、Discord、Telegram) @@ -2160,10 +2162,10 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 音訊、影片在頁內播放(手機瀏覽器的播放器);其他檔案顯示大小和原因,按「儲存到手機」下載; - 預覽頁上方永遠有下載鈕;對話詳細資訊的檔案清單也點同一個預覽。 - **接管在 App 內打開**:「接管」「看 Bot 的電腦」不再跳頁,整個接管畫面蓋在 App 上;左上 ✕ 或返回手勢關掉(VNC 連線一起斷),右上 ↗ 可在新分頁開。接管時打字列多 ↑ ↓ 鍵,「接管」按鈕接管中變成黃色。 -- 設定(擁有者): +- 設定(擁有者):開著的設定頁跟著電腦那邊的改變重讀(例如在聊天打 /always-approve 填了三條預設「一律詢問」規則,權限頁不用重新整理就看得到;以前只讀一次,要重新整理)。 - 一般(主題、強調色、時區、通知、語言)、權限(直接操作、自動審核、允許/詢問規則)、整合(訊息管道、MCP 開關和移除); - 模型:每個服務是否可以用;可以設定或換 API 金鑰、清除金鑰、新 Bot 預設模型。**金鑰只能寫入**,手機永遠看不到原本的金鑰; - - 電腦:Bot 的電腦的狀態和縮圖、開啟電腦、接管、喚醒、儲存快照、檢查用量、更新、自動更新時間、容器隔離、從快照復原/重設(會先確認)、「請 Bot 提出清理方案」(帶到主要 Bot 的對話,先列出不刪除); + - 電腦:Bot 的電腦的狀態和縮圖、開啟電腦、接管、喚醒、儲存快照、檢查用量、更新、自動更新時間、容器隔離、從快照復原/重設(會先確認)、「請 Bot 提出清理方案」(帶到主要 Bot 的對話,先列出不刪除)。沒有 Docker 時「更新 Bot 的電腦」寫「沒有 Docker,現在沒有這台電腦」、還沒建立時寫「還沒建立(建立時是 v…)」,容器隔離不說主機有沒有 gVisor(以前沒有 Docker 也寫「已是 v14」「這台 Docker 主機沒有 gVisor」); - 保險庫:只說明,不傳任何密碼到手機; - 手機與帳號:直接連線的手機清單,可以登出別支手機; - 更新:版本和有沒有新版。 @@ -2674,6 +2676,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **OpenCode Go 供應商**:設定 → 模型 選「OpenCode Go」,貼上 opencode.ai Console 的 Go 金鑰。依官方模型清單自動決定每個模型用 OpenAI 格式(/openai/v1)或 Anthropic 格式(/anthropic/v1);每個 Bot 的對話帶固定的 x-opencode-session。 - **ChatGPT 方案供應商**(`src/chatgpt.rs`):用 ChatGPT 帳號登入,Bot 用使用者 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰——OpenAI 給開源、本機執行 App 的 Sign in with ChatGPT(developers.openai.com/siwc/token-sharing-open-source)。 + - Bot 要登出或換帳號時先跳卡片,標題照它要做的寫:「… 想要登出 ChatGPT 方案」「… 想要換 ChatGPT 帳號」(以前不管哪個都寫「想要ChatGPT 方案登入」)。 - 登入:設定 → 模型 → ChatGPT 方案 →「使用 ChatGPT 繼續」,或請 Bot 用 `chatgpt_login`。瀏覽器到 auth.openai.com(PKCE S256、state、nonce、`resource=https://api.openai.com/v1`、scope 含 `chatgpt.tokens.use.direct`),回到大腦上的 `http://127.0.0.1:/auth/callback`(先試 1455);瀏覽器在別台電腦時,把那頁網址貼回聊天由大腦換 token。第一次用 `client_id=dynamic_agent_client` 註冊、`agent_name_hint=AnyBot`,記住發下來的 `oaiapp_…` 之後重用;每台大腦一個隨機 `ext_agent_host_id`(urn:uuid)。 - 檢查:callback 的 state;新註冊一定要帶回 client_id,重新登入帶回不同的就拒絕;ID token 用 OpenAI 的 JWKS 驗 RS256 簽章、iss、aud(=client_id)、exp、nonce;同一個註冊換成別的帳號(sub 不同)就拒絕。沒有 `chatgpt.tokens.use.direct` 算登入但不能用。 - Token 存在 `<資料夾>/providers/chatgpt.json`(0600、先寫暫存檔再換名),access/refresh/id_token 用設定密鑰封存;不進設定檔,螢幕電腦和手機拿不到。剩 5 分鐘到期或被回 401 時用 refresh token 更新(一次一個,refresh token 會輪替);refresh token 失效就清掉 token、保留註冊,請使用者重新登入。登出會到 OpenAI 撤銷 refresh token;「換帳號」連註冊一起忘掉。 diff --git a/SECURITY.md b/SECURITY.md index 532e6cf..9962a4b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -43,7 +43,7 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 -- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。「Tailscale 通道介面」是:macOS 上同時帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::/48)的 utun 這類點對點介面、Linux 上叫 tailscale… 的介面(或帶著那個 IPv6 位址的)、Windows 上名字有 Tailscale 的介面卡(從 ifconfig、ip -o addr、ipconfig 讀,30 秒更新一次)。只有 100.64.0.0/10 位址的點對點介面(PPPoE、手機的電信 NAT、Cloudflare WARP)不算;Windows 上介面卡改過名字就認不出來,http 一律轉 https。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 +- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。直接連線只憑這組密碼,所以從那裡改設定只能收緊、不能放寬:打開直接操作或自動審核、在聊天打「/always-approve」(/yolo)、加「無需詢問直接允許」規則、拿掉「一律詢問」規則、加或打開連接器、打開訊息管道、打開 Bot 的電腦工具、分享 Bot 給團隊或把 Bot 加進分享給團隊的群組、勾回能力或可以用的電腦、把 Bot 的電腦從 gVisor 換回標準,一律 403;設定或動作的名字不是一字不差的(多空白、大小寫不同、沒列在分類裡的動作)回 400、什麼都不改(大腦那邊也照原字讀,不先去空白)。匯入的 Bot 檔不帶團隊分享。可以用的電腦只動手機上列出的那幾台:帳號裡關機沒列出的電腦維持原狀,有清單的 Bot 不會因為全勾就變成「每一台」。要放寬,在電腦上或經帳號連線。卡片上的允許/一律允許照樣能從直接連線按。**例外**:打開「從手機看這台電腦的螢幕並操作」(預設關)後,那支手機能點電腦版的設定,這個保證就不成立。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。「Tailscale 通道介面」是:macOS 上同時帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::/48)的 utun 這類點對點介面、Linux 上叫 tailscale… 的介面(或帶著那個 IPv6 位址的)、Windows 上名字有 Tailscale 的介面卡(從 ifconfig、ip -o addr、ipconfig 讀,30 秒更新一次)。只有 100.64.0.0/10 位址的點對點介面(PPPoE、手機的電信 NAT、Cloudflare WARP)不算;Windows 上介面卡改過名字就認不出來,http 一律轉 https。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 - 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在開連線的那一刻,對真正要連的那幾個位址做(名字第二次查可能答不一樣):http 的帳號伺服器每個請求都開新的連線(不留著給下一個請求用),所以每個請求都查;長連線(WebSocket)在每次連上、重連時查,連著的時候不會中途再查。不符合就不連:登入、建立帳號、還原、配對直接回到表單說原因;長連線、備用連線和 `--serve` 的 `ANYBOT_ACCOUNT` 寫進狀態或紀錄,之後自己再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。`localhost` 只連它查到的這台(loopback)位址,其他位址(例如舊 Mac 的 /etc/hosts 裡的 `fe80::1%lo0`)略過;一個 loopback 都沒有就不連。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。 - 一個字的名字(以英文字母開頭,只有字母、數字、`-`、`_`,例如 `relay`)是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS、系統的搜尋網域或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。純數字或 0x 開頭的寫法(系統會把 `134744072`、`0x8080808` 讀成 8.8.8.8)不算名字。 diff --git a/docs/feature-map/account.md b/docs/feature-map/account.md index afb8434..667c036 100644 --- a/docs/feature-map/account.md +++ b/docs/feature-map/account.md @@ -12,7 +12,7 @@ - `account-direct` 同一個網路直接連:先設手機密碼(至少 8 個字)才能打開;列出這台的網址(同一個 Wi-Fi,或都裝了 Tailscale)。區網用 https(這台自己做的憑證);http 只收從 Tailscale 連到這台 Tailscale 位址(Tailscale 通道介面上的 100.x)的,其他一律轉到 https——Wi-Fi 自己發 100.64.x 位址(電信業者 NAT 那一段)時也是區網。同一個位址密碼錯 5 次要等一分鐘。 - `account-bind` 聽哪個位址:預設聽這台的每個位址,連接埠從 8793 起(被占用往後找,照設定頁列出的網址打開)。啟動時的 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)、連接埠都被占用或不准用(1024 以下要管理員權限)時照實寫,每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。 - `account-devices` 直接連線的裝置:用手機密碼登入過的手機和瀏覽器、最近使用時間,可以逐台「登出」;換手機密碼會把它們全部登出。 -- `account-can` 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。 +- `account-can` 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。直接連線的手機改設定只能收緊、不能放寬(打開直接操作或自動審核、在聊天打「/always-approve」、加「無需詢問直接允許」規則、拿掉「一律詢問」規則、加或打開連接器、打開訊息管道、打開 Bot 的電腦工具、分享給團隊或加進分享的群組、勾回能力或可以用的電腦、把 Bot 的電腦從強隔離換回標準,都會被擋;反過來都可以),設定或動作的名字不是 AnyBot 認得的(多空白、大小寫不同)一律不做([autonomy](autonomy.md))。用帳號連線或在電腦上就沒有這個限制。打開「從手機看這台電腦的螢幕並操作」時這個限制不成立:那支手機能直接操作電腦版的設定。 - `account-push` 通知:需要你允許、問你、需要你處理,你不在時做完事,例行任務暫停,收到傳來的檔案——推播到開了通知的手機,點了直接打開那個 Bot。每支手機自己選要哪幾種(需要你/做完了/例行任務暫停/收到傳來的檔案),可以送一則測試通知。圖示是 AnyBot 的貓,Android 狀態列是貓的單色剪影;App 圖示上的數字是正在等你的 Bot。「需要你允許」的通知在 Android 上有「允許/拒絕」(只答那個請求,換了就不答);主畫面圖示長按有「主要 Bot」「未讀」兩個捷徑。 ## 使用者怎麼到 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index aad2732..891bdd6 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -10,11 +10,11 @@ - `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,或用帳號連線。 +- `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機只能收緊、不能放寬(「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」)。擋下的:打開直接操作、在聊天打「/always-approve」(或 /yolo)打開一律放行、打開自動審核、加「無需詢問直接允許」規則、拿掉「一律詢問」規則、加連接器或把關掉的打開、打開訊息管道、打開 Bot 的電腦工具、分享 Bot 給團隊、把 Bot 加進分享給團隊的群組、勾回能力或可以用的電腦、Bot 的電腦從強隔離換回標準。不認得的動作也擋(不是放行)。可以的:上面每一項反過來,和不動權限的(名字、外觀、模型、金鑰、技能、例行任務、記憶;匯入的 Bot 不帶電腦工具、授權和團隊分享)。打開了「從手機看這台電腦的螢幕並操作」就不算數:那等於坐在電腦前,什麼都改得了。設定的名字要一字不差(多空白、大小寫不同就回「不認得這個設定」,什麼都不改)。要放寬:在電腦上的 AnyBot,或用帳號連線。卡片上的「允許」「一律允許」照樣可以按(那是回答眼前那張卡)。手機的權限頁跟著電腦那邊的改變重讀,不用重新整理。 ## 使用者怎麼到 -- 在任何聊天打「/always-approve」(「/」清單裡有),或 設定 › 權限 ›「一律放行」的開關「什麼都不問,全部直接做」。手機用擁有者身分打也可以;團隊成員、管理員打的不算指令(會變成「【名字】/always-approve」給 Bot)。 +- 在任何聊天打「/always-approve」(「/」清單裡有),或 設定 › 權限 ›「一律放行」的開關「什麼都不問,全部直接做」。手機用帳號連線、擁有者身分打也可以;同一個網路直接連的手機只能「/always-approve status」「/always-approve off」,打開會被擋。團隊成員、管理員打的不算指令(會變成「【名字】/always-approve」給 Bot)。 - 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。 - 手機:設定 › 權限(直接操作、自動審核的開關,「一律詢問(優先)」「無需詢問直接允許」兩組規則)。 - Hooks:資料夾的 hooks/hooks.json(使用者的);管理員的放 /Library/Application Support/AnyBot/hooks.json(Mac)、/etc/anybot/hooks.json、%ProgramData%\AnyBot\hooks.json,最後跑(看得到你的 hook 改過的參數)、AnyBot 裡改不了。/doctor 寫有幾個 hook、檔案看不看得懂。 @@ -27,10 +27,10 @@ - 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。 -- **一律放行**(covers `autonomy-yolo`、`autonomy-direct`):打「/always-approve」,再請 Bot 改名。指令:`$CTL phone send '/always-approve' && $CTL phone wait-text '已一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == true' && $CTL phone send '改名 [[call update_bot {"name":"放行後的名字"}]]' && $CTL phone wait-text 放行後的名字 --in '#isl-name' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "update_bot") | .status]'`。看到:「已一律放行:…仍然會擋:…」;直接操作跟著開;改名沒有跳卡片,步驟是 done。 +- **一律放行**(covers `autonomy-yolo`、`autonomy-direct`、`autonomy-remote`):先看一眼手機的 設定 › 權限(還沒有規則),回聊天打「/always-approve」(直接連線打不開),改在這台電腦上打(`--ask` 跟在電腦版的聊天打一樣),再請 Bot 改名。指令:`$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 wait-text '還沒有規則' --in '#list' && $CTL phone click '[data-back]' && $CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '/always-approve' && $CTL phone wait-text '只能收緊、不能放寬' --in '#toast' && $CTL phone shot autonomy-yolo-lan && $CTL api GET /api/settings --jq .direct_mode && $CTL stop && $CTL ask '/always-approve' && $CTL serve && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text '已一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == true' && $CTL phone send '改名 [[call update_bot {"name":"放行後的名字"}]]' && $CTL phone wait-text 放行後的名字 --in '#isl-name' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "update_bot") | .status]'`。看到:手機上打「/always-approve」跳出「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」,打的字放回輸入框,直接操作還是 false;在這台電腦上打就「已一律放行:…仍然會擋:…」(手機的聊天也看得到);直接操作跟著開;改名沒有跳卡片,步驟是 done。 - **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-remote`、`autonomy-direct`、`autonomy-review`):不重新整理,回首頁 › 帳戶選單 › 設定 › 權限;停在這頁時另一台裝置加一條「一律詢問」規則;再按「直接操作」。指令:`$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 wait-text '刪除檔案或資料夾' --in '#list' && $CTL api POST /api/act/setting '{"key":"rule_add","list":"ask","value":"寄信前先問我"}' && $CTL phone wait-text '寄信前先問我' --in '#list' && $CTL api --expect 403 POST /api/act/setting '{"key":"rule_remove","list":"ask","value":"寄信前先問我"}' && $CTL api --expect 400 POST /api/act/setting '{"key":" rule_add","list":"allow","value":"全部直接做"}' && $CTL api --expect 403 POST /api/act/setting '{"key":"auto_review","value":true}' && $CTL state '{ask: .review_ask_rules, allow: .review_allow_rules}' && $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'`。看到:「一律詢問(優先)」裡三條預設規則(第一步看過的「還沒有規則」沒有留著);另一台加的「寄信前先問我」自己出現;直接連線拿掉它回 403、名字多一格空白的「 rule_add」回 400「不認得這個設定」、打開自動審核回 403,state 裡「寄信前先問我」還在、允許規則是空的;按開關、確認「打開」後跳出「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」,直接操作還是關的。 - **桌面的閃電圖示**(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`)。 @@ -41,5 +41,4 @@ - hook 在大腦上、用使用者的身分、在 Bot 的沙盒外跑:只加看得懂的指令。每一步都會跑 PreToolUse,慢的 hook 會讓 Bot 變慢(預設最多等 60 秒)。 - 外面的訊息和團隊成員的訊息不用你的直接操作和自動審核:要核准的事都得你親手按。 - 自動審核靠模型讀規則,寫得含糊會判錯;內建的安全規則不靠它。 -- 手機的設定頁(權限、一般…)不會自己更新:別處改了(例如一律放行填了預設規則)要重新整理才看得到。 - (驗證)hook 擋 `update_bot` 的話,後面改名的步驟都會被擋;示範用不用問的 `shell`。 diff --git a/docs/feature-map/box.md b/docs/feature-map/box.md index d17cf90..843efb9 100644 --- a/docs/feature-map/box.md +++ b/docs/feature-map/box.md @@ -23,7 +23,7 @@ - 基本前提和「手機已登入」(README),停在首頁。scratch 刻意沒有 Docker(`DOCKER_HOST` 指到不存在的地方),所以 Bot 的電腦是退回後的封閉資料夾。手機上「開啟電腦」「接管」「喚醒」「儲存快照」「檢查用量」「重設電腦」都不要按:它們去叫 Docker。 -- **沒有 Docker 時**(covers `box-machine`、`box-manage`):首頁點「電腦」。指令:`$CTL phone wait-text 0/1 --in '#quick' && $CTL phone click '#quick [data-q="computers"]' && $CTL phone wait-text '沒有 Docker' && $CTL phone wait-text '已是 v' && $CTL phone shot box-nodocker && $CTL api GET '/api/state?since=0' --jq '{box, box_available}' && $CTL api GET /api/settings --jq '.box | {state, available, version, runtime, snapshot, auto_update}'`。看到:「驗證小幫手 的電腦 · 沒有 Docker」,沒有畫面小圖;按鈕列、「更新 Bot 的電腦:已是 v…」「自動更新:關」「容器隔離:標準」「上次快照:還沒有」「重設電腦」;API 是 box「沒有 Docker」、available false、runtime runc。 +- **沒有 Docker 時**(covers `box-machine`、`box-manage`):首頁點「電腦」。指令:`$CTL phone wait-text 0/1 --in '#quick' && $CTL phone click '#quick [data-q="computers"]' && $CTL phone wait-text '沒有 Docker' && $CTL phone wait-text '沒有 Docker,現在沒有這台電腦' && $CTL phone shot box-nodocker && $CTL api GET '/api/state?since=0' --jq '{box, box_available}' && $CTL api GET /api/settings --jq '.box | {state, available, version, runtime, snapshot, auto_update}'`。看到:「驗證小幫手 的電腦 · 沒有 Docker」,沒有畫面小圖;按鈕列、「更新 Bot 的電腦:沒有 Docker,現在沒有這台電腦」「自動更新:關」「容器隔離:標準」(不說主機有沒有 gVisor)「上次快照:還沒有」「重設電腦」;API 是 box「沒有 Docker」、available false、runtime runc。 - **聊天裡的電腦**(covers `box-machine`):Bot 在自己的電腦寫檔,再看對話詳細資訊的「電腦」。指令:`$CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call shell {"command":"echo hi > box.txt; ls"}]]' && $CTL phone wait-text '的電腦] box.txt' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text 對話詳細資訊 && $CTL phone click '[data-tab="computer"]' && $CTL phone wait-text 沒有畫面 --in '#details' && $CTL botfile box.txt && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .status]'`。看到:沒有卡片就跑完(自己的電腦不用問),回覆裡有 box.txt;「電腦」分頁是「驗證小幫手 的電腦 · 沒有 Docker」「沒有畫面」;檔案內容 hi。 - **畫面、更新、重設**(covers `box-desktop`、`box-manage`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot box ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`;畫面本身走不到——要 Docker(scratch 不准碰使用者的 Docker、Lima)。看到:設定 › 電腦「Bot 的電腦」一段沒有 Docker 時的樣子;桌面、工作列、檔案視窗、更新排隊靠下面要 Docker 的實機測試。`make update-box` 也不跑:它找的是裝好的那台 AnyBot。 - **從帳號看畫面**(covers `box-account-view`):指令:走不到——要帳號伺服器和 Docker。看到:最接近的真路是 `relay/` 的 `cargo test` 和 `cargo test remote::`(畫面的票)。 @@ -36,6 +36,5 @@ - 桌面是第 12 版起換的(照 LazyBoy2 的 box:XFCE 工作列、深色主題、繁中、台北時間;字型第 14 版起是思源黑體,和 AnyBot 視窗同一套,以前是粉圓);第 11 版以前是 fluxbox,只有右鍵選單和一條細工作列,設定 › 電腦「更新 Bot 的電腦」換新版。桌面設定每次開機照映像檔重放,在桌面上改的外觀、工作列不會留下;留下的是檔案和瀏覽器的登入。工作列鎖住(xfconf 的鎖要寫使用者名稱 bot,寫「*」不算數);它的「面板 › 登出 › 結束」只關掉工作列,一秒後自己回來。網頁上傳檔案的視窗開機時設好大小和位置(GTK 沒記著位置就照字型算大小,比螢幕大)。時區是 /etc/localtime(台北),沒有 TZ 變數,Bot 改了就生效。 - 檔案視窗的「取消」「開啟」在最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——換新版)。看畫面時可以跟自己的電腦互相複製貼上;在畫面裡打的字進到正在看的那個螢幕(Bot 自己的螢幕也一樣,不會打到共用的)。那個 Bot 的螢幕沒開時,看到的是共用桌面,點擊和打字也算在共用桌面(共用桌面上的 Bot 會停手);畫面中途關掉,之後打的字不會另外開一個看不到的螢幕。 - 實機要確認的:選單是中文、只有一層;工作列按右鍵沒有「移除」;網頁上傳檔案的視窗整個在螢幕裡(看得到「開啟」);請 Bot 打開終端機要開出跟工作列「終端機」同一種視窗,打開檔案總管要開出檔案管理員、在 bot 家目錄;開著畫面關掉 Wi-Fi 一分鐘再打開要自己接回;把畫面連結複製到另一個瀏覽器(原本的開著)要連不上。 -- 沒有 Docker 時手機的「電腦」頁照樣寫「已是 v…」「這台 Docker 主機沒有 gVisor」:其實沒有那台電腦,看最上面的狀態。 - 從帳號看畫面:之前靜止一分鐘、或看超過十分鐘會被帳號伺服器切掉,要更新帳號伺服器(make update-server)。 - 從帳號看畫面的票會出現在網址裡,所以網頁一打開就換掉連結裡那張(舊的當場作廢),每次斷線重連再換一張;票只在發出後十分鐘內能開新連線,已連上的畫面在要票的手機還登入時一直開著。斷線超過十分鐘:手機網頁用自己的登入重新要票;電腦開的網頁顯示「這個畫面連結已過期」並停止重試,回 AnyBot 再開一次。 diff --git a/docs/feature-map/branch.md b/docs/feature-map/branch.md index 5ab0568..9a15995 100644 --- a/docs/feature-map/branch.md +++ b/docs/feature-map/branch.md @@ -16,7 +16,7 @@ ## 怎麼操作(verify-anybot) -- Bot:支線裡照常做事;支線不能再開支線,也不能改設定。 +- Bot:支線裡照常做事;支線不能再開支線,也不能動大家共用的東西(設定、建 Bot、群組、刪除或安裝技能、換掉已有的技能、連接器和 hook、瀏覽器設定檔),要做就寫在結果裡給主線。 前提: @@ -25,13 +25,13 @@ - **主線忙的時候開**(covers `branch-btw`、`branch-card`、`branch-report`):Bot 跑 20 秒的指令時打「/」,送「/btw 查一下匯率」。指令:`$CTL phone send '忙 [[call shell {"command":"sleep 20"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == true' && $CTL phone type '#input' '/' && $CTL phone wait-text '/btw' --in '#slash' && $CTL phone wait-gone '#slash [data-sl]' --text '/goal' && $CTL phone send '/btw 查一下匯率' && $CTL phone wait-text '做完了' --in '.talk.branch' && $CTL phone shot branch-done && $CTL phone wait-text '支線的結果已交給正在做事的主線' --in '#msgs' 40 && $CTL model 'select(.user | test("匯率")) | {kind, user: .user[0:40]}'`。看到:工作中「/」只剩 /btw;卡「支線 查一下匯率 ✓ 做完了」和結果;先問一次會不會衝突(沒帶工具的請求「主線正在做…支線要做…」),主線這一輪讀到「〔支線回報〕支線「查一下匯率」做完了…」。 - **主線閒著**(covers `branch-report`):等主線做完再開。指令:`$CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '/btw 查天氣' && $CTL phone wait-text '支線「查天氣」做完了' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.text | startswith("支線「查天氣」")) | .text]'`。看到:結果貼在主聊天的一則訊息裡(只說一次)。 - **停止支線**(covers `branch-card`、`branch-report`):指令:`$CTL phone send '/btw 跑 [[call shell {"command":"sleep 30"}]]' && $CTL phone wait '[data-brstop]' && $CTL phone click '[data-brstop]' && $CTL phone wait-gone '[data-brstop]' && $CTL phone wait-text '已停止' --in '#msgs' && $CTL phone wait-text '看過程' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.branch) | [.branch.state, .text[0:12]]]'`。看到:「停止支線」不見、卡寫「已停止」和「看過程(1)」;被停止的不回報(沒有多一則「支線「跑…」」)。 -- **卡上核准、改不了設定**(covers `branch-card`、`branch-btw`):支線要登出 ChatGPT(按拒絕);支線改自己的描述。指令:`$CTL phone send '/btw 登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '支線:' --in '#ask' && $CTL api GET '/api/state?since=0' --jq '.approvals[0] | {bot, target, title}' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '/btw 改 [[call update_my_profile {"description":"支線改的"}]]' && $CTL phone wait-text '支線改不了設定' --in '#msgs' && $CTL api GET /api/bots/1/detail --jq .description`。看到:卡標題「支線:驗證小幫手 想要…」(target 是那條支線);「支線改不了設定:回到主線再請它改。」,描述還是空的。 -- **重開 AnyBot**(covers `branch-card`):開一條跑 30 秒的支線,重開。指令:`$CTL phone send '/btw 再跑 [[call shell {"command":"sleep 30"}]]' && $CTL phone wait '[data-brstop]' && $CTL restart && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL wait-api /api/bots/1 '[.messages[] | select(.branch.task | tostring | startswith("再跑")) | .branch.state] == ["stopped"]' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.branch.task | tostring | startswith("再跑")) | .branch.note]'`。看到:卡寫「已停止」,原因「被停止了」(`ctl` 是正常關;當掉後重開寫「AnyBot 重新啟動,這條支線停了」),沒有回報。 +- **卡上核准、改不了設定**(covers `branch-card`、`branch-btw`):支線要登出 ChatGPT(按拒絕);支線改自己的描述、改 Bot 的名字。指令:`$CTL phone send '/btw 登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '支線:驗證小幫手 想要登出 ChatGPT 方案' --in '#ask' && $CTL api GET '/api/state?since=0' --jq '.approvals[0] | {bot, target, title}' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '/btw 改 [[call update_my_profile {"description":"支線改的"}]]' && $CTL phone wait-text '支線改不了設定' --in '#msgs' && $CTL phone send '/btw 改名 [[call update_bot {"name":"支線改的名字"}]]' && $CTL wait-api /api/bots/1 '[.messages[] | select(.text | tostring | startswith("支線「改名"))] | length == 1' && $CTL api GET '/api/state?since=0' --jq '{name: .bots[0].name, approvals}' && $CTL api GET /api/bots/1/detail --jq .description && $CTL phone send '/btw 建 [[call create_bot {"name":"支線的 Bot"}]]' && $CTL wait-api /api/bots/1 '[.messages[] | select(.text | tostring | startswith("支線「建"))] | length == 1' && $CTL phone send '/btw 換 [[call browser {"action":"profiles","name":"工作"}]]' && $CTL wait-api /api/bots/1 '[.messages[] | select(.text | tostring | startswith("支線「換"))] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.text | tostring | test("^支線「(建|換)")) | .text]' && $CTL api GET '/api/state?since=0' --jq '[.bots[].name]'`。看到:卡標題「支線:驗證小幫手 想要登出 ChatGPT 方案」(target 是那條支線);改描述、改名、建 Bot、換瀏覽器設定檔都沒有卡片,馬上回「支線改不了設定:回到主線再請它改。」;名字還是「驗證小幫手」、描述還是空的,Bot 清單只有它。 +- **重開 AnyBot**(covers `branch-card`):開一條跑 30 秒的支線,重開。指令:`$CTL phone send '/btw 再跑 [[call shell {"command":"sleep 30"}]]' && $CTL phone wait '[data-brstop]' && $CTL restart && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL wait-api /api/bots/1 '[.messages[] | select(.branch.task | tostring | startswith("再跑")) | .branch.state] == ["stopped"]' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.branch.task | tostring | startswith("再跑")) | .branch.note]'`。看到:卡寫「已停止」,原因「AnyBot 關掉了,這條支線停了」(`ctl` 是正常關;當掉後重開寫「AnyBot 重新啟動,這條支線停了」;「被停止了」只在使用者按停止),沒有回報。 - **沒做完**(covers `branch-report`):主 Bot 換成沒金鑰的 xAI 再開支線。指令:`$CTL phone send '換 [[call update_my_profile {"provider":"xai"}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0].provider == "Xai"' && $CTL phone send '/btw 查匯率' && $CTL phone wait-text '支線「查匯率」沒有做完' --in '#msgs' && $CTL phone shot branch-failed && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.error) | .text]'`。看到:主聊天一則「支線「查匯率」沒有做完:還沒有設定 xAI Grok 的 API 金鑰…」(error);手機的卡也寫原因。 - **桌面**(covers `branch-card`、`branch-report`、`branch-btw`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot branch ANYBOT_SHOT_VIEW=btw`。看到:電腦版的支線卡;沒做完那則的紅色驚嘆號和「重開這條支線」;同時最多 3 條、會衝突就等主線、`context: fork` 靠自動測試。 - 自動測試:`cargo test app::branch::`、`cargo test a_fork_skill`、`cargo test a_branch`(做完回報、記憶算主 Bot、會衝突就等、手機的支線卡)。 ## 陷阱 -- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。在 Bot 的電腦上支線有自己的暫時螢幕和瀏覽器(登入從主線複製),看不到主線開著的網頁;在使用者的電腦上還是一次一個。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」;正常關掉的寫「被停止了」);被停止的支線不回報。 +- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定或動大家共用的東西:`update_my_profile`、`update_bot`、`update_settings`、`teach_skill`、`create_bot`、`create_group`、`move_to_group`、`rename_group`、`delete_group`、`delete_skill`、`skill_install`(內建的也是),連接器和 hook 除了看(`manage_connectors` 的 list、reconnect、登入登出,`manage_hooks` 的 list)以外的動作,瀏覽器的 `profiles` 新增或切換,都馬上回「支線改不了設定」、不跳卡片;`save_skill`、`skillify` 存新技能可以(算主 Bot 的),但不能換掉技能庫裡已有的同名技能(大小寫不同也算);瀏覽器步驟指名的 `profile` 只用在那一步,不會變成使用中;登入登出 ChatGPT 不算設定,照樣跳卡;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。在 Bot 的電腦上支線有自己的暫時螢幕和瀏覽器(登入從主線複製),看不到主線開著的網頁;在使用者的電腦上還是一次一個。關掉 AnyBot 時,沒做完的支線會停掉(「AnyBot 關掉了,這條支線停了」;當掉後重新啟動的寫「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。 - 支線的結果在主線還在做事時交給正在做事的主線(聊天裡一行「支線的結果已交給正在做事的主線」),主線閒著才另外貼一則。 diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index c620e8e..0672e44 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -4,9 +4,9 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 ## 子功能 -- `browser-actions` 一個 `browser` 工具,用 action 分:`open` 開網址並讀出頁面、`read` 讀目前分頁、`elements` 只列可操作的元素、`find` 找字、`table` 讀表格、`screenshot` 截圖(有編號框);`click`、`hover`、`type`、`press`、`select`、`scroll`、`wait`;`tabs` 分頁、`back` 上一頁/下一頁/重新整理;`upload`、`download`、`pdf`;`dialog` 回應網頁跳出的對話框;`eval` 唯讀的小段 JavaScript;`sent` 查帳號已經送過什麼;`profiles` 列出、新增、切換設定檔;`fill` 從保險庫填帳密、卡號、地址([vault](vault.md))。 +- `browser-actions` 一個 `browser` 工具,用 action 分:`open` 開網址並讀出頁面、`read` 讀目前分頁、`elements` 只列可操作的元素、`find` 找字、`table` 讀表格、`screenshot` 截圖(有編號框);`click`、`hover`、`type`、`press`、`select`、`scroll`、`wait`;`tabs` 分頁、`back` 上一頁/下一頁/重新整理;`upload`、`download`、`pdf`;`dialog` 回應網頁跳出的對話框;`eval` 唯讀的小段 JavaScript;`sent` 查帳號已經送過什麼;`profiles` 設定檔:不帶 name 列出,帶 name 換到 AnyBot 自己那個名字的設定檔(名字要一樣,大小寫不算;沒有就新增一個全新的);`fill` 從保險庫填帳密、卡號、地址([vault](vault.md))。 - `browser-fetch` `web_fetch`:不用登入的公開網頁,直接下載成文字。 -- `browser-profiles` 設定檔:Chrome、Brave、Edge、Chromium 或 Firefox。名稱結尾是「(Firefox)」的是使用者自己的 Firefox 設定檔(帶著他的登入);「你的瀏覽器」是使用者平常用的瀏覽器(只能讀)。 +- `browser-profiles` 設定檔:Chrome、Brave、Edge、Chromium 或 Firefox。名稱結尾是「(Firefox)」的是使用者自己的 Firefox 設定檔(帶著他的登入);「你的瀏覽器」是使用者平常用的瀏覽器(只能讀)。這兩種是使用者自己的:Bot 不會換過去當使用中(要使用者在設定裡換),某一步指名用它也不會變成使用中。Bot 的電腦上的瀏覽器只有一個設定檔。 - `browser-refs` 元素編號:同一頁重讀編號不變;換頁要用新結果的編號。 - `browser-type` 打字:`type` 的換行會整段放進去(像貼上),結果說欄位現在裝了什麼。 - `browser-wait` 間隔:`wait` 加 `after_send: true`,從上一次送出起算(最多 900 秒),下一則可以先打好再等。 @@ -21,7 +21,7 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 ## 怎麼操作(verify-anybot) -- Bot:先 `open` 或 `read`,再照最新結果的編號(ref)或看得到的字操作,不要憑記憶。每次都帶同一個 `profile`。多行留言直接 `type`,不用剪貼簿;送出用 `press`(例如 ctrl+Return)或 `click` 送出鍵。送出後看結果最後那行【系統】:「已送出,系統重新讀過頁面確認」才算成功;「沒有送出」或「發布前檢查沒通過」就照它說的做。防重複先用 `sent`(帶 profile)看回過誰,比讀網站的回覆頁便宜。 +- Bot:先 `open` 或 `read`,再照最新結果的編號(ref)或看得到的字操作,不要憑記憶。每次都帶同一個 `profile`。多行留言直接 `type`,不用剪貼簿;送出用 `press`(例如 ctrl+Return)或 `click` 送出鍵。送出後看結果最後那行【系統】:「已送出,系統重新讀過頁面確認」才算成功;「沒有送出」或「發布前檢查沒通過」就照它說的做。防重複先用 `sent`(帶 profile)看回過誰,比讀網站的回覆頁便宜。換設定檔用 `profiles` 帶 name(沒有就新增並換過去);使用者自己的瀏覽器要請他在設定裡換,Bot 的電腦上和支線裡不能換。 前提: @@ -29,8 +29,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - scratch 沒有 Docker:沒有 Bot 電腦的瀏覽器,真的要開網頁時 AnyBot 會在跑驗證的這台 Mac 開一個看得到的瀏覽器——所以下面只走開瀏覽器之前就有答案的路,卡片一律按「拒絕」。 - **公開網頁以外不讀**(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-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`):`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 wait-text '在 執行 AnyBot 的這台電腦 上' --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/」「(在 執行 AnyBot 的這台電腦 上)」(Bot 的電腦都開不了瀏覽器,開的會是 AnyBot 在這台的;可以一律允許);拒絕後兩步都是 denied。 +- **已送帳本、設定檔**(covers `browser-gate`、`browser-profiles`、`browser-actions`):請 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:]' && $CTL phone send '[[call browser {"action":"profiles","name":"工作"}]]' && $CTL phone wait-text '已新增並切換到設定檔「工作」' --in '#msgs' && $CTL phone send '[[call browser {"action":"profiles","name":"預設"}]]' && $CTL phone wait-text '已切換到「預設」' --in '#msgs' && $CTL phone send '[[call browser {"action":"profiles","name":"你的瀏覽器"}]]' && $CTL phone wait-text '是使用者自己的瀏覽器' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.label == "瀏覽器設定檔") | .detail]' && $CTL datafile browser-profile.txt`。看到:「帳本裡最近 30 天沒有送出紀錄(AnyBot 從開始記帳本那天起才有…)」;「AnyBot 瀏覽器的設定檔:預設(使用中)、你的瀏覽器。每個設定檔有自己的登入。…」;「已新增並切換到設定檔「工作」(全新的,還沒登入任何網站)…現在:預設、工作(使用中)、你的瀏覽器」;「已切換到「預設」…」;換到「你的瀏覽器」被擋:「「你的瀏覽器」是使用者自己的瀏覽器(帶著他的登入):Bot 不能自己換過去…請使用者在 設定 › 電腦 ›「AnyBot 瀏覽器設定檔」自己切換。」;設定檔步驟寫「列出設定檔」「切換到「工作」」「切換到「預設」」「切換到「你的瀏覽器」」(最後一個 failed);記著的使用中設定檔是「預設」;都沒開瀏覽器。 - **真的開網頁、打字、送出**(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` 也換掉)。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index 9c4f3aa..980ed03 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -6,7 +6,7 @@ Bot 在它能用的電腦上跑指令、讀寫搜尋檔案、開背景指令和 - `files-shell` `shell` 在工作資料夾裡跑,輸入一開始就關著,不會卡在等人打字。超過 timeout_ms(預設 30 秒,最多 10 分鐘)不中斷,移到背景繼續跑,給背景指令編號。 - `files-terminal` 互動終端機:`shell` 加 interactive,給要真的終端機的程式(全螢幕介面、會問問題的、編輯器);`write_terminal` 打字和按鍵,`read_terminal` 看畫面。 -- `files-monitor` 監看:`shell` 加 monitor,指令馬上放背景,每印出新的一行叫醒 Bot 一次(一秒內的併一次,最多列 20 行);閒著馬上開一輪,在做事就等這輪完。10 秒超過 200 行或叫滿 60 次自動停;指令結束說一次;stop 停掉的不再說。 +- `files-monitor` 監看:`shell` 加 monitor,指令馬上放背景,每印出新的一行叫醒 Bot 一次(一秒內的併一次,最多列 20 行);閒著馬上開一輪,在做事就等這輪完。10 秒超過 200 行或叫滿 60 次自動停;指令結束說一次;stop 停掉的不再說。手機上叫醒的那則上方標「監看」。 - `files-background` 背景指令用 `read_terminal` 看(id;wait_ms 最多 120 秒,等到有新東西又安靜;until 等某段字);`write_terminal` 加 stop 停掉它和它啟動的程式。 - `files-edit` 檔案:`list_dir` 看資料夾;`read_file` 讀(有行號,offset、limit 分段,最大 8 MB);`search` 找字(「路徑:行號:內容」,有 ripgrep 可用正規表示式);`edit_file` 改(old_text 要剛好出現一次;留空是新建或整個覆寫)。 - `files-workdir` 工作資料夾:這台電腦是 Bot 設定的「起始資料夾」(沒填是家目錄);Bot 自己的電腦是它的資料夾;SSH 電腦是設定的資料夾或對方家目錄。 @@ -27,7 +27,7 @@ Bot 在它能用的電腦上跑指令、讀寫搜尋檔案、開背景指令和 - 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。沒有 Docker:Bot 的電腦是沙盒裡的資料夾;背景指令照順序從 #1 編。 -- **監看**(covers `files-monitor`):第一步(見陷阱)。指令:`$CTL model-reply 幫我盯著 '[[call shell {"command":"sleep 2; for i in 1 2; do echo tick$i; sleep 2; done","monitor":true}]] 開始盯了' && $CTL phone send 幫我盯著 && $CTL phone wait-text 開始盯了 && $CTL model-reply --clear && $CTL phone wait-text 監看也停了 30 && $CTL api GET /api/bots/1 --jq '[.messages[]|select(.wake)|.text]'`。看到:「[監看 #1]…印出了…tick1」「…tick2」各叫醒一輪,最後「指令結束了,監看也停了。」;API 有這三則。 +- **監看**(covers `files-monitor`):第一步(見陷阱)。指令:`$CTL model-reply 幫我盯著 '[[call shell {"command":"sleep 2; for i in 1 2; do echo tick$i; sleep 2; done","monitor":true}]] 開始盯了' && $CTL phone send 幫我盯著 && $CTL phone wait-text 開始盯了 && $CTL model-reply --clear && $CTL phone wait-text 監看也停了 30 && $CTL phone wait-text 監看 --in '#msgs .m.user .tag' && $CTL phone shot files-monitor && $CTL api GET /api/bots/1 --jq '[.messages[]|select(.wake)|.text]'`。看到:「[監看 #1]…印出了…tick1」「…tick2」各叫醒一輪,最後「指令結束了,監看也停了。」,手機上這三則上方標「監看」;API 有這三則。 - **寫、找、出界**(covers `files-edit`、`files-workdir`):指令:`$CTL phone send '[[call edit_file {"path":"a.txt","old_text":"","new_text":"第一行\n蘋果\n"}]]' && $CTL phone wait-text 已建立 && $CTL phone send '[[call search {"pattern":"蘋果"}]]' && $CTL phone click '.step.done .h' --text 搜尋檔案 && $CTL phone wait-text 'a.txt:2:蘋果' && $CTL phone send '[[call read_file {"path":"/etc/hosts"}]]' && $CTL phone wait '.step.denied' --text 讀取檔案 && $CTL botfile a.txt`。看到:搜尋點開是「…/bot-1/a.txt:2:蘋果」;/etc/hosts 被擋(「…看不到這台電腦上的其他檔案」);檔案兩行。 - **超時進背景**(covers `files-shell`、`files-background`):指令:`$CTL phone send '[[call shell {"command":"sleep 3; echo done","timeout_ms":1000}]]' && $CTL phone wait-text '背景指令 #2' && $CTL phone send '[[call read_terminal {"id":2,"wait_ms":10000,"until":"done"}]]' && $CTL phone click '.step.done .h' --text 查看背景指令 && $CTL phone wait-text '(已出現「done」)'`。看到:「指令跑了超過 1 秒,已移到背景繼續執行(背景指令 #2)」;等到 done。 - **互動終端機、重新啟動**(covers `files-terminal`、`files-background`):指令:`$CTL phone send '[[call shell {"command":"cat","interactive":true}]]' && $CTL phone wait-text '已在互動終端機 #3' && $CTL phone send '[[call write_terminal {"id":3,"input":"你好\n"}]]' && $CTL phone wait-text '已送出 3 個字' && $CTL phone send '[[call write_terminal {"id":3,"stop":true}]]' && $CTL phone wait-text '已停止背景指令 #3' && $CTL phone send '[[call shell {"command":"sleep 300","timeout_ms":1000}]]' && $CTL phone wait-text '背景指令 #4' && $CTL phone send '[[call write_terminal {"id":4,"input":"x\n"}]]' && $CTL phone wait-text 不是互動終端機 && $CTL phone click '[data-back]' && $CTL phone click '[data-botmenu="1"]' && $CTL phone click '#sheet-in .opt' --text 更多 && $CTL phone click '#sheet-in .opt' --text 重新啟動這個 && $CTL phone wait-text 已重新啟動 && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call read_terminal {"id":4}]]' && $CTL phone wait-text 狀態:已結束`。看到:打字那步點開是兩行「你好」(回顯+cat);#3 停掉;一般指令 #4「不是互動終端機…」;「已重新啟動」後 #4 已結束。 diff --git a/docs/feature-map/market.md b/docs/feature-map/market.md index 415e616..c6ef2b2 100644 --- a/docs/feature-map/market.md +++ b/docs/feature-map/market.md @@ -27,7 +27,7 @@ - 要一個連接器在清單上:請 Bot 加一個指向這台沒有的資料夾的(連不上,但列在清單裡;scratch 不連網,不加市集的)。 - **手機的連接器清單**(covers `market-phone`、`market-list`):請 Bot 加 far,允許;到 設定 › 整合 看那一列,按重新連線,再關掉。指令:`$CTL phone send '加 [[call manage_connectors {"action":"add","name":"far","command":"node /nope/srv/x.js"}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text '這台電腦上沒有' --in '#msgs' 60 && $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 '這台電腦上沒有「/nope/srv/x.js」' --in '#list' && $CTL phone shot market-phone && $CTL phone click '[data-mcpre="far"]' && $CTL phone wait-text 重新連線中 && $CTL phone click 'label.sw:has([data-mcp="far"])' && $CTL phone wait-text 已關閉 --in '#list' && $CTL wait-api /api/settings '.mcp[0].enabled == false'`。看到:「連接器(MCP)」一列 far:黃點、原因(一行)、重新連線、開關、垃圾桶,下面「從公用市集加入」;關掉後「已關閉」,大腦那邊 enabled 是 false。 -- **手機不能改名、區網加不了**(covers `market-rename`、`market-phone`、`market-registry`):送手機頁面會送的兩個請求:改名,和公用市集選好後的「加入」。指令:`$CTL api --expect 403 POST /api/act/mcp '{"name":"far","rename":"near"}' && $CTL api --expect 403 POST /api/act/mcp '{"add":{"name":"x","url":"https://x.example/mcp"}}' && $CTL api GET /api/settings --jq '[.mcp[].name]'`。看到:「連接器的名稱只能在電腦上的 AnyBot 改」;加入回「這項設定會讓 Bot 不用問就動手,不能從區網連線(沒有加密)打開…」;清單還是只有 far。 +- **手機不能改名、區網加不了**(covers `market-rename`、`market-phone`、`market-registry`):送手機頁面會送的兩個請求:改名,和公用市集選好後的「加入」。指令:`$CTL api --expect 403 POST /api/act/mcp '{"name":"far","rename":"near"}' && $CTL api --expect 403 POST /api/act/mcp '{"add":{"name":"x","url":"https://x.example/mcp"}}' && $CTL api GET /api/settings --jq '[.mcp[].name]'`。看到:「連接器的名稱只能在電腦上的 AnyBot 改」;加入回「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」;清單還是只有 far。 - **手機移除**(covers `market-phone`):按垃圾桶 ›「移除」。指令:`$CTL phone click '[data-mcprm="far"]' && $CTL phone click '#sheet-in .opt' --text 移除 && $CTL phone wait-text 還沒有連接器 --in '#list' && $CTL api GET /api/settings --jq '.mcp'`。看到:先問「移除這個連接器?」;之後寫「還沒有連接器」,大腦那邊是空的。 - **桌面的四個頁**(covers `market-list`、`market-item`、`market-add`、`market-builtin`、`market-registry`、`market-rename`):指令:要開視窗——`$CTL stop && (for pg in list 0 add market; do ABV_ALLOW_WINDOW=1 $CTL desktop-shot market-$pg ANYBOT_SHOT_VIEW=channels ANYBOT_SHOT_SUB=1 ANYBOT_SHOT_MCP_PAGE=$pg ANYBOT_SHOT_MCP_TOOLS=12 || exit 1; done)`(示範資料:github、files 兩個)。看到:清單一列一個;github 自己的頁有「工具(12)」「搜尋工具」、欄位卡和紅字移除;「新增連接器」頁;「瀏覽市集」的 8 個和公用市集的搜尋框。打字改名、Enter/Esc 靠自動測試。 - **加入市集的、公用市集搜尋**(covers `market-builtin`、`market-registry`):指令:走不到——要網路(npm、PyPI、官方 MCP Registry)和 Node.js、uv;scratch 不對外連。看到:最接近的真路是上面的 403、[connectors](connectors.md) 的本機伺服器和 `cargo test mcp::`(`the_registry_lists_what_can_be_reached_by_address`)。 diff --git a/docs/feature-map/models.md b/docs/feature-map/models.md index f6300ad..d2b47be 100644 --- a/docs/feature-map/models.md +++ b/docs/feature-map/models.md @@ -26,8 +26,8 @@ - **設定 › 模型**(covers `models-providers`、`models-chatgpt`):帳戶選單 › 設定 › 模型,點「ChatGPT 方案」。指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="models"]' && $CTL phone wait-text 'OpenCode Go' --in '#list' && $CTL phone shot models-list && $CTL phone click '[data-prov]' --text 'ChatGPT 方案' && $CTL phone wait-text '使用 ChatGPT 繼續' --in '#sheet-in' && $CTL api POST /api/act/chatgpt '{"action":"status"}' --jq .status`。看到:九家,xAI 到 OpenCode Go「未設定」,Ollama(本機)、自訂「可以用」;ChatGPT 方案的選單有「使用 ChatGPT 繼續…」(不按:會連 OpenAI);大腦說「還沒有用 ChatGPT 登入。」 - **換到沒金鑰的供應商**(covers `models-bot`、`models-providers`):請 Bot 只換供應商成 xAI,允許,再傳一句。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '換 [[call update_my_profile {"provider":"xai"}]]' && $CTL phone wait-text 'xAI Grok' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0].via == "xAI Grok · grok-4"' && $CTL phone send '你好' && $CTL phone wait-text '還沒有設定 xAI Grok 的 API 金鑰' --in '#msgs' && $CTL phone shot models-nokey`。看到:卡片「AI 供應商:自訂(OpenAI 相容) → xAI Grok」;模型自動換成 xAI 的建議模型 grok-4;下一則出錯「還沒有設定 xAI Grok 的 API 金鑰。請到「設定 → 模型」貼上金鑰。」(沒有連出去)。 - **從手機換回來**(covers `models-bot`):標題 › 模型,選 fake-model。指令:`$CTL phone click '#island' && $CTL phone click '[data-d="model"]' && $CTL phone wait-text '其他模型' --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text fake-model && $CTL wait-api '/api/state?since=0' '.bots[0].via == "自訂(OpenAI 相容) · fake-model"' && $CTL phone click '[data-back]' && $CTL phone send '回來了嗎' && $CTL phone wait-text 'FAKE-MODEL 回答:回來了嗎' --in '#msgs'`。看到:選單只列可以用的(Ollama(本機)、自訂(OpenAI 相容))和「其他模型…」;換回後又能回話。 -- **思考模式、執行步驟用的模型**(covers `models-thinking`):指令:`$CTL phone send '想深一點 [[call update_my_profile {"thinking":"high","step_model":"off"}]]' && $CTL phone wait-text '思考模式' --in '#ask' && $CTL phone shot models-thinking && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0] | .thinking == "high" and .step_model == "off"' && $CTL phone send '再說一次' && $CTL phone wait-text 'FAKE-MODEL 回答:再說一次' --in '#msgs'`。看到:卡片列出思考模式和執行步驟用的模型的新值;允許後大腦記著 high、off,照常回話。 -- **ChatGPT 登出要先問**(covers `models-chatgpt`):請 Bot 登出,按拒絕;再看狀態。指令:`$CTL phone send '登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '登出 ChatGPT' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '狀態 [[call chatgpt_login {"action":"status"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "chatgpt_login" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "chatgpt_login") | {status, result}]'`。看到:登出先跳卡片(「登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答…」),拒絕後 denied;status 不用問,「還沒有用 ChatGPT 登入。」 +- **思考模式、執行步驟用的模型**(covers `models-thinking`):指令:`$CTL phone send '想深一點 [[call update_my_profile {"thinking":"high","step_model":"off"}]]' && $CTL phone wait-text '思考模式' --in '#ask' && $CTL phone wait-text '執行步驟用的模型:自動 → 不分開' --in '#ask' && $CTL phone shot models-thinking && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0] | .thinking == "high" and .step_model == "off"' && $CTL phone send '再說一次' && $CTL phone wait-text 'FAKE-MODEL 回答:再說一次' --in '#msgs'`。看到:卡片列出「思考模式:自動(模型自己決定) → 深入(想得久,較慢)」和「執行步驟用的模型:自動 → 不分開」(設定畫面上的說法);允許後大腦記著 high、off,照常回話。 +- **ChatGPT 登出要先問**(covers `models-chatgpt`):請 Bot 登出,按拒絕;再看狀態。指令:`$CTL phone send '登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '登出 ChatGPT' --in '#ask' && $CTL phone wait-text '驗證小幫手 想要登出 ChatGPT 方案' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '狀態 [[call chatgpt_login {"action":"status"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "chatgpt_login" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "chatgpt_login") | {status, result}]'`。看到:登出先跳卡片「驗證小幫手 想要登出 ChatGPT 方案」(「登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答…」),拒絕後 denied;status 不用問,「還沒有用 ChatGPT 登入。」 - **用 ChatGPT 登入**(covers `models-chatgpt`):指令:走不到——登入會向 OpenAI 註冊、要真的 ChatGPT 帳號和方案(貼回網址、螢幕電腦的「完成登入」、額度用完都一樣)。看到:最接近的真路是上一步的 status 和 `cargo test chatgpt::`(註冊一次後重用、貼回網址、沒勾同意、額度用完)。 - **桌面**(covers `models-bot`、`models-providers`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot models ANYBOT_SHOT_TAB=providers`。看到:設定 › 模型 每家的金鑰欄和「使用 ChatGPT 繼續」;輸入框 + 的模型子選單(「(未設定金鑰)」)、Bot 設定的紅字「前往設定」靠自動測試。 - 自動測試:`cargo test chatgpt::`、`cargo test providers::`、`cargo test profile::`、`cargo test remote::tests::only_the_owner_signs_the_brain_in_to_chatgpt`。 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 6c8a406..be05598 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -4,7 +4,7 @@ ## 子功能 -- `phone-pages` 頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」;卡片太高時卡在內面自己捲,輸入框不會被頂出螢幕)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定(一般、模型、權限、整合、電腦、保險庫、手機與帳號、更新,能改的比電腦少)、傳送到其他裝置。 +- `phone-pages` 頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止;叫醒 Bot 的訊息上方標是什麼叫醒的:目標、例行任務、觸發、訊息管道、來自其他 Bot、監看)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」;卡片太高時卡在內面自己捲,輸入框不會被頂出螢幕)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定(一般、模型、權限、整合、電腦、保險庫、手機與帳號、更新,能改的比電腦少;開著的設定頁跟著電腦那邊的改變重讀,不用重新整理;直接連線只能收緊、不能放寬,見 [autonomy](autonomy.md))、傳送到其他裝置。 - `phone-cards` 手機上的卡(允許、需要處理、問題卡)只答它畫出來的那一張:那張已經在電腦或另一支手機上回答、被停止、或換成下一張時,按了不算,聊天裡寫「手機上的回答沒有用上…」;開了很久沒重新整理的舊頁面也一樣。螢幕電腦上的卡也是;比大腦舊的螢幕電腦答不了任何卡,要在那台 設定 › 更新 換新版(重新整理沒用)。支線的卡沒用上時,寫在主線的聊天。 - `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,用宋體(思源宋體,沒有就用系統的宋體)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。你自己的訊息(泡泡)和所有按鈕、清單、設定用黑體。手機沒有字型選項。 - `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」可以選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版的電腦沒送顏色時,手機用內建的「紙」。 @@ -27,7 +27,7 @@ - **清單和選單**(covers `phone-pages`、`phone-claude`):看首頁,打開 Bot 那列的「⋯」。指令:`$CTL phone wait '.row[data-bot="1"]' && $CTL phone click '[data-botmenu="1"]' && $CTL phone wait-text 對話詳細資訊 --in '#sheet-in' && $CTL phone shot phone-menu && $CTL phone click '#sheet-in .opt' --text 釘選 && $CTL wait-api '/api/state?since=0' '.bots[0].pinned == true'`。看到:一列一個 Bot(第二行一行說明);選單有「對話詳細資訊」「釘選」「移至分區」「更多…」;釘選後大腦那邊 pinned。 - **聊天**(covers `phone-pages`、`phone-look`、`phone-claude`):打開 Bot、傳一句。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone send '你好,從手機傳的' && $CTL phone wait-text 'FAKE-MODEL 回答:你好,從手機傳的' --in '#msgs' && $CTL phone shot phone-chat`。看到:標題列是名稱和 fake-model;你的話是泡泡,回答直接排在畫面上(宋體)、下面只有時間和圖示;輸入框是底部圓角卡片。 -- **全部允許,之後直接操作**(covers `phone-pages`、`phone-cards`):請 Bot 改名,在卡片上按「全部允許,之後直接操作」›「打開」,再按「允許」。指令:`$CTL phone send '請改名 [[call update_bot {"name":"手機改的名字"}]]' && $CTL phone click '#ask [data-direct]' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '不能從區網連線' && $CTL phone wait '#ask .ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text 手機改的名字 --in '#isl-name'`。看到:直接連線打不開直接操作([autonomy](autonomy.md)),卡片留著;按「允許」才改名。 +- **全部允許,之後直接操作**(covers `phone-pages`、`phone-cards`):請 Bot 改名,在卡片上按「全部允許,之後直接操作」›「打開」,再按「允許」。指令:`$CTL phone send '請改名 [[call update_bot {"name":"手機改的名字"}]]' && $CTL phone click '#ask [data-direct]' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '只能收緊、不能放寬' && $CTL phone wait '#ask .ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text 手機改的名字 --in '#isl-name'`。看到:直接連線打不開直接操作([autonomy](autonomy.md)),卡片留著;按「允許」才改名。 - **舊頁面的回答不算**(covers `phone-cards`):卡片在等時,一個說不出是哪張卡的回答進來。指令:`$CTL phone send '再改 [[call update_bot {"name":"不該出現的名字"}]]' && $CTL wait-api '/api/state?since=0' '.approvals | length == 1' && $CTL api POST /api/bots/1/answer '{"answer":"once"}' && $CTL phone wait-text '手機上的回答沒有用上' --in '#msgs' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL state '.bots[0].name'`。看到:「手機上的回答沒有用上:這個頁面太舊…」,卡片還在;拒絕後名字還是「手機改的名字」。 - **顏色跟著電腦**(covers `phone-colors`):請 Bot 把電腦換成深色,重新整理;再把這支手機選「淺色」。指令:`$CTL phone send '換深色 [[call update_settings {"theme":"dark"}]]' && $CTL phone wait-text '主題 → dark' --in '#msgs' && $CTL phone open --listed && $CTL phone wait 'html[data-theme="dark"]' && $CTL phone shot phone-dark && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 這支手機的外觀 && $CTL phone click '#sheet-in .opt' --text 淺色 && $CTL phone wait 'html[data-theme="light"]'`。看到:外觀「跟著電腦」時變深色;選「淺色」就只有這支手機變回淺色。 - **設定頁**(covers `phone-pages`):帳戶選單 › 設定,再點「保險庫」。指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot phone-settings && $CTL phone click '[data-go="vault"]' && $CTL phone wait-text '只在電腦上的 AnyBot 管理'`。看到:一般、模型、權限、整合、電腦、保險庫、手機與帳號、更新;保險庫只有一句說明(手機看不到密碼)。 diff --git a/docs/feature-map/profile.md b/docs/feature-map/profile.md index df91218..5178e93 100644 --- a/docs/feature-map/profile.md +++ b/docs/feature-map/profile.md @@ -26,8 +26,8 @@ - **讀自己的設定**(covers `profile-self`):指令:`$CTL phone send '你的設定 [[call my_profile {}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "my_profile" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "my_profile") | .result]'`。看到:描述、Soul 與指示(只有你自己讀)、擅長、不找你做的事、能力(11 類)、技能、電腦、模型、頭像,和「要改就用 update_my_profile…」。 - **關掉一類能力要先問**(covers `profile-self`、`profile-abilities`):拒絕一次、允許一次。指令:`$CTL phone send '關掉 [[call update_my_profile {"abilities_off":["files"]}]]' && $CTL phone wait-text '關掉「檔案與指令」' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL api GET /api/bots/1/detail --jq '[.abilities[] | select(.on | not) | .key]' && $CTL phone send '再關 [[call update_my_profile {"abilities_off":["files"]}]]' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/bots/1/detail '[.abilities[] | select(.on | not) | .key] == ["files"]'`。看到:卡片「「驗證小幫手」想改自己的設定:- 能力:關掉「檔案與指令」」;拒絕後一類都沒少(`[]`);允許後只少 files。 - **下一則起生效**(covers `profile-abilities`):指令:`$CTL phone send '跑 [[call shell {"command":"echo hi"}]]' && $CTL phone wait-text '這一輪沒有 shell 這個工具' --in '#msgs' && $CTL model 'select(.kind == "call" or .kind == "missing-tool") | {kind, tools}'`。看到:「FAKE-MODEL:這一輪沒有 shell 這個工具(有:…)」;模型收到的工具比前一輪少。 -- **手機的 Bot 設定**(covers `profile-editor`、`profile-abilities`):試著勾回「檔案與指令」;換形狀和顏色、寫擅長和 Soul。指令:`$CTL phone click '#island' && $CTL phone click '#b-botset' && $CTL phone click '[data-tick="abilities"][data-key="files"]' && $CTL phone wait-text '不能從區網連線' --in '#toast' && $CTL api GET /api/bots/1/detail --jq '[.abilities[] | select(.on | not) | .key]' && $CTL phone click '[data-shape="heart"]' && $CTL phone click '[data-color="green"]' && $CTL phone click '[data-e="strengths"]' && $CTL phone type '#ask-in' '查資料ZZ' && $CTL phone click '#ask-ok' && $CTL phone click '[data-e="instr"]' && $CTL phone type '#ask-in' '秘密口令QQ' && $CTL phone click '#ask-ok' && $CTL phone wait-text 秘密口令QQ --in '#botset' && $CTL phone shot profile-botset && $CTL wait-api /api/bots/1/detail '.shape == "heart" and .color == "green" and .strengths == "查資料ZZ"'`。看到:基本、個人檔案、能力(11 個開關)、會的技能、頭像(14 種形狀、10 種顏色)、AI 與電腦、整理;直接連線勾不回能力(「這項設定會讓 Bot 不用問就動手,不能從區網連線…」),還是少 files;形狀、顏色、擅長、Soul 照改。 -- **請 Bot 勾回來**(covers `profile-self`、`profile-abilities`):指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '打開 [[call update_my_profile {"abilities_on":["files"]}]]' && $CTL phone wait-text '打開「檔案與指令」' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/bots/1/detail '[.abilities[] | select(.on | not)] == []'`。看到:卡片「能力:打開「檔案與指令」」,允許後 11 類全開。 +- **手機的 Bot 設定**(covers `profile-editor`、`profile-abilities`):試著勾回「檔案與指令」、勾掉「頁面」;換形狀和顏色、寫擅長和 Soul。指令:`$CTL phone click '#island' && $CTL phone click '#b-botset' && $CTL phone click '[data-tick="abilities"][data-key="files"]' && $CTL phone wait-text '只能收緊、不能放寬' --in '#toast' && $CTL api GET /api/bots/1/detail --jq '[.abilities[] | select(.on | not) | .key]' && $CTL phone click '[data-tick="abilities"][data-key="pages"]' && $CTL wait-api /api/bots/1/detail '[.abilities[] | select(.on | not) | .key] == ["files", "pages"]' && $CTL phone click '[data-shape="heart"]' && $CTL phone click '[data-color="green"]' && $CTL phone click '[data-e="strengths"]' && $CTL phone type '#ask-in' '查資料ZZ' && $CTL phone click '#ask-ok' && $CTL phone click '[data-e="instr"]' && $CTL phone type '#ask-in' '秘密口令QQ' && $CTL phone click '#ask-ok' && $CTL phone wait-text 秘密口令QQ --in '#botset' && $CTL phone shot profile-botset && $CTL wait-api /api/bots/1/detail '.shape == "heart" and .color == "green" and .strengths == "查資料ZZ"'`。看到:基本、個人檔案、能力(11 個開關)、會的技能、頭像(14 種形狀、10 種顏色)、AI 與電腦、整理;直接連線勾不回能力(「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」),還是少 files;勾掉「頁面」照做(少 files、pages);形狀、顏色、擅長、Soul 照改。 +- **請 Bot 勾回來**(covers `profile-self`、`profile-abilities`):指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '打開 [[call update_my_profile {"abilities_on":["files","pages"]}]]' && $CTL phone wait-text '打開「檔案與指令」' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/bots/1/detail '[.abilities[] | select(.on | not)] == []'`。看到:卡片「能力:打開「檔案與指令」」「能力:打開「頁面」」,允許後 11 類全開。 - **名冊有擅長、沒有 Soul**(covers `profile-roster`):建第二個 Bot,看它讀到什麼。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-newbot' && $CTL phone click '#sheet-in .opt' --text '建立 Bot' && $CTL phone type '#ask-in' '研究員' && $CTL phone click '#ask-ok' && $CTL phone wait-text 研究員 --in '#isl-name' && $CTL model-reply 秘密口令QQ 看得到Soul && $CTL phone send '誰能幫忙' && $CTL phone wait-text 'FAKE-MODEL 回答:誰能幫忙' --in '#msgs' && $CTL model-reply 查資料ZZ 名冊有驗證小幫手 && $CTL phone send '誰能查' && $CTL phone wait-text '名冊有驗證小幫手' --in '#msgs' && $CTL model-reply --clear`。看到:研究員照常回(它的說明裡沒有驗證小幫手的 Soul);改比對擅長就回「名冊有驗證小幫手」(擅長在同事名冊裡)。 - **支線改不了**(covers `profile-self`):在研究員的聊天開支線改描述。指令:`$CTL phone send '/btw 改 [[call update_my_profile {"description":"支線改的"}]]' && $CTL phone wait-text '支線改不了設定' --in '#msgs' && $CTL api GET /api/bots/2/detail --jq .description`。看到:「支線改不了設定:回到主線再請它改。」,描述還是空的。 - **桌面的 Bot 設定**(covers `profile-editor`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot profile ANYBOT_SHOT_VIEW=editor`。看到:「Bot 資料」卡、四張收起的卡各一行、「自訂」色盤和「色碼」;視窗不會變寬(卡片和標題列一樣寬)靠 `cargo test layout_audit::`。 @@ -40,5 +40,6 @@ - 「模型可讀長度」和「可以用的電腦」在「電腦操作」裡,要先勾「讓這個 Bot 查看、修改檔案和執行指令」才看得到;電腦只有一台時不顯示「可以用的電腦」。 - 能力或技能全部勾回來就是「全部」:之後新增的能力類別、新裝的技能也自動算它的。它自己的電腦一定能用,拿不掉。 - Bot 設定要按「儲存」才算;關掉或按「取消」就不存(手機的 Bot 設定每一項改了就存)。 -- 手機用同一個網路直接連時,改不了能力和可以用的電腦(勾掉也不行):在電腦上改、用帳號連線,或請 Bot 用 `update_my_profile`。 +- 手機的「可以用的電腦」只列現在連得到的電腦:帳號裡關機的那台不在清單上,維持原狀(原本不准就還是不准);有清單的 Bot 在手機上全勾也還是清單,不會變成「每一台」(以後新加的電腦要另外勾)。 +- 手機用同一個網路直接連時只能收緊:能力和可以用的電腦只能勾掉、不能勾回,電腦工具只能關、不能開,不能分享給團隊,也不能把 Bot 加進分享給團隊的群組;要放寬在電腦上改、用帳號連線,或請 Bot 用 `update_my_profile`(會先跳卡片)。 - (驗證)說明裡有沒有某段字(名冊、Soul),假模型的紀錄看不到全文:用 `model-reply <那段字> <回答>` 比對。 diff --git a/docs/feature-map/replay.md b/docs/feature-map/replay.md index 0996c19..61fb52a 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -24,7 +24,7 @@ - 回頭看的請求 system 開頭是「你在幫一個會操作電腦的 Bot 整理經驗」:用 `model-reply` 照這段字指定它存什麼。假模型一輪只叫一個工具,五步要在它做事時插話(每步 `sleep 4`,參數不同:一樣的參數做 3 次會被擋)。 - **做五步、學會**(covers `replay-learn`、`replay-steps`):指令:`$CTL model-reply 整理經驗 '{"save":true,"name":"記一筆","description":"在 log.txt 記一筆","instructions":"用 shell 在 log.txt 加一行。注意:一次一行。","replay":[9],"blanks":{"第五筆":"內容"},"tool_issues":[]}' && $CTL phone send '記五筆 [[call shell {"command":"sleep 4; echo 1"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 1' && $CTL phone send '[[call shell {"command":"sleep 4; echo 2"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 2' && $CTL phone send '[[call shell {"command":"sleep 4; echo 3"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 3' && $CTL phone send '[[call shell {"command":"sleep 4; echo 4"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 4' && $CTL phone send '[[call shell {"command":"echo 第五筆 >> log.txt"}]]' && $CTL phone wait-text '學會了新做法「記一筆」' --in '#msgs' 60 && $CTL phone shot replay-learned && $CTL model 'select(.rule) | .user_full | split(":\n- ")[0]' && $CTL state '.skills[] | select(.name == "記一筆") | .steps'`。看到:一輪五個「執行指令」,回覆下面「(學會了新做法「記一筆」,下次做這件事會照著做。)」;回頭看的請求列了每一步(插話也各佔一號,第五步是 9)和「已經有的技能」;技能只留那一步,「第五筆」變成 `{{內容}}`。 -- **重播、填空格**(covers `replay-steps`):先不給空格,再給;再看設定 › 整合 的清單。指令:`$CTL phone send '[[call replay_skill {"name":"記一筆"}]]' && $CTL phone wait-text '「記一筆」每次要填:內容' --in '#msgs' && $CTL phone send '[[call replay_skill {"name":"記一筆","values":{"內容":"重播的一筆"}}]]' && $CTL phone wait-text '重播「記一筆」做完了' --in '#msgs' && $CTL phone shot replay-run && $CTL botfile log.txt && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.via | test("重播")) | .tools[].detail]' && $CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '可重播 1 步' --in '#list'`。看到:第一次「「記一筆」每次要填:內容。用 values…」;第二次(電腦版「正在照技能重做:記一筆」)「執行指令 echo 重播的一筆 >> log.txt」沒經過模型(那一則標「fake-model(重播)」),回覆帶「(重播「記一筆」做完了,共 1 步。…)」;log.txt 多一行「重播的一筆」;清單裡記一筆標「可重播 1 步」。 +- **重播、填空格**(covers `replay-steps`):先不給空格,再給;再看設定 › 整合 的清單。指令:`$CTL phone send '[[call replay_skill {"name":"記一筆"}]]' && $CTL phone wait-text '「記一筆」每次要填:內容' --in '#msgs' && $CTL phone send '[[call replay_skill {"name":"記一筆","values":{"內容":"重播的一筆"}}]]' && $CTL phone wait-text '重播「記一筆」做完了' --in '#msgs' && $CTL phone wait-text '重播技能' --in '#msgs' && $CTL phone shot replay-run && $CTL botfile log.txt && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.label == "重播技能") | .detail]' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.via | test("重播")) | .tools[].detail]' && $CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '可重播 1 步' --in '#list'`。看到:第一次「「記一筆」每次要填:內容。用 values…」;第二次(電腦版「正在照技能重做:記一筆」)「執行指令 echo 重播的一筆 >> log.txt」沒經過模型(那一則標「fake-model(重播)」),回覆帶「(重播「記一筆」做完了,共 1 步。…)」;兩次叫重播的那一步都寫「重播技能 「記一筆」」;log.txt 多一行「重播的一筆」;清單裡記一筆標「可重播 1 步」。 - **教我做(大腦那邊)**(covers `replay-teach`):做一回合,再送「教我做」選單送的同一個請求。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '寫教學 [[call shell {"command":"echo 教 >> teach.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("teach"))] | length == 1' && $CTL api POST /api/act/app '{"name":"skillify","args":{"prompt":"寫教學 [[call shell {\"command\":\"echo 教 >> teach.txt\"}]]"}}'`。看到:「已把「…」那一回合存成技能「…」(1 步可重播),…」。 - **教我做的選單**(covers `replay-teach`):指令:走不到——選單要長按自己的訊息,ctl phone 沒有長按或右鍵。看到:最接近的真路是上一步(同一個請求)。 - **網站地圖**(covers `replay-map`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。 diff --git a/docs/feature-map/routines.md b/docs/feature-map/routines.md index 75d31b4..861fa65 100644 --- a/docs/feature-map/routines.md +++ b/docs/feature-map/routines.md @@ -30,7 +30,7 @@ Bot 照排程(每天、每週、每月、只一次)或某件事發生時(P - **建三條**(covers `routines-schedule`、`routines-target`):首頁「例行任務」›「新增例行任務」建一條每天的;建一個 Bot「同事」,在 Bot 1 的聊天請它建兩條要送 1 則的。指令:`$CTL phone click '[data-q="routines"]' && $CTL phone click '#rt-new' && $CTL phone type '#rt-title' 早報 && $CTL phone type '#rt-prompt' 整理重點 && $CTL phone click '#rt-ok' && $CTL phone wait-text '每天 09:00' --in '#list' && $CTL phone open --listed && $CTL phone click '#b-newbot' && $CTL phone click '#sheet-in .opt' --text '建立 Bot' && $CTL phone type '#ask-in' 同事 && $CTL phone click '#ask-ok' && $CTL phone wait-text 同事 --in '#isl-name' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call create_routine {"title":"回覆","prompt":"回一則","schedule":{"frequency":"weekly","daysOfWeek":["MO","WE"],"time":"10:00"},"target_sends":1}]]' && $CTL phone wait-text '已建立例行任務 #2' --in '#msgs' && $CTL phone send '[[call create_routine {"title":"打招呼","prompt":"跟同事說早安","schedule":{"frequency":"monthly","monthDay":1,"time":"08:00"},"target_sends":1}]]' && $CTL phone wait-text '已建立例行任務 #3' --in '#msgs' && $CTL api GET /api/bots/1/detail --jq '[.routines[] | "\(.title) \(.repeat) \(.when) \(.target)"]'`。看到:「每天 09:00 · 下次 …」;「已建立例行任務 #2 「回覆」:每週…」;三條的排程,後兩條「完成條件:送出 1 則」。 - **立即執行、紀錄**(covers `routines-now`、`routines-runs`、`routines-fresh`):點「早報」›「立即執行」,重新整理再點開。指令:`$CTL phone open --listed && $CTL phone click '[data-q="routines"]' && $CTL phone click '[data-rt="1:1"]' && $CTL phone click '#sheet-in .opt' --text 立即執行 && $CTL wait-api /api/bots/1/detail '.routines[0].runs[0].line | test("完成")' && $CTL phone open --listed && $CTL phone click '[data-q="routines"]' && $CTL phone click '[data-rt="1:1"]' && $CTL phone wait-text 最近執行 --in '#sheet-in' && $CTL phone shot routines-run && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.wake) | .text]'`。看到:Bot 1 收到「[例行任務]「早報」時間到了:整理重點」;「最近執行」一行「…完成:FAKE-MODEL 回答:…」、「上次 今天 …」。 - **不到數算失敗、兩次就暫停、繼續**(covers `routines-target`、`routines-pause`、`routines-carry`、`routines-runs`):「回覆」立即執行兩次,再按「繼續」。指令:`$CTL phone click '[data-back]' && $CTL api POST /api/act/app '{"name":"run_routine_now","args":{"id":2},"bot":1}' && $CTL wait-api /api/bots/1/detail '.routines[1].runs[0].bad' && $CTL api POST /api/act/app '{"name":"run_routine_now","args":{"id":2},"bot":1}' && $CTL wait-api /api/bots/1/detail '.routines[1].paused' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text '連續 2 次失敗,AnyBot 先暫停了' --in '#msgs' && $CTL phone click '#island' && $CTL phone click '[data-tab="routines"]' && $CTL phone wait-text 打招呼 --in '#details' && $CTL wait-api /api/bots/1/detail '.routines | length == 3' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.wake) | .text][-1]' && $CTL phone open --listed && $CTL phone click '[data-q="routines"]' && $CTL phone click '[data-rt="1:2"]' && $CTL phone wait-text '只送出 0/1 則(系統計數)' --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text 繼續 && $CTL wait-api /api/bots/1/detail '.routines[1] | (.paused | not) and .paused_why == ""'`。看到:兩次都是「失敗:只送出 0/1 則(系統計數):…」;第二次的任務訊息多「(上一次執行沒有成功:只送出 0/1 則…)」;聊天「例行任務「回覆」連續 2 次失敗,AnyBot 先暫停了。…按繼續。」;詳細資訊的「例行任務」有三條;按繼續後不再暫停、原因清掉。 -- **送到了、送出證據**(covers `routines-target`、`routines-runs`):「打招呼」立即執行,它傳訊息給同事。指令:`$CTL model-reply '「打招呼」時間到了' '[[call message_bot {"bot":"同事","text":"早安"}]] 送了' && $CTL api POST /api/act/app '{"name":"run_routine_now","args":{"id":3},"bot":1}' && $CTL wait-api /api/bots/1/detail '.routines[2].runs[0].line | test("完成")' && $CTL api GET /api/bots/1/detail --jq '.routines[2].runs[0]' && $CTL api GET /api/bots/2 --jq '[.messages[].text]'`。看到:「完成(1 步,系統記到送出 1 次):送了」,送出證據一行(message_bot…);同事收到「[來自 Bot]「驗證小幫手」:早安」。 +- **送到了、送出證據**(covers `routines-target`、`routines-runs`):「打招呼」立即執行,它傳訊息給同事。指令:`$CTL model-reply '「打招呼」時間到了' '[[call message_bot {"bot":"同事","text":"早安"}]] 送了' && $CTL api POST /api/act/app '{"name":"run_routine_now","args":{"id":3},"bot":1}' && $CTL wait-api /api/bots/1/detail '.routines[2].runs[0].line | test("完成")' && $CTL api GET /api/bots/1/detail --jq '.routines[2].runs[0]' && $CTL api GET /api/bots/2 --jq '[.messages[].text]'`。看到:「完成(1 步,系統記到送出 1 次):送了」,送出證據一行「傳訊息給其他 Bot 給 同事:早安」(照步驟的名字寫,不是 message_bot);同事收到「[來自 Bot]「驗證小幫手」:早安」。 - **桌面的例行任務視窗**(covers `routines-runs`、`routines-now`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot routines ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=panel && ABV_ALLOW_WINDOW=1 $CTL desktop-shot routines-demo ANYBOT_SHOT_VIEW=routines`(第二張是示範資料:真資料的截圖開不了例行任務視窗)。看到:右側面板「例行任務」列出這次建的(標題、時間或「已暫停」);示範視窗只有一張「AI 新聞早報」卡——示範資料沒有暫停原因、完成條件、執行紀錄,這三樣靠上面的步驟和 `cargo test routines::`。 - **事件觸發**(covers `routines-trigger`):指令:走不到——GitHub、Slack…要真的帳號;webhook 聽在 127.0.0.1:8792 起,ctl 沒有打它的指令(使用者真的 AnyBot 也可能在 8792)。看到:最接近的真路是 `create_routine` 帶 trigger 建得起來、沒有「下次執行時間」,和自動測試。 - 自動測試:`cargo test routines::`、`cargo test appctl::`、`cargo test a_routines_runs_are_kept_and_two_failures_pause_it`、`cargo test a_routine_run_starts_fresh_for_the_model`、`cargo test triggers::`、`cargo test garden::`。 diff --git a/mobile/index.html b/mobile/index.html index 0409585..dc69ebd 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1132,6 +1132,7 @@ function apply(v) { else loadChat(); } else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, true); + settingsChanged(); } // ---------- home: the sidebar ---------- @@ -1461,9 +1462,9 @@ function renderMsgs() { return; } if (m.role === "user") { - const goal = m.wake && String(m.text || "").startsWith(GOAL_TAG); - const tag = goal ? `
${ic("target", 12)} 目標
` : m.wake ? `
${ic("alarm-clock", 12)} ${esc(m.via || "例行任務")}
` : ""; - if (goal) m = {...m, text: m.text.slice(GOAL_TAG.length)}; + const wt = m.wake ? wakeTag(m.text) : null; + const tag = wt ? `
${ic(wt.icon, 12)} ${esc(wt.label)}
` : ""; + if (wt) m = {...m, text: wt.body}; const q = String(m.text || "").match(/^((?:>.*\n?)+)\n*([\s\S]*)$/); const text = q ? q[2] : m.text; const quote = q ? `
${esc(plain(q[1].replace(/^> ?/gm, "")).replace(/\|/g, " ").replace(/\s+/g, " ").trim())}
` : ""; @@ -1715,7 +1716,16 @@ input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false}; /** AnyBot's own / commands (goal.rs on the brain). */ const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "rewind", description: "退回:把 Bot 改的檔案和對話退回之前說的某一句"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; -const GOAL_TAG = "[目標]"; +/** What woke the bot, from the tag its message starts with (app::chat_ui::wake_tag on the + * desktop): [tag, icon, label], and the words after it. 監看's tag carries the command's number, so + * its words stay whole. (Every wake used to say 例行任務 — a 監看's lines, a colleague's message.) */ +const WAKE_TAGS = [["[目標]", "target", "目標"], ["[例行任務]", "alarm-clock", "例行任務"], ["[觸發]", "zap", "觸發"], ["[訊息管道]", "message", "訊息管道"], ["[來自 Bot]", "bot", "來自其他 Bot"], ["⏰ ", "alarm-clock", "例行任務"], ["⚡ ", "zap", "觸發"], ["💬 ", "message", "訊息管道"], ["📨 ", "bot", "來自其他 Bot"]]; +function wakeTag(text) { + const t = String(text || ""); + for (const [tag, icon, label] of WAKE_TAGS) if (t.startsWith(tag)) return {icon, label, body: t.slice(tag.length)}; + if (t.startsWith("[監看 ")) return {icon: "eye", label: "監看", body: t}; + return null; +} /** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name * contains it, then description. None once a space ends the name, or while the bot works. */ function slashHits() { @@ -2295,9 +2305,23 @@ async function renderBotset(id) { // ---------- 設定 and the other lists ---------- async function loadSettings() { if (!owner()) return null; + S.settingsOld = false; try { S.settings = await api(base() + "api/settings"); } catch (e) { toast(e.message); } return S.settings; } +const SETTINGS_PAGES = ["computers", "settings", "general", "models", "perms", "integrations", "vault", "account", "updates"]; +/** Something changed on the computer (the state's version moved): the settings read before are + * old — the page showing them is read again now, any other the next time it opens. (They were + * read once: after /always-approve filled the 一律詢問 rules, 權限 still said 還沒有規則.) */ +async function settingsChanged() { + S.settingsOld = true; + const t = cur(); + if (t.v !== "list" || !SETTINGS_PAGES.includes(t.arg.kind)) return; + if (S.settingsLoading) { S.settingsAgain = true; return; } + S.settingsLoading = true; + try { do { S.settingsAgain = false; await loadSettings(); } while (S.settingsAgain); } finally { S.settingsLoading = false; } + if (cur().v === "list" && cur().arg.kind === t.arg.kind) drawSettings(t.arg.kind, true); +} let listTimer = null; function stopListTimer() { clearInterval(listTimer); listTimer = null; } const TITLES = {routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"}; @@ -2309,8 +2333,8 @@ async function renderList(arg) { stopListTimer(); if (kind === "routines") return listRoutines(el); if (kind === "pages") return listPages(el); - if (["computers", "settings", "general", "models", "perms", "integrations", "vault", "account", "updates"].includes(kind)) { - if (!S.settings) { el.innerHTML = `
載入中…
`; await loadSettings(); } + if (SETTINGS_PAGES.includes(kind)) { + if (!S.settings || S.settingsOld) { if (!S.settings) el.innerHTML = `
載入中…
`; await loadSettings(); } if (cur().v !== "list" || cur().arg.kind !== kind) return; drawSettings(kind); // Things that change on their own (Bot 的電腦 updating, a channel connecting): look again. @@ -2424,7 +2448,9 @@ function computersHtml(st) { const rt = box.runtime === "runsc" ? "強隔離(gVisor)" : "標準"; const running_rt = f.running ? (f.running === "runsc" ? "強隔離" : "標準") : ""; const steps = f.steps && f.steps.n ? `平均每步 ${Math.round(f.steps.total_ms / f.steps.n)} ms(${f.steps.n} 步)` : ""; - h += group("", item({icon: "download", k: "更新 Bot 的電腦", v: f.update == null ? "檢查中…" : f.update ? `有新版(v${box.version})。檔案和登入都會留著` : `已是 v${box.version}`, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) + + // (Not looked at yet: undefined. Nothing to look at — no Docker, no box yet: null.) + const upd = f.update === undefined ? "檢查中…" : f.update === null ? (box.available ? `還沒建立(建立時是 v${box.version})` : "沒有 Docker,現在沒有這台電腦") : f.update ? `有新版(v${box.version})。檔案和登入都會留著` : `已是 v${box.version}`; + h += group("", item({icon: "download", k: "更新 Bot 的電腦", v: upd, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) + item({icon: "alarm-clock", k: "自動更新", r: box.auto_update || "關", tap: isOwner() ? 1 : 0, data: 'data-bx="auto"'}) + item({icon: "shield", k: "容器隔離", v: running_rt && running_rt !== rt.slice(0, 2) ? `目前是${running_rt};按更新後改成${rt}` : (f.gvisor === false && box.runtime !== "runsc" ? "這台 Docker 主機沒有 gVisor" : ""), r: rt, tap: isOwner() && (f.gvisor || box.runtime === "runsc") ? 1 : 0, data: 'data-bx="runtime"'}) + item({icon: "hard-drive", k: "上次快照", r: box.snapshot || "還沒有"}) + diff --git a/src/agent.rs b/src/agent.rs index e0e5178..18328aa 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -421,6 +421,16 @@ static JOB_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new /// A call's arguments with the job's name added: the browser keeps each job's tabs apart by it /// (also on another computer's browser, which gets the arguments as they are). +/// A browser step's arguments marked as using its profile for this step only (botbrowser::open +/// doesn't make it the current one): a 支線's. +fn this_step_only(args: &str) -> String { + let mut v = tools::args_of(args); + if let Some(o) = v.as_object_mut() { + o.insert("_this_step_only".into(), serde_json::json!(true)); + } + v.to_string() +} + fn with_job(args: &str, job: &str) -> String { let mut v: serde_json::Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or_else(|_| serde_json::json!({})); if let Some(o) = v.as_object_mut() { @@ -481,6 +491,10 @@ enum BrowserAt { Device(String), } +/// Where a browser step opens when none of the bot's computers has a browser (browser_place's +/// empty name): AnyBot's own browser, on the computer AnyBot runs on. +const BROWSER_HERE: &str = "執行 AnyBot 的這台電腦"; + /// Whose browser a browser step uses: the computer it names, else the bot's chosen computer; a /// computer without a browser (a server, an SSH one) hands it to the person's computer. /// A computer the person NAMED never gets handed to another one silently — a step meant for the @@ -1553,6 +1567,15 @@ const UNTRUSTED_BROWSER: &str = "被安全規則擋下:這則訊息是別人 /// Why a step isn't run for a turn whose message came from someone other than the person: the /// browsers (theirs are logged in as the person) and the sent book. None: it may run. +/// What a 支線 isn't let do in a step (its app actions are refused on the window's side, +/// appctl::changes_settings): add or switch AnyBot's browser profiles — the choice is every +/// bot's, kept on this computer. Listing them is fine. +fn branch_refusal(job: &Job, name: &str, args: &str) -> Option<&'static str> { + let v = tools::args_of(args); + let changes = name == "browser_profiles" && (!v["name"].as_str().unwrap_or("").trim().is_empty() || !matches!(v["action"].as_str().unwrap_or("").trim(), "" | "list")); + (job.home != 0 && changes).then_some(crate::appctl::BRANCH_NO_SETTINGS) +} + fn untrusted_refusal(job: &Job, name: &str) -> Option<&'static str> { // (The browser ability: every browser action, the vault's fills, the sent book.) (job.untrusted && crate::profile::ability_of(name) == Some("browser")).then_some(UNTRUSTED_BROWSER) @@ -1665,7 +1688,7 @@ fn after_send(gate: &Gate, call: &crate::model::ToolCall, args: &str, bot: &str, (format!("\n{line}{note}"), proof) } Gate::Unsure if crate::evidence::sends(call) => { - let what = format!("{} {}", call.name, tools::describe(&call.name, &call.args)).trim().to_string(); + let what = crate::evidence::step_line(&call.name, &call.args); (format!("\n{}(那台電腦的 AnyBot 比較舊,系統沒辦法確認送到哪裡)", crate::publish::SENT_MARK), format!("{what}(沒有確認)")) } _ => (String::new(), String::new()), @@ -3570,6 +3593,9 @@ echo 'done送出了' > done.html; (setsid pyt let v: serde_json::Value = serde_json::from_str(&a).unwrap(); assert_eq!((v["_job"].as_str(), v["url"].as_str(), v["profile"].as_str()), (Some("6-1-1"), Some("https://example.com"), Some("工作"))); assert_eq!(serde_json::from_str::(&with_job("", "j")).unwrap()["_job"], "j"); + // A 支線's browser step uses the profile it names for that step only. + let marked: serde_json::Value = serde_json::from_str(&this_step_only(&with_job(r#"{"url":"https://example.com","profile":"工作"}"#, "j"))).unwrap(); + assert_eq!((marked["_this_step_only"].as_bool(), marked["profile"].as_str(), marked["_job"].as_str()), (Some(true), Some("工作"), Some("j"))); // Two jobs never share a name. assert_ne!(UsedBrowsers::new("b", 6, true).job, UsedBrowsers::new("b", 6, true).job); } @@ -3706,6 +3732,40 @@ echo 'done送出了' > done.html; (setsid pyt assert!(matches!(browser_place(&own, "browser_open", r#"{"url":"https://example.com"}"#), Ok((BrowserAt::Device(_), _)))); } + /// A local address asks first, and its card says where it would open: with no browser on + /// any of the bot's computers, AnyBot's own here (the card read 「(在 上)」). Answered no, + /// so no browser starts. + #[test] + fn a_local_address_card_says_where_it_would_open() { + let (port, _) = recording_model(vec![tool_delta("b", crate::browser::TOOL, serde_json::json!({"action": "open", "url": "http://127.0.0.1:9/"})), serde_json::json!({"content": "沒開"})]); + let own = "小幫手 的電腦"; + let job = Job { + req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "main".into(), system: String::new(), history: vec![Message::user("看一下本機的頁面")], tools: vec![crate::browser::tool(&serde_json::json!({"type": "string"}))], session: String::new(), effort: String::new() }, + computers: vec![tools::Target { name: own.into(), place: tools::Place::Sealed { root: std::env::temp_dir() } }], + default_computer: own.into(), + roles: tools::Roles { own: own.into(), person: None, server: false }, + close_browsers: false, + ..test_job() + }; + let (tx, rx) = channel(); + spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + let mut cards = vec![]; + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { + (_, StreamEvent::NeedApproval(a)) => { + cards.push(a.reason.clone()); + let _ = a.reply.send(ApprovalAnswer::Reject); + } + (_, StreamEvent::Done) => break, + (_, StreamEvent::Error(e)) => panic!("{e}"), + _ => {} + } + } + assert_eq!(cards.len(), 1, "{cards:?}"); + assert!(cards[0].starts_with("在瀏覽器開啟本機或內部網路網址:http://127.0.0.1:9/"), "{cards:?}"); + assert!(cards[0].ends_with(&format!("\n(在 {BROWSER_HERE} 上)")), "{cards:?}"); + } + #[test] fn cut_keeps_tool_pairs_and_recent_messages() { let mut h = vec![]; @@ -4487,7 +4547,7 @@ echo 'done送出了' > done.html; (setsid pyt assert_eq!(names.last(), Some(&"OnComputer")); assert_eq!(names.iter().collect::>().len(), names.len(), "{names:?}"); let pos = |n: &str| names.iter().position(|x| *x == n).unwrap(); - assert!(pos("Lacking") < pos("AppTool") && pos("Untrusted") < pos("SentLog") && pos("Untrusted") > pos("WaitAfterSend")); + assert!(pos("Lacking") < pos("AppTool") && pos("Untrusted") < pos("SentLog") && pos("Untrusted") > pos("WaitAfterSend") && pos("BranchLimits") < pos("InBotsBrowser")); let which = |job: &Job, name: &str, args: serde_json::Value| -> &'static str { let (mut history, mut grants, mut browsers) = (vec![], vec![], UsedBrowsers::new("t", 1, false)); let (mut b1, mut b2, mut b3, mut b4, mut changes, mut replay, mut plan_go) = (false, false, false, false, 0u32, None, None); @@ -4516,6 +4576,12 @@ echo 'done送出了' > done.html; (setsid pyt assert_eq!(which(&job, "shell", serde_json::json!({"command": "ls"})), "OnComputer"); let stranger = Job { untrusted: true, ..test_job() }; assert_eq!(which(&stranger, "browser_open", serde_json::json!({"url": "https://example.com"})), "Untrusted"); + // A 支線 lists the browser's profiles but doesn't add or switch them (every bot's choice). + let branch = Job { home: 7, ..test_job() }; + assert_eq!(which(&branch, "browser_profiles", serde_json::json!({"name": "工作"})), "BranchLimits"); + assert_eq!(which(&branch, "browser_profiles", serde_json::json!({"action": "use", "name": ""})), "BranchLimits"); + assert_eq!(which(&branch, "browser_profiles", serde_json::json!({})), "InBotsBrowser"); + assert_eq!(which(&job, "browser_profiles", serde_json::json!({"name": "工作"})), "InBotsBrowser"); assert_eq!(which(&stranger, "web_fetch", serde_json::json!({"url": "https://example.com"})), "InBotsBrowser"); let lacking = Job { lacks: vec!["admin".into()], ..test_job() }; assert_eq!(which(&lacking, "create_bot", serde_json::json!({})), "Lacking"); diff --git a/src/agent/steps.rs b/src/agent/steps.rs index ae2c5db..80bd55f 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -164,7 +164,7 @@ pub(super) trait TurnTool: Sync { /// In the order they are asked: the first that takes a call runs it (OnComputer takes all). pub(super) static TOOLS: &[&dyn TurnTool] = &[ - &BadAction, &Lacking, &SkillLimit, &ReplaySkill, &FeatureMap, &LookImage, &AppTool, &DemoStep, &WaitAfterSend, &Untrusted, &SentLog, &InBotsBrowser, &Handoff, &KeptResult, &PlanSubmit, &PlanUpdate, &AskCard, &ShowCard, &React, &SendFile, &OpenForPerson, &Phone, &PublishSite, &VaultList, &VaultFill, &ConnectorFind, &Connector, &OnComputer, + &BadAction, &Lacking, &SkillLimit, &ReplaySkill, &FeatureMap, &LookImage, &AppTool, &DemoStep, &WaitAfterSend, &Untrusted, &BranchLimits, &SentLog, &InBotsBrowser, &Handoff, &KeptResult, &PlanSubmit, &PlanUpdate, &AskCard, &ShowCard, &React, &SendFile, &OpenForPerson, &Phone, &PublishSite, &VaultList, &VaultFill, &ConnectorFind, &Connector, &OnComputer, ]; /// The tool that runs this step. @@ -473,6 +473,26 @@ impl TurnTool for Untrusted { } } +/// 支線: a step that would change what every bot uses (adding or switching a browser profile) — +/// refused, as its app actions are. +pub(super) struct BranchLimits; + +impl TurnTool for BranchLimits { + fn name(&self) -> &'static str { + "BranchLimits" + } + + fn takes(&self, s: &Step<'_>) -> bool { + branch_refusal(s.job, &s.call.name, &s.call.args).is_some() + } + + fn run(&self, s: &mut Step<'_>) -> Flow { + let Some(why) = branch_refusal(s.job, &s.call.name, &s.call.args) else { return Flow::Next }; + s.finish(why, ToolStatus::Denied, None); + Flow::Next + } +} + /// 已送帳本: what this brain saw go out, by account — read here, not on a page. pub(super) struct SentLog; @@ -558,7 +578,10 @@ impl TurnTool for InBotsBrowser { 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 })); + // (No name: none of the bot's computers has a browser, and AnyBot opens + // its own where it runs — the card read 「(在 上)」.) + let at = if on.is_empty() { BROWSER_HERE } else { on.as_str() }; + send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("在瀏覽器開啟本機或內部網路網址:{norm}\n(在 {at} 上)"), 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), @@ -706,6 +729,8 @@ impl TurnTool for InBotsBrowser { }); } let args = with_job(&call_args, &s.browsers.job); + // 支線: the profile it names is for this step; every bot's choice stays as it is. + let args = if job.home != 0 { this_step_only(&args) } else { args }; let (output, ok, img) = run_there(&call.name, &args); if ok { step_sent_at.set(Some(Instant::now())); diff --git a/src/app.rs b/src/app.rs index 9cc99f9..a1f9eed 100644 --- a/src/app.rs +++ b/src/app.rs @@ -45,6 +45,7 @@ mod memory_ui; mod goal_ui; mod context_ui; mod commands; +pub(crate) use commands::words_loosen; mod doctor_ui; mod plan_ui; mod mood_ui; @@ -320,6 +321,8 @@ pub struct App { /// their way to the brain) — shown at once, dimmed, until the chat has them: (words, when). sending: HashMap>, branch_live: Instant, + /// AnyBot is closing (on_exit): a turn it stops wasn't stopped by the person. + quitting: bool, /// 群組: how many members answered since the person last wrote (members @naming each other /// stop at MAX_GROUP_ANSWERS). group_spoken: HashMap, @@ -565,6 +568,7 @@ impl App { branch_checks: vec![], sending: HashMap::new(), branch_live: Instant::now(), + quitting: false, group_spoken: HashMap::new(), goal_due: vec![], goal_checking: Default::default(), @@ -3051,6 +3055,12 @@ impl App { continue; } if let StreamEvent::AppAction(call) = ev { + // 支線: changes no settings — not its own, another bot's or AnyBot's (said at + // once, with no card to allow). + if self.state.bot(id).is_some_and(|b| b.branch_of != 0) && appctl::changes_settings(&call.name, &call.args) { + let _ = call.reply.send((appctl::BRANCH_NO_SETTINGS.into(), false)); + continue; + } // 改自己的設定: the person sees exactly what changes and says yes first; a request // that can't be done says why at once. let ask = if call.name == "update_my_profile" { @@ -4005,13 +4015,13 @@ impl App { fn approval_body(&self, ui: &mut egui::Ui, bot: &Bot, big: bool) -> Option { let p = self.pal; let a = self.approvals.get(&bot.id)?; - let (tool, reason, grant, kind) = (a.tool.clone(), a.reason.clone(), a.grant.clone(), a.kind); + let (reason, grant, kind) = (a.reason.clone(), a.grant.clone(), a.kind); // "允許 the reference assistant 在 {targetMachineDisplay} 上使用 {app} 嗎?" (eQViQE): name the machine. let (reason, machine) = match reason.rsplit_once("\n(在 ") { Some((r, m)) => (r.to_string(), m.trim_end_matches(" 上)").to_string()), None => (reason.clone(), String::new()), }; - let what = if appctl::is_app_tool(&tool) { appctl::label(&tool) } else if crate::macapps::is_mac_tool(&tool) { crate::macapps::label(&tool) } else if crate::computer::is_computer_tool(&tool) { crate::computer::label(&tool) } else if web::is_web_tool(&tool) { web::label(&tool) } else { tools::label(&tool) }; + let what = remote_ui::card_what(bot, a); let title = match kind { ApprovalKind::EnableTools => format!("允許 {} 使用電腦工具嗎?", bot.name), // Hd1KB+: 允許…在這台電腦上執行任務,而不只是在它自己的電腦上 @@ -6488,6 +6498,9 @@ impl App { let json = opts.json; let line = |v: serde_json::Value| println!("{v}"); let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0); + // One of AnyBot's own commands (「/always-approve」, 「/usage」…): done without a turn. + let command = app.command_for(id, &opts.text).is_some(); + let turn_before = app.state.bot(id).and_then(|b| b.last_turn.as_ref()).map(|t| t.turn_id.clone()); app.drafts.insert(id, opts.text.clone()); app.send(ctx, id); let t0 = Instant::now(); @@ -6570,8 +6583,12 @@ impl App { Role::Tool => println!(" ↳ {}{}", if m.images.is_empty() { "" } else { "[附截圖] " }, clip(&m.text, if full { 4000 } else { 400 })), } } - let outcome = app.state.bot(id).and_then(|b| b.last_turn.as_ref()).map(|t| t.outcome); - let code = ask_exit_code(INTERRUPTED.load(Ordering::SeqCst), timed_out, outcome); + let last = app.state.bot(id).and_then(|b| b.last_turn.as_ref()); + let outcome = last.map(|t| t.outcome); + // (A command that started no turn is done when it has said its piece: it used to end + // 「沒有做完」 with code 1, from no turn at all or an earlier one's.) + let no_turn = command && last.map(|t| t.turn_id.clone()) == turn_before; + let code = if no_turn && !timed_out && !INTERRUPTED.load(Ordering::SeqCst) { 0 } else { ask_exit_code(INTERRUPTED.load(Ordering::SeqCst), timed_out, outcome) }; let answer = msgs.iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()).map(|m| m.text.clone()).unwrap_or_default(); if json { line(serde_json::json!({"type": "done", "ok": code == 0, "code": code, "steps": steps, "secs": secs, "timed_out": timed_out, "answer": crate::secrets::mask(&answer)})); @@ -6670,6 +6687,29 @@ impl App { } } +impl App { + /// Closing: a turn mid-reply ends as cancelled, so it isn't left looking stuck, and a 支線 + /// that hadn't started (checking for a clash, waiting for the main line) ends too — saying + /// AnyBot closed, not that the person stopped it. (On a screen of a brain the bots keep + /// working there.) + fn end_turns_for_quit(&mut self) { + if self.mir.on { + self.streams.clear(); + return; + } + self.quitting = true; + let ids: Vec = self.streams.keys().copied().collect(); + for id in ids { + self.stop(id); + } + for r in self.state.bots.iter_mut().flat_map(|b| b.branches.iter_mut()).filter(|r| r.state.open()) { + r.state = crate::model::BranchState::Stopped; + r.note = branch::QUIT_NOTE.into(); + r.doing.clear(); + } + } +} + impl eframe::App for App { /// Screenshot mode only: ANYBOT_SHOT_CLICK="x,y@frame[;x,y@frame…][:right]" clicks there at that /// frame (to check buttons really respond). @@ -6923,15 +6963,7 @@ impl eframe::App for App { } fn on_exit(&mut self) { - // Closing mid-reply ends that turn as cancelled, so it isn't left looking stuck. - // (On a screen of a brain the bots keep working there.) - if self.mir.on { - self.streams.clear(); - } - let ids: Vec = self.streams.keys().copied().collect(); - for id in ids { - self.stop(id); - } + self.end_turns_for_quit(); tools::stop_all(); crate::cloudbox::shutdown(); // (The connectors' programs too: they were left running after the window closed.) @@ -7331,7 +7363,7 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu } // 支線: a copy of the bot doing one more thing alongside its main line. if b.branch_of != 0 { - s.push_str("\n\n你現在是一條支線:使用者用 /btw 開的分身,帶著同一段對話和記憶,跟主線(你的本尊)同時做對話最後交代的那件事。只做那件事,不要接手或重做主線正在做的事。做完用一段話寫清楚結果,它會原封不動送回主線的聊天。要使用者核准的步驟一樣會問他。在「Bot 的電腦」上你有自己的暫時螢幕和瀏覽器(登入從主線的瀏覽器複製過來,支線結束就關掉),不會跟主線搶,但看不到主線開著的網頁,要用就自己打開。在使用者的電腦上,同一個螢幕主線或別的 Bot 正在用時,那一步會被擋下:先做不用螢幕的部分、改用別台電腦,或晚點再試。不能再開支線,也不能改自己的設定。"); + s.push_str("\n\n你現在是一條支線:使用者用 /btw 開的分身,帶著同一段對話和記憶,跟主線(你的本尊)同時做對話最後交代的那件事。只做那件事,不要接手或重做主線正在做的事。做完用一段話寫清楚結果,它會原封不動送回主線的聊天。要使用者核准的步驟一樣會問他。在「Bot 的電腦」上你有自己的暫時螢幕和瀏覽器(登入從主線的瀏覽器複製過來,支線結束就關掉),不會跟主線搶,但看不到主線開著的網頁,要用就自己打開。在使用者的電腦上,同一個螢幕主線或別的 Bot 正在用時,那一步會被擋下:先做不用螢幕的部分、改用別台電腦,或晚點再試。不能再開支線,也不能動大家共用的東西:改任何 Bot 或 AnyBot 的設定、建立 Bot、建立或整理群組、刪除或安裝技能、換掉技能庫裡已經有的技能(存新的可以)、改連接器或 hook、新增或切換瀏覽器設定檔,都會被擋下;需要做這些,就在結果裡寫給主線。"); } // 個人檔案: what it is good at and what it leaves to others; then who the others are. // (Its soul — the 指示 — comes last, where it weighs most.) @@ -9020,6 +9052,70 @@ mod tests { assert!(app.state.bot(id).is_none(), "gone when done"); } + /// A 支線 changes no settings: update_bot (itself, which renamed the main bot once its card + /// was allowed) is refused at once — no card, the name stays — and so are the others. + #[test] + fn a_branch_changes_no_settings() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-btw-settings.png"))); + let main = app.state.bots[0].id; + let name = app.state.bots[0].name.clone(); + let call = |id: &str, name: &str, args: serde_json::Value| serde_json::json!({"tool_calls": [{"index": 0, "id": id, "function": {"name": name, "arguments": args.to_string()}}]}); + scripted_bot(&mut app, main, vec![call("u1", "update_bot", serde_json::json!({"name": "支線改的名字"})), serde_json::json!({"content": "沒改成。"})]); + app.drafts.insert(main, "/btw 幫自己改個名".into()); + app.send(&ctx, main); + let id = app.state.bot(main).unwrap().branches[0].id; + assert!(pump(&mut app, &ctx, |x| !x.streams.contains_key(&id)), "no card holds the branch up"); + assert!(!app.approvals.contains_key(&id) && !app.app_pending.contains_key(&id)); + let m = app.state.bot(main).unwrap(); + assert_eq!(m.name, name); + assert!(m.branches[0].log.iter().any(|l| l.starts_with('✗') && l.contains(appctl::label("update_bot"))), "{:?}", m.branches[0].log); + let refused_ones = ["update_settings", "teach_skill", "create_bot", "create_group", "move_to_group", "rename_group", "delete_group", "delete_skill", "skill_install"]; + for tool in refused_ones { + assert!(appctl::changes_settings(tool, r#"{"url":"builtin:pptx"}"#), "{tool}"); + } + for (tool, args, refused) in [(crate::mcp::MANAGE_TOOL, r#"{"action":"add","name":"x"}"#, true), (crate::mcp::MANAGE_TOOL, r#"{"action":" Remove "}"#, true), (crate::mcp::MANAGE_TOOL, r#"{"action":"list"}"#, false), (crate::mcp::MANAGE_TOOL, r#"{"action":"reconnect"}"#, false), (crate::hooks::MANAGE_TOOL, r#"{"action":"remove"}"#, true), (crate::hooks::MANAGE_TOOL, r#"{"action":"list"}"#, false), (crate::chatgpt::TOOL, r#"{"action":"logout"}"#, false), ("create_routine", "{}", false), ("remember", "{}", false), ("save_skill", "{}", false), ("skillify", "{}", false)] { + assert_eq!(appctl::changes_settings(tool, args), refused, "{tool} {args}"); + } + // A new skill from a 支線 is the main bot's; one already in the library stays as it was. + app.state.skills.push(crate::memory::Skill { name: "週報(測試)".into(), instructions: "原本的做法".into(), ..Default::default() }); + let mut br = app.state.bot(main).unwrap().clone(); + br.id = 9200; + br.branch_of = main; + app.state.branch_bots.push(br); + let out = appctl::apply(&mut app.state, 9200, "save_skill", &serde_json::json!({"name": "週報(測試)", "instructions": "支線改的做法"}).to_string()); + assert!(!out.ok && out.text.contains("支線不能換掉"), "{}", out.text); + // Nor by changing the case (the skill's folder is found that way, and it was overwritten). + app.state.skills.push(crate::memory::Skill { name: "Weekly Report".into(), instructions: "原本的做法".into(), ..Default::default() }); + let out = appctl::apply(&mut app.state, 9200, "save_skill", &serde_json::json!({"name": "weekly report ", "instructions": "支線改的做法"}).to_string()); + assert!(!out.ok && out.text.contains("支線不能換掉"), "{}", out.text); + assert_eq!(app.state.skills.iter().find(|k| k.name == "週報(測試)").map(|k| k.instructions.as_str()), Some("原本的做法")); + } + + /// Closing AnyBot ends a working 支線 and one still waiting with 「AnyBot 關掉了…」; 「被停止了」 + /// is the person pressing stop (closing used to say that too). + #[test] + fn closing_anybot_says_so_on_its_open_branches() { + use crate::model::{Branch, BranchState}; + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-btw-quit.png"))); + let main = app.state.bots[0].id; + for id in [9100, 9101] { + let mut br = app.state.bot(main).unwrap().clone(); + br.id = id; + br.branch_of = main; + app.state.branch_bots.push(br); + app.state.bot_mut(main).unwrap().branches.push(Branch { id, task: format!("查 {id}"), state: BranchState::Running, ..Default::default() }); + fake_turn(&mut app, id); + } + app.state.bot_mut(main).unwrap().branches.push(Branch { id: 9102, task: "等主線".into(), state: BranchState::Waiting, ..Default::default() }); + app.stop(9100); + app.end_turns_for_quit(); + let notes: Vec<(BranchState, String)> = app.state.bot(main).unwrap().branches.iter().filter(|r| r.id >= 9100).map(|r| (r.state, r.note.clone())).collect(); + assert_eq!(notes, vec![(BranchState::Stopped, "被停止了".to_string()), (BranchState::Stopped, branch::QUIT_NOTE.to_string()), (BranchState::Stopped, branch::QUIT_NOTE.to_string())]); + assert!(app.streams.is_empty() && app.state.branch_bots.is_empty()); + } + /// The main line at work: a clash waits for its turn to end; no clash starts at once, and /// its report goes into the running turn. #[test] @@ -9274,6 +9370,13 @@ mod tests { assert_eq!(lines.len(), 4, "{lines:?}"); // Every skill again: back to "all of them". assert!(b.skills.is_none()); + // The quick model's settings in the editor's words (the card read 「(空) → 「off」」). + app.state.bot_mut(id).unwrap().step_model.clear(); + let (_, _, lines) = app.profile_change(id, r#"{"step_model":"off"}"#).unwrap(); + assert_eq!(lines, vec!["執行步驟用的模型:自動 → 不分開".to_string()]); + app.state.bot_mut(id).unwrap().step_model = "off".into(); + let (_, _, lines) = app.profile_change(id, r#"{"step_model":"grok-mini"}"#).unwrap(); + assert_eq!(lines, vec!["執行步驟用的模型:不分開 → grok-mini".to_string()]); } #[test] diff --git a/src/app/branch.rs b/src/app/branch.rs index a788035..1ac24ab 100644 --- a/src/app/branch.rs +++ b/src/app/branch.rs @@ -28,6 +28,9 @@ pub(super) const REPORT_TAG: &str = "〔支線回報〕"; /// Finished branches a bot keeps the record of (the newest). const KEEP_FINISHED: usize = 20; +/// Why a 支線 ended when AnyBot was closed (a clean shutdown; after a crash the restart says it). +pub(super) const QUIT_NOTE: &str = "AnyBot 關掉了,這條支線停了"; + /// Most branches one bot has open at once. pub(super) const MAX_BRANCHES: usize = 3; /// How often a running branch's card is brought up to date. @@ -308,6 +311,8 @@ impl App { log.truncate(120); let (state, note) = match outcome { TurnOutcome::Success => (BranchState::Done, String::new()), + // (Closing AnyBot stops every turn: that isn't the person stopping this one.) + TurnOutcome::Cancelled if self.quitting => (BranchState::Stopped, QUIT_NOTE.to_string()), TurnOutcome::Cancelled => (BranchState::Stopped, "被停止了".to_string()), _ => (BranchState::Failed, if said.is_empty() { "出錯了".to_string() } else { said.chars().take(300).collect() }), }; diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index d361de7..282ca13 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -1165,11 +1165,16 @@ pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> { SLASH_COMMANDS.iter().copied().filter(|(n, _)| n.starts_with(&q)).collect() } +/// The tags a woken message starts with: (tag, icon, label). The emoji forms are what older chats +/// were saved with. (The phone has the same table: mobile/index.html WAKE_TAGS.) +const WAKE_TAGS: [(&str, crate::icons::Icon, &str); 9] = { + use crate::icons::Icon; + [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] +}; + /// "[例行任務]…" → (icon, label) and the words after the tag. pub fn wake_tag(text: &str) -> (Option<(crate::icons::Icon, &'static str)>, &str) { - use crate::icons::Icon; - // (The emoji forms are what older chats were saved with.) - for (tag, icon, label) in [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] { + for (tag, icon, label) in WAKE_TAGS { if let Some(rest) = text.strip_prefix(tag) { return (Some((icon, label)), rest); } @@ -1186,6 +1191,17 @@ fn hover_icon(ui: &mut egui::Ui, icon: crate::icons::Icon, p: Palette) -> egui:: mod tests { use super::*; + /// The phone tags a woken message from the same table as the window (its fallback used to + /// call every wake — a 監看's lines too — 例行任務). + #[test] + fn the_phone_tags_woken_messages_like_the_window() { + let page = include_str!("../../mobile/index.html"); + for (tag, _, label) in WAKE_TAGS { + assert!(page.contains(&format!("[\"{tag}\", \"")) && page.contains(&format!("\", \"{label}\"]")), "{tag} {label}"); + } + assert!(!page.contains("m.via || \"例行任務\"")); + } + #[test] fn phrases_follow_what_it_does() { let say = |name: &str, args: &str| status_phrase(Some((name, args)), None, false, false, false, 0); diff --git a/src/app/commands.rs b/src/app/commands.rs index 9a9dccf..23591d4 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -24,6 +24,25 @@ pub(super) enum AppCommand { Rewind(Result), } +impl AppCommand { + /// Whether carrying it out lets the bots do more without asking — what a phone on a direct + /// connection may not type (remote.rs refuses those words before they reach the app; it used + /// to let 「/always-approve」 turn 直接操作 and 一律放行 on). Every command is named here, so a + /// new one has to be decided. + fn loosens(&self) -> bool { + match self { + AppCommand::Always(crate::always::Command::On) => true, + AppCommand::Always(crate::always::Command::Off | crate::always::Command::Status) => false, + AppCommand::Btw(_) | AppCommand::Goal(_) | AppCommand::Plan(_) | AppCommand::Usage | AppCommand::Context | AppCommand::Compact | AppCommand::Doctor | AppCommand::Fork(_) | AppCommand::Rewind(_) => false, + } + } +} + +/// Words that, sent in a chat, are one of AnyBot's commands that would loosen a guard. +pub(crate) fn words_loosen(text: &str) -> bool { + app_command(text).is_some_and(|c| c.loosens()) +} + /// How many of the person's messages /rewind offers. const REWIND_POINTS: usize = 10; @@ -228,6 +247,17 @@ mod tests { assert!(app_command("你好").is_none() && app_command("/Users/me/a.txt").is_none()); } + /// The commands that loosen a guard — what a direct connection may not type. + #[test] + fn turning_always_approve_on_is_the_command_that_loosens() { + for on in ["/always-approve", "/yolo", " /always-approve on ", "/yolo 開", "/always-approve 打開"] { + assert!(words_loosen(on), "{on}"); + } + for not in ["/always-approve off", "/yolo 關", "/always-approve status", "/always-approve 現在呢", "/goal 測試通過", "/plan 整理", "/btw 查", "/rewind", "/doctor", "你好", "請 /always-approve"] { + assert!(!words_loosen(not), "{not}"); + } + } + #[test] fn a_fork_keeps_a_copy_and_goes_on_here() { let ctx = egui::Context::default(); diff --git a/src/app/profile_ui.rs b/src/app/profile_ui.rs index b9f6852..4cdb4c6 100644 --- a/src/app/profile_ui.rs +++ b/src/app/profile_ui.rs @@ -234,7 +234,7 @@ impl App { pub(super) fn profile_change(&self, conv: u64, args: &str) -> Result<(u64, Bot, Vec), String> { let me = self.speaking_bot(conv); if self.state.bot(me).is_some_and(|b| b.branch_of != 0) { - return Err("支線改不了設定:回到主線再請它改。".into()); + return Err(appctl::BRANCH_NO_SETTINGS.into()); } // 同事之間: what another bot asked for isn't the person's word. let started_by = self.state.bot(conv).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted)).map(|m| m.from_bot).unwrap_or(0); @@ -373,7 +373,13 @@ impl App { } } if let Some(m) = text("step_model").filter(|m| *m != b.step_model) { - lines.push(format!("執行步驟用的模型:{} → {}", brief(&b.step_model), brief(&m))); + // In the editor's words: "" is 自動, "off" is 不分開 (the card read 「(空) → 「off」」). + let name = |x: &str| match x.trim() { + "" => "自動".to_string(), + "off" => "不分開".to_string(), + m => m.to_string(), + }; + lines.push(format!("執行步驟用的模型:{} → {}", name(&b.step_model), name(&m))); b.step_model = m; } if let Some(c) = text("color").filter(|c| *c != b.color) { diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index fc6cdaa..5eac6b4 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -53,8 +53,18 @@ fn address_only(url: &str) -> String { /// A card as the phone draws it. `key`: the card's own (on_new_approval) — the phone sends it /// back with the answer, so the brain applies it only to this card. +/// What a card asks to do, for its title: the tool's name — or, where the call says which +/// (ChatGPT 方案: sign in, out, another account), that. +pub(super) fn card_what(bot: &Bot, a: &Approval) -> String { + if a.tool == crate::chatgpt::TOOL { + let args = bot.messages.iter().rev().take(24).flat_map(|m| m.tool_calls.iter()).find(|c| c.id == a.call_id).map(|c| c.args.as_str()).unwrap_or(""); + return crate::chatgpt::ask_label(args).to_string(); + } + remote::tool_label(&a.tool).to_string() +} + fn approval_json(bot: &Bot, a: &Approval, key: &str) -> serde_json::Value { - let what = remote::tool_label(&a.tool); + let what = card_what(bot, a); let title = match a.kind { ApprovalKind::EnableTools => format!("允許 {} 使用電腦工具嗎?", bot.name), ApprovalKind::EnableThisComputer => format!("允許 {} 在你的電腦上執行任務嗎?", bot.name), @@ -1209,9 +1219,11 @@ fn box_facts() -> serde_json::Value { if stale && !cfg!(test) && !BOX_FACTS_BUSY.swap(true, std::sync::atomic::Ordering::SeqCst) { std::thread::spawn(|| { let (n, exec_ms, total_ms) = crate::cloudbox::step_stats(); + // (What can't be known — no Docker to ask, no box yet — is null, and the phone says + // so: it read 「已是 v14」 and 「這台 Docker 主機沒有 gVisor」 with no Docker at all.) let v = json!({ - "update": crate::cloudbox::update_available(), - "gvisor": crate::cloudbox::host_has_gvisor(), + "update": crate::cloudbox::box_outdated(), + "gvisor": crate::cloudbox::gvisor_on_host(), "running": crate::cloudbox::running_runtime(), "steps": {"n": n, "exec_ms": exec_ms, "total_ms": total_ms}, }); @@ -1236,6 +1248,9 @@ impl App { let owner = role == "owner"; let bot = b["bot"].as_u64().unwrap_or(0); let s = |k: &str| b[k].as_str().unwrap_or("").trim().to_string(); + // A setting's name, exactly as sent: 「direct_mode 」 isn't direct_mode. (Trimmed, it slipped + // past the direct connection's guard, which reads names exactly — remote::lan_guard.) + let name_of = |k: &str| b[k].as_str().unwrap_or("").to_string(); let fail = |e: &str| json!({"error": e}); let done = |t: &str| json!({"ok": true, "text": t}); let owner_only = || json!({"error": "這件事只有這台 AnyBot 的擁有者能做"}); @@ -1372,7 +1387,7 @@ impl App { return fail("找不到這個 Bot"); } let v = &b["value"]; - let key = s("key"); + let key = name_of("key"); if matches!(key.as_str(), "tools" | "allow_remove" | "strengths" | "not_for" | "abilities" | "skills" | "may_use") && !owner { return owner_only(); } @@ -1419,8 +1434,17 @@ impl App { }; // (In the list's own order, so what the bot is told reads the same every turn.) let kept: Vec = every.iter().filter(|n| ticked.contains(n)).cloned().collect(); - let list = if kept.len() == every.len() { None } else { Some(kept) }; + let all = kept.len() == every.len(); let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") }; + let list = match (key.as_str(), &x.computers) { + // 可以用的電腦 lists the computers there now: an account computer that is + // off isn't. One not listed keeps how it was, allowed or not, and a + // bot with a list keeps one — ticking every computer listed made it + // "every computer", and one the person had left out came back in. + ("may_use", Some(prev)) => Some(kept.into_iter().chain(prev.iter().filter(|c| !every.contains(c)).cloned()).collect()), + _ if all => None, + _ => Some(kept), + }; match key.as_str() { "abilities" => x.abilities = list, "skills" => x.skills = list, @@ -1535,7 +1559,8 @@ impl App { return owner_only(); } let v = &b["value"]; - match s("key").as_str() { + let key = name_of("key"); + match key.as_str() { "direct_mode" => { if v.as_bool().unwrap_or(false) { self.enable_direct_mode() @@ -1547,8 +1572,13 @@ impl App { "notify" => self.state.notify = v.as_bool().unwrap_or(true), "rule_add" | "rule_remove" => { let text = v.as_str().unwrap_or("").trim().to_string(); - let list = if s("list") == "ask" { &mut self.state.review_ask_rules } else { &mut self.state.review_allow_rules }; - if s("key") == "rule_add" { + // (Any list but 「ask」 used to be the allow list.) + let list = match name_of("list").as_str() { + "ask" => &mut self.state.review_ask_rules, + "allow" => &mut self.state.review_allow_rules, + _ => return fail("不認得這個規則清單"), + }; + if key == "rule_add" { if text.is_empty() { return fail("規則是空的"); } @@ -1714,7 +1744,7 @@ impl App { } // 設定 › 電腦's buttons for Bot 的電腦. "box" => { - let op = s("op"); + let op = name_of("op"); if matches!(op.as_str(), "update" | "reset" | "runtime" | "auto_update") && !owner { return owner_only(); } @@ -1795,7 +1825,7 @@ impl App { "may_use": self.every_computer(b).into_iter().enumerate().map(|(i, (name, kind))| json!({"key": name, "name": name, "note": kind, "on": i == 0 || b.computers.as_ref().is_none_or(|a| a.contains(&name)), "fixed": i == 0})).collect::>(), "computer": chosen, "computers": choices.iter().map(|(name, note)| json!({"name": name, "note": note})).collect::>(), "tools_enabled": b.tools_enabled, "context_tokens": b.context_tokens, "folder": b.folder, "pinned": b.pinned, - "primary": b.id == self.state.primary_bot, "unread": b.unread, + "primary": b.id == self.state.primary_bot, "unread": b.unread, "team": b.team, "members": b.members.iter().map(|i| json!({"id": i, "name": names.get(i).cloned().unwrap_or_default()})).collect::>(), "memories": if owner { b.memories.clone() } else { vec![] }, "allow_rules": if owner { b.allow_rules.clone() } else { vec![] }, "demos": b.demos.iter().map(|d| json!({"name": d.name, "created": d.created, "steps": d.steps.len()})).collect::>(), @@ -2021,6 +2051,165 @@ mod phone_act_tests { assert!(main_rx.try_recv().is_err() && app.approvals.contains_key(&main.id), "the main bot's card still waits"); } + /// An act from a direct connection: remote::lan_guard first (asked about the bot as the + /// route asks), then phone_act — as remote.rs does it. + fn over_lan(ctx: &egui::Context, app: &mut App, action: &str, body: serde_json::Value) -> Result { + let detail = app.phone_act(ctx, "detail", &json!({"bot": body["bot"]}), "owner"); + match crate::remote::lan_guard(action, &body, || detail, "runc") { + crate::remote::Guard::Keeps => Ok(app.phone_act(ctx, action, &body, "owner")), + other => Err(other), + } + } + + /// A direct connection only tightens, however a setting's name is spelled: 「direct_mode 」, + /// 「 rule_add」, 「abilities 」 got past the guard (it read the name exactly) and were done + /// anyway (phone_act trimmed it). Each loosening, padded, cased or with a wide space, leaves + /// every guard as it was; the tightenings still go through. + #[test] + fn a_direct_connection_cannot_loosen_by_spelling_a_setting_differently() { + let (ctx, mut app) = demo(); + let b = app.state.bots[0].id; + app.state.direct_mode = false; + app.state.auto_review = false; + app.state.review_ask_rules = vec!["付款前先問我".into()]; + app.state.review_allow_rules = vec![]; + { + let x = app.state.bot_mut(b).unwrap(); + x.abilities = Some(vec!["web".into()]); + x.tools_enabled = false; + x.team = false; + x.allow_rules = vec!["rm".into()]; + } + let guards = |app: &App| { + let x = app.state.bot(b).unwrap(); + format!("{} {} {:?} {:?} {:?} {} {} {:?}", app.state.direct_mode, app.state.auto_review, app.state.review_ask_rules, app.state.review_allow_rules, x.abilities, x.tools_enabled, x.team, x.allow_rules) + }; + let before = guards(&app); + let every = crate::profile::ABILITIES.iter().map(|a| a.0).collect::>(); + let loosen: Vec<(&str, &str, serde_json::Value)> = vec![ + ("setting", "key", json!({"key": "direct_mode", "value": true})), + ("setting", "key", json!({"key": "auto_review", "value": true})), + ("setting", "key", json!({"key": "rule_add", "list": "allow", "value": "全部直接做"})), + ("setting", "list", json!({"key": "rule_add", "list": "allow", "value": "全部直接做"})), + ("setting", "key", json!({"key": "rule_remove", "list": "ask", "value": "付款前先問我"})), + ("setting", "list", json!({"key": "rule_remove", "list": "ask", "value": "付款前先問我"})), + ("bot", "key", json!({"bot": b, "key": "abilities", "value": every})), + ("bot", "key", json!({"bot": b, "key": "tools", "value": true})), + ("bot", "key", json!({"bot": b, "key": "team", "value": true})), + ]; + for (action, field, body) in loosen { + assert!(over_lan(&ctx, &mut app, action, body.clone()).is_err(), "as sent: {body}"); + let name = body[field].as_str().unwrap().to_string(); + for spelled in [format!("{name} "), format!(" {name}"), format!("\t{name}"), format!("{name}\u{3000}"), format!("{name}\u{a0}"), name.to_uppercase()] { + let mut odd = body.clone(); + odd[field] = json!(spelled); + let _ = over_lan(&ctx, &mut app, action, odd.clone()); + assert_eq!(guards(&app), before, "{odd}"); + } + } + // Tightening still works from there: an ask rule in, an allow rule out, tools off. + assert_eq!(over_lan(&ctx, &mut app, "setting", json!({"key": "rule_add", "list": "ask", "value": "寄信前先問我"})).unwrap()["ok"], true); + assert_eq!(over_lan(&ctx, &mut app, "bot", json!({"bot": b, "key": "allow_remove", "value": "rm"})).unwrap()["ok"], true); + assert_eq!(over_lan(&ctx, &mut app, "bot", json!({"bot": b, "key": "abilities", "value": []})).unwrap()["ok"], true); + assert!(app.state.review_ask_rules.contains(&"寄信前先問我".to_string()) && app.state.bot(b).unwrap().allow_rules.is_empty()); + assert_eq!(app.state.bot(b).unwrap().abilities, Some(vec![])); + // An unknown list is said so, not taken as the allow list. + assert!(app.phone_act(&ctx, "setting", &json!({"key": "rule_add", "list": "Ask", "value": "x"}), "owner")["error"].is_string()); + assert!(app.state.review_allow_rules.is_empty()); + } + + /// phone_act reads a setting's name exactly as sent, on every road in (the account's too): + /// 「direct_mode 」, 「Tools」, 「update 」 aren't those, and change nothing. + #[test] + fn phone_act_reads_setting_names_exactly() { + let (ctx, mut app) = demo(); + let b = app.state.bots[0].id; + app.state.direct_mode = false; + app.state.bot_mut(b).unwrap().tools_enabled = false; + for (action, body) in [ + ("setting", json!({"key": "direct_mode ", "value": true})), + ("setting", json!({"key": " auto_review", "value": true})), + ("setting", json!({"key": "rule_add", "list": " allow", "value": "全部直接做"})), + ("bot", json!({"bot": b, "key": "Tools", "value": true})), + ("bot", json!({"bot": b, "key": "abilities\u{3000}", "value": []})), + ("box", json!({"op": "update "})), + ] { + assert!(app.phone_act(&ctx, action, &body, "owner")["error"].is_string(), "{body}"); + } + assert!(!app.state.direct_mode && !app.state.auto_review && app.state.review_allow_rules.is_empty()); + let x = app.state.bot(b).unwrap(); + assert!(!x.tools_enabled && x.abilities.is_none()); + } + + /// A bot file imported from a direct connection: a file that says 「team」 doesn't share the + /// new bot with the team (it got past the guard as an action nobody had classified, and the + /// file's sharing was kept). + #[test] + fn an_imported_bot_is_not_shared_with_the_team() { + let (ctx, mut app) = demo(); + let mut x = app.state.bots[0].clone(); + x.team = true; + let content = crate::share::export(&x).replacen("\"name\"", "\"team\":true,\"name\"", 1); + let r = over_lan(&ctx, &mut app, "import_bot", json!({"content": content})).expect("importing changes no guard"); + let id = r["bot"].as_u64().unwrap(); + assert!(!app.state.bot(id).unwrap().team); + } + + /// 可以用的電腦 from the phone while a computer of the account is off (so not listed): it + /// keeps how it was. Ticking every computer listed used to make the list "every computer", + /// and a computer the person had left out came back in. + #[test] + fn a_computer_that_is_off_keeps_its_place_in_the_list() { + let (ctx, mut app) = demo(); + let b = app.state.bots[0].id; + app.state.remote.host_token = "t".into(); + app.state.remote.host_id = "me".into(); + *app.rm.peers.lock().unwrap() = vec![("dev1".into(), "筆電".into(), true), ("dev2".into(), "桌機".into(), true)]; + let x = app.state.bot(b).unwrap().clone(); + let names: Vec = app.every_computer(&x).into_iter().map(|c| c.0).collect(); + assert!(names.contains(&"筆電".to_string()) && names.contains(&"桌機".to_string()), "{names:?}"); + // Every computer but 筆電; then 筆電 and 桌機 go off. + let kept: Vec = names.iter().skip(1).filter(|n| *n != "筆電").cloned().collect(); + app.state.bot_mut(b).unwrap().computers = Some(kept.clone()); + *app.rm.peers.lock().unwrap() = vec![("dev1".into(), "筆電".into(), false), ("dev2".into(), "桌機".into(), false)]; + let ticked = |app: &mut App| -> Vec { + let d = app.phone_act(&ctx, "detail", &json!({"bot": b}), "owner"); + d["may_use"].as_array().unwrap().iter().filter(|m| m["on"] == true).filter_map(|m| m["key"].as_str().map(String::from)).collect() + }; + let now = ticked(&mut app); + assert!(over_lan(&ctx, &mut app, "bot", json!({"bot": b, "key": "may_use", "value": now})).is_ok()); + assert_eq!(app.state.bot(b).unwrap().computers, Some(kept.clone()), "筆電 stays out, 桌機 stays in"); + // From the account too (no guard there): a list stays a list. + let now = ticked(&mut app); + app.phone_act(&ctx, "bot", &json!({"bot": b, "key": "may_use", "value": now}), "owner"); + assert_eq!(app.state.bot(b).unwrap().computers, Some(kept)); + // A bot with no list (every computer) keeps none while everything listed stays ticked. + app.state.bot_mut(b).unwrap().computers = None; + let now = ticked(&mut app); + app.phone_act(&ctx, "bot", &json!({"bot": b, "key": "may_use", "value": now}), "owner"); + assert_eq!(app.state.bot(b).unwrap().computers, None); + } + + /// A ChatGPT card says what it asks — here a 支線 signing out — not the tool's name (it read + /// 「支線:…想要ChatGPT 方案登入」 for a logout). + #[test] + fn a_chatgpt_card_says_whether_it_signs_in_or_out() { + let (_ctx, mut app) = demo(); + let main = app.state.bots[0].clone(); + let mut br = main.clone(); + br.id = 9003; + br.branch_of = main.id; + let call = crate::model::ToolCall { id: "c1".into(), name: crate::chatgpt::TOOL.into(), args: r#"{"action":"logout"}"#.into(), status: crate::model::ToolStatus::Waiting }; + br.messages = vec![crate::model::Message::user("登出"), crate::model::Message { tool_calls: vec![call], ..crate::model::Message::assistant("", "x") }]; + app.state.branch_bots.push(br); + let (tx, _rx) = std::sync::mpsc::channel(); + app.approvals.insert(9003, crate::providers::Approval { call_id: "c1".into(), tool: crate::chatgpt::TOOL.into(), reason: "登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); + let cards = app.phone_cards(&main); + let card = cards.iter().find(|c| c["target"] == 9003).cloned().unwrap_or_default(); + assert_eq!(card["title"], format!("支線:{} 想要登出 ChatGPT 方案", main.name), "{cards:?}"); + assert_eq!(crate::chatgpt::ask_label(r#"{"action":"switch_account"}"#), "換 ChatGPT 帳號"); + } + /// A card that takes another's place with the same call id (call_0 every round) and the same /// words — the same step asking again — is published again (the view's signature changes), /// so the phone and the screens get the new card's key: with the old one every answer would diff --git a/src/appctl.rs b/src/appctl.rs index 54cf65d..8457063 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -203,6 +203,39 @@ pub fn describe(name: &str, args: &str) -> String { } } +/// What a 支線 is told when it tries to change a setting. +pub const BRANCH_NO_SETTINGS: &str = "支線改不了設定:回到主線再請它改。"; + +/// The app actions a 支線 is refused, at once and with no card (BRANCH_NO_SETTINGS) — it does its +/// one thing and changes nothing app-wide (an update_bot from one renamed the main bot once its +/// card was allowed): +/// - any bot's settings: update_bot, update_my_profile, teach_skill; +/// - AnyBot's settings: update_settings; +/// - the bots and the sidebar: create_bot, create_group, move_to_group, rename_group, +/// delete_group; +/// - the skill library: delete_skill, skill_install (the built-in ones too); +/// - connectors and hooks, except looking (manage_connectors list, reconnect, signing in or out; +/// manage_hooks list) — any other action, however spelled, counts as a change. +/// +/// Elsewhere: save_skill and skillify may add a skill (the main bot's) but not replace one +/// already in the library (apply); browser profiles may be listed but not added or switched +/// (agent::branch_refusal). Signing in or out of ChatGPT isn't a setting: it asks on a card. +pub fn changes_settings(name: &str, args: &str) -> bool { + let action = crate::tools::args_of(args)["action"].as_str().unwrap_or("").trim().to_lowercase(); + match name { + "update_bot" | "update_settings" | "update_my_profile" | "teach_skill" | "create_bot" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" => true, + crate::mcp::MANAGE_TOOL => !matches!(action.as_str(), "list" | "reconnect" | "login" | "logout"), + crate::hooks::MANAGE_TOOL => action != "list", + _ => false, + } +} + +/// A 支線 adds skills but doesn't replace one already in the library. +fn branch_replaces_skill(state: &State, bot_id: u64, name: &str) -> Option { + // (Matched as skills::write_skill_package reuses a folder: the name, ASCII case aside.) + (state.bot(bot_id).is_some_and(|b| b.branch_of != 0) && state.skills.iter().any(|k| k.name.trim().eq_ignore_ascii_case(name.trim()))).then(|| format!("支線不能換掉技能庫裡已經有的「{name}」:換個名字存,或回到主線再改。")) +} + /// App actions that need a yes from the person first (the original confirms deletions: /// "這會刪除例行任務並停止其後續執行。此操作無法復原。", VAgxC4). pub fn needs_approval(name: &str, args: &str, state: &State) -> Option { @@ -416,7 +449,8 @@ pub fn wake_message(r: &Routine) -> Message { pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome { // 支線: what it keeps, makes and sets up is its main bot's (memories, pages, routines, the - // work it hands over); it goes when it is done. + // work it hands over); it goes when it is done. (`asker`: the 支線 itself.) + let asker = bot_id; let bot_id = state.home_of(bot_id); let v: Value = match serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }) { Ok(v) => v, @@ -690,6 +724,10 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome if name.is_empty() || instructions.trim().is_empty() { return err("技能要有名稱和做法".into()); } + // (Before its folder is written: that would already replace the skill's files.) + if let Some(why) = branch_replaces_skill(state, asker, &name) { + return err(why); + } let mut extra: Vec<(String, Vec)> = vec![]; for f in v["files"].as_array().into_iter().flatten() { if let (Some(p), Some(c)) = (f["path"].as_str(), f["content"].as_str()) { @@ -771,6 +809,9 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome Some(sk) => { let n = sk.steps.len(); let name = sk.name.clone(); + if let Some(why) = branch_replaces_skill(state, asker, &name) { + return err(why); + } crate::memory::upsert_skill(&mut state.skills, sk); let who = learned(state, bot_id, &name); ok(format!("已把「{prompt}」那一回合存成技能「{name}」({n} 步可重播),{who}")) diff --git a/src/botbrowser.rs b/src/botbrowser.rs index e1a20b0..de0949b 100644 --- a/src/botbrowser.rs +++ b/src/botbrowser.rs @@ -321,6 +321,11 @@ pub fn current() -> String { } pub fn set_current(name: &str) -> Result { + // Bot 的電腦 has the one profile; the choice kept here is this computer's, and a step there + // reset it to 「預設」 (resolve answers 「預設」 inside the box). + if using_box() { + return Err(BOX_ONE_PROFILE.into()); + } let name = resolve(Some(name))?; std::fs::write(current_file(), &name).map_err(|e| format!("存不了設定檔選擇:{e}"))?; Ok(name) @@ -355,7 +360,7 @@ pub fn resolve(requested: Option<&str>) -> Result { None => Ok(current()), Some(r) => { let all = choices(); - match_profile(&all, r).ok_or_else(|| format!("AnyBot 瀏覽器沒有叫「{r}」的設定檔。現有:{}。要新的可以用 browser_profiles 新增(action: add)。", all.join("、"))) + match_profile(&all, r).ok_or_else(|| format!("AnyBot 瀏覽器沒有叫「{r}」的設定檔。現有:{}。要新的:browser 的 profiles 帶 name 填新名字,會新增並換過去。", all.join("、"))) } } } @@ -383,6 +388,9 @@ pub fn check_name(name: &str) -> Result { /// Make a new empty profile (its own folder, so its own logins). pub fn add(name: &str) -> Result { + if using_box() { + return Err(BOX_ONE_PROFILE.into()); + } let n = check_name(name)?; if let Some(have) = match_profile(&profiles(), &n) { return Ok(have); @@ -801,13 +809,18 @@ fn close_chrome(port: u16) -> Result<(), String> { Ok(()) } -/// Open a link in a new tab of the bot's browser (in the named profile, which becomes current). -pub fn open(url: &str, profile: Option<&str>) -> Result { +/// Open a link in a new tab of the bot's browser (in the named profile, which becomes current — +/// unless `this_step_only`: a 支線's step, which mustn't change every bot's choice). +pub fn open(url: &str, profile: Option<&str>, this_step_only: bool) -> Result { if crate::web::is_forbidden_browser_url(url) { return Err("安全規則禁止開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。".into()); } let prof = resolve(profile)?; - let _ = set_current(&prof); + // (The person's own browsers are used for this step, never made the one every later step + // uses: that is the person's choice, in Settings.) + if !is_persons(&prof) && !this_step_only { + let _ = set_current(&prof); + } let (name, port, fresh) = ensure(&prof, Some(url))?; if !fresh { let kind = kind_of(Some(&prof)); @@ -861,14 +874,68 @@ pub fn show(profile: &str) -> Result<(), String> { } } +/// What Bot 的電腦's browser has: one profile, its logins on that computer. +const BOX_ONE_PROFILE: &str = "Bot 的電腦上的瀏覽器只有一個設定檔(預設),登入留在那台電腦上:不能新增或切換設定檔。要用別的設定檔,要在使用者的電腦上用 AnyBot 瀏覽器。"; + +/// The person's own browsers among the choices — their Firefox profiles, their everyday +/// browser: they carry the person's logins. +fn is_persons(name: &str) -> bool { + name.ends_with(FIREFOX_MARK) || name == PERSON_PROFILE +} + +/// AnyBot's own profile of exactly this name (case aside: it is a folder). +fn own_profile(own: &[String], name: &str) -> Option { + let w = name.trim().to_lowercase(); + own.iter().find(|p| !w.is_empty() && p.to_lowercase() == w).cloned() +} + +/// What a browser_profiles call does. The one `browser` tool's own `action` is 「profiles」, so +/// a call from the model carries no list/add/use of its own: a name alone means "work in that +/// one" — AnyBot's own profile of that name (`own`) is switched to, any other name is a new, +/// empty one. (Every call with a name used to list the profiles and change nothing; a loose match +/// then would have switched 「阿金」 to the person's own 「阿金(Firefox)」.) +fn profiles_action<'a>(action: &'a str, name: &str, own: &[String]) -> &'a str { + match action.trim() { + "" if name.trim().is_empty() => "list", + "" if own_profile(own, name).is_some() => "use", + "" => "add", + a => a, + } +} + +/// A name that is the person's own browser — exactly a choice of theirs, or their browser's +/// other names: the bot doesn't switch to it. Switching is for every later step and every bot, +/// with the person's logins; the person does it in Settings (one tap) — refused rather than +/// asked on a card, which this tool has no way to show. +fn persons_choice(name: &str, all: &[String]) -> Option { + let w = name.trim().to_lowercase(); + if PERSON_ALIASES.contains(&w.as_str()) { + return Some(PERSON_PROFILE.to_string()); + } + all.iter().find(|c| is_persons(c) && c.to_lowercase() == w).cloned() +} + /// The browser_profiles tool: list, add or switch profiles. pub fn profiles_tool(action: &str, name: &str) -> Result { let list_text = || { let cur = current(); choices().iter().map(|p| if *p == cur { format!("{p}(使用中)") } else { p.clone() }).collect::>().join("、") }; - match action.trim() { - "" | "list" => Ok(format!( + if using_box() { + return match profiles_action(action, name, &[]) { + "list" => Ok("Bot 的電腦上的 AnyBot 瀏覽器只有一個設定檔:預設(使用中)。".into()), + _ => Err(BOX_ONE_PROFILE.into()), + }; + } + let own = profiles(); + let act = profiles_action(action, name, &own); + if act != "list" { + if let Some(p) = persons_choice(name, &choices()) { + return Err(format!("「{p}」是使用者自己的瀏覽器(帶著他的登入):Bot 不能自己換過去,換了之後每一步、每個 Bot 都會用他的帳號。請使用者在 設定 › 電腦 ›「AnyBot 瀏覽器設定檔」自己切換。")); + } + } + match act { + "list" => Ok(format!( "AnyBot 瀏覽器的設定檔:{}。每個設定檔有自己的登入。{}{}", list_text(), if choices().iter().any(|c| c.ends_with(FIREFOX_MARK)) { format!("名字後面有「{FIREFOX_MARK}」的是使用者自己的 Firefox 設定檔(用使用者的登入),AnyBot 會用可以操作的方式打開它;如果使用者已經用一般方式開著那個設定檔,要先請使用者關掉那個視窗。") } else { String::new() }, @@ -877,14 +944,14 @@ pub fn profiles_tool(action: &str, name: &str) -> Result { "add" | "create" => { let n = add(name)?; set_current(&n)?; - Ok(format!("已新增並切換到設定檔「{n}」(全新的,還沒登入任何網站)。用 browser_open 打開網站後,請使用者在那個視窗登入一次。現在:{}", list_text())) + Ok(format!("已新增並切換到設定檔「{n}」(全新的,還沒登入任何網站)。用 browser 的 open 打開網站後,請使用者在那個視窗登入一次。現在:{}", list_text())) } "use" | "switch" => { - let n = set_current(name)?; - let note = if n == PERSON_PROFILE { "(使用者平常的瀏覽器:請使用者在那裡切到想要的 Chrome 設定檔)" } else { "" }; - Ok(format!("已切換到「{n}」{note},之後的 browser_open / browser_read 都用它。現在:{}", list_text())) + let n = own_profile(&own, name).ok_or_else(|| format!("AnyBot 瀏覽器沒有叫「{}」的設定檔。現有:{}。", name.trim(), own.join("、")))?; + let n = set_current(&n)?; + Ok(format!("已切換到「{n}」,之後 browser 的 open、read 都用它。現在:{}", list_text())) } - other => Err(format!("不懂「{other}」,action 請用 list、add 或 use")), + other => Err(format!("不懂「{other}」:不帶 name 是列出設定檔,帶 name 是換到那個設定檔(沒有就先新增)")), } } @@ -945,7 +1012,7 @@ mod tests { #[ignore] fn reads_a_real_page() { // Opening hands back the loaded page itself (no browser_read needed). - let r = open("https://example.com", None).unwrap(); + let r = open("https://example.com", None, false).unwrap(); assert!(r.contains("example.com") && r.contains("Example Domain") && r.contains("[1] 連結"), "{r}"); let page = read(2000, None).unwrap(); assert!(page.contains("Example Domain"), "{page}"); @@ -1020,6 +1087,53 @@ mod tests { assert!(check_name(PERSON_PROFILE).is_err()); } + /// The model's `browser` call has 「profiles」 as its own action: a name in it switches to + /// AnyBot's own profile of exactly that name, or adds a new one — it used to list them and + /// change nothing. A near name (「阿金」 beside the person's 「阿金(Firefox)」) is a new + /// profile, and the person's own browsers are never switched to by the bot. + #[test] + fn a_profile_named_by_the_model_is_switched_to_or_added() { + let asked = |args: &str, own: &[String]| { + let mut c = crate::model::ToolCall { id: "c".into(), name: crate::browser::TOOL.into(), args: args.into(), status: crate::model::ToolStatus::Done }; + crate::browser::expand_call(&mut c); + assert_eq!(c.name, "browser_profiles"); + let v = crate::tools::args_of(&c.args); + profiles_action(v["action"].as_str().unwrap_or(""), v["name"].as_str().unwrap_or(""), own).to_string() + }; + let own = vec![DEFAULT_PROFILE.to_string(), "工作".to_string()]; + assert_eq!(asked(r#"{"action":"profiles"}"#, &own), "list"); + assert_eq!(asked(r#"{"action":"profiles","name":" "}"#, &own), "list"); + assert_eq!(asked(r#"{"action":"profiles","name":"私人"}"#, &own), "add"); + assert_eq!(asked(r#"{"action":"profiles","name":"工作"}"#, &own), "use"); + // The person's own browsers, by their exact name or their browser's other names; a near + // name is a new profile of AnyBot's, even with every choice in view. + let all = vec![DEFAULT_PROFILE.to_string(), "工作".to_string(), format!("阿金{FIREFOX_MARK}"), PERSON_PROFILE.to_string()]; + assert_eq!(asked(r#"{"action":"profiles","name":"阿金"}"#, &all), "add"); + assert_eq!(asked(r#"{"action":"profiles","name":"我的 Chrome"}"#, &all), "add"); + assert_eq!(persons_choice("阿金", &all), None); + assert_eq!(persons_choice(&format!("阿金{FIREFOX_MARK}"), &all).as_deref(), Some(format!("阿金{FIREFOX_MARK}").as_str())); + assert_eq!(persons_choice("我的 Chrome", &all).as_deref(), Some(PERSON_PROFILE)); + assert_eq!(persons_choice(PERSON_PROFILE, &all).as_deref(), Some(PERSON_PROFILE)); + assert_eq!(persons_choice("工作", &all), None); + // AnyBot's own callers still say which. + assert_eq!(profiles_action("add", "私人", &own), "add"); + assert_eq!(crate::web::describe("browser_profiles", r#"{"name":"私人"}"#), "切換到「私人」"); + assert_eq!(crate::web::describe("browser_profiles", "{}"), "列出設定檔"); + } + + /// Bot 的電腦's browser has one profile: adding or switching there is refused with that, and + /// nothing is written to this computer's choice (a switch there wrote 「預設」 over it, and the + /// bot was told 「已新增並切換到…」). + #[test] + fn the_box_browser_has_one_profile_and_leaves_this_computers_choice() { + assert_eq!(in_box(|| profiles_tool("", "工作")), Err(BOX_ONE_PROFILE.to_string())); + assert_eq!(in_box(|| profiles_tool("use", DEFAULT_PROFILE)), Err(BOX_ONE_PROFILE.to_string())); + assert!(in_box(|| profiles_tool("", "")).unwrap().contains("只有一個設定檔")); + assert_eq!(in_box(|| set_current("工作")), Err(BOX_ONE_PROFILE.to_string())); + assert_eq!(in_box(|| add("工作")), Err(BOX_ONE_PROFILE.to_string())); + assert!(!using_box()); + } + #[test] fn profile_names_are_checked() { assert_eq!(check_name(" 工作 ").unwrap(), "工作"); @@ -1083,14 +1197,14 @@ mod tests { // Open the everyday way (nobody can drive it): AnyBot asks for it to be closed first. let mut everyday = Command::new(bin).args(["--headless", "--new-instance", "--profile"]).arg(&dir).arg("about:blank").stdout(Stdio::null()).stderr(Stdio::null()).spawn().unwrap(); wait_for(true); - let e = open(&format!("http://127.0.0.1:{port}/"), Some("阿金")).unwrap_err(); + let e = open(&format!("http://127.0.0.1:{port}/"), Some("阿金"), false).unwrap_err(); assert!(e.contains("先關掉"), "{e}"); let _ = everyday.kill(); let _ = everyday.wait(); wait_for(false); // Now AnyBot opens it itself and drives it like any of its own. let go = || -> Result<(), String> { - let r = open(&format!("http://127.0.0.1:{port}/"), Some("阿金"))?; + let r = open(&format!("http://127.0.0.1:{port}/"), Some("阿金"), false)?; assert!(r.contains("Firefox") && r.contains("阿金(Firefox)") && r.contains("按我"), "{r}"); let (t, _) = crate::browser::run("browser_click", &serde_json::json!({"text": "按我", "profile": "阿金"}))?; assert!(t.contains("按到了"), "{t}"); @@ -1125,7 +1239,7 @@ mod tests { }); let url = format!("http://127.0.0.1:{port}/"); let tidy = |job: &str| as_job(job, || crate::browser::run("browser_tabs", &serde_json::json!({"action": "tidy", "close": true, "profile": "收尾"})).map(|r| r.0)); - let open_as = |job: &str| as_job(job, || open(&url, Some("收尾"))); + let open_as = |job: &str| as_job(job, || open(&url, Some("收尾"), false)); let quit_within = |secs: u64| { let t = Instant::now(); while firefox_in_use(&dir) && t.elapsed() < Duration::from_secs(secs) { @@ -1179,7 +1293,7 @@ mod tests { }); let url = format!("http://127.0.0.1:{port}/"); let tidy = |job: &str| as_job(job, || crate::browser::run("browser_tabs", &serde_json::json!({"action": "tidy", "close": true, "profile": DEFAULT_PROFILE})).map(|r| r.0)); - let open_as = |job: &str| as_job(job, || open(&url, Some(DEFAULT_PROFILE))); + let open_as = |job: &str| as_job(job, || open(&url, Some(DEFAULT_PROFILE), false)); let quit_within = |secs: u64| { let t = Instant::now(); while alive(default_port()) && t.elapsed() < Duration::from_secs(secs) { diff --git a/src/browser.rs b/src/browser.rs index 363ba36..92c9f9b 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -1490,7 +1490,7 @@ mod tests { let url = format!("http://127.0.0.1:{port}/"); let r = { botbrowser::as_job("lines", || -> Result<(), String> { - botbrowser::open(&url, None)?; + botbrowser::open(&url, None, false)?; let refs = || -> Result { run("browser_elements", &json!({})).map(|r| r.0) }; let num = |list: &str, name: &str| -> String { list.lines().find(|l| l.contains(name)).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).unwrap_or_default() }; let first = refs()?; @@ -1554,7 +1554,7 @@ document.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey let url = format!("http://127.0.0.1:{port}/"); let r = { botbrowser::as_job("send", || -> Result<(), String> { - botbrowser::open(&url, None)?; + botbrowser::open(&url, None, false)?; let info = |mode: &str, rf: &str, value: &str| -> Result { run(SEND_INFO, &json!({"mode": mode, "ref": rf, "value": value})).map(|r| serde_json::from_str(&r.0).unwrap()) }; let check = |before: &Value, text: &str| -> Result { run(SENT_CHECK, &json!({"excerpt": crate::publish::excerpt(text), "links": before["links"], "target": before["target"]})).map(|r| serde_json::from_str(&r.0).unwrap()) @@ -1690,7 +1690,7 @@ customElements.define('my-panel', class extends HTMLElement { constructor() { su v }; let go = || -> Result<(), String> { - crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("shadow-test"))?; + crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("shadow-test"), false)?; let (els, _) = run("browser_elements", &p(json!({})))?; println!("{els}"); for want in ["「名稱」", "「開始」", "「自動更新」"] { @@ -1752,7 +1752,7 @@ q.addEventListener('keydown', e => { if (e.key === 'Enter') out.innerText = '搜 crate::botbrowser::add("drive-test").unwrap(); let p = |v: Value| { let mut v = v; v["profile"] = json!("drive-test"); v }; let go = || -> Result<(), String> { - crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("drive-test"))?; + crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("drive-test"), false)?; let (els, _) = run("browser_elements", &p(json!({})))?; assert!(els.contains("「數據周期」"), "{els}"); run("browser_hover", &p(json!({"text": "商品分析"})))?; diff --git a/src/chatgpt.rs b/src/chatgpt.rs index 6a6f259..7c53061 100644 --- a/src/chatgpt.rs +++ b/src/chatgpt.rs @@ -880,6 +880,18 @@ pub fn run_tool(args: &str) -> (String, bool) { } /// What the call does, in a line (the step, the approval card). +/// What a call does, as the title of its card: 「…想要登出 ChatGPT 方案」 (the tool's own name, +/// 「ChatGPT 方案登入」, made a logout's card read 「…想要ChatGPT 方案登入」). +pub fn ask_label(args: &str) -> &'static str { + let v: Value = serde_json::from_str(args).unwrap_or(json!({})); + match v["action"].as_str().unwrap_or("") { + "login" => "登入 ChatGPT 方案", + "logout" => "登出 ChatGPT 方案", + "switch_account" => "換 ChatGPT 帳號", + _ => "查看 ChatGPT 方案", + } +} + pub fn describe(args: &str) -> String { let v: Value = serde_json::from_str(args).unwrap_or(json!({})); match v["action"].as_str().unwrap_or("") { diff --git a/src/cloudbox.rs b/src/cloudbox.rs index 5993b07..3b517cc 100644 --- a/src/cloudbox.rs +++ b/src/cloudbox.rs @@ -456,7 +456,13 @@ pub fn box_runtime() -> String { /// The box's Docker host has gVisor (a runtime registered as runsc). pub fn host_has_gvisor() -> bool { - dk(&["info", "--format", "{{range $k, $v := .Runtimes}}{{$k}} {{end}}"]).map(|o| o.split_whitespace().any(|r| r == "runsc")).unwrap_or(false) + gvisor_on_host().unwrap_or(false) +} + +/// Whether the Docker host has gVisor; None when Docker can't be asked (there is no host to +/// say it of). +pub fn gvisor_on_host() -> Option { + dk(&["info", "--format", "{{range $k, $v := .Runtimes}}{{$k}} {{end}}"]).ok().map(|o| o.split_whitespace().any(|r| r == "runsc")) } /// The runtime the box is running on now ("runc", "runsc"), when there is a box. @@ -527,7 +533,13 @@ pub fn wanted_version() -> String { /// The running computer is older than the one this AnyBot carries. (Any other version counts: /// the box is always the one its AnyBot carries — one built beside it is put back.) pub fn update_available() -> bool { - box_version().is_some_and(|v| v != wanted_version()) + box_outdated().unwrap_or(false) +} + +/// Whether the box is older than this AnyBot's; None when there is no box to compare (no Docker, +/// or none built yet). +pub fn box_outdated() -> Option { + box_version().map(|v| v != wanted_version()) } /// The box's version (its image's label); None when there is no box or Docker can't be asked. @@ -3146,6 +3158,16 @@ pub fn shutdown() { #[cfg(test)] mod tests { + /// With no Docker to ask (a test never reaches one), what can't be known is None, not "up to + /// date" and "no gVisor" — the phone's 電腦 page said 「已是 v14」 and 「這台 Docker 主機沒有 + /// gVisor」 with no Docker at all. + #[test] + fn without_docker_the_box_facts_are_unknown() { + assert_eq!(super::box_outdated(), None); + assert_eq!(super::gvisor_on_host(), None); + assert!(!super::update_available() && !super::host_has_gvisor()); + } + /// E1: a test never reaches the person's data folder or their real Docker computer — the /// data folder is this run's own, docker goes nowhere and fails at once, no VM is started. #[test] diff --git a/src/evidence.rs b/src/evidence.rs index f8b1f35..d5d993f 100644 --- a/src/evidence.rs +++ b/src/evidence.rs @@ -51,6 +51,12 @@ pub fn went_out(call: &ToolCall, result: Option<&Message>) -> bool { !crate::browser::is_tool(&call.name) && sends(call) } +/// A step as the person reads it, for the evidence of a send: what it is and what it was on — +/// 「傳訊息給其他 Bot 給 同事:早安」 (it read 「message_bot 工作資料夾」). +pub fn step_line(name: &str, args: &str) -> String { + format!("{} {}", crate::remote::tool_label(name), crate::remote::tool_detail(name, args)).trim().to_string() +} + /// Count the steps of `msgs`. pub fn tally(msgs: &[Message]) -> Tally { let results: std::collections::HashMap<&str, &Message> = msgs.iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), m)).collect(); @@ -64,7 +70,7 @@ pub fn tally(msgs: &[Message]) -> Tally { t.sent += 1; let line = match result.filter(|r| !r.sent.is_empty()) { Some(r) => r.sent.clone(), - None => format!("{} {}", c.name, crate::tools::describe(&c.name, &c.args)).trim().to_string(), + None => step_line(&c.name, &c.args), }; t.sends.push(line); } @@ -97,7 +103,10 @@ mod tests { let t = tally(&msgs); assert_eq!((t.steps, t.failed, t.sent), (7, 2, 3)); assert_eq!(t.sends.len(), 3); - assert!(t.sends[0].starts_with("computer_use_press_key")); + // In words, as the person reads it (it read 「computer_use_press_key 工作資料夾」). + assert_eq!(t.sends[0], "按鍵 ctrl+Return"); + let told = vec![Message::user("跟同事說"), Message { tool_calls: vec![call("message_bot", r#"{"bot":"同事","text":"早安"}"#, ToolStatus::Done)], ..Message::assistant("", "") }]; + assert_eq!(tally(&told).sends, vec!["傳訊息給其他 Bot 給 同事:早安".to_string()]); } #[test] diff --git a/src/oplog.rs b/src/oplog.rs index d2f48cd..192e819 100644 --- a/src/oplog.rs +++ b/src/oplog.rs @@ -387,7 +387,6 @@ pub fn replay_of(name: &str) -> Replay { "computer_use_check_permissions", "browser_read", "browser_screenshot", - "browser_profiles", "browser_wait", "browser_tabs", "browser_sent_log", @@ -707,7 +706,8 @@ mod tests { fn looking_may_run_again_and_reaching_out_never() { assert_eq!(replay_of("computer_use_screenshot"), Replay::Safe); assert_eq!(replay_of("read_file"), Replay::Safe); - for t in ["send_sms", "post_to_x", "publish_site", "browser_fill_card", "mac_send_mail", "shell", "edit_file", "computer_use_click", "computer_use_typing", "mcp__github__create_issue"] { + // (browser_profiles adds and switches profiles: it was listed as only looking.) + for t in ["send_sms", "post_to_x", "publish_site", "browser_fill_card", "mac_send_mail", "shell", "edit_file", "computer_use_click", "computer_use_typing", "mcp__github__create_issue", "browser_profiles"] { assert_eq!(replay_of(t), Replay::Never, "{t}"); } } diff --git a/src/remote.rs b/src/remote.rs index e013f04..bb1be59 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -379,6 +379,8 @@ pub fn tool_label(name: &str) -> &'static str { pub(crate) fn tool_detail(name: &str, args: &str) -> String { let d = if crate::appctl::is_app_tool(name) { crate::appctl::describe(name, args) + } else if crate::macapps::is_mac_tool(name) { + crate::macapps::describe(name, args) } else if crate::computer::is_computer_tool(name) { crate::computer::describe(name, args) } else if crate::web::is_web_tool(name) { @@ -682,18 +684,24 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { } ("POST", ["api", "act", action]) => { let body = req.json(); - // 區網 is plain http: whoever shares the Wi-Fi can read one request and use its - // login. So what would let a bot act without asking — 直接操作, an 「一律允許」 - // rule, a new connector — can't be switched on over it; on the computer itself, or - // through the account (https), it can. - // 改名 is a screen's (/api/sync/mcp-rename): the phone has no use for it, and over the - // plain-http LAN one read login could rename connectors so that another one inherits a - // 「一律允許」 (they are kept by name). + // 同一個網路直接連: a device there signs in with the phone password alone (and the + // connection is plain http over Tailscale, or when the certificate couldn't be made). + // So what would let a bot do more without asking — 直接操作, an 「一律允許」 rule, a + // new connector, an ability or computer ticked on — can't be switched on from it, only + // off; on the computer itself, or through the account, it can. + // 改名 is a screen's (/api/sync/mcp-rename): the phone has no use for it, and one + // borrowed login could rename connectors so that another one inherits a 「一律允許」 + // (they are kept by name). if *action == "mcp" && !body["rename"].is_null() { return Resp::error(403, "連接器的名稱只能在電腦上的 AnyBot 改"); } - if !via_relay && loosens_guard(action, &body) { - return Resp::error(403, "這項設定會讓 Bot 不用問就動手,不能從區網連線(沒有加密)打開:請在電腦上的 AnyBot 改,或用帳號連線。"); + if !via_relay { + let bot_now = || hub().ask_sync_for(SyncKind::Phone { action: "detail".into(), body: json!({"bot": body["bot"]}), role: role.clone() }, 20).unwrap_or(Value::Null); + match lan_guard(action, &body, bot_now, &crate::cloudbox::box_runtime()) { + Guard::Keeps => {} + Guard::Loosens => return Resp::error(403, LOOSEN_REFUSED), + Guard::Unknown => return Resp::error(400, "不認得這個設定"), + } } // ChatGPT 方案 from the phone: the owner's; over the network, so not on the app's thread. if *action == "chatgpt" { @@ -752,6 +760,11 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { if text.is_empty() && attachments.is_empty() { return Resp::error(400, "訊息是空的"); } + // A command that loosens a guard (「/always-approve」) is a setting typed in + // a chat: from a direct connection, refused like the switch (lan_guard). + if !via_relay && crate::app::words_loosen(&text) { + return Resp::error(403, LOOSEN_REFUSED); + } // 團隊: the bot knows who is talking when it isn't the owner (except `/goal` and // `/plan` commands from an admin, which AnyBot handles before the bot). let who = req.header("x-anybot-user"); @@ -926,23 +939,86 @@ fn picks_of(b: &Value) -> Option> { b["memories"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.trim().to_string())).filter(|s| !s.is_empty()).take(20).collect()) } +/// Why a direct connection can't loosen a guard (it isn't a matter of encryption: that +/// connection is https; it signs in with the phone password alone). +pub const LOOSEN_REFUSED: &str = "這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬。請在電腦上的 AnyBot 改,或用帳號連線。"; + +/// What a phone act does to the bots' guards, asked of every act over a direct connection. +#[derive(Debug, PartialEq)] +pub(crate) enum Guard { + /// Changes no guard, or makes one stricter: done. + Keeps, + /// Lets a bot do more without asking, or lets more in: refused (LOOSEN_REFUSED). + Loosens, + /// A setting whose name isn't exactly one AnyBot knows (「direct_mode 」, 「Rule_add」…): refused + /// rather than guessed — the app's side reads names exactly too, so nothing passes here that + /// does something there. + Unknown, +} + /// 團隊角色: what each role may do. "member" chats and attaches files; "admin" also approves, /// stops, starts new chats and uses the screens; only "device" (another AnyBot of the owner's /// account) may run tools here. /// A phone action carried out on the app's thread (where the state is), with its answer. -/// Whether a phone action takes a guard away: turning 直接操作 on, adding an allow rule, adding -/// a connector (a new tool the bots may call). -fn loosens_guard(action: &str, body: &Value) -> bool { +/// Which way a phone act moves the guards (`remote_ui.rs` `phone_act` does it, reading the same +/// names exactly). Looser: 直接操作 or 自動審核 on, an 「無需詢問直接允許」 rule added or an +/// 「一律詢問」 one removed, a connector added or switched back on, a messaging channel switched +/// back on, a bot's computer tools on, a bot shared with the team (or a bot added to a group that +/// is), an ability or a computer ticked on (the phone sends the whole ticked list: only ticking one that is off now — `now`, +/// the bot's detail, asked only then — loosens), Bot 的電腦 taken from 強隔離 (gVisor) to +/// 標準 (`runtime`: the box's now). The rest — the other way round for each of those, and what +/// changes no guard (names, looks, models, keys, skills, routines, memories, pages) — keeps. +/// (Cards are answered, 一律允許 included, through api/bots/…/answer: that is the card in front of +/// the person, not a setting.) +pub(crate) fn lan_guard(action: &str, body: &Value, now: impl FnOnce() -> Value, runtime: &str) -> Guard { + let on = |v: &Value| v.as_bool() == Some(true); + let looser = |b: bool| if b { Guard::Loosens } else { Guard::Keeps }; + let key = body["key"].as_str().unwrap_or(""); match action { - "setting" => match body["key"].as_str().unwrap_or("") { - "direct_mode" => body["value"].as_bool().unwrap_or(false), - "rule_add" => body["list"].as_str() != Some("ask"), - _ => false, + "setting" => match key { + // (As phone_act reads them: a missing value is off.) + "direct_mode" | "auto_review" => looser(on(&body["value"])), + "notify" => Guard::Keeps, + "rule_add" | "rule_remove" => match body["list"].as_str().unwrap_or("") { + "allow" => looser(key == "rule_add"), + "ask" => looser(key == "rule_remove"), + _ => Guard::Unknown, + }, + _ => Guard::Unknown, }, - "mcp" => body["add"].is_object(), - // What a bot may do, and where (the phone sends the whole ticked list). - "bot" => matches!(body["key"].as_str().unwrap_or(""), "abilities" | "may_use"), - _ => false, + "bot" => match key { + "abilities" | "may_use" => { + let now = now(); + let ticked_now: Vec<&str> = now[key].as_array().into_iter().flatten().filter(|x| x["on"] == true).filter_map(|x| x["key"].as_str()).collect(); + looser(body["value"].as_array().into_iter().flatten().any(|t| !t.as_str().is_some_and(|t| ticked_now.contains(&t)))) + } + // (phone_act: a missing value turns the tools on.) + "tools" => looser(body["value"].as_bool().unwrap_or(true)), + "team" => looser(on(&body["value"])), + // A group shared with the team: a member added is a bot the teammates reach too. + "members" => { + let now = now(); + let had: Vec = now["members"].as_array().into_iter().flatten().filter_map(|m| m["id"].as_u64()).collect(); + looser(now["team"] != false && body["value"].as_array().into_iter().flatten().any(|m| !m.as_u64().is_some_and(|m| had.contains(&m)))) + } + "allow_remove" | "skills" | "pinned" | "pin_at" | "folder" | "primary" | "strengths" | "not_for" | "unread" | "shape" | "color" | "context" | "thinking" | "step_model" => Guard::Keeps, + _ => Guard::Unknown, + }, + // (Renaming is refused before this; reconnecting connects only what is on.) + "mcp" => looser(body["add"].is_object() || (!on(&body["reconnect"]) && !on(&body["remove"]) && on(&body["enabled"]))), + "channel" => looser(!on(&body["remove"]) && on(&body["enabled"])), + "box" => match body["op"].as_str().unwrap_or("") { + "runtime" => looser(runtime == "runsc" && body["value"].as_str() != Some("runsc")), + "wake" | "snapshot" | "disk" | "update" | "reset" | "auto_update" => Guard::Keeps, + _ => Guard::Unknown, + }, + // Looking; chats, pages and memories; bots made, imported (with no tools, grants, team or + // running routines), deleted or restarted; models and keys; skills; signing in to ChatGPT; + // signing a phone out — none of these moves a guard. + "search" | "detail" | "settings" | "pages" | "export_bot" | "export_transcript" | "import_bot" | "section_move" | "memory" | "app" | "group_chat" | "delete_bot" | "restart_bot" | "react" | "reply" | "resume" | "clear" | "delete_page" | "provider" | "device_remove" | "skill" | "chatgpt" => Guard::Keeps, + // An action this list doesn't name is refused, not let through (import_bot slipped by + // that way with a file's 「team」). A new one has to be put on one side or the other. + _ => Guard::Unknown, } } @@ -2948,6 +3024,99 @@ mod tests { assert_eq!(to_brain(&s, "GET", "/x", &[], &[], 10).unwrap_err(), "找不到這個 Bot"); } + /// Every setting the phone can send, which way it moves the guards over a direct connection: + /// each loosening is refused, each tightening (and what changes no guard) goes through, and a + /// name that isn't exactly one AnyBot knows is refused, not guessed. + #[test] + fn a_direct_connection_only_tightens() { + let unasked = || -> Value { panic!("the bot is asked about only for its abilities and computers") }; + let g = |action: &str, body: Value| lan_guard(action, &body, unasked, "runc"); + let loosens = [ + ("setting", json!({"key": "direct_mode", "value": true})), + ("setting", json!({"key": "auto_review", "value": true})), + ("setting", json!({"key": "rule_add", "list": "allow", "value": "x"})), + ("setting", json!({"key": "rule_remove", "list": "ask", "value": "x"})), + ("bot", json!({"bot": 1, "key": "tools", "value": true})), + ("bot", json!({"bot": 1, "key": "tools"})), + ("bot", json!({"bot": 1, "key": "team", "value": true})), + ("mcp", json!({"add": {"url": "https://x"}})), + ("mcp", json!({"name": "x", "enabled": true})), + ("channel", json!({"id": 1, "enabled": true})), + ]; + for (a, b) in loosens { + assert_eq!(g(a, b.clone()), Guard::Loosens, "{a} {b}"); + } + let keeps = [ + ("setting", json!({"key": "direct_mode", "value": false})), + ("setting", json!({"key": "auto_review", "value": false})), + ("setting", json!({"key": "notify", "value": true})), + ("setting", json!({"key": "rule_add", "list": "ask", "value": "x"})), + ("setting", json!({"key": "rule_remove", "list": "allow", "value": "x"})), + ("bot", json!({"bot": 1, "key": "tools", "value": false})), + ("bot", json!({"bot": 1, "key": "team", "value": false})), + ("bot", json!({"bot": 1, "key": "allow_remove", "value": "rm"})), + ("bot", json!({"bot": 1, "key": "shape", "value": "heart"})), + ("bot", json!({"bot": 1, "key": "skills", "value": []})), + ("mcp", json!({"name": "x", "enabled": false})), + ("mcp", json!({"name": "x", "remove": true, "enabled": true})), + ("mcp", json!({"name": "x", "reconnect": true})), + ("channel", json!({"id": 1, "enabled": false})), + ("channel", json!({"id": 1, "remove": true, "enabled": true})), + ("box", json!({"op": "runtime", "value": "runsc"})), + ("box", json!({"op": "wake"})), + ("app", json!({"name": "update_settings", "args": {"theme": "dark"}})), + ("provider", json!({"provider": "Xai", "key": "k"})), + ]; + for (a, b) in keeps { + assert_eq!(g(a, b.clone()), Guard::Keeps, "{a} {b}"); + } + // 強隔離 to 標準 is looser; already 標準, nothing changes. + assert_eq!(lan_guard("box", &json!({"op": "runtime", "value": ""}), unasked, "runsc"), Guard::Loosens); + assert_eq!(lan_guard("box", &json!({"op": "runtime", "value": " runsc"}), unasked, "runsc"), Guard::Loosens); + assert_eq!(lan_guard("box", &json!({"op": "runtime", "value": ""}), unasked, "runc"), Guard::Keeps); + // Names exactly as AnyBot spells them, or not at all (phone_act trimmed 「direct_mode 」 + // after the guard had read it as something else). + for k in ["direct_mode ", " direct_mode", "Direct_mode", "direct_mode\u{3000}", "direct_mode\u{a0}", "\tdirect_mode", "rule_add ", "auto_review\n"] { + assert_eq!(g("setting", json!({"key": k, "list": "allow", "value": true})), Guard::Unknown, "{k:?}"); + } + for l in ["allow ", " ask", "Allow", "ASK", "ask\u{3000}", ""] { + assert_eq!(g("setting", json!({"key": "rule_add", "list": l, "value": "x"})), Guard::Unknown, "{l:?}"); + } + for k in ["abilities ", " may_use", "Tools", "team\u{a0}"] { + assert_eq!(lan_guard("bot", &json!({"bot": 1, "key": k, "value": ["web"]}), || Value::Null, "runc"), Guard::Unknown, "{k:?}"); + } + assert_eq!(g("box", json!({"op": "runtime "})), Guard::Unknown); + // An action no one put on either side is refused, not let through (import_bot was). + for a in ["made_up", "Setting", "import_bot ", ""] { + assert_eq!(g(a, json!({})), Guard::Unknown, "{a:?}"); + } + for a in ["import_bot", "export_bot", "search", "chatgpt", "skill", "app", "group_chat", "delete_bot"] { + assert_eq!(g(a, json!({})), Guard::Keeps, "{a}"); + } + // A group shared with the team: adding a member lets the teammates reach that bot. + let shared = || json!({"team": true, "members": [{"id": 2}, {"id": 3}]}); + let private = || json!({"team": false, "members": [{"id": 2}, {"id": 3}]}); + let members = |ids: Value, now: &dyn Fn() -> Value| lan_guard("bot", &json!({"bot": 9, "key": "members", "value": ids}), now, "runc"); + assert_eq!(members(json!([2, 3, 4]), &shared), Guard::Loosens); + assert_eq!(members(json!([2]), &shared), Guard::Keeps); + assert_eq!(members(json!([2, 3, 4]), &private), Guard::Keeps); + assert_eq!(members(json!([2, 4]), &|| Value::Null), Guard::Loosens); + // Abilities and computers: unticking one is tighter (it used to be refused too); ticking + // one that is off now, or one the bot doesn't have, is looser. + let detail = || json!({"abilities": [{"key": "web", "on": true}, {"key": "files", "on": true}, {"key": "admin", "on": false}], "may_use": [{"key": "Bot 的電腦", "on": true}, {"key": "伺服器", "on": false}]}); + let bot = |key: &str, ticked: Value, now: &dyn Fn() -> Value| lan_guard("bot", &json!({"bot": 1, "key": key, "value": ticked}), now, "runc"); + assert_eq!(bot("abilities", json!(["web"]), &detail), Guard::Keeps); + assert_eq!(bot("abilities", json!(["web", "files"]), &detail), Guard::Keeps); + assert_eq!(bot("abilities", json!(["web", "files", "admin"]), &detail), Guard::Loosens); + assert_eq!(bot("abilities", json!(["web", "made-up"]), &detail), Guard::Loosens); + assert_eq!(bot("abilities", json!(["web "]), &detail), Guard::Loosens); + assert_eq!(bot("may_use", json!(["Bot 的電腦"]), &detail), Guard::Keeps); + assert_eq!(bot("may_use", json!(["Bot 的電腦", "伺服器"]), &detail), Guard::Loosens); + // The bot couldn't be asked: nothing counts as on. + assert_eq!(bot("abilities", json!(["web"]), &|| Value::Null), Guard::Loosens); + assert!(!LOOSEN_REFUSED.contains("加密") && LOOSEN_REFUSED.contains("只能收緊、不能放寬")); + } + #[test] fn roles_gate_the_sync_and_hands_apis() { // 大腦 sync (mirror) and 裝置連結 (device) are separate doors on the hands machine: @@ -2962,12 +3131,6 @@ mod tests { assert!(!role_allows("admin", "GET", &["api", "sync"])); // A role the relay didn't name is nobody's. assert!(!role_allows("none", "GET", &["api", "state"])); - // 區網 can't switch a guard off; turning one on, or an ask rule, is fine. - assert!(loosens_guard("setting", &json!({"key": "direct_mode", "value": true}))); - assert!(!loosens_guard("setting", &json!({"key": "direct_mode", "value": false}))); - assert!(loosens_guard("setting", &json!({"key": "rule_add", "list": "allow", "value": "x"}))); - assert!(!loosens_guard("setting", &json!({"key": "rule_add", "list": "ask", "value": "x"}))); - assert!(loosens_guard("mcp", &json!({"add": {"url": "https://x"}}))); assert!(role_allows("member", "POST", &["api", "bots", "1", "send"])); assert!(!role_allows("member", "POST", &["api", "bots", "1", "stop"])); @@ -3038,6 +3201,25 @@ mod tests { let cmds = hub().take_cmds(); assert!(cmds.iter().any(|c| matches!(c, Cmd::DeviceAdded(d) if d.name == "iPhone"))); assert!(cmds.contains(&Cmd::Send { bot: 1, text: "你好".into(), attachments: vec![], from: String::new(), memories: Some(vec![]), member: false }) || cmds.contains(&Cmd::Send { bot: 1, text: "你好".into(), attachments: vec![], from: String::new(), memories: None, member: false })); + // 「/always-approve」 typed on a direct connection is the 直接操作 switch in other words: + // refused, nothing queued (it turned 直接操作 and 一律放行 on); status and off go through, + // and so does the owner through the account. + let say = |text: &str, relay: bool| { + let mut r = Req { method: "POST".into(), path: "/api/bots/1/send".into(), body: json!({"text": text}).to_string().into_bytes(), ..Default::default() }; + r.headers = req.headers.clone(); + if relay { + r.headers.insert("x-anybot-role".into(), "owner".into()); + } + let status = handle(r, relay).status; + let sent = hub().take_cmds().into_iter().any(|c| matches!(c, Cmd::Send { text: t, .. } if t == text)); + (status, sent) + }; + for on in ["/always-approve", "/yolo", "/always-approve on"] { + assert_eq!(say(on, false), (403, false), "{on}"); + } + assert_eq!(say("/always-approve status", false), (200, true)); + assert_eq!(say("/always-approve off", false), (200, true)); + assert_eq!(say("/always-approve", true), (200, true)); // The Mac's own screen stays closed unless allowed. let mut mac = Req { method: "GET".into(), path: "/api/screen/mac".into(), ..Default::default() }; mac.headers = req.headers.clone(); diff --git a/src/share.rs b/src/share.rs index d1b188a..0fc41f6 100644 --- a/src/share.rs +++ b/src/share.rs @@ -41,7 +41,7 @@ pub fn export(b: &Bot) -> String { let mut v = serde_json::to_value(b).unwrap_or(Value::Null); if let Value::Object(m) = &mut v { // (Its 可以用的電腦 are this account's computers by name; its 草稿 is unsent words: neither travels.) - for k in ["messages", "threads", "allow_rules", "memories", "tools_enabled", "default_computer", "unread", "last_turn", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of"] { + for k in ["messages", "threads", "allow_rules", "memories", "tools_enabled", "default_computer", "unread", "last_turn", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of", "team"] { m.remove(k); } if let Some(Value::Array(routines)) = m.get_mut("routines") { @@ -80,13 +80,17 @@ pub fn import(text: &str, new_id: u64, next_routine: &mut u64, now: i64) -> Resu if let Value::Object(m) = &mut v { m.insert("id".into(), Value::from(new_id)); m.insert("messages".into(), Value::Array(vec![])); - // Never import another person's grants, local workdir, threads or memories. - for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn"] { + // Never import another person's grants, local workdir, threads or memories — nor its + // sharing with a team (a file carrying 「team」 shared the new bot at once). + for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn", "team", "branches", "branch_of"] { m.remove(k); } } let mut b: Bot = serde_json::from_value(v).map_err(|e| format!("檔案內容不完整:{e}"))?; b.tools_enabled = false; + b.team = false; + b.branch_of = 0; + b.branches.clear(); b.allow_rules.clear(); b.workdir = crate::model::default_workdir(); b.default_computer.clear(); @@ -157,6 +161,14 @@ mod tests { assert!(got.routines[0].paused, "a trigger waits for the new owner's token"); assert_eq!(got.demos[0].steps, vec!["點 (1, 2)".to_string()]); assert!(import("{}", 1, &mut next, 0).is_err()); + // Sharing with a team doesn't travel either way: not written, and a file that carries it + // brings a bot nobody else can reach (it used to share the new bot at once). + let mut shared = b.clone(); + shared.team = true; + assert!(!export(&shared).contains("\"team\"")); + let crafted = text.replacen("\"name\"", "\"team\":true,\"branch_of\":3,\"name\"", 1); + let got = import(&crafted, 98, &mut next, crate::routines::now()).unwrap(); + assert!(!got.team && got.branch_of == 0, "{got:?}"); st.bots.clear(); } } diff --git a/src/tools.rs b/src/tools.rs index f8a918a..7b5345c 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -102,6 +102,7 @@ pub fn label(name: &str) -> &'static str { "browser_fill_card" => "填入卡片", "browser_fill_contact" => "填入聯絡資訊", crate::mcp::FIND_TOOL => "找連接器的工具", + crate::agent::REPLAY_TOOL => "重播技能", n if n.starts_with(crate::mcp::PREFIX) || n == crate::mcp::USE_TOOL => "用連接器", _ => "工具", } @@ -163,10 +164,11 @@ pub fn describe(name: &str, args: &str) -> String { if site.is_empty() { "目前的網站".into() } else { site } } "browser_fill_card" | "browser_fill_contact" => "目前的網頁".into(), - _ => { - let p = arg_str(&v, "path"); - if p.is_empty() { "工作資料夾".into() } else { p } - } + crate::agent::REPLAY_TOOL => format!("「{}」", arg_str(&v, "name")), + // A file step names its file; list_dir without one lists the working folder. Any other + // tool has no folder to name (replay_skill read 「工作資料夾」). + "list_dir" if arg_str(&v, "path").is_empty() => "工作資料夾".into(), + _ => arg_str(&v, "path"), } } @@ -3293,6 +3295,19 @@ mod tests { assert!(matches!(decide_file_out(&t, "/etc/passwd", &[]), Decision::Deny(_))); } + /// A step's line says what it did and on what: a replay names its skill (it read 「工具 + /// 工作資料夾」); only a file step names a folder. + #[test] + fn a_step_names_what_it_did() { + assert_eq!(label(crate::agent::REPLAY_TOOL), "重播技能"); + assert_eq!(describe(crate::agent::REPLAY_TOOL, r#"{"name":"記一筆","values":{"內容":"x"}}"#), "「記一筆」"); + assert_eq!(crate::remote::tool_detail(crate::agent::REPLAY_TOOL, r#"{"name":"記一筆"}"#), "「記一筆」"); + assert_eq!(describe("list_dir", "{}"), "工作資料夾"); + assert_eq!(describe("read_file", r#"{"path":"a.txt"}"#), "a.txt"); + assert_eq!(describe("react", r#"{"emoji":"👍"}"#), ""); + assert_eq!(crate::remote::tool_detail("message_bot", r#"{"bot":"同事","text":"早安"}"#), "給 同事:早安"); + } + // (The tool specs are the bot's view of the computer: a name, description or parameter // changed by accident (or by a UI refactor that brushed past this file) silently breaks // how the bot works. Every change must show up as a reviewed diff in the lock file, and diff --git a/src/vault.rs b/src/vault.rs index 57d7d56..6cc73d2 100644 --- a/src/vault.rs +++ b/src/vault.rs @@ -889,14 +889,14 @@ mod tests { // What the bot sees has no secrets. let seen = list_for_bot("{}"); assert!(seen.contains("tester@example.org") && seen.contains("1111") && !seen.contains("4111111111111111") && !seen.contains("pa\\\"ss") && !seen.contains("123\""), "{seen}"); - crate::botbrowser::open(&format!("http://127.0.0.1:{port}/login"), Some("vault-test"))?; + crate::botbrowser::open(&format!("http://127.0.0.1:{port}/login"), Some("vault-test"), false)?; let plan = plan_login("{}")?; assert!(plan.matched && plan.item.as_ref().map(|i| i.id == login).unwrap_or(false)); let said = fill_login(&plan, false)?; assert!(!said.contains("pa\"ss"), "{said}"); let (_, got) = crate::botbrowser::eval_current(None, "JSON.stringify([e.value, p.value])")?; assert_eq!(got.as_str().unwrap(), r#"["tester@example.org","pa\"ss 你好"]"#); - crate::botbrowser::open(&format!("http://127.0.0.1:{port}/checkout"), Some("vault-test"))?; + crate::botbrowser::open(&format!("http://127.0.0.1:{port}/checkout"), Some("vault-test"), false)?; let said = fill_card(&format!("{{\"card_id\":\"{card}\"}}"))?; assert!(!said.contains("4111111111111111") && !said.contains("123"), "{said}"); fill_contact(&format!("{{\"contact_id\":\"{contact}\"}}"))?; diff --git a/src/web.rs b/src/web.rs index 85688e5..f17ec40 100644 --- a/src/web.rs +++ b/src/web.rs @@ -106,6 +106,8 @@ pub fn describe(name: &str, args: &str) -> String { "browser_profiles" => match (arg(&v, "action").as_str(), arg(&v, "name")) { ("add" | "create", n) => format!("新增「{n}」"), ("use" | "switch", n) => format!("切換到「{n}」"), + // The model's call: a name alone switches to it (adding it when it is new). + ("", n) if !n.is_empty() => format!("切換到「{n}」"), _ => "列出設定檔".into(), }, n if crate::browser::is_tool(n) => crate::browser::describe(n, args), @@ -151,7 +153,7 @@ pub fn run(name: &str, args: &str, cancel: &AtomicBool) -> (String, bool) { "web_fetch" => fetch(&arg(&v, "url")), "browser_open" if crate::botbrowser::available() && uses_person_browser(args) => browser_open(&arg(&v, "url"), cancel), "browser_read" if crate::botbrowser::available() && uses_person_browser(args) => browser_read(v.get("max_chars").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(MAX_PAGE_CHARS).min(MAX_PAGE_CHARS * 2), cancel), - "browser_open" if crate::botbrowser::available() => normalize_url(&arg(&v, "url")).and_then(|u| crate::botbrowser::open(&u, Some(arg(&v, "profile").as_str()))), + "browser_open" if crate::botbrowser::available() => normalize_url(&arg(&v, "url")).and_then(|u| crate::botbrowser::open(&u, Some(arg(&v, "profile").as_str()), v["_this_step_only"] == true)), "browser_read" if crate::botbrowser::available() => crate::botbrowser::read(v.get("max_chars").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(MAX_PAGE_CHARS).min(MAX_PAGE_CHARS * 2), Some(arg(&v, "profile").as_str())), "browser_profiles" if crate::botbrowser::available() => crate::botbrowser::profiles_tool(&arg(&v, "action"), &arg(&v, "name")), "browser_profiles" => Err("設定檔要 AnyBot 自己的瀏覽器(需要 Chrome、Brave、Edge、Chromium 或 Firefox)。現在用的是你自己的 Safari。".into()),