base/context/session.rs
1//! 会话状态的契约:引擎从设置推出来的 `SessionEnv`、写进会话日志的 `DurableState`、
2//! 工具与策略经 `Arc<dyn Session>` 看到的 `Session` trait,以及绑定任务生命周期的
3//! `TaskScope` / `TaskLease`。实现在 `session-state` crate,是这个 trait 唯一的实现。
4
5use super::goal::{GoalAction, GoalError, GoalView, TurnOrigin};
6use super::ledger::SessionLedger;
7use super::task::{RunningStatus, RunningTask, TaskInfo, TaskType, TodoItem};
8use crate::interface::exec::ExecProviders;
9use crate::permission::PermissionMode;
10use crate::tool::Tool;
11use std::collections::HashSet;
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use tokio_util::sync::CancellationToken;
15
16/// One `Read` whose result went to the model.
17#[derive(Debug, Clone, Copy)]
18pub struct ReadRecord<'a> {
19 pub path: &'a Path,
20 pub offset: Option<usize>,
21 pub limit: Option<usize>,
22 /// The call whose result holds what was read.
23 pub tool_use_id: &'a str,
24 /// The result showed less of the range than was asked for: it stopped at
25 /// the default line count, or cut lines at their length cap.
26 pub cut_short: bool,
27}
28
29impl<'a> ReadRecord<'a> {
30 /// All of `path`, shown whole.
31 pub fn whole(path: &'a Path, tool_use_id: &'a str) -> Self {
32 Self {
33 path,
34 offset: None,
35 limit: None,
36 tool_use_id,
37 cut_short: false,
38 }
39 }
40}
41
42/// What the model holds of a file it read before.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum HeldRead {
45 /// All of the range it asked for.
46 Whole,
47 /// What a repeat of that read would show again, but not all of the range.
48 CutShort,
49}
50
51/// What the engine running a session derives from its settings and scene.
52/// Each engine brings its own, and attaching an engine replaces the
53/// session's whole.
54#[derive(Debug, Clone, Default)]
55pub struct SessionEnv {
56 pub cwd: PathBuf,
57 /// Directories a relative deny or ask path rule is also read against,
58 /// besides `cwd`: the project root, for a session working in one of its
59 /// worktrees. An allow is read against `cwd` alone.
60 pub refusal_rule_roots: Vec<PathBuf>,
61 /// 用户级附加可写目录(`files.extra_dirs`)—— Tool 在做路径校验时用
62 pub additional_writable_dirs: Vec<PathBuf>,
63 /// Directories outside the project the file tools may read without
64 /// asking — `files.read_dirs`.
65 pub read_directories: Vec<PathBuf>,
66 /// `files.read_dirs` holding `/`.
67 pub read_anywhere: bool,
68 /// Package and build caches a sandboxed command may write —
69 /// `sandbox.cache_dirs`; a `~/` path is expanded when the command
70 /// runs.
71 pub cache_directories: Vec<PathBuf>,
72 /// Nobody answers this session's questions or permission prompts — see
73 /// `SceneSpec::interactive`.
74 pub unattended: bool,
75 /// The permission mode the engine runs the session in: the one decided
76 /// for the session, not necessarily its settings' `permissions.mode`.
77 pub base_mode: PermissionMode,
78 /// The host's skill directories this session lists: readable without
79 /// asking, like `read_directories`, and changed without a rebuild.
80 pub skill_dirs: LiveDirs,
81 /// Every host skill directory a session in this process has listed, and
82 /// the directory of each of the host's own packages: no tool writes
83 /// under one, in any permission mode, and no sandboxed command.
84 pub protected_dirs: LiveDirs,
85}
86
87/// A list of directories shared by everything handed a clone and replaced
88/// in place, so a session's tools see a change without the session being
89/// rebuilt.
90#[derive(Debug, Clone, Default)]
91pub struct LiveDirs(Arc<std::sync::RwLock<Vec<PathBuf>>>);
92
93impl LiveDirs {
94 pub fn get(&self) -> Vec<PathBuf> {
95 self.0
96 .read()
97 .unwrap_or_else(std::sync::PoisonError::into_inner)
98 .clone()
99 }
100
101 pub fn set(&self, dirs: Vec<PathBuf>) {
102 *self
103 .0
104 .write()
105 .unwrap_or_else(std::sync::PoisonError::into_inner) = dirs;
106 }
107
108 /// Adds those of `dirs` not listed yet; removes nothing.
109 pub fn extend(&self, dirs: impl IntoIterator<Item = PathBuf>) {
110 let mut held = self
111 .0
112 .write()
113 .unwrap_or_else(std::sync::PoisonError::into_inner);
114 for dir in dirs {
115 if !held.contains(&dir) {
116 held.push(dir);
117 }
118 }
119 }
120
121 /// The listed directory `path` is in or is.
122 pub fn holding(&self, path: &Path) -> Option<PathBuf> {
123 self.0
124 .read()
125 .unwrap_or_else(std::sync::PoisonError::into_inner)
126 .iter()
127 .find(|dir| path.starts_with(dir))
128 .cloned()
129 }
130}
131
132impl SessionEnv {
133 pub fn new(cwd: PathBuf) -> Self {
134 Self {
135 cwd,
136 ..Self::default()
137 }
138 }
139}
140
141/// Log namespace and event under which [`DurableState`] is recorded.
142pub const SESSION_STATE_NS: &str = "agix.session_state";
143pub const SESSION_STATE_EVENT: &str = "change";
144
145/// The part of a session's state that outlives its engine: what the model
146/// set up for itself, which an engine brought back from the log must still
147/// hold. The rest is derived from settings again or ends with the engine.
148#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
149pub struct DurableState {
150 #[serde(default)]
151 pub plan: Option<PlanState>,
152 #[serde(default)]
153 pub todos: Vec<TodoItem>,
154 /// The deferred tools `ToolSearch` loaded, sorted.
155 #[serde(default, skip_serializing_if = "Vec::is_empty")]
156 pub activated_tools: Vec<String>,
157}
158
159/// In plan mode, and where `ExitPlanMode` returns to: `None` is `Default`,
160/// for a session that started out in plan mode.
161#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
162pub struct PlanState {
163 pub exit_to: Option<PermissionMode>,
164}
165
166/// What tools and permission policies see of the session they run in. The
167/// layering needs the trait, not an extension point: `session-state` holds
168/// the one implementation.
169pub trait Session: Send + Sync + std::fmt::Debug {
170 /// What the attached engine derived from its settings and scene; empty
171 /// until one is attached.
172 fn env(&self) -> Arc<SessionEnv>;
173
174 /// The providers the attached engine's tool calls run on, if one is
175 /// attached.
176 fn exec(&self) -> Option<ExecProviders>;
177
178 /// The tool this session's calls named `name` dispatch to, if the
179 /// attached engine's registry holds it.
180 fn tool(&self, name: &str) -> Option<Arc<dyn Tool>>;
181
182 /// 读当前模式。
183 fn permission_mode(&self) -> PermissionMode;
184
185 /// 直接设模式,并忘掉进入计划模式前的那个。
186 fn set_permission_mode(&self, mode: PermissionMode);
187
188 /// 进计划模式,记下进入前的模式给 [`exit_plan_mode`](Self::exit_plan_mode)。
189 /// 已经在计划模式里时什么都不改。
190 fn enter_plan_mode(&self);
191
192 /// 退出计划模式,回到进入前的模式;会话一开始就在计划模式里的回到 `Default`。
193 fn exit_plan_mode(&self) -> PermissionMode;
194
195 /// The mode outside plan a host switched the session to since its engine
196 /// was attached; `None` leaves it to the engine's settings. What a
197 /// delegate spawned now starts from.
198 fn host_permission_mode(&self) -> Option<PermissionMode>;
199
200 /// The model the session's next call asks for, when a host chose one;
201 /// `None` leaves it on the model its engine was built with.
202 fn model_choice(&self) -> Option<String>;
203
204 /// Register work this session is running, under `cancel` — the token the
205 /// work itself observes, so stopping the task stops the work.
206 ///
207 /// Its start is announced at once, except a shell command's or a
208 /// monitor's: most of those finish in milliseconds, and a list that
209 /// flickered with each one would hide the ones worth seeing. Those are
210 /// announced only if still running a second later, and a task never
211 /// announced ends without a word. From then on what they print goes out
212 /// as `task_progress`, at most once a second, and once more as they end.
213 fn register_task(
214 &self,
215 task_id: String,
216 task_type: TaskType,
217 cancel: CancellationToken,
218 detail: serde_json::Value,
219 ) -> Arc<RunningTask>;
220
221 /// Record that a task's work is over, having ended with `status`: its
222 /// output closes and `task_finished` goes out. A task already ended —
223 /// stopped by `cancel_running_task`, say, before its own code got here —
224 /// keeps the ending it has. Finished tasks beyond the newest few are
225 /// forgotten.
226 fn finish_task(&self, task_id: &str, status: RunningStatus);
227
228 /// 找一个 running task。返回 Arc 让 caller 读快照(output / status)。
229 fn find_running_task(&self, task_id: &str) -> Option<Arc<RunningTask>>;
230
231 /// Stop a running task: cancel what it runs under and record it as
232 /// stopped. `false` if there is no such task or it had already ended.
233 ///
234 /// `task_finished` waits for the work to wind down — what it prints on
235 /// the way out is part of its output — up to a grace period.
236 fn cancel_running_task(&self, task_id: &str) -> bool;
237
238 /// Ids of the background work still running — sub-agents, teammates,
239 /// programs, monitors; not a foreground shell command — sorted.
240 fn running_background_task_ids(&self) -> Vec<String>;
241
242 /// Every task this session knows — running, and the most recently ended —
243 /// oldest first.
244 fn task_infos(&self) -> Vec<TaskInfo>;
245
246 /// Tell this session's agent something it did not ask for in this turn,
247 /// such as a background sub-agent having finished. A running turn reads
248 /// it at its next step boundary; otherwise the next turn opens with it.
249 ///
250 /// A notice under `key` can be [retracted](Self::retract_notice) before
251 /// it is read: one about a task the agent has since waited for tells it
252 /// nothing new.
253 fn post_notice(&self, key: Option<String>, text: String);
254
255 /// Withdraw the unread notice under `key`; `false` if there was none —
256 /// never posted, or already read.
257 fn retract_notice(&self, key: &str) -> bool;
258
259 fn take_notices(&self) -> Vec<String>;
260
261 /// Record what `Read` just showed the model, with the file's mtime: a
262 /// later read of the same range of an unchanged file is answered from the
263 /// cache while that result is still in the model's context, and
264 /// `Edit`/`Write` know the file was read and when.
265 fn record_read(&self, read: ReadRecord<'_>);
266
267 /// Record that `Edit` / `Write` just changed `path`, so the next edit of
268 /// it does not ask for a `Read` first or call the session's own change
269 /// an outside one.
270 fn record_write(&self, path: &Path);
271
272 /// 检查文件是否已读且未过期。
273 ///
274 /// - 文件不存在于磁盘 → 跳过检查(返回 None)
275 /// - 文件已读且 mtime 一致 → 返回 None(通过)
276 /// - 文件未读 → 返回 "must be read" 错误信息
277 /// - 文件已读但 mtime 不同 → 返回 "modified since read" 错误信息
278 fn check_read_staleness(&self, path: &Path) -> Option<&'static str>;
279
280 /// How the model still holds an earlier read of exactly this
281 /// `offset`/`limit` range of `path`, unchanged since; `None` when it does
282 /// not, and the file must be read again.
283 fn check_read_dedup_with_range(
284 &self,
285 path: &Path,
286 offset: Option<usize>,
287 limit: Option<usize>,
288 ) -> Option<HeldRead>;
289
290 /// 给定路径是否与最近一次读取的文件一致。
291 /// 仅检查路径相等;mtime 一致性由调用方通过 `check_read_dedup_with_range` 保证。
292 fn is_consecutive_read(&self, path: &Path) -> bool;
293
294 /// 读取当前 todo 列表(克隆给调用方)
295 fn todos(&self) -> Vec<TodoItem>;
296
297 /// TodoWrite 工具用:一次性替换整个列表。
298 /// 如果全部 completed 则自动清空。
299 fn set_todos(&self, items: Vec<TodoItem>);
300
301 /// 当前已激活的 deferred 工具名(克隆 set;调用方只读)。
302 fn activated_tools(&self) -> HashSet<String>;
303
304 /// ToolSearch 命中后调用:把工具加进 activated 集合。
305 /// 多次调用 idempotent;空集合也允许。
306 fn activate_tools(&self, names: Vec<String>);
307
308 fn ledger(&self) -> std::sync::MutexGuard<'_, SessionLedger>;
309
310 /// The goal as hosts and the model see it.
311 fn goal_view(&self) -> Option<GoalView>;
312
313 fn goal_create(
314 &self,
315 objective: String,
316 limits: super::goal::GoalLimits,
317 origin: TurnOrigin,
318 ) -> Result<GoalView, GoalError>;
319
320 /// An edit may give the goal no more than `max_rounds_limit` rounds.
321 fn goal_update(
322 &self,
323 goal_id: &str,
324 revision: u64,
325 action: GoalAction,
326 origin: TurnOrigin,
327 max_rounds_limit: u32,
328 ) -> Result<GoalView, GoalError>;
329}
330
331/// Stop `task` from outside its lease, posting `notice` as its end's
332/// notice before it ends. Of this and the lease, whichever comes first
333/// ends the task and notifies; the other leaves both to it.
334pub fn stop_with_notice(
335 session: &dyn Session,
336 task: &RunningTask,
337 notice: impl FnOnce(&RunningTask) -> String,
338) {
339 task.cancel.cancel();
340 if !task.claim_end() {
341 return;
342 }
343 if !task.has_ended() {
344 session.post_notice(Some(task.task_id.clone()), notice(task));
345 }
346 session.cancel_running_task(&task.task_id);
347}
348
349/// A task that lasts as long as this value: registered on creation, ended on
350/// drop — stopped if its token was cancelled, done otherwise. For work bounded
351/// by one call, like a shell command.
352pub struct TaskScope {
353 session: Arc<dyn Session>,
354 task: Arc<RunningTask>,
355}
356
357impl TaskScope {
358 pub fn new(
359 session: Arc<dyn Session>,
360 task_id: impl Into<String>,
361 task_type: TaskType,
362 cancel: tokio_util::sync::CancellationToken,
363 detail: serde_json::Value,
364 ) -> Self {
365 let task = session.register_task(task_id.into(), task_type, cancel, detail);
366 Self { session, task }
367 }
368
369 pub fn task(&self) -> &Arc<RunningTask> {
370 &self.task
371 }
372}
373
374impl Drop for TaskScope {
375 fn drop(&mut self) {
376 let status = if self.task.cancel.is_cancelled() {
377 RunningStatus::Cancelled
378 } else {
379 RunningStatus::Completed
380 };
381 self.session.finish_task(&self.task.task_id, status);
382 }
383}
384
385/// A task whose holder says how it ended: registered on creation, ended by
386/// [`conclude`](Self::conclude). One dropped without concluding — its work
387/// panicked, was dropped from a queue, or its holder simply went away — ends
388/// as stopped, and the parent hears so when the lease was taken
389/// [notifying](Self::notifying) it. No task held by a lease is left running.
390pub struct TaskLease {
391 session: Arc<dyn Session>,
392 task: Arc<RunningTask>,
393 stopped_notice: Option<StoppedNotice>,
394 concluded: bool,
395}
396
397type StoppedNotice = Box<dyn Fn(&RunningTask) -> String + Send + Sync>;
398
399impl TaskLease {
400 pub fn new(
401 session: Arc<dyn Session>,
402 task_id: impl Into<String>,
403 task_type: TaskType,
404 cancel: tokio_util::sync::CancellationToken,
405 detail: serde_json::Value,
406 ) -> Self {
407 let task = session.register_task(task_id.into(), task_type, cancel, detail);
408 Self {
409 session,
410 task,
411 stopped_notice: None,
412 concluded: false,
413 }
414 }
415
416 /// The notice the parent is posted when the lease is dropped unconcluded.
417 pub fn notifying(
418 mut self,
419 notice: impl Fn(&RunningTask) -> String + Send + Sync + 'static,
420 ) -> Self {
421 self.stopped_notice = Some(Box::new(notice));
422 self
423 }
424
425 pub fn task(&self) -> &Arc<RunningTask> {
426 &self.task
427 }
428
429 /// End the task with `status`. `notice` is posted to the session first,
430 /// so whoever wakes on the task's end finds it there to withdraw; a task
431 /// already stopped from outside gets none, since whoever stopped it knows.
432 pub fn conclude(mut self, status: RunningStatus, notice: Option<String>) {
433 self.concluded = true;
434 if !self.task.claim_end() {
435 return;
436 }
437 if let Some(notice) = notice.filter(|_| !self.task.has_ended()) {
438 self.session
439 .post_notice(Some(self.task.task_id.clone()), notice);
440 }
441 self.session.finish_task(&self.task.task_id, status);
442 }
443}
444
445impl Drop for TaskLease {
446 fn drop(&mut self) {
447 if self.concluded || !self.task.claim_end() {
448 return;
449 }
450 if let Some(notice) = self.stopped_notice.as_ref() {
451 if !self.task.has_ended() {
452 self.session
453 .post_notice(Some(self.task.task_id.clone()), notice(&self.task));
454 }
455 }
456 self.session
457 .finish_task(&self.task.task_id, RunningStatus::Cancelled);
458 }
459}