diff --git a/FEATURES.md b/FEATURES.md index e709445..7af438f 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -750,6 +750,12 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **插話**:Bot 工作時你送出的訊息,會在下一步交給模型。模型本來要結束、但還有沒讀的插話時,回合會繼續,讓它看到你的新訊息。 - **喚醒**:例行任務時間到,或別的 Bot 傳訊息過來,都會像你傳訊息一樣開始新回合。Bot 正在忙時(例如你按了「立即執行」、別的 Bot 用 message_bot 交辦、觸發器觸發),喚醒會排隊,等它做完再開自己的一輪,訊息原樣保留(例行任務的新開始、哪個 Bot 傳的、轉了幾手、是不是外人傳的);以前會被壓成純文字插進正在跑的那一輪。 - **說了就做**:模型的回答沒有呼叫工具、最後一句卻是在說接下來要做什麼(以「:」結尾,或「我來/我先/我現在/我把…」「開始抓…」「Let me…」這類,而不是「好了/已經…」或「明天再…」),或在問「要我現在就開始/繼續嗎?」,回合不結束:AnyBot 告訴模型「什麼都還沒做」,下一步安靜地跑(文字不即時顯示)。它呼叫了工具或說了新的話才顯示;回「〔到此為止〕」(其實做完了,或接下來要使用者決定)就什麼都不加、回合照原樣結束;只是又說一次要做什麼也不顯示(聊天裡不會出現兩次同樣的宣告),再提醒或結束。連著兩次沒動手、或一輪滿 12 次就不再提醒。最後一句提到刪除、付款、寄出、發文、關機、斷線這類收不回來的事,一律不提醒、留給使用者(一律放行或直接操作開著時沒有卡片擋)。只看最後一句的規則,不叫模型判斷;猜錯只多一次模型呼叫,聊天不會多一則。起因:一個小模型三成的回合是「我把它整理成一頁」就停,使用者得一直打「繼續」。 +- **追進度(follow_up)**:Bot 啟動要等很久的事(下載、算圖、訓練、部署、別台機器上的工作)後,登記一個很快就跑完的檢查指令(du、tail log、curl 狀態、SSH 一行都可以)、done_when(輸出出現什麼算好了,/…/ 是正規表示式)、可選的 fail_when、then(好了要接著做什麼),就可以結束這一輪。 + - 大腦每 every_secs(15–3600,預設 60)秒在那台電腦上跑一次檢查,不叫模型;輸出有變、而且距離上一行超過 10 分鐘,聊天裡記一行「[追進度 #N]「…」還在進行(追了 M 分鐘):最後一行」。 + - 好了、出現 fail_when、輸出 15 分鐘(或十次檢查)沒變、超過 give_up_after_mins(預設 180,最多 1440)、或檢查指令連續 3 次失敗,就叫醒 Bot:「[追進度 #N]「…」好了/看起來失敗了/可能卡住了…」,附最後的輸出和 then,告訴它接著怎麼做。 + - 登記時,那個檢查指令照 shell 的規則決定要不要問使用者(問的話卡片寫明之後會每 N 秒自動執行),被安全規則擋的不登記;之後不再一次次問。list 看、stop 停;一個 Bot 同時最多 8 個。存在 Bot 身上,重開 AnyBot 照樣追;只有大腦跑,螢幕電腦不跑。 + - 系統指示要求:要等的事不要 sleep 卡在指令裡、也不要說「我去盯」就結束;「說了就做」的提醒也會叫它用 follow_up。起因:Bot 說「我去盯它跑」之後沒有人叫它回來,使用者只好一直問「好了沒」。 +- **主動回報**(系統指示):事情做到一個段落、或追進度叫它回來時,主動用一兩句話回報做到哪、接下來做什麼;發現問題先自己處理。 - **回合結束有三種**: - 成功:模型用文字回完;或用完步驟上限。 - 取消:你按停止。每一步和每個工具前後都會檢查;正在等你回答的請求一律當作拒絕;不顯示錯誤。 @@ -765,6 +771,10 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - Claude(支援的模型)送 `output_config.effort`;其他 OpenAI 相容的服務送 `reasoning_effort`。 - 模型不收這個設定(回 400)時,同一個請求會不帶設定再送一次,之後也不再對那個模型送。 - 只管 Bot 自己的模型;「執行步驟用的模型」和寫摘要不帶。 +- **滾動收起**:較早步驟還沒收起的長結果,加起來到可讀長度的 15%(128K 約 19,000 token)就一次全部收起,不必等到快滿;一批一次,模型的快取只斷一次。收起的那一步,它的長參數(例如一段三千字的 SSH 腳本)在送給模型時也只留每段開頭 240 字(還是同樣的 JSON 欄位)——實測一段對話裡指令參數佔了每個請求的三分之一。估長度時也照收起後的算。 +- **換模型**:換過去的第一輪先把較早的結果收起(完整的用 read_result 讀,不會不見),不一次送一大包;另一個模型留下的思考區塊(帶它的簽章)不會送給別的模型(會被拒絕),改用文字和工具呼叫重組;模型自己說的可讀長度記在「供應商/模型」底下,各記各的,換模型不會把別的模型的聊天壓太短。資料、記憶、聊天都不用因為換模型而調整。 +- **摘要分段寫、一定寫得出來**:要整理的一段太長時(超過 40,000 字),分段交給模型,每段併進目前為止的摘要;步驟結果只帶開頭 600 字。模型寫不出來(出錯、太慢)時,AnyBot 自己整理一份:更早的摘要、做過的每一步和成敗(最新 40 步)、最後的回答,下面照樣附使用者原話和還在跑的背景指令。 +- **第一個字等多久**:模型要先讀完整個請求才開始回答;送得多就等得久:120 秒起,超過 30,000 token 每多 1,000 多等 2 秒,最多 10 分鐘(視窗的看門狗再多給 30 秒)。等不到任何回應時不再原樣重送,先照「太長」的方法把對話收小(收起結果、寫摘要)再問一次;收到最小還是不行才報錯。以前固定 120 秒:一個在自己 GPU 上跑、讀 10 萬 token 的模型連續三輪都被切掉。 - **摘要用快速模型寫**:Bot 有「執行步驟用的模型」時,摘要交給它(整理不是思考,快很多也便宜);沒有就用 Bot 自己的模型。 - **可讀長度**:每個 Bot 可以設,預設 128,000 tokens(估計值)。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 9076c23..77fa7fa 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -14,8 +14,8 @@ - `chat-select` 選取一段文字(手機頁面,和用電腦的瀏覽器打開的網頁版):按住一則訊息(或回答下的 ⋯)打開訊息選單,「複製」是整則;「選取文字」把這則放進下方的面板,在那裡按住一個字開始選、拖兩端調整、再按系統的「拷貝」(電腦上拖曳後按 ⌘C 或 Ctrl+C),「完成」關掉。用電腦的瀏覽器時也能直接在聊天裡拖曳選取:在選好的字上按右鍵是瀏覽器自己的選單(「複製」),在別的地方按右鍵才是訊息選單;按住選好的字也不開選單;連結上按右鍵(Android 是長按)是瀏覽器的連結選單。 - `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」的閃光最多每秒畫 20 次;等你決定時黃點和輕彈還在,大約每秒 5 次。轉圈圖示也是。沒在動就不重畫;你不在(視窗不在前面或 90 秒沒動)頭像不眨眼。 - `chat-attach` 附件:「附加檔案」、拖進視窗、⌘V 貼圖。每個檔最多 50 MB,一個文字檔最多讀 20,000 字給模型。 -- `chat-compact` 長對話:用到「模型可讀長度」的 6 成,先收起舊步驟的長結果,不夠才把舊對話寫成摘要,聊天裡出現「較早的對話已整理成摘要」(「展開摘要」)。一個要求做很多步時,也先把這一輪較早的步驟寫成摘要(你的要求照原文留著),不等模型說太長。 -- `chat-stall` 卡住偵測:120 秒還沒開始回應,顯示「模型未能及時開始回應。請重試。」;開始後安靜 35 秒,顯示「回應中斷:模型超過 35 秒沒有送出任何內容。」。等你允許、工具在跑時不算。 +- `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度的 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫摘要,出現「較早的對話已整理成摘要」(「展開摘要」)。一個要求做很多步時也寫。摘要分段寫,模型寫不出來就由 AnyBot 整理。 +- `chat-stall` 卡住偵測:送得多的請求等得久(120 秒起,最多 10 分鐘),等不到第一個字先收小對話再問,還不行才顯示「模型未能及時開始回應」;開始後靜 35 秒是「回應中斷…」。等你允許、工具在跑時不算。 ## 使用者怎麼到 diff --git a/docs/feature-map/goal.md b/docs/feature-map/goal.md index 670ef7f..fabb5c8 100644 --- a/docs/feature-map/goal.md +++ b/docs/feature-map/goal.md @@ -10,6 +10,7 @@ - `goal-next` 下一輪:沒達成時,系統自己送出一則「[目標]還沒達成:理由」開始下一輪。 - `goal-brake` 煞車:做滿 20 輪先停下來問;連續 3 輪沒有用任何工具(只是在跟評審說話)就停;連續兩輪評審說差的是同一件事(字稍微不同也算)就停,看起來卡住了;Bot 在等使用者回答時停;評審沒有回應時停。使用者傳任何一句話就接著做(滿 20 輪的話再給 20 輪)。 - `goal-done` 達成或做不到:聊天裡留一行結果(花了幾輪),目標清掉。達成、做不到或停下來時,使用者不在電腦前(而且通知開著)會跳通知,手機也收得到。 +- `goal-followup` 追進度:Bot 啟動要等很久的事(下載、算圖、訓練、別台機器上的工作)後,登記一個看進度的指令和「看到什麼算好」就結束這一輪,不用你問「好了沒」。大腦定期在那台電腦上跑那個指令(不叫模型):有進展時聊天裡報一行「[追進度 #N]「…」還在進行…」(最多每 10 分鐘一行);好了、失敗、太久沒變化(約 15 分鐘)、超過時間(預設 3 小時)或指令一直失敗,就叫 Bot 回來接著做。登記時那個指令照 `shell` 的規則問你一次,之後不再一次次問。重開 AnyBot 照樣繼續追。 - `goal-restart` 重開:目標存在 Bot 身上,重開 AnyBot 還在;進行中的會先暫停(「AnyBot 重新啟動過」),等使用者一句話才繼續。 ## 使用者怎麼到 @@ -19,7 +20,7 @@ ## 怎麼操作(verify-anybot) -- Bot:沒有專用工具,照常做事就好。不要用說的宣稱完成,評審只認工具留下的結果;送出類的工作,系統會自己數送出幾次、記下送到哪裡。需要使用者回答就直接問,目標會停下來等。 +- Bot:要等很久的事用 `follow_up`(check、done_when、fail_when、then、every_secs、give_up_after_mins、computer;`list`、`stop`)登記後結束這一輪,不要 sleep 或說「我去盯」就停。目標本身沒有專用工具,照常做事就好。不要用說的宣稱完成,評審只認工具留下的結果;送出類的工作,系統會自己數送出幾次、記下送到哪裡。需要使用者回答就直接問,目標會停下來等。 前提: @@ -36,7 +37,8 @@ - **評審不能改、做不到**(covers `goal-judge`、`goal-done`):評審想寫檔,再判做不到。指令:`$CTL model-reply --clear && $CTL model-reply 你是驗收員 '[[call edit_file {"path":"judge.txt","old_text":"","new_text":"x"}]] {"verdict":"impossible","reason":"沒有這個網站"}' && $CTL phone send '/goal 登入一個不存在的網站' && $CTL phone wait-text '目標做不到,已清除' --in '#msgs' 60 && $CTL botfile --absent judge.txt && $CTL model 'select(.tool_result) | .tool_result'`。看到:「目標做不到,已清除:…」;沒有 judge.txt;評審拿到「檢查目標時不能用「edit_file」」。 - **桌面的圖示**(covers `goal-set`):電腦版臉那一行的圖示。指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot goal ANYBOT_SHOT_VIEW=goal ANYBOT_SHOT_GOAL=paused`(沒同意就靠自動測試)。看到:灰的目標圖示在臉的同一行右邊,不另外佔一行。 - **另一家評審、通知**(covers `goal-judge`、`goal-done`):指令:走不到——另一家供應商要真的金鑰,通知要帳號和真的手機。看到:最接近的真路是上面幾步:`$CTL model` 裡評審打到同一個假模型(都沒有才用自己的)。 -- 自動測試:`cargo test goal::`(滿 20 輪、連續 3 輪沒動手、等你回覆、評審沒回應、重開時暫停)、`cargo test evidence::`、`cargo test the_judge_looks_for_itself`。 +- **追進度**(covers `goal-followup`):Bot 登記一個馬上就好的檢查。指令:`$CTL phone send '追進度測試 [[call follow_up {"what":"驗證下載","check":"echo DL_DONE","done_when":"DL_DONE","every_secs":15}]]' && $CTL wait-api /api/bots/1 '[.messages[] | select(.text | test("追進度 #[0-9]+]「驗證下載」好了"))] | length >= 1' 60 && $CTL state '.bots[0].follow_ups // [] | length'`。看到:「已登記追進度 #N…」之後,不用再傳話,Bot 被「[追進度 #N]「驗證下載」好了…」叫回來回答;`follow_ups` 是 0(追完就拿掉)。 +- 自動測試:`cargo test followup`、`cargo test goal::`(滿 20 輪、連續 3 輪沒動手、等你回覆、評審沒回應、重開時暫停)、`cargo test evidence::`、`cargo test the_judge_looks_for_itself`。 ## 陷阱 diff --git a/docs/feature-map/models.md b/docs/feature-map/models.md index d2b47be..6bc4ffa 100644 --- a/docs/feature-map/models.md +++ b/docs/feature-map/models.md @@ -5,6 +5,7 @@ ## 子功能 - `models-providers` 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama(本機)、自訂(OpenAI 相容),每個 Bot 各選各的。 +- `models-switch` 換模型:資料、記憶、聊天都不用動。換過去的第一個請求先把舊步驟的結果收起(要用再讀),不一次送一大包;另一個模型的思考內容不會送過去(它會拒絕);模型說過的可讀長度各記各的,不會把別的模型的聊天壓得太短。 - `models-bot` 「AI 供應商與模型」(Bot 設定裡):供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」——欄位名稱在上,說明在名稱旁的「?」。 - `models-thinking` 思考模式:「自動(模型自己決定)」「快速(想得少,回得快)」「平衡」「深入(想得久,較慢)」。執行步驟用的模型:「自動」、「不分開(每一步都用上面的模型)」或指定一個;上面的模型負責想計畫、遇到問題和最後確認,中間的步驟交給快的模型。 - `models-chatgpt` 「ChatGPT 方案」:用 ChatGPT 帳號登入(OpenAI 的 Sign in with ChatGPT),用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰。第一次登入時 AnyBot 向 OpenAI 註冊自己,之後重用;登入後 設定 › 模型 寫「已用 ChatGPT 登入(信箱)」,第一次回答會說一次「你正在使用你的 ChatGPT 方案」。 @@ -25,12 +26,12 @@ - **設定 › 模型**(covers `models-providers`、`models-chatgpt`):帳戶選單 › 設定 › 模型,點「ChatGPT 方案」。指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="models"]' && $CTL phone wait-text 'OpenCode Go' --in '#list' && $CTL phone shot models-list && $CTL phone click '[data-prov]' --text 'ChatGPT 方案' && $CTL phone wait-text '使用 ChatGPT 繼續' --in '#sheet-in' && $CTL api POST /api/act/chatgpt '{"action":"status"}' --jq .status`。看到:九家,xAI 到 OpenCode Go「未設定」,Ollama(本機)、自訂「可以用」;ChatGPT 方案的選單有「使用 ChatGPT 繼續…」(不按:會連 OpenAI);大腦說「還沒有用 ChatGPT 登入。」 - **換到沒金鑰的供應商**(covers `models-bot`、`models-providers`):請 Bot 只換供應商成 xAI,允許,再傳一句。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '換 [[call update_my_profile {"provider":"xai"}]]' && $CTL phone wait-text 'xAI Grok' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0].via == "xAI Grok · grok-4"' && $CTL phone send '你好' && $CTL phone wait-text '還沒有設定 xAI Grok 的 API 金鑰' --in '#msgs' && $CTL phone shot models-nokey`。看到:卡片「AI 供應商:自訂(OpenAI 相容) → xAI Grok」;模型自動換成 xAI 的建議模型 grok-4;下一則出錯「還沒有設定 xAI Grok 的 API 金鑰。請到「設定 → 模型」貼上金鑰。」(沒有連出去)。 -- **從手機換回來**(covers `models-bot`):標題 › 模型,選 fake-model。指令:`$CTL phone click '#island' && $CTL phone click '[data-d="model"]' && $CTL phone wait-text '其他模型' --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text fake-model && $CTL wait-api '/api/state?since=0' '.bots[0].via == "自訂(OpenAI 相容) · fake-model"' && $CTL phone click '[data-back]' && $CTL phone send '回來了嗎' && $CTL phone wait-text 'FAKE-MODEL 回答:回來了嗎' --in '#msgs'`。看到:選單只列可以用的(Ollama(本機)、自訂(OpenAI 相容))和「其他模型…」;換回後又能回話。 +- **從手機換回來**(covers `models-bot`、`models-switch`):標題 › 模型,選 fake-model。指令:`$CTL phone click '#island' && $CTL phone click '[data-d="model"]' && $CTL phone wait-text '其他模型' --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text fake-model && $CTL wait-api '/api/state?since=0' '.bots[0].via == "自訂(OpenAI 相容) · fake-model"' && $CTL phone click '[data-back]' && $CTL phone send '回來了嗎' && $CTL phone wait-text 'FAKE-MODEL 回答:回來了嗎' --in '#msgs'`。看到:選單只列可以用的(Ollama(本機)、自訂(OpenAI 相容))和「其他模型…」;換回後又能回話。 - **思考模式、執行步驟用的模型**(covers `models-thinking`):指令:`$CTL phone send '想深一點 [[call update_my_profile {"thinking":"high","step_model":"off"}]]' && $CTL phone wait-text '思考模式' --in '#ask' && $CTL phone wait-text '執行步驟用的模型:自動 → 不分開' --in '#ask' && $CTL phone shot models-thinking && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api '/api/state?since=0' '.bots[0] | .thinking == "high" and .step_model == "off"' && $CTL phone send '再說一次' && $CTL phone wait-text 'FAKE-MODEL 回答:再說一次' --in '#msgs'`。看到:卡片列出「思考模式:自動(模型自己決定) → 深入(想得久,較慢)」和「執行步驟用的模型:自動 → 不分開」(設定畫面上的說法);允許後大腦記著 high、off,照常回話。 - **ChatGPT 登出要先問**(covers `models-chatgpt`):請 Bot 登出,按拒絕;再看狀態。指令:`$CTL phone send '登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '登出 ChatGPT' --in '#ask' && $CTL phone wait-text '驗證小幫手 想要登出 ChatGPT 方案' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '狀態 [[call chatgpt_login {"action":"status"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "chatgpt_login" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "chatgpt_login") | {status, result}]'`。看到:登出先跳卡片「驗證小幫手 想要登出 ChatGPT 方案」(「登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答…」),拒絕後 denied;status 不用問,「還沒有用 ChatGPT 登入。」 - **用 ChatGPT 登入**(covers `models-chatgpt`):指令:走不到——登入會向 OpenAI 註冊、要真的 ChatGPT 帳號和方案(貼回網址、螢幕電腦的「完成登入」、額度用完都一樣)。看到:最接近的真路是上一步的 status 和 `cargo test chatgpt::`(註冊一次後重用、貼回網址、沒勾同意、額度用完)。 - **桌面**(covers `models-bot`、`models-providers`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot models ANYBOT_SHOT_TAB=providers`。看到:設定 › 模型 每家的金鑰欄和「使用 ChatGPT 繼續」;輸入框 + 的模型子選單(「(未設定金鑰)」)、Bot 設定的紅字「前往設定」靠自動測試。 -- 自動測試:`cargo test chatgpt::`、`cargo test providers::`、`cargo test profile::`、`cargo test remote::tests::only_the_owner_signs_the_brain_in_to_chatgpt`。 +- 自動測試:`cargo test chatgpt::`、`cargo test providers::`(含 `calls_of_set_aside_steps_go_shortened`)、`cargo test a_switched_model_starts_from_a_lean_request`、`cargo test profile::`、`cargo test remote::tests::only_the_owner_signs_the_brain_in_to_chatgpt`。 ## 陷阱 diff --git a/src/agent.rs b/src/agent.rs index c0c881a..79a41b5 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1011,7 +1011,10 @@ pub fn history_tokens(system: &str, h: &[Message]) -> u64 { } m.images.iter().map(|p| image_tokens(p)).sum() }; - estimate_tokens(system) + h.iter().enumerate().map(|(i, m)| estimate_tokens(&m.text) + m.tool_calls.iter().map(|c| estimate_tokens(&c.args)).sum::() + pictures(i, m) + 4).sum::() + // A call whose result was set aside goes shortened (providers::fold_called_args). + let folded: std::collections::HashSet<&str> = h.iter().filter(|m| m.role == Role::Tool && m.folded).map(|m| m.tool_call_id.as_str()).collect(); + let args = |c: &crate::model::ToolCall| if folded.contains(c.id.as_str()) { estimate_tokens(&c.args).min(FOLDED_ARGS_TOKENS) } else { estimate_tokens(&c.args) }; + estimate_tokens(system) + h.iter().enumerate().map(|(i, m)| estimate_tokens(&m.text) + m.tool_calls.iter().map(&args).sum::() + pictures(i, m) + 4).sum::() } /// What a picture costs the model that receives it. Vision providers price by pixels (a @@ -1065,6 +1068,18 @@ fn flatten(h: &[Message]) -> String { /// A step's result longer than this may be set aside once it is old (estimated). const FOLD_MIN_CHARS: usize = 600; +/// Old results not yet set aside are set aside together once they are this share of the +/// context (estimated): about 19 000 tokens of a 128 000 one. +const FOLD_BATCH_PERCENT: u64 = 15; + +/// About what a set-aside call's shortened arguments take (estimated). +const FOLDED_ARGS_TOKENS: u64 = 200; + +/// What the old results that fold_results would set aside take now (tokens, estimated). +fn old_results_tokens(history: &[Message]) -> u64 { + let keep_from = history.len().saturating_sub(KEEP_RECENT_MESSAGES); + history[..keep_from].iter().filter(|m| m.role == Role::Tool && !m.folded && !m.summary && m.text.chars().count() > FOLD_MIN_CHARS).map(|m| estimate_tokens(&m.text)).sum() +} /// What stays of a result that was set aside: its first words. const FOLD_HEAD_CHARS: usize = 200; @@ -1126,30 +1141,131 @@ thread_local! { /// second try when it came back too short, then the person's own words as they wrote them and /// the background commands still running (both from AnyBot, not the model: they can't be lost). pub fn summarize(base: &ChatRequest, quick: Option<&str>, part: &[Message], cancel: &AtomicBool, quiet: &dyn Fn(StreamEvent)) -> Option { - let flat = flatten(part); - let ask = |extra: &str| { + let ask = |input: &str, extra: &str| { let req = ChatRequest { system: SUMMARY_SYSTEM.into(), - history: vec![Message::user(&format!("請整理下面這段對話:{extra}\n\n{flat}"))], + history: vec![Message::user(&format!("請整理下面這段對話:{extra}\n\n{input}"))], tools: vec![], model: quick.map(String::from).unwrap_or_else(|| base.model.clone()), effort: String::new(), ..base.clone() }; - providers::run_step(&req, cancel, quiet).ok().map(|o| o.text.trim().to_string()) + providers::run_step(&req, cancel, quiet).ok().map(|o| o.text.trim().to_string()).filter(|t| !t.is_empty()) }; - let mut text = ask("")?; - if text.chars().count() < SUMMARY_MIN_CHARS && flat.chars().count() > SUMMARY_MIN_CHARS * 10 && !cancel.load(Ordering::Relaxed) { - if let Some(again) = ask("(上一次整理得太短,請照段落寫完整)").filter(|t| t.chars().count() > text.chars().count()) { - text = again; + // A long stretch goes in pieces the model can read, each folded into the summary so far: in + // one piece it was more than the model could read, the summary failed, and the chat stayed as + // long as it was. + let pieces = summary_pieces(part, SUMMARY_PIECE_CHARS); + let mut text: Option = None; + let mut failed = false; + for piece in &pieces { + if cancel.load(Ordering::Relaxed) { + return None; + } + let got = match &text { + None => ask(piece, ""), + Some(so_far) => ask(&format!("【到目前為止的摘要】\n{so_far}\n\n【接下來的對話】\n{piece}"), "(把接下來的對話併進到目前為止的摘要,照同樣的段落寫一份完整的)"), + }; + match got { + Some(t) => text = Some(t), + None => { + failed = true; + break; + } } } - if text.is_empty() || cancel.load(Ordering::Relaxed) { + if let (Some(t), [only]) = (&text, pieces.as_slice()) { + if !failed && t.chars().count() < SUMMARY_MIN_CHARS && only.chars().count() > SUMMARY_MIN_CHARS * 10 && !cancel.load(Ordering::Relaxed) { + if let Some(again) = ask(only, "(上一次整理得太短,請照段落寫完整)").filter(|a| a.chars().count() > t.chars().count()) { + text = Some(again); + } + } + } + if cancel.load(Ordering::Relaxed) { return None; } + // The model couldn't write it (an error, too slow): AnyBot writes one itself from what it + // knows — the steps and the last answer — so making room never fails for want of a summary. + let text = match (text, failed) { + (Some(t), false) => t, + (Some(t), true) => format!("{t}\n\n{}", local_summary(part)), + (None, _) => local_summary(part), + }; Some(with_what_must_stay(&text, part, TURN_BOT.with(|b| b.get()))) } +/// Characters of conversation one summary request carries at most: what a 32 000-token model +/// reads with room left to write. +const SUMMARY_PIECE_CHARS: usize = 40_000; +/// A step's result in a summary request: its first words only (the steps themselves say most). +const SUMMARY_RESULT_CHARS: usize = 600; + +/// The stretch flattened (as flatten does, results shorter) and packed into pieces of at most +/// `max` characters, in order. +fn summary_pieces(part: &[Message], max: usize) -> Vec { + let mut pieces: Vec = vec![]; + let mut cur = String::new(); + for m in part { + let line = match m.role { + Role::Tool if !m.summary => { + let r: String = m.text.chars().take(SUMMARY_RESULT_CHARS).collect(); + format!("工具結果({}):{r}{}", m.tool_name, if m.text.chars().count() > SUMMARY_RESULT_CHARS { "…" } else { "" }) + } + _ => flatten(std::slice::from_ref(m)), + }; + let line: String = line.chars().take(max).collect(); + if !cur.is_empty() && cur.chars().count() + line.chars().count() + 2 > max { + pieces.push(std::mem::take(&mut cur)); + } + if !cur.is_empty() { + cur.push_str("\n\n"); + } + cur.push_str(&line); + } + if !cur.is_empty() { + pieces.push(cur); + } + pieces +} + +/// A summary AnyBot writes without a model: the earlier summaries, the steps (newest +/// LOCAL_SUMMARY_STEPS) with how each went, and the last answer. +fn local_summary(part: &[Message]) -> String { + let mut out = String::from("(這份摘要由 AnyBot 自己整理:模型這次沒寫出摘要。較早步驟的完整結果可以用 read_result 讀。)"); + for m in part.iter().filter(|m| m.summary) { + out.push_str(&format!("\n\n## 更早的摘要\n{}", m.text.chars().take(4_000).collect::())); + } + let steps: Vec = part + .iter() + .flat_map(|m| m.tool_calls.iter()) + .map(|c| { + let how = match c.status { + ToolStatus::Done => "完成", + ToolStatus::Failed => "失敗", + ToolStatus::Denied => "被拒絕或停止", + _ => "沒有結果", + }; + format!("- {}({how})", tools::describe(&c.name, &c.args).chars().take(160).collect::()) + }) + .collect(); + if !steps.is_empty() { + out.push_str("\n\n## 做過的事和結果"); + if steps.len() > LOCAL_SUMMARY_STEPS { + out.push_str(&format!("\n- (更早的 {} 步省略)", steps.len() - LOCAL_SUMMARY_STEPS)); + } + for s in &steps[steps.len().saturating_sub(LOCAL_SUMMARY_STEPS)..] { + out.push_str(&format!("\n{s}")); + } + } + if let Some(last) = part.iter().rev().find(|m| m.role == Role::Assistant && !m.summary && !m.text.trim().is_empty()) { + out.push_str(&format!("\n\n## 最後的回答\n{}", last.text.trim().chars().take(1_500).collect::())); + } + out +} + +/// Steps a summary written without a model lists at most (the newest). +const LOCAL_SUMMARY_STEPS: usize = 40; + /// The bot whose summaries this thread writes (its background commands are named under them). pub fn set_turn_bot(bot: u64) { TURN_BOT.with(|b| b.set(bot)); @@ -1182,6 +1298,17 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A // (The tools' descriptions go with every request too: ~12 000 tokens for a bot with all.) let tools = tools_tokens(&job.req.tools); let used = history_tokens(&job.req.system, history) + tools; + // Rolling: old long results the model has used are set aside in one batch once they add up + // to FOLD_BATCH_PERCENT of what it reads — each was sent again with every step since, not + // only when the chat is near full. (A batch at a time: the cache breaks once, not every step.) + if percent > 0 && old_results_tokens(history) * 100 >= job.context_tokens * FOLD_BATCH_PERCENT { + let set_aside = fold_results(history); + if !set_aside.is_empty() { + log::info!("AnyBot:較早的步驟結果累積太多,收起 {} 個", set_aside.len()); + send(StreamEvent::Folded(set_aside)); + } + } + let used = if percent > 0 { history_tokens(&job.req.system, history) + tools } else { used }; if used * 100 < job.context_tokens * percent { return None; } @@ -1223,6 +1350,26 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A Some(cut) } +/// What each bot's current request may take to its first word (seconds), for the window's +/// watchdog: it gives a long request as long as the request itself does, plus a margin. +fn first_waits() -> &'static Mutex> { + static W: std::sync::OnceLock>> = std::sync::OnceLock::new(); + W.get_or_init(Default::default) +} + +fn set_first_wait_of(bot: u64, secs: u64) { + first_waits().lock().unwrap_or_else(|e| e.into_inner()).insert(bot, secs); +} + +/// The window's first-response deadline for `bot`'s turn: its request's own first wait and a +/// margin (the turn itself gives up first and makes room; this only catches what hangs). +pub fn first_wait_secs(bot: u64) -> u64 { + first_waits().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).copied().unwrap_or(providers::FIRST_RESPONSE_TIMEOUT_SECS).max(providers::FIRST_RESPONSE_TIMEOUT_SECS) + FIRST_WAIT_MARGIN_SECS +} + +/// How much longer the window waits than the turn does. +const FIRST_WAIT_MARGIN_SECS: u64 = 30; + /// Longest browser_wait after_send (a spacing of up to a quarter of an hour). const AFTER_SEND_MAX_SECS: f64 = 900.0; @@ -2072,6 +2219,18 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // Making room because the model said it was too long: each way once per thing the person // said (see make_room), and which one this step's retry rides on. let mut room = Room::default(); + // 換模型: the model the bot was switched to has never read this chat (nothing of it is in + // its cache either). Old results are set aside first — whole for read_result, nothing + // lost — so its first request isn't everything at once. + let last_answer = history.iter().rev().find(|m| m.role == Role::Assistant && !m.summary && !m.via.is_empty()); + let same = |m: &Message| providers::written_by(m, &job.req.model) || job.step_model.as_deref().is_some_and(|q| providers::written_by(m, q)); + if last_answer.is_some_and(|m| !same(m)) { + let ids = fold_results(&mut history); + if !ids.is_empty() { + log::info!("AnyBot:換了模型({}),先收起 {} 個較早的步驟結果", job.req.model, ids.len()); + send(StreamEvent::Folded(ids)); + } + } maybe_compact(&job, &mut history, COMPACT_THRESHOLD_PERCENT, &cancel, &send); let mut plan = StepPlan::new(job.step_model.clone()); // A quick step's answer was set aside: its (empty) message in the chat is reused. @@ -2196,6 +2355,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } attempt += 1; job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "assistant".into(), attempt }); + // How long this request may take to its first word: longer the more it carries + // (the window's watchdog reads the same, see first_wait_secs). + let wait = providers::first_wait_for(history_tokens(&job.req.system, &history) + tools_tokens(&job.req.tools)); + providers::set_first_wait(wait); + set_first_wait_of(bot_id, wait); let main_req = ChatRequest { history: history.clone(), ..job.req.clone() }; let quick_now = if plan.quick_is_off() { None } else { quick.clone() }; let got = match quick_now { @@ -2225,6 +2389,17 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // Too long for the model: that answer is thrown away, room is made — the // pictures, then old results, then a summary — and the same step is asked // again, however full the chat looks by our estimate. + // Too long for this model to even start in time: made smaller the same ways as a + // request that was too long, then asked once more — not the same request again. + Err(e) if providers::is_slow_start(&e) && !cancel.load(Ordering::Relaxed) => { + log::warn!("AnyBot:{e}(約 {} token),先把對話收小再問一次", history_tokens(&job.req.system, &history)); + if make_room(&job, &mut history, &mut room, &cancel, &send).is_none() { + closing.close(crate::oplog::Outcome::Failed); + send(StreamEvent::Error(format!("{e}\n對話已經收到最小了還是太慢:換一個快一點的模型,或用 /compact 之後再試。"))); + return; + } + send(StreamEvent::Nudged("對話太長、模型遲遲沒開始回答,先收小再問一次…".into())); + } Err(e) if providers::is_context_overflow(&e) && !cancel.load(Ordering::Relaxed) => { // The size it named is the bot's from now on (summarized in time next). if let Some(limit) = providers::overflow_limit(&e).filter(|l| *l < job.context_tokens) { @@ -5578,7 +5753,7 @@ echo 'done送出了' > done.html; (setsid pyt let mut history = vec![Message::user("把十件事做完")]; for i in 0..10 { let call = ToolCall { id: format!("c{i}"), name: "shell".into(), args: serde_json::json!({"command": format!("echo step-{i}")}).to_string(), status: ToolStatus::Done }; - history.push(Message { tool_calls: vec![call], ..Message::assistant("", "test") }); + history.push(Message { tool_calls: vec![call], ..Message::assistant("", "測試 · m") }); history.push(Message::tool_result(&format!("c{i}"), "shell", &format!("結果 {i}:{}", "很長的輸出 ".repeat(200)))); } let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() }, ..test_job() }; @@ -5669,6 +5844,80 @@ echo 'done送出了' > done.html; (setsid pyt } } + /// 換模型: the first request to a model the bot was switched to goes lean — the old results + /// it never read are set aside first (whole for read_result) — and nothing of it is lost. + #[test] + fn a_switched_model_starts_from_a_lean_request() { + let (port, seen) = fake_http(vec![sse_text("接著做")]); + let mut history = vec![Message::user("查很多檔案")]; + for i in 0..8 { + let call = ToolCall { id: format!("c{i}"), name: "read_file".into(), args: "{}".into(), status: ToolStatus::Done }; + history.push(Message { tool_calls: vec![call], ..Message::assistant("", "自訂 · old-model") }); + history.push(Message::tool_result(&format!("c{i}"), "read_file", &format!("檔案 {i}:{}", "內容".repeat(800)))); + } + history.push(Message::user("換你接著做")); + let req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "new-model".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() }; + let (evs, _) = drive(Job { req, ..test_job() }, ApprovalAnswer::Reject); + assert!(evs.iter().any(|e| matches!(e, StreamEvent::Folded(ids) if !ids.is_empty()))); + let sent = seen.lock().unwrap()[0].clone(); + assert!(sent.contains("較早的結果已收起") && sent.contains("檔案 7"), "old ones short, the newest whole"); + } + + /// A long stretch goes to the summarizer in pieces it can read, each under the limit, all of + /// it in order. + #[test] + fn a_long_stretch_is_summarized_in_pieces() { + let mut part = vec![Message::user("開始")]; + for k in 0..120 { + part.push(Message::assistant(&format!("第 {k} 步:{}", "說明".repeat(200)), "x")); + part.push(Message::tool_result(&format!("c{k}"), "shell", &"輸出".repeat(2_000))); + } + let pieces = summary_pieces(&part, SUMMARY_PIECE_CHARS); + assert!(pieces.len() >= 2, "{}", pieces.len()); + assert!(pieces.iter().all(|p| p.chars().count() <= SUMMARY_PIECE_CHARS)); + assert!(pieces[0].starts_with("使用者:開始") && pieces.last().unwrap().contains("第 119 步")); + } + + /// The model can't write the summary (it refuses): AnyBot writes one itself — making room + /// doesn't fail — and the person's own words are still there word for word. + #[test] + fn a_summary_the_model_cant_write_is_written_here() { + let (port, _) = fake_http(vec![(400, r#"{"error":{"message":"bad request"}}"#.into())]); + let req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![], tools: vec![], session: String::new(), effort: String::new() }; + let part = vec![ + Message::user("把模型抓下來"), + Message { tool_calls: vec![crate::model::ToolCall { id: "c1".into(), name: "shell".into(), args: r#"{"command":"hf download qwen"}"#.into(), status: ToolStatus::Done }], ..Message::assistant("開始抓", "x") }, + Message::tool_result("c1", "shell", "ok"), + Message::assistant("抓好了,14G 到位。", "x"), + ]; + let out = summarize(&req, None, &part, &AtomicBool::new(false), &|_| {}).expect("a summary all the same"); + assert!(out.contains("AnyBot 自己整理") && out.contains("完成") && out.contains("抓好了,14G 到位"), "{out}"); + assert!(out.contains("「把模型抓下來」"), "the person's words stay: {out}"); + } + + /// Rolling fold: old long results the model already used are set aside in one batch once + /// they add up to FOLD_BATCH_PERCENT of the context — well before the chat is near full. + #[test] + fn old_results_are_set_aside_before_the_chat_is_full() { + let mut h = vec![Message::user("查很多東西")]; + for k in 0..12 { + h.push(Message { tool_calls: vec![crate::model::ToolCall { id: format!("c{k}"), name: "read_file".into(), args: "{}".into(), status: ToolStatus::Done }], ..Message::assistant("", "x") }); + h.push(Message::tool_result(&format!("c{k}"), "read_file", &"資料".repeat(1_200))); + } + let job = Job { context_tokens: 128_000, ..test_job() }; + let before = history_tokens("", &h); + assert!(before * 100 < 128_000 * COMPACT_THRESHOLD_PERCENT, "well under the threshold: {before}"); + let got = std::sync::Mutex::new(vec![]); + maybe_compact(&job, &mut h, COMPACT_THRESHOLD_PERCENT, &AtomicBool::new(false), &|e| { + if let StreamEvent::Folded(ids) = e { + got.lock().unwrap().extend(ids); + } + }); + let folded = got.lock().unwrap().len(); + assert!(folded >= 8, "the old ones went in one batch: {folded}"); + assert!(history_tokens("", &h) * 3 < before, "much less is sent from now on"); + } + /// 說了就做 (chat-followthrough): an answer that says what it will do and calls nothing /// doesn't end the turn — the model is told, its quiet next step acts, and the turn goes on /// to the end without the person saying 「繼續」. diff --git a/src/agent/followthrough.rs b/src/agent/followthrough.rs index 63b99c8..2f1fd03 100644 --- a/src/agent/followthrough.rs +++ b/src/agent/followthrough.rs @@ -100,7 +100,7 @@ pub fn nudge(short: Short) -> String { Short::AskedToGoOn => "【AnyBot:你剛才在問使用者要不要接著做。這是他交代的事,照規則做完,不要中途停下來問。】", }; format!( - "{why}\n現在就呼叫工具把它做下去,不要再說一次要做什麼,也不要重複前面說過的話。\n只有兩種情況不做:其實已經做完了;或接下來是收不回來的事(刪除、付款、寄出、會斷線)或他沒交代過的新事情,真的要他先決定——這時只回「{DONE_MARK}」這幾個字,別的什麼都不寫。" + "{why}\n現在就呼叫工具把它做下去,不要再說一次要做什麼,也不要重複前面說過的話。要等的事(下載、算圖、別台機器上的工作)用 follow_up 登記怎麼看進度和看到什麼算好,再結束這一輪。\n只有兩種情況不做:其實已經做完了;或接下來是收不回來的事(刪除、付款、寄出、會斷線)或他沒交代過的新事情,真的要他先決定——這時只回「{DONE_MARK}」這幾個字,別的什麼都不寫。" ) } diff --git a/src/app.rs b/src/app.rs index 98d4d89..7c727f1 100644 --- a/src/app.rs +++ b/src/app.rs @@ -54,6 +54,7 @@ mod asks; /// A server's brain was told to stop (see App::serve). static STOPPING: AtomicBool = AtomicBool::new(false); mod branch; +mod followup_ui; mod talk_ui; mod group; #[cfg(test)] @@ -1954,7 +1955,7 @@ impl App { } g }, - context_tokens: b.context_tokens.max(4_000), + context_tokens: b.reads(), via, via_name: b.name.clone(), steer, @@ -3146,6 +3147,16 @@ impl App { continue; } } + } else if call.name == crate::followup::TOOL { + // 追進度: its check runs again and again without asking — asked like that + // command with shell, once (a refused one isn't registered). + match self.followup_ask(id, &call.args) { + Ok(ask) => ask, + Err(e) => { + let _ = call.reply.send((e, false)); + continue; + } + } } else if call.name == crate::hooks::MANAGE_TOOL { // Hooks: run outside the sandbox as the person — every change shown and asked. match crate::hooks::parse_change(&call.args) { @@ -3202,8 +3213,10 @@ impl App { } } // The model said how much it reads: this bot summarizes in time from now on. + // (For this model only: another one the bot switches to reads what it reads.) StreamEvent::ContextLimit(n) => { - b.context_tokens = n; + let key = b.limit_key(); + b.model_limits.insert(key, n); self.dirty = true; } // Pictures taken out to make room: not sent again next turn (they stayed in @@ -3281,7 +3294,6 @@ impl App { /// approval timeout on unattended routine/trigger wakes so one unanswered prompt never /// freezes all future schedules and channels. fn watchdog(&mut self) { - let first = std::time::Duration::from_secs(providers::FIRST_RESPONSE_TIMEOUT_SECS); let idle = std::time::Duration::from_millis(providers::STREAM_IDLE_STALL_MS); let unattended_approval = std::time::Duration::from_secs(15 * 60); let approvals_open: std::collections::HashSet = self.approvals.keys().copied().collect(); @@ -3297,7 +3309,8 @@ impl App { } else { None } - } else if !l.produced && l.started.elapsed() > first { + // (As long as this request itself may take to its first word: a long one longer.) + } else if !l.produced && l.started.elapsed() > std::time::Duration::from_secs(crate::agent::first_wait_secs(*id)) { Some((*id, "模型未能及時開始回應。請重試。".into())) } else if l.produced && l.last.elapsed() > idle { Some((*id, "回應中斷:模型超過 35 秒沒有送出任何內容。".into())) @@ -3605,6 +3618,8 @@ impl App { members: vec![], threads: Default::default(), context_tokens: agent::DEFAULT_CONTEXT_TOKENS, + model_limits: Default::default(), + follow_ups: vec![], routines: vec![], last_turn: None, goal: None, @@ -6440,6 +6455,7 @@ impl App { self.meetings_poll(ctx); self.tick_routines(ctx); self.monitor_tick(ctx); + self.followup_tick(ctx); self.tick_asks(ctx); self.tick_branches(ctx); self.watchdog(); @@ -7537,6 +7553,11 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu ways.push("- 沒見過的 App 或畫面也一樣:先看清楚(截圖、需要就放大),找選單、設定、按鈕上的字,照編號點;網頁上的東西用 browser 的編號。".into()); } ways.push("- 使用者交代的事就做完:不要做到一半停下來問「要我繼續嗎」「要我現在做嗎」,畫面不如預期就自己處理(關掉擋路的視窗、打開要用的 App)再接著做。只有需要使用者親手做、或要先確認會切斷連線、刪除、付款這類事情時才停下來問。".into()); + // 追進度 (followup.rs): long things are followed by AnyBot, not by a sleep or a promise. + if b.tools_enabled { + ways.push("- 要等很久的事(下載、算圖、訓練、部署、別台機器上跑的工作):不要用 sleep 卡在指令裡等,也不要說「我去盯」「好了再跟你說」就結束——那樣沒有人會叫你回來。啟動之後用 follow_up 登記一個很快就跑完的檢查指令(看進度的,例如 du、tail log、curl 狀態、SSH 一行)和 done_when(看到什麼算好了),寫上 then(好了要接著做什麼),用一兩句話告訴使用者你在追什麼,然後結束這一輪;AnyBot 會在背景幫你看,好了、失敗、卡住或超時都會叫你回來接著做完。".into()); + ways.push("- 主動一點:使用者交代的事情做到一個段落、或追進度叫你回來時,主動用一兩句話回報做到哪、接下來做什麼;發現問題先自己處理,處理完再說,不要等使用者來問「好了沒」。".into()); + } if screen { ways.push("- 系統跳出的權限或安全詢問(「允許…存取」「要允許…嗎」、輸入密碼、Touch ID)不要替使用者按:告訴他是什麼、請他自己決定(需要時用 hand_over_computer)。".into()); ways.push("- 按快捷鍵(cmd+w、cmd+q、cmd+s…)前先確定最前面的是你要操作的 App;關掉一個視窗以後,最前面的可能已經換成別的 App。".into()); diff --git a/src/app/context_ui.rs b/src/app/context_ui.rs index ae76f38..b178493 100644 --- a/src/app/context_ui.rs +++ b/src/app/context_ui.rs @@ -10,7 +10,7 @@ impl App { let Some(b) = self.state.bot(bot_id) else { return }; let start = crate::model::model_view_start(&b.messages); let used = agent::history_tokens("", &b.messages[start..]); - let limit = b.context_tokens.max(4_000); + let limit = b.reads(); let text = format!( "這個對話(模型看得到的部分)約 {} token,{} 可讀 {} token,約 {}%(系統指示和工具說明另外大約幾千到一萬多 token)。到 {}% 會自動把較早的內容整理成摘要;要現在整理打 /compact。", used, diff --git a/src/app/followup_ui.rs b/src/app/followup_ui.rs new file mode 100644 index 0000000..2ba3fa8 --- /dev/null +++ b/src/app/followup_ui.rs @@ -0,0 +1,128 @@ +// 追進度 on the brain (followup.rs): each bot's follow-ups are checked when due, on the computer +// they name, on threads of their own; what a check says becomes a progress line in the chat (no +// model) or wakes the bot. A screen of a brain runs none: the brain's bots are the brain's. + +use super::*; +use crate::followup::{self, Verdict}; + +impl App { + /// Whether registering this follow-up asks the person first: as running its check with + /// `shell` there would (Err: refused — never registered). Listing and stopping don't. + pub(super) fn followup_ask(&self, bot_id: u64, args: &str) -> Result, String> { + let v: serde_json::Value = serde_json::from_str(args).unwrap_or(serde_json::Value::Null); + if v.get("list").is_some() || v.get("stop").is_some() { + return Ok(None); + } + let check = v["check"].as_str().unwrap_or("").trim(); + if check.is_empty() { + return Ok(None); + } + let Some(b) = self.state.bot(bot_id) else { return Err("找不到這個 Bot".into()) }; + let (target, name) = self.followup_target(b, v["computer"].as_str().unwrap_or(""))?; + let every = v["every_secs"].as_u64().unwrap_or(followup::DEFAULT_EVERY_SECS).clamp(followup::MIN_EVERY_SECS, followup::MAX_EVERY_SECS); + match tools::decide_on("shell", &serde_json::json!({"command": check}).to_string(), &target, &b.allow_rules) { + tools::Decision::Allow => Ok(None), + tools::Decision::Ask { reason, .. } => Ok(Some(format!("追進度:之後每 {every} 秒會在「{name}」自動執行這個檢查(不再一次次問你),直到好了或停掉。\n{reason}"))), + tools::Decision::Deny(why) => Err(format!("這個檢查指令不能用:{why}")), + } + } + + /// The computer a follow-up runs on: the one it names, or the bot's chosen one. + fn followup_target(&self, b: &Bot, named: &str) -> Result<(tools::Target, String), String> { + let targets = self.targets_for(b); + let roles = self.roles_for(b, &targets); + let name = if named.trim().is_empty() { Self::chosen_computer(b, &targets, &roles).0 } else { named.trim().to_string() }; + targets.into_iter().find(|t| t.name == name).map(|t| (t, name.clone())).ok_or_else(|| format!("「{name}」現在連不到")) + } + + pub(super) fn followup_tick(&mut self, ctx: &egui::Context) { + if self.mir.on { + return; + } + let now = crate::model::now_ms(); + let (mut notes, mut wakes) = (vec![], vec![]); + for (bot, id, got) in followup::take_results() { + let Some(b) = self.state.bot_mut(bot) else { continue }; + let Some(i) = b.follow_ups.iter().position(|f| f.id == id) else { continue }; + let mut f = b.follow_ups[i].clone(); + let verdict = followup::judge(&mut f, got, now); + match &verdict { + Verdict::Wait => b.follow_ups[i] = f, + Verdict::Progress(line) => { + notes.push((bot, followup::progress_text(&f, line, now))); + b.follow_ups[i] = f; + } + ended => { + b.follow_ups.remove(i); + if let Some(text) = followup::wake_text(&f, ended, now) { + wakes.push((bot, text)); + } + } + } + self.dirty = true; + } + for (bot, text) in notes { + self.goal_note(bot, &text); + } + for (bot, text) in wakes { + log::info!("AnyBot:追進度叫醒 Bot {bot}:{}", text.lines().next().unwrap_or("")); + self.wake(ctx, bot, Message { wake: true, ..Message::user(&text) }); + } + // The ones due now, each on a thread of its own; the window comes back at the next one. + let mut soonest: Option = None; + let all: Vec<(u64, followup::FollowUp)> = self.state.bots.iter().flat_map(|b| b.follow_ups.iter().map(move |f| (b.id, f.clone()))).collect(); + for (bot, f) in all { + if followup::is_running(bot, f.id) { + continue; + } + if f.next_ms > now { + soonest = Some(soonest.map_or(f.next_ms, |s: i64| s.min(f.next_ms))); + continue; + } + let Some(b) = self.state.bot(bot) else { continue }; + match self.followup_target(b, &f.computer) { + Ok((target, _)) => followup::start_check(bot, &f, target, self.repaint_fn()), + // (Out of reach now: counted like a failed check, at its own pace.) + Err(e) => followup::push_result(bot, f.id, Err(e)), + } + } + if let Some(at) = soonest { + ctx.request_repaint_after(std::time::Duration::from_millis((at - now).max(1_000) as u64)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 追進度 end to end on the brain: registered by the tool, a check that moved on is one line + /// in the chat (no model), and the one that says done wakes the bot with what to do next. + #[test] + fn a_follow_up_reports_and_wakes_its_bot_when_done() { + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-followup.png"))); + let id = app.state.bots[0].id; + let r = crate::appctl::apply(&mut app.state, id, crate::followup::TOOL, r#"{"what":"下載 Turbo","check":"du -sh /m","done_when":"DL_DONE","then":"跑第一張驗證圖"}"#); + assert!(r.ok && r.text.contains("結束這一輪"), "{}", r.text); + let f = app.state.bot(id).unwrap().follow_ups[0].clone(); + // The bot is busy: a wake waits for its turn to end (no model in this test). + app.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Default::default(), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 0 }); + // Ten minutes later it moved on: a progress line, still followed. + app.state.bot_mut(id).unwrap().follow_ups[0].reported_ms -= crate::followup::REPORT_EVERY_MS; + followup::push_result(id, f.id, Ok("5.2G /m".into())); + app.followup_tick(&ctx); + let b = app.state.bot(id).unwrap(); + assert_eq!(b.follow_ups.len(), 1); + assert!(b.messages.iter().any(|m| m.note && m.text.contains("還在進行") && m.text.contains("5.2G")), "a progress line in the chat"); + // Done: no longer followed, and the bot is woken with what it said it would do next. + followup::push_result(id, f.id, Ok("14G /m\nDL_DONE".into())); + app.followup_tick(&ctx); + assert!(app.state.bot(id).unwrap().follow_ups.is_empty()); + let woke = app.waiting_wakes.iter().find(|(b, _)| *b == id).map(|(_, m)| m.text.clone()).unwrap_or_default(); + assert!(woke.contains("好了") && woke.contains("跑第一張驗證圖") && woke.contains("DL_DONE"), "{woke}"); + // list and stop. + let r = crate::appctl::apply(&mut app.state, id, crate::followup::TOOL, r#"{"list":true}"#); + assert!(r.text.contains("沒有在追")); + } +} diff --git a/src/appctl.rs b/src/appctl.rs index 15c125e..b0e2307 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -9,7 +9,9 @@ use crate::model::{self, Bot, Message, State, Theme, Accent}; use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::routines::{self, Routine, Schedule}; -pub const NAMES: [&str; 31] = [ +pub const NAMES: [&str; 32] = [ + // 追進度: follow something long in the background (followup.rs; checks run on the brain). + "follow_up", "list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now", "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); @@ -40,6 +42,7 @@ pub fn label(name: &str) -> &'static str { crate::hooks::MANAGE_TOOL => "管理 hook", crate::chatgpt::TOOL => "ChatGPT 方案登入", "create_routine" => "建立例行任務", + "follow_up" => "追進度", "update_routine" => "修改例行任務", "delete_routine" => "刪除例行任務", "run_routine_now" => "立即執行例行任務", @@ -93,6 +96,7 @@ fn schedule_schema() -> Value { pub fn specs() -> Vec { vec![ + crate::followup::spec(), json!({"name": "list_routines", "description": "List this bot's routines (scheduled, repeating tasks).", "parameters": {"type": "object", "properties": {}}}), json!({"name": "look_image", "description": "Look at an earlier picture in this chat again, for one specific question. Older attachments and screenshots are carried in the chat as a short caption only; when that caption is not enough (small text, exact numbers, details), use this. It asks a model that sees pictures for a fresh answer about that one picture. index counts pictures back from the newest (0 = the newest picture in the chat, attachments and screenshots together).", "parameters": {"type": "object", "properties": { @@ -461,6 +465,35 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string); let now = routines::now(); match name { + // 追進度: kept on the bot; the window runs the checks (app/followup_ui.rs). + crate::followup::TOOL => { + let now_ms = crate::model::now_ms(); + let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) }; + if v.get("list").and_then(Value::as_bool) == Some(true) { + return ok(crate::followup::list_text(&b.follow_ups, now_ms)); + } + if let Some(id) = v.get("stop").and_then(Value::as_u64) { + let Some(b) = state.bot_mut(bot_id) else { return err("找不到這個 Bot".into()) }; + let before = b.follow_ups.len(); + b.follow_ups.retain(|f| f.id != id); + return if b.follow_ups.len() < before { ok(format!("已停止追進度 #{id}。")) } else { err(format!("沒有在追的 #{id}(用 list 看有哪些)")) }; + } + if b.follow_ups.len() >= crate::followup::MAX_PER_BOT { + return err(format!("同時最多追 {} 件事:先用 stop 停掉用不到的(list 看有哪些)", crate::followup::MAX_PER_BOT)); + } + let id = state.next_routine_id; + let f = match crate::followup::parse(&v, id, now_ms) { + Ok(f) => f, + Err(e) => return err(e), + }; + state.next_routine_id += 1; + let computer = if f.computer.is_empty() { "你選的電腦".to_string() } else { f.computer.clone() }; + let text = crate::followup::started_text(&f, &computer); + if let Some(b) = state.bot_mut(bot_id) { + b.follow_ups.push(f); + } + ok(text) + } "write_page" => { // 同事的頁面: read it, don't overwrite it — say whose it is and how to get it changed. if let Some(owner) = crate::pages::owner_of(&state.pages, bot_id, v["id"].as_u64()) { @@ -863,6 +896,8 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome members: vec![], threads: Default::default(), context_tokens: model::default_context_tokens(), + model_limits: Default::default(), + follow_ups: vec![], routines: vec![], last_turn: None, goal: None, diff --git a/src/followup.rs b/src/followup.rs new file mode 100644 index 0000000..b904c80 --- /dev/null +++ b/src/followup.rs @@ -0,0 +1,383 @@ +//! 追進度 (follow_up): a bot that started something long — a download, a render, a training run, +//! a deploy, a job on another machine over SSH — registers how to look at it and what "done" +//! looks like, and ends its turn. The brain runs the check now and then on that computer (no +//! model in between), posts a progress line in the chat when it moved on, and wakes the bot when +//! it is done, failed, seems stuck, or ran out of time — the person never has to ask 「好了沒」. +//! +//! Before this, the bot said 「我去盯它跑」 and nothing came back: a `sleep` inside a command (cut +//! by its timeout), a 監看 that only watches this computer's own output, or a /goal judge that +//! paused after two rounds of 「還沒好」. +//! +//! The check runs unattended, again and again: registering it is asked like running that command +//! with `shell` (the window decides, app/followup_ui.rs), and it runs where `shell` would. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +pub const TOOL: &str = "follow_up"; + +/// Seconds between checks: at least, by default, at most. +pub const MIN_EVERY_SECS: u64 = 15; +pub const DEFAULT_EVERY_SECS: u64 = 60; +pub const MAX_EVERY_SECS: u64 = 3_600; +/// Minutes before it gives up: by default, at most. +pub const DEFAULT_GIVE_UP_MINS: u64 = 180; +pub const MAX_GIVE_UP_MINS: u64 = 1_440; +/// A progress line in the chat at most this often (only when the output moved on). +pub const REPORT_EVERY_MS: i64 = 10 * 60_000; +/// The check itself failing this many times in a row ends it. +pub const ERRORS_IN_A_ROW: u32 = 3; +/// Follow-ups one bot keeps at once. +pub const MAX_PER_BOT: usize = 8; +/// What is kept of each check's output (its end: progress lines are usually last). +const OUTPUT_KEEP: usize = 1_500; + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct FollowUp { + pub id: u64, + /// What it follows, in the person's words (「下載 Qwen Turbo」). + pub what: String, + /// The command that shows where it is now. + pub check: String, + /// The computer it runs on (empty: the bot's chosen one). + #[serde(default)] + pub computer: String, + /// Done when the output has this (text; /…/ is a regular expression). + pub done_when: String, + /// Failed when the output has this (same; empty: never). + #[serde(default)] + pub fail_when: String, + /// What the bot said it does once it is done (given back when woken). + #[serde(default)] + pub then: String, + pub every_secs: u64, + pub started_ms: i64, + pub until_ms: i64, + #[serde(default)] + pub next_ms: i64, + /// The latest output (its end) and when it last changed. + #[serde(default)] + pub last: String, + #[serde(default)] + pub last_change_ms: i64, + #[serde(default)] + pub reported_ms: i64, + #[serde(default)] + pub errors: u32, +} + +impl FollowUp { + /// No change for this long reads as stuck: 15 minutes, or ten checks if they are further apart. + pub fn stall_ms(&self) -> i64 { + (15 * 60_000).max(self.every_secs as i64 * 10_000) + } +} + +/// What one check says. +#[derive(Debug, PartialEq)] +pub enum Verdict { + /// Not yet; check again at next_ms. + Wait, + /// Not yet, and it moved on: a progress line for the chat (no model). + Progress(String), + Done, + Failed, + Stuck, + OutOfTime, + /// The check command itself kept failing (its last error). + CheckBroken(String), +} + +pub fn spec() -> Value { + json!({"name": TOOL, "description": "追進度: follow something long that keeps going without you — a download, a render, a training run, a deploy, a job on another machine (an SSH one-liner as the check works). Register how to look at it (`check`, a quick command that prints where it is now) and what done looks like (`done_when`); then tell the person in a sentence what you are following and END YOUR TURN — do not sleep, poll in a loop or say 「我去盯」 without this. AnyBot runs the check every `every_secs` on that computer (no model in between), posts a short progress line in the chat when it moved on, and wakes you with the latest output when it is done, failed (`fail_when`), shows no change for a long while, or runs out of time — then carry on (`then` is given back to you). `stop` ends one; `list` shows them.", + "parameters": {"type": "object", "properties": { + "what": {"type": "string", "description": "What it follows, for the person (e.g. 下載 Qwen-Image Turbo、渲染第 3 版影片)."}, + "check": {"type": "string", "description": "A quick command that prints the current state and exits (e.g. `du -sh /model/x`, `tail -n 3 /tmp/job.log`, `curl -s localhost:8188/history/ID`, or an SSH one-liner to another machine). Not a loop, not a sleep."}, + "done_when": {"type": "string", "description": "Text in the check's output that means done (e.g. DL_DONE, \"status\": \"success\"). /…/ is a regular expression."}, + "fail_when": {"type": "string", "description": "Text that means it failed (e.g. Traceback|Error). /…/ is a regular expression. Optional."}, + "then": {"type": "string", "description": "What you will do once it is done (given back to you when woken). Optional."}, + "every_secs": {"type": "integer", "description": "Seconds between checks (15–3600, default 60)."}, + "give_up_after_mins": {"type": "integer", "description": "Minutes before it gives up and wakes you (default 180, at most 1440)."}, + "computer": {"type": "string", "description": "Which computer runs the check (as list_computers names it); default: the one you work on."}, + "stop": {"type": "integer", "description": "End the follow-up with this number instead."}, + "list": {"type": "boolean", "description": "Show the follow-ups running now instead."}}}}) +} + +/// A new follow-up from the tool's arguments. +pub fn parse(v: &Value, id: u64, now_ms: i64) -> Result { + let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::trim).unwrap_or("").to_string(); + let check = s("check"); + if check.is_empty() { + return Err("缺少 check:一個很快就結束、會印出現在進度的指令".into()); + } + let done_when = s("done_when"); + if done_when.is_empty() { + return Err("缺少 done_when:檢查的輸出裡出現什麼代表好了".into()); + } + for (k, p) in [("done_when", &done_when), ("fail_when", &s("fail_when"))] { + if let Some(re) = as_regex(p) { + regex::Regex::new(re).map_err(|e| format!("{k} 的正規表示式有問題:{e}"))?; + } + } + let every_secs = v.get("every_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_EVERY_SECS).clamp(MIN_EVERY_SECS, MAX_EVERY_SECS); + let mins = v.get("give_up_after_mins").and_then(Value::as_u64).unwrap_or(DEFAULT_GIVE_UP_MINS).clamp(1, MAX_GIVE_UP_MINS); + let what = Some(s("what")).filter(|w| !w.is_empty()).unwrap_or_else(|| check.chars().take(40).collect()); + Ok(FollowUp { + id, + what, + check, + computer: s("computer"), + done_when, + fail_when: s("fail_when"), + then: s("then"), + every_secs, + started_ms: now_ms, + until_ms: now_ms + mins as i64 * 60_000, + next_ms: now_ms, + last_change_ms: now_ms, + reported_ms: now_ms, + ..Default::default() + }) +} + +/// /…/: a regular expression (what is inside). +fn as_regex(p: &str) -> Option<&str> { + p.strip_prefix('/').and_then(|r| r.strip_suffix('/')).filter(|r| !r.is_empty()) +} + +fn matches(pattern: &str, text: &str) -> bool { + if pattern.is_empty() { + return false; + } + match as_regex(pattern) { + Some(re) => regex::Regex::new(re).is_ok_and(|r| r.is_match(text)), + None => text.contains(pattern), + } +} + +/// The end of an output, at most OUTPUT_KEEP characters. +fn tail(s: &str) -> String { + let s = s.trim(); + let n = s.chars().count(); + s.chars().skip(n.saturating_sub(OUTPUT_KEEP)).collect() +} + +/// One check's result for `f` at `now_ms`: what it says, with `f` brought up to date (its next +/// check, the latest output, when it changed). +pub fn judge(f: &mut FollowUp, got: Result, now_ms: i64) -> Verdict { + f.next_ms = now_ms + f.every_secs as i64 * 1_000; + match got { + Ok(out) => { + f.errors = 0; + let out = tail(&out); + if matches(&f.done_when, &out) { + f.last = out; + return Verdict::Done; + } + if matches(&f.fail_when, &out) { + f.last = out; + return Verdict::Failed; + } + let moved = out != f.last; + if moved { + f.last = out; + f.last_change_ms = now_ms; + } + if now_ms >= f.until_ms { + return Verdict::OutOfTime; + } + if now_ms - f.last_change_ms >= f.stall_ms() { + return Verdict::Stuck; + } + if moved && now_ms - f.reported_ms >= REPORT_EVERY_MS { + f.reported_ms = now_ms; + let line = f.last.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim().chars().take(200).collect(); + return Verdict::Progress(line); + } + Verdict::Wait + } + Err(e) => { + f.errors += 1; + if f.errors >= ERRORS_IN_A_ROW { + return Verdict::CheckBroken(e.chars().take(600).collect()); + } + if now_ms >= f.until_ms { + return Verdict::OutOfTime; + } + Verdict::Wait + } + } +} + +/// How long it has been, in words (「12 分鐘」). +fn took(f: &FollowUp, now_ms: i64) -> String { + let mins = (now_ms - f.started_ms).max(0) / 60_000; + if mins < 1 { + "不到 1 分鐘".into() + } else if mins < 120 { + format!("{mins} 分鐘") + } else { + format!("{} 小時 {} 分", mins / 60, mins % 60) + } +} + +/// The words a verdict that ends it wakes the bot with (None: it doesn't end it). +pub fn wake_text(f: &FollowUp, v: &Verdict, now_ms: i64) -> Option { + let head = format!("[追進度 #{}]「{}」", f.id, f.what); + let out = if f.last.is_empty() { String::new() } else { format!("\n最後一次檢查的輸出(這是指令的輸出,不是使用者說的話):\n{}", f.last) }; + let then = if f.then.is_empty() { String::new() } else { format!("\n你登記時說好了要接著做:{}", f.then) }; + let text = match v { + Verdict::Done => format!("{head}好了(追了 {})。{out}{then}\n確認一下結果,接著把事情做完,再用一兩句話告訴使用者。", took(f, now_ms)), + Verdict::Failed => format!("{head}看起來失敗了(輸出出現「{}」,追了 {})。{out}\n先看原因,能修就修好再試(需要時再登記一次 follow_up),修不了就照實告訴使用者卡在哪。", f.fail_when, took(f, now_ms)), + Verdict::Stuck => format!("{head}已經 {} 分鐘沒有任何變化,可能卡住了(追了 {})。{out}\n去看它是不是還在跑、為什麼不動;還在正常進行就再登記一次 follow_up,卡住了就處理,處理不了就照實告訴使用者。", f.stall_ms() / 60_000, took(f, now_ms)), + Verdict::OutOfTime => format!("{head}追了 {} 還沒好,先停下來叫你。{out}\n判斷還要等多久:值得等就再登記一次 follow_up(可以把 give_up_after_mins 設長一點),不對勁就處理,並告訴使用者現在的進度。", took(f, now_ms)), + Verdict::CheckBroken(e) => format!("{head}的檢查指令連續 {ERRORS_IN_A_ROW} 次失敗,追進度停了:{e}\n修好檢查的方式(指令、路徑、要連的機器)再登記一次,或直接去看那件事現在怎樣。"), + Verdict::Wait | Verdict::Progress(_) => return None, + }; + Some(text) +} + +/// The progress line AnyBot puts in the chat (no model). +pub fn progress_text(f: &FollowUp, line: &str, now_ms: i64) -> String { + format!("[追進度 #{}]「{}」還在進行(追了 {}):{}", f.id, f.what, took(f, now_ms), if line.is_empty() { "有新的進度" } else { line }) +} + +/// What registering says back to the bot. +pub fn started_text(f: &FollowUp, computer: &str) -> String { + let fail = if f.fail_when.is_empty() { String::new() } else { format!("、出現「{}」(失敗)", f.fail_when) }; + format!( + "已登記追進度 #{}「{}」:每 {} 秒在「{computer}」跑一次檢查;看到「{}」(好了){fail}、{} 分鐘沒有變化,或追了 {} 分鐘還沒好,AnyBot 就會叫你回來,中途有進展會在聊天裡報一行。現在不用等它:用一兩句話告訴使用者你在追什麼、好了會自己接著做,然後結束這一輪。", + f.id, + f.what, + f.every_secs, + f.done_when, + f.stall_ms() / 60_000, + (f.until_ms - f.started_ms) / 60_000 + ) +} + +/// The follow-ups in words (for `list`). +pub fn list_text(all: &[FollowUp], now_ms: i64) -> String { + if all.is_empty() { + return "現在沒有在追進度的事。".into(); + } + all.iter() + .map(|f| format!("#{}「{}」:追了 {},每 {} 秒檢查,看到「{}」算好;最後的輸出:{}", f.id, f.what, took(f, now_ms), f.every_secs, f.done_when, f.last.lines().last().unwrap_or("(還沒檢查)"))) + .collect::>() + .join("\n") +} + +// ---------- the checks run here, results come back to the window ---------- + +use std::sync::{Mutex, OnceLock}; + +type Result3 = (u64, u64, Result); + +fn results() -> &'static Mutex> { + static R: OnceLock>> = OnceLock::new(); + R.get_or_init(Default::default) +} + +fn running() -> &'static Mutex> { + static R: OnceLock>> = OnceLock::new(); + R.get_or_init(Default::default) +} + +/// Whether bot's follow-up `id` has a check running now. +pub fn is_running(bot: u64, id: u64) -> bool { + running().lock().unwrap_or_else(|e| e.into_inner()).contains(&(bot, id)) +} + +/// Run one check on `target` on a thread of its own; its result comes back with take_results. +pub fn start_check(bot: u64, f: &FollowUp, target: crate::tools::Target, wake: std::sync::Arc) { + if !running().lock().unwrap_or_else(|e| e.into_inner()).insert((bot, f.id)) { + return; + } + let (id, check) = (f.id, f.check.clone()); + std::thread::spawn(move || { + let args = json!({"command": check, "timeout_ms": 120_000, "computer": target.name}).to_string(); + let ids = crate::tools::RunIds { conversation: bot.to_string(), request: format!("followup-{id}") }; + let (out, ok) = crate::tools::run_on("shell", &args, &target, &std::sync::atomic::AtomicBool::new(false), &ids); + results().lock().unwrap_or_else(|e| e.into_inner()).push((bot, id, if ok { Ok(out) } else { Err(out) })); + running().lock().unwrap_or_else(|e| e.into_inner()).remove(&(bot, id)); + wake(); + }); +} + +/// A result that needs no check run (the computer is out of reach): judged like one. +pub fn push_result(bot: u64, id: u64, got: Result) { + results().lock().unwrap_or_else(|e| e.into_inner()).push((bot, id, got)); +} + +/// The checks that finished since last time: (bot, follow-up id, its output or error). +pub fn take_results() -> Vec { + std::mem::take(&mut *results().lock().unwrap_or_else(|e| e.into_inner())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fu(now: i64) -> FollowUp { + parse(&json!({"what": "下載 Turbo", "check": "du -sh /m", "done_when": "DL_DONE", "fail_when": "/Error|Traceback/", "every_secs": 60}), 1, now).unwrap() + } + + #[test] + fn registering_needs_a_check_and_what_done_looks_like() { + assert!(parse(&json!({"done_when": "x"}), 1, 0).unwrap_err().contains("check")); + assert!(parse(&json!({"check": "ls"}), 1, 0).unwrap_err().contains("done_when")); + assert!(parse(&json!({"check": "ls", "done_when": "/(/"}), 1, 0).unwrap_err().contains("正規表示式")); + let f = parse(&json!({"check": "ls", "done_when": "ok", "every_secs": 1, "give_up_after_mins": 99_999}), 1, 0).unwrap(); + assert_eq!(f.every_secs, MIN_EVERY_SECS); + assert_eq!(f.until_ms, MAX_GIVE_UP_MINS as i64 * 60_000); + assert_eq!(f.what, "ls"); + } + + #[test] + fn done_failed_and_waiting_by_the_output() { + let mut f = fu(0); + assert_eq!(judge(&mut f, Ok("612M /m".into()), 60_000), Verdict::Wait); + assert_eq!(f.next_ms, 120_000); + assert_eq!(judge(&mut f, Ok("14G /m\nDL_DONE".into()), 120_000), Verdict::Done); + let mut f = fu(0); + assert_eq!(judge(&mut f, Ok("Traceback (most recent call last)".into()), 60_000), Verdict::Failed); + assert!(wake_text(&f, &Verdict::Failed, 60_000).unwrap().contains("Traceback")); + } + + #[test] + fn progress_is_said_now_and_then_and_stillness_reads_as_stuck() { + let mut f = fu(0); + // Moving on, but the last line was just now: nothing to say yet. + assert_eq!(judge(&mut f, Ok("1G".into()), 60_000), Verdict::Wait); + // Ten minutes on and it moved: one line for the chat. + assert_eq!(judge(&mut f, Ok("5G".into()), REPORT_EVERY_MS + 1), Verdict::Progress("5G".into())); + assert_eq!(judge(&mut f, Ok("6G".into()), REPORT_EVERY_MS + 60_000), Verdict::Wait); + // No change for the stall time: stuck. + let at = f.last_change_ms + f.stall_ms(); + assert_eq!(judge(&mut f, Ok("6G".into()), at), Verdict::Stuck); + } + + #[test] + fn a_broken_check_and_running_out_of_time_end_it() { + let mut f = fu(0); + assert_eq!(judge(&mut f, Err("ssh: connect timed out".into()), 60_000), Verdict::Wait); + assert_eq!(judge(&mut f, Err("ssh: connect timed out".into()), 120_000), Verdict::Wait); + assert!(matches!(judge(&mut f, Err("ssh: connect timed out".into()), 180_000), Verdict::CheckBroken(_))); + let mut f = fu(0); + let end = f.until_ms; + // (Still changing: not stuck, only out of time.) + assert_eq!(judge(&mut f, Ok("99%".into()), end), Verdict::OutOfTime); + assert!(wake_text(&f, &Verdict::OutOfTime, end).unwrap().contains("give_up_after_mins")); + } + + #[test] + fn the_words_say_what_to_do_next() { + let mut f = fu(0); + f.then = "跑第一張驗證圖".into(); + f.last = "14G\nDL_DONE".into(); + let w = wake_text(&f, &Verdict::Done, 90 * 60_000).unwrap(); + assert!(w.starts_with("[追進度 #1]「下載 Turbo」好了") && w.contains("跑第一張驗證圖") && w.contains("不是使用者說的話") && w.contains("90 分鐘"), "{w}"); + assert!(started_text(&f, "進化之神 的電腦").contains("結束這一輪")); + assert!(progress_text(&f, "5G", 30 * 60_000).contains("還在進行")); + } +} diff --git a/src/main.rs b/src/main.rs index 963f41d..db81919 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ #![recursion_limit = "512"] // the one `computer` tool's schema is one deep json! literal mod agent; +mod followup; mod shared; mod ask; mod app; diff --git a/src/model.rs b/src/model.rs index 48ad50c..f50b42c 100644 --- a/src/model.rs +++ b/src/model.rs @@ -405,6 +405,14 @@ pub struct Bot { /// How much the model can read at once, for deciding when to summarize. #[serde(default = "default_context_tokens")] pub context_tokens: u64, + /// What each model said it can read when a request was too long ("供應商/模型" → tokens): + /// learned per model, so one model's small limit doesn't shrink another's chats after a + /// switch (it used to overwrite context_tokens for every model the bot would use). + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub model_limits: std::collections::BTreeMap, + /// 追進度: what this bot follows now (followup.rs); the brain checks them, the bot is woken. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub follow_ups: Vec, #[serde(default)] pub routines: Vec, #[serde(default)] @@ -473,6 +481,18 @@ pub fn default_computer() -> String { pub const INTERRUPTED_NOTE: &str = "(這次的回應被中斷了,可能是 App 關閉或重新啟動。按「重新產生」再試一次。)"; impl Bot { + /// The key model_limits uses for this bot's model now. + pub fn limit_key(&self) -> String { + format!("{}/{}", self.provider.key(), self.model) + } + + /// How much this bot's model now reads: the person's setting, or less when this model said + /// so (model_limits). + pub fn reads(&self) -> u64 { + let own = self.model_limits.get(&self.limit_key()).copied().unwrap_or(u64::MAX); + self.context_tokens.min(own).max(4_000) + } + /// 「儲存」 in the bot's settings: what the person changed there (`edited`, against `from` /// — the bot as the editor opened it) is put onto the bot as it is now. Everything else /// stays as it is now: a turn running meanwhile gave it messages, things to remember, @@ -1212,6 +1232,8 @@ impl State { members: vec![], threads: Default::default(), context_tokens: default_context_tokens(), + model_limits: Default::default(), + follow_ups: vec![], routines: vec![], last_turn: None, goal: None, diff --git a/src/profile.rs b/src/profile.rs index 6ffdc52..ec2f5b7 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -36,7 +36,7 @@ pub fn ability_of(tool: &str) -> Option<&'static str> { t if t.starts_with("browser") || t.starts_with("vault_") => "browser", crate::computer::TOOL | crate::agent::REPLAY_TOOL | "view_demo_step" => "screen", t if t.starts_with("computer_use") => "screen", - "shell" | "read_file" | "edit_file" | "list_dir" | "search" | "read_terminal" | "write_terminal" | "open_for_person" | "publish_site" | "send_to_device" => "files", + "shell" | "read_file" | "edit_file" | "list_dir" | "search" | "read_terminal" | "write_terminal" | "open_for_person" | "publish_site" | "send_to_device" | crate::followup::TOOL => "files", t if crate::macapps::is_mac_tool(t) => "mac_apps", t if crate::mcp::is_mcp_tool(t) || t == crate::mcp::FIND_TOOL || t == crate::mcp::USE_TOOL => "connectors", "place_call" | "send_sms" | "post_to_x" => "phone", diff --git a/src/providers.rs b/src/providers.rs index 342bf59..9a3d752 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -420,6 +420,40 @@ pub fn set_patient(on: bool) { PATIENT.with(|p| p.set(on)); } +thread_local! { + /// How long this thread's next model call may take to its first word (seconds; 0: the + /// usual FIRST_RESPONSE_TIMEOUT_SECS). See first_wait_for. + static FIRST_WAIT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The longest first wait, however long the request. +pub const FIRST_WAIT_MAX_SECS: u64 = 600; + +/// How long a request of `tokens` (estimated) may take to its first word: a model reads the whole +/// request before it writes anything, and one on the person's own GPUs read 100 000 tokens for +/// longer than the fixed 120 s — the turn was cut, and asked again with the same request, cut +/// again. 120 s up to 30 000 tokens, 2 s more for each 1 000 beyond, at most FIRST_WAIT_MAX_SECS. +pub fn first_wait_for(tokens: u64) -> u64 { + (FIRST_RESPONSE_TIMEOUT_SECS + tokens.saturating_sub(30_000) / 1_000 * 2).min(FIRST_WAIT_MAX_SECS) +} + +/// The first wait for this thread's model calls from now on (first_wait_for of the request). +pub fn set_first_wait(secs: u64) { + FIRST_WAIT.with(|w| w.set(secs)); +} + +fn first_wait() -> u64 { + FIRST_WAIT.with(|w| w.get()).max(FIRST_RESPONSE_TIMEOUT_SECS) +} + +/// What a request that got no word at all within its first wait fails with: too much for this +/// model to read in time. Not asked again as it is — made smaller first (agent::make_room). +pub const SLOW_START: &str = "模型讀這麼長的對話,久到還沒開始回答:"; + +pub fn is_slow_start(msg: &str) -> bool { + msg.starts_with(SLOW_START) +} + /// (tries in all, longest wait) for this thread's model calls. fn retry_budget() -> (u32, u64) { if PATIENT.with(|p| p.get()) { @@ -447,11 +481,12 @@ fn agent() -> ureq::Agent { // `ureq` would forward unchanged to an untrusted redirect target, and 301/302 turns POST into GET. .max_redirects(0) .timeout_connect(Some(Duration::from_millis(CONNECT_TIMEOUT_MS))) - .timeout_recv_response(Some(Duration::from_secs(FIRST_RESPONSE_TIMEOUT_SECS))) + .timeout_recv_response(Some(Duration::from_secs(first_wait()))) // A stream that goes silent (a NAT that dropped the mapping, a server that died without // a FIN) must end: without a read timeout the lines() loop blocks forever, and every - // such turn leaks a thread and its socket. 5 minutes of total silence is a dead stream. - .timeout_per_read(Some(Duration::from_secs(300))) + // such turn leaks a thread and its socket. 5 minutes of total silence is a dead stream — + // or, before the first word, the request's own first wait (read_sse_from tells them apart). + .timeout_per_read(Some(Duration::from_secs(first_wait().min(300)))) .build(); config.into() } @@ -792,8 +827,9 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea let mut attempt = 1; // 沒人在看的一輪 waits longer (set_patient). let (tries, longest) = retry_budget(); - // Steps left without a result (stopped while waiting for the person) are closed off. - let repaired = ChatRequest { history: repair_history(&req.history), ..req.clone() }; + // Steps left without a result (stopped while waiting for the person) are closed off; the + // calls of steps whose result was set aside go shortened too (fold_called_args). + let repaired = ChatRequest { history: fold_called_args(repair_history(&req.history)), ..req.clone() }; let req = &repaired; let mut blind_copy: Option = None; loop { @@ -856,12 +892,22 @@ fn read_sse(body: ureq::Body, cancel: &AtomicBool, send: &dyn Fn(StreamEvent), o fn read_sse_from(r: impl std::io::Read, cancel: &AtomicBool, send: &dyn Fn(StreamEvent), mut on_data: impl FnMut(&str, &str) -> bool) -> Result<(), Failure> { let reader = BufReader::new(r); let mut event = String::new(); + let started = std::time::Instant::now(); + let mut heard = false; for line in reader.lines() { if cancel.load(Ordering::Relaxed) { return Ok(()); } - // SAND-E0403 streamReset: retryable. - let line = line.map_err(|e| Failure::retry(format!("連線中斷:{e}")))?; + // Nothing at all within the first wait: the request is too much for this model to read + // in time — asking again as it is would only wait as long again (agent makes room). + let line = match line { + Err(e) if !heard && matches!(e.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock) => { + return Err(Failure::fatal(format!("{SLOW_START}等了 {} 秒沒有任何回應。", started.elapsed().as_secs()))); + } + // SAND-E0403 streamReset: retryable. + r => r.map_err(|e| Failure::retry(format!("連線中斷:{e}")))?, + }; + heard = true; send(StreamEvent::Alive); if let Some(ev) = line.strip_prefix("event:") { event = ev.trim().to_string(); @@ -936,6 +982,50 @@ pub fn image_refused(msg: &str) -> bool { /// Every tool call needs its result right after it (providers refuse the conversation /// otherwise). A step stopped or refused while it waited for the person has none: give it one. /// Results whose call is gone are dropped. +/// A call's arguments longer than this are shortened once its result was set aside. +const ARGS_FOLD_MIN: usize = 600; +/// What stays of each long text in them. +const ARGS_FOLD_HEAD: usize = 240; + +/// The calls whose results were set aside (folded) go with their long texts shortened: a +/// 3 000-character script was sent again with every request of every turn after it — in one +/// chat the calls' arguments were a third of each request. The model has used them; like the +/// folded results they read the same from then on, so the cache isn't broken step after step. +pub fn fold_called_args(mut h: Vec) -> Vec { + let folded: std::collections::HashSet = h.iter().filter(|m| m.role == Role::Tool && m.folded).map(|m| m.tool_call_id.clone()).collect(); + if folded.is_empty() { + return h; + } + for m in h.iter_mut().filter(|m| m.role == Role::Assistant) { + for c in m.tool_calls.iter_mut().filter(|c| c.args.chars().count() > ARGS_FOLD_MIN && folded.contains(&c.id)) { + c.args = shortened_args(&c.args); + } + } + h +} + +/// The arguments with every long text cut to its first words (still JSON, same keys). +fn shortened_args(args: &str) -> String { + fn walk(v: &mut Value) { + match v { + Value::String(s) if s.chars().count() > ARGS_FOLD_HEAD => { + let head: String = s.chars().take(ARGS_FOLD_HEAD).collect(); + *s = format!("{head}…(較早一步的內容已收起)"); + } + Value::Array(a) => a.iter_mut().for_each(walk), + Value::Object(o) => o.values_mut().for_each(walk), + _ => {} + } + } + match serde_json::from_str::(args) { + Ok(mut v) => { + walk(&mut v); + v.to_string() + } + Err(_) => json!({"(已收起)": args.chars().take(ARGS_FOLD_HEAD).collect::()}).to_string(), + } +} + pub fn repair_history(history: &[Message]) -> Vec { let mut out: Vec = Vec::with_capacity(history.len()); let mut i = 0; @@ -1675,6 +1765,11 @@ fn chatgpt_models() -> Result, String> { Ok(ids) } +/// Whether `m` was written by `model` (its 「供應商 · 模型」 line ends with it). +pub(crate) fn written_by(m: &Message, model: &str) -> bool { + m.via.rsplit(" · ").next().map(|w| w.trim_end_matches("(重播)")) == Some(model) +} + pub fn anthropic_messages(req: &ChatRequest) -> Vec { let mut messages: Vec = vec![]; let mut push = |role: &str, blocks: Vec| { @@ -1720,7 +1815,10 @@ pub fn anthropic_messages(req: &ChatRequest) -> Vec { } Role::User => {} Role::Assistant => { - if !m.blocks.is_empty() { + // Its own blocks (thinking with its signature) go back only to the model that wrote + // them: another model refuses a signature that isn't its own — after a switch the + // turn failed. Others get the words and calls rebuilt below. + if !m.blocks.is_empty() && written_by(m, &req.model) { push("assistant", m.blocks.clone()); } else if !m.error || !m.tool_calls.is_empty() { let mut b = vec![]; @@ -2038,6 +2136,62 @@ mod tests { } use super::*; + + /// The first wait grows with what the request carries, within its bounds. + #[test] + fn a_longer_request_may_take_longer_to_start() { + assert_eq!(first_wait_for(10_000), FIRST_RESPONSE_TIMEOUT_SECS); + assert_eq!(first_wait_for(100_000), FIRST_RESPONSE_TIMEOUT_SECS + 140); + assert_eq!(first_wait_for(10_000_000), FIRST_WAIT_MAX_SECS); + } + + /// Nothing at all before the read timed out: too slow to start (made smaller, not asked + /// again as it was). A stream that stopped after it began is a dropped line, as before. + #[test] + fn no_first_word_is_told_apart_from_a_dropped_line() { + struct Then(Vec>>); + impl std::io::Read for Then { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0.is_empty() { + return Ok(0); + } + match self.0.remove(0) { + Ok(b) => { + buf[..b.len()].copy_from_slice(&b); + Ok(b.len()) + } + Err(e) => Err(e), + } + } + } + let timed_out = || std::io::Error::new(std::io::ErrorKind::TimedOut, "timed out"); + let quiet = |_: StreamEvent| {}; + let cancel = AtomicBool::new(false); + let e = read_sse_from(Then(vec![Err(timed_out())]), &cancel, &quiet, |_, _| true).unwrap_err(); + assert!(is_slow_start(&e.msg) && !e.retryable, "{}", e.msg); + let e = read_sse_from(Then(vec![Ok(b"data: {}\n".to_vec()), Err(timed_out())]), &cancel, &quiet, |_, _| true).unwrap_err(); + assert!(!is_slow_start(&e.msg) && e.retryable, "{}", e.msg); + } + + /// A step whose result was set aside goes with its long arguments shortened (still JSON, + /// same keys); a step whose result is still whole goes as it was. + #[test] + fn calls_of_set_aside_steps_go_shortened() { + let script = format!("python3 <<'EOF'\n{}\nEOF", "print('x')\n".repeat(200)); + let call = |id: &str| ToolCall { id: id.into(), name: "shell".into(), args: json!({"command": script, "computer": "box"}).to_string(), status: ToolStatus::Done }; + let h = vec![ + Message::user("做"), + Message { tool_calls: vec![call("old")], ..Message::assistant("", "x") }, + Message { folded: true, ..Message::tool_result("old", "shell", "(收起)") }, + Message { tool_calls: vec![call("new")], ..Message::assistant("", "x") }, + Message::tool_result("new", "shell", "ok"), + ]; + let out = fold_called_args(h); + let old: Value = serde_json::from_str(&out[1].tool_calls[0].args).unwrap(); + assert!(old["command"].as_str().unwrap().ends_with("(較早一步的內容已收起)") && old["computer"] == "box", "{old}"); + assert!(out[1].tool_calls[0].args.len() < 1_000); + assert_eq!(out[3].tool_calls[0].args, call("new").args, "a step still in use goes whole"); + } use std::io::{Read, Write}; use std::net::TcpListener; diff --git a/src/setup.rs b/src/setup.rs index 1d86af9..d86621e 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1163,6 +1163,8 @@ fn seed_first() -> i32 { voice_lang: String::new(), demos: vec![], context_tokens: crate::agent::DEFAULT_CONTEXT_TOKENS, + model_limits: Default::default(), + follow_ups: vec![], routines: vec![], last_turn: None, goal: None,