合併: /plan 先規劃再動手、聊天裡管理連接器、/always-approve 一律放行、輸入框上方狀態不破版

This commit is contained in:
王性驊 2026-11-17 10:55:37 +08:00
commit 77c55e00ba
31 changed files with 2195 additions and 25 deletions

View File

@ -486,7 +486,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
### 「/」清單只放指令 ### 「/」清單只放指令
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/btw),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
- 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。
### 上線前補上的防護(安全和資源) ### 上線前補上的防護(安全和資源)
@ -1489,6 +1489,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。 - **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。
- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。 - 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。
- 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。 - 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。
- **在聊天裡請 Bot 加**(設定畫面能做的,聊天也能做):有「管理 App」能力的 Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器。改的就是大腦上「設定 › 整合 › 連接器」那一份(Bot 的這一輪本來就在大腦上跑),所以每台螢幕電腦和手機都看得到,不會寫到手腳電腦(例如 nobledesktop 上的 ~/.local/share/AnyBot)那邊的檔案。新增、修改、移除先跳「允許…管理連接器嗎?」卡片,列出要執行的指令或網址、環境變數和標頭;名字像金鑰的(TOKEN、KEY、SECRET、PASS、AUTH…)和密碼顯示成「••••(已填)」。加好後等它連上(最多 90 秒)再回報「已連上,N 個工具」或連不上的原因;連上的工具同一輪的下一步就能用(例如「加上 GitLab,然後列出我的 MR」一次做完)。名稱重複、command 和 url 都給、網址不是 http(s)、還有「{…}」沒填、要改卻沒東西可改,都在問你之前就回給 Bot 說原因。
### 記憶、技能、範本 ### 記憶、技能、範本
@ -1523,6 +1524,20 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- **權限不變**:要你核准的步驟照樣停下來等;要放著讓它自己做完,Bot 要開「直接操作」或「自動審核」(Claude Code 也要配 auto mode)。 - **權限不變**:要你核准的步驟照樣停下來等;要放著讓它自己做完,Bot 要開「直接操作」或「自動審核」(Claude Code 也要配 auto mode)。
- **終端機**:`anybot --ask "/goal …"` 會一直做到達成、做不到或暫停才結束(像 `claude -p "/goal …"`),最長 ANYBOT_ASK_SECS 秒(預設 900)。 - **終端機**:`anybot --ask "/goal …"` 會一直做到達成、做不到或暫停才結束(像 `claude -p "/goal …"`),最長 ANYBOT_ASK_SECS 秒(預設 900)。
- 實測(假的 OpenAI 相容模型,獨立的大腦):「兩步」的目標第一輪檢查說還差第二步,AnyBot 自己開第二輪,第二輪後判定達成;永遠沒進展的目標在第 3 輪暫停;要登入的目標判定在等使用者而暫停,回一句「我登入了」後接著做並達成;目標的那幾行沒有出現在任何一次送給模型的內容裡。 - 實測(假的 OpenAI 相容模型,獨立的大腦):「兩步」的目標第一輪檢查說還差第二步,AnyBot 自己開第二輪,第二輪後判定達成;永遠沒進展的目標在第 3 輪暫停;要登入的目標判定在等使用者而暫停,回一句「我登入了」後接著做並達成;目標的那幾行沒有出現在任何一次送給模型的內容裡。
- **/always-approve 一律放行**(也可以打 /yolo;像 Claude Code 的 bypassPermissions、Codex 的 --yolo):你打一句就把自己的權限一把全開,不用去設定裡一個個開。
- **打開時做的事**:打開「直接操作」(也就是「在這台電腦上執行」、所有 Bot 的電腦工具),之後所有要等「允許」的卡片都替你按允許,連直接操作還會問的也不問:「一律詢問」規則、付款/傳送/刪除這類點擊、寄信、傳訊息、沙盒外的 AppleScript、打電話、簡訊、在 X 發文、用保險庫的卡片;自動審核也略過(反正都會允許,不用再等一個模型判斷)。打開那一刻你自己的 Bot 正在等的卡片也一起放行。
- **還是會擋的**:安全規則一律拒絕的(sudo、rm -rf /、格式化、金鑰和密碼檔、AnyBot 自己的資料、雲端中繼資料位址)——那是拒絕,不是詢問;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你親手按;問題卡、「需要處理」和 /plan 的計畫卡要的是你的回答或你的手,照樣等你。
- **只有你能開**:聊天裡你自己打(電腦、大腦的螢幕、手機用擁有者身分),或 設定 › 權限 ›「一律放行」。Bot、例行任務、訊息管道都打不開;團隊管理員和成員打的會變成「【名字】/always-approve」交給 Bot,不是指令。管理員(MDM)鎖了直接操作或「在這台電腦上執行」就打不開。
- **看得到它開著**:每個聊天的輸入框上方一條「一律放行 · Bot 做事不再問你」,右邊「關閉」。重開 AnyBot 還開著。
- **關掉**:「/always-approve off」(或條上的「關閉」、設定的開關):要核准的又會問;直接操作如果是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在怎樣。
- **/plan 計畫**(照 Claude Code 的 plan mode、Cursor 的 Plan Mode、Codex 的 update_plan 做):先規劃、你核准後才動手。適合會動到很多東西、做錯很麻煩的事(搬家、改設定、一連串對外送出)。
- **用法**:「/plan 要做的事」開始(Bot 正在做事時不行,先等它做完或按停止);「/plan」看計畫和進度;「/plan clear」取消(stop、取消…也可以)。電腦、大腦的螢幕、手機打的都算,由大腦處理;團隊的管理員也能用,成員和訊息管道打的不算指令。群組聊天還不能用;最多 4000 字。
- **計畫模式(還沒核准)**:Bot 只能看——讀檔、列資料夾、搜尋、讀網頁(web_fetch、瀏覽器打開/讀取/捲動)、截圖、查記憶和技能、查功能地圖。執行指令、改檔案、點擊、打字、送出、改設定在執行那一層就被擋下,回給 Bot「計畫還沒核准」(不是只靠提示詞,跟 Claude Code、Codex、Gemini CLI 一樣)。它先自己查清楚現況,查得到的不問;有你才能決定的取捨,用問題卡一次問完(最多 3 題、建議的放第一個),你略過就用建議的並寫成假設。
- **計畫卡**:Bot 用 submit_plan 交出計畫,聊天裡是一張「計畫」卡:一兩句摘要、照順序的步驟(通常 3 到 7 步,每步是一個看得到的結果,最後一步是驗證)、「怎麼確認做對了」、「注意」(假設、風險、花錢、對外送出、不能復原的)。只寫它建議的那一個做法。研究顯示錯的計畫比沒有計畫更糟,所以要求它根據查到的事實、寧可短而對。
- **核准**:輸入框上方的問題卡「照這個計畫做嗎?」:「開始照計畫做」、「先不要」,或直接打字寫要改哪裡(它改完再交一張新卡,舊卡變「已修改,見下面新版」)。在卡片外傳訊息也算要修改;只有按「開始照計畫做」才算核准,不會等太久自己核准。按「先不要」或略過,計畫就取消,什麼都沒做。
- **照計畫做**:核准後同一輪接著做(不用再傳訊息),所有工具打開,第 1 步自動標成進行中;它每做完一步用 update_plan 更新一次(整份清單、同時只有一步進行中;不用每個小動作都更新——Manus 發現打勾佔了三分之一的動作)。計畫和實際不符就改清單並在訊息裡說為什麼,大改先問。卡上的步驟跟著打勾(✓ 做完、▸ 進行中、– 略過),輸入框上方一行「照計畫做 · 2/5 · 現在這一步」,滑過去看整份清單,右邊「取消計畫」。全部做完那一輪結束時留一行「計畫完成:5 步都做完了。」,計畫清掉。
- **只管你自己的訊息**:例行任務、訊息管道和團隊成員的訊息照平常做,不受計畫模式限制。照計畫做的期間每一輪都帶著這份計畫(像 Claude Code 把核准的計畫交回給模型),所以聊別的事前先取消。清除聊天記錄、開始新對話會連計畫一起清掉;分享 Bot 的檔案不含計畫。重開 AnyBot 計畫還在;還沒核准時重開,傳一句話它就接著規劃。
- 手機一樣:計畫卡、問題卡、計畫列和「取消計畫」都有。
- **外觀(Bot 是主角)**:介面本身安靜(黑、白、灰),顏色和動作都留給 Bot。 - **外觀(Bot 是主角)**:介面本身安靜(黑、白、灰),顏色和動作都留給 Bot。
- **字型**:介面用思源黑體(Noto Sans TC),讀的文字——Bot 的回答、頁面內文和標題——用思源宋體(Noto Serif TC),像 Claude 的回答一樣是書的字;兩種都有 Regular 和 Bold,包在 App 裡,每台電腦看起來一樣。程式碼用系統的等寬字。沒有字型選項。 - **字型**:介面用思源黑體(Noto Sans TC),讀的文字——Bot 的回答、頁面內文和標題——用思源宋體(Noto Serif TC),像 Claude 的回答一樣是書的字;兩種都有 Regular 和 Bold,包在 App 裡,每台電腦看起來一樣。程式碼用系統的等寬字。沒有字型選項。
- **你的訊息是淡灰泡泡**(預設「安靜」;設定 › 一般 › 聊天的顏色可以改成「跟著 Bot」:你的訊息泡泡、送出鈕、側邊欄選中的那格用 Bot 的顏色,或「只用黑色」)。Bot 的回覆不用泡泡,像文件一樣排在頁面上,只有錯誤訊息有泡泡。 - **你的訊息是淡灰泡泡**(預設「安靜」;設定 › 一般 › 聊天的顏色可以改成「跟著 Bot」:你的訊息泡泡、送出鈕、側邊欄選中的那格用 Bot 的顏色,或「只用黑色」)。Bot 的回覆不用泡泡,像文件一樣排在頁面上,只有錯誤訊息有泡泡。

View File

@ -42,6 +42,7 @@ AnyBot 的功能,照「行為」整理:一區一份檔,每份都回答同
### 自己會動 ### 自己會動
- [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。 - [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。
- [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。 - [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。
- [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。
### 在電腦上做事 ### 在電腦上做事
- [computers](computers.md):大腦與手腳、這台電腦、SSH、帳號裡的其他電腦、雲端電腦。 - [computers](computers.md):大腦與手腳、這台電腦、SSH、帳號裡的其他電腦、雲端電腦。

View File

@ -5,7 +5,7 @@
## 子功能 ## 子功能
- 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。 - 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/btw,打「@」列出其他 Bot。 - 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md)),打「@」列出其他 Bot。
- 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。 - 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。
- 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。
- 停止:工作中、輸入框空著時,送出鈕變成「停止」。 - 停止:工作中、輸入框空著時,送出鈕變成「停止」。

View File

@ -12,18 +12,21 @@
- 「公用市集(官方 MCP Registry)」:搜尋用網址連的連接器,按「加入」會填好表單;還有「{…}」沒換成你的值時,按不下「新增」。 - 「公用市集(官方 MCP Registry)」:搜尋用網址連的連接器,按「加入」會填好表單;還有「{…}」沒換成你的值時,按不下「新增」。
- 給 Bot 的方式:所有連接器加起來 20 個工具以內,每個工具直接給,名字是 `mcp__連接器__工具`;超過 20 個,只給 `find_connector_tool` 和 `use_connector_tool`。 - 給 Bot 的方式:所有連接器加起來 20 個工具以內,每個工具直接給,名字是 `mcp__連接器__工具`;超過 20 個,只給 `find_connector_tool` 和 `use_connector_tool`。
- 工具回的文字和圖片都交給 Bot;一次最多等 120 秒。 - 工具回的文字和圖片都交給 Bot;一次最多等 120 秒。
- 在聊天裡請 Bot 加:Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器,跟設定畫面是同一份清單(大腦的),不會寫到別台電腦的檔案。新增、修改、移除先跳卡片給你看(指令在大腦上執行;金鑰、Token、密碼顯示成「••••(已填)」);加好會等它連上(最多 90 秒)再回報幾個工具,同一輪就能用。
## 使用者怎麼到 ## 使用者怎麼到
- 設定 ›「整合」›「連接器」分頁:上面「連接器(MCP)」列出已接上的,下面「連接器市集」「新增連接器」「公用市集(官方 MCP Registry)」。 - 設定 ›「整合」›「連接器」分頁:上面「連接器(MCP)」列出已接上的,下面「連接器市集」「新增連接器」「公用市集(官方 MCP Registry)」。
- 連接器在大腦上跑。在螢幕上看大腦時,開關就是大腦上的開關,錯誤前面會寫「在大腦上:」。 - 連接器在大腦上跑。在螢幕上看大腦時,開關就是大腦上的開關,錯誤前面會寫「在大腦上:」。
- 手機:設定 ›「整合」列出連接器(開關、重新連線、移除),還有「從公用市集加入」(只有擁有者能用)。 - 手機:設定 ›「整合」列出連接器(開關、重新連線、移除),還有「從公用市集加入」(只有擁有者能用)。
- 聊天:直接請 Bot「幫我加上 GitLab 的連接器」,給它網址或指令和 Token;它要「管理 App」能力。
- Bot 設定 ›「能力」›「連接器」沒開,Bot 就沒有連接器工具。 - Bot 設定 ›「能力」›「連接器」沒開,Bot 就沒有連接器工具。
## 怎麼操作 ## 怎麼操作
- Bot:工具少時直接呼叫那個 `mcp__…` 工具。工具多時先 `find_connector_tool`:`query` 用功能的字找(英文比較準),或只給 `server` 列出那個連接器全部工具的名字;結果有完整名稱、說明和參數,再用 `use_connector_tool`(`tool` 是完整名稱,`arguments` 是參數)。名字給錯會叫你先找。 - Bot:工具少時直接呼叫那個 `mcp__…` 工具。工具多時先 `find_connector_tool`:`query` 用功能的字找(英文比較準),或只給 `server` 列出那個連接器全部工具的名字;結果有完整名稱、說明和參數,再用 `use_connector_tool`(`tool` 是完整名稱,`arguments` 是參數)。名字給錯會叫你先找。
- 驗證:在「連接器市集」加入 time,卡片要變成「已連上,2 個工具」;請 Bot 查台北現在幾點:第一次要跳「使用連接器「time」的工具:…」,選一律允許後同一個連接器不再問。關掉開關後開新的一輪,Bot 不該再有它的工具。再加入 playwright(工具超過 20 個),Bot 拿到的要變成 `find_connector_tool` 和 `use_connector_tool`。自動測試:`cargo test mcp::`、`cargo test profile::`;實機(要網路、Node.js、uv):`cargo test --release -- --ignored marketplace`、`cargo test registry_search_live -- --ignored`。 - Bot(管理):`manage_connectors`:`action` 是 list、add(name,加 command 或 url,env、headers、username、password、instructions)、update(只給要改的;換了指令或網址沒給新密碼,舊密碼清掉)、remove、reconnect。加之前先在自己的電腦跑一次指令確認能動;秘密放 env、headers 或 password,不要寫進 instructions。
- 驗證:在聊天請 Bot 加 time 連接器(`uvx mcp-server-time`):要先跳「新增連接器「time」」卡片,允許後 設定 › 整合 › 連接器 多一列「已連上,2 個工具」、Bot 同一輪就能查時間;在螢幕電腦和手機上也看得到這一列。請它關掉、再移除,各跳一次卡片。在「連接器市集」加入 time,卡片要變成「已連上,2 個工具」;請 Bot 查台北現在幾點:第一次要跳「使用連接器「time」的工具:…」,選一律允許後同一個連接器不再問。關掉開關後開新的一輪,Bot 不該再有它的工具。再加入 playwright(工具超過 20 個),Bot 拿到的要變成 `find_connector_tool` 和 `use_connector_tool`。自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`;實機(要網路、Node.js、uv):`cargo test --release -- --ignored marketplace`、`cargo test registry_search_live -- --ignored`。
## 陷阱 ## 陷阱

32
docs/feature-map/plan.md Normal file
View File

@ -0,0 +1,32 @@
# 計畫(/plan)
先規劃再動手:Bot 先查清楚、寫出計畫,使用者核准後才照著做,做的時候一步一步打勾。
## 子功能
- 開始:「/plan 要做的事」(最多 4,000 字)。「/plan」看目前的計畫,「/plan clear」(或 stop、取消)取消。
- 計畫模式(還沒核准):只能看——讀檔、列資料夾、搜尋、`web_fetch`、瀏覽器的打開/讀取/捲動、截圖、查記憶和技能、`anybot_guide`。執行指令、改檔案、點擊、打字、送出、改設定都會被擋下(擋在執行那一層,不是只靠提醒)。有使用者才能決定的取捨,用問題卡一次問完(最多 3 題,建議的選項在第一個);略過的話 Bot 用建議的那個,寫成假設。
- 計畫卡:Bot 用 `submit_plan` 交出計畫,聊天裡出現一張「計畫」卡:一兩句摘要、照順序的步驟(通常 3 到 7 步,最後一步是驗證)、「怎麼確認做對了」、「注意」(假設、風險、會花錢或對外送出的地方)。卡右上角寫狀態:等你決定、照著做 · 2/5、已核准、已修改(見下面新版)、沒有採用;修改過或沒採用的只剩摘要。
- 核准:輸入框上方的問題卡「照這個計畫做嗎?」:「開始照計畫做」、「先不要」,或直接打字寫要改哪裡(Bot 改完再交一張新卡)。在卡片之外傳訊息也算要修改;只有按「開始照計畫做」才算核准,不會自己過期核准。
- 照計畫做:核准後同一輪接著做,工具全部打開,第 1 步自動標成進行中。Bot 每做完一步用 `update_plan` 更新一次(整份清單,同時只有一步進行中);計畫和實際不符就改清單並說為什麼,大改先問。計畫卡上的步驟跟著打勾(✓ 做完、▸ 進行中、– 略過)。
- 完成:全部步驟做完(或略過)那一輪結束時,聊天裡留一行「計畫完成:5 步都做完了。」,計畫清掉。
## 使用者怎麼到
- 在輸入框打「/」選 /plan,或直接打「/plan 要做的事」送出(手機一樣)。Bot 正在做事時不能開始,要等它做完或先按停止。
- 有計畫時,輸入框上方有一條計畫列:「計畫模式 · 只查資料、寫計畫,你核准後才動手」或「照計畫做 · 2/5 · 現在這一步」;滑過去看要做的事和整份清單,旁邊有「取消計畫」。
- 計畫存在 Bot 身上,重開 AnyBot 還在;還沒核准時重開,等你傳一句話它就接著規劃、重交一張卡。
## 怎麼操作
- Bot:計畫模式裡多一個 `submit_plan`(summary、steps[title、detail]、check、notes),只開放會看的工具和 `ask_person`;核准後多一個 `update_plan`(steps:title 和 status:pending、in_progress、done、skipped)。不要在訊息裡把計畫再寫一次,卡片會顯示。
- 驗證:對 Bot 打「/plan 在工作資料夾建立 hello.txt,內容是 hi」:計畫列出現、它不建檔、交出一張計畫卡和「照這個計畫做嗎?」;在卡上打「檔名改成 hi.txt」要收到新版卡、舊卡變「已修改」;按「開始照計畫做」後它建檔、卡上步驟打勾、做完留「計畫完成」那一行、計畫列消失。再試一次按「先不要」:計畫列消失、什麼都沒做。計畫模式時叫它執行指令,要被擋下並說計畫還沒核准。自動測試:`cargo test plan::`、`cargo test agent::tests::plan`。
## 陷阱
- 計畫模式只管使用者自己的訊息:例行任務、訊息管道和團隊成員傳來的訊息照平常做,不受計畫影響;群組聊天不能用 /plan。
- Bot 漏了 `update_plan`,計畫列會停在舊的步驟,計畫也不會自己結束:叫它更新進度,或「/plan clear」。
- 照計畫做的期間,每一輪都會帶著這份計畫;聊別的事前先取消,免得它一直想回到計畫。
- 清除聊天記錄或開始新對話,計畫跟著清掉。
- 在同一步裡跟計畫一起要求的動作(例如交計畫的同時要執行指令)不會執行:那時還沒核准。
- 終端機的 `anybot --ask "/plan …"` 沒有人按卡片:核准卡會被自動拒絕(等於「先不要」),所以只會規劃、不會動手。

View File

@ -9,6 +9,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
- 一律允許記在那個 Bot 身上(例如「修改檔案」、「npm install」、某個連接器),Bot 設定 ›「電腦操作」的「已設定「一律允許」」看得到,按 × 移除。 - 一律允許記在那個 Bot 身上(例如「修改檔案」、「npm install」、某個連接器),Bot 設定 ›「電腦操作」的「已設定「一律允許」」看得到,按 × 移除。
- 拒絕後停下:同一輪裡 Bot 再提一模一樣的操作(同一個工具、同樣的參數),直接替你拒絕、不再問,直到你再傳一則訊息(工作中插話也算)。按停止、關視窗不算拒絕。 - 拒絕後停下:同一輪裡 Bot 再提一模一樣的操作(同一個工具、同樣的參數),直接替你拒絕、不再問,直到你再傳一則訊息(工作中插話也算)。按停止、關視窗不算拒絕。
- 直接操作:打開時一次做完——打開「在這台電腦上執行」、自動審核、所有 Bot 的電腦工具;「一律詢問」規則是空的就填三條預設(刪除檔案或資料夾/付款、購買或轉帳/用我的帳號發文、留言,或傳訊息給別人);進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。 - 直接操作:打開時一次做完——打開「在這台電腦上執行」、自動審核、所有 Bot 的電腦工具;「一律詢問」規則是空的就填三條預設(刪除檔案或資料夾/付款、購買或轉帳/用我的帳號發文、留言,或傳訊息給別人);進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。
- 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的(「一律詢問」規則、付款/傳送/刪除的點擊、寄信、傳訊息、AppleScript、打電話、簡訊、在 X 發文、保險庫卡片)也不問,自動審核也略過。仍然擋:安全規則一律拒絕的(下面那串);別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方有一條「一律放行 · Bot 做事不再問你」和「關閉」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。
- 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的;畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 - 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的;畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。
- 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。 - 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。
- 安全規則(你的電腦上): - 安全規則(你的電腦上):
@ -36,6 +37,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
## 使用者怎麼到 ## 使用者怎麼到
- 請求:在那個 Bot 的聊天,輸入框上方;別的 Bot 在等時,側邊欄寫「需要你允許」。不在 App 前面而且通知開著時跳系統通知、推播到手機;「需要你時響一聲」開著就響。 - 請求:在那個 Bot 的聊天,輸入框上方;別的 Bot 在等時,側邊欄寫「需要你允許」。不在 App 前面而且通知開著時跳系統通知、推播到手機;「需要你時響一聲」開著就響。
- 在任何聊天打「/always-approve」(「/」清單裡有),或 設定 › 權限 ›「一律放行」的開關「什麼都不問,全部直接做」。手機用擁有者身分打也可以;團隊成員、管理員打的不算指令(會變成「【名字】/always-approve」給 Bot)。
- 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。 - 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。
- 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。 - 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。
- 手機:一樣的卡片和 設定 › 權限([phone](phone.md))。 - 手機:一樣的卡片和 設定 › 權限([phone](phone.md))。
@ -43,12 +45,13 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
## 怎麼操作 ## 怎麼操作
- Bot:不能替你按允許,也不能點 AnyBot 的核准按鈕;被拒後不要再試同一件事,也不要換個寫法做。`update_settings` 改不了這些開關(打開「在這台電腦上執行」只有使用者能做)。要你親手做的步驟用 `hand_over_computer`,要你決定的用 `ask_person`([chat](chat.md))。 - Bot:不能替你按允許,也不能點 AnyBot 的核准按鈕;被拒後不要再試同一件事,也不要換個寫法做。`update_settings` 改不了這些開關(打開「在這台電腦上執行」只有使用者能做)。要你親手做的步驟用 `hand_over_computer`,要你決定的用 `ask_person`([chat](chat.md))。
- 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`。 - 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。打「/always-approve」後再請它在你的電腦執行 `printf ok`(訊息裡指名你的電腦),不該跳卡片、結果有 ok;用訊息管道傳同一句,照樣要你按;「/always-approve off」後又會問。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`、`cargo test always`。
## 陷阱 ## 陷阱
- 請求只在那個 Bot 的聊天裡(輸入框上方),沒有蓋住整個視窗的彈出視窗;在別的 Bot 那裡看不到卡片,要看側邊欄。 - 請求只在那個 Bot 的聊天裡(輸入框上方),沒有蓋住整個視窗的彈出視窗;在別的 Bot 那裡看不到卡片,要看側邊欄。
- 「在這台電腦上執行」選了「永不允許」,打開直接操作也不能在這台做事。 - 「在這台電腦上執行」選了「永不允許」,打開直接操作也不能在這台做事。
- 一律放行會一直開著(重開 AnyBot 也是),例行任務半夜也照樣直接做;用完記得「/always-approve off」。Bot 自己、例行任務、訊息管道都打不開它,只有你打的指令或設定的開關可以。
- 「一律允許」每個 Bot 各記各的,換一個 Bot 還會再問。 - 「一律允許」每個 Bot 各記各的,換一個 Bot 還會再問。
- 拒絕只擋一模一樣的操作;換個寫法擋不住,要靠 Bot 自己停。 - 拒絕只擋一模一樣的操作;換個寫法擋不住,要靠 Bot 自己停。
- 外面的訊息和團隊成員的訊息不用你的「一律允許」、直接操作和自動審核:要核准的事都得你親手按;AnyBot 瀏覽器(帶著你的登入)和保險庫完全不給用。 - 外面的訊息和團隊成員的訊息不用你的「一律允許」、直接操作和自動審核:要核准的事都得你親手按;AnyBot 瀏覽器(帶著你的登入)和保險庫完全不給用。

View File

@ -24,7 +24,7 @@
- Bot 的電腦:狀態、更新、自動更新、重設、磁碟;終端機與環境密鑰;在哪裡執行(Docker 主機、容器隔離)([computers](computers.md))。 - Bot 的電腦:狀態、更新、自動更新、重設、磁碟;終端機與環境密鑰;在哪裡執行(Docker 主機、容器隔離)([computers](computers.md))。
- 「示範教學」:錄下你做一次,Bot 學起來([screen](screen.md))。 - 「示範教學」:錄下你做一次,Bot 學起來([screen](screen.md))。
- 「AnyBot 瀏覽器設定檔」:每個設定檔自己的登入,「做完就關掉瀏覽器」、「發布前檢查」和另外的規則([browser](browser.md))。 - 「AnyBot 瀏覽器設定檔」:每個設定檔自己的登入,「做完就關掉瀏覽器」、「發布前檢查」和另外的規則([browser](browser.md))。
- 「權限」:直接操作開關、自動審核開關、「無需詢問直接允許」和「一律詢問」規則([safety](safety.md))。 - 「權限」:直接操作開關、「一律放行」開關(跟聊天打 /always-approve 一樣)、自動審核開關、「無需詢問直接允許」和「一律詢問」規則([safety](safety.md))。
- 「保險庫」:登入資訊、卡片、聯絡資訊([vault](vault.md))。 - 「保險庫」:登入資訊、卡片、聯絡資訊([vault](vault.md))。
- 「語音」:「語音服務」一張清單,「聽(語音轉文字)」把說的話變文字(語音輸入、語音聊天、會議錄音),「說(朗讀)」把回答唸出來;各自在右邊選服務,選了在那一列下面展開要填的欄位(快速填入、網址、金鑰、模型;「說」還有「聲音」選單),能用了列上寫「可以用」,並有「試試看(說一句話)」或「試聽」。「聲音」選單第一項是「預設(eve)」,下面是服務列出的聲音,選了試唸一句;拿不到清單時選單裡寫原因、可以直接輸入名稱或「再試一次」。每個 Bot 的 對話詳細資訊 › 語音聊天 ›「聲音」是同一個選單(預設是這裡選的聲音)。 - 「語音」:「語音服務」一張清單,「聽(語音轉文字)」把說的話變文字(語音輸入、語音聊天、會議錄音),「說(朗讀)」把回答唸出來;各自在右邊選服務,選了在那一列下面展開要填的欄位(快速填入、網址、金鑰、模型;「說」還有「聲音」選單),能用了列上寫「可以用」,並有「試試看(說一句話)」或「試聽」。「聲音」選單第一項是「預設(eve)」,下面是服務列出的聲音,選了試唸一句;拿不到清單時選單裡寫原因、可以直接輸入名稱或「再試一次」。每個 Bot 的 對話詳細資訊 › 語音聊天 ›「聲音」是同一個選單(預設是這裡選的聲音)。
- 「更新」:「版本」、「自動更新」(你離開時換新版)、「園丁報告」、「待改進」清單([garden](garden.md))、「重新啟動」。 - 「更新」:「版本」、「自動更新」(你離開時換新版)、「園丁報告」、「待改進」清單([garden](garden.md))、「重新啟動」。

View File

@ -280,6 +280,13 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)}
.goalbar .t span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .goalbar .t span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.goalbar.on .t .ic{color:var(--accent)} .goalbar.on .t .ic{color:var(--accent)}
.goalbar button{flex:none;font-size:var(--fs-small);color:var(--text2);padding:4px 8px;border-radius:var(--r-s)} .goalbar button{flex:none;font-size:var(--fs-small);color:var(--text2);padding:4px 8px;border-radius:var(--r-s)}
/* 計畫 (/plan): the plan handed in, as a card — waiting on you (accent edge), followed (its steps tick), or past. */
.card.plan .t{display:flex;align-items:center;gap:6px}.card.plan .t .st{margin-left:auto;font-weight:400;font-size:var(--fs-small);color:var(--text3)}
.card.plan.wait{box-shadow:inset 0 0 0 1px var(--accent)}.card.plan.wait .t .st{color:var(--accent)}
.card.plan .sum{margin:4px 0 2px;color:var(--text)}.card.plan.past .sum{color:var(--text2)}
.card.plan ol{margin:6px 0 0;padding-left:22px}.card.plan li{padding:2px 0}.card.plan li::marker{color:var(--text3)}
.card.plan li .d{display:block;color:var(--text3);font-size:var(--fs-small)}.card.plan li.done{color:var(--text3);list-style-type:"✓ "}.card.plan li.now{list-style-type:"▸ "}.card.plan li.now::marker{color:var(--accent)}.card.plan li.skip{color:var(--text3);text-decoration:line-through;list-style-type:"– "}
.card.plan .x{margin-top:6px;color:var(--text2);font-size:var(--fs-small)}
.msgs .note{align-self:center;display:flex;gap:6px;max-width:min(560px,100%);margin:6px 0;padding:7px 12px;border-radius:var(--r-m);background:var(--hover);color:var(--text2)} .msgs .note{align-self:center;display:flex;gap:6px;max-width:min(560px,100%);margin:6px 0;padding:7px 12px;border-radius:var(--r-m);background:var(--hover);color:var(--text2)}
.msgs .note .ic{flex:none;margin-top:2px;color:var(--text3)} .msgs .note .ic{flex:none;margin-top:2px;color:var(--text3)}
.queued{max-width:560px;margin:0 auto 6px;font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:7px 11px;overflow-wrap:anywhere} .queued{max-width:560px;margin:0 auto 6px;font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:7px 11px;overflow-wrap:anywhere}
@ -596,6 +603,7 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se
<div class="dock"> <div class="dock">
<div id="ask"></div> <div id="ask"></div>
<div id="goalbar"></div> <div id="goalbar"></div>
<div id="planbar"></div>
<div id="queued"></div> <div id="queued"></div>
<div class="quoting" id="quoting" style="display:none"></div> <div class="quoting" id="quoting" style="display:none"></div>
<div class="chips" id="chips"></div> <div class="chips" id="chips"></div>
@ -1348,6 +1356,22 @@ function talkCard(t, status, from) {
else tail = `<div class="tk-st err">${esc(t.answer || "沒有完成")}</div>`; else tail = `<div class="tk-st err">${esc(t.answer || "沒有完成")}</div>`;
return `<div class="talk"><div class="tk-h">${av(me)}<b>${esc(from)}</b>${ic("chevron-right", 12)}${av(to)}<b>${esc(t.to)}</b><span>${t.ask ? "問" : "交辦"}</span></div>${q ? `<div class="tk-q">${esc(q)}</div>` : ""}${tail}${to ? `<button class="tk-go" data-bot="${to.id}">「${esc(t.to)}」那邊的紀錄 ›</button>` : ""}</div>`; return `<div class="talk"><div class="tk-h">${av(me)}<b>${esc(from)}</b>${ic("chevron-right", 12)}${av(to)}<b>${esc(t.to)}</b><span>${t.ask ? "問" : "交辦"}</span></div>${q ? `<div class="tk-q">${esc(q)}</div>` : ""}${tail}${to ? `<button class="tk-go" data-bot="${to.id}">「${esc(t.to)}」那邊的紀錄 ›</button>` : ""}</div>`;
} }
/** 計畫: the plan a bot handed in (`state`: waiting, approved, changed, not_now; `live`: its steps as followed now). */
function planCard(p) {
if (!p || !p.summary) return "";
const st = {waiting: "等你決定", approved: p.live ? `照著做 · ${p.live.filter((s) => s.status === "done" || s.status === "skipped").length}/${p.live.length}` : "已核准", changed: "已修改,見下面新版", not_now: "沒有採用"}[p.state] || "";
const whole = p.state === "waiting" || p.state === "approved";
const cls = p.state === "waiting" ? " wait" : whole ? "" : " past";
let h = `<div class="card plan${cls}"><div class="t">${ic("list-checks", 15)}<span>計畫</span><span class="st">${esc(st)}</span></div><div class="sum">${esc(p.summary)}</div>`;
if (whole) {
const rows = p.live ? p.live.map((s) => ({title: s.title, detail: "", status: s.status})) : (p.steps || []);
h += "<ol>" + rows.map((s) => `<li class="${{done: "done", in_progress: "now", skipped: "skip"}[s.status] || ""}">${esc(s.title)}${s.detail && s.status !== "done" ? `<span class="d">${esc(s.detail)}</span>` : ""}</li>`).join("") + "</ol>";
if (p.check) h += `<div class="x">怎麼確認做對了:${esc(p.check)}</div>`;
if (p.notes) h += `<div class="x">注意:${esc(p.notes)}</div>`;
if (p.state === "waiting") h += `<div class="x">在下面的卡片選「開始照計畫做」,或寫下要改哪裡</div>`;
}
return h + "</div>";
}
function card(c) { function card(c) {
if (!c) return ""; if (!c) return "";
const rows = (c.rows || []).map((r) => `<div class="r"><span>${esc(r.label)}</span><span>${esc(r.value)}</span></div>`).join(""); const rows = (c.rows || []).map((r) => `<div class="r"><span>${esc(r.label)}</span><span>${esc(r.value)}</span></div>`).join("");
@ -1369,7 +1393,7 @@ function renderMsgs() {
S.msgs.forEach((m, i) => { S.msgs.forEach((m, i) => {
if (m.role === "user" || m.summary || m.interrupted || m.note) { curT = null; return; } if (m.role === "user" || m.summary || m.interrupted || m.note) { curT = null; return; }
if (!curT) { curT = {first: i, last: i, key: String(m.at || i), steps: 0}; turns.push(curT); } if (!curT) { curT = {first: i, last: i, key: String(m.at || i), steps: 0}; turns.push(curT); }
curT.last = i; curT.steps += (m.tools || []).filter((t) => !t.page && !t.card).length; curT.last = i; curT.steps += (m.tools || []).filter((t) => !t.page && !t.card && !t.plan && !t.plan_update).length;
}); });
const turnOf = {}; turns.forEach((t) => { for (let i = t.first; i <= t.last; i++) turnOf[i] = t; }); const turnOf = {}; turns.forEach((t) => { for (let i = t.first; i <= t.last; i++) turnOf[i] = t; });
const lastTurn = turns[turns.length - 1]; const lastTurn = turns[turns.length - 1];
@ -1419,6 +1443,8 @@ function renderMsgs() {
(m.tools || []).forEach((x, k) => { (m.tools || []).forEach((x, k) => {
if (x.page) { extra += pageCard(x.page); return; } if (x.page) { extra += pageCard(x.page); return; }
if (x.card) { extra += card(x.card); return; } if (x.card) { extra += card(x.card); return; }
if (x.plan) { extra += planCard(x.plan); return; }
if (x.plan_update) return;
if (x.talk) { extra += talkCard(x.talk, x.status, m.author || (bot(S.open) || {}).name || ""); return; } if (x.talk) { extra += talkCard(x.talk, x.status, m.author || (bot(S.open) || {}).name || ""); return; }
const n = (shown[t.key] = (shown[t.key] || 0) + 1); const n = (shown[t.key] = (shown[t.key] || 0) + 1);
if (unfolded) { steps += stepHtml(x, m.index + ":" + k); return; } if (unfolded) { steps += stepHtml(x, m.index + ":" + k); return; }
@ -1584,6 +1610,12 @@ function renderDockRest(b) {
if (g && owner()) $("goal-x").onclick = async () => { if (g && owner()) $("goal-x").onclick = async () => {
try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/goal clear", attachments: []}}); toast("已清除目標"); loadChat(); } catch (e) { toast(e.message); } try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/goal clear", attachments: []}}); toast("已清除目標"); loadChat(); } catch (e) { toast(e.message); }
}; };
// 計畫: where it is (the steps on hover), and 取消計畫 (sent as 「/plan clear」).
const pl = b.plan;
$("planbar").innerHTML = pl ? `<div class="goalbar on"><div class="t" title="${esc("要做的事:" + pl.task + (pl.steps ? "\n\n" + pl.steps : ""))}">${ic("list-checks", 14)}<span>${esc(pl.line)}</span></div>${owner() ? `<button id="plan-x">取消計畫</button>` : ""}</div>` : "";
if (pl && owner()) $("plan-x").onclick = async () => {
try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/plan clear", attachments: []}}); toast("已取消計畫"); loadChat(); } catch (e) { toast(e.message); }
};
const q = b.queued || []; const q = b.queued || [];
$("queued").innerHTML = q.length ? `<div class="queued">${ic("history", 13)} 已排入:「${esc(q.join("」「"))}」,${esc(b.name)} 會在下一步看到</div>` : ""; $("queued").innerHTML = q.length ? `<div class="queued">${ic("history", 13)} 已排入:「${esc(q.join("」「"))}」,${esc(b.name)} 會在下一步看到</div>` : "";
renderSendBtn(); renderSendBtn();
@ -1624,7 +1656,7 @@ input.addEventListener("keydown", (e) => {
input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } }); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } });
const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false}; 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). */ /** AnyBot's own / commands (goal.rs on the brain). */
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
const GOAL_TAG = "[目標]"; const GOAL_TAG = "[目標]";
/** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name /** 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. */ * contains it, then description. None once a space ends the name, or while the bot works. */
@ -1722,7 +1754,7 @@ async function send() {
const memories = b.busy ? undefined : memPicks(); const memories = b.busy ? undefined : memPicks();
memReset(); memReset();
input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash();
const quiet = /^\/goal(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text); const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text);
if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; }
// 先顯示: while it works the words aren't in the chat yet — shown at once all the same. // 先顯示: while it works the words aren't in the chat yet — shown at once all the same.
const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null; const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null;

View File

@ -92,6 +92,32 @@ pub struct Job {
/// member): no owner memories, grants or direct mode — and no AnyBot browser, which carries /// member): no owner memories, grants or direct mode — and no AnyBot browser, which carries
/// the person's logins. /// the person's logins.
pub untrusted: bool, pub untrusted: bool,
/// 計畫 (/plan) being written: only the tools that look run until the person approves it on
/// the card; then these take over (see plan.rs).
pub drafting: Option<Drafting>,
}
/// What a turn in plan mode switches to once the plan is approved.
pub struct Drafting {
pub plan: crate::plan::Plan,
/// Every tool this turn would have had, with `update_plan`.
pub tools: Vec<serde_json::Value>,
/// The system prompt without the plan-mode part.
pub system: String,
}
/// 計畫模式: the tools offered while a plan is being written — the ones that only look, the
/// browser and the screen (only their looking actions run: see `runs_while_planning`), and the
/// question card.
pub fn offered_while_planning(name: &str) -> bool {
only_looks(name) || name == crate::browser::TOOL || name == crate::computer::TOOL || name == crate::ask::TOOL
}
/// 計畫模式: a step that may run before the plan is approved (by the name it runs as: the
/// browser's and the screen's actions each have their own). Opening and scrolling a page only
/// looks too; typing, clicking, commands, files and anything sent out wait for the approval.
fn runs_while_planning(name: &str) -> bool {
only_looks(name) || matches!(name, "browser_open" | "browser_scroll" | "browser_back" | crate::ask::TOOL | crate::plan::SUBMIT_TOOL)
} }
impl Job { impl Job {
@ -1603,6 +1629,13 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
let mut tools_on = job.tools_enabled; let mut tools_on = job.tools_enabled;
// The screen and browser steps of this turn (to stop the same step being tried over and over). // The screen and browser steps of this turn (to stop the same step being tried over and over).
let mut tried: Vec<String> = Vec::new(); let mut tried: Vec<String> = Vec::new();
// 計畫: the plan the person approved on its card this turn (every tool from the next step
// on), and how many times they sent it back.
let mut plan_go: Option<Vec<crate::plan::Step>> = None;
let mut plan_changes: u32 = 0;
// 連接器: the ones this turn may use, as they were when it started.
let connectors_live = !job.untrusted && !job.lacks.iter().any(|l| l == "connectors");
let mut mcp_sig = crate::mcp::tools_sig();
// Every step's (tool, failed, what it said) this turn: a tool that keeps failing the same // Every step's (tool, failed, what it said) this turn: a tool that keeps failing the same
// way, whatever it is given, is stopped (see same_failures). // way, whatever it is given, is stopped (see same_failures).
let runs: std::cell::RefCell<Vec<(String, bool, String)>> = Default::default(); let runs: std::cell::RefCell<Vec<(String, bool, String)>> = Default::default();
@ -1718,6 +1751,25 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
} }
} }
reuse_slot = false; reuse_slot = false;
// 計畫: approved on the card — from this step on every tool is there, and the model
// is told to follow the plan (no longer to only look).
if let Some(steps) = plan_go.take() {
if let Some(d) = job.drafting.take() {
let doing = crate::plan::Plan { stage: crate::plan::Stage::Doing, steps, ..d.plan };
job.req.tools = d.tools;
job.req.system = format!("{}{}", d.system, crate::plan::doing_block(&doing));
}
}
// 連接器 that came on or went while the turn runs (one the bot just added with
// manage_connectors): their tools from this step on. (Not while a plan is written.)
if connectors_live && job.drafting.is_none() {
let sig = crate::mcp::tools_sig();
if sig != mcp_sig {
mcp_sig = sig;
job.req.tools.retain(|t| !crate::mcp::is_connector_spec(t["name"].as_str().unwrap_or("")));
job.req.tools.extend(crate::mcp::specs());
}
}
// Quick steps don't stream their words: an answer may be set aside for the check. // Quick steps don't stream their words: an answer may be set aside for the check.
let quiet = |ev: StreamEvent| { let quiet = |ev: StreamEvent| {
if !matches!(ev, StreamEvent::Text(_) | StreamEvent::Thinking(_)) { if !matches!(ev, StreamEvent::Text(_) | StreamEvent::Thinking(_)) {
@ -1868,6 +1920,15 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
} }
// What runs: the call as asked, on the chosen computer (see keep_to_chosen). // What runs: the call as asked, on the chosen computer (see keep_to_chosen).
let call = ToolCall { args: runs_with.get(&asked.id).cloned().unwrap_or_else(|| asked.args.clone()), ..asked.clone() }; let call = ToolCall { args: runs_with.get(&asked.id).cloned().unwrap_or_else(|| asked.args.clone()), ..asked.clone() };
// 計畫模式: until the person approves the plan, only looking runs (even a step
// asked for in the same breath as the plan: the model didn't know the answer).
if job.drafting.is_some() && !runs_while_planning(&call.name) {
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Denied));
let result = Message::tool_result(&call.id, &call.name, crate::plan::NOT_YET);
send(StreamEvent::ToolResult(result.clone()));
history.push(result);
continue;
}
// 鬼打牆: the same screen or browser step again and again (a click on the same // 鬼打牆: the same screen or browser step again and again (a click on the same
// empty spot ten times). The third time it runs with a warning; after that it isn't // empty spot ten times). The third time it runs with a warning; after that it isn't
// run at all, and the bot is told to change course. (Counted as the model asked, // run at all, and the bot is told to change course. (Counted as the model asked,
@ -2352,6 +2413,72 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
finish(&mut history, &output, status, None); finish(&mut history, &output, status, None);
continue; continue;
} }
// 計畫: the plan on a card (a 問題卡 with 開始照計畫做 and 先不要; their own words
// are a change); the turn waits. A message typed meanwhile is a change too.
if call.name == crate::plan::SUBMIT_TOOL {
let (output, status) = match (crate::plan::parse_draft(&call.args), job.drafting.as_ref()) {
(Err(e), _) => (e, ToolStatus::Failed),
(Ok(_), None) => ("現在不在計畫模式(或計畫已經核准):不用再交計畫,直接照計畫做。".to_string(), ToolStatus::Failed),
(Ok(draft), Some(d)) => {
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: crate::plan::approval_card(), grant: String::new(), reply: atx, kind: ApprovalKind::Question }));
let answer = loop {
if cancel.load(Ordering::Relaxed) {
return;
}
match arx.recv_timeout(Duration::from_millis(200)) {
Ok(a) => break Some(a),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
if !job.steer.lock().unwrap().is_empty() {
break None;
}
}
Err(_) => break Some(ApprovalAnswer::Reject),
}
};
let decision = match answer {
Some(ApprovalAnswer::Answered(text)) => crate::plan::decide(&text),
Some(_) => crate::plan::Decision::NotNow,
None => crate::plan::Decision::Change(String::new()),
};
match decision {
crate::plan::Decision::Approve => {
let steps = draft.steps();
send(StreamEvent::Plan(crate::plan::Event::Approved(steps.clone())));
let out = crate::plan::approved_result(&steps);
plan_go = Some(steps);
(out, ToolStatus::Done)
}
crate::plan::Decision::NotNow => {
send(StreamEvent::Plan(crate::plan::Event::NotNow));
(crate::plan::NOT_NOW_RESULT.to_string(), ToolStatus::Denied)
}
crate::plan::Decision::Change(words) => {
plan_changes += 1;
send(StreamEvent::Plan(crate::plan::Event::Changed));
let out = if words.is_empty() { crate::plan::WROTE_INSTEAD_RESULT.to_string() } else { crate::plan::change_result(&words, d.plan.revisions + plan_changes) };
(out, ToolStatus::Done)
}
}
}
};
finish(&mut history, &output, status, None);
continue;
}
// 計畫: where it is in the approved plan (the line above the input follows it).
if call.name == crate::plan::UPDATE_TOOL {
let (output, status) = match crate::plan::parse_progress(&call.args) {
Ok(steps) => {
let out = crate::plan::progress_result(&steps);
send(StreamEvent::Plan(crate::plan::Event::Progress(steps)));
(out, ToolStatus::Done)
}
Err(e) => (e, ToolStatus::Failed),
};
finish(&mut history, &output, status, None);
continue;
}
// 問題卡: the questions on a card; the turn waits for the answers. A message typed // 問題卡: the questions on a card; the turn waits for the answers. A message typed
// meanwhile leaves the card unanswered and is what the bot goes by. // meanwhile leaves the card unanswered and is what the bot goes by.
if call.name == crate::ask::TOOL { if call.name == crate::ask::TOOL {
@ -3356,6 +3483,7 @@ mod tests {
target_sends: 0, target_sends: 0,
timezone: "Asia/Taipei".into(), timezone: "Asia/Taipei".into(),
untrusted: false, untrusted: false,
drafting: None,
} }
} }
@ -4871,6 +4999,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
target_sends: 0, target_sends: 0,
timezone: "Asia/Taipei".into(), timezone: "Asia/Taipei".into(),
untrusted: false, untrusted: false,
drafting: None,
}; };
let (tx, rx) = channel(); let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false)); let cancel = Arc::new(AtomicBool::new(false));
@ -4958,6 +5087,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
target_sends: 0, target_sends: 0,
timezone: "Asia/Taipei".into(), timezone: "Asia/Taipei".into(),
untrusted: false, untrusted: false,
drafting: None,
}; };
let (tx, rx) = channel(); let (tx, rx) = channel();
spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default());
@ -5048,6 +5178,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
target_sends: 0, target_sends: 0,
timezone: "Asia/Taipei".into(), timezone: "Asia/Taipei".into(),
untrusted: false, untrusted: false,
drafting: None,
}; };
let (tx, rx) = channel(); let (tx, rx) = channel();
spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default());
@ -5274,6 +5405,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
target_sends: 0, target_sends: 0,
timezone: "Asia/Taipei".into(), timezone: "Asia/Taipei".into(),
untrusted: false, untrusted: false,
drafting: None,
}; };
let (tx, rx) = channel(); let (tx, rx) = channel();
spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default());
@ -5471,6 +5603,132 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
} }
} }
/// 計畫模式: a turn writing a plan, with the model's replies scripted. The plan card gets
/// `card`; any other request is allowed. Returns the plan events, the step results, what each
/// request to the model carried, and the folder it worked in.
#[allow(clippy::type_complexity)]
fn plan_turn(replies: Vec<(u16, String)>, card: Vec<ApprovalAnswer>) -> (Vec<crate::plan::Event>, Vec<(String, String)>, Vec<String>, std::path::PathBuf) {
let (port, seen) = fake_http(replies);
let w = std::env::temp_dir().join(format!("anybot-plan-{}-{}", std::process::id(), crate::httpd::random_hex(4)));
std::fs::create_dir_all(&w).unwrap();
let all = tools::specs_for(&[crate::model::THIS_COMPUTER_NAME.to_string()], crate::model::THIS_COMPUTER_NAME);
let mut offered: Vec<serde_json::Value> = all.iter().filter(|t| offered_while_planning(t["name"].as_str().unwrap_or(""))).cloned().collect();
offered.push(crate::plan::submit_spec());
let plan = crate::plan::Plan::new("在工作資料夾建立 made.txt", 0);
let mut every = all.clone();
every.push(crate::plan::update_spec());
let job = Job {
req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: format!("你是 Bot。{}", crate::plan::block(&plan)), history: vec![Message::user("/plan 在工作資料夾建立 made.txt")], tools: offered, session: String::new(), effort: String::new() },
computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }],
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
local_execution: true,
direct: Arc::new(AtomicBool::new(true)),
drafting: Some(Drafting { plan, tools: every, system: "你是 Bot。".into() }),
..test_job()
};
let (tx, rx) = channel();
spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default());
let (mut events, mut results, mut card) = (vec![], vec![], card.into_iter());
loop {
match rx.recv_timeout(Duration::from_secs(15)).expect("loop stalled") {
(_, StreamEvent::NeedApproval(a)) => {
let answer = if a.tool == crate::plan::SUBMIT_TOOL { card.next().expect("a plan card too many") } else { ApprovalAnswer::Once };
let _ = a.reply.send(answer);
}
(_, StreamEvent::Plan(e)) => events.push(e),
(_, StreamEvent::ToolResult(m)) => results.push((m.tool_name.clone(), m.text.clone())),
(_, StreamEvent::Done) => break,
(_, StreamEvent::Error(e)) => panic!("{e}"),
_ => {}
}
}
let bodies = seen.lock().unwrap().iter().map(|r| r.split_once("\r\n\r\n").map(|x| x.1.to_string()).unwrap_or_default()).collect();
(events, results, bodies, w)
}
fn plan_args() -> serde_json::Value {
serde_json::json!({"summary": "在工作資料夾建立 made.txt", "steps": [{"title": "建立 made.txt"}, {"title": "確認內容"}], "check": "cat made.txt 印出 hi"})
}
/// 計畫模式: nothing that changes anything runs before the plan is approved on its card;
/// approved, the same turn goes on with every tool and the model is told to follow the plan.
#[test]
fn plan_mode_only_looks_until_the_card_says_go() {
let make = serde_json::json!({"command": "echo hi > made.txt", "computer": crate::model::THIS_COMPUTER_NAME});
let (events, results, bodies, w) = plan_turn(
vec![
sse_call("c1", "shell", make.clone()),
sse_call("p1", crate::plan::SUBMIT_TOOL, plan_args()),
sse_call("c2", "shell", make),
sse_call("u1", crate::plan::UPDATE_TOOL, serde_json::json!({"steps": [{"title": "建立 made.txt", "status": "done"}, {"title": "確認內容", "status": "in_progress"}]})),
sse_text("做好了"),
],
vec![ApprovalAnswer::Answered(serde_json::json!([crate::plan::APPROVE]).to_string())],
);
assert_eq!(results[0], ("shell".to_string(), crate::plan::NOT_YET.to_string()), "{results:?}");
assert!(results[1].1.starts_with("使用者按了「開始照計畫做」"), "{results:?}");
assert!(w.join("made.txt").exists(), "approved: the command ran ({results:?})");
assert!(results[3].1.contains("1/2"), "{results:?}");
let s = |t: &str, st| crate::plan::Step { title: t.into(), status: st };
use crate::plan::{Event, Status};
assert_eq!(events, vec![Event::Approved(vec![s("建立 made.txt", Status::InProgress), s("確認內容", Status::Pending)]), Event::Progress(vec![s("建立 made.txt", Status::Done), s("確認內容", Status::InProgress)])]);
// Before: only looking (no shell, no update_plan), told to plan. After: every tool, told to follow.
let names = |b: &str| serde_json::from_str::<serde_json::Value>(b).unwrap()["tools"].as_array().unwrap().iter().filter_map(|t| t["function"]["name"].as_str().map(String::from)).collect::<Vec<_>>();
assert!(names(&bodies[0]).contains(&"read_file".to_string()) && names(&bodies[0]).contains(&crate::plan::SUBMIT_TOOL.to_string()));
assert!(!names(&bodies[0]).contains(&"shell".to_string()) && !names(&bodies[0]).contains(&crate::plan::UPDATE_TOOL.to_string()));
assert!(bodies[1].contains("〔計畫模式〕"));
assert!(names(&bodies[2]).contains(&"shell".to_string()) && names(&bodies[2]).contains(&crate::plan::UPDATE_TOOL.to_string()) && !names(&bodies[2]).contains(&crate::plan::SUBMIT_TOOL.to_string()));
assert!(bodies[2].contains("〔照計畫做〕") && !bodies[2].contains("〔計畫模式〕"));
let _ = std::fs::remove_dir_all(&w);
}
/// 先不要: the plan is dropped and still nothing runs; a change on the card comes back in the
/// person's words, and the plan handed in again is what gets approved.
#[test]
fn plan_mode_not_now_does_nothing_and_a_change_is_handed_in_again() {
let make = serde_json::json!({"command": "echo hi > made.txt", "computer": crate::model::THIS_COMPUTER_NAME});
let (events, results, _, w) = plan_turn(
vec![sse_call("p1", crate::plan::SUBMIT_TOOL, plan_args()), sse_call("c1", "shell", make), sse_text("好,先不做")],
vec![ApprovalAnswer::Answered(serde_json::json!([crate::plan::NOT_NOW]).to_string())],
);
assert_eq!(events, vec![crate::plan::Event::NotNow]);
assert_eq!(results[0].1, crate::plan::NOT_NOW_RESULT);
assert_eq!(results[1].1, crate::plan::NOT_YET);
assert!(!w.join("made.txt").exists());
let _ = std::fs::remove_dir_all(&w);
let (events, results, _, w) = plan_turn(
vec![sse_call("p1", crate::plan::SUBMIT_TOOL, plan_args()), sse_call("p2", crate::plan::SUBMIT_TOOL, plan_args()), sse_text("好")],
vec![ApprovalAnswer::Answered(serde_json::json!(["檔名改成 hi.txt"]).to_string()), ApprovalAnswer::Answered(serde_json::json!([crate::plan::APPROVE]).to_string())],
);
assert!(matches!(events.as_slice(), [crate::plan::Event::Changed, crate::plan::Event::Approved(_)]), "{events:?}");
assert!(results[0].1.contains("檔名改成 hi.txt") && results[0].1.contains(crate::plan::SUBMIT_TOOL));
assert_eq!(crate::plan::outcome(Some(&results[0].1)), crate::plan::Outcome::Changed);
assert_eq!(crate::plan::outcome(Some(&results[1].1)), crate::plan::Outcome::Approved);
// 略過 on the card is 先不要.
let (events, _, _, w2) = plan_turn(vec![sse_call("p1", crate::plan::SUBMIT_TOOL, plan_args()), sse_text("好")], vec![ApprovalAnswer::Reject]);
assert_eq!(events, vec![crate::plan::Event::NotNow]);
let _ = std::fs::remove_dir_all(&w);
let _ = std::fs::remove_dir_all(&w2);
}
#[test]
fn plan_mode_offers_looking_tools_and_lets_only_looking_actions_run() {
for n in ["read_file", "list_dir", "search", "web_fetch", "browser", "computer", "ask_person", "anybot_guide"] {
assert!(offered_while_planning(n), "{n}");
}
for n in ["shell", "write_file", "edit_file", "send_file", "update_settings", "publish_site"] {
assert!(!offered_while_planning(n), "{n}");
}
for n in ["browser_open", "browser_read", "browser_scroll", "computer_use_screenshot", crate::plan::SUBMIT_TOOL] {
assert!(runs_while_planning(n), "{n}");
}
for n in ["browser_click", "browser_type", "browser_eval", "computer_use_click", "computer_use_typing", "shell", crate::plan::UPDATE_TOOL] {
assert!(!runs_while_planning(n), "{n}");
}
}
/// The model says the chat is too long: older messages are folded into a summary and the same /// The model says the chat is too long: older messages are folded into a summary and the same
/// step is asked again (with the summary), instead of the turn failing. /// step is asked again (with the summary), instead of the turn failing.
#[test] #[test]

94
src/always.rs Normal file
View File

@ -0,0 +1,94 @@
//! 一律放行 (/always-approve, also /yolo): one switch for "don't ask me". Typed by the person, it
//! turns on 直接操作 (this computer, every bot's tools) and from then on answers every request
//! that would wait for 允許 by itself — the ones 直接操作 still asked about too (the 「一律詢問」
//! rules, a click on 付款/傳送/刪除, sending mail or messages, calls, texts, posts on X, a card
//! from the vault). Like Claude Code's bypassPermissions or Codex's --yolo.
//!
//! What it never changes: what the safety rules refuse outright (sudo, rm -rf /, the private key
//! files, AnyBot's own data, cloud metadata addresses) — those are refusals, not questions; a
//! question card or 需要處理 (they need the person's words or hands, not a yes); and a turn
//! started by someone else's message (a channel, a teammate): theirs still waits for the person.
//! Only the person turns it on: the command is read from what they type (the window, a screen of
//! the brain, the phone as the owner), never from a bot, a routine or a channel.
use crate::providers::{ApprovalAnswer, ApprovalKind};
/// What 「/always-approve …」 asks for.
#[derive(Debug, PartialEq)]
pub enum Command {
On,
Off,
Status,
}
/// 「/always-approve」 (or 「/yolo」), with 「off」 or 「status」; None for anything else.
pub fn command(text: &str) -> Option<Command> {
let t = text.trim();
let rest = t.strip_prefix("/always-approve").or_else(|| t.strip_prefix("/yolo"))?;
if rest.chars().next().is_some_and(|c| !c.is_whitespace()) {
return None;
}
Some(match rest.trim().to_lowercase().as_str() {
"" | "on" | "開" | "打開" | "開啟" => Command::On,
"off" | "stop" | "關" | "關閉" | "關掉" | "取消" | "停止" => Command::Off,
_ => Command::Status,
})
}
/// The answer it gives in the person's place (None: it still waits for them).
pub fn answer_for(kind: ApprovalKind) -> Option<ApprovalAnswer> {
match kind {
ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer => Some(ApprovalAnswer::Once),
ApprovalKind::Handoff | ApprovalKind::Question => None,
}
}
pub const ON_NOTE: &str = "已一律放行:所有 Bot 做事都不再一個個問你(例行任務也一樣),連「一律詢問」規則、付款/傳送/刪除的點擊、寄信、傳訊息、打電話、發文都直接做。\n仍然會擋:安全規則一律拒絕的(sudo、rm -rf /、金鑰和密碼檔、AnyBot 自己的資料);別人傳來的訊息(訊息管道、團隊成員)照樣等你按;問題卡和「需要處理」照樣等你。\n關掉:/always-approve off,或 設定 › 權限。";
pub const LOCKED_NOTE: &str = "沒辦法一律放行:「直接操作」或「在這台電腦上執行」被你的管理員鎖住了。";
/// What 「/always-approve off」 says (whether 直接操作 stayed on: it was on before).
pub fn off_note(direct_stays: bool) -> String {
if direct_stays {
"已關閉一律放行:要核准的事又會問你。「直接操作」還開著(在這之前就開了;設定 › 權限 可以關)。".into()
} else {
"已關閉一律放行:要核准的事又會問你,「直接操作」也關了。".into()
}
}
pub fn status_note(on: bool) -> String {
if on {
"現在是一律放行:Bot 做事不會問你(安全規則擋的、別人傳來的訊息除外)。關掉用 /always-approve off。".into()
} else {
"現在沒有一律放行:要核准的事會問你。打開用 /always-approve。".into()
}
}
/// The line above the input while it is on.
pub const BAR: &str = "一律放行 · Bot 做事不再問你(安全規則擋的照樣擋)";
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_command_and_its_words() {
assert_eq!(command("/always-approve"), Some(Command::On));
assert_eq!(command(" /yolo "), Some(Command::On));
assert_eq!(command("/always-approve off"), Some(Command::Off));
assert_eq!(command("/yolo 關閉"), Some(Command::Off));
assert_eq!(command("/always-approve status"), Some(Command::Status));
assert_eq!(command("/always-approver"), None);
assert_eq!(command("/yolox"), None);
assert_eq!(command("請 /yolo"), None);
}
#[test]
fn it_answers_requests_but_not_questions_or_handoffs() {
assert_eq!(answer_for(ApprovalKind::Action), Some(ApprovalAnswer::Once));
assert_eq!(answer_for(ApprovalKind::EnableTools), Some(ApprovalAnswer::Once));
assert_eq!(answer_for(ApprovalKind::EnableThisComputer), Some(ApprovalAnswer::Once));
assert_eq!(answer_for(ApprovalKind::Question), None);
assert_eq!(answer_for(ApprovalKind::Handoff), None);
}
}

View File

@ -43,6 +43,7 @@ mod voice_ui;
mod drops_ui; mod drops_ui;
mod memory_ui; mod memory_ui;
mod goal_ui; mod goal_ui;
mod plan_ui;
mod mood_ui; mod mood_ui;
mod profile_ui; mod profile_ui;
mod asks; mod asks;
@ -207,6 +208,9 @@ pub struct App {
popup_hidden: std::collections::HashSet<u64>, popup_hidden: std::collections::HashSet<u64>,
/// "全部允許,之後直接操作" was clicked in a request. /// "全部允許,之後直接操作" was clicked in a request.
want_direct: std::cell::Cell<bool>, want_direct: std::cell::Cell<bool>,
/// Bots whose running turn came from someone else's message (a channel, a teammate):
/// 一律放行 doesn't answer for them.
strangers: std::collections::HashSet<u64>,
/// Admin locks (policy.rs), read at start and when Settings opens. /// Admin locks (policy.rs), read at start and when Settings opens.
managed: policy::Managed, managed: policy::Managed,
settings_was_open: bool, settings_was_open: bool,
@ -483,6 +487,7 @@ impl App {
md_head_rects: Vec::new(), md_head_rects: Vec::new(),
popup_hidden: Default::default(), popup_hidden: Default::default(),
want_direct: Default::default(), want_direct: Default::default(),
strangers: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() }, managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false, settings_was_open: false,
exe_built: crate::version::exe_modified(), exe_built: crate::version::exe_modified(),
@ -779,6 +784,40 @@ impl App {
app.drafts.insert(1, d); app.drafts.insert(1, d);
} }
} }
// 計畫: a plan handed in and waiting on its card (ANYBOT_SHOT_PLAN=doing: approved,
// its steps ticking, the line above the input).
Ok("plan") => {
app.state.selected = 1;
app.streams.clear();
app.approvals.clear();
let task = "把部落格從舊主機搬到新的 VPS,網址不變";
let now = crate::model::now_ms();
let args = serde_json::json!({"summary": "把 blog.example.com 的檔案和資料庫搬到新 VPS,切換 DNS 後網址不變,舊主機留一週當備援。",
"steps": [{"title": "在舊主機備份網站檔案和 MySQL 資料庫", "detail": "tar 整個 /var/www/blog,mysqldump 匯出 blog 資料庫"},
{"title": "在新 VPS 裝好 Nginx、PHP 8.3、MySQL"}, {"title": "把備份搬過去並還原"},
{"title": "用 hosts 檔先在新主機上試開網站"}, {"title": "把 DNS 的 A 紀錄改到新 VPS"}, {"title": "確認網站、後台登入和留言都正常"}],
"check": "從手機網路打開 blog.example.com,最新一篇文章、後台登入和留言都正常", "notes": "改 DNS 後最多要 1 小時才全部生效;舊主機先不要關。"}).to_string();
let doing = std::env::var("ANYBOT_SHOT_PLAN").as_deref() == Ok("doing");
if let Some(b) = app.state.bot_mut(1) {
b.messages.clear();
b.messages.push(Message { at: now - 9 * 60_000, ..Message::user(&format!("/plan {task}")) });
b.messages.push(Message { at: now - 6 * 60_000, tool_calls: vec![crate::model::ToolCall { id: "plan1".into(), name: crate::plan::SUBMIT_TOOL.into(), args, status: if doing { ToolStatus::Done } else { ToolStatus::Waiting } }], ..Message::assistant("我看過舊主機的設定和 DNS 了,計畫如下。", "Anthropic · claude") });
let mut p = crate::plan::Plan::new(task, now - 9 * 60_000);
if doing {
use crate::plan::Status::*;
b.messages.push(Message::tool_result("plan1", crate::plan::SUBMIT_TOOL, &crate::plan::approved_result(&[])));
p.stage = crate::plan::Stage::Doing;
let titles = ["在舊主機備份網站檔案和 MySQL 資料庫", "在新 VPS 裝好 Nginx、PHP 8.3、MySQL", "把備份搬過去並還原", "用 hosts 檔先在新主機上試開網站", "把 DNS 的 A 紀錄改到新 VPS", "確認網站、後台登入和留言都正常"];
p.steps = titles.iter().zip([Done, Done, InProgress, Pending, Pending, Pending]).map(|(t, status)| crate::plan::Step { title: t.to_string(), status }).collect();
b.messages.push(Message { at: now - 60_000, ..Message::assistant("備份好了(網站 1.2 GB、資料庫 85 MB),新 VPS 也裝好了,正在把備份傳過去。", "Anthropic · claude") });
}
b.plan = Some(p);
}
if !doing {
let (reply, _) = channel();
app.approvals.insert(1, Approval { call_id: "plan1".into(), tool: crate::plan::SUBMIT_TOOL.into(), reason: crate::plan::approval_card(), grant: String::new(), reply, kind: ApprovalKind::Question });
}
}
// A chat long enough to scroll far up (回到底部; with ANYBOT_SHOT_SCROLL). // A chat long enough to scroll far up (回到底部; with ANYBOT_SHOT_SCROLL).
Ok("longchat") => { Ok("longchat") => {
app.state.selected = 1; app.state.selected = 1;
@ -1373,7 +1412,7 @@ impl App {
} }
// 先顯示: while it works (or the words travel to the brain) they aren't in the chat // 先顯示: while it works (or the words travel to the brain) they aren't in the chat
// yet — the person sees them at once all the same. (A command here draws its own line.) // yet — the person sees them at once all the same. (A command here draws its own line.)
let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some()); let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some() || crate::always::command(&text).is_some());
if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command { if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command {
self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now())); self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now()));
} }
@ -1413,6 +1452,16 @@ impl App {
self.goal_command(ctx, bot_id, cmd, &text, attachments, picks); self.goal_command(ctx, bot_id, cmd, &text, attachments, picks);
return; return;
} }
// 計畫: 「/plan …」 is AnyBot's too.
if let Some(cmd) = crate::plan::command(&text) {
self.plan_command(ctx, bot_id, cmd, &text, attachments, picks);
return;
}
// 一律放行: 「/always-approve」 changes the person's own permissions.
if let Some(cmd) = crate::always::command(&text) {
self.always_command(ctx, bot_id, cmd);
return;
}
self.goal_heard(bot_id); self.goal_heard(bot_id);
// While it works, a new message steers the running turn (the original's `turnSteer`: // While it works, a new message steers the running turn (the original's `turnSteer`:
// it doesn't count as a new turn) and reaches the model at its next step. // it doesn't count as a new turn) and reaches the model at its next step.
@ -1561,6 +1610,9 @@ impl App {
let trigger_msg = conv.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted); let trigger_msg = conv.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted);
let untrusted = trigger_msg.is_some_and(|m| m.untrusted_sender); let untrusted = trigger_msg.is_some_and(|m| m.untrusted_sender);
let unattended_wake = trigger_msg.is_some_and(|m| m.wake); let unattended_wake = trigger_msg.is_some_and(|m| m.wake);
// 計畫 (/plan): the person's own turns in a chat with a plan (not a routine's run, not
// someone else's message, not a group chat).
let plan_now = conv.plan.clone().filter(|_| speaker.is_none() && !untrusted && !trigger_msg.is_some_and(|m| m.routine != 0));
// 記憶: the person's newest message carries its memories, chosen once (when nobody picked // 記憶: the person's newest message carries its memories, chosen once (when nobody picked
// any under the composer) and kept on the message — never attached for untrusted senders. // any under the composer) and kept on the message — never attached for untrusted senders.
// (A 支線 uses its main bot's memories: what it keeps, the main bot keeps.) // (A 支線 uses its main bot's memories: what it keeps, the main bot keeps.)
@ -1709,6 +1761,21 @@ impl App {
// 能力: only the tool families this bot has (profile.rs) — what it lacks isn't offered // 能力: only the tool families this bot has (profile.rs) — what it lacks isn't offered
// (nor described: ~200 tokens a tool, on every step). // (nor described: ~200 tokens a tool, on every step).
crate::profile::trim_tools(&b, &mut tool_specs); crate::profile::trim_tools(&b, &mut tool_specs);
// 計畫: while the plan is written only the tools that look are offered, with submit_plan
// (the rest wait for the approval: plan_tools); once approved, update_plan joins them.
let mut plan_tools = None;
match plan_now.as_ref().map(|p| p.stage) {
Some(crate::plan::Stage::Drafting) => {
let mut all = tool_specs.clone();
all.push(crate::plan::update_spec());
plan_tools = Some(all);
tool_specs.retain(|t| agent::offered_while_planning(t["name"].as_str().unwrap_or("")));
tool_specs.push(crate::plan::submit_spec());
}
Some(crate::plan::Stage::Doing) => tool_specs.push(crate::plan::update_spec()),
None => {}
}
let mut plan_system = None;
// 看圖小幫手: the person's models that may see pictures, for a bot whose model can't. // 看圖小幫手: the person's models that may see pictures, for a bot whose model can't.
providers::set_eyes(self.eyes()); providers::set_eyes(self.eyes());
providers::set_cloud_eyes_for(ALL_PROVIDERS.into_iter().filter(|k| self.state.provider(*k).cloud_eyes).map(|k| providers::resolve_base(k, &self.state.provider(k).base_url)).collect()); providers::set_cloud_eyes_for(ALL_PROVIDERS.into_iter().filter(|k| self.state.provider(*k).cloud_eyes).map(|k| providers::resolve_base(k, &self.state.provider(k).base_url)).collect());
@ -1731,6 +1798,11 @@ impl App {
sys.push_str("在 Bot 的電腦上每個成員有自己的螢幕和瀏覽器(登入一樣),看不到彼此開著的畫面和網頁:交棒給別的成員時,把網址、檔案路徑或頁面名稱寫進回覆,讓它自己打開;不要只說「我開好了」。"); sys.push_str("在 Bot 的電腦上每個成員有自己的螢幕和瀏覽器(登入一樣),看不到彼此開著的畫面和網頁:交棒給別的成員時,把網址、檔案路徑或頁面名稱寫進回覆,讓它自己打開;不要只說「我開好了」。");
} }
} }
// 計畫: last, where it reads as this turn's way of working.
if let Some(p) = &plan_now {
plan_system = Some(sys.clone());
sys.push_str(&crate::plan::block(p));
}
sys sys
}, },
history: { history: {
@ -1768,7 +1840,13 @@ impl App {
let turn = self.turn_seq; let turn = self.turn_seq;
self.streams.insert(bot_id, Live { cancel: cancel.clone(), started: Instant::now(), last: Instant::now(), produced: false, status: None, paused: false, paused_at: None, unattended: unattended_wake, steer: steer.clone(), turn_id: turn_id.clone(), direct: direct.clone(), turn }); self.streams.insert(bot_id, Live { cancel: cancel.clone(), started: Instant::now(), last: Instant::now(), produced: false, status: None, paused: false, paused_at: None, unattended: unattended_wake, steer: steer.clone(), turn_id: turn_id.clone(), direct: direct.clone(), turn });
self.stick_bottom = true; self.stick_bottom = true;
let review = (!untrusted && self.state.auto_review).then(|| agent::Review { allow: self.state.review_allow_rules.clone(), ask: self.state.review_ask_rules.clone() }); // 一律放行: everything it would ask is answered yes anyway — no review step to wait for.
let review = (!untrusted && self.state.auto_review && !self.always_on()).then(|| agent::Review { allow: self.state.review_allow_rules.clone(), ask: self.state.review_ask_rules.clone() });
if untrusted {
self.strangers.insert(bot_id);
} else {
self.strangers.remove(&bot_id);
}
// 發布前檢查: another provider's model reads the words before they go out (like the // 發布前檢查: another provider's model reads the words before they go out (like the
// /goal judge) — the bot's own when there is no other, or when its model is a local one // /goal judge) — the bot's own when there is no other, or when its model is a local one
// (what it works on doesn't leave for a cloud service behind the person's back). // (what it works on doesn't leave for a cloud service behind the person's back).
@ -1833,6 +1911,10 @@ impl App {
target_sends, target_sends,
timezone: self.state.timezone.clone(), timezone: self.state.timezone.clone(),
untrusted, untrusted,
drafting: match (plan_now, plan_tools, plan_system) {
(Some(plan), Some(tools), Some(system)) => Some(agent::Drafting { plan, tools, system }),
_ => None,
},
}; };
// The turn speaks into a channel of its own; what it says goes on to the window with // The turn speaks into a channel of its own; what it says goes on to the window with
// the turn's number on it. // the turn's number on it.
@ -2114,6 +2196,8 @@ impl App {
} }
let away = self.away() && self.state.notify; let away = self.away() && self.state.notify;
let chime = self.state.alert_sound; let chime = self.state.alert_sound;
// 計畫: every step done — the plan is over.
self.plan_settled(bot_id);
if let Some(l) = self.streams.remove(&bot_id) { if let Some(l) = self.streams.remove(&bot_id) {
// 目標: whether it holds is checked next (goal_tick), and that check tells the person. // 目標: whether it holds is checked next (goal_tick), and that check tells the person.
let on_the_way = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active()); let on_the_way = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active());
@ -2351,6 +2435,11 @@ impl App {
self.ask_bot(ctx, bot_id, call); self.ask_bot(ctx, bot_id, call);
return; return;
} }
// 管理連接器: answered once the connector has connected (or said why not).
if call.name == crate::mcp::MANAGE_TOOL {
self.manage_connectors(ctx, call);
return;
}
let out = if call.name == "list_computers" { let out = if call.name == "list_computers" {
let text = self.state.bot(bot_id).cloned().map(|b| self.computers_text(&b)).unwrap_or_default(); let text = self.state.bot(bot_id).cloned().map(|b| self.computers_text(&b)).unwrap_or_default();
appctl::Outcome { text, ok: true, wake: vec![], theme_changed: false, page: None } appctl::Outcome { text, ok: true, wake: vec![], theme_changed: false, page: None }
@ -2458,6 +2547,84 @@ impl App {
self.state.direct_mode && self.managed.direct.allows() && self.managed.local.allows() self.state.direct_mode && self.managed.direct.allows() && self.managed.local.allows()
} }
/// 一律放行 as it applies: on, and not locked by an admin.
fn always_on(&self) -> bool {
self.state.always_approve && self.managed.direct.allows() && self.managed.local.allows()
}
/// The yes 一律放行 gives for this bot's request now (None: the person is asked).
fn always_answer(&self, bot_id: u64, kind: ApprovalKind) -> Option<ApprovalAnswer> {
if !self.always_on() || self.strangers.contains(&bot_id) {
return None;
}
crate::always::answer_for(kind)
}
/// 「/always-approve」 (or 「/yolo」): on, off, or how it stands — a line in this chat.
fn always_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: crate::always::Command) {
use crate::always::Command;
let note = match cmd {
Command::Status => crate::always::status_note(self.always_on()),
Command::On if !(self.managed.direct.allows() && self.managed.local.allows()) => crate::always::LOCKED_NOTE.into(),
Command::On => {
if !self.state.always_approve {
self.state.direct_before_always = self.direct_on();
}
self.enable_direct_mode();
self.state.always_approve = true;
// What the person's own turns are waiting on now goes ahead.
let waiting: Vec<u64> = self.approvals.iter().filter(|(id, a)| !self.strangers.contains(id) && crate::always::answer_for(a.kind).is_some()).map(|(id, _)| *id).collect();
for id in waiting {
self.answer(ctx, id, ApprovalAnswer::Once);
}
self.notice = None;
crate::always::ON_NOTE.into()
}
Command::Off => {
let stays = self.state.direct_before_always;
self.state.always_approve = false;
if !stays {
self.disable_direct_mode();
}
crate::always::off_note(stays)
}
};
self.goal_note(bot_id, &note);
self.dirty = true;
self.save_now = true;
}
/// The line above the input while 一律放行 is on (every chat: it is everyone's), with 關閉.
fn always_bar(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot_id: u64) {
if !self.always_on() {
return;
}
let p = self.pal;
let mut off = false;
ui.horizontal(|ui| {
ui.add_space(14.0);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.add_space(10.0);
off = small_button(ui, "關閉", p).clicked();
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let (r, _) = ui.allocate_exact_size(vec2(13.0, 14.0), egui::Sense::hover());
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Zap, p.danger);
ui.add(egui::Label::new(RichText::new(t(crate::always::BAR)).size(FONT_XS).color(p.text2)).truncate().selectable(false))
.on_hover_text(t("用 /always-approve 打開的。安全規則一律拒絕的(sudo、rm -rf /、金鑰檔…)照樣擋;別人傳來的訊息照樣等你按;問題卡和「需要處理」照樣等你。"));
});
});
});
ui.add_space(2.0);
if off {
if self.mir.on {
self.mirror_send(bot_id, "/always-approve off".into(), vec![], None);
} else {
self.always_command(ctx, bot_id, crate::always::Command::Off);
}
}
}
fn local_on(&self) -> bool { fn local_on(&self) -> bool {
(self.state.local_execution || self.state.direct_mode && self.managed.direct.allows()) && self.managed.local.allows() (self.state.local_execution || self.state.direct_mode && self.managed.direct.allows()) && self.managed.local.allows()
} }
@ -2637,6 +2804,11 @@ impl App {
self.goal_verdict(ctx, id, since, judged); self.goal_verdict(ctx, id, since, judged);
continue; continue;
} }
// 計畫: approved, dropped, sent back, or its steps moved on.
if let StreamEvent::Plan(e) = ev {
self.plan_event(id, e);
continue;
}
// A stopped request may still deliver a few pieces; ignore them — also when the // A stopped request may still deliver a few pieces; ignore them — also when the
// bot has a new turn running by now. // bot has a new turn running by now.
if self.streams.get(&id).map(|l| l.turn) != Some(turn) { if self.streams.get(&id).map(|l| l.turn) != Some(turn) {
@ -2678,6 +2850,13 @@ impl App {
_ => {} _ => {}
} }
} }
// 一律放行: the person's own turn gets its yes at once (questions and hand-offs wait).
if let StreamEvent::NeedApproval(a) = &ev {
if let Some(yes) = self.always_answer(id, a.kind) {
let _ = a.reply.send(yes);
continue;
}
}
if let StreamEvent::NeedApproval(a) = ev { if let StreamEvent::NeedApproval(a) = ev {
if let Some(b) = self.state.bot_mut(id) { if let Some(b) = self.state.bot_mut(id) {
if id != selected { if id != selected {
@ -2727,9 +2906,20 @@ impl App {
continue; continue;
} }
} }
} else if call.name == crate::mcp::MANAGE_TOOL {
// 管理連接器: checked against the list as it is; a change is shown first.
match crate::mcp::parse_change(&call.args, &self.state.mcp_servers) {
Ok(c) => crate::mcp::change_question(&c),
Err(e) => {
let _ = call.reply.send((e, false));
continue;
}
}
} else { } else {
appctl::needs_approval(&call.name, &call.args, &self.state) appctl::needs_approval(&call.name, &call.args, &self.state)
}; };
// 一律放行: what would be asked is done at once.
let ask = ask.filter(|_| self.always_answer(id, ApprovalKind::Action).is_none());
match ask { match ask {
Some(reason) => { Some(reason) => {
let (reply, _) = channel(); let (reply, _) = channel();
@ -3059,6 +3249,7 @@ impl App {
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
goal: None, goal: None,
plan: None,
draft: String::new(), draft: String::new(),
regen_undo: vec![], regen_undo: vec![],
team: false, team: false,
@ -4090,6 +4281,10 @@ impl App {
ui.add_space(4.0); ui.add_space(4.0);
// 目標: how the goal stands, and 清除目標. // 目標: how the goal stands, and 清除目標.
self.goal_bar(ui, ctx, bot); self.goal_bar(ui, ctx, bot);
// 計畫: where the plan is, and 取消計畫.
self.plan_bar(ui, ctx, bot);
// 一律放行: on in every chat while it lasts, with 關閉.
self.always_bar(ui, ctx, bot.id);
// Quote and attachments sit just above the pill. // Quote and attachments sit just above the pill.
if let Some(q) = self.quoting.get(&bot.id).cloned() { if let Some(q) = self.quoting.get(&bot.id).cloned() {
ui.horizontal(|ui| { ui.horizontal(|ui| {
@ -5350,6 +5545,26 @@ impl App {
} }
hint(ui, "仍會擋下:危險指令(sudo、格式化…)、密碼和金鑰檔、AnyBot 自己的資料,以及你在「自動審核」寫的「一律詢問」規則(預設:刪除檔案、付款、用你的帳號發文或傳訊息)。macOS 第一次讓 AnyBot 控制瀏覽器時還是會自己問一次,按「好」就行。", p); hint(ui, "仍會擋下:危險指令(sudo、格式化…)、密碼和金鑰檔、AnyBot 自己的資料,以及你在「自動審核」寫的「一律詢問」規則(預設:刪除檔案、付款、用你的帳號發文或傳訊息)。macOS 第一次讓 AnyBot 控制瀏覽器時還是會自己問一次,按「好」就行。", p);
}); });
// 一律放行: the same switch as 「/always-approve」 in a chat.
section(ui, "一律放行", p);
setting_card(ui, p, |ui| {
let allowed = self.managed.direct.allows() && self.managed.local.allows();
let mut on = self.always_on();
let mut flip = None;
ui.horizontal(|ui| {
ui.label(RichText::new(t("什麼都不問,全部直接做")).size(FONT_BASE).color(p.text));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add_enabled(allowed, computers_ui::toggle(&mut on)).changed() {
flip = Some(on);
}
});
});
hint(ui, "也可以在任何聊天打 /always-approve(關掉打 /always-approve off)。會打開「直接操作」,連「一律詢問」規則、付款、寄信、傳訊息、打電話、發文都不再問。還是會擋:安全規則一律拒絕的、別人傳來的訊息;問題卡和「需要處理」照樣等你。", p);
if let Some(on) = flip {
let id = self.state.selected;
self.always_command(ctx, id, if on { crate::always::Command::On } else { crate::always::Command::Off });
}
});
section(ui, "自動審核", p); section(ui, "自動審核", p);
setting_card(ui, p, |ui| { setting_card(ui, p, |ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
@ -7737,6 +7952,175 @@ mod tests {
assert_eq!(app.state.bot(id).unwrap().name, name); assert_eq!(app.state.bot(id).unwrap().name, name);
} }
/// 一律放行: before it, a command on this computer waits for 允許; after 「/always-approve」 the
/// person's own turn runs it with no card at all; a stranger's message still waits; 「off」
/// puts asking back (and 直接操作 off again, as it was before).
#[test]
fn always_approve_answers_the_persons_requests_but_not_a_strangers() {
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-always.png")));
let id = app.state.bots[0].id;
// This computer, by the name it has here, working in a folder of its own.
let w = std::env::temp_dir().join(format!("anybot-always-{}", std::process::id()));
std::fs::create_dir_all(&w).unwrap();
app.state.bot_mut(id).unwrap().workdir = w.display().to_string();
let bot = app.state.bot(id).unwrap().clone();
let here = app.targets_for(&bot).into_iter().find(|t| matches!(t.place, crate::tools::Place::Local { .. })).map(|t| t.name).expect("this computer is one of the bot's");
// (Chosen and named: a step on another computer would be moved back to the chosen one —
// the bots' Docker computer by default, which a test must never start.)
app.state.bot_mut(id).unwrap().default_computer = here.clone();
let shell = |id: &str| serde_json::json!({"tool_calls": [{"index": 0, "id": id, "function": {"name": "shell", "arguments": serde_json::json!({"command": "printf always-ok", "computer": here}).to_string()}}]});
let done = || serde_json::json!({"content": "好"});
let port = scripted_model(vec![shell("s1"), done(), shell("s2"), done(), shell("s3"), done()]);
app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = format!("http://127.0.0.1:{port}/v1");
{
let b = app.state.bot_mut(id).unwrap();
b.provider = crate::providers::ProviderKind::Custom;
b.model = "m".into();
b.step_model = "off".into();
}
app.state.direct_mode = false;
app.state.always_approve = false;
let say = |app: &mut super::App, text: &str| {
app.drafts.insert(id, text.into());
app.send(&ctx, id);
};
// Before: it asks (refused here).
app.wake(&ctx, id, Message { memories_set: true, ..Message::user(&format!("在{here}上印一下")) });
assert!(pump(&mut app, &ctx, |a| a.approvals.contains_key(&id)), "asked before 一律放行: {:?}", app.state.bot(id).unwrap().messages.iter().rev().take(4).map(|m| (m.role, m.text.chars().take(200).collect::<String>())).collect::<Vec<_>>());
app.answer(&ctx, id, ApprovalAnswer::Reject);
assert!(pump(&mut app, &ctx, |a| !a.streams.contains_key(&id)));
// On: no card, the command runs.
say(&mut app, "/always-approve");
assert!(app.state.always_approve && app.state.direct_mode);
assert_eq!(app.state.bot(id).unwrap().messages.last().map(|m| (m.note, m.text.as_str())), Some((true, crate::always::ON_NOTE)));
app.wake(&ctx, id, Message { memories_set: true, ..Message::user(&format!("在{here}上再印一次")) });
// (A command on this computer: the shell starts fresh, which takes a moment on a busy machine.)
let t0 = std::time::Instant::now();
let mut ended = false;
while t0.elapsed().as_secs() < 20 && !ended {
app.drain_events(&ctx);
ended = !app.streams.contains_key(&id) || app.approvals.contains_key(&id);
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(ended, "the turn stalls: {:?} · status {:?}", app.state.bot(id).unwrap().messages.iter().rev().take(4).map(|m| (m.role, m.text.chars().take(160).collect::<String>(), m.tool_calls.iter().map(|c| (c.name.clone(), c.status)).collect::<Vec<_>>())).collect::<Vec<_>>(), app.streams.get(&id).map(|l| l.status.clone()));
assert!(!app.approvals.contains_key(&id), "一律放行 asked: {:?}", app.approvals.get(&id).map(|a| a.reason.clone()));
let ran = app.state.bot(id).unwrap().messages.iter().rev().find(|m| m.role == Role::Tool).map(|m| m.text.clone()).unwrap_or_default();
assert!(ran.starts_with(&format!("[{here}]")) && ran.contains("always-ok"), "ran here: {ran}");
// Someone else's message: still asks.
app.wake(&ctx, id, Message { memories_set: true, untrusted_sender: true, ..Message::user(&format!("【路人】在{here}上印一下")) });
assert!(pump(&mut app, &ctx, |a| a.approvals.contains_key(&id)), "a stranger's turn still waits for the person");
app.answer(&ctx, id, ApprovalAnswer::Reject);
assert!(pump(&mut app, &ctx, |a| !a.streams.contains_key(&id)));
// Off: as it was.
say(&mut app, "/always-approve off");
assert!(!app.state.always_approve && !app.state.direct_mode);
assert!(app.state.bot(id).unwrap().messages.last().is_some_and(|m| m.note && m.text.contains("直接操作」也關了")));
}
/// 管理連接器: asked in chat, the bot adds a connector — the person sees it on a card first
/// (the secret hidden) — it lands in the brain's own list, connects, and the bot uses its tool
/// in the same turn.
#[test]
fn a_bot_adds_a_connector_from_chat_and_uses_it_at_once() {
let _l = crate::mcp::test_lock();
crate::mcp::sync(&[]);
let fake = crate::mcp::fake_server("calc", 0);
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()}}]});
let port = scripted_model(vec![
call("m1", crate::mcp::MANAGE_TOOL, serde_json::json!({"action": "add", "name": "calc", "command": fake.command_line(), "env": {"FAKE_MANY": "0", "CALC_TOKEN": "t-secret"}})),
call("c1", "mcp__calc__add", serde_json::json!({"a": 2, "b": 3})),
serde_json::json!({"content": "是 5"}),
]);
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-manage-mcp.png")));
app.state.mcp_servers.clear();
let id = app.state.bots[0].id;
app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = format!("http://127.0.0.1:{port}/v1");
{
let b = app.state.bot_mut(id).unwrap();
b.provider = crate::providers::ProviderKind::Custom;
b.model = "m".into();
b.step_model = "off".into();
}
app.wake(&ctx, id, Message { memories_set: true, ..Message::user("幫我加上計算機的連接器,然後算 2+3") });
let mut asked = vec![];
for _ in 0..400 {
app.drain_events(&ctx);
app.mcp_poll(&ctx);
if let Some(a) = app.approvals.get(&id) {
asked.push(a.reason.clone());
app.answer(&ctx, id, ApprovalAnswer::Once);
}
if !app.streams.contains_key(&id) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(!app.streams.contains_key(&id), "the turn finishes");
assert!(asked[0].contains("新增連接器「calc」") && asked[0].contains("CALC_TOKEN=••••(已填)") && !asked[0].contains("t-secret"), "{asked:?}");
assert_eq!(app.state.mcp_servers.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), vec!["calc"], "in the brain's own list");
let results: Vec<String> = app.state.bot(id).unwrap().messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.text.clone()).collect();
assert!(results[0].contains("已新增連接器「calc」") && results[0].contains("已連上,2 個工具"), "{results:?}");
assert!(results[1].contains("sum=5"), "used in the same turn: {results:?}");
crate::mcp::sync(&[]);
}
/// 計畫 (/plan): typed, the bot hands in a plan on a card and waits; 開始照計畫做 and it goes on
/// in the same turn, its steps move on, and a plan whose steps are all done says so and is gone.
/// 「/plan」 says how it stands; 「/plan clear」 cancels; 先不要 drops it.
#[test]
fn a_plan_is_approved_on_its_card_and_followed_to_the_end() {
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()}}]});
let port = scripted_model(vec![
call("p1", crate::plan::SUBMIT_TOOL, serde_json::json!({"summary": "在工作資料夾建一個檔", "steps": [{"title": "建檔"}, {"title": "檢查內容"}]})),
call("u1", crate::plan::UPDATE_TOOL, serde_json::json!({"steps": [{"title": "建檔", "status": "done"}, {"title": "檢查內容", "status": "in_progress"}]})),
call("u2", crate::plan::UPDATE_TOOL, serde_json::json!({"steps": [{"title": "建檔", "status": "done"}, {"title": "檢查內容", "status": "done"}]})),
serde_json::json!({"content": "做好了"}),
call("p2", crate::plan::SUBMIT_TOOL, serde_json::json!({"summary": "再建一個", "steps": ["建檔"]})),
serde_json::json!({"content": "好,先不做"}),
]);
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-plan.png")));
let id = app.state.bots[0].id;
app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = format!("http://127.0.0.1:{port}/v1");
{
let b = app.state.bot_mut(id).unwrap();
b.provider = crate::providers::ProviderKind::Custom;
b.model = "m".into();
b.step_model = "off".into();
b.messages.clear();
}
let say = |app: &mut super::App, text: &str| {
app.drafts.insert(id, text.into());
app.send(&ctx, id);
};
say(&mut app, "/plan 在工作資料夾建一個檔");
assert_eq!(app.state.bot(id).unwrap().plan.as_ref().map(|p| (p.task.as_str(), p.stage)), Some(("在工作資料夾建一個檔", crate::plan::Stage::Drafting)));
assert!(pump(&mut app, &ctx, |a| a.approvals.contains_key(&id)), "the plan waits on its card");
assert_eq!(app.approvals[&id].tool, crate::plan::SUBMIT_TOOL);
assert_eq!(crate::ask::parse(&app.approvals[&id].reason).unwrap()[0].question, crate::plan::QUESTION);
app.answer(&ctx, id, ApprovalAnswer::Answered(serde_json::json!([crate::plan::APPROVE]).to_string()));
assert!(pump(&mut app, &ctx, |a| !a.streams.contains_key(&id)), "the turn finishes");
let b = app.state.bot(id).unwrap();
assert!(b.plan.is_none(), "every step done: the plan is over ({:?})", b.plan);
assert!(b.messages.iter().any(|m| m.note && m.text == "計畫完成:2 步都做完了。"), "{:?}", b.messages.iter().map(|m| &m.text).collect::<Vec<_>>());
assert!(b.messages.iter().any(|m| m.text == "做好了"));
// 「/plan」 with none, then 先不要.
say(&mut app, "/plan");
assert!(app.state.bot(id).unwrap().messages.last().is_some_and(|m| m.note && m.text.starts_with("沒有計畫")));
say(&mut app, "/plan 再建一個");
assert!(pump(&mut app, &ctx, |a| a.approvals.contains_key(&id)));
app.answer(&ctx, id, ApprovalAnswer::Answered(serde_json::json!([crate::plan::NOT_NOW]).to_string()));
assert!(pump(&mut app, &ctx, |a| !a.streams.contains_key(&id)));
assert!(app.state.bot(id).unwrap().plan.is_none(), "先不要 drops it");
// 「/plan clear」 cancels one still being written.
app.state.bot_mut(id).unwrap().plan = Some(crate::plan::Plan::new("x", 1));
say(&mut app, "/plan clear");
let b = app.state.bot(id).unwrap();
assert!(b.plan.is_none() && b.messages.last().is_some_and(|m| m.note && m.text == "已取消計畫:x"));
}
/// 問同事: A asks B and waits; B answers in its own chat with its own model; B's last words /// 問同事: A asks B and waits; B answers in its own chat with its own model; B's last words
/// come back as A's step result and A goes on with them. /// come back as A's step result and A goes on with them.
#[test] #[test]
@ -7948,7 +8332,7 @@ mod tests {
let mut bot = app.state.bots[0].clone(); let mut bot = app.state.bots[0].clone();
bot.skills = Some(vec!["週報".into()]); bot.skills = Some(vec!["週報".into()]);
let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::<Vec<_>>(); let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::<Vec<_>>();
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "btw"]); assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve"]);
assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word"); assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word");
assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]); assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]);
} }

View File

@ -193,6 +193,8 @@ impl App {
b.regen_undo.clear(); b.regen_undo.clear();
b.draft.clear(); b.draft.clear();
b.goal = None; b.goal = None;
// (A 支線 does its one thing now: the main line's plan, being written or followed, isn't its.)
b.plan = None;
b.pinned = false; b.pinned = false;
b.unread = false; b.unread = false;
b.last_turn = None; b.last_turn = None;

View File

@ -7,6 +7,8 @@ use std::collections::VecDeque;
/// How often the connectors are synced again: what failed or died is connected again. /// How often the connectors are synced again: what failed or died is connected again.
const MCP_RETRY: std::time::Duration = std::time::Duration::from_secs(30); const MCP_RETRY: std::time::Duration = std::time::Duration::from_secs(30);
/// How long a bot's 管理連接器 waits for a connector it added to connect before answering.
const CONNECT_WAIT: std::time::Duration = std::time::Duration::from_secs(90);
pub struct ChannelUi { pub struct ChannelUi {
pub tx: Sender<Incoming>, pub tx: Sender<Incoming>,
@ -422,7 +424,7 @@ impl App {
/// Connect the configured MCP servers when they change (in the background), and re-sync /// Connect the configured MCP servers when they change (in the background), and re-sync
/// every half minute: sync keeps what is alive and connects again what failed or died, so a /// every half minute: sync keeps what is alive and connects again what failed or died, so a
/// server that wasn't up yet, crashed, or lost its machine comes back on its own. /// server that wasn't up yet, crashed, or lost its machine comes back on its own.
fn mcp_poll(&mut self, ctx: &egui::Context) { pub(super) fn mcp_poll(&mut self, ctx: &egui::Context) {
if self.ch.mcp_busy.load(Ordering::SeqCst) { if self.ch.mcp_busy.load(Ordering::SeqCst) {
return; return;
} }
@ -442,6 +444,64 @@ impl App {
}); });
} }
/// 管理連接器 (a bot asked; the person already said yes to a change): the brain's own list
/// changes, as 新增連接器 / 設定 / 移除 would, and the answer waits until the connector has
/// connected or said why not (at most CONNECT_WAIT; a first `npx` may download for a while).
pub(super) fn manage_connectors(&mut self, ctx: &egui::Context, call: crate::providers::AppCall) {
let change = match crate::mcp::parse_change(&call.args, &self.state.mcp_servers) {
Ok(c) => c,
Err(e) => {
let _ = call.reply.send((e, false));
return;
}
};
if change == crate::mcp::Change::List {
let text = crate::mcp::list_text(&self.state.mcp_servers, &crate::mcp::status(), &self.ch.mcp_errors.lock().unwrap(), self.ch.mcp_busy.load(Ordering::SeqCst));
let _ = call.reply.send((text, true));
return;
}
let said = crate::mcp::apply_change(&change, &mut self.state.mcp_servers);
let waits = match &change {
crate::mcp::Change::Add(s) => Some(s.name.clone()),
crate::mcp::Change::Update { after, .. } if after.enabled => Some(after.name.clone()),
crate::mcp::Change::Reconnect(n) => Some(n.clone()),
_ => None,
};
match &change {
crate::mcp::Change::Update { after, .. } => self.mcp_reconnect(&after.name),
crate::mcp::Change::Reconnect(n) => self.mcp_reconnect(n),
crate::mcp::Change::Remove(s) => crate::mcp::forget(&s.name),
_ => {}
}
self.ch.mcp_errors.lock().unwrap().retain(|e| Some(&e.0) != waits.as_ref());
self.dirty = true;
self.save_now = true;
ctx.request_repaint();
let Some(name) = waits else {
let _ = call.reply.send((said, true));
return;
};
let (errs, busy, c) = (self.ch.mcp_errors.clone(), self.ch.mcp_busy.clone(), ctx.clone());
std::thread::spawn(move || {
let t0 = Instant::now();
// (Let the window start the connection first: until then the old answer stands.)
std::thread::sleep(std::time::Duration::from_millis(600));
loop {
c.request_repaint();
let done = !busy.load(Ordering::SeqCst) && t0.elapsed() > std::time::Duration::from_secs(2);
if let Some((text, ok)) = crate::mcp::connected_text(&name, &crate::mcp::status(), &errs.lock().unwrap()).filter(|_| done) {
let _ = call.reply.send((format!("{said}\n{text}"), ok));
return;
}
if t0.elapsed() > CONNECT_WAIT {
let _ = call.reply.send((format!("{said}\n還在連線中(第一次啟動可能在下載套件)。稍後用 action=list 看它連上了沒有。"), true));
return;
}
std::thread::sleep(std::time::Duration::from_millis(500));
}
});
}
/// 重新連線 (here, or asked by a screen or the phone): drop the server's link and connect it /// 重新連線 (here, or asked by a screen or the phone): drop the server's link and connect it
/// again now; its line says 連線中… until the answer. /// again now; its line says 連線中… until the answer.
pub(super) fn mcp_reconnect(&mut self, name: &str) { pub(super) fn mcp_reconnect(&mut self, name: &str) {

View File

@ -176,6 +176,8 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> String {
"send_to_device" => "正在傳到你的另一台裝置".into(), "send_to_device" => "正在傳到你的另一台裝置".into(),
"publish_site" => "正在發布網站".into(), "publish_site" => "正在發布網站".into(),
"show_card" => "正在整理成卡片".into(), "show_card" => "正在整理成卡片".into(),
"submit_plan" => "正在交計畫給你看".into(),
"update_plan" => "正在更新計畫進度".into(),
"react" => "正在按表情".into(), "react" => "正在按表情".into(),
"view_demo_step" => "正在看示範".into(), "view_demo_step" => "正在看示範".into(),
"place_call" => "正在打電話".into(), "place_call" => "正在打電話".into(),
@ -475,7 +477,7 @@ impl App {
if m.role == Role::Tool { if m.role == Role::Tool {
return; return;
} }
let has_body = !m.text.trim().is_empty() || !m.attachments.is_empty() || m.tool_calls.iter().any(|c| c.name == "show_card" || is_talk(&c.name)) || !crate::pages::ids_in(&m.tool_calls).is_empty(); let has_body = !m.text.trim().is_empty() || !m.attachments.is_empty() || m.tool_calls.iter().any(|c| c.name == "show_card" || c.name == crate::plan::SUBMIT_TOOL || is_talk(&c.name)) || !crate::pages::ids_in(&m.tool_calls).is_empty();
let steps_open = self.steps_open.contains(&(bot.id, idx)); let steps_open = self.steps_open.contains(&(bot.id, idx));
if m.role == Role::Assistant && !has_body && !m.summary && !steps_open { if m.role == Role::Assistant && !has_body && !m.summary && !steps_open {
return; return;
@ -784,6 +786,10 @@ impl App {
ui.add_space(6.0); ui.add_space(6.0);
card(ui, &c.args, p); card(ui, &c.args, p);
} }
// 計畫: the plan handed in, as its card (how it stands; its steps tick while followed).
for c in m.tool_calls.iter().filter(|c| c.name == crate::plan::SUBMIT_TOOL) {
self.plan_card(ui, bot, c);
}
// 同事之間: asking a colleague, or handing it work, is a conversation shown here. // 同事之間: asking a colleague, or handing it work, is a conversation shown here.
for c in m.tool_calls.iter().filter(|c| is_talk(&c.name)) { for c in m.tool_calls.iter().filter(|c| is_talk(&c.name)) {
self.talk_card(ui, ctx, bot, m, c); self.talk_card(ui, ctx, bot, m, c);
@ -835,7 +841,7 @@ impl App {
/// How many steps (tool calls) belong to the reply at `idx` and the step messages right /// How many steps (tool calls) belong to the reply at `idx` and the step messages right
/// before it in the same turn. /// before it in the same turn.
fn steps_of(&self, bot: &Bot, idx: usize) -> usize { fn steps_of(&self, bot: &Bot, idx: usize) -> usize {
self.step_range(bot, idx).map(|i| bot.messages[i].tool_calls.iter().filter(|c| c.name != "show_card").count()).sum() self.step_range(bot, idx).map(|i| bot.messages[i].tool_calls.iter().filter(|c| !card_call(&c.name)).count()).sum()
} }
fn step_range(&self, bot: &Bot, idx: usize) -> std::ops::Range<usize> { fn step_range(&self, bot: &Bot, idx: usize) -> std::ops::Range<usize> {
@ -857,7 +863,7 @@ impl App {
ui.label(RichText::new(&m.thinking).size(FONT_SM).color(p.text3)); ui.label(RichText::new(&m.thinking).size(FONT_SM).color(p.text3));
}); });
} }
for c in m.tool_calls.iter().filter(|c| c.name != "show_card") { for c in m.tool_calls.iter().filter(|c| !card_call(&c.name)) {
use crate::icons::Icon; use crate::icons::Icon;
let (icon, col) = match c.status { let (icon, col) = match c.status {
ToolStatus::Waiting => (Icon::Alert, p.accent), ToolStatus::Waiting => (Icon::Alert, p.accent),
@ -908,7 +914,7 @@ impl App {
if let (None, Some((asked, who))) = (&live.status, colleague) { if let (None, Some((asked, who))) = (&live.status, colleague) {
return Some(if asked { format!("正在回答「{who}」的問題…") } else { format!("正在做「{who}」交辦的事…") }); return Some(if asked { format!("正在回答「{who}」的問題…") } else { format!("正在做「{who}」交辦的事…") });
} }
Some(live.status.clone().unwrap_or_else(|| t(&status_phrase(running.map(|c| (c.name.as_str(), c.args.as_str())), place, waiting, has_text, did_steps, tick)))) Some(live.status.as_deref().map(one_line).unwrap_or_else(|| t(&status_phrase(running.map(|c| (c.name.as_str(), c.args.as_str())), place, waiting, has_text, did_steps, tick))))
} }
pub(super) fn toggle_reaction(&mut self, bot_id: u64, idx: usize, e: &str) { pub(super) fn toggle_reaction(&mut self, bot_id: u64, idx: usize, e: &str) {
@ -1127,7 +1133,28 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool {
} }
/// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs). /// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs).
pub const SLASH_COMMANDS: [(&str, &str); 2] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡")]; pub const SLASH_COMMANDS: [(&str, &str); 4] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)")];
/// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone).
/// A status of several lines — a retry: the error, what it means, when it tries again — used to
/// stack up past the row into the input. It reads as the reason, then what happens now:
/// 「模型供應商目前負載過高,15 秒後重試(第 3 次,共 3 次)…」. The reason is the explanation's first
/// sentence, or the error itself when there is none.
pub(super) fn one_line(s: &str) -> String {
let lines: Vec<&str> = s.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
let Some((now, before)) = lines.split_last() else { return String::new() };
if before.is_empty() {
return now.to_string();
}
let said = before.iter().rev().find(|l| !l.starts_with("錯誤")).or(before.first()).copied().unwrap_or("");
let why = said.split('。').next().unwrap_or(said).trim_end_matches([',', '。', ':']);
format!("{why},{now}")
}
/// Steps drawn as a card of their own (or as the line above the input), not as a step row.
fn card_call(name: &str) -> bool {
matches!(name, "show_card" | crate::plan::SUBMIT_TOOL | crate::plan::UPDATE_TOOL)
}
/// The commands a draft like 「/go」 asks for (none once a space ends the name). /// The commands a draft like 「/go」 asks for (none once a space ends the name).
pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> { pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> {
@ -1192,12 +1219,21 @@ mod tests {
assert!((pop(1.0) - 1.0).abs() < 1e-4 && pop(0.6) > 1.0); assert!((pop(1.0) - 1.0).abs() < 1e-4 && pop(0.6) > 1.0);
} }
#[test]
fn a_status_of_several_lines_reads_as_one() {
assert_eq!(one_line("錯誤 503:Server busy: husky queue longer than 10 seconds\n模型供應商目前負載過高。通常是暫時的。\n15 秒後重試(第 3 次,共 3 次)…"), "模型供應商目前負載過高,15 秒後重試(第 3 次,共 3 次)…");
assert_eq!(one_line("錯誤 429:rate limited\n5 秒後重試(第 1 次,共 3 次)…"), "錯誤 429:rate limited,5 秒後重試(第 1 次,共 3 次)…");
assert_eq!(one_line("正在讀網頁…"), "正在讀網頁…");
assert_eq!(one_line(" \n"), "");
}
#[test] #[test]
fn the_slash_list_offers_goal_first() { fn the_slash_list_offers_goal_first() {
assert_eq!(slash_commands("/").len(), SLASH_COMMANDS.len()); assert_eq!(slash_commands("/").len(), SLASH_COMMANDS.len());
assert_eq!(slash_commands("/go").first().map(|c| c.0), Some("goal")); assert_eq!(slash_commands("/go").first().map(|c| c.0), Some("goal"));
assert_eq!(slash_commands("/GOAL").first().map(|c| c.0), Some("goal")); assert_eq!(slash_commands("/GOAL").first().map(|c| c.0), Some("goal"));
assert!(slash_commands("/pptx").is_empty()); assert!(slash_commands("/pptx").is_empty());
assert_eq!(slash_commands("/pl").first().map(|c| c.0), Some("plan"));
assert!(slash_commands("/goal 測試通過").is_empty(), "a space ends the name"); assert!(slash_commands("/goal 測試通過").is_empty(), "a space ends the name");
assert!(slash_commands("goal").is_empty()); assert!(slash_commands("goal").is_empty());
let (tag, body) = wake_tag("[目標]還沒達成:還有 1 個失敗"); let (tag, body) = wake_tag("[目標]還沒達成:還有 1 個失敗");

View File

@ -110,6 +110,8 @@ impl App {
pub(super) fn goal_drop(&mut self, bot_id: u64) { pub(super) fn goal_drop(&mut self, bot_id: u64) {
if let Some(b) = self.state.bot_mut(bot_id) { if let Some(b) = self.state.bot_mut(bot_id) {
b.goal = None; b.goal = None;
// 計畫 too: it was about that chat.
b.plan = None;
} }
self.goal_checking.remove(&bot_id); self.goal_checking.remove(&bot_id);
self.goal_due.retain(|(id, _)| *id != bot_id); self.goal_due.retain(|(id, _)| *id != bot_id);

View File

@ -181,6 +181,28 @@ fn scenes() -> Vec<(&'static str, Open)> {
a.approvals.insert(id, Approval { call_id: "audit-q".into(), tool: crate::ask::TOOL.into(), reason: qs.to_string(), grant: String::new(), reply, kind: ApprovalKind::Question }); a.approvals.insert(id, Approval { call_id: "audit-q".into(), tool: crate::ask::TOOL.into(), reason: qs.to_string(), grant: String::new(), reply, kind: ApprovalKind::Question });
}), }),
), ),
(
"聊天:計畫卡(長步驟)與計畫列",
Box::new(|a: &mut App| {
let id = a.state.selected;
let long = "把客戶服務與售後追蹤小組的每週報表從舊的共用資料夾搬到新的雲端硬碟並保留所有版本紀錄";
let args = |n: &str| serde_json::json!({"summary": format!("{long},做完後兩邊的檔案數量和最後修改時間都一樣。"), "steps": [
{"title": format!("{n}備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"), "detail": "Extremely-long-unbreakable-detail-token-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"},
{"title": long}, {"title": "檢查兩邊的檔案數量"}],
"check": "兩邊 find | wc -l 一樣", "notes": format!("會用掉約 2 GB 空間;{long}")}).to_string();
if let Some(b) = a.state.bot_mut(id) {
let call = |cid: &str, n: &str| crate::model::ToolCall { id: cid.into(), name: crate::plan::SUBMIT_TOOL.into(), args: args(n), status: ToolStatus::Done };
b.messages.push(Message::user(&format!("/plan {long}")));
b.messages.push(Message { tool_calls: vec![call("audit-p1", "")], ..Message::assistant("", "模型") });
b.messages.push(Message::tool_result("audit-p1", crate::plan::SUBMIT_TOOL, &crate::plan::approved_result(&[])));
b.messages.push(Message { tool_calls: vec![call("audit-p2", "新版:")], ..Message::assistant("", "模型") });
b.plan = Some(crate::plan::Plan { task: long.into(), since: 0, stage: crate::plan::Stage::Doing, revisions: 0, steps: vec![
crate::plan::Step { title: format!("備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"), status: crate::plan::Status::Done },
crate::plan::Step { title: long.into(), status: crate::plan::Status::InProgress },
crate::plan::Step { title: "檢查兩邊的檔案數量".into(), status: crate::plan::Status::Pending }] });
}
}),
),
( (
"聊天:需要處理(長指示)", "聊天:需要處理(長指示)",
Box::new(|a: &mut App| { Box::new(|a: &mut App| {

View File

@ -45,7 +45,7 @@ fn copy_own(to: &mut State, from: &State) {
to.celebrate = from.celebrate; to.celebrate = from.celebrate;
} }
/// Bot fields the brain alone changes (its chat, and what a turn leaves behind). /// Bot fields the brain alone changes (its chat, and what a turn leaves behind).
const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "context_tokens", "goal", "regen_undo", "branches", "branch_of"]; const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"];
/// Stands in for a key or token the brain doesn't hand out. /// Stands in for a key or token the brain doesn't hand out.
pub const REDACTED: &str = "••••(已設定,在大腦上)"; pub const REDACTED: &str = "••••(已設定,在大腦上)";

244
src/app/plan_ui.rs Normal file
View File

@ -0,0 +1,244 @@
// 計畫 (/plan) in the window: 「/plan …」 typed to this brain (here, on one of its screens, on the
// phone), what a turn says about its plan (approved, dropped, sent back, the steps moving on),
// the line above the input, and the plan's card in the chat. What a plan is and what the bot is
// told: plan.rs; how a turn keeps to it (only looking until it is approved): agent.rs.
//
// The approval itself is a 問題卡 (開始照計畫做 · 先不要 · their own words), so the window, a
// screen of another brain and the phone all answer it the way they answer any question.
use super::*;
use crate::plan::{self, Command, Outcome, Plan, Stage, Status};
use serde_json::{json, Value};
/// How the plan `call` handed in stands (from its step's result), and the plan being followed
/// when it is this one: the newest approved plan, while the bot has a plan to follow.
pub(super) fn plan_state<'a>(bot: &'a Bot, call: &crate::model::ToolCall) -> (Outcome, Option<&'a Plan>) {
let result = |id: &str| bot.messages.iter().rev().find(|m| m.role == Role::Tool && m.tool_call_id == id).map(|m| m.text.as_str());
let how = plan::outcome(result(&call.id));
let following = bot.plan.as_ref().filter(|pl| pl.stage == Stage::Doing).filter(|_| {
how == Outcome::Approved && bot.messages.iter().rev().flat_map(|m| m.tool_calls.iter().rev()).find(|c| c.name == plan::SUBMIT_TOOL && plan::outcome(result(&c.id)) == Outcome::Approved).is_some_and(|c| c.id == call.id)
});
(how, following)
}
/// The plan card's state for the phone (its words for `Outcome`), and the steps as followed now.
pub(super) fn plan_card_state(bot: &Bot, call: &crate::model::ToolCall) -> (Value, Value) {
let (how, following) = plan_state(bot, call);
let state = match how {
Outcome::Waiting => "waiting",
Outcome::Approved => "approved",
Outcome::Changed => "changed",
Outcome::NotNow | Outcome::Refused => "not_now",
};
let live = following.map(|pl| serde_json::to_value(&pl.steps).unwrap_or(Value::Null)).unwrap_or(Value::Null);
(json!(state), live)
}
impl App {
/// 「/plan …」: show, cancel, or start planning.
pub(super) fn plan_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: Command, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) {
let Some(b) = self.state.bot(bot_id) else { return };
match cmd {
Command::Status => {
let s = plan::status(b.plan.as_ref());
self.goal_note(bot_id, &s);
}
Command::Clear => {
let s = match self.state.bot_mut(bot_id).and_then(|b| b.plan.take()) {
Some(p) => format!("已取消計畫:{}", p.task),
None => "沒有計畫。".into(),
};
// A plan waiting on its card: the card goes too (as 先不要: the turn stops
// there, nothing done).
if self.approvals.get(&bot_id).is_some_and(|a| a.tool == plan::SUBMIT_TOOL) {
self.answer(ctx, bot_id, ApprovalAnswer::Reject);
}
self.goal_note(bot_id, &s);
}
Command::Start(task) => {
if !b.members.is_empty() {
self.goal_note(bot_id, "群組聊天還不能用 /plan。");
return;
}
if task.chars().count() > plan::MAX_TASK_CHARS {
self.goal_note(bot_id, &format!("要做的事太長了(最多 {} 字)。", plan::MAX_TASK_CHARS));
return;
}
// Planning is a turn of its own (its tools are set when it starts).
if self.streams.contains_key(&bot_id) {
let name = b.name.clone();
self.goal_note(bot_id, &format!("{name} 正在做事:等它做完,或先按停止,再用 /plan。"));
return;
}
let m = person_message(&self.state, bot_id, text.trim(), attachments, picks);
if let Some(b) = self.state.bot_mut(bot_id) {
b.plan = Some(Plan::new(&task, m.at));
b.messages.push(m);
}
self.start_reply(ctx, bot_id);
}
}
self.dirty = true;
self.save_now = true;
}
/// What a turn said about its plan.
pub(super) fn plan_event(&mut self, bot_id: u64, ev: plan::Event) {
let Some(b) = self.state.bot_mut(bot_id) else { return };
match ev {
plan::Event::Approved(steps) => {
if let Some(p) = b.plan.as_mut() {
p.stage = Stage::Doing;
p.steps = steps;
}
}
plan::Event::NotNow => b.plan = None,
plan::Event::Changed => {
if let Some(p) = b.plan.as_mut() {
p.revisions += 1;
}
}
plan::Event::Progress(steps) => {
if let Some(p) = b.plan.as_mut().filter(|p| p.stage == Stage::Doing) {
p.steps = steps;
}
}
}
self.dirty = true;
self.save_now = true;
}
/// A turn ended: a plan with every step done is over (a line says so).
pub(super) fn plan_settled(&mut self, bot_id: u64) {
let Some(p) = self.state.bot(bot_id).and_then(|b| b.plan.clone()).filter(Plan::finished) else { return };
if let Some(b) = self.state.bot_mut(bot_id) {
b.plan = None;
}
self.goal_note(bot_id, &plan::finished_note(&p));
self.save_now = true;
}
/// 取消計畫 above the input: on a screen the brain cancels it, as if typed there.
fn plan_clear(&mut self, ctx: &egui::Context, bot_id: u64) {
if self.mir.on {
self.mirror_send(bot_id, "/plan clear".into(), vec![], None);
return;
}
self.plan_command(ctx, bot_id, Command::Clear, "/plan clear", vec![], None);
}
/// The line above the input while there is a plan: where it is (the steps on hover) and
/// 取消計畫. The words end in … before the button on a narrow window.
pub(super) fn plan_bar(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) {
let Some(pl) = bot.plan.as_ref() else { return };
let p = self.pal;
let text = t(&plan::bar_text(pl));
let mut tip = format!("{}{}", t("要做的事:"), pl.task);
if pl.stage == Stage::Doing {
tip.push_str(&format!("\n\n{}", plan::checklist(&pl.steps)));
}
let mut clear = false;
ui.horizontal(|ui| {
ui.add_space(14.0);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.add_space(10.0);
clear = small_button(ui, "取消計畫", p).clicked();
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let (r, _) = ui.allocate_exact_size(vec2(13.0, 14.0), egui::Sense::hover());
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Summary, p.accent);
ui.add(egui::Label::new(RichText::new(&text).size(FONT_XS).color(p.text2)).truncate().selectable(false)).on_hover_text(&tip);
});
});
});
ui.add_space(2.0);
if clear {
self.plan_clear(ctx, bot.id);
}
}
/// The plan a bot handed in (`submit_plan`), as a card in its reply: waiting on the person,
/// followed (its steps tick as the bot goes: the newest approved plan, while it lasts),
/// changed, or not taken. One sent back or not taken shows only its summary.
pub(super) fn plan_card(&self, ui: &mut egui::Ui, bot: &Bot, call: &crate::model::ToolCall) {
let Ok(draft) = plan::parse_draft(&call.args) else { return };
let (how, following) = plan_state(bot, call);
if how == Outcome::Refused {
return;
}
let p = self.pal;
let label = match how {
Outcome::Waiting => t("等你決定"),
Outcome::Approved => match following {
Some(pl) => format!("{} · {}/{}", t("照著做"), pl.done(), pl.steps.len()),
None => t("已核准"),
},
Outcome::Changed => t("已修改,見下面新版"),
Outcome::NotNow | Outcome::Refused => t("沒有採用"),
};
let whole = matches!(how, Outcome::Waiting | Outcome::Approved);
ui.add_space(6.0);
Frame::new()
.fill(p.elevated)
.stroke(Stroke::new(1.0, if how == Outcome::Waiting { p.accent } else { p.border }))
.corner_radius(R_L)
.inner_margin(Margin::symmetric(14, 12))
.show(ui, |ui| {
ui.set_max_width(message_max_width(ui.available_width() + 32.0));
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), egui::Sense::hover());
crate::icons::paint(ui.painter(), r, crate::icons::Icon::Summary, p.text2);
ui.label(RichText::new(t("計畫")).strong().family(crate::bold()).size(FONT_BASE));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.label(RichText::new(label).size(FONT_XS).color(if how == Outcome::Waiting { p.accent } else { p.text3 }));
});
});
ui.add_space(4.0);
ui.add(egui::Label::new(RichText::new(&draft.summary).size(FONT_SM).color(if whole { p.text } else { p.text2 })).wrap());
if !whole {
return;
}
ui.add_space(6.0);
// The steps: as the bot keeps them while it follows the plan, else as handed in.
let rows: Vec<(String, String, Option<Status>)> = match following {
Some(pl) => pl.steps.iter().map(|s| (s.title.clone(), draft.steps.iter().find(|d| d.title == s.title).map(|d| d.detail.clone()).unwrap_or_default(), Some(s.status))).collect(),
None => draft.steps.iter().map(|s| (s.title.clone(), s.detail.clone(), None)).collect(),
};
for (i, (title, detail, status)) in rows.iter().enumerate() {
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let (mark, col) = match status {
Some(Status::Done) => ("✓".to_string(), p.up),
Some(Status::InProgress) => ("●".to_string(), p.accent),
Some(Status::Skipped) => ("–".to_string(), p.text3),
_ => (format!("{}.", i + 1), p.text3),
};
ui.add_sized(vec2(18.0, 18.0), egui::Label::new(RichText::new(mark).size(FONT_SM).color(col)));
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 1.0;
let done = matches!(status, Some(Status::Done | Status::Skipped));
let mut words = RichText::new(title).size(FONT_SM).color(if done { p.text3 } else { p.text });
if *status == Some(Status::Skipped) {
words = words.strikethrough();
}
ui.add(egui::Label::new(words).wrap());
if !detail.is_empty() && !done {
ui.add(egui::Label::new(RichText::new(detail).size(FONT_XS).color(p.text3)).wrap());
}
});
});
}
for (head, body) in [("怎麼確認做對了:", &draft.check), ("注意:", &draft.notes)] {
if !body.is_empty() {
ui.add_space(6.0);
ui.add(egui::Label::new(RichText::new(format!("{}{body}", t(head))).size(FONT_XS).color(p.text2)).wrap());
}
}
if how == Outcome::Waiting {
ui.add_space(6.0);
ui.label(RichText::new(t("在下面的卡片選「開始照計畫做」,或寫下要改哪裡")).size(FONT_XS).color(p.text3));
}
});
}
}

View File

@ -401,6 +401,11 @@ impl App {
"thinking": b.thinking, "step_model": b.step_model, "thinking": b.thinking, "step_model": b.step_model,
"queued": live.map(|l| l.steer.lock().unwrap().iter().map(|q| q.text.clone()).collect::<Vec<_>>()).unwrap_or_default(), "queued": live.map(|l| l.steer.lock().unwrap().iter().map(|q| q.text.clone()).collect::<Vec<_>>()).unwrap_or_default(),
// 目標: how it stands (the line above the input), worded here so the phone says it the same way. // 目標: how it stands (the line above the input), worded here so the phone says it the same way.
// 計畫: where it is (the line above the input), worded here like the window's.
"plan": b.plan.as_ref().map(|p| json!({
"task": p.task, "stage": p.stage, "line": crate::plan::bar_text(p),
"steps": if p.stage == crate::plan::Stage::Doing { crate::plan::checklist(&p.steps) } else { String::new() },
})),
"goal": b.goal.as_ref().map(|g| json!({ "goal": b.goal.as_ref().map(|g| json!({
"condition": g.condition, "reason": g.reason, "active": g.active(), "condition": g.condition, "reason": g.reason, "active": g.active(),
"line": if g.active() && self.goal_checking.contains(&b.id) { "目標 · 正在檢查有沒有達成…".to_string() } else { crate::goal::bar_text(g, crate::model::now_ms()) }, "line": if g.active() && self.goal_checking.contains(&b.id) { "目標 · 正在檢查有沒有達成…".to_string() } else { crate::goal::bar_text(g, crate::model::now_ms()) },
@ -430,6 +435,12 @@ impl App {
} }
if let Some(tools) = v["tools"].as_array_mut() { if let Some(tools) = v["tools"].as_array_mut() {
for (t, c) in tools.iter_mut().zip(m.tool_calls.iter()) { for (t, c) in tools.iter_mut().zip(m.tool_calls.iter()) {
if t["plan"].is_object() {
let (state, live) = super::plan_ui::plan_card_state(b, c);
t["plan"]["state"] = state;
t["plan"]["live"] = live;
continue;
}
if t.get("talk").is_some() { if t.get("talk").is_some() {
if let Some(r) = results.get(c.id.as_str()) { if let Some(r) = results.get(c.id.as_str()) {
t["talk"]["answer"] = json!(clip(r.trim(), 2000)); t["talk"]["answer"] = json!(clip(r.trim(), 2000));
@ -532,6 +543,15 @@ impl App {
self.goal_command(ctx, bot, cmd, &text, atts, memories); self.goal_command(ctx, bot, cmd, &text, atts, memories);
return; return;
} }
if let Some(cmd) = crate::plan::command(&text) {
self.plan_command(ctx, bot, cmd, &text, atts, memories);
return;
}
// 一律放行: the owner's (a teammate's words arrive as 「【名字】…」, never a command).
if let Some(cmd) = crate::always::command(&text) {
self.always_command(ctx, bot, cmd);
return;
}
self.goal_heard(bot); self.goal_heard(bot);
} }
if self.streams.contains_key(&bot) { if self.streams.contains_key(&bot) {

View File

@ -9,7 +9,7 @@ use crate::model::{self, Bot, Message, State, Theme, Accent};
use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::providers::{ProviderKind, ALL_PROVIDERS};
use crate::routines::{self, Routine, Schedule}; use crate::routines::{self, Routine, Schedule};
pub const NAMES: [&str; 28] = [ pub const NAMES: [&str; 29] = [
"list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now", "list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now",
"list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings", "list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings",
// 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs); // 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs);
@ -20,6 +20,9 @@ pub const NAMES: [&str; 28] = [
// 個人檔案: a bot looks at its own settings and changes them when the person asks (each change // 個人檔案: a bot looks at its own settings and changes them when the person asks (each change
// is shown to the person first; run on the window's side, which knows the computers). // is shown to the person first; run on the window's side, which knows the computers).
"my_profile", "update_my_profile", "my_profile", "update_my_profile",
// 連接器: list, add, change, reconnect and remove them (the window runs it; it knows how they
// connect; adding, changing and removing ask the person first).
crate::mcp::MANAGE_TOOL,
]; ];
pub fn is_app_tool(name: &str) -> bool { pub fn is_app_tool(name: &str) -> bool {
@ -29,6 +32,7 @@ pub fn is_app_tool(name: &str) -> bool {
pub fn label(name: &str) -> &'static str { pub fn label(name: &str) -> &'static str {
match name { match name {
"list_routines" => "查看例行任務", "list_routines" => "查看例行任務",
crate::mcp::MANAGE_TOOL => "管理連接器",
"create_routine" => "建立例行任務", "create_routine" => "建立例行任務",
"update_routine" => "修改例行任務", "update_routine" => "修改例行任務",
"delete_routine" => "刪除例行任務", "delete_routine" => "刪除例行任務",
@ -154,6 +158,7 @@ pub fn specs() -> Vec<Value> {
json!({"name": "update_settings", "description": "Change app settings: theme (light/dark/system), accent (bot_color/black), timezone (IANA). Running tasks on the person's own computer can only be turned on by the person.", json!({"name": "update_settings", "description": "Change app settings: theme (light/dark/system), accent (bot_color/black), timezone (IANA). Running tasks on the person's own computer can only be turned on by the person.",
"parameters": {"type": "object", "properties": { "parameters": {"type": "object", "properties": {
"theme": {"type": "string", "enum": ["light", "dark", "system"]}, "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}), "theme": {"type": "string", "enum": ["light", "dark", "system"]}, "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}),
crate::mcp::manage_spec(),
] ]
.into_iter() .into_iter()
.chain(crate::pages::specs()) .chain(crate::pages::specs())
@ -171,6 +176,7 @@ pub fn describe(name: &str, args: &str) -> String {
format!("{t} {when}").trim().to_string() format!("{t} {when}").trim().to_string()
} }
"delete_routine" | "run_routine_now" => format!("#{}", v.get("id").and_then(Value::as_u64).unwrap_or(0)), "delete_routine" | "run_routine_now" => format!("#{}", v.get("id").and_then(Value::as_u64).unwrap_or(0)),
crate::mcp::MANAGE_TOOL => format!("{} {}", s("action"), s("name")).trim().to_string(),
"message_bot" => format!("給 {}:{}", s("bot"), s("text").chars().take(40).collect::<String>()), "message_bot" => format!("給 {}:{}", s("bot"), s("text").chars().take(40).collect::<String>()),
"ask_bot" => format!("問 {}:{}", s("bot"), s("question").chars().take(40).collect::<String>()), "ask_bot" => format!("問 {}:{}", s("bot"), s("question").chars().take(40).collect::<String>()),
"teach_skill" => format!("「{}」給 {}", s("skill"), s("bot")), "teach_skill" => format!("「{}」給 {}", s("skill"), s("bot")),
@ -795,6 +801,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
goal: None, goal: None,
plan: None,
draft: String::new(), draft: String::new(),
regen_undo: vec![], regen_undo: vec![],
team: false, team: false,

View File

@ -38,6 +38,7 @@ pub const AREAS: &[Area] = &[
area!("pages", "頁面"), area!("pages", "頁面"),
area!("routines", "例行任務"), area!("routines", "例行任務"),
area!("goal", "目標(/goal)"), area!("goal", "目標(/goal)"),
area!("plan", "計畫(/plan)"),
area!("computers", "電腦:大腦與手腳"), area!("computers", "電腦:大腦與手腳"),
area!("files", "檔案與指令"), area!("files", "檔案與指令"),
area!("browser", "瀏覽器"), area!("browser", "瀏覽器"),
@ -108,6 +109,7 @@ mod tests {
all.extend(names(&crate::phone::specs())); all.extend(names(&crate::phone::specs()));
all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true }))); all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true })));
all.push(crate::ask::spec()["name"].as_str().unwrap().to_string()); all.push(crate::ask::spec()["name"].as_str().unwrap().to_string());
all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL].map(String::from));
all.push(crate::teach::view_step_spec()["name"].as_str().unwrap().to_string()); all.push(crate::teach::view_step_spec()["name"].as_str().unwrap().to_string());
all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from)); all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from));
all.sort(); all.sort();

View File

@ -70,6 +70,8 @@ mod evidence;
mod featuremap; mod featuremap;
mod garden; mod garden;
mod goal; mod goal;
mod plan;
mod always;
mod store; mod store;
mod docindex; mod docindex;
mod drops; mod drops;

View File

@ -916,6 +916,281 @@ pub fn market_server(name: &str, cmd: &str) -> Server {
Server { name: name.to_string(), command, args, ..serde_json::from_str("{\"name\":\"x\"}").unwrap() } Server { name: name.to_string(), command, args, ..serde_json::from_str("{\"name\":\"x\"}").unwrap() }
} }
// ---------- 管理連接器: a bot does what 設定 › 整合 › 連接器 does ----------
/// Which connector tools there are now (a turn notices one added or gone while it runs).
pub fn tools_sig() -> String {
sorted_tools().iter().map(|t| format!("{}/{}", t.server, t.name)).collect::<Vec<_>>().join("|")
}
/// A tool spec that comes from the connectors (one of theirs, or the two that find and use them).
pub fn is_connector_spec(name: &str) -> bool {
is_mcp_tool(name) || name == FIND_TOOL || name == USE_TOOL
}
/// The tool a bot lists, adds, changes, reconnects and removes connectors with. They land in the
/// brain's own list (the one 設定 › 整合 › 連接器 shows, on every screen and the phone): the turn
/// runs on the brain, so there is no other place they could go.
pub const MANAGE_TOOL: &str = "manage_connectors";
pub fn manage_spec() -> Value {
json!({"name": MANAGE_TOOL,
"description": "List, add, change (including turning on or off), reconnect or remove the person's connectors (MCP servers) — what 設定 › 整合 › 連接器 does. They run on the brain (this AnyBot) and every bot with the 連接器 ability gets their tools; a connector added now can be used from your next step. Adding, changing and removing show the person a card first (a command runs on the brain). A local server is a command (`npx -y …`, `uvx …`; the brain needs Node.js or uv); a remote one is a URL (Streamable HTTP). Secrets go in env, headers or password, never in instructions. Try a command once on your computer before adding it. After adding, the answer says whether it connected (a first start may download packages for a minute; check again with action=list).",
"parameters": {"type": "object", "properties": {
"action": {"type": "string", "enum": ["list", "add", "update", "remove", "reconnect"]},
"name": {"type": "string", "description": "The connector's name (short, e.g. gitlab). Needed for everything but list."},
"command": {"type": "string", "description": "A local server's command line, e.g. `npx -y @zereight/mcp-gitlab`. Not with url."},
"url": {"type": "string", "description": "A remote server's address (http:// or https://). Not with command."},
"env": {"type": "object", "additionalProperties": {"type": "string"}, "description": "Environment variables for a local server, e.g. {\"GITLAB_API_URL\": \"https://gitlab.example.com/api/v4\"}. With update, the whole set."},
"headers": {"type": "object", "additionalProperties": {"type": "string"}, "description": "Headers for a remote server, e.g. {\"Authorization\": \"Bearer …\"}. With update, the whole set."},
"username": {"type": "string", "description": "For a server that signs in with an account (see {username} in the connector help)."},
"password": {"type": "string", "description": "Its password (kept like a key, never shown)."},
"instructions": {"type": "string", "description": "Notes for bots on how to use it."},
"enabled": {"type": "boolean", "description": "update: false turns it off, true on."}},
"required": ["action"]}})
}
/// What a `manage_connectors` call asks for, checked against the list as it is. (One lives for
/// a call, so an update carrying two servers is fine unboxed.)
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum Change {
List,
Add(Server),
Update { before: Server, after: Server },
Remove(Server),
Reconnect(String),
}
/// `{"K": "v"}`, or 「K=v K2=v2」 as the form takes it.
fn pairs_of(v: &Value, sep: char) -> Option<BTreeMap<String, String>> {
match v {
Value::Object(o) => Some(o.iter().map(|(k, v)| (k.trim().to_string(), v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).filter(|(k, _)| !k.is_empty()).collect()),
Value::String(s) if sep == '=' => Some(s.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect()),
Value::String(s) => Some(s.lines().filter_map(|kv| kv.split_once(sep)).map(|(k, v)| (k.trim().to_string(), v.trim().to_string())).collect()),
_ => None,
}
}
/// A command line or an address into the server, as the 新增連接器 form does it.
fn set_place(s: &mut Server, command: Option<&str>, url: Option<&str>) -> Result<(), String> {
match (command.map(str::trim).filter(|c| !c.is_empty()), url.map(str::trim).filter(|u| !u.is_empty())) {
(Some(_), Some(_)) => Err("command 和 url 只能給一個:本機伺服器給 command,遠端伺服器給 url。".into()),
(Some(c), None) if c.starts_with("http://") || c.starts_with("https://") => set_place(s, None, Some(c)),
(Some(c), None) => {
let mut it = c.split_whitespace();
s.command = it.next().unwrap_or_default().to_string();
s.args = it.map(String::from).collect();
s.url.clear();
Ok(())
}
(None, Some(u)) if u.starts_with("http://") || u.starts_with("https://") => {
s.url = u.to_string();
s.command.clear();
s.args.clear();
Ok(())
}
(None, Some(u)) => Err(format!("url 要是 http:// 或 https:// 開頭的網址(收到「{u}」)。")),
(None, None) => Ok(()),
}
}
/// The `manage_connectors` call, checked: what it would change (nothing yet).
pub fn parse_change(args: &str, servers: &[Server]) -> Result<Change, String> {
let v: Value = serde_json::from_str(args).map_err(|_| "manage_connectors 的參數不是 JSON 物件。".to_string())?;
let action = v["action"].as_str().unwrap_or("").trim();
let name = v["name"].as_str().unwrap_or("").trim().to_string();
let find = |n: &str| servers.iter().find(|s| s.name == n || s.name.eq_ignore_ascii_case(n)).cloned();
let names = || {
let all: Vec<&str> = servers.iter().map(|s| s.name.as_str()).collect();
if all.is_empty() { "目前一個連接器都沒有".to_string() } else { format!("現有的:{}", all.join("、")) }
};
let existing = || find(&name).ok_or_else(|| format!("沒有叫「{name}」的連接器({})。", names()));
let text = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
let fill = |s: &mut Server| -> Result<(), String> {
if let Some(e) = v.get("env").filter(|x| !x.is_null()) {
s.env = pairs_of(e, '=').ok_or("env 要是 {\"變數\": \"值\"}。")?;
}
if let Some(h) = v.get("headers").filter(|x| !x.is_null()) {
s.headers = pairs_of(h, ':').ok_or("headers 要是 {\"標頭\": \"值\"}。")?;
}
if let Some(u) = text("username") {
s.username = u.trim().to_string();
}
if let Some(p) = text("password") {
s.password = p;
}
if let Some(i) = text("instructions") {
s.instructions = i.trim().to_string();
}
if let Some(e) = v["enabled"].as_bool() {
s.enabled = e;
}
let shown = format!("{} {} {}", s.command_line(), s.url, s.headers.values().cloned().collect::<Vec<_>>().join(" "));
if Server::unfilled(&shown) {
return Err("指令、網址或標頭裡還有「{…}」沒換成真的值({username}、{password} 以外的)。".into());
}
Ok(())
};
match action {
"list" | "" => Ok(Change::List),
"add" => {
if name.is_empty() {
return Err("新增要給 name(短的名字,例如 gitlab)。".into());
}
if name.chars().count() > 40 {
return Err("name 太長了(最多 40 字)。".into());
}
if let Some(s) = find(&name) {
return Err(format!("已經有叫「{}」的連接器:要改它用 action=update,或換個名字。", s.name));
}
let mut s = Server { name, enabled: true, ..Default::default() };
set_place(&mut s, text("command").as_deref(), text("url").as_deref())?;
if s.command.is_empty() && s.url.is_empty() {
return Err("新增要給 command(本機伺服器的指令,例如 npx -y …)或 url(遠端伺服器的網址)。".into());
}
fill(&mut s)?;
Ok(Change::Add(s))
}
"update" => {
let before = existing()?;
let mut after = before.clone();
set_place(&mut after, text("command").as_deref(), text("url").as_deref())?;
// A new place: the password isn't sent there unless given again (as the form does).
if (after.command_line() != before.command_line() || after.url != before.url) && text("password").is_none() {
after.password.clear();
}
fill(&mut after)?;
if after == before {
return Err(format!("「{}」沒有要改的:給要改的欄位(command、url、env、headers、username、password、instructions 或 enabled)。", before.name));
}
Ok(Change::Update { before, after })
}
"remove" => Ok(Change::Remove(existing()?)),
"reconnect" => Ok(Change::Reconnect(existing()?.name)),
other => Err(format!("action「{other}」看不懂:用 list、add、update、remove 或 reconnect。")),
}
}
impl Server {
/// The command as one line (empty for a remote server).
pub fn command_line(&self) -> String {
std::iter::once(self.command.as_str()).chain(self.args.iter().map(String::as_str)).filter(|x| !x.is_empty()).collect::<Vec<_>>().join(" ")
}
}
/// A name that holds a secret (a key, a token, a password): its value isn't shown on a card.
fn secret_name(k: &str) -> bool {
let k = k.to_ascii_uppercase();
["TOKEN", "KEY", "SECRET", "PASS", "AUTH", "CREDENTIAL", "COOKIE", "PAT"].iter().any(|w| k.contains(w))
}
fn shown_pairs(m: &BTreeMap<String, String>, sep: &str) -> String {
m.iter().map(|(k, v)| if secret_name(k) && !v.is_empty() { format!("{k}{sep}••••(已填)") } else { format!("{k}{sep}{v}") }).collect::<Vec<_>>().join("、")
}
/// One connector's settings as lines for a card (secrets hidden).
fn server_lines(s: &Server) -> Vec<String> {
let mut out = vec![];
if s.url.is_empty() {
out.push(format!("指令(在大腦上執行):{}", s.command_line()));
} else {
out.push(format!("網址:{}", s.url));
}
if !s.env.is_empty() {
out.push(format!("環境變數:{}", shown_pairs(&s.env, "=")));
}
if !s.headers.is_empty() {
out.push(format!("標頭:{}", shown_pairs(&s.headers, ": ")));
}
if !s.username.is_empty() || !s.password.is_empty() {
out.push(format!("帳號:{} · 密碼:{}", if s.username.is_empty() { "(沒填)" } else { &s.username }, if s.password.is_empty() { "(沒填)" } else { "••••(已填)" }));
}
if !s.instructions.is_empty() {
out.push(format!("給 Bot 的說明:{}", s.instructions.chars().take(120).collect::<String>()));
}
out
}
/// What the person is asked before the change (None: nothing to ask — a list or a reconnect).
pub fn change_question(c: &Change) -> Option<String> {
match c {
Change::List | Change::Reconnect(_) => None,
Change::Add(s) => Some(format!("新增連接器「{}」(加在大腦的 設定 › 整合 › 連接器):\n- {}", s.name, server_lines(s).join("\n- "))),
Change::Update { before, after } => {
let (b, a) = (server_lines(before), server_lines(after));
let mut lines: Vec<String> = a.iter().filter(|l| !b.contains(l)).cloned().collect();
lines.extend(b.iter().filter(|l| !a.iter().any(|x| x.split_once(':').map(|p| p.0) == l.split_once(':').map(|p| p.0))).map(|l| format!("拿掉 {}", l.split_once(':').map(|p| p.0).unwrap_or(l))));
if before.enabled != after.enabled {
lines.push(if after.enabled { "打開".into() } else { "關閉(它的工具暫時不能用)".into() });
}
if !before.password.is_empty() && after.password.is_empty() {
lines.push("密碼清掉(換了指令或網址,舊密碼不送過去)".into());
}
if lines.is_empty() {
lines.push("密碼換新".into());
}
Some(format!("修改連接器「{}」:\n- {}", before.name, lines.join("\n- ")))
}
Change::Remove(s) => Some(format!("移除連接器「{}」:它的工具就不能用了,設定(指令、金鑰)一起刪掉。", s.name)),
}
}
/// Make the change in the list (the person said yes). The answer for the bot.
pub fn apply_change(c: &Change, servers: &mut Vec<Server>) -> String {
match c {
Change::List => String::new(),
Change::Add(s) => {
servers.push(s.clone());
format!("已新增連接器「{}」,正在連線。", s.name)
}
Change::Update { before, after } => {
if let Some(x) = servers.iter_mut().find(|x| x.name == before.name) {
*x = after.clone();
}
if after.enabled { format!("已修改連接器「{}」,正在重新連線。", after.name) } else { format!("已關閉連接器「{}」。", after.name) }
}
Change::Remove(s) => {
servers.retain(|x| x.name != s.name);
format!("已移除連接器「{}」。", s.name)
}
Change::Reconnect(n) => format!("正在重新連線「{n}」。"),
}
}
/// The connectors as the bot reads them: each one's state, where it runs and how (secrets hidden).
pub fn list_text(servers: &[Server], status: &HashMap<String, usize>, errors: &[(String, String)], busy: bool) -> String {
if servers.is_empty() {
return "還沒有連接器(設定 › 整合 › 連接器 是空的)。用 action=add 新增。".into();
}
let mut out = String::from("連接器(大腦的 設定 › 整合 › 連接器):");
for s in servers {
let state = if !s.enabled {
"已關閉".to_string()
} else if let Some(n) = status.get(&s.name) {
format!("已連上,{n} 個工具")
} else if let Some((_, e)) = errors.iter().find(|e| e.0 == s.name) {
format!("連不上:{e}")
} else if busy {
"連線中…".into()
} else {
"未連線".into()
};
out.push_str(&format!("\n- {}:{state}\n {}", s.name, server_lines(s).join("\n ")));
}
out
}
/// How the change came out, once the connector has had its chance to connect.
pub fn connected_text(name: &str, status: &HashMap<String, usize>, errors: &[(String, String)]) -> Option<(String, bool)> {
if let Some(n) = status.get(name) {
let names: Vec<String> = tools().iter().filter(|t| t.server == name).take(8).map(|t| t.name.clone()).collect();
let more = if *n > names.len() { "…" } else { "" };
return Some((format!("「{name}」已連上,{n} 個工具({}{more})。從下一步起就能用(工具多時先用 {FIND_TOOL} 找)。", names.join("、")), true));
}
errors.iter().find(|e| e.0 == name).map(|(_, e)| (format!("「{name}」連不上:{e}\n設定已經存好了:修好原因後用 action=update 改,或 action=reconnect 再試。"), false))
}
/// Tests that connect servers share one table: one at a time. /// Tests that connect servers share one table: one at a time.
#[cfg(test)] #[cfg(test)]
pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> { pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
@ -1425,3 +1700,86 @@ for line in sys.stdin:
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
} }
} }
#[cfg(test)]
mod manage_tests {
use super::*;
fn gitlab() -> String {
json!({"action": "add", "name": "gitlab", "command": "npx -y @zereight/mcp-gitlab@2.3.28", "env": {"GITLAB_PERSONAL_ACCESS_TOKEN": "glpat-SECRET", "GITLAB_API_URL": "https://gitlab.example.com/api/v4"}, "instructions": "查 MR 先用 list_merge_requests"}).to_string()
}
/// 管理連接器: an add lands as the form would make it; the card shows what runs and where,
/// never the secret.
#[test]
fn a_connector_added_from_chat_is_what_the_form_makes() {
let c = parse_change(&gitlab(), &[]).unwrap();
let Change::Add(s) = &c else { panic!("{c:?}") };
assert_eq!((s.command.as_str(), s.args.clone()), ("npx", vec!["-y".to_string(), "@zereight/mcp-gitlab@2.3.28".into()]));
assert!(s.enabled && s.url.is_empty());
assert_eq!(s.env["GITLAB_PERSONAL_ACCESS_TOKEN"], "glpat-SECRET");
let q = change_question(&c).unwrap();
assert!(q.contains("新增連接器「gitlab」") && q.contains("指令(在大腦上執行):npx -y @zereight/mcp-gitlab@2.3.28"), "{q}");
assert!(q.contains("GITLAB_PERSONAL_ACCESS_TOKEN=••••(已填)") && q.contains("GITLAB_API_URL=https://gitlab.example.com/api/v4"), "{q}");
assert!(!q.contains("glpat-SECRET"), "{q}");
let mut list = vec![];
assert_eq!(apply_change(&c, &mut list), "已新增連接器「gitlab」,正在連線。");
assert_eq!(list.len(), 1);
// Remote, with a header given as one line; its secret hidden too.
let r = parse_change(&json!({"action": "add", "name": "notion", "url": "https://mcp.example.com/mcp", "headers": "Authorization: Bearer abc"}).to_string(), &list).unwrap();
let Change::Add(n) = &r else { panic!() };
assert_eq!((n.url.as_str(), n.headers["Authorization"].as_str(), n.command.as_str()), ("https://mcp.example.com/mcp", "Bearer abc", ""));
assert!(change_question(&r).unwrap().contains("Authorization: ••••(已填)"));
}
#[test]
fn a_change_that_cant_be_made_says_why_before_asking() {
let list = vec![fake_server("gitlab", 0)];
let err = |a: Value| parse_change(&a.to_string(), &list).unwrap_err();
assert!(err(json!({"action": "add", "name": "GitLab", "command": "x"})).contains("已經有叫「gitlab」"));
assert!(err(json!({"action": "add", "name": "x"})).contains("command"));
assert!(err(json!({"action": "add", "name": "x", "command": "a", "url": "https://b"})).contains("只能給一個"));
assert!(err(json!({"action": "add", "name": "x", "url": "ftp://b"})).contains("http"));
assert!(err(json!({"action": "add", "name": "x", "url": "https://b/{tenant}"})).contains("{…}"));
assert!(err(json!({"action": "remove", "name": "nope"})).contains("現有的:gitlab"));
assert!(err(json!({"action": "update", "name": "gitlab"})).contains("沒有要改的"));
assert!(err(json!({"action": "zap"})).contains("list"));
assert!(parse_change("{}", &[]).is_ok_and(|c| c == Change::List));
// {username} and {password} are slots, not leftovers.
assert!(parse_change(&json!({"action": "add", "name": "scc", "command": "scc-mcp --user {username}", "username": "amy", "password": "pw"}).to_string(), &list).is_ok());
}
#[test]
fn an_update_turns_off_moves_and_forgets_the_old_password() {
let mut list = vec![Server { password: "old".into(), username: "amy".into(), ..fake_server("scc", 0) }];
let off = parse_change(&json!({"action": "update", "name": "scc", "enabled": false}).to_string(), &list).unwrap();
assert!(change_question(&off).unwrap().contains("關閉"));
assert_eq!(apply_change(&off, &mut list), "已關閉連接器「scc」。");
assert!(!list[0].enabled && list[0].password == "old");
let moved = parse_change(&json!({"action": "update", "name": "scc", "url": "https://new.example.com/mcp", "enabled": true}).to_string(), &list).unwrap();
let q = change_question(&moved).unwrap();
assert!(q.contains("網址:https://new.example.com/mcp") && q.contains("拿掉 指令") && q.contains("密碼清掉") && q.contains("打開"), "{q}");
apply_change(&moved, &mut list);
assert!(list[0].command.is_empty() && list[0].password.is_empty() && list[0].username == "amy");
let gone = parse_change(&json!({"action": "remove", "name": "scc"}).to_string(), &list).unwrap();
assert!(change_question(&gone).unwrap().contains("移除連接器「scc」"));
apply_change(&gone, &mut list);
assert!(list.is_empty());
assert!(change_question(&parse_change(&json!({"action": "list"}).to_string(), &list).unwrap()).is_none());
}
#[test]
fn the_list_says_how_each_stands_without_secrets() {
let mut a = fake_server("calc", 0);
a.env.insert("API_KEY".into(), "k-123".into());
let b = Server { enabled: false, ..fake_server("off", 0) };
let c = fake_server("broken", 0);
let status: HashMap<String, usize> = [("calc".to_string(), 2)].into_iter().collect();
let t = list_text(&[a, b, c], &status, &[("broken".into(), "找不到 npx".into())], false);
assert!(t.contains("- calc:已連上,2 個工具") && t.contains("- off:已關閉") && t.contains("- broken:連不上:找不到 npx"), "{t}");
assert!(t.contains("API_KEY=••••(已填)") && !t.contains("k-123"));
assert!(list_text(&[], &status, &[], false).contains("還沒有連接器"));
assert!(connected_text("broken", &status, &[("broken".into(), "x".into())]).is_some_and(|(t, ok)| !ok && t.contains("action=update")));
assert!(connected_text("nope", &status, &[]).is_none());
}
}

View File

@ -413,6 +413,10 @@ pub struct Bot {
/// The brain's alone (a turn's end changes it); see goal.rs. /// The brain's alone (a turn's end changes it); see goal.rs.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub goal: Option<crate::goal::Goal>, pub goal: Option<crate::goal::Goal>,
/// 計畫 (/plan): look first, hand in a plan, follow it once the person approves. The brain's
/// alone (the turn changes it); see plan.rs.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plan: Option<crate::plan::Plan>,
/// Name of the computer tools use unless told otherwise. /// Name of the computer tools use unless told otherwise.
#[serde(default = "default_computer")] #[serde(default = "default_computer")]
pub default_computer: String, pub default_computer: String,
@ -702,6 +706,15 @@ pub struct State {
/// "always ask" rules stop the bot. /// "always ask" rules stop the bot.
#[serde(default)] #[serde(default)]
pub direct_mode: bool, pub direct_mode: bool,
/// 一律放行 (/always-approve): every request that would wait for 允許 is answered yes by
/// itself (the person's own turns; refusals, questions and someone else's messages excepted).
/// See always.rs.
#[serde(default)]
pub always_approve: bool,
/// Whether 直接操作 was already on when 一律放行 turned it on (so turning 一律放行 off
/// leaves it as it was).
#[serde(default)]
pub direct_before_always: bool,
/// 「在你離開時自動更新用戶端」(4vprnG); on by default like the original. /// 「在你離開時自動更新用戶端」(4vprnG); on by default like the original.
#[serde(default = "yes")] #[serde(default = "yes")]
pub auto_update_when_away: bool, pub auto_update_when_away: bool,
@ -1172,6 +1185,7 @@ impl State {
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
goal: None, goal: None,
plan: None,
default_computer: default_computer(), default_computer: default_computer(),
draft: String::new(), draft: String::new(),
regen_undo: vec![], regen_undo: vec![],
@ -1228,6 +1242,8 @@ impl State {
notify: true, notify: true,
alert_sound: true, alert_sound: true,
direct_mode: false, direct_mode: false,
always_approve: false,
direct_before_always: false,
auto_update_when_away: true, auto_update_when_away: true,
close_browsers_when_done: true, close_browsers_when_done: true,
send_check: true, send_check: true,

565
src/plan.rs Normal file
View File

@ -0,0 +1,565 @@
//! 計畫 (/plan): the bot looks before it acts. 「/plan 要做的事」 puts the bot's chat in planning:
//! it may only look (read files, search, read web pages, take screenshots) and ask the person
//! (問題卡), then hands in a plan with `submit_plan`. The person answers on a card: 開始照計畫做
//! (the turn goes on with every tool, now following the plan), a change in their own words (it
//! revises and hands it in again), or 先不要 (the plan is dropped, nothing was done). While it
//! works it keeps the steps current with `update_plan`, and the line above the input shows where
//! it is. Like Claude Code's plan mode (read-only until the plan is approved), Cursor's Plan
//! Mode (questions first, a plan with to-dos) and Codex's `update_plan` (one step in progress at
//! a time, the whole list each time).
//!
//! The plan lives on the brain, on the bot (`Bot::plan`); screens and the phone show it. Nothing
//! here draws or runs anything: the command, the plan's state, the two tools, what the model is
//! told and how the person's answer is read. The window wires it in (app/plan_ui.rs), the turn
//! keeps to it (agent.rs).
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
/// Longest task after 「/plan」 (like /goal's condition).
pub const MAX_TASK_CHARS: usize = 4_000;
/// Most steps in a plan: more than this is a project, not a plan to approve in one look.
pub const MAX_STEPS: usize = 20;
/// A step's title, at most (a line, not a paragraph).
pub const MAX_TITLE_CHARS: usize = 160;
/// A step's detail, the plan's notes and its check, at most.
const MAX_TEXT_CHARS: usize = 1_500;
/// Plans handed in again after a change before it says the back-and-forth is long.
pub const MANY_REVISIONS: u32 = 5;
/// The bot hands its plan in.
pub const SUBMIT_TOOL: &str = "submit_plan";
/// The bot keeps the steps of an approved plan current.
pub const UPDATE_TOOL: &str = "update_plan";
/// The card's question and its two choices (anything typed instead is a change).
pub const QUESTION: &str = "照這個計畫做嗎?";
pub const APPROVE: &str = "開始照計畫做";
pub const NOT_NOW: &str = "先不要";
/// Where a plan is.
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum Stage {
/// Looking and writing the plan: only the tools that look.
#[default]
Drafting,
/// Approved: every tool, following the plan.
Doing,
}
/// One step's state (Codex's update_plan: pending, in_progress, completed).
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum Status {
#[default]
Pending,
InProgress,
Done,
/// Not needed after all (the bot says why when it skips one).
Skipped,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct Step {
pub title: String,
#[serde(default)]
pub status: Status,
}
/// A bot's plan, kept on the bot (it survives restarts).
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct Plan {
/// What 「/plan …」 asked for.
pub task: String,
/// When it was asked (ms).
pub since: i64,
#[serde(default)]
pub stage: Stage,
/// The approved plan's steps, as the bot last left them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub steps: Vec<Step>,
/// Plans handed in so far that the person sent back with a change.
#[serde(default)]
pub revisions: u32,
}
impl Plan {
pub fn new(task: &str, since: i64) -> Plan {
Plan { task: task.trim().to_string(), since, ..Default::default() }
}
pub fn done(&self) -> usize {
self.steps.iter().filter(|s| matches!(s.status, Status::Done | Status::Skipped)).count()
}
/// Every step done (or skipped).
pub fn finished(&self) -> bool {
self.stage == Stage::Doing && !self.steps.is_empty() && self.done() == self.steps.len()
}
/// The step it is on: the one in progress, else the next one waiting.
pub fn current(&self) -> Option<&Step> {
self.steps.iter().find(|s| s.status == Status::InProgress).or_else(|| self.steps.iter().find(|s| s.status == Status::Pending))
}
}
/// What a turn tells the window about its plan (it keeps `Bot::plan`).
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
/// 開始照計畫做: these are the steps now.
Approved(Vec<Step>),
/// 先不要 (or the card skipped): the plan is dropped.
NotNow,
/// Sent back with a change (on the card, or a message instead).
Changed,
/// `update_plan`: the steps as they stand.
Progress(Vec<Step>),
}
/// What 「/plan …」 asks for.
#[derive(Debug, PartialEq)]
pub enum Command {
/// 「/plan」: how it stands.
Status,
/// 「/plan clear」 (stop, off, reset, none, cancel, 清除, 取消, 停止).
Clear,
/// 「/plan 要做的事」: look first, then hand in a plan.
Start(String),
}
/// 「/plan」, 「/plan clear」 or 「/plan 要做的事」; None for anything else (「/plans」 too).
pub fn command(text: &str) -> Option<Command> {
let rest = text.trim().strip_prefix("/plan")?;
if rest.chars().next().is_some_and(|c| !c.is_whitespace()) {
return None;
}
let arg = rest.trim();
Some(match arg.to_lowercase().as_str() {
"" => Command::Status,
"clear" | "stop" | "off" | "reset" | "none" | "cancel" | "清除" | "取消" | "停止" => Command::Clear,
_ => Command::Start(arg.to_string()),
})
}
// ---------- the plan handed in ----------
/// One step as handed in.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct DraftStep {
pub title: String,
pub detail: String,
}
/// `submit_plan`'s arguments, checked.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Draft {
pub summary: String,
pub steps: Vec<DraftStep>,
/// How it will show the result is right (the last thing it does).
pub check: String,
/// Assumptions, risks, what it found that matters.
pub notes: String,
}
impl Draft {
/// The steps to follow, the first one under way (one call less for the bot: tracking cost
/// Manus a third of its actions).
pub fn steps(&self) -> Vec<Step> {
self.steps.iter().enumerate().map(|(i, s)| Step { title: s.title.clone(), status: if i == 0 { Status::InProgress } else { Status::Pending } }).collect()
}
}
fn cut(s: &str, n: usize) -> String {
let s = s.trim();
if s.chars().count() <= n {
s.to_string()
} else {
format!("{}…", s.chars().take(n).collect::<String>())
}
}
/// `submit_plan`'s arguments (a JSON object; steps as objects or plain lines).
pub fn parse_draft(args: &str) -> Result<Draft, String> {
let v: Value = serde_json::from_str(args).map_err(|_| "submit_plan 的參數不是 JSON 物件。".to_string())?;
let text = |k: &str| v[k].as_str().map(|s| cut(s, MAX_TEXT_CHARS)).unwrap_or_default();
let steps: Vec<DraftStep> = v["steps"]
.as_array()
.into_iter()
.flatten()
.filter_map(|s| match s {
Value::String(t) => Some(DraftStep { title: cut(t, MAX_TITLE_CHARS), detail: String::new() }),
Value::Object(_) => Some(DraftStep { title: cut(s["title"].as_str().unwrap_or(""), MAX_TITLE_CHARS), detail: cut(s["detail"].as_str().unwrap_or(""), MAX_TEXT_CHARS) }),
_ => None,
})
.filter(|s| !s.title.is_empty())
.collect();
let d = Draft { summary: text("summary"), steps, check: text("check"), notes: text("notes") };
if d.summary.is_empty() {
return Err("submit_plan 需要 summary:一兩句話說要做什麼、做完是什麼樣子。".into());
}
if d.steps.is_empty() {
return Err("submit_plan 需要 steps:照順序列出要做的步驟(每步一行標題,必要時加 detail)。".into());
}
if d.steps.len() > MAX_STEPS {
return Err(format!("計畫有 {} 步,太多了(最多 {MAX_STEPS} 步):把小步驟合併,一步是一個看得到的結果。", d.steps.len()));
}
Ok(d)
}
/// The card the person answers (a 問題卡: the window, a screen and the phone all draw it).
pub fn approval_card() -> String {
crate::ask::to_json(&[crate::ask::Question { question: QUESTION.into(), options: vec![APPROVE.into(), NOT_NOW.into()], multiple: false, default: String::new() }])
}
/// What the person said on the card.
#[derive(Debug, PartialEq)]
pub enum Decision {
Approve,
NotNow,
/// Their own words: what to change.
Change(String),
}
/// The card's answer (as it travels back: a JSON list, one string per question).
pub fn decide(answer: &str) -> Decision {
let a = crate::ask::answers_of(answer).into_iter().next().unwrap_or_default();
let a = a.trim();
if a == APPROVE {
Decision::Approve
} else if a.is_empty() || a == NOT_NOW {
Decision::NotNow
} else {
Decision::Change(a.to_string())
}
}
/// How the results of `submit_plan` begin (the card reads its state from them).
const APPROVED_HEAD: &str = "使用者按了「開始照計畫做」";
const NOT_NOW_HEAD: &str = "使用者選了「先不要」";
const CHANGE_HEAD: &str = "使用者還沒核准,他要修改計畫";
const WROTE_HEAD: &str = "使用者沒有按卡片";
/// What the bot reads after 開始照計畫做 (every tool is there from the next step on).
pub fn approved_result(steps: &[Step]) -> String {
format!(
"{APPROVED_HEAD},計畫核准了。現在所有工具都能用了,接著在這一輪照計畫做(第 1 步已經標成進行中):\n{}\n每做完一步用 update_plan 更新一次:同一次把它標 done、下一步標 in_progress。",
checklist(steps)
)
}
/// How a plan handed in stands, from its step's result (None: still waiting on the card).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
Waiting,
Approved,
Changed,
NotNow,
/// Not a plan (its arguments were wrong): nothing to show.
Refused,
}
pub fn outcome(result: Option<&str>) -> Outcome {
match result {
None => Outcome::Waiting,
Some(r) if r.starts_with(APPROVED_HEAD) => Outcome::Approved,
Some(r) if r.starts_with(NOT_NOW_HEAD) => Outcome::NotNow,
Some(r) if r.starts_with(CHANGE_HEAD) || r.starts_with(WROTE_HEAD) => Outcome::Changed,
Some(_) => Outcome::Refused,
}
}
pub const NOT_NOW_RESULT: &str = "使用者選了「先不要」:這個計畫先不做,計畫模式結束了。不要動手做任何事;簡短回一句就好(例如計畫留在上面,之後要做再說),等他下一步指示。";
/// What the bot reads after the person wrote a change on the card.
pub fn change_result(words: &str, revisions: u32) -> String {
let long = if revisions >= MANY_REVISIONS { format!("(已經改了 {revisions} 次:這次改完,如果還有沒說清楚的取捨,先用 ask_person 一次問清楚再交。)") } else { String::new() };
format!("{CHANGE_HEAD}:「{words}」\n照他的意見調整(需要的話再查),再用 submit_plan 交出修改後的完整計畫。還不能動手。{long}")
}
pub const WROTE_INSTEAD_RESULT: &str = "使用者沒有按卡片,而是傳了訊息(就在下面)。照他說的調整計畫,再用 submit_plan 交出來;他在卡片上按「開始照計畫做」才算核准,在那之前還不能動手。";
/// A step that does something, asked for before the plan is approved.
pub const NOT_YET: &str = "計畫模式:計畫還沒核准,現在只能查看、不能動手(這一步沒有執行)。先把需要的資料查清楚,再用 submit_plan 交出計畫;使用者核准之後才能做。";
// ---------- following it ----------
fn status_of(s: &str) -> Option<Status> {
Some(match s.trim().to_lowercase().as_str() {
"pending" | "todo" | "not_started" => Status::Pending,
"in_progress" | "doing" | "active" | "started" => Status::InProgress,
"done" | "completed" | "complete" => Status::Done,
"skipped" | "skip" | "cancelled" | "canceled" => Status::Skipped,
_ => return None,
})
}
/// `update_plan`'s arguments: the whole list, each step with its status. Only one step may be in
/// progress: the first one named so keeps it, later ones wait.
pub fn parse_progress(args: &str) -> Result<Vec<Step>, String> {
let v: Value = serde_json::from_str(args).map_err(|_| "update_plan 的參數不是 JSON 物件。".to_string())?;
let mut steps = vec![];
for s in v["steps"].as_array().into_iter().flatten() {
let title = cut(s["title"].as_str().unwrap_or(""), MAX_TITLE_CHARS);
if title.is_empty() {
continue;
}
let status = match s["status"].as_str() {
None => Status::Pending,
Some(x) => status_of(x).ok_or_else(|| format!("「{title}」的 status「{x}」看不懂:用 pending、in_progress、done 或 skipped。"))?,
};
steps.push(Step { title, status });
}
if steps.is_empty() {
return Err("update_plan 需要 steps:整份清單,每步有 title 和 status(pending、in_progress、done、skipped)。".into());
}
if steps.len() > MAX_STEPS {
return Err(format!("計畫最多 {MAX_STEPS} 步。"));
}
let mut seen = false;
for s in steps.iter_mut().filter(|s| s.status == Status::InProgress) {
if seen {
s.status = Status::Pending;
}
seen = true;
}
Ok(steps)
}
/// What the bot reads after `update_plan`.
pub fn progress_result(steps: &[Step]) -> String {
let p = Plan { stage: Stage::Doing, steps: steps.to_vec(), ..Default::default() };
if p.finished() {
return format!("進度已更新:{} 步全部完成。最後檢查成果(實際的輸出、檔案、畫面),再用一段話跟使用者回報結果。", steps.len());
}
let now = p.current().map(|s| format!(";接下來:{}", s.title)).unwrap_or_default();
format!("進度已更新:{}/{} 完成{now}。", p.done(), steps.len())
}
/// The steps as a short checklist (✓ done, ▸ in progress, ○ waiting, – skipped).
pub fn checklist(steps: &[Step]) -> String {
steps
.iter()
.enumerate()
.map(|(i, s)| {
let mark = match s.status {
Status::Done => "✓",
Status::InProgress => "▸",
Status::Pending => "○",
Status::Skipped => "–",
};
format!("{mark} {}. {}", i + 1, s.title)
})
.collect::<Vec<_>>()
.join("\n")
}
// ---------- what the model is told ----------
/// The system prompt's last part while the plan is being written.
pub fn drafting_block(p: &Plan) -> String {
format!(
"\n\n〔計畫模式〕使用者用 /plan 要你先規劃、他核准後才動手。要做的事:「{}」\n\
現在只能看、不能改:可以讀檔、列資料夾、搜尋、看網頁(web_fetch、browser 的 open/read)、截圖、查記憶和技能、用 anybot_guide 查 AnyBot 怎麼用;執行指令、改檔案、點擊或打字、送出、改設定都會被擋下。\n\
1. 先自己查清楚現況(相關的檔案、網頁、設定、之前的對話),找出真正要改的地方和限制。查得到的就不要問。\n\
2. 有使用者才能決定的取捨(會影響結果、沒有明顯最好的選擇),用 ask_person 一次問完,最多 3 題,每題 2 到 4 個選項、你建議的放第一個。沒有就不要問。他略過問題卡,就用你建議的選項,寫進 notes 當假設。\n\
3. 用 {SUBMIT_TOOL} 交出計畫:只寫你建議的那一個做法(不要列好幾個方案讓他挑);summary 一兩句話說要做什麼、做完是什麼樣子;steps 照順序,通常 3 到 7 步,每步是一個看得到的結果(不是「研究一下」),寫清楚動到哪裡(檔案、網頁、帳號、哪台電腦);最後一步是驗證;check 寫怎麼證明做對了;notes 寫你的假設、風險、會花錢或對外送出、不能復原的地方。計畫要根據你查到的事實,寧可短而對:錯的計畫比沒有計畫更糟。不要在訊息裡把計畫再寫一次,卡片會顯示。\n\
4. 使用者按「{APPROVE}」後,工具就會打開,你在同一輪接著做;他寫了修改,就照著改完再交一次。",
p.task
)
}
/// The system prompt's last part while the approved plan is being carried out.
pub fn doing_block(p: &Plan) -> String {
format!(
"\n\n〔照計畫做〕使用者核准了這個計畫(要做的事:「{}」)。目前進度:\n{}\n\
照順序做,同一時間只有一步是 in_progress。每做完一步用 {UPDATE_TOOL} 更新一次(傳整份清單:同一次把它標 done、下一步標 in_progress);不用每個小動作都更新。\n\
做的時候發現計畫和實際不符(檔案不一樣、多了或少了步驟),用 {UPDATE_TOOL} 改清單,並在訊息裡說一句為什麼,不要默默偏離;要換做法、會多花很多錢或時間、或有風險的大改,先用 ask_person 問。\n\
全部做完:用實際的結果(指令輸出、檔案內容、畫面)檢查,再用一段話回報做了什麼、怎麼確認的、還有什麼沒做。",
p.task,
checklist(&p.steps)
)
}
/// The system prompt's last part for this plan, by where it is.
pub fn block(p: &Plan) -> String {
match p.stage {
Stage::Drafting => drafting_block(p),
Stage::Doing => doing_block(p),
}
}
// ---------- the tools ----------
pub fn submit_spec() -> Value {
json!({"name": SUBMIT_TOOL,
"description": "Hand in your plan for the person to approve (plan mode, after 「/plan」). Use it once you have looked into everything you need; the chat shows the plan as a card with 「開始照計畫做」 and a field to ask for changes, and the turn waits. If they approve, every tool is available from your next step and you carry out the plan in the same turn; if they write a change, revise and call this again with the whole plan; if they say 先不要, stop. Don't repeat the plan in your message.",
"parameters": {"type": "object", "properties": {
"summary": {"type": "string", "description": "One or two sentences in the person's language: what you will do and what it looks like when done."},
"steps": {"type": "array", "description": "The steps in order, 3–7 usually (at most 20): only the approach you recommend. Each is one visible result, naming what it touches (file, page, account, computer). The last one checks the work.",
"items": {"type": "object", "properties": {
"title": {"type": "string", "description": "The step in one short line."},
"detail": {"type": "string", "description": "Only when needed: how, or what exactly changes."}},
"required": ["title"]}},
"check": {"type": "string", "description": "How you will show it worked (a test, a command's output, the page as it looks)."},
"notes": {"type": "string", "description": "Assumptions, risks, anything that costs money, sends something out or can't be undone."}},
"required": ["summary", "steps"]}})
}
pub fn update_spec() -> Value {
json!({"name": UPDATE_TOOL,
"description": "Keep the approved plan's steps current, so the person sees where you are. Send the whole list every time, each step with its status: pending, in_progress (only one at a time), done or skipped. Call it once per finished step: mark that one done and the next in_progress in the same call (not for every small action). If the plan has to change (a step was wrong, one is missing), send the changed list and say why in your message.",
"parameters": {"type": "object", "properties": {
"steps": {"type": "array", "items": {"type": "object", "properties": {
"title": {"type": "string"},
"status": {"type": "string", "enum": ["pending", "in_progress", "done", "skipped"]}},
"required": ["title", "status"]}}},
"required": ["steps"]}})
}
// ---------- what the person sees ----------
/// 「/plan」 with nothing after it.
pub fn status(p: Option<&Plan>) -> String {
let Some(p) = p else { return "沒有計畫。用「/plan 要做的事」讓它先查清楚、寫出計畫給你核准,核准後才動手。".into() };
match p.stage {
Stage::Drafting => format!("正在規劃:{}\n還沒動手:它在查資料、寫計畫,交出來後由你決定要不要照著做。不要了就用 /plan clear。", p.task),
Stage::Doing => format!("照計畫做:{}\n{}/{} 步完成\n{}", p.task, p.done(), p.steps.len(), checklist(&p.steps)),
}
}
/// The one line above the input while there is a plan.
pub fn bar_text(p: &Plan) -> String {
match p.stage {
Stage::Drafting => "計畫模式 · 只查資料、寫計畫,你核准後才動手".into(),
Stage::Doing => match p.current() {
Some(s) => format!("照計畫做 · {}/{} · {}", p.done(), p.steps.len(), s.title),
None => format!("照計畫做 · {}/{}", p.done(), p.steps.len()),
},
}
}
/// The line left in the chat when every step is done.
pub fn finished_note(p: &Plan) -> String {
let skipped = p.steps.iter().filter(|s| s.status == Status::Skipped).count();
if skipped > 0 {
format!("計畫完成:{} 步做完({skipped} 步略過)。", p.steps.len() - skipped)
} else {
format!("計畫完成:{} 步都做完了。", p.steps.len())
}
}
/// `submit_plan`'s arguments for the phone and a screen's card: the plan, and how it stands.
pub fn card_json(args: &str) -> Value {
match parse_draft(args) {
Ok(d) => json!({"summary": d.summary, "steps": d.steps.iter().map(|s| json!({"title": s.title, "detail": s.detail})).collect::<Vec<_>>(), "check": d.check, "notes": d.notes}),
Err(_) => Value::Null,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_command_reads_like_goal() {
assert_eq!(command("/plan"), Some(Command::Status));
assert_eq!(command(" /plan "), Some(Command::Status));
assert_eq!(command("/plan clear"), Some(Command::Clear));
assert_eq!(command("/plan 取消"), Some(Command::Clear));
assert_eq!(command("/plan STOP"), Some(Command::Clear));
assert_eq!(command("/plan 把部落格搬到新主機"), Some(Command::Start("把部落格搬到新主機".into())));
assert_eq!(command("/plan\n多行\n任務"), Some(Command::Start("多行\n任務".into())));
assert_eq!(command("/plans"), None);
assert_eq!(command("/planning 什麼"), None);
assert_eq!(command("先 /plan 一下"), None);
}
#[test]
fn a_plan_needs_a_summary_and_steps() {
assert!(parse_draft("nope").is_err());
assert!(parse_draft(r#"{"steps": [{"title": "a"}]}"#).unwrap_err().contains("summary"));
assert!(parse_draft(r#"{"summary": "s", "steps": []}"#).unwrap_err().contains("steps"));
assert!(parse_draft(r#"{"summary": "s", "steps": [{"title": " "}]}"#).unwrap_err().contains("steps"));
let many: Vec<Value> = (0..=MAX_STEPS).map(|i| json!({"title": format!("步驟 {i}")})).collect();
assert!(parse_draft(&json!({"summary": "s", "steps": many}).to_string()).unwrap_err().contains("太多"));
// Plain lines are steps too; long titles are cut to a line.
let d = parse_draft(&json!({"summary": " 搬家 ", "steps": ["備份", {"title": "x".repeat(400), "detail": "細節"}], "check": "打開網站"}).to_string()).unwrap();
assert_eq!(d.summary, "搬家");
assert_eq!(d.steps[0], DraftStep { title: "備份".into(), detail: String::new() });
assert_eq!(d.steps[1].title.chars().count(), MAX_TITLE_CHARS + 1);
assert_eq!(d.steps[1].detail, "細節");
assert_eq!(d.steps().iter().map(|s| s.status).collect::<Vec<_>>(), vec![Status::InProgress, Status::Pending]);
assert_eq!(d.check, "打開網站");
}
#[test]
fn the_card_answer_decides() {
assert_eq!(decide(&json!([APPROVE]).to_string()), Decision::Approve);
assert_eq!(decide(&json!([NOT_NOW]).to_string()), Decision::NotNow);
assert_eq!(decide(&json!([""]).to_string()), Decision::NotNow);
assert_eq!(decide(&json!(["第 3 步先備份資料庫"]).to_string()), Decision::Change("第 3 步先備份資料庫".into()));
// An answer that isn't a list (an older card) is read as the words themselves.
assert_eq!(decide(APPROVE), Decision::Approve);
let card = crate::ask::parse(&format!("{{\"questions\": {}}}", approval_card())).unwrap();
assert_eq!(card[0].question, QUESTION);
assert_eq!(card[0].options, vec![APPROVE.to_string(), NOT_NOW.to_string()]);
}
#[test]
fn the_card_reads_how_the_plan_stands_from_its_result() {
let steps = vec![Step { title: "a".into(), status: Status::InProgress }];
assert_eq!(outcome(None), Outcome::Waiting);
assert_eq!(outcome(Some(&approved_result(&steps))), Outcome::Approved);
assert_eq!(outcome(Some(NOT_NOW_RESULT)), Outcome::NotNow);
assert_eq!(outcome(Some(&change_result("改", 1))), Outcome::Changed);
assert_eq!(outcome(Some(WROTE_INSTEAD_RESULT)), Outcome::Changed);
assert_eq!(outcome(Some("submit_plan 需要 steps")), Outcome::Refused);
assert!(change_result("改", MANY_REVISIONS).contains("ask_person"));
}
#[test]
fn progress_keeps_one_step_in_progress() {
let steps = parse_progress(&json!({"steps": [{"title": "a", "status": "completed"}, {"title": "b", "status": "in_progress"}, {"title": "c", "status": "doing"}, {"title": "d"}]}).to_string()).unwrap();
assert_eq!(steps.iter().map(|s| s.status).collect::<Vec<_>>(), vec![Status::Done, Status::InProgress, Status::Pending, Status::Pending]);
assert!(parse_progress(r#"{"steps": [{"title": "a", "status": "maybe"}]}"#).unwrap_err().contains("maybe"));
assert!(parse_progress(r#"{"steps": []}"#).is_err());
let r = progress_result(&steps);
assert!(r.contains("1/4") && r.contains("接下來:b"), "{r}");
let all: Vec<Step> = steps.iter().map(|s| Step { status: Status::Done, ..s.clone() }).collect();
assert!(progress_result(&all).contains("全部完成"));
}
#[test]
fn where_it_stands_reads_in_one_line() {
let mut p = Plan::new("搬部落格", 1);
assert!(!p.finished());
assert!(bar_text(&p).starts_with("計畫模式"));
assert!(block(&p).contains("〔計畫模式〕") && block(&p).contains("搬部落格") && block(&p).contains(SUBMIT_TOOL));
p.stage = Stage::Doing;
p.steps = vec![Step { title: "備份".into(), status: Status::Done }, Step { title: "搬檔案".into(), status: Status::InProgress }, Step { title: "檢查".into(), status: Status::Pending }];
assert_eq!(bar_text(&p), "照計畫做 · 1/3 · 搬檔案");
assert!(block(&p).contains("〔照計畫做〕") && block(&p).contains("✓ 1. 備份\n▸ 2. 搬檔案\n○ 3. 檢查"));
assert!(status(Some(&p)).contains("1/3 步完成"));
assert!(status(None).contains("/plan"));
for s in p.steps.iter_mut() {
s.status = Status::Done;
}
p.steps[2].status = Status::Skipped;
assert!(p.finished());
assert_eq!(finished_note(&p), "計畫完成:2 步做完(1 步略過)。");
// Old state files (no plan fields yet) still read.
let old: Plan = serde_json::from_str(r#"{"task": "t", "since": 5}"#).unwrap();
assert_eq!((old.stage, old.steps.len(), old.revisions), (Stage::Drafting, 0, 0));
}
#[test]
fn the_tools_name_their_arguments() {
assert_eq!(submit_spec()["name"], SUBMIT_TOOL);
assert_eq!(update_spec()["name"], UPDATE_TOOL);
assert_eq!(submit_spec()["parameters"]["required"], json!(["summary", "steps"]));
assert_eq!(update_spec()["parameters"]["properties"]["steps"]["items"]["properties"]["status"]["enum"], json!(["pending", "in_progress", "done", "skipped"]));
assert!(card_json(r#"{"summary": "s", "steps": ["a"]}"#)["steps"][0]["title"] == "a");
assert!(card_json("{}").is_null());
}
}

View File

@ -43,7 +43,7 @@ pub fn ability_of(tool: &str) -> Option<&'static str> {
"create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" => "routines", "create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" => "routines",
"write_page" | "read_page" | "list_pages" => "pages", "write_page" | "read_page" | "list_pages" => "pages",
"message_bot" | "ask_bot" | "teach_skill" | "list_bots" => "team", "message_bot" | "ask_bot" | "teach_skill" | "list_bots" => "team",
"create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" => "admin", "create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" | crate::mcp::MANAGE_TOOL => "admin",
_ => return None, _ => return None,
}) })
} }

View File

@ -258,6 +258,8 @@ pub enum StreamEvent {
Issues(Vec<String>), Issues(Vec<String>),
/// 目標: the check after a turn has spoken (for the goal set at this time, ms). /// 目標: the check after a turn has spoken (for the goal set at this time, ms).
Goal(i64, crate::goal::Judged), Goal(i64, crate::goal::Judged),
/// 計畫: the plan was approved, dropped, sent back, or its steps moved on.
Plan(crate::plan::Event),
Done, Done,
Error(String), Error(String),
} }

View File

@ -416,6 +416,12 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap<u64, String>, pag
} }
if c.name == "show_card" { if c.name == "show_card" {
json!({"card": serde_json::from_str::<Value>(&c.args).unwrap_or(Value::Null), "status": st}) json!({"card": serde_json::from_str::<Value>(&c.args).unwrap_or(Value::Null), "status": st})
} else if c.name == crate::plan::SUBMIT_TOOL {
// 計畫: the plan's card (its state is added where the chat's results are known).
json!({"plan": crate::plan::card_json(&c.args), "status": st})
} else if c.name == crate::plan::UPDATE_TOOL {
// (The line above the input says where it is.)
json!({"plan_update": true, "status": st})
} else if matches!(c.name.as_str(), "ask_bot" | "message_bot") { } else if matches!(c.name.as_str(), "ask_bot" | "message_bot") {
// 同事之間: a conversation card (the answer joins it with the step's result). // 同事之間: a conversation card (the answer joins it with the step's result).
let a = crate::tools::args_of(&c.args); let a = crate::tools::args_of(&c.args);
@ -563,6 +569,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
o.insert("threads".into(), json!([])); o.insert("threads".into(), json!([]));
o.insert("queued".into(), json!([])); o.insert("queued".into(), json!([]));
o.remove("goal"); o.remove("goal");
o.remove("plan");
} }
c c
}) })
@ -727,10 +734,10 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
if text.is_empty() && attachments.is_empty() { if text.is_empty() && attachments.is_empty() {
return Resp::error(400, "訊息是空的"); return Resp::error(400, "訊息是空的");
} }
// 團隊: the bot knows who is talking when it isn't the owner (except `/goal` // 團隊: the bot knows who is talking when it isn't the owner (except `/goal` and
// commands from an admin, which AnyBot handles before the bot). // `/plan` commands from an admin, which AnyBot handles before the bot).
let who = req.header("x-anybot-user"); let who = req.header("x-anybot-user");
let is_admin_goal = role == "admin" && crate::goal::command(&text).is_some(); let is_admin_goal = role == "admin" && (crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some());
let text = if role != "owner" && !who.is_empty() && !is_admin_goal { format!("【{who}】{text}") } else { text }; let text = if role != "owner" && !who.is_empty() && !is_admin_goal { format!("【{who}】{text}") } else { text };
let member = role == "member"; let member = role == "member";
Cmd::Send { bot, text, attachments, from: String::new(), memories: if role == "owner" { picks_of(&b) } else { Some(vec![]) }, member } Cmd::Send { bot, text, attachments, from: String::new(), memories: if role == "owner" { picks_of(&b) } else { Some(vec![]) }, member }

View File

@ -1162,6 +1162,7 @@ fn seed_first() -> i32 {
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
goal: None, goal: None,
plan: None,
draft: String::new(), draft: String::new(),
regen_undo: vec![], regen_undo: vec![],
team: false, team: false,

View File

@ -41,7 +41,7 @@ pub fn export(b: &Bot) -> String {
let mut v = serde_json::to_value(b).unwrap_or(Value::Null); let mut v = serde_json::to_value(b).unwrap_or(Value::Null);
if let Value::Object(m) = &mut v { if let Value::Object(m) = &mut v {
// (Its 可以用的電腦 are this account's computers by name; its 草稿 is unsent words: neither travels.) // (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", "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"] {
m.remove(k); m.remove(k);
} }
if let Some(Value::Array(routines)) = m.get_mut("routines") { if let Some(Value::Array(routines)) = m.get_mut("routines") {
@ -81,7 +81,7 @@ pub fn import(text: &str, new_id: u64, next_routine: &mut u64, now: i64) -> Resu
m.insert("id".into(), Value::from(new_id)); m.insert("id".into(), Value::from(new_id));
m.insert("messages".into(), Value::Array(vec![])); m.insert("messages".into(), Value::Array(vec![]));
// Never import another person's grants, local workdir, threads or memories. // Never import another person's grants, local workdir, threads or memories.
for k in ["goal", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn"] { for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn"] {
m.remove(k); m.remove(k);
} }
} }

View File

@ -75,6 +75,8 @@ pub fn label(name: &str) -> &'static str {
match name { match name {
HANDOFF_TOOL => "請你接手電腦", HANDOFF_TOOL => "請你接手電腦",
crate::ask::TOOL => "問你", crate::ask::TOOL => "問你",
crate::plan::SUBMIT_TOOL => "交計畫給你核准",
crate::plan::UPDATE_TOOL => "更新計畫進度",
"list_dir" => "查看資料夾", "list_dir" => "查看資料夾",
"search_documents" => "翻你的文件", "search_documents" => "翻你的文件",
"search" => "搜尋檔案", "search" => "搜尋檔案",