你在 IDE 裡啟動一個 Coding Agent,要求它修改三個模組、跑完整測試,並在必要時等待批准。

執行到一半,IDE 被關掉了。稍後你從 Web 介面重新打開同一個任務。

這時真正重要的問題不是「聊天紀錄還在不在」,而是:

  • Agent 已經完成哪些步驟?
  • 哪個 Tool Call 已經產生副作用?
  • 是否還有待處理的批准?
  • 使用的是哪一版 Prompt、Tool Catalog、Policy 與 Model Config?
  • 目前可以繼續、暫停、取消,還是必須先恢復 Checkpoint?
  • 兩個 Client 同時按下 Resume 時,誰有權啟動下一個 Worker?

若這些答案只存在 IDE 記憶體或 Transcript 裡,這個任務並沒有真正的 Runtime State。它只有一段看起來像進度的對話。

Runtime 的工作,是維持 Agent 執行時所依賴的世界:狀態、資源、版本、生命週期與控制介面。 Agent Loop 決定下一步做什麼;Runtime 確保那一步發生在一致、可恢復、可追蹤的執行環境裡。

Agent Runtime hosting and state authority

Figure 6-1|Client 可以斷線或更換;Canonical State、Worker Lifecycle 與 Artifact 必須留在可持久化的 Runtime。

Runtime 和 Agent Loop 不是同一件事

Part 03 已經拆過 Agent Loop:模型產生下一步,Tool 執行後把 Observation 放回迴圈,直到完成、等待、失敗或被取消。

Runtime 負責的是另一層問題:

  • Loop 在哪個 Process、Container 或 Sandbox 裡執行
  • Thread、Run、Tool Call 與 Approval 的狀態保存在哪裡
  • Client 斷線後,工作是否仍可繼續
  • Crash 後從哪個 Checkpoint 恢復
  • 哪個 Config Version 綁定這次執行
  • 哪個 Worker 有權操作同一個 Run
  • Pause、Resume、Cancel 與 Fork 如何維持一致性
  • Tool Catalog、Prompt Cache 與 Policy 變更後,哪些衍生狀態必須失效

可以把兩者的關係寫成:

Agent Loop
  decides and executes the next step

Runtime
  hosts, persists, versions and controls the execution world

Loop 可以是一個 while。Runtime 不能只靠一個 while 撐住。

先把幾個容易混在一起的識別單位拆開

Agent 產品常同時出現 Request、Session、Thread、Turn、Run、Task、Workspace 與 Checkpoint。若沒有明確語意,同一個 session_id 很快會被拿來表示三種不同東西。

名稱建議責任不應被誤當成
Request一次 API 或 Client 操作完整任務生命週期
Session一段具有連續身份或環境的互動範圍唯一的業務任務
Thread可持久化的對話與 Agent 工作容器單次模型呼叫
Turn一次輸入所觸發的一段 Agent Work長任務的全部狀態
Run一次受控執行實例,具有狀態、版本與預算Transcript
Task要完成的業務目標與 Completion ContractWorker Process
Workspace檔案、Branch、Sandbox 或其他操作環境對話歷史
Checkpoint某個可恢復執行點的版本化快照與引用任意 Object Dump

實作可以採用不同命名,但必須回答三個問題:

  1. 哪個 ID 代表長期容器?
  2. 哪個 ID 代表這一次執行嘗試?
  3. 哪個 ID 能指向可恢復的狀態?

OpenAI Codex App Server 把 Thread 定義成可持久化容器,Thread 內包含多個 Turn;Thread 可以被 Resume、Fork 與 Archive。這類 Primitive 的價值不在名稱本身,而在生命週期和責任有明確邊界。1

這張表是本文採用的責任模型,不是跨所有產品的命名標準。名稱可以不同,但 Identity、Lifecycle、Ownership 與 Recovery Boundary 不能互相代用,也不能讓同一個 ID 偷偷承擔三種責任。

Runtime 在開始工作前,先要證明自己 Ready

Initialization 不是多印一行 server started

對新 Workspace、複雜 Build、外部服務或預計跨 Session 的任務,Runtime 應先建立後續步驟可依賴的操作基線:

load config
→ validate schema and version
→ initialise storage and state authority
→ discover tools and connected capabilities
→ load policy and sandbox profile
→ verify model availability
→ run baseline checks
→ publish readiness evidence

Readiness Contract 應證明什麼

至少包括:

  • Config 已載入,而且版本可追蹤
  • Model Provider 或 Local Runtime 可用
  • Tool Registry 的 Schema、Handler 與 Policy 一致
  • State Store、Artifact Store 與 Checkpoint Store 可讀寫
  • 必要服務已經 Ready,而不是只啟動 Process
  • Baseline Check 通過,或已知失敗被明確記錄
  • Runtime 能把結果綁定到正確 Tenant、Workspace 與 Task

產生 init.sh、Dockerfile 或 Environment Manifest,只代表初始化有了結構。它不能證明 Dependency 可安裝、Service 可連接、Migration 正確,或 Fresh Session 找得到下一步。

初始化也不應在 Trust Boundary 尚未建立前一次開啟所有能力。比較穩的順序是先載入唯讀工具與最小權限,等身份、Policy、Workspace Scope 與 Storage Ready 後,再開放寫入、External Send 與敏感 Credential。

Runtime Prompt Assembly 不是持續加長一個字串

Part 04 已經處理 Context Builder。進入 Runtime 後,這些 Context 還要與 Agent Identity、Invariant Policy、Tool Guidance、Workspace State、Budget 與輸出模式組成實際送給模型的 Prompt。

一個可治理的 Prompt Assembly,至少要區分兩類 Section。

Stable sections

適合形成可重用 Cache Prefix:

  • Agent identity 與 operating principles
  • invariant policies
  • stable output conventions
  • 長期穩定的 Tool Guidance

Dynamic sections

每次 Run、Turn 或 Workspace 可能改變:

  • tenant、workspace、branch 與 environment
  • 當前 Task Contract 與 phase
  • tool catalog version
  • connected MCP servers 或 plugins
  • policy snapshot
  • memory index generation
  • current budget、deadline 與 output mode

每個 Section 應有 owner、version、priority、token budget 與 omission reason。組裝後保存 Prompt Manifest,Replay 時才知道當時模型看到哪一版資訊。

Cache Boundary 必須跟著真實依賴

只要以下任一項改變,相關 Cache 就可能失效:

  • Agent Config Version
  • Prompt Section Version
  • Tool Catalog Version
  • Policy Version
  • Workspace Ref
  • Tenant Scope
  • Memory Index Generation
  • Connected Server Set

最危險的 Cache 不是完全壞掉,而是安靜地回傳一個舊世界。Agent 會很有自信地操作已經不存在的 Tool、過期的 Schema 或錯誤 Branch。

Model Adapter 統一介面,但不能抹平語意

Runtime 通常不希望業務工作流直接依賴某一家 Provider SDK 的 Response Shape,因此會建立內部 Model Adapter,統一:

  • messages 或 input items
  • tool schemas
  • structured output
  • streaming
  • usage
  • finish/stop reason
  • provider request ID
  • errors 與 retryability
  • optional reasoning metadata

概念介面可能長這樣:

class ModelAdapter(Protocol):
    async def generate(
        self,
        *,
        input_items: list[InputItem],
        tools: list[ToolSchema],
        model_profile: ModelProfile,
    ) -> ModelResponse:
        ...

這段只能說明業務層不應直接耦合 Provider Response。它不能證明不同模型的 Tool Semantics、Streaming Event、Stop Reason 或 Structured Output 能被無損轉換。

例如兩個 Provider 都回傳 tool_call,不代表它們在 parallel calls、partial arguments、cancellation 或 reasoning item 上具有完全相同的語意。Adapter 應明確暴露 capability difference,而不是為了介面漂亮把差異吞掉。

更安全的 Adapter 會維護 Capability Matrix,並把轉換結果標成:

  • supported
  • degraded
  • emulated
  • unsupported
  • lossy

若 Runtime 只能把一個 Provider 的 Rich Approval Event 壓成普通文字,它應留下 Loss Flag,或拒絕啟用依賴該語意的功能。靜默降級最危險,因為上層 Workflow 仍會以為完整 Contract 被保留下來。

Canonical RunState:Runtime 真正相信的執行生命週期

可靠 Runtime 應為每個 Run 維持一個可持久化的 Lifecycle Authority。

這裡的「Canonical」不是宣稱 RunState 取代所有外部真相。Database 仍對自己的資料持有 Authority,Git Remote 仍對 Push Result 持有 Authority,Payment Provider 仍對交易結果持有 Authority。RunState 的責任是記錄:

  • 這個 Run 目前位於哪個合法狀態
  • 哪些 Operation 已提出、已授權、已送出或結果未知
  • 哪些外部 Authority 必須被查詢或 Reconcile
  • 哪個 Worker 目前有權提交下一個 Transition
  • 哪一版 Contract、Config、Policy 與 Catalog 約束這次執行

因此,一個 RunState 至少要涵蓋:

  • identity:run、thread、turn、task、tenant、user、workspace
  • contract:goal、scope、completion criteria
  • configuration:agent、prompt、tool catalog、policy、model profile 版本
  • execution:current phase、step、attempt、active worker
  • concurrency:state version、worker epoch、lease expiry、fencing token
  • model interactions:request IDs、stop reasons、usage
  • tool operations:call ID、arguments digest、terminal result、external operation ID、reconciliation state
  • control:pause、cancel、approval、deadline、budget
  • evidence:artifact、test、trace 與 verification references
  • recovery:checkpoint pointer、resume cursor、last committed sequence
  • terminal state:completed、failed、cancelled、waiting 與 stop reason

以下是一個示意性的 RunState 摘要:

{
  "run_id": "run_108",
  "thread_id": "thread_42",
  "task_id": "task_checkout_fix",
  "tenant_id": "tenant_acme",
  "workspace_id": "ws_701",
  "status": "waiting_for_approval",
  "phase": "verification",
  "state_version": 37,
  "worker": {
    "worker_id": "worker_a",
    "epoch": 9,
    "fencing_token": 1482,
    "lease_expires_at": "2026-07-08T11:30:00Z"
  },
  "config": {
    "agent_version": "agent-17",
    "tool_catalog_version": "tools-4",
    "policy_version": "policy-12",
    "model_profile": "safe-default"
  },
  "active_operation": {
    "tool_call_id": "call_88",
    "operation_id": "op_771",
    "state": "approval_required",
    "arguments_digest": "sha256:example-only"
  },
  "budget": {
    "max_cost_usd": 4.0,
    "spent_cost_usd": 1.37
  },
  "checkpoint_id": "cp_31",
  "last_committed_sequence": 284
}

這個例子說明 Identity、Version、Worker Ownership、Control 與 Recovery 指標都屬於 Runtime State。

它不能證明:

  • State Machine 已正確實作
  • Fencing Token 真的被所有寫入路徑檢查
  • External Side Effect 可以安全重播
  • Approval 沒有被另一個 Operation 消耗
  • max_cost_usd: 4.0 是合理 Production Budget
  • JSON 可以取代 Event Log、Artifact Store、External Authority 或 Database Transaction

數字與 Digest 都只是示意。

Transcript and Canonical RunState

Figure 6-2|Transcript 是互動投影;Canonical RunState 保存執行生命週期、版本、Worker Ownership、控制狀態與外部 Operation Reference。

Transcript 很重要,但不能當唯一 State Store

Transcript 適合保存:

  • User Message
  • Agent Message
  • Model-visible Tool Request/Result
  • 對話中公開的 Plan 與說明

但有些資訊不應只靠 Transcript 表達:

  • Policy Snapshot 與授權決策
  • Worker Lease
  • Tool Operation 的外部 ID
  • 已提交但回應未知的副作用
  • Budget Counter
  • Schema Version
  • Checkpoint Commit Status
  • Pending Approval 的 expiry 與 terminal result
  • Artifact 的 Durable Location

Transcript 也可能被 Compaction、Redaction 或 UI Filtering 改寫。Runtime State 則必須能回答「系統現在可以合法做什麼」,而不只是「模型曾經說過什麼」。

Anthropic Agent SDK 的 Session Resume 可以延續先前讀過的檔案、分析與對話;Claude Managed Agents 的 Session 則進一步把事件、Sandbox Checkpoint 與恢復生命週期做成服務端能力。這些產品實作不同,但共同說明 Session Continuity 需要 Runtime 支援,不能只把前一段文字重新貼回 Prompt。23

Checkpoint 保存的是可恢復事實,不是整包 Object Dump

Checkpoint 的目的,是讓 Runtime 在中斷後重建一個合法且可判定的狀態。

安全的 Checkpoint Boundary 通常落在 Durable Commit 之後

run_created
model_response_committed
pre_effect_intent_committed
tool_result_or_unknown_outcome_committed
approval_wait_committed
verification_result_committed
control_signal_applied
run_terminal

tool_call_authorised 本身不一定是可重播 Checkpoint。若 Runtime 已取得批准、已送出 External Request,卻還沒保存 Receipt,恢復後不能簡單地把 Tool 再跑一次。

Checkpoint 至少需要:

  • schema version
  • policy、safety overlay 與 config reference
  • workflow/agent phase
  • committed event sequence
  • message、evidence 與 artifact references
  • pending operation、approval 與 background work context
  • completed 或 unknown side-effect operation IDs
  • worker epoch/fencing token
  • current attempt、waiting reason 與 stop reason
  • restore validation result

Snapshot、Checkpoint、Event Log 與 Replay 是不同能力

  • Snapshot:某一時刻的狀態投影。
  • Checkpoint:經 Runtime 宣告可作為恢復起點的 Versioned Recovery Point。
  • Event Log:記錄已提交的 Transition 與順序。
  • Replay:用事件、Artifact 與外部 Evidence 重建或模擬 Trajectory。
  • External Reconciliation:向真正持有 Side-effect Authority 的系統確認結果。

序列化 Python Object 或完整 Transcript,可能仍然無法回答:

  • Payment API 是否已接受 Request
  • Git Push 是否成功但 Response 遺失
  • Approval 是否已被消耗
  • Tool Result 是否已寫入 State Store
  • 舊 Worker 是否仍持有過期 Lease

恢復流程應先驗證:

  1. Checkpoint Schema 與 Config 是否可讀。
  2. State Version 與 Event Sequence 是否連續。
  3. Workspace、Artifact 與 Tool Catalog Reference 是否仍有效。
  4. Unknown Outcome 是否先 Reconcile。
  5. 新 Worker 是否取得更高 Fencing Token。
  6. Resume 是否從一個合法 Transition 開始。

Side-effect Reconciliation、Idempotency 與 Compensation 會在 Part 08 展開。Part 06 先固定邊界:Checkpoint 是一個受驗證的恢復承諾,不是「我們有把 Object 存下來」。

Runtime Control Plane:控制正在執行的工作

長時間或背景 Agent 需要把 Data Plane 與 Control Plane 分開。

Data Plane

負責:

  • Model Call
  • Tool Execution
  • Observation
  • State Transition
  • Artifact Production

Control Plane

負責:

  • Status Query
  • Pause/Resume/Cancel
  • Fork
  • Approval 與補充資訊
  • Budget 或 Deadline Update
  • Safety Overlay、Credential Revocation 與 Kill Switch
  • Drain/Shutdown
  • 經測試的 Config Migration

控制命令不能只是 Client 傳一個 Boolean,然後希望 Worker 剛好看到。

每個 Command 至少需要:

  • command ID
  • actor 與 authority
  • target run/thread
  • expected state version
  • idempotency key
  • requested effect
  • acceptedappliedrejectedexpired 結果
  • audit event

accepted 只代表 Runtime 已接收控制意圖;applied 才代表狀態在合法 Transition 上真正改變。

Safe Point:一致性變更不能硬切在半途

若 Agent 正在執行不可逆 Tool Call,收到 Pause 時立刻殺掉 Process,可能把系統留在「副作用已發生,但 Result 尚未持久化」的縫隙裡。

Runtime 應在 Safe Point 檢查控制訊號,例如:

  • Model Call 前後
  • Tool Execution 前
  • Tool 完成且 Result Durable 後
  • Workflow State Transition 前後
  • Checkpoint Commit 後

狀態需要分開:

pause_requested → pausing → paused
cancel_requested → cancelling → cancelled
resume_requested → claiming → running

Cancel requested 不等於 CancelledPause requested 也不代表當下已可 Resume。

Resume 還需要新的 Worker Ownership。當兩個 Client 同時按下 Resume 時,Server 應把兩個 Request 去重或排序,只有一個 Claim 能透過 Compare-and-swap 取得新的 Worker Epoch 與 Fencing Token。

Runtime control plane and safe points

Figure 6-3|Control Command 先被接受,再在 Safe Point 套用;Resume 只有在取得新 Worker Epoch 與 Fencing Token 後才能回到 Running。

Worker Lease 不足以單獨防止 Split Brain

Lease 告訴系統 Worker 在某段時間內被視為 Owner,但舊 Worker 可能因網路分割或長時間停頓,在 Lease 到期後仍繼續工作。

因此 State Store 與 Side-effect Gateway 應檢查單調遞增的 Fencing Token

worker A obtains token 41
lease expires
worker B obtains token 42
worker A attempts commit with token 41
→ rejected as stale

關鍵 Write 應同時驗證:

  • expected state version
  • current worker epoch
  • fencing token
  • operation ownership
  • cancellation/terminal state

只有 Heartbeat 而沒有 Fencing,仍可能讓兩個 Worker 各自認為自己是 Owner。

Fork 不是複製一段聊天文字

Fork 通常需要:

  • 來源 Thread/Checkpoint
  • 新的 Thread 或 Run Identity
  • Parent/Child 關係
  • Artifact 的 Share/Copy-on-write 規則
  • Workspace Clone、Isolation 與 Merge Policy
  • Config Pinning
  • Credential 與 Policy 重新判斷
  • 新的 Worker Ownership
  • 後續 Merge 是否允許

OpenAI Codex App Server 的 thread/fork 會從既有 Thread 建立新的 Thread Identity,並保留來源關係。這比複製 Transcript 多了一個重要保證:來源 History 與 Fork Identity 是 Protocol 的一部分。4

Fork 後的兩個分支不能暗中共用可變 Workspace。若 Artifact 共享,應是 Immutable Reference 或 Copy-on-write,而不是兩個 Run 同時改同一份未受控狀態。Workspace Isolation 與 Multi-agent Claim 會在 Part 07 深入。

Hosting Boundary:Client 不是 Runtime

當 Agent 只在本機 CLI 裡跑,Client Process、Agent Process 與 Workspace 可能暫時綁在一起。搬到 Web、IDE、Remote Worker 或 Multi-tenant Service 後,就會遇到標準 Distributed Systems 問題:

  • 誰 Spawn Worker
  • 同一 Thread 的事件路由到哪裡
  • Client 斷線後如何 Reconnect
  • Worker Crash 後誰重新 Claim
  • Idle Runtime 何時 Reclaim
  • Drain 時如何阻止新工作
  • Session、Artifact、Credential 與 Workspace 如何綁定 Tenant

常見分層是:

Clients
  CLI / IDE / Desktop / Web

Bidirectional protocol

Harness Service
  auth / routing / thread manager / control commands

Agent Runtime Workers
  model loop / tools / sandbox

Durable State / Event / Checkpoint / Artifact Stores

Client 負責 Render、Input 與 Interaction。Harness Service 持有 Routing 與 Control Authority;Worker 執行 Data Plane;Durable Stores 保存可重建狀態。

OpenAI Codex App Server 是一個具體例子:App Server 管理 Core Threads,讓不同 Client 共用相同 Harness。Client 可以處理 Streaming、Diff 與 Approval,Thread History 和 Runtime Ownership 留在 Server。1

Session Routing 必須同時綁定 Identity、Version 與 Worker Ownership

只有 thread_id 不足以安全路由。

Runtime 通常還要驗證:

  • tenant ownership
  • user/service identity
  • workspace ownership
  • region/data residency
  • expected state version
  • current worker epoch/fencing token
  • active lease
  • allowed client capability
  • terminal/archived/deleted state

路由層若只看 ID,取得另一個 Thread ID 的 Client 可能讀到錯誤事件,或對不屬於自己的 Run 發送 Resume。

Resume 也不是「找一個 Worker 開始跑」這麼簡單。它應執行:

authorise command
→ compare expected state version
→ acquire new lease and fencing token
→ restore and validate checkpoint
→ commit owner transition
→ start worker

完整 Credential Binding 與 Tenant Isolation 留到 Part 09。Part 06 的責任邊界是:State Routing、Identity Routing 與 Worker Ownership 必須由同一條可稽核的控制路徑協調。

Agent Config 應該是可部署 Artifact

Prompt、Toolset、Model Profile、Policy、Verifier、Sandbox 與 Output Contract 都會改變 Agent 行為。若它們散落在環境變數、資料庫欄位和程式碼條件裡,一次 Run 失敗後很難重建當時的執行條件。

可版本化的 Agent Config Manifest 可以長這樣:

agent_version: agent-17
prompt_bundle: prompt-9
tool_catalog: tools-4
policy_bundle: policy-12
model_profile: safe-default
verifier_suite: verifier-8
sandbox_profile: sandbox-3
protocol_schema: app-server-v2
artifact_digest: sha256:example-only

這個範例能說明要 Pin 哪些行為輸入。

它不能證明:

  • 這些版本彼此相容
  • safe-default 已通過 Evaluation
  • Rollback 不會遇到 Schema 或 Migration 衝突
  • SHA-256 範例對應真實 Artifact

sha256:example-only 明確是示意值。

Pinned Config 不等於凍結所有安全控制

為了可重現,Run 通常 Pin Prompt Bundle、Tool Catalog、Model Profile、Verifier Suite、Sandbox Profile 與一般 Behaviour Policy。

但緊急安全控制不能被舊 Run 永久繞過。Credential Revocation、Tenant/Enterprise Hard Deny、Compromised Tool Disable、Kill Switch 與 Data-egress Block 可以作為較高 Authority 的 Runtime Overlay 生效。

這類 Overlay 應有 Version、Reason、Authority 與 Audit,並在下一個 Safe Point 觸發 Deny、Pause 或 Stop。它不是把 agent-17 偷偷改寫成 agent-18,而是在保留原始 Config Pin 的同時增加可追溯的安全約束。

Create、Evaluate、Promote 與 Migrate 是不同動作

較安全的 Release Flow 是:

Create immutable config version
→ run pinned evaluations
→ review evidence
→ canary or shadow
→ promote deployment pointer
→ monitor
→ roll back pointer when required

建立版本,不代表它可以進 Production;Evaluation 通過,也不代表有權修改 Deployment Pointer。

核心原則:

  • 每個 Run 記錄精確 Config Version
  • Production 不直接指向 latest
  • Promotion 是受控操作
  • 新 Run 解析 Deployment Pointer 後 Pin 到 Immutable Version
  • 已開始的 Run 通常保留原本版本
  • 若要把 In-flight Run 遷移到新 Config,必須有獨立 Compatibility Check、Migration Plan 與 State Transition
  • Eval Dataset、Grader 與 Threshold 也要版本化
  • Deployment Pointer Update 使用 Expected Version/Optimistic Concurrency
  • Emergency Safety Overlay 不需要把 Run 遷移到新 Behaviour Config 才能生效

Anthropic 目前的 Claude Managed Agents 把可版本化 Agent Definition、Environment 與 Stateful Session 分成不同 Resource。官方文件在 2026 年 7 月仍標示 Managed Agents 為 Beta,並要求 managed-agents-2026-04-01 Beta Header。本文引用的是責任分離,不把目前欄位形狀當成永久標準。56

Rollback 不只是換回舊 Prompt

Rollback 前至少要檢查:

  • 舊 Tool Schema、Handler 與依賴是否仍存在
  • Data Migration 是否向後相容
  • 舊 Runtime 能否讀取新版 Session/Checkpoint State
  • 新版建立的 Artifact 是否能被舊版理解
  • Client Protocol 是否仍支援
  • 哪些 In-flight Run 留在新版
  • 哪些新 Run 改由舊 Deployment Pointer 啟動
  • Safety Overlay/Credential Revocation 是否仍然有效

Rollback 通常只移動「新 Run 要使用哪個 Config」的 Pointer。它不會讓已發生的 Side Effect、Data Migration 或 Artifact Schema 自動倒帶。

Agent configuration promotion and rollback

Figure 6-4|Immutable Config 經 Evaluation 與 Canary 後才更新 Deployment Pointer;In-flight Run 保留原始 Pin,Safety Overlay 則可獨立阻止危險行為。

Protocol Versioning:先明確協商,再使用能力

Agent Client 與 Harness Runtime 會獨立演進。新版本可能加入 Streaming Delta、Rich Approval UI、Diff Rendering、Image Artifact、Thread Fork、Remote Workspace、Plan State 或 Experimental Event。

若 Server 假設每個 Client 都支援全部功能,舊 Client 可能收到自己無法呈現或回應的 Event。

需要保留的通用不變式是:

在使用某項 Operation 前,雙方必須明確知道 Protocol Version、Peer Identity、Capability 與不相容時的行為。

協商不一定永遠長成同一種 Handshake。

Connection-scoped negotiation

OpenAI Codex App Server 目前要求每個 Transport Connection 先送出一次 initialize,並以 Capability Opt-in 區分 Stable 與 Experimental Surface。4

MCP 最新穩定規格在 2026 年 7 月仍是 2025-11-25。該版本把生命週期分成 Initialization、Operation 與 Shutdown,並在初始化階段協商 Protocol Version 與 Capabilities。78

Client
  supported versions
  client identity
  capabilities
        ↓ initialize
Server
  selected version
  enabled capabilities
  warnings / deprecations
        ↓ initialized
Normal operation

Request-scoped or stateless negotiation

MCP 官方 Draft 正在探索不同模型,包括移除 Connection-level Session 與 initialize Handshake,改由 Discovery 或每個 Request 攜帶 Version/Capability Metadata。Draft 不是最新穩定規格,但它提醒我們:核心原則是顯式相容性,不是永遠固定使用某一個 Method Name。9

因此 Runtime 要版本化的通常不只有 Protocol Number:

  • Message Schema
  • Error Code
  • Event Type
  • Capability Name
  • Experimental Extension
  • Client Fallback
  • Unknown-field Handling
  • Deprecation/Removal Window

Protocol versioning and capability negotiation

Figure 6-5|Runtime 可採 Connection-scoped Handshake 或其他顯式協商模式;共同要求是在正式 Operation 前建立可驗證的 Version 與 Capability Contract。

Pinned Binary 與 Decoupled Server 各有代價

Pinned Binary

Client 綁定一個已測試的 Harness Binary。

優點:

  • 行為可重現
  • Compatibility Surface 較小
  • Client 與 Runtime 可以一起驗證

代價:

  • Runtime 修復要等 Client Release
  • 多個 Client 版本容易分叉

Decoupled Server

穩定 Client 連接較新的 Backward-compatible Server。

優點:

  • Runtime 修復與新能力可獨立上線
  • 多個 Client 共用同一 State Authority

代價:

  • 需要嚴格 Protocol Contract
  • 要測 Old Client/New Server 等 Compatibility Matrix
  • Unknown Field、Unavailable Feature 與 Fallback 必須有定義

沒有絕對比較高級的選項。選擇取決於 Release Cadence、風險、離線需求與 Compatibility Testing 能力。

Resource Lifecycle:Archive 和 Delete 不是同一件事

Runtime 會持續累積:

  • Agent Config
  • Session/Thread/Run
  • Workspace/Environment
  • Credential Grant
  • Memory Store
  • Artifact
  • Checkpoint
  • Evaluation Run

每種資源都要定義:

active → idle → archived → deleted
              ↘ retained for audit

Archive

停止 Live Resource、釋放運算或 Quota,但保留 Audit、Artifact 與 Retrieval Record。

Delete

移除紀錄,通常還要考慮 Retention、Legal Hold、Tenant Export、Deletion Request 與 Audit Tombstone。

封存 Parent 也不應暗示所有 Child Resource 都自動被刪除。Workspace、Credential、Memory 與 Artifact 需要明確 Cascade Policy。

大多數 Production Cleanup 應先 Archive,再按 Retention Policy Delete。直接把 Cleanup 寫成遞迴刪除,速度很快,事故報告通常也會寫得很長。

Dynamic Tool Pool 與 Cache 必須保持同一個世界版本

Part 05 已經處理 Dynamic Tool Discovery。到了 Runtime,問題變成:外部 MCP Server 連上、Plugin 啟用、Tool 撤回或 Policy 改變後,所有相關狀態是否一起更新。

以下內容必須維持一致:

  • model-visible Tool Schemas
  • execution handlers
  • permission policy
  • prompt tool guidance
  • discovery index
  • audit metadata
  • subagent inherited catalog
  • eval/replay manifest

Catalog Assembly 應具有 deterministic collision policy,不能依 Dictionary Insertion Order 默默決定哪個同名 Tool 勝出。

Tool Catalog 改變後,通常要失效:

  • Model Request Tool Schema Cache
  • 描述工具的 Prompt Section
  • Semantic Discovery Index
  • Authorization Decision Cache
  • Derived Repository/Capability Context
  • Replay Manifest

Remote Server 自稱 Tool 是 readOnlyidempotent,只能成為 Policy Input,不能直接變成安全保證。

若 Server 斷線,Runtime 也應把 Active Call 移到 Known State,增加 Catalog Version,並對使用舊 Catalog 的 Model Call 回傳結構化的 unavailable,而不是偷偷改用另一個 Handler。

用一個背景程式碼遷移任務走一次

假設使用者在 IDE 啟動任務:

把舊的付款狀態列舉遷移到新版 Schema,修改相關程式與測試,但不要執行 Production Migration。

1. Initialization

Runtime 驗證:

  • Repository 與 Branch 正確
  • Workspace 可重現
  • Test Database 可用
  • Production Credential 沒有注入
  • Tool Catalog、Policy 與 Sandbox Ready

2. Create Run

建立 run_id,綁定:

  • Task Contract
  • Workspace
  • Agent Config Version
  • Model Profile
  • Policy Snapshot
  • Budget

3. Execute and checkpoint

Agent 讀取 Schema、修改程式、跑測試。每個 Tool Result 先持久化,再更新 RunState 與 Checkpoint Pointer。

4. Client disconnects

IDE 關閉。Worker 可以繼續,或在 Safe Point 暫停。事件、Artifact 與 State 不依賴 IDE 記憶體。

5. Resume from Web

Web Client 完成 Initialize Handshake,取得支援的 Capability,驗證 Thread Ownership,讀取 Snapshot 與 Missing Events。

6. Approval required

Agent 準備執行一個會修改 Test Database 的 Migration。Runtime 將 Run 移到 waiting_for_approval,保存 Pending Operation 與 expiry。

7. Config promoted during the wait

Production Pointer 已升級到 agent-18,但這個 Run 仍使用建立時綁定的 agent-17,除非有經驗證的 Migration Procedure。

8. Complete

測試、Diff 與 Artifact 被 Verifier 接收後,Run 才進入 Terminal State。Client 顯示完成,但 Pass Authority 不在 Client。

這個案例的關鍵不在於 UI 可以跨裝置接續,而是每個狀態轉移都有唯一 Authority、版本與持久化證據。

用十二個問題審查一套 Agent Runtime

  1. Client 關閉後,哪個系統仍持有 Canonical Run Lifecycle?
  2. Thread、Turn、Run、Task、Workspace 與 Checkpoint 是否各有單一責任?
  3. Startup Readiness 由哪些可重跑 Evidence 證明?
  4. Model Adapter 是否暴露 unsupporteddegradedlossy 差異?
  5. RunState 如何關聯 External Authority,而不是假裝取代它?
  6. Checkpoint 是否位於 Durable Commit 後,並能辨識 Unknown Outcome?
  7. Pause、Resume、Cancel 與 Fork 是否有 acceptedappliedrejected 結果?
  8. 兩個 Worker 競爭同一 Run 時,Lease、State Version 與 Fencing Token 如何防止 Split Brain?
  9. 哪些 Behaviour Config 被 Pin?哪些 Emergency Safety Overlay 可立即收緊權限?
  10. Promotion、Migration 與 Rollback 是否具有不同 Authority 與 Compatibility Gate?
  11. Protocol 相容性是 Connection Handshake、Request Metadata,還是其他顯式 Contract?
  12. Archive、Delete、Retention 與 Cascade 是否對每種 Resource 分開定義?

若答案仍是「UI 記得」、「我們目前只有一個 Worker」或「直接使用 latest」,這套 Runtime 還沒有成為可靠系統。


理論轉實作:Part 06 檢查表

  • Runtime 與 Agent Loop 的責任明確分離。
  • Initialization 具有 Evidence-based Readiness Contract。
  • Thread、Turn、Run、Task、Workspace 與 Checkpoint 各有明確語意。
  • 每個 Run 有一個 Durable Lifecycle Authority,同時保留 External Authority Reference。
  • Transcript 不承擔 Worker、Approval、Budget、Side Effect 與 Recovery 的唯一狀態。
  • Checkpoint 只在可驗證的 Durable Boundary 建立,並能區分 Unknown Outcome。
  • Pause、Resume、Cancel 與 Fork 使用明確 State Machine 與 Idempotent Command Result。
  • Worker Ownership 使用 Lease、Expected State Version 與 Fencing Token。
  • Config Pinning、In-flight Migration 與 Emergency Safety Overlay 分開。
  • Config Create、Evaluate、Promote、Rollback 由不同 Authority 與 Compatibility Gate 控制。
  • Protocol/Capability Compatibility 在正式 Operation 前明確建立,不依賴固定 Vendor Method。
  • Archive、Delete、Retention、Cascade 與 Dynamic Catalog Invalidation 分開治理。

Part 07 會處理下一個問題:Runtime 已經能保存狀態後,工作如何跨 Session、Context Window 與多個 Agent 延續,而且不重做、不搶同一項任務,也不讓兩個 Workspace 互相踩踏。答案會落在 Progress Ledger、Handoff Contract、Atomic Claim 與 Workspace Isolation。

References

Footnotes

  1. OpenAI, Unlocking the Codex harness: how we built the App Server, 4 February 2026. 2

  2. Anthropic, Agent SDK overview, accessed 8 July 2026.

  3. Anthropic, Claude Managed Agents: Session event stream, accessed 8 July 2026. The Managed Agents API is marked Beta in the current documentation.

  4. OpenAI Developers, Codex App Server, accessed 8 July 2026. 2

  5. Anthropic, Claude Managed Agents overview, accessed 8 July 2026.

  6. Anthropic, Claude API overview, accessed 8 July 2026. The Agents, Sessions and Environments APIs are marked Beta in the current documentation.

  7. Model Context Protocol, Lifecycle, specification version 2025-11-25, accessed 8 July 2026.

  8. Model Context Protocol, Specification 2025-11-25, accessed 8 July 2026. The official site labelled this the latest stable version on that date.

  9. Model Context Protocol, Draft: Key Changes, accessed 8 July 2026. Draft material is cited only to show that negotiation shape may evolve; it is not treated as the stable protocol.