CHAPTER 12 · SESSION RUNTIME
Session Actor:线程、状态与取消边界
每个 Session 在独立 OS 线程上运行 current-thread Tokio runtime 与 LocalSet。SessionActor 协调 turn,ChatStateActor 串行拥有对话状态,CancellationToken 负责协作式终止。
课程目标
能解释线程隔离、Actor 状态所有权和取消信号如何配合,并准确描述 Agent 的「有效不可变」边界。
能解释线程隔离、Actor 状态所有权和取消信号如何配合,并准确描述 Agent 的「有效不可变」边界。
核心视觉 · 教学化运行时图
Turn loop 的真实职责
SessionActor 协调
run_session同时接收 SessionCommand、ChatStateEvent、SessionEvent 与 turn completion。maybe_start_running_task启动待处理 turn。- turn 完成后执行 completion、turn end 和后续通知处理。
ChatStateActor 拥有状态
- 专属拥有 conversation、token、配置与 persistence。
- 通过
mpsc::UnboundedReceiver串行处理命令。 - 取消 token 触发退出,全部 handle 被丢弃也会结束循环。
Agent 的真实字段边界
definitionAgentDefinition,定义身份、模式与策略输入。
prompt_context支持检查、重渲染与序列化的 PromptContext。
system_prompt从 prompt context 渲染并缓存的字符串。
tool_bridgeArc<ToolBridge>,工具注册与会话上下文桥梁。
reminder_policySession 级 reminder 策略。
compaction_policy自动压缩、memory flush 和 two-pass 配置。
hosted_tools发送给 API 的后端托管工具定义。
backend_search_enabled构建时的服务端搜索开关。
准确表述:源码注释称 Agent 构建后「effectively immutable」。它仍提供
finalize_prompt(&mut self) 更新构建时间并重新渲染 prompt,所以不能描述成绝对不可变。真实源码证据
crates/codegen/xai-grok-shell/src/session/acp_session_impl/spawn.rs
let join_handle = std::thread::Builder::new()
.name(thread_name)
.stack_size(8 * 1024 * 1024)
.spawn(move || {
let rt = tokio::runtime::Builder
::new_current_thread().enable_all().build()?;
let local = tokio::task::LocalSet::new();
});
.name(thread_name)
.stack_size(8 * 1024 * 1024)
.spawn(move || {
let rt = tokio::runtime::Builder
::new_current_thread().enable_all().build()?;
let local = tokio::task::LocalSet::new();
});
crates/codegen/xai-grok-agent/src/agent.rs
/// Re-render the system prompt
pub async fn finalize_prompt(&mut self) {
self.prompt_context.build_timestamp_utc =
chrono::Utc::now().to_rfc3339();
self.system_prompt = self.prompt_context
.render(&self.tool_bridge).await
.unwrap_or_default();
}
pub async fn finalize_prompt(&mut self) {
self.prompt_context.build_timestamp_utc =
chrono::Utc::now().to_rfc3339();
self.system_prompt = self.prompt_context
.render(&self.tool_bridge).await
.unwrap_or_default();
}
源码快照说明:本页依据本地同步副本核对。该副本没有
.git 元数据,因此不声称对应某个 commit 版本。课堂练习
给状态找唯一拥有者
把 conversation、system_prompt、tool registry、sampling request 分别放到 ChatStateActor、Agent、ToolBridge、SamplerActor。再说明取消 token 与消息优先级属于不同概念,本源码没有「高优先级消息插入队首」的通用设计。
Takeaway:Session 的隔离单位是 OS 线程加 LocalSet。SessionActor 负责 turn 编排,ChatStateActor 拥有对话状态,CancellationToken 负责取消。Agent 以有效不可变为主,同时保留显式重渲染入口。