Skip to main content

locode_engine/
session.rs

1//! The public driving API.
2
3use std::sync::Arc;
4
5use locode_protocol::{ContentBlock, Message, Report};
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}
44
45impl Session {
46    /// Assemble a session from its parts.
47    ///
48    /// `preamble` is the base `System` + `Developer` messages (the pack supplies
49    /// these); `provider`/`sink` are trait objects so the binary can select them at
50    /// runtime.
51    #[must_use]
52    pub fn new(
53        provider: Arc<dyn Provider>,
54        registry: Registry,
55        preamble: Vec<Message>,
56        config: EngineConfig,
57        sink: Box<dyn EventSink>,
58    ) -> Self {
59        Self {
60            provider,
61            registry,
62            history: preamble.clone(),
63            preamble,
64            config,
65            sink,
66            cancel: CancellationToken::new(),
67            turns_run: 0,
68            approver: Arc::new(AllowAll),
69        }
70    }
71
72    /// Install an [`Approver`] consulted before every tool call (ADR-0017).
73    ///
74    /// Builder-style so [`Session::new`]'s signature stays intact. The default
75    /// is [`AllowAll`] — headless consumers are unchanged without this call.
76    #[must_use]
77    pub fn with_approver(mut self, approver: Arc<dyn Approver>) -> Self {
78        self.approver = approver;
79        self
80    }
81
82    /// The conversation so far: the preamble plus every appended turn across all
83    /// runs on this session (ADR-0016). Lets a frontend render the transcript
84    /// after a run without replaying the event stream.
85    #[must_use]
86    pub fn history(&self) -> &[Message] {
87        &self.history
88    }
89
90    /// The cancellation handle for the **current run** (ADR-0018).
91    ///
92    /// Clone it *before* calling [`Session::run`] (mandatory — `run` takes
93    /// `&mut self`, so nothing is callable mid-run) and move it into an Esc
94    /// handler, signal handler, or timeout. Firing it stops the run at the
95    /// next observation point — mid-sample (the in-flight request is
96    /// aborted), between batch calls (the rest of the batch is paired
97    /// synthetically), or at the loop top — and the run returns a report with
98    /// [`Status::Cancelled`](locode_protocol::Status). Partial work is
99    /// preserved: with session continuity, the next `run()` continues the
100    /// same conversation.
101    ///
102    /// The token is **per-run, replaced when `run` returns**: a cancel landing
103    /// after the run ended hits the retired token — a harmless no-op — so the
104    /// Esc-lands-late race is resolved by construction. Re-fetch the handle
105    /// each turn. `cancel()` is idempotent; there is no reset.
106    #[must_use]
107    pub fn cancel_handle(&self) -> CancellationToken {
108        self.cancel.clone()
109    }
110
111    /// Drive the loop to a terminal state and return the run's [`Report`].
112    pub async fn run(&mut self, user: Vec<ContentBlock>) -> Report {
113        self.drive(user).await
114    }
115
116    /// Convenience: drive with a plain-text user prompt.
117    pub async fn run_text(&mut self, prompt: impl Into<String>) -> Report {
118        self.run(vec![ContentBlock::Text {
119            text: prompt.into(),
120        }])
121        .await
122    }
123}