Skip to main content

locode_engine/
session.rs

1//! The public driving API.
2
3use std::sync::Arc;
4
5use locode_protocol::{ContentBlock, Event, Message, Report, Role};
6use locode_provider::Provider;
7use locode_tools::Registry;
8use tokio_util::sync::CancellationToken;
9
10use crate::approve::{AllowAll, Approver};
11use crate::config::EngineConfig;
12use crate::sink::EventSink;
13
14/// One driven agent session. Owns the conversation history **across runs**: a
15/// second [`Session::run`] on the same session continues the same conversation
16/// (ADR-0016) — the exact call shape an interactive frontend needs for
17/// follow-up turns.
18///
19/// Construct with [`Session::new`], then call [`Session::run`] (or
20/// [`Session::run_text`]) to drive one run to a terminal state. `run` is
21/// **infallible** — every terminal condition (including provider and `Fatal` tool
22/// errors) is captured in the returned [`Report`]'s `status`/`error`, so a caller
23/// gets a structured result every time (`locode-exec` maps status → exit code).
24///
25/// Each [`Report`] is **per-run**: `turns`/`usage`/`tool_calls` count the current
26/// run only (a cumulative view is derivable from the event stream). Continuing
27/// after a failed run is allowed unconditionally — for `ModelError` the history
28/// simply didn't advance, and for `Error` the transcript was fully paired before
29/// the break; the pre-send pairing repair heals any residue on the next sample.
30pub struct Session {
31    pub(crate) provider: Arc<dyn Provider>,
32    pub(crate) registry: Registry,
33    pub(crate) preamble: Vec<Message>,
34    pub(crate) config: EngineConfig,
35    pub(crate) sink: Box<dyn EventSink>,
36    pub(crate) cancel: CancellationToken,
37    /// The conversation so far: preamble + every appended turn, across runs.
38    pub(crate) history: Vec<Message>,
39    /// Runs driven on this session; gates the once-per-session `Init` event.
40    pub(crate) turns_run: u32,
41    /// The pre-dispatch approval gate (ADR-0017); [`AllowAll`] by default.
42    pub(crate) approver: Arc<dyn Approver>,
43    /// The listing body from the most recent scan, injected on the next turn
44    /// (ADR-0025 §3.2 — scanning happens after a run, never at the top of one).
45    pub(crate) skills_body: Option<String>,
46    /// Text typed while a run is in flight, drained into the next tool-result
47    /// batch (ADR-0028).
48    pub(crate) input_queue: crate::InputQueue,
49}
50
51impl Session {
52    /// Assemble a session from its parts.
53    ///
54    /// `preamble` is the base `System` + `Developer` messages (the pack supplies
55    /// these); `provider`/`sink` are trait objects so the binary can select them at
56    /// runtime.
57    #[must_use]
58    pub fn new(
59        provider: Arc<dyn Provider>,
60        registry: Registry,
61        preamble: Vec<Message>,
62        config: EngineConfig,
63        sink: Box<dyn EventSink>,
64    ) -> Self {
65        Self {
66            provider,
67            registry,
68            history: preamble.clone(),
69            preamble,
70            config,
71            sink,
72            cancel: CancellationToken::new(),
73            turns_run: 0,
74            approver: Arc::new(AllowAll),
75            skills_body: None,
76            input_queue: crate::InputQueue::new(),
77        }
78    }
79
80    /// Install an [`Approver`] consulted before every tool call (ADR-0017).
81    ///
82    /// Builder-style so [`Session::new`]'s signature stays intact. The default
83    /// is [`AllowAll`] — headless consumers are unchanged without this call.
84    #[must_use]
85    pub fn with_approver(mut self, approver: Arc<dyn Approver>) -> Self {
86        self.approver = approver;
87        self
88    }
89
90    /// Switch the model this session samples with, mid-conversation.
91    ///
92    /// The caller rebuilds the provider (the registry's factory already takes a model
93    /// override) and hands it in; this swaps it and updates the config so the trace's
94    /// later records name the model actually in use.
95    ///
96    /// **The preamble is not rewritten.** A pack's system prompt may name the model —
97    /// Claude Code's env block does, and so does our port — and after a switch that line
98    /// is stale. Rewriting the `System` message would desync the transcript from the
99    /// trace, whose `Init` record already captured the original preamble: a resumed
100    /// session would replay one preamble while the live session had another. So the
101    /// change is **announced instead**, as an appended `<system-reminder>` — the same
102    /// never-mutate-history discipline project instructions and skills already follow.
103    ///
104    /// Returns the announcement, which the caller appends and emits like any other
105    /// message. (Doing it here would bypass the sink the caller owns.)
106    pub fn set_model(&mut self, provider: Arc<dyn Provider>, model: &str) -> Message {
107        self.provider = provider;
108        self.config.model = model.to_string();
109        Message {
110            role: Role::User,
111            content: vec![ContentBlock::Text {
112                text: format!(
113                    "<system-reminder>\nThe model for this conversation is now {model}. \
114                     Any earlier statement about which model you are is out of date.\n\
115                     </system-reminder>"
116                ),
117            }],
118        }
119    }
120
121    /// Register another discovery root, so the next turn's instruction and skill
122    /// rescans see that directory's `AGENTS.md` and `.agents/skills`.
123    ///
124    /// Only the *config* changes here — widening the tool jail is the host's
125    /// job (`Host::add_root`), and the caller does both. Both discoveries
126    /// already re-run per turn (ADR-0023 whole-body diff, ADR-0025 post-run
127    /// rescan), so nothing needs re-injecting by hand: the added root simply
128    /// appears in the next scan.
129    pub fn add_root(&mut self, root: std::path::PathBuf) {
130        if !self.config.instructions.extra_roots.contains(&root) {
131            self.config.instructions.extra_roots.push(root.clone());
132        }
133        if !self.config.skills.extra_roots.contains(&root) {
134            self.config.skills.extra_roots.push(root);
135        }
136    }
137
138    /// A clonable handle to this session's mid-run input queue (ADR-0028).
139    ///
140    /// Clone it **before** calling [`Session::run`] — `run` takes `&mut self`,
141    /// so nothing on the session is reachable while a turn is in flight. Same
142    /// shape as [`Session::cancel_handle`] and for the same reason.
143    #[must_use]
144    pub fn input_queue(&self) -> crate::InputQueue {
145        self.input_queue.clone()
146    }
147
148    /// Set the reasoning effort subsequent turns sample with.
149    ///
150    /// Unlike [`Session::set_model`] this announces nothing: effort changes how
151    /// hard the model thinks, not who it is, so there is no stale statement in
152    /// the transcript to correct — and injecting a reminder would cost a cache
153    /// breakpoint for no gain.
154    pub fn set_effort(&mut self, effort: Option<locode_provider::ReasoningEffort>) {
155        self.config.sampling_args.reasoning_effort = effort;
156    }
157
158    /// Append a message to the conversation and emit it, exactly as a turn would.
159    pub fn announce(&mut self, message: Message) {
160        self.history.push(message.clone());
161        self.sink.emit(Event::Message { message });
162    }
163
164    /// The conversation so far: the preamble plus every appended turn across all
165    /// runs on this session (ADR-0016). Lets a frontend render the transcript
166    /// after a run without replaying the event stream.
167    #[must_use]
168    pub fn history(&self) -> &[Message] {
169        &self.history
170    }
171
172    /// The cancellation handle for the **current run** (ADR-0018).
173    ///
174    /// Clone it *before* calling [`Session::run`] (mandatory — `run` takes
175    /// `&mut self`, so nothing is callable mid-run) and move it into an Esc
176    /// handler, signal handler, or timeout. Firing it stops the run at the
177    /// next observation point — mid-sample (the in-flight request is
178    /// aborted), between batch calls (the rest of the batch is paired
179    /// synthetically), or at the loop top — and the run returns a report with
180    /// [`Status::Cancelled`](locode_protocol::Status). Partial work is
181    /// preserved: with session continuity, the next `run()` continues the
182    /// same conversation.
183    ///
184    /// The token is **per-run, replaced when `run` returns**: a cancel landing
185    /// after the run ended hits the retired token — a harmless no-op — so the
186    /// Esc-lands-late race is resolved by construction. Re-fetch the handle
187    /// each turn. `cancel()` is idempotent; there is no reset.
188    #[must_use]
189    pub fn cancel_handle(&self) -> CancellationToken {
190        self.cancel.clone()
191    }
192
193    /// Drive the loop to a terminal state and return the run's [`Report`].
194    pub async fn run(&mut self, user: Vec<ContentBlock>) -> Report {
195        self.drive(user).await
196    }
197
198    /// Convenience: drive with a plain-text user prompt.
199    pub async fn run_text(&mut self, prompt: impl Into<String>) -> Report {
200        self.run(vec![ContentBlock::Text {
201            text: prompt.into(),
202        }])
203        .await
204    }
205}