DEV Community

Cover image for 為什麼 osFoundry 讓 Codex CLI 針對每個資源輪詢 cursor,而不是主動推送變更?
BBT for BBT 繁體中文

Posted on

為什麼 osFoundry 讓 Codex CLI 針對每個資源輪詢 cursor,而不是主動推送變更?

想知道「什麼東西變了」的 client,osFoundry 的 MCP server 能給的就只有下面這些。在這台 Mac 上、不帶 token 執行:

$ uv run --with tiktoken --with jsonschema python3 watch_sim.py
== Part 1: live wire, 8 calls each, ms ==
initialize                   HTTP 200  median  414.7  p90  757.8
tools/list                   HTTP 200  median  606.8  p90  716.7
resources/subscribe          HTTP 200  median  450.6  p90  550.2
GET (stream)                 HTTP 405  median  423.9  p90  475.4
tools/call poll (no token)   HTTP 401  median  322.0  p90  463.9
initialize capabilities: {"tools": {"listChanged": false}}
resources/subscribe -> {"code": -32601, "message": "Method not found"}
GET body -> ''
poll without token -> isError True | Authentication required
rate limit headers: limit 2000, reset in 61 s
Enter fullscreen mode Exit fullscreen mode

三條 push 的路都關著。initialize 只宣告了 tools,其他什麼都沒有,而且是 listChanged: false,所以連 tool 清單變動都不會通知。resources/subscribe 回的是 "Method not found"。對 MCP URL 發 GET,也就是 Streamable HTTP server 原本會開出 server 到 client 串流的地方,回傳 405。剩下的只有一個唯讀 tool:

{"name": "poll_resource_events",
 "description": "Resume from an event sequence for one granted channel, Note, knowledge base, record, or session.",
 "inputSchema": {"properties": {
     "resource_type": {"enum": ["message_channel", "note", "knowledge_base", "record_channel", "room",
                                "gitnest_repository", "agent_session", "team_session", "loop_session",
                                "graph_session"]},
     "resource_id": {"type": "string"},
     "after_sequence": {"type": "integer", "minimum": 0},
     "limit": {"type": "integer", "minimum": 1, "maximum": 100}},
   "required": ["resource_type", "resource_id"], "additionalProperties": false},
 "annotations": {"readOnlyHint": true, "openWorldHint": false, "destructiveHint": false},
 "securitySchemes": [{"type": "oauth2", "scopes": ["osfoundry:read"]}]}
Enter fullscreen mode Exit fullscreen mode

"One granted" 的資源、"resume from an event sequence"。這篇接下來就是在講這幾個字,client 端則用 Python 重建。這台機器沒有安裝 codex 執行檔,所以由 script 扮演 client。osFoundry 的 server 程式碼沒有公開:Part 1 和 Part 2 打的是正式環境的 server,Part 3 則是重建版本,回應格式和活動頻率都是它自己設定的。

為什麼 Codex 特別適合用輪詢,而不是 push?

Codex CLI 不是 daemon。你執行它,它才會跑,做完一個 turn 之後就結束,或是停下來等你。Push channel 需要有東西在你的 session 之間持續監聽,而在筆電上,這個東西往往不存在。Sequence cursor 剛好符合這種使用方式:client 每個資源只記一個整數,想回來的時候再回來,問「這個號碼之後發生了什麼」。

上面的毫秒數是在日本用 Apple M1 量的,所以反映的多半是網路路徑,而不是 server 本身。更重要的是 rate limit header。未驗證的回應帶有 X-RateLimit-Limit: 2000,大約 61 s 後重置。登入後的 client 是否有同樣的額度沒有另外確認,但就算每 30 s 輪詢 30 個資源,也才每分鐘 60 個請求。限制 Codex 監看程式的不是 server 負載,而是它自己的 turn:每一次 poll 都是一次 tool call,模型得發出去、再讀回來。

Client 怎麼知道自己可以輪詢哪些資源?

靠兩個呼叫,而 schema 本身就透露了不少設計思路:

list_granted_resources   osfoundry:read  ro=True required=[] props=[]
list_project_resources   osfoundry:read  ro=True required=['project_id', 'resource_type'] props=['project_id', 'resource_type', 'search', 'offset', 'limit']
poll_resource_events     osfoundry:read  ro=True required=['resource_type', 'resource_id'] props=['resource_type', 'resource_id', 'after_sequence', 'limit']
59 tools on server; these three = 591 of 12662 tokens (4.7%, cl100k_base)
poll_resource_events types: 10 | list_project_resources types: 9 | only pollable: ['graph_session']
Enter fullscreen mode Exit fullscreen mode

list_granted_resources 完全不接受參數,schema 也把加參數的路堵死了:

list_granted_resources   no arguments           ok
list_granted_resources   project_id passed      REJECT additionalProperties
Enter fullscreen mode Exit fullscreen mode

這是 server 告訴 client 它擁有什麼,而不是 client 去要求什麼。initialize 的 instructions 第一句就是 "Use list_granted_resources first." 回傳的內容是加到這個連線的 project,以及個別授權的資源。在 web client(ExternalAssistantsPanel.tsx)裡,對應的是 Projects 區塊和 "Older individual access"。

list_project_resources 一定要帶 resource_type。沒有「列出這個 project 裡所有東西」的方式,所以要盤點完整內容,每種類型就要呼叫一次,總共九種;某個類型超過 50 筆的話還要更多次(limit 上限 50,用 offset 分頁)。它的 description 還補充了 project 存取的唯一例外:"Ordinary Message channels require a separate invitation."

graph_session 可以輪詢,但不能列出。Graph 存在 owner 的桌面上,要透過 list_graph_sessions 進來,而且前提是 owner 已經從桌面 app 分享出來。

為什麼 cursor 由 client 持有,而不是 server?

osFoundry 兩種都有。Agent network 上的 wait_for_messages 會幫你記住 cursor:"Without after_sequence it resumes where your last call stopped",而且支援 timeout_s 最多 50 的 long polling。poll_resource_events 兩者都沒有。timeout_s 會被拒絕,description 也只寫 "resume from",所以號碼要由 client 自己帶:

wait_for_messages props: ['after_sequence', 'timeout_s', 'limit'] timeout_s max 50 | poll_resource_events has timeout: False
poll_resource_events     timeout_s 30           REJECT additionalProperties
Enter fullscreen mode Exit fullscreen mode

Server 端持有 cursor,對單一監聽者來說很方便。但只要兩個 client 共用同一個連線就會出問題,而你用同一個登入在兩個終端機開 Codex 時,正好就是這種情況。重建版本讓 600 個 channel 事件經過兩個隨機輪流輪詢的終端機:

two terminals, client cursor: A saw 600/600, B saw 600/600
two terminals, server cursor: A saw 305/600, B saw 295/600
Enter fullscreen mode Exit fullscreen mode

每個連線一個 server 端 cursor 的話,每個終端機都會替另一個把 cursor 往前推,結果各自只看到大約一半。Request 裡帶 after_sequence 的話,兩邊都能看到全部,server 也完全不需要保存每個讀取者的狀態。對於可能被多個工具各自讀取的資源 log 來說,cursor 交給 client 才是對的。

Schema 沒有把 after_sequence 設為必填,也沒說省略時代表什麼。不要依賴這個行為。把號碼存下來,每次都帶上。

一整頁要花多少次呼叫?

limit 最多 100。大量匯入之後,一則 note 可能有好幾百個事件在等。要清空,就得從最後一個 sequence 繼續呼叫,直到回來的頁面不滿為止:

burst of 350 events, limit 100:  4 calls to drain, cursor ends at 350
burst of 350 events, limit  50:  7 calls to drain, cursor ends at 350
burst of 350 events, limit  20: 18 calls to drain, cursor ends at 350
Enter fullscreen mode Exit fullscreen mode

就設 100。在重建版本裡,空白頁的回應是 17 個 token,一個事件是 41 個,用 cl100k_base 計算。這是重建版的格式,不是 osFoundry 的,但數量級已經足以說明:空的 poll 讀起來很便宜,所以輪詢的成本主要在 turn 的次數。

Codex 應該多久輪詢一次 30 個資源?

重建版本給一個 project 30 個資源,涵蓋九種可列出的類型,活躍度刻意不平均:3 個很忙(每分鐘一個事件)、7 個普通(每 10 分鐘一個)、20 個冷門(每 2 小時一個)。這些頻率是假設值。它在模擬時鐘上用五個 seed 跑一個 8 小時的工作日:

every 30 s, all 30                 calls/hour   3600  empty  94.7%  seen late median   14.9 s  p90   27.0 s  max     30 s  (1843 events/day)
every 5 min, all 30                calls/hour    360  empty  78.0%  seen late median  150.9 s  p90  271.1 s  max    300 s  (1843 events/day)
30 s, x2 when empty, cap 10 min    calls/hour    502  empty  70.2%  seen late median   34.9 s  p90  206.4 s  max    599 s  (1843 events/day)
30 s, x2 when empty, cap 30 min    calls/hour    420  empty  65.3%  seen late median   35.6 s  p90  238.4 s  max   1799 s  (1843 events/day)
server window for comparison: 2000 requests per ~61 s
Enter fullscreen mode Exit fullscreen mode

固定每 30 s 很快,但 95% 是浪費:每小時 3,600 次呼叫,幾乎都是空的。固定每 5 分鐘很省,但到處都慢,連最忙的 channel 也一樣。以資源為單位的 backoff,也就是每次 poll 空手而回就把該資源的間隔加倍、一有事件就重置,呼叫次數接近省錢方案,延遲中位數又接近快速方案。原因是忙碌的資源一直維持在 30 s,冷門的則逐漸拉長。代價在上限:設 30 分鐘的話,冷門資源的第一個變更可能要等上半小時。

對 Codex 來說,這張表主要是在說明根本不需要計時器。有人問「改了什麼?」的時候,用已存好的 cursor 跑一輪,每個監看的資源只花一次呼叫,而且到那一刻為止的所有變化都能零延遲回答。Backoff 排程是給那種要讓 Codex 或其他東西持續監看的 script 用的。

Owner 撤銷存取權限時會發生什麼事?

Owner 在 4 h 07 min 把 project 移除。這時 30 個 cursor 全都指向連線讀不到的資源。問題是 client 還會繼續輪詢多久:

owner removes the project at 4 h 07 min (30 resources lose access):
  re-list grants every 10 min    failed polls after removal  180, list_granted_resources calls 25
  re-list grants every 60 min    failed polls after removal 3180, list_granted_resources calls 5
  re-list grants on first error  failed polls after removal    1, list_granted_resources calls 5
Enter fullscreen mode Exit fullscreen mode

用計時器檢查授權,要嘛多花呼叫次數,要嘛浪費掉好幾千次失敗的 poll。把第一次被拒的 poll 當成「重新讀取授權」的訊號,只需要一次失敗加一次額外的 list_granted_resources。接著把資源已經不在清單上的 cursor 全部丟掉。如果 owner 之後又把 project 加回來,client 就從頭開始處理那些資源。

Schema 會在哪些地方擋下 client?

剩下的情況,用 jsonschema(Draft 2020-12)對照正式環境的 inputSchema 檢查:

list_project_resources   no resource_type       REJECT required
list_project_resources   limit 50               ok
list_project_resources   limit 51               REJECT maximum: limit
list_project_resources   graph_session          REJECT enum: resource_type
list_project_resources   search 101 chars       REJECT maxLength: search
poll_resource_events     no after_sequence      ok
poll_resource_events     graph_session          ok
poll_resource_events     after_sequence -1      REJECT minimum: after_sequence
poll_resource_events     limit 100              ok
poll_resource_events     limit 101              REJECT maximum: limit
poll_resource_events     resource_type project  REJECT enum: resource_type
Enter fullscreen mode Exit fullscreen mode

resource_type: "project" 是大家最先會試的。Project 不是一個有 log 的資源,而是讓資源變得可見的那個授權。

整個 script 在 M1 上花了 20.2 s 的實際時間,包含 40 次網路呼叫。User CPU 時間是 0.91 s。

如果你要自己實作

  • 每個資源各自維護一份 log,cursor 交給 client 持有。這樣同一個連線上的兩個讀取者就不會互相搶走事件,server 也不必保存讀取者狀態。
  • 授權清單給它一個專用、不帶參數的 tool,並讓 client 從那裡開始。Discovery 應該只回傳 owner 授權過的東西。
  • 限制每頁大小,並說明怎麼清空(從最後一個 sequence 繼續呼叫,直到拿到不滿的一頁)。
  • Backoff 以資源為單位,不要全域套用。忙碌的資源保持快速,冷門的變得便宜。
  • 第一次 poll 被拒時,重新讀取授權,把已經消失的 cursor 丟掉,而不是一直重試。
  • 處理完事件之後才把 cursor 寫回去,這樣當機時事件會重播,而不是被跳過。

osFoundry 如何決定每個連線能拿到哪些 tool,請看 tool scope 頁面。協定的簡短定義在 MCP 詞彙條目。

Top comments (0)