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, AgentModel, AgentSelection, CreateTaskRequest, ReasoningLevel,
12    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}
60
61/// Idempotent turn submitted to one session.
62#[derive(Clone, Debug, Eq, PartialEq)]
63pub struct DurableMessageRequest {
64    /// Agent-facing prompt.
65    pub message: String,
66    /// Stable operation identifier reused when delivery is retried.
67    pub operation_id: String,
68    /// Whether the machine-authored prompt is shown in the human transcript.
69    pub visibility: DurableMessageVisibility,
70}
71
72/// Transcript treatment for one durable prompt.
73#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
74pub enum DurableMessageVisibility {
75    /// Deliver generated context without displaying it as user chat.
76    #[default]
77    Hidden,
78    /// Display the submitted instruction in session history.
79    Visible,
80}
81
82/// Operation a host may choose to serve to frontends that check
83/// [`SessionService::supports`] first, such as remote control.
84///
85/// A frontend offers an operation only when the host reports it, so adding a
86/// variant never exposes an operation that an existing host has not opted
87/// into.
88#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
89#[non_exhaustive]
90pub enum SessionOperation {
91    /// Creating a session in the active project through
92    /// [`SessionBackend::create_session`].
93    CreateSession,
94    /// Describing the active project through
95    /// [`SessionBackend::host_context`].
96    HostContext,
97    /// Merging a review-ready session through
98    /// [`SessionBackend::merge_session`].
99    MergeSession,
100    /// Reading a session's changes through
101    /// [`SessionBackend::get_session_diff`].
102    SessionDiff,
103    /// Listing the files and directories in a session's worktree through
104    /// [`SessionBackend::list_session_files`].
105    SessionFiles,
106    /// Stopping a running turn through [`SessionBackend::stop_turn`].
107    StopTurn,
108    /// Rebasing a session branch onto its base branch through
109    /// [`SessionBackend::rebase_session`].
110    RebaseSession,
111    /// Changing a session's model, reasoning, style, or speed through
112    /// [`SessionBackend::update_session_settings`].
113    SessionSettings,
114    /// Publishing a session to its existing branch, or under its default name
115    /// the first time, and creating or refreshing its review request through
116    /// [`SessionBackend::create_review_request`].
117    PublishSession,
118}
119
120/// Settings to change on one session; `None` keeps a setting as it is.
121#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
122pub struct SessionSettingsChange {
123    /// Model to switch to; the session's own agent runs it, as in the
124    /// terminal's `/model`.
125    pub model: Option<AgentModel>,
126    /// Reasoning level to use for later turns.
127    pub reasoning_level: Option<ReasoningLevel>,
128    /// Response style to use for later turns.
129    pub response_style: Option<ResponseStyle>,
130    /// Response speed to use for later turns.
131    pub speed_mode: Option<SpeedMode>,
132}
133
134/// One file a session's diff changes.
135#[derive(Clone, Debug, Eq, PartialEq)]
136pub struct SessionDiffFile {
137    /// Lines the file's patch adds.
138    pub added_lines: u64,
139    /// Lines the file's patch removes.
140    pub deleted_lines: u64,
141    /// Path before a rename, or `None` when the path did not change.
142    pub old_path: Option<String>,
143    /// The file's unified diff, including its `diff --git` header.
144    pub patch: String,
145    /// Path after the change; a deleted file keeps its old path.
146    pub path: String,
147    /// How the change affects the file.
148    pub status: SessionDiffFileStatus,
149}
150
151/// How a session's diff changes one file.
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub enum SessionDiffFileStatus {
154    /// The file is new.
155    Added,
156    /// The file is removed.
157    Deleted,
158    /// The file's contents or mode changed.
159    Modified,
160    /// The file moved, possibly with changes.
161    Renamed,
162}
163
164/// One file or directory in a session's worktree.
165#[derive(Clone, Debug, Eq, PartialEq)]
166pub struct SessionFileEntry {
167    /// Whether the entry is a directory.
168    pub is_dir: bool,
169    /// Path relative to the worktree root, with `/` separators.
170    pub path: String,
171}
172
173/// The project a host creates new sessions in, and how it creates them.
174#[derive(Clone, Debug, Eq, PartialEq)]
175pub struct HostContext {
176    /// Branch new sessions start from.
177    pub base_branch: String,
178    /// Model a new session in the first of `session_modes` starts with: the
179    /// harness model when only Harness sessions are offered, otherwise the
180    /// regular agent's default.
181    pub default_model: AgentModel,
182    /// Agents and models a session can switch to now, in display order.
183    /// A session switches only among the entries of its own agent, as the
184    /// terminal's `/model` offers them; each gives the model's id and name.
185    pub models: Vec<AgentSelection>,
186    /// Identifier of the active project, the only one that accepts new
187    /// sessions.
188    pub project_id: i64,
189    /// Display name of the active project.
190    pub project_name: String,
191    /// Creation modes the host can serve now, in display order, each with
192    /// the agent and model its new sessions start with.
193    pub session_modes: Vec<HostSessionMode>,
194}
195
196/// One creation mode a host serves, and how its new sessions start.
197#[derive(Clone, Debug, Eq, PartialEq)]
198pub struct HostSessionMode {
199    /// Agent and model a new session in this mode starts with.
200    pub agent: AgentSelection,
201    /// Creation mode.
202    pub mode: CreateSessionMode,
203}
204
205/// Host implementation boundary for session persistence and workflows.
206///
207/// The trait is object-safe so agent loops and background workflows can hold a
208/// programmatic session capability without depending on a concrete frontend.
209#[async_trait]
210pub trait SessionBackend: Send + Sync {
211    /// Reports whether the host serves `operation` to frontends that ask
212    /// first. Hosts serve none unless they opt in.
213    fn supports(&self, operation: SessionOperation) -> bool {
214        let _ = operation;
215
216        false
217    }
218
219    /// Reserves generation without waiting for model completion.
220    async fn generate_graph_proposal(
221        &self,
222        request: crate::GenerateGraphProposalRequest,
223    ) -> Result<(), SessionError> {
224        let _ = request;
225        Err(SessionError::Operation(
226            "Host does not support graph proposals".into(),
227        ))
228    }
229
230    /// Reads retained state without generating or launching work.
231    async fn get_graph_proposal(
232        &self,
233        id: &str,
234    ) -> Result<Option<crate::GraphProposalState>, SessionError> {
235        let _ = id;
236        Err(SessionError::Operation(
237            "Host does not support graph proposals".into(),
238        ))
239    }
240
241    /// Applies an explicit action to the exact inspected version.
242    async fn act_on_graph_proposal(
243        &self,
244        id: &str,
245        version: u32,
246        action: crate::GraphProposalAction,
247    ) -> Result<(), SessionError> {
248        let _ = (id, version, action);
249        Err(SessionError::Operation(
250            "Host does not support graph proposals".into(),
251        ))
252    }
253
254    /// Reads durable progress without launching or retrying work.
255    async fn get_execution_graph(
256        &self,
257        graph_id: &str,
258    ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
259        let _ = graph_id;
260
261        Err(SessionError::Operation(
262            "Host does not support execution graphs".into(),
263        ))
264    }
265
266    /// Closes graph admission durably, then signals its owned workers.
267    async fn cancel_execution_graph(
268        &self,
269        request: crate::GraphControlRequest,
270    ) -> Result<(), SessionError> {
271        let _ = request;
272
273        Err(SessionError::Operation(
274            "Host does not support execution graphs".into(),
275        ))
276    }
277
278    /// Explicitly restarts dispatch without replaying admitted executions.
279    async fn resume_execution_graph(
280        &self,
281        request: crate::ResumeExecutionGraphRequest,
282    ) -> Result<(), SessionError> {
283        let _ = request;
284
285        Err(SessionError::Operation(
286            "Host does not support execution graphs".into(),
287        ))
288    }
289
290    /// Records an explicit increase of one budget's provider calls, then
291    /// releases nodes waiting for that credit.
292    async fn extend_execution_graph_budget(
293        &self,
294        request: crate::ExtendGraphBudgetRequest,
295    ) -> Result<(), SessionError> {
296        let _ = request;
297
298        Err(SessionError::Operation(
299            "Host does not support execution graphs".into(),
300        ))
301    }
302
303    /// Authorizes one new attempt against an exact failed/question execution.
304    async fn continue_execution_graph_node(
305        &self,
306        request: crate::ContinueGraphNodeRequest,
307    ) -> Result<(), SessionError> {
308        let _ = request;
309
310        Err(SessionError::Operation(
311            "Host does not support execution graphs".into(),
312        ))
313    }
314
315    /// Saves and starts a static graph. Existing admitted nodes are never
316    /// replayed. Named budgets are fixed at first launch and their spending is
317    /// recorded durably, so relaunching never replenishes them.
318    async fn start_execution_graph(
319        &self,
320        request: StartExecutionGraphRequest,
321    ) -> Result<(), SessionError> {
322        let _ = request;
323
324        Err(SessionError::Operation(
325            "Host does not support execution graphs".into(),
326        ))
327    }
328
329    /// Records explicit acceptance of an exact graph output and wakes ready
330    /// dependents. Model output must never call this trusted host boundary.
331    async fn accept_execution_graph_result(
332        &self,
333        reference: crate::GraphResultRef,
334    ) -> Result<(), SessionError> {
335        let _ = reference;
336
337        Err(SessionError::Operation(
338            "Host does not support execution graphs".into(),
339        ))
340    }
341    /// Admits a role-bound attempt with its own isolated conversation.
342    async fn submit_agent_task(
343        &self,
344        session_id: &SessionId,
345        request: crate::SubmitAgentTaskRequest,
346    ) -> Result<(), SessionError> {
347        let _ = (session_id, request);
348
349        Err(SessionError::Operation(
350            "Host does not support role-aware tasks".to_string(),
351        ))
352    }
353
354    /// Reads isolated task responses without exposing host storage types.
355    async fn get_agent_task_history(
356        &self,
357        task_id: &str,
358    ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
359        let _ = task_id;
360
361        Err(SessionError::Operation(
362            "Host does not support role-aware tasks".to_string(),
363        ))
364    }
365
366    /// Explicitly accepts a standalone Planner response by producing version.
367    async fn accept_agent_plan(
368        &self,
369        _session_id: &SessionId,
370        _request: AcceptTaskPlanRequest,
371    ) -> Result<(), SessionError> {
372        Err(SessionError::Operation(
373            "Host does not support plan acceptance".into(),
374        ))
375    }
376
377    /// Persists an outcome without execution. Older hosts may omit support.
378    async fn create_task(
379        &self,
380        _session_id: &SessionId,
381        _request: CreateTaskRequest,
382    ) -> Result<(), SessionError> {
383        Err(SessionError::Operation(
384            "Host does not support tasks".to_string(),
385        ))
386    }
387
388    /// Lists a session's tasks, including unattempted and completed outcomes.
389    async fn list_tasks(&self, _session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
390        Err(SessionError::Operation(
391            "Host does not support tasks".to_string(),
392        ))
393    }
394
395    /// Admits an explicit task attempt. Older hosts may omit task support.
396    async fn submit_task(
397        &self,
398        _session_id: &SessionId,
399        _request: SubmitTaskRequest,
400    ) -> Result<(), SessionError> {
401        Err(SessionError::Operation(
402            "Host does not support tasks".to_string(),
403        ))
404    }
405
406    /// Loads the desired outcome and retained attempt history.
407    async fn get_task(&self, _task_id: &str) -> Result<Option<Task>, SessionError> {
408        Err(SessionError::Operation(
409            "Host does not support tasks".to_string(),
410        ))
411    }
412
413    /// Explicitly accepts the task outcome after all attempts have settled.
414    async fn complete_task(&self, _task_id: &str) -> Result<(), SessionError> {
415        Err(SessionError::Operation(
416            "Host does not support tasks".to_string(),
417        ))
418    }
419
420    /// Describes the active project new sessions are created in. Older hosts
421    /// may omit it.
422    async fn host_context(&self) -> Result<HostContext, SessionError> {
423        Err(SessionError::Operation(
424            "Host does not describe its project".to_string(),
425        ))
426    }
427
428    /// Creates one session and returns its stable identifier.
429    async fn create_session(
430        &self,
431        request: CreateSessionRequest,
432    ) -> Result<SessionId, SessionError>;
433
434    /// Loads one complete session aggregate, including settings and messages.
435    async fn get_session(&self, session_id: &SessionId) -> Result<Option<Session>, SessionError>;
436
437    /// Loads the files a session changes against its base branch, or `None`
438    /// when the host has not loaded the session. Hosts that do not serve
439    /// diffs report it as an error.
440    async fn get_session_diff(
441        &self,
442        session_id: &SessionId,
443    ) -> Result<Option<Vec<SessionDiffFile>>, SessionError> {
444        let _ = session_id;
445
446        Err(SessionError::Operation(
447            "Host does not serve session diffs".to_string(),
448        ))
449    }
450
451    /// Lists the files and directories in a session's worktree, directories
452    /// first, or `None` when the host has not loaded the session. Hosts that
453    /// do not serve file listings report it as an error.
454    async fn list_session_files(
455        &self,
456        session_id: &SessionId,
457    ) -> Result<Option<Vec<SessionFileEntry>>, SessionError> {
458        let _ = session_id;
459
460        Err(SessionError::Operation(
461            "Host does not serve session files".to_string(),
462        ))
463    }
464
465    /// Lists the host's loaded sessions in its display order. Older hosts
466    /// may omit listing support.
467    async fn list_sessions(&self) -> Result<Vec<SessionSummary>, SessionError> {
468        Err(SessionError::Operation(
469            "Host does not support session listing".to_string(),
470        ))
471    }
472
473    /// Lists the host's loaded sessions in its display order, with the
474    /// figures a dense list shows. Hosts that do not provide them return
475    /// [`Self::list_sessions`] without stats.
476    async fn list_session_entries(&self) -> Result<Vec<SessionListEntry>, SessionError> {
477        let summaries = self.list_sessions().await?;
478
479        Ok(summaries.into_iter().map(SessionListEntry::from).collect())
480    }
481
482    /// Sends one text message, starting, resuming, or queueing as appropriate.
483    async fn send_message(
484        &self,
485        session_id: &SessionId,
486        message: String,
487    ) -> Result<(), SessionError>;
488
489    /// Submits a durable turn without entering the lossy live-chat
490    /// queue used while an ordinary user turn is active.
491    async fn submit_durable_message(
492        &self,
493        session_id: &SessionId,
494        request: DurableMessageRequest,
495    ) -> Result<(), SessionError>;
496
497    /// Answers the complete current clarification-question set.
498    async fn answer_questions(
499        &self,
500        session_id: &SessionId,
501        request: AnswerQuestionsRequest,
502    ) -> Result<(), SessionError>;
503
504    /// Cancels one session through the host lifecycle workflow.
505    async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
506
507    /// Stops the session's running turn and returns the session to review,
508    /// keeping its worktree and changes. Older hosts may omit support.
509    async fn stop_turn(&self, session_id: &SessionId) -> Result<(), SessionError> {
510        let _ = session_id;
511
512        Err(SessionError::Operation(
513            "Host does not support stopping a turn".to_string(),
514        ))
515    }
516
517    /// Starts or queues a rebase of the session branch onto its base
518    /// branch; a conflict starts an agent-assisted resolution turn. Older
519    /// hosts may omit support.
520    async fn rebase_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
521        let _ = session_id;
522
523        Err(SessionError::Operation(
524            "Host does not support syncing a session branch".to_string(),
525        ))
526    }
527
528    /// Changes the session's settings for later turns. A model or speed
529    /// change waits while the session still has accepted work. Older hosts
530    /// may omit support.
531    async fn update_session_settings(
532        &self,
533        session_id: &SessionId,
534        change: SessionSettingsChange,
535    ) -> Result<(), SessionError> {
536        let _ = (session_id, change);
537
538        Err(SessionError::Operation(
539            "Host does not support changing session settings".to_string(),
540        ))
541    }
542
543    /// Requests merge processing for one review-ready session.
544    async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
545
546    /// Queues publication of one session branch and creates or refreshes its
547    /// review request.
548    async fn create_review_request(
549        &self,
550        session_id: &SessionId,
551    ) -> Result<ReviewRequest, SessionError>;
552}
553
554/// Stable programmatic facade for session lifecycle operations.
555#[derive(Clone)]
556pub struct SessionService {
557    backend: Arc<dyn SessionBackend>,
558}
559
560/// Explicit static-graph launch, separate from ordinary chat.
561#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
562pub struct StartExecutionGraphRequest {
563    /// Validated immutable snapshot to save before admitting nodes.
564    pub graph: crate::ExecutionGraph,
565    /// Provider calls shared by nodes naming the same budget, including
566    /// repairs. These limits cannot be replenished by redelivering an
567    /// active launch.
568    pub provider_call_limits: std::collections::BTreeMap<String, usize>,
569}
570
571impl SessionService {
572    /// Generates a proposal through the host's bounded worker workflow.
573    ///
574    /// # Errors
575    /// Returns admission, permissions, or persistence errors.
576    pub async fn generate_graph_proposal(
577        &self,
578        request: crate::GenerateGraphProposalRequest,
579    ) -> Result<(), SessionError> {
580        self.backend.generate_graph_proposal(request).await
581    }
582
583    /// Queries pending, restored, or approved state without execution.
584    ///
585    /// # Errors
586    /// Returns query delivery or persistence errors.
587    pub async fn get_graph_proposal(
588        &self,
589        id: &str,
590    ) -> Result<Option<crate::GraphProposalState>, SessionError> {
591        self.backend.get_graph_proposal(id).await
592    }
593
594    /// Answers the complete question set on an exact proposal version.
595    ///
596    /// # Errors
597    /// Returns stale-version, incomplete-answer, or generation-limit errors.
598    pub async fn answer_graph_proposal(
599        &self,
600        id: &str,
601        version: u32,
602        answers: Vec<String>,
603    ) -> Result<(), SessionError> {
604        self.backend
605            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Answer(answers))
606            .await
607    }
608
609    /// Regenerates within the original captured generation ceiling.
610    ///
611    /// # Errors
612    /// Returns stale-version, approved-proposal, or exhausted-limit errors.
613    pub async fn regenerate_graph_proposal(
614        &self,
615        id: &str,
616        version: u32,
617    ) -> Result<(), SessionError> {
618        self.backend
619            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Regenerate)
620            .await
621    }
622
623    /// Regenerates with user feedback, including its images, added to the
624    /// generation history, within the original captured generation ceiling.
625    ///
626    /// # Errors
627    /// Returns stale-version, empty-feedback, approved-proposal, or
628    /// exhausted-limit errors.
629    pub async fn revise_graph_proposal(
630        &self,
631        id: &str,
632        version: u32,
633        feedback: TurnPrompt,
634    ) -> Result<(), SessionError> {
635        self.backend
636            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Revise(feedback))
637            .await
638    }
639
640    /// Approves the exact preview before dispatch. Redelivery never dispatches.
641    ///
642    /// # Errors
643    /// Returns stale-version, resolution, permissions, or publication errors.
644    pub async fn approve_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
645        self.backend
646            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Approve)
647            .await
648    }
649
650    /// Cancels a pending proposal and any active generating utility.
651    ///
652    /// # Errors
653    /// Returns stale-version or already-approved errors.
654    pub async fn cancel_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
655        self.backend
656            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Cancel)
657            .await
658    }
659
660    /// Reads graph/node progress and immutable execution history.
661    ///
662    /// # Errors
663    /// Returns failed persistence or query delivery errors.
664    pub async fn get_execution_graph(
665        &self,
666        graph_id: &str,
667    ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
668        self.backend.get_execution_graph(graph_id).await
669    }
670
671    /// Permanently cancels this graph without canceling unrelated session work.
672    ///
673    /// # Errors
674    /// Rejects missing/stale graphs and failed durable cancellation.
675    pub async fn cancel_execution_graph(
676        &self,
677        request: crate::GraphControlRequest,
678    ) -> Result<(), SessionError> {
679        self.backend.cancel_execution_graph(request).await
680    }
681
682    /// Resumes dispatch explicitly; failed nodes still require a new action.
683    ///
684    /// # Errors
685    /// Rejects canceled/stale graphs, graphs without recorded launch limits,
686    /// or ineligible sessions.
687    pub async fn resume_execution_graph(
688        &self,
689        request: crate::ResumeExecutionGraphRequest,
690    ) -> Result<(), SessionError> {
691        self.backend.resume_execution_graph(request).await
692    }
693
694    /// Adds provider calls to one launched budget through a recorded,
695    /// idempotent extension; the launch limits stay unchanged.
696    ///
697    /// # Errors
698    /// Rejects stale, completed, or canceled graphs, unknown budgets,
699    /// amounts outside `1..=ExtendGraphBudgetRequest::MAX_ADDITIONAL_CALLS`,
700    /// conflicting action identities, and failed persistence.
701    pub async fn extend_execution_graph_budget(
702        &self,
703        request: crate::ExtendGraphBudgetRequest,
704    ) -> Result<(), SessionError> {
705        self.backend.extend_execution_graph_budget(request).await
706    }
707
708    /// Retries a failed node or answers its exact settled clarification set.
709    ///
710    /// # Errors
711    /// Rejects stale sources, partial answers, conflicting action identities,
712    /// canceled graphs, and failed persistence or delivery.
713    pub async fn continue_execution_graph_node(
714        &self,
715        request: crate::ContinueGraphNodeRequest,
716    ) -> Result<(), SessionError> {
717        self.backend.continue_execution_graph_node(request).await
718    }
719
720    /// Starts an explicit static graph without waiting for model execution.
721    ///
722    /// # Errors
723    /// Rejects unsupported profiles, stale/conflicting identities, missing
724    /// budgets, ineligible sessions, and failed persistence or delivery.
725    pub async fn start_execution_graph(
726        &self,
727        request: StartExecutionGraphRequest,
728    ) -> Result<(), SessionError> {
729        self.backend.start_execution_graph(request).await
730    }
731
732    /// Accepts one exact validated output and releases its acceptance gate.
733    ///
734    /// # Errors
735    /// Rejects stale or unvalidated references and failed persistence.
736    pub async fn accept_execution_graph_result(
737        &self,
738        reference: crate::GraphResultRef,
739    ) -> Result<(), SessionError> {
740        self.backend.accept_execution_graph_result(reference).await
741    }
742
743    /// Accepts a standalone Planner version from durable task history.
744    ///
745    /// # Errors
746    /// Returns an error for stale/ineligible versions or failed persistence.
747    pub async fn accept_agent_plan(
748        &self,
749        session_id: &SessionId,
750        request: AcceptTaskPlanRequest,
751    ) -> Result<(), SessionError> {
752        self.backend.accept_agent_plan(session_id, request).await
753    }
754
755    /// Creates an owned session capability backed by a shared host handle.
756    pub fn new(backend: Arc<dyn SessionBackend>) -> Self {
757        Self { backend }
758    }
759
760    /// Admits an isolated role-bound attempt, acknowledging durable admission.
761    /// Identical redeliveries do not execute again. Task completion is
762    /// explicit.
763    ///
764    /// # Errors
765    /// Returns an error for invalid input, unaccepted implementation plans,
766    /// conflicting identity, or a session unable to accept work.
767    pub async fn submit_agent_task(
768        &self,
769        session_id: &SessionId,
770        request: crate::SubmitAgentTaskRequest,
771    ) -> Result<(), SessionError> {
772        self.backend.submit_agent_task(session_id, request).await
773    }
774
775    /// Reads the task's own responses. Attempt status remains authoritative.
776    ///
777    /// # Errors
778    /// Returns an error when the host cannot load the isolated conversation.
779    pub async fn get_agent_task_history(
780        &self,
781        task_id: &str,
782    ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
783        self.backend.get_agent_task_history(task_id).await
784    }
785
786    /// Persists a task with zero attempts in an existing session, regardless
787    /// of its execution status. Does not start work or change session state.
788    /// Identical creation requests preserve the task and its history.
789    ///
790    /// # Errors
791    /// Returns an error for empty inputs, conflicting identity, a missing
792    /// session, or a host that cannot persist tasks.
793    pub async fn create_task(
794        &self,
795        session_id: &SessionId,
796        request: CreateTaskRequest,
797    ) -> Result<(), SessionError> {
798        self.backend.create_task(session_id, request).await
799    }
800
801    /// Lists all tasks owned by a session in creation order, including their
802    /// attempt histories in one snapshot. Equal timestamps retain insertion
803    /// order. Returns an empty list for a missing session or one without tasks.
804    ///
805    /// # Errors
806    /// Returns an error when the host cannot read tasks.
807    pub async fn list_tasks(&self, session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
808        self.backend.list_tasks(session_id).await
809    }
810
811    /// Admits one task attempt through the existing serialized session worker.
812    /// Creates the task atomically if it does not already exist.
813    /// Acceptance does not wait for execution or imply task completion.
814    /// Identical deliveries are acknowledged without running again.
815    ///
816    /// # Errors
817    /// Returns an error for conflicting identity, an unavailable host, a
818    /// completed task, or a session that cannot accept a new durable turn.
819    pub async fn submit_task(
820        &self,
821        session_id: &SessionId,
822        request: SubmitTaskRequest,
823    ) -> Result<(), SessionError> {
824        self.backend.submit_task(session_id, request).await
825    }
826
827    /// Loads a task and all its attempts from durable storage.
828    ///
829    /// # Errors
830    /// Returns an error when the host cannot read tasks.
831    pub async fn get_task(&self, task_id: &str) -> Result<Option<Task>, SessionError> {
832        self.backend.get_task(task_id).await
833    }
834
835    /// Explicitly accepts the outcome. Successful model execution alone never
836    /// completes a task. Repeated completion retains its original timestamp.
837    ///
838    /// # Errors
839    /// Returns an error if the task is missing, an attempt is unfinished, or
840    /// the host cannot persist completion.
841    pub async fn complete_task(&self, task_id: &str) -> Result<(), SessionError> {
842        self.backend.complete_task(task_id).await
843    }
844
845    /// Reports whether the host serves `operation` to frontends that ask
846    /// first.
847    #[must_use]
848    pub fn supports(&self, operation: SessionOperation) -> bool {
849        self.backend.supports(operation)
850    }
851
852    /// Describes the active project new sessions are created in.
853    ///
854    /// # Errors
855    /// Returns an error when the host does not describe its project or
856    /// cannot load its defaults.
857    pub async fn host_context(&self) -> Result<HostContext, SessionError> {
858        self.backend.host_context().await
859    }
860
861    /// Creates one session and returns its stable identifier.
862    ///
863    /// # Errors
864    /// Returns an error when the host cannot create the requested session.
865    pub async fn create_session(
866        &self,
867        request: CreateSessionRequest,
868    ) -> Result<SessionId, SessionError> {
869        self.backend.create_session(request).await
870    }
871
872    /// Loads one complete session aggregate by identifier.
873    ///
874    /// # Errors
875    /// Returns an error when persisted data cannot be loaded or decoded.
876    pub async fn get_session(
877        &self,
878        session_id: &SessionId,
879    ) -> Result<Option<Session>, SessionError> {
880        self.backend.get_session(session_id).await
881    }
882
883    /// Loads the files one session changes against its base branch, or
884    /// `None` when the host has not loaded the session.
885    ///
886    /// # Errors
887    /// Returns an error when the host does not serve diffs or cannot compute
888    /// or load this one.
889    pub async fn get_session_diff(
890        &self,
891        session_id: &SessionId,
892    ) -> Result<Option<Vec<SessionDiffFile>>, SessionError> {
893        self.backend.get_session_diff(session_id).await
894    }
895
896    /// Lists the files and directories in one session's worktree,
897    /// directories first, or `None` when the host has not loaded the
898    /// session.
899    ///
900    /// # Errors
901    /// Returns an error when the host does not serve file listings or cannot
902    /// read this one.
903    pub async fn list_session_files(
904        &self,
905        session_id: &SessionId,
906    ) -> Result<Option<Vec<SessionFileEntry>>, SessionError> {
907        self.backend.list_session_files(session_id).await
908    }
909
910    /// Lists the host's loaded sessions in its display order.
911    ///
912    /// # Errors
913    /// Returns an error when the host cannot list sessions.
914    pub async fn list_sessions(&self) -> Result<Vec<SessionSummary>, SessionError> {
915        self.backend.list_sessions().await
916    }
917
918    /// Lists the host's loaded sessions in its display order, with list
919    /// stats when the host provides them.
920    ///
921    /// # Errors
922    /// Returns an error when the host cannot list sessions.
923    pub async fn list_session_entries(&self) -> Result<Vec<SessionListEntry>, SessionError> {
924        self.backend.list_session_entries().await
925    }
926
927    /// Sends a text message to one session.
928    ///
929    /// # Errors
930    /// Returns an error when the session cannot accept or enqueue the message.
931    pub async fn send_message(
932        &self,
933        session_id: &SessionId,
934        message: impl Into<String> + Send,
935    ) -> Result<(), SessionError> {
936        self.backend.send_message(session_id, message.into()).await
937    }
938
939    /// Submits one durable turn directly to the serialized worker.
940    ///
941    /// # Errors
942    /// Returns an error when the session is busy or cannot accept the turn.
943    pub async fn submit_durable_message(
944        &self,
945        session_id: &SessionId,
946        request: DurableMessageRequest,
947    ) -> Result<(), SessionError> {
948        self.backend
949            .submit_durable_message(session_id, request)
950            .await
951    }
952
953    /// Answers the complete current clarification-question set.
954    ///
955    /// # Errors
956    /// Returns an error when the answers are stale, incomplete, or cannot be
957    /// enqueued as a follow-up turn.
958    pub async fn answer_questions(
959        &self,
960        session_id: &SessionId,
961        request: AnswerQuestionsRequest,
962    ) -> Result<(), SessionError> {
963        self.backend.answer_questions(session_id, request).await
964    }
965
966    /// Cancels one session through its host lifecycle workflow.
967    ///
968    /// # Errors
969    /// Returns an error when the session does not exist or cannot be canceled
970    /// in its current state.
971    pub async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
972        self.backend.cancel_session(session_id).await
973    }
974
975    /// Stops the session's running turn and returns the session to review.
976    /// Unlike [`Self::cancel_session`], the worktree and its changes stay;
977    /// messages queued behind the turn are discarded.
978    ///
979    /// # Errors
980    /// Returns an error when the session does not exist, has no running
981    /// turn, or the host does not support stopping a turn.
982    pub async fn stop_turn(&self, session_id: &SessionId) -> Result<(), SessionError> {
983        self.backend.stop_turn(session_id).await
984    }
985
986    /// Starts or queues a rebase of the session branch onto its base branch.
987    /// The host acknowledges admission; a conflict starts an agent-assisted
988    /// resolution turn.
989    ///
990    /// # Errors
991    /// Returns an error when the session does not exist, cannot be rebased in
992    /// its current state, or the host does not support syncing.
993    pub async fn rebase_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
994        self.backend.rebase_session(session_id).await
995    }
996
997    /// Changes the session's model, reasoning, style, or speed for later
998    /// turns, where the terminal's composer could change them.
999    ///
1000    /// The host refuses the whole change, applying none of it, when the
1001    /// session's status has no composer, the model is not one the session's
1002    /// agent offers, or fast mode does not suit the model the session will
1003    /// have. It then applies the model, reasoning, style, and speed in that
1004    /// order. Reasoning and style apply at once; a model or speed change
1005    /// waits while the session still has accepted work. Changes are not
1006    /// transactional: when one fails to apply, the ones before it stay
1007    /// applied.
1008    ///
1009    /// # Errors
1010    /// Returns an error when the session does not exist or its status has no
1011    /// composer, a model is not available to it, fast mode does not suit the
1012    /// resulting model, switching or persisting a setting fails, or the host
1013    /// does not support the change.
1014    pub async fn update_session_settings(
1015        &self,
1016        session_id: &SessionId,
1017        change: SessionSettingsChange,
1018    ) -> Result<(), SessionError> {
1019        self.backend
1020            .update_session_settings(session_id, change)
1021            .await
1022    }
1023
1024    /// Requests merge processing for one session.
1025    ///
1026    /// # Errors
1027    /// Returns an error when the session is not mergeable or queueing fails.
1028    pub async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1029        self.backend.merge_session(session_id).await
1030    }
1031
1032    /// Queues publication of one session and creates or refreshes its review
1033    /// request.
1034    ///
1035    /// # Errors
1036    /// Returns an error when queueing, branch publication, forge access, or
1037    /// persistence fails.
1038    pub async fn create_review_request(
1039        &self,
1040        session_id: &SessionId,
1041    ) -> Result<ReviewRequest, SessionError> {
1042        self.backend.create_review_request(session_id).await
1043    }
1044}
1045
1046#[cfg(test)]
1047#[path = "service_test.rs"]
1048mod tests;