Skip to main content

ag_session/
service.rs

1//! Programmatic session orchestration facade and host backend port.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6
7use crate::error::SessionError;
8use crate::model::{ReviewRequest, Session, SessionId};
9
10/// Creation strategy for a new session.
11#[derive(Clone, Debug, Default, Eq, PartialEq)]
12pub enum CreateSessionMode {
13    /// Creates a regular root session with an eagerly materialized worktree.
14    #[default]
15    Regular,
16    /// Creates a root draft whose worktree is materialized on first send.
17    Draft,
18    /// Creates a controller session that plans and supervises worker sessions.
19    Orchestrator,
20    /// Creates one worker owned by a persisted orchestration task.
21    OrchestrationChild {
22        /// Durable task row used to re-link the child after restart.
23        task_id: i64,
24    },
25    /// Creates one temporary read-only researcher owned by an orchestration
26    /// task.
27    OrchestrationResearch {
28        /// Durable task row used to re-link the child after restart.
29        task_id: i64,
30    },
31    /// Creates a draft stacked on an existing parent session.
32    Stacked {
33        /// Review-ready parent session whose branch becomes the stack base.
34        parent_session_id: SessionId,
35    },
36}
37
38/// Explicit input for creating one session.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct CreateSessionRequest {
41    /// Existing session whose launch settings should be copied.
42    ///
43    /// When absent, the host resolves the owning project's current defaults.
44    pub inherit_from_session_id: Option<SessionId>,
45    /// Determines whether the session is regular, deferred, or stacked.
46    pub mode: CreateSessionMode,
47    /// Project that owns the new session.
48    pub project_id: i64,
49}
50
51/// One structured response to a persisted clarification question.
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct QuestionAnswer {
54    /// User response paired with `question`.
55    pub answer: String,
56    /// Exact persisted question text being answered.
57    pub question: String,
58}
59
60/// Structured input for resuming one session from clarification questions.
61#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct AnswerQuestionsRequest {
63    /// Ordered question and answer pairs for the current question set.
64    pub answers: Vec<QuestionAnswer>,
65}
66
67/// Durable coordinator-owned turn submitted to one controller session.
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct CoordinatorMessageRequest {
70    /// Agent-facing roll-up or supervision prompt.
71    pub message: String,
72    /// Stable operation identifier reused when delivery is retried.
73    pub operation_id: String,
74    /// Whether the machine-authored prompt is shown in the human transcript.
75    pub visibility: CoordinatorMessageVisibility,
76}
77
78/// Transcript treatment for one coordinator-owned prompt.
79#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
80pub enum CoordinatorMessageVisibility {
81    /// Deliver agent context without duplicating board data in chat.
82    #[default]
83    Hidden,
84    /// Preserve a worker continuation instruction in its inspectable history.
85    Visible,
86}
87
88/// Host implementation boundary for session persistence and workflows.
89///
90/// The trait is object-safe so agent loops and future orchestrators can hold a
91/// programmatic session capability without depending on a concrete frontend.
92#[async_trait]
93pub trait SessionBackend: Send + Sync {
94    /// Creates one session and returns its stable identifier.
95    async fn create_session(
96        &self,
97        request: CreateSessionRequest,
98    ) -> Result<SessionId, SessionError>;
99
100    /// Loads one complete session aggregate, including settings and messages.
101    async fn get_session(&self, session_id: &SessionId) -> Result<Option<Session>, SessionError>;
102
103    /// Sends one text message, starting, resuming, or queueing as appropriate.
104    async fn send_message(
105        &self,
106        session_id: &SessionId,
107        message: String,
108    ) -> Result<(), SessionError>;
109
110    /// Submits a coordinator-owned turn without entering the lossy live-chat
111    /// queue used while an ordinary user turn is active.
112    async fn submit_coordinator_message(
113        &self,
114        session_id: &SessionId,
115        request: CoordinatorMessageRequest,
116    ) -> Result<(), SessionError>;
117
118    /// Answers the complete current clarification-question set.
119    async fn answer_questions(
120        &self,
121        session_id: &SessionId,
122        request: AnswerQuestionsRequest,
123    ) -> Result<(), SessionError>;
124
125    /// Cancels one session through the host lifecycle workflow.
126    async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
127
128    /// Requests merge processing for one review-ready session.
129    async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
130
131    /// Queues publication of one session branch and creates or refreshes its
132    /// review request.
133    async fn create_review_request(
134        &self,
135        session_id: &SessionId,
136    ) -> Result<ReviewRequest, SessionError>;
137}
138
139/// Stable programmatic facade for session lifecycle operations.
140#[derive(Clone)]
141pub struct SessionService {
142    backend: Arc<dyn SessionBackend>,
143}
144
145impl SessionService {
146    /// Creates an owned session capability backed by a shared host handle.
147    pub fn new(backend: Arc<dyn SessionBackend>) -> Self {
148        Self { backend }
149    }
150
151    /// Creates one session and returns its stable identifier.
152    ///
153    /// # Errors
154    /// Returns an error when the host cannot create the requested session.
155    pub async fn create_session(
156        &self,
157        request: CreateSessionRequest,
158    ) -> Result<SessionId, SessionError> {
159        self.backend.create_session(request).await
160    }
161
162    /// Loads one complete session aggregate by identifier.
163    ///
164    /// # Errors
165    /// Returns an error when persisted data cannot be loaded or decoded.
166    pub async fn get_session(
167        &self,
168        session_id: &SessionId,
169    ) -> Result<Option<Session>, SessionError> {
170        self.backend.get_session(session_id).await
171    }
172
173    /// Sends a text message to one session.
174    ///
175    /// # Errors
176    /// Returns an error when the session cannot accept or enqueue the message.
177    pub async fn send_message(
178        &self,
179        session_id: &SessionId,
180        message: impl Into<String> + Send,
181    ) -> Result<(), SessionError> {
182        self.backend.send_message(session_id, message.into()).await
183    }
184
185    /// Submits one coordinator-owned turn directly to the serialized worker.
186    ///
187    /// # Errors
188    /// Returns an error when the session is busy or cannot accept the turn.
189    pub async fn submit_coordinator_message(
190        &self,
191        session_id: &SessionId,
192        request: CoordinatorMessageRequest,
193    ) -> Result<(), SessionError> {
194        self.backend
195            .submit_coordinator_message(session_id, request)
196            .await
197    }
198
199    /// Answers the complete current clarification-question set.
200    ///
201    /// # Errors
202    /// Returns an error when the answers are stale, incomplete, or cannot be
203    /// enqueued as a follow-up turn.
204    pub async fn answer_questions(
205        &self,
206        session_id: &SessionId,
207        request: AnswerQuestionsRequest,
208    ) -> Result<(), SessionError> {
209        self.backend.answer_questions(session_id, request).await
210    }
211
212    /// Cancels one session through its host lifecycle workflow.
213    ///
214    /// # Errors
215    /// Returns an error when the session does not exist or cannot be canceled
216    /// in its current state.
217    pub async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
218        self.backend.cancel_session(session_id).await
219    }
220
221    /// Requests merge processing for one session.
222    ///
223    /// # Errors
224    /// Returns an error when the session is not mergeable or queueing fails.
225    pub async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
226        self.backend.merge_session(session_id).await
227    }
228
229    /// Queues publication of one session and creates or refreshes its review
230    /// request.
231    ///
232    /// # Errors
233    /// Returns an error when queueing, branch publication, forge access, or
234    /// persistence fails.
235    pub async fn create_review_request(
236        &self,
237        session_id: &SessionId,
238    ) -> Result<ReviewRequest, SessionError> {
239        self.backend.create_review_request(session_id).await
240    }
241}
242
243#[cfg(test)]
244#[path = "service_test.rs"]
245mod tests;