Skip to main content

ag_session/
service.rs

1//! Programmatic session orchestration facade and host backend port.
2
3use std::sync::Arc;
4
5use ag_protocol::{TurnPrompt, TurnPromptAttachment};
6use async_trait::async_trait;
7
8use crate::error::SessionError;
9use crate::model::{ReviewRequest, Session, SessionId, SessionListEntry, SessionSummary};
10use crate::{
11    AcceptTaskPlanRequest, AgentKind, AgentModel, AgentSelection, CreateTaskRequest,
12    ReasoningLevel, ResponseStyle, SpeedMode, SubmitTaskRequest, Task,
13};
14
15/// Creation strategy for a new session.
16#[derive(Clone, Debug, Default, Eq, PartialEq)]
17pub enum CreateSessionMode {
18    /// Creates a regular session with an eagerly materialized worktree.
19    #[default]
20    Regular,
21    /// Creates a draft whose worktree is materialized on first send.
22    Draft,
23    /// Creates a regular session that runs on the in-process
24    /// [`crate::AgentKind::Harness`] with its default model.
25    Harness,
26}
27
28/// Explicit input for creating one session.
29#[derive(Clone, Debug, Eq, PartialEq)]
30pub struct CreateSessionRequest {
31    /// Existing session whose launch settings should be copied.
32    ///
33    /// When absent, the host resolves the owning project's current defaults.
34    pub inherit_from_session_id: Option<SessionId>,
35    /// Determines whether the session is regular, deferred, or harness-backed.
36    pub mode: CreateSessionMode,
37    /// Project that owns the new session.
38    pub project_id: i64,
39}
40
41/// One structured response to a persisted clarification question.
42#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct QuestionAnswer {
44    /// User response paired with `question`.
45    pub answer: String,
46    /// Exact persisted question text being answered.
47    pub question: String,
48}
49
50/// Structured input for resuming one session from clarification questions.
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct AnswerQuestionsRequest {
53    /// Ordered question and answer pairs for the current question set.
54    pub answers: Vec<QuestionAnswer>,
55    /// Local images referenced by `[Image #n]` placeholders in `answers`,
56    /// delivered with the reply turn like prompt attachments. The caller
57    /// keeps the files when the request fails, so it can retry with them.
58    pub attachments: Vec<TurnPromptAttachment>,
59    /// [`crate::Session::graph_question_target`] of the graph questions the
60    /// answers are for, as the snapshot the answers were entered on
61    /// reported it. `None` answers the questions of the session's own turn.
62    /// The host refuses answers for graph work other than the one pending
63    /// now, even when it asks the same questions.
64    pub graph_question_target: Option<String>,
65}
66
67/// One encoded image a frontend sends with a chat message, whose bytes the
68/// host writes to its own prompt-image directory and attaches to the turn.
69///
70/// Only PNG and JPEG files are accepted, recognized by their signature, so
71/// the host never trusts a name or media type the sender chose.
72#[derive(Clone, Debug, Eq, PartialEq)]
73pub struct MessageImage {
74    data: Vec<u8>,
75    format: MessageImageFormat,
76}
77
78impl MessageImage {
79    /// Wraps the encoded bytes of one PNG or JPEG image.
80    ///
81    /// # Errors
82    /// Returns an error when `data` is neither a PNG nor a JPEG file.
83    pub fn new(data: Vec<u8>) -> Result<Self, SessionError> {
84        let format = MessageImageFormat::of(&data).ok_or_else(|| {
85            SessionError::Operation("Only PNG and JPEG images can be attached".to_string())
86        })?;
87
88        Ok(Self { data, format })
89    }
90
91    /// Returns the encoded image bytes.
92    #[must_use]
93    pub fn data(&self) -> &[u8] {
94        &self.data
95    }
96
97    /// Returns the image's file format.
98    #[must_use]
99    pub fn format(&self) -> MessageImageFormat {
100        self.format
101    }
102
103    /// Returns the encoded image bytes, consuming the image.
104    #[must_use]
105    pub fn into_data(self) -> Vec<u8> {
106        self.data
107    }
108}
109
110/// File format of one [`MessageImage`].
111#[derive(Clone, Copy, Debug, Eq, PartialEq)]
112pub enum MessageImageFormat {
113    /// A JPEG image.
114    Jpeg,
115    /// A PNG image.
116    Png,
117}
118
119impl MessageImageFormat {
120    /// Returns the file extension the host stores the image under.
121    #[must_use]
122    pub fn extension(self) -> &'static str {
123        match self {
124            Self::Jpeg => "jpg",
125            Self::Png => "png",
126        }
127    }
128
129    /// Recognizes the format of `data` by its file signature.
130    fn of(data: &[u8]) -> Option<Self> {
131        const JPEG_SIGNATURE: &[u8] = &[0xFF, 0xD8, 0xFF];
132        const PNG_SIGNATURE: &[u8] = &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
133
134        if data.starts_with(PNG_SIGNATURE) {
135            Some(Self::Png)
136        } else if data.starts_with(JPEG_SIGNATURE) {
137            Some(Self::Jpeg)
138        } else {
139            None
140        }
141    }
142}
143
144/// Idempotent turn submitted to one session.
145#[derive(Clone, Debug, Eq, PartialEq)]
146pub struct DurableMessageRequest {
147    /// Agent-facing prompt.
148    pub message: String,
149    /// Stable operation identifier reused when delivery is retried.
150    pub operation_id: String,
151    /// Whether the machine-authored prompt is shown in the human transcript.
152    pub visibility: DurableMessageVisibility,
153}
154
155/// Transcript treatment for one durable prompt.
156#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
157pub enum DurableMessageVisibility {
158    /// Deliver generated context without displaying it as user chat.
159    #[default]
160    Hidden,
161    /// Display the submitted instruction in session history.
162    Visible,
163}
164
165/// Operation a host may choose to serve to frontends that check
166/// [`SessionService::supports`] first, such as remote control.
167///
168/// A frontend offers an operation only when the host reports it, so adding a
169/// variant never exposes an operation that an existing host has not opted
170/// into.
171#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
172#[non_exhaustive]
173pub enum SessionOperation {
174    /// Creating a session in the active project through
175    /// [`SessionBackend::create_session`].
176    CreateSession,
177    /// Describing the active project through
178    /// [`SessionBackend::host_context`].
179    HostContext,
180    /// Merging a review-ready session through
181    /// [`SessionBackend::merge_session`].
182    MergeSession,
183    /// Reading a session's changes through
184    /// [`SessionBackend::get_session_diff`].
185    SessionDiff,
186    /// Listing the files and directories in the active project's checkout
187    /// through [`SessionBackend::list_project_files`], for drafting a new
188    /// session before it has a worktree.
189    ProjectFiles,
190    /// Listing the files and directories in a session's worktree through
191    /// [`SessionBackend::list_session_files`].
192    SessionFiles,
193    /// Stopping a running turn through [`SessionBackend::stop_turn`].
194    StopTurn,
195    /// Rebasing a session branch onto its base branch through
196    /// [`SessionBackend::rebase_session`].
197    RebaseSession,
198    /// Changing a session's model, reasoning, style, or speed through
199    /// [`SessionBackend::update_session_settings`].
200    SessionSettings,
201    /// Publishing a session to its existing branch, or under its default name
202    /// the first time, and creating or refreshing its review request through
203    /// [`SessionBackend::create_review_request`].
204    PublishSession,
205    /// Reporting the active project's branch, its distance from upstream,
206    /// and its latest sync through [`SessionBackend::project_status`].
207    ProjectStatus,
208    /// Syncing the active project's branch with its upstream through
209    /// [`SessionBackend::sync_project`].
210    SyncProject,
211    /// Reading a session's graph proposal and execution graphs through
212    /// [`SessionBackend::session_graphs`], and summarizing them in
213    /// [`Session::graph`].
214    Graphs,
215    /// Acting on a session's execution graph as its inspector does, bound
216    /// to the snapshot a [`SessionBackend::session_graphs`] read returned,
217    /// through [`SessionBackend::act_on_session_graph`].
218    GraphActions,
219    /// Generating a graph proposal for a task, as the host's own graph
220    /// command does, through [`SessionBackend::generate_graph_proposal`].
221    /// Nothing launches until a reply approves the proposal.
222    GenerateGraphProposal,
223    /// Sending a chat message with images through
224    /// [`SessionBackend::send_message_with_images`].
225    MessageImages,
226}
227
228/// Settings to change on one session; `None` keeps a setting as it is.
229#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
230pub struct SessionSettingsChange {
231    /// Agent to run `model`, as the terminal's `/model` picks one before the
232    /// model; `None` keeps the session's own agent. It names an agent only
233    /// together with `model`, since agents share model ids.
234    pub agent: Option<AgentKind>,
235    /// Model to switch to, run by `agent`.
236    pub model: Option<AgentModel>,
237    /// Reasoning level to use for later turns.
238    pub reasoning_level: Option<ReasoningLevel>,
239    /// Response style to use for later turns.
240    pub response_style: Option<ResponseStyle>,
241    /// Response speed to use for later turns.
242    pub speed_mode: Option<SpeedMode>,
243}
244
245/// One file a session's diff changes.
246#[derive(Clone, Debug, Eq, PartialEq)]
247pub struct SessionDiffFile {
248    /// Lines the file's patch adds.
249    pub added_lines: u64,
250    /// Lines the file's patch removes.
251    pub deleted_lines: u64,
252    /// Path before a rename, or `None` when the path did not change.
253    pub old_path: Option<String>,
254    /// The file's unified diff, including its `diff --git` header.
255    pub patch: String,
256    /// Path after the change; a deleted file keeps its old path.
257    pub path: String,
258    /// How the change affects the file.
259    pub status: SessionDiffFileStatus,
260}
261
262/// How a session's diff changes one file.
263#[derive(Clone, Copy, Debug, Eq, PartialEq)]
264pub enum SessionDiffFileStatus {
265    /// The file is new.
266    Added,
267    /// The file is removed.
268    Deleted,
269    /// The file's contents or mode changed.
270    Modified,
271    /// The file moved, possibly with changes.
272    Renamed,
273}
274
275/// One file or directory in a session's worktree or the active project's
276/// checkout.
277#[derive(Clone, Debug, Eq, PartialEq)]
278pub struct SessionFileEntry {
279    /// Whether the entry is a directory.
280    pub is_dir: bool,
281    /// Path relative to the listed root, with `/` separators.
282    pub path: String,
283}
284
285/// The project a host creates new sessions in, and how it creates them.
286#[derive(Clone, Debug, Eq, PartialEq)]
287pub struct HostContext {
288    /// Branch new sessions start from.
289    pub base_branch: String,
290    /// Model a new session in the first of `session_modes` starts with: the
291    /// harness model when only Harness sessions are offered, otherwise the
292    /// regular agent's default.
293    pub default_model: AgentModel,
294    /// Agents and models a session can switch to now, in display order, as
295    /// the terminal's `/model` offers them; each gives the model's id and
296    /// name.
297    pub models: Vec<AgentSelection>,
298    /// Identifier of the active project, the only one that accepts new
299    /// sessions.
300    pub project_id: i64,
301    /// Display name of the active project.
302    pub project_name: String,
303    /// Creation modes the host can serve now, in display order, each with
304    /// the agent and model its new sessions start with.
305    pub session_modes: Vec<HostSessionMode>,
306}
307
308/// One creation mode a host serves, and how its new sessions start.
309#[derive(Clone, Debug, Eq, PartialEq)]
310pub struct HostSessionMode {
311    /// Agent and model a new session in this mode starts with.
312    pub agent: AgentSelection,
313    /// Creation mode.
314    pub mode: CreateSessionMode,
315    /// Reasoning level a new session in this mode starts with.
316    pub reasoning_level: ReasoningLevel,
317    /// Response style a new session in this mode starts with.
318    pub response_style: ResponseStyle,
319    /// Response-speed preference a new session in this mode starts with.
320    pub speed_mode: SpeedMode,
321}
322
323/// The host's active project as a session list shows it.
324#[derive(Clone, Debug, Eq, PartialEq)]
325pub struct HostProjectStatus {
326    /// Commits the branch is ahead of and behind its upstream, in that
327    /// order, as of the host's latest fetch; `None` when the host has not
328    /// compared them.
329    pub ahead_behind: Option<(u32, u32)>,
330    /// Branch the project's checkout is on, which new sessions start from;
331    /// `None` when it has none, such as a detached `HEAD`.
332    pub branch: Option<String>,
333    /// Display name of the active project.
334    pub project_name: String,
335    /// Latest explicit sync of this project, while the host still shows it.
336    pub sync: Option<HostProjectSync>,
337}
338
339/// One explicit sync of the active project's branch with its upstream.
340#[derive(Clone, Debug, Eq, PartialEq)]
341pub struct HostProjectSync {
342    /// Branch the sync updates.
343    pub branch: String,
344    /// How far the sync has come.
345    pub phase: HostProjectSyncPhase,
346}
347
348/// How far an explicit project sync has come.
349#[derive(Clone, Debug, Eq, PartialEq)]
350pub enum HostProjectSyncPhase {
351    /// The host is pulling, rebasing, or pushing.
352    Running,
353    /// An agent is resolving the conflicts of this many files.
354    ResolvingConflicts {
355        /// Files the rebase left in conflict.
356        conflicted_file_count: usize,
357    },
358    /// The branch matches its upstream.
359    Complete {
360        /// Commits pulled from upstream, when the host counted them.
361        pulled_commits: Option<u32>,
362        /// Local commits pushed upstream, when the host counted them.
363        pushed_commits: Option<u32>,
364        /// Files whose conflicts the agent resolved.
365        resolved_conflict_count: usize,
366    },
367    /// The host did not start the sync, such as while a merge runs or the
368    /// checkout has uncommitted changes.
369    Blocked {
370        /// Why the sync could not start.
371        message: String,
372    },
373    /// Git, authentication, or conflict resolution failed.
374    Failed {
375        /// Why the sync failed.
376        message: String,
377    },
378}
379
380/// Host implementation boundary for session persistence and workflows.
381///
382/// The trait is object-safe so agent loops and background workflows can hold a
383/// programmatic session capability without depending on a concrete frontend.
384#[async_trait]
385pub trait SessionBackend: Send + Sync {
386    /// Reports whether the host serves `operation` to frontends that ask
387    /// first. Hosts serve none unless they opt in.
388    fn supports(&self, operation: SessionOperation) -> bool {
389        let _ = operation;
390
391        false
392    }
393
394    /// Reserves generation without waiting for model completion.
395    async fn generate_graph_proposal(
396        &self,
397        request: crate::GenerateGraphProposalRequest,
398    ) -> Result<(), SessionError> {
399        let _ = request;
400        Err(SessionError::Operation(
401            "Host does not support graph proposals".into(),
402        ))
403    }
404
405    /// Reads retained state without generating or launching work.
406    async fn get_graph_proposal(
407        &self,
408        id: &str,
409    ) -> Result<Option<crate::GraphProposalState>, SessionError> {
410        let _ = id;
411        Err(SessionError::Operation(
412            "Host does not support graph proposals".into(),
413        ))
414    }
415
416    /// Applies an explicit action to the exact inspected version.
417    async fn act_on_graph_proposal(
418        &self,
419        id: &str,
420        version: u32,
421        action: crate::GraphProposalAction,
422    ) -> Result<(), SessionError> {
423        let _ = (id, version, action);
424        Err(SessionError::Operation(
425            "Host does not support graph proposals".into(),
426        ))
427    }
428
429    /// Reads durable progress without launching or retrying work.
430    async fn get_execution_graph(
431        &self,
432        graph_id: &str,
433    ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
434        let _ = graph_id;
435
436        Err(SessionError::Operation(
437            "Host does not support execution graphs".into(),
438        ))
439    }
440
441    /// Reads a session's graphs, its latest proposal, and the selected
442    /// graph's live progress and outputs, without launching or changing any
443    /// work.
444    async fn session_graphs(
445        &self,
446        request: crate::SessionGraphsRequest,
447    ) -> Result<crate::SessionGraphs, SessionError> {
448        let _ = request;
449
450        Err(SessionError::Operation(
451            "Host does not support execution graphs".into(),
452        ))
453    }
454
455    /// Applies one inspector action to a session's graph, as the host's own
456    /// inspector would with the same node or output selected, only while the
457    /// graph still matches the snapshot the action was chosen from.
458    async fn act_on_session_graph(
459        &self,
460        request: crate::SessionGraphActionRequest,
461    ) -> Result<(), SessionError> {
462        let _ = request;
463
464        Err(SessionError::Operation(
465            "Host does not support execution graph actions".into(),
466        ))
467    }
468
469    /// Closes graph admission durably, then signals its owned workers.
470    async fn cancel_execution_graph(
471        &self,
472        request: crate::GraphControlRequest,
473    ) -> Result<(), SessionError> {
474        let _ = request;
475
476        Err(SessionError::Operation(
477            "Host does not support execution graphs".into(),
478        ))
479    }
480
481    /// Explicitly restarts dispatch without replaying admitted executions.
482    async fn resume_execution_graph(
483        &self,
484        request: crate::ResumeExecutionGraphRequest,
485    ) -> Result<(), SessionError> {
486        let _ = request;
487
488        Err(SessionError::Operation(
489            "Host does not support execution graphs".into(),
490        ))
491    }
492
493    /// Records an explicit increase of one budget's provider calls, then
494    /// releases nodes waiting for that credit.
495    async fn extend_execution_graph_budget(
496        &self,
497        request: crate::ExtendGraphBudgetRequest,
498    ) -> Result<(), SessionError> {
499        let _ = request;
500
501        Err(SessionError::Operation(
502            "Host does not support execution graphs".into(),
503        ))
504    }
505
506    /// Authorizes one new attempt against an exact failed/question execution.
507    async fn continue_execution_graph_node(
508        &self,
509        request: crate::ContinueGraphNodeRequest,
510    ) -> Result<(), SessionError> {
511        let _ = request;
512
513        Err(SessionError::Operation(
514            "Host does not support execution graphs".into(),
515        ))
516    }
517
518    /// Saves and starts a static graph. Existing admitted nodes are never
519    /// replayed. Named budgets are fixed at first launch and their spending is
520    /// recorded durably, so relaunching never replenishes them.
521    async fn start_execution_graph(
522        &self,
523        request: StartExecutionGraphRequest,
524    ) -> Result<(), SessionError> {
525        let _ = request;
526
527        Err(SessionError::Operation(
528            "Host does not support execution graphs".into(),
529        ))
530    }
531
532    /// Records explicit acceptance of an exact graph output and wakes ready
533    /// dependents. Model output must never call this trusted host boundary.
534    async fn accept_execution_graph_result(
535        &self,
536        reference: crate::GraphResultRef,
537    ) -> Result<(), SessionError> {
538        let _ = reference;
539
540        Err(SessionError::Operation(
541            "Host does not support execution graphs".into(),
542        ))
543    }
544    /// Admits a role-bound attempt with its own isolated conversation.
545    async fn submit_agent_task(
546        &self,
547        session_id: &SessionId,
548        request: crate::SubmitAgentTaskRequest,
549    ) -> Result<(), SessionError> {
550        let _ = (session_id, request);
551
552        Err(SessionError::Operation(
553            "Host does not support role-aware tasks".to_string(),
554        ))
555    }
556
557    /// Reads isolated task responses without exposing host storage types.
558    async fn get_agent_task_history(
559        &self,
560        task_id: &str,
561    ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
562        let _ = task_id;
563
564        Err(SessionError::Operation(
565            "Host does not support role-aware tasks".to_string(),
566        ))
567    }
568
569    /// Explicitly accepts a standalone Planner response by producing version.
570    async fn accept_agent_plan(
571        &self,
572        _session_id: &SessionId,
573        _request: AcceptTaskPlanRequest,
574    ) -> Result<(), SessionError> {
575        Err(SessionError::Operation(
576            "Host does not support plan acceptance".into(),
577        ))
578    }
579
580    /// Persists an outcome without execution. Older hosts may omit support.
581    async fn create_task(
582        &self,
583        _session_id: &SessionId,
584        _request: CreateTaskRequest,
585    ) -> Result<(), SessionError> {
586        Err(SessionError::Operation(
587            "Host does not support tasks".to_string(),
588        ))
589    }
590
591    /// Lists a session's tasks, including unattempted and completed outcomes.
592    async fn list_tasks(&self, _session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
593        Err(SessionError::Operation(
594            "Host does not support tasks".to_string(),
595        ))
596    }
597
598    /// Admits an explicit task attempt. Older hosts may omit task support.
599    async fn submit_task(
600        &self,
601        _session_id: &SessionId,
602        _request: SubmitTaskRequest,
603    ) -> Result<(), SessionError> {
604        Err(SessionError::Operation(
605            "Host does not support tasks".to_string(),
606        ))
607    }
608
609    /// Loads the desired outcome and retained attempt history.
610    async fn get_task(&self, _task_id: &str) -> Result<Option<Task>, SessionError> {
611        Err(SessionError::Operation(
612            "Host does not support tasks".to_string(),
613        ))
614    }
615
616    /// Explicitly accepts the task outcome after all attempts have settled.
617    async fn complete_task(&self, _task_id: &str) -> Result<(), SessionError> {
618        Err(SessionError::Operation(
619            "Host does not support tasks".to_string(),
620        ))
621    }
622
623    /// Describes the active project new sessions are created in. Older hosts
624    /// may omit it.
625    async fn host_context(&self) -> Result<HostContext, SessionError> {
626        Err(SessionError::Operation(
627            "Host does not describe its project".to_string(),
628        ))
629    }
630
631    /// Reports the active project's branch, its distance from upstream, and
632    /// its latest explicit sync. Older hosts may omit it.
633    async fn project_status(&self) -> Result<HostProjectStatus, SessionError> {
634        Err(SessionError::Operation(
635            "Host does not report its project status".to_string(),
636        ))
637    }
638
639    /// Starts or queues a sync of the active project's branch with its
640    /// upstream: a pull with rebase, then a push, with agent-assisted
641    /// conflict resolution. The host acknowledges admission and reports
642    /// progress through [`Self::project_status`]. Older hosts may omit
643    /// support.
644    async fn sync_project(&self) -> Result<(), SessionError> {
645        Err(SessionError::Operation(
646            "Host does not support syncing its project".to_string(),
647        ))
648    }
649
650    /// Creates one session and returns its stable identifier.
651    async fn create_session(
652        &self,
653        request: CreateSessionRequest,
654    ) -> Result<SessionId, SessionError>;
655
656    /// Loads one complete session aggregate, including settings and messages.
657    async fn get_session(&self, session_id: &SessionId) -> Result<Option<Session>, SessionError>;
658
659    /// Loads the files a session changes against its base branch, or `None`
660    /// when the host has not loaded the session. Hosts that do not serve
661    /// diffs report it as an error.
662    async fn get_session_diff(
663        &self,
664        session_id: &SessionId,
665    ) -> Result<Option<Vec<SessionDiffFile>>, SessionError> {
666        let _ = session_id;
667
668        Err(SessionError::Operation(
669            "Host does not serve session diffs".to_string(),
670        ))
671    }
672
673    /// Lists the files and directories in a session's worktree, directories
674    /// first, or `None` when the host has not loaded the session. Hosts that
675    /// do not serve file listings report it as an error.
676    async fn list_session_files(
677        &self,
678        session_id: &SessionId,
679    ) -> Result<Option<Vec<SessionFileEntry>>, SessionError> {
680        let _ = session_id;
681
682        Err(SessionError::Operation(
683            "Host does not serve session files".to_string(),
684        ))
685    }
686
687    /// Lists the files and directories in the active project's checkout,
688    /// directories first. Hosts that do not serve project file listings
689    /// report it as an error.
690    async fn list_project_files(&self) -> Result<Vec<SessionFileEntry>, SessionError> {
691        Err(SessionError::Operation(
692            "Host does not serve project files".to_string(),
693        ))
694    }
695
696    /// Lists the host's loaded sessions in its display order. Older hosts
697    /// may omit listing support.
698    async fn list_sessions(&self) -> Result<Vec<SessionSummary>, SessionError> {
699        Err(SessionError::Operation(
700            "Host does not support session listing".to_string(),
701        ))
702    }
703
704    /// Lists the host's loaded sessions in its display order, with the
705    /// figures a dense list shows. Hosts that do not provide them return
706    /// [`Self::list_sessions`] without stats.
707    async fn list_session_entries(&self) -> Result<Vec<SessionListEntry>, SessionError> {
708        let summaries = self.list_sessions().await?;
709
710        Ok(summaries.into_iter().map(SessionListEntry::from).collect())
711    }
712
713    /// Sends one text message, starting, resuming, or queueing as appropriate.
714    async fn send_message(
715        &self,
716        session_id: &SessionId,
717        message: String,
718    ) -> Result<(), SessionError>;
719
720    /// Sends one message with images, which the host stores itself and
721    /// attaches as `[Image #n]`, numbered in `images` order from 1. A
722    /// placeholder `message` lacks is appended to it. Older hosts may omit
723    /// support.
724    async fn send_message_with_images(
725        &self,
726        session_id: &SessionId,
727        message: String,
728        images: Vec<MessageImage>,
729    ) -> Result<(), SessionError> {
730        let _ = (session_id, message, images);
731
732        Err(SessionError::Operation(
733            "Host does not support images in messages".to_string(),
734        ))
735    }
736
737    /// Submits a durable turn without entering the lossy live-chat
738    /// queue used while an ordinary user turn is active.
739    async fn submit_durable_message(
740        &self,
741        session_id: &SessionId,
742        request: DurableMessageRequest,
743    ) -> Result<(), SessionError>;
744
745    /// Answers the complete current clarification-question set.
746    async fn answer_questions(
747        &self,
748        session_id: &SessionId,
749        request: AnswerQuestionsRequest,
750    ) -> Result<(), SessionError>;
751
752    /// Cancels one session through the host lifecycle workflow.
753    async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
754
755    /// Stops the session's running turn and returns the session to review,
756    /// keeping its worktree and changes. Older hosts may omit support.
757    async fn stop_turn(&self, session_id: &SessionId) -> Result<(), SessionError> {
758        let _ = session_id;
759
760        Err(SessionError::Operation(
761            "Host does not support stopping a turn".to_string(),
762        ))
763    }
764
765    /// Starts or queues a rebase of the session branch onto its base
766    /// branch; a conflict starts an agent-assisted resolution turn. Older
767    /// hosts may omit support.
768    async fn rebase_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
769        let _ = session_id;
770
771        Err(SessionError::Operation(
772            "Host does not support syncing a session branch".to_string(),
773        ))
774    }
775
776    /// Changes the session's settings for later turns. A model or speed
777    /// change waits while the session still has accepted work. Older hosts
778    /// may omit support.
779    async fn update_session_settings(
780        &self,
781        session_id: &SessionId,
782        change: SessionSettingsChange,
783    ) -> Result<(), SessionError> {
784        let _ = (session_id, change);
785
786        Err(SessionError::Operation(
787            "Host does not support changing session settings".to_string(),
788        ))
789    }
790
791    /// Requests merge processing for one review-ready session.
792    async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
793
794    /// Queues publication of one session branch and creates or refreshes its
795    /// review request.
796    async fn create_review_request(
797        &self,
798        session_id: &SessionId,
799    ) -> Result<ReviewRequest, SessionError>;
800}
801
802/// Stable programmatic facade for session lifecycle operations.
803#[derive(Clone)]
804pub struct SessionService {
805    backend: Arc<dyn SessionBackend>,
806}
807
808/// Explicit static-graph launch, separate from ordinary chat.
809#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
810pub struct StartExecutionGraphRequest {
811    /// Validated immutable snapshot to save before admitting nodes.
812    pub graph: crate::ExecutionGraph,
813    /// Provider calls shared by nodes naming the same budget, including
814    /// repairs. These limits cannot be replenished by redelivering an
815    /// active launch.
816    pub provider_call_limits: std::collections::BTreeMap<String, usize>,
817}
818
819impl SessionService {
820    /// Generates a proposal through the host's bounded worker workflow.
821    ///
822    /// # Errors
823    /// Returns admission, permissions, or persistence errors.
824    pub async fn generate_graph_proposal(
825        &self,
826        request: crate::GenerateGraphProposalRequest,
827    ) -> Result<(), SessionError> {
828        self.backend.generate_graph_proposal(request).await
829    }
830
831    /// Queries pending, restored, or approved state without execution.
832    ///
833    /// # Errors
834    /// Returns query delivery or persistence errors.
835    pub async fn get_graph_proposal(
836        &self,
837        id: &str,
838    ) -> Result<Option<crate::GraphProposalState>, SessionError> {
839        self.backend.get_graph_proposal(id).await
840    }
841
842    /// Answers the complete question set on an exact proposal version.
843    ///
844    /// # Errors
845    /// Returns stale-version, incomplete-answer, or generation-limit errors.
846    pub async fn answer_graph_proposal(
847        &self,
848        id: &str,
849        version: u32,
850        answers: Vec<String>,
851    ) -> Result<(), SessionError> {
852        self.backend
853            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Answer(answers))
854            .await
855    }
856
857    /// Regenerates within the original captured generation ceiling.
858    ///
859    /// # Errors
860    /// Returns stale-version, approved-proposal, or exhausted-limit errors.
861    pub async fn regenerate_graph_proposal(
862        &self,
863        id: &str,
864        version: u32,
865    ) -> Result<(), SessionError> {
866        self.backend
867            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Regenerate)
868            .await
869    }
870
871    /// Regenerates with user feedback, including its images, added to the
872    /// generation history, within the original captured generation ceiling.
873    ///
874    /// # Errors
875    /// Returns stale-version, empty-feedback, approved-proposal, or
876    /// exhausted-limit errors.
877    pub async fn revise_graph_proposal(
878        &self,
879        id: &str,
880        version: u32,
881        feedback: TurnPrompt,
882    ) -> Result<(), SessionError> {
883        self.backend
884            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Revise(feedback))
885            .await
886    }
887
888    /// Approves the exact preview before dispatch. Redelivery never dispatches.
889    ///
890    /// # Errors
891    /// Returns stale-version, resolution, permissions, or publication errors.
892    pub async fn approve_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
893        self.backend
894            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Approve)
895            .await
896    }
897
898    /// Cancels a pending proposal and any active generating utility.
899    ///
900    /// # Errors
901    /// Returns stale-version or already-approved errors.
902    pub async fn cancel_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
903        self.backend
904            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Cancel)
905            .await
906    }
907
908    /// Reads graph/node progress and immutable execution history.
909    ///
910    /// # Errors
911    /// Returns failed persistence or query delivery errors.
912    pub async fn get_execution_graph(
913        &self,
914        graph_id: &str,
915    ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
916        self.backend.get_execution_graph(graph_id).await
917    }
918
919    /// Reads a session's graphs as an inspector shows them: every graph,
920    /// the latest proposal with its preview, and the selected graph with
921    /// its live progress and the selected node's outputs.
922    ///
923    /// # Errors
924    /// Rejects a `graph_id` of another session, and returns failed
925    /// persistence or query delivery errors.
926    pub async fn session_graphs(
927        &self,
928        request: crate::SessionGraphsRequest,
929    ) -> Result<crate::SessionGraphs, SessionError> {
930        self.backend.session_graphs(request).await
931    }
932
933    /// Accepts an output, cancels, resumes, or retries a graph, replies to
934    /// one of its nodes, or adds provider calls to its spent budget, as the
935    /// graph's inspector does.
936    ///
937    /// # Errors
938    /// Rejects a graph of another session, a graph that changed since
939    /// `request.snapshot` was read, an action that snapshot does not offer,
940    /// an empty reply, and a budget increase outside
941    /// `1..=`[`crate::ExtendGraphBudgetRequest::MAX_ADDITIONAL_CALLS`], and
942    /// returns failed admission or delivery errors.
943    pub async fn act_on_session_graph(
944        &self,
945        request: crate::SessionGraphActionRequest,
946    ) -> Result<(), SessionError> {
947        self.backend.act_on_session_graph(request).await
948    }
949
950    /// Permanently cancels this graph without canceling unrelated session work.
951    ///
952    /// # Errors
953    /// Rejects missing/stale graphs and failed durable cancellation.
954    pub async fn cancel_execution_graph(
955        &self,
956        request: crate::GraphControlRequest,
957    ) -> Result<(), SessionError> {
958        self.backend.cancel_execution_graph(request).await
959    }
960
961    /// Resumes dispatch explicitly; failed nodes still require a new action.
962    ///
963    /// # Errors
964    /// Rejects canceled/stale graphs, graphs without recorded launch limits,
965    /// or ineligible sessions.
966    pub async fn resume_execution_graph(
967        &self,
968        request: crate::ResumeExecutionGraphRequest,
969    ) -> Result<(), SessionError> {
970        self.backend.resume_execution_graph(request).await
971    }
972
973    /// Adds provider calls to one launched budget through a recorded,
974    /// idempotent extension; the launch limits stay unchanged.
975    ///
976    /// # Errors
977    /// Rejects stale, completed, or canceled graphs, unknown budgets,
978    /// amounts outside `1..=ExtendGraphBudgetRequest::MAX_ADDITIONAL_CALLS`,
979    /// conflicting action identities, and failed persistence.
980    pub async fn extend_execution_graph_budget(
981        &self,
982        request: crate::ExtendGraphBudgetRequest,
983    ) -> Result<(), SessionError> {
984        self.backend.extend_execution_graph_budget(request).await
985    }
986
987    /// Retries a failed node or answers its exact settled clarification set.
988    ///
989    /// # Errors
990    /// Rejects stale sources, partial answers, conflicting action identities,
991    /// canceled graphs, and failed persistence or delivery.
992    pub async fn continue_execution_graph_node(
993        &self,
994        request: crate::ContinueGraphNodeRequest,
995    ) -> Result<(), SessionError> {
996        self.backend.continue_execution_graph_node(request).await
997    }
998
999    /// Starts an explicit static graph without waiting for model execution.
1000    ///
1001    /// # Errors
1002    /// Rejects unsupported profiles, stale/conflicting identities, missing
1003    /// budgets, ineligible sessions, and failed persistence or delivery.
1004    pub async fn start_execution_graph(
1005        &self,
1006        request: StartExecutionGraphRequest,
1007    ) -> Result<(), SessionError> {
1008        self.backend.start_execution_graph(request).await
1009    }
1010
1011    /// Accepts one exact validated output and releases its acceptance gate.
1012    ///
1013    /// # Errors
1014    /// Rejects stale or unvalidated references and failed persistence.
1015    pub async fn accept_execution_graph_result(
1016        &self,
1017        reference: crate::GraphResultRef,
1018    ) -> Result<(), SessionError> {
1019        self.backend.accept_execution_graph_result(reference).await
1020    }
1021
1022    /// Accepts a standalone Planner version from durable task history.
1023    ///
1024    /// # Errors
1025    /// Returns an error for stale/ineligible versions or failed persistence.
1026    pub async fn accept_agent_plan(
1027        &self,
1028        session_id: &SessionId,
1029        request: AcceptTaskPlanRequest,
1030    ) -> Result<(), SessionError> {
1031        self.backend.accept_agent_plan(session_id, request).await
1032    }
1033
1034    /// Creates an owned session capability backed by a shared host handle.
1035    pub fn new(backend: Arc<dyn SessionBackend>) -> Self {
1036        Self { backend }
1037    }
1038
1039    /// Admits an isolated role-bound attempt, acknowledging durable admission.
1040    /// Identical redeliveries do not execute again. Task completion is
1041    /// explicit.
1042    ///
1043    /// # Errors
1044    /// Returns an error for invalid input, unaccepted implementation plans,
1045    /// conflicting identity, or a session unable to accept work.
1046    pub async fn submit_agent_task(
1047        &self,
1048        session_id: &SessionId,
1049        request: crate::SubmitAgentTaskRequest,
1050    ) -> Result<(), SessionError> {
1051        self.backend.submit_agent_task(session_id, request).await
1052    }
1053
1054    /// Reads the task's own responses. Attempt status remains authoritative.
1055    ///
1056    /// # Errors
1057    /// Returns an error when the host cannot load the isolated conversation.
1058    pub async fn get_agent_task_history(
1059        &self,
1060        task_id: &str,
1061    ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
1062        self.backend.get_agent_task_history(task_id).await
1063    }
1064
1065    /// Persists a task with zero attempts in an existing session, regardless
1066    /// of its execution status. Does not start work or change session state.
1067    /// Identical creation requests preserve the task and its history.
1068    ///
1069    /// # Errors
1070    /// Returns an error for empty inputs, conflicting identity, a missing
1071    /// session, or a host that cannot persist tasks.
1072    pub async fn create_task(
1073        &self,
1074        session_id: &SessionId,
1075        request: CreateTaskRequest,
1076    ) -> Result<(), SessionError> {
1077        self.backend.create_task(session_id, request).await
1078    }
1079
1080    /// Lists all tasks owned by a session in creation order, including their
1081    /// attempt histories in one snapshot. Equal timestamps retain insertion
1082    /// order. Returns an empty list for a missing session or one without tasks.
1083    ///
1084    /// # Errors
1085    /// Returns an error when the host cannot read tasks.
1086    pub async fn list_tasks(&self, session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
1087        self.backend.list_tasks(session_id).await
1088    }
1089
1090    /// Admits one task attempt through the existing serialized session worker.
1091    /// Creates the task atomically if it does not already exist.
1092    /// Acceptance does not wait for execution or imply task completion.
1093    /// Identical deliveries are acknowledged without running again.
1094    ///
1095    /// # Errors
1096    /// Returns an error for conflicting identity, an unavailable host, a
1097    /// completed task, or a session that cannot accept a new durable turn.
1098    pub async fn submit_task(
1099        &self,
1100        session_id: &SessionId,
1101        request: SubmitTaskRequest,
1102    ) -> Result<(), SessionError> {
1103        self.backend.submit_task(session_id, request).await
1104    }
1105
1106    /// Loads a task and all its attempts from durable storage.
1107    ///
1108    /// # Errors
1109    /// Returns an error when the host cannot read tasks.
1110    pub async fn get_task(&self, task_id: &str) -> Result<Option<Task>, SessionError> {
1111        self.backend.get_task(task_id).await
1112    }
1113
1114    /// Explicitly accepts the outcome. Successful model execution alone never
1115    /// completes a task. Repeated completion retains its original timestamp.
1116    ///
1117    /// # Errors
1118    /// Returns an error if the task is missing, an attempt is unfinished, or
1119    /// the host cannot persist completion.
1120    pub async fn complete_task(&self, task_id: &str) -> Result<(), SessionError> {
1121        self.backend.complete_task(task_id).await
1122    }
1123
1124    /// Reports whether the host serves `operation` to frontends that ask
1125    /// first.
1126    #[must_use]
1127    pub fn supports(&self, operation: SessionOperation) -> bool {
1128        self.backend.supports(operation)
1129    }
1130
1131    /// Describes the active project new sessions are created in.
1132    ///
1133    /// # Errors
1134    /// Returns an error when the host does not describe its project or
1135    /// cannot load its defaults.
1136    pub async fn host_context(&self) -> Result<HostContext, SessionError> {
1137        self.backend.host_context().await
1138    }
1139
1140    /// Reports the active project's branch, its distance from upstream, and
1141    /// its latest explicit sync.
1142    ///
1143    /// # Errors
1144    /// Returns an error when the host does not report its project status.
1145    pub async fn project_status(&self) -> Result<HostProjectStatus, SessionError> {
1146        self.backend.project_status().await
1147    }
1148
1149    /// Starts or queues a sync of the active project's branch with its
1150    /// upstream. The host acknowledges admission; [`Self::project_status`]
1151    /// reports the progress and the outcome.
1152    ///
1153    /// # Errors
1154    /// Returns an error when the host cannot start the sync now, such as
1155    /// while a merge runs, or does not support syncing its project.
1156    pub async fn sync_project(&self) -> Result<(), SessionError> {
1157        self.backend.sync_project().await
1158    }
1159
1160    /// Creates one session and returns its stable identifier.
1161    ///
1162    /// # Errors
1163    /// Returns an error when the host cannot create the requested session.
1164    pub async fn create_session(
1165        &self,
1166        request: CreateSessionRequest,
1167    ) -> Result<SessionId, SessionError> {
1168        self.backend.create_session(request).await
1169    }
1170
1171    /// Loads one complete session aggregate by identifier.
1172    ///
1173    /// # Errors
1174    /// Returns an error when persisted data cannot be loaded or decoded.
1175    pub async fn get_session(
1176        &self,
1177        session_id: &SessionId,
1178    ) -> Result<Option<Session>, SessionError> {
1179        self.backend.get_session(session_id).await
1180    }
1181
1182    /// Loads the files one session changes against its base branch, or
1183    /// `None` when the host has not loaded the session.
1184    ///
1185    /// # Errors
1186    /// Returns an error when the host does not serve diffs or cannot compute
1187    /// or load this one.
1188    pub async fn get_session_diff(
1189        &self,
1190        session_id: &SessionId,
1191    ) -> Result<Option<Vec<SessionDiffFile>>, SessionError> {
1192        self.backend.get_session_diff(session_id).await
1193    }
1194
1195    /// Lists the files and directories in one session's worktree,
1196    /// directories first, or `None` when the host has not loaded the
1197    /// session.
1198    ///
1199    /// # Errors
1200    /// Returns an error when the host does not serve file listings or cannot
1201    /// read this one.
1202    pub async fn list_session_files(
1203        &self,
1204        session_id: &SessionId,
1205    ) -> Result<Option<Vec<SessionFileEntry>>, SessionError> {
1206        self.backend.list_session_files(session_id).await
1207    }
1208
1209    /// Lists the files and directories in the active project's checkout,
1210    /// directories first.
1211    ///
1212    /// # Errors
1213    /// Returns an error when the host does not serve project file listings
1214    /// or cannot read the checkout.
1215    pub async fn list_project_files(&self) -> Result<Vec<SessionFileEntry>, SessionError> {
1216        self.backend.list_project_files().await
1217    }
1218
1219    /// Lists the host's loaded sessions in its display order.
1220    ///
1221    /// # Errors
1222    /// Returns an error when the host cannot list sessions.
1223    pub async fn list_sessions(&self) -> Result<Vec<SessionSummary>, SessionError> {
1224        self.backend.list_sessions().await
1225    }
1226
1227    /// Lists the host's loaded sessions in its display order, with list
1228    /// stats when the host provides them.
1229    ///
1230    /// # Errors
1231    /// Returns an error when the host cannot list sessions.
1232    pub async fn list_session_entries(&self) -> Result<Vec<SessionListEntry>, SessionError> {
1233        self.backend.list_session_entries().await
1234    }
1235
1236    /// Sends a text message to one session.
1237    ///
1238    /// # Errors
1239    /// Returns an error when the session cannot accept or enqueue the message.
1240    pub async fn send_message(
1241        &self,
1242        session_id: &SessionId,
1243        message: impl Into<String> + Send,
1244    ) -> Result<(), SessionError> {
1245        self.backend.send_message(session_id, message.into()).await
1246    }
1247
1248    /// Sends a message with images to one session. The host attaches the
1249    /// images as `[Image #n]`, numbered in `images` order from 1.
1250    ///
1251    /// # Errors
1252    /// Returns an error when the host does not take images in messages, or
1253    /// the session cannot accept or enqueue the message.
1254    pub async fn send_message_with_images(
1255        &self,
1256        session_id: &SessionId,
1257        message: impl Into<String> + Send,
1258        images: Vec<MessageImage>,
1259    ) -> Result<(), SessionError> {
1260        self.backend
1261            .send_message_with_images(session_id, message.into(), images)
1262            .await
1263    }
1264
1265    /// Submits one durable turn directly to the serialized worker.
1266    ///
1267    /// # Errors
1268    /// Returns an error when the session is busy or cannot accept the turn.
1269    pub async fn submit_durable_message(
1270        &self,
1271        session_id: &SessionId,
1272        request: DurableMessageRequest,
1273    ) -> Result<(), SessionError> {
1274        self.backend
1275            .submit_durable_message(session_id, request)
1276            .await
1277    }
1278
1279    /// Answers the complete current clarification-question set.
1280    ///
1281    /// # Errors
1282    /// Returns an error when the answers are stale, incomplete, or cannot be
1283    /// enqueued as a follow-up turn.
1284    pub async fn answer_questions(
1285        &self,
1286        session_id: &SessionId,
1287        request: AnswerQuestionsRequest,
1288    ) -> Result<(), SessionError> {
1289        self.backend.answer_questions(session_id, request).await
1290    }
1291
1292    /// Cancels one session through its host lifecycle workflow.
1293    ///
1294    /// # Errors
1295    /// Returns an error when the session does not exist or cannot be canceled
1296    /// in its current state.
1297    pub async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1298        self.backend.cancel_session(session_id).await
1299    }
1300
1301    /// Stops the session's running turn and returns the session to review.
1302    /// Unlike [`Self::cancel_session`], the worktree and its changes stay;
1303    /// messages queued behind the turn are discarded.
1304    ///
1305    /// # Errors
1306    /// Returns an error when the session does not exist, has no running
1307    /// turn, or the host does not support stopping a turn.
1308    pub async fn stop_turn(&self, session_id: &SessionId) -> Result<(), SessionError> {
1309        self.backend.stop_turn(session_id).await
1310    }
1311
1312    /// Starts or queues a rebase of the session branch onto its base branch.
1313    /// The host acknowledges admission; a conflict starts an agent-assisted
1314    /// resolution turn.
1315    ///
1316    /// # Errors
1317    /// Returns an error when the session does not exist, cannot be rebased in
1318    /// its current state, or the host does not support syncing.
1319    pub async fn rebase_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1320        self.backend.rebase_session(session_id).await
1321    }
1322
1323    /// Changes the session's model, reasoning, style, or speed for later
1324    /// turns, where the terminal's composer could change them.
1325    ///
1326    /// The host refuses the whole change, applying none of it, when the
1327    /// session's status has no composer, the model is not one the session's
1328    /// agent offers, or fast mode does not suit the model the session will
1329    /// have. It then applies the model, reasoning, style, and speed in that
1330    /// order. Reasoning and style apply at once; a model or speed change
1331    /// waits while the session still has accepted work. Changes are not
1332    /// transactional: when one fails to apply, the ones before it stay
1333    /// applied.
1334    ///
1335    /// # Errors
1336    /// Returns an error when the session does not exist or its status has no
1337    /// composer, a model is not available to it, fast mode does not suit the
1338    /// resulting model, switching or persisting a setting fails, or the host
1339    /// does not support the change.
1340    pub async fn update_session_settings(
1341        &self,
1342        session_id: &SessionId,
1343        change: SessionSettingsChange,
1344    ) -> Result<(), SessionError> {
1345        self.backend
1346            .update_session_settings(session_id, change)
1347            .await
1348    }
1349
1350    /// Requests merge processing for one session.
1351    ///
1352    /// # Errors
1353    /// Returns an error when the session is not mergeable or queueing fails.
1354    pub async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1355        self.backend.merge_session(session_id).await
1356    }
1357
1358    /// Queues publication of one session and creates or refreshes its review
1359    /// request.
1360    ///
1361    /// # Errors
1362    /// Returns an error when queueing, branch publication, forge access, or
1363    /// persistence fails.
1364    pub async fn create_review_request(
1365        &self,
1366        session_id: &SessionId,
1367    ) -> Result<ReviewRequest, SessionError> {
1368        self.backend.create_review_request(session_id).await
1369    }
1370}
1371
1372#[cfg(test)]
1373#[path = "service_test.rs"]
1374mod tests;