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};
10use crate::{AcceptTaskPlanRequest, CreateTaskRequest, SubmitTaskRequest, Task};
11
12/// Creation strategy for a new session.
13#[derive(Clone, Debug, Default, Eq, PartialEq)]
14pub enum CreateSessionMode {
15    /// Creates a regular session with an eagerly materialized worktree.
16    #[default]
17    Regular,
18    /// Creates a draft whose worktree is materialized on first send.
19    Draft,
20    /// Creates a regular session that runs on the in-process
21    /// [`crate::AgentKind::Harness`] with its default model.
22    Harness,
23}
24
25/// Explicit input for creating one session.
26#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct CreateSessionRequest {
28    /// Existing session whose launch settings should be copied.
29    ///
30    /// When absent, the host resolves the owning project's current defaults.
31    pub inherit_from_session_id: Option<SessionId>,
32    /// Determines whether the session is regular, deferred, or harness-backed.
33    pub mode: CreateSessionMode,
34    /// Project that owns the new session.
35    pub project_id: i64,
36}
37
38/// One structured response to a persisted clarification question.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct QuestionAnswer {
41    /// User response paired with `question`.
42    pub answer: String,
43    /// Exact persisted question text being answered.
44    pub question: String,
45}
46
47/// Structured input for resuming one session from clarification questions.
48#[derive(Clone, Debug, Eq, PartialEq)]
49pub struct AnswerQuestionsRequest {
50    /// Ordered question and answer pairs for the current question set.
51    pub answers: Vec<QuestionAnswer>,
52    /// Local images referenced by `[Image #n]` placeholders in `answers`,
53    /// delivered with the reply turn like prompt attachments. The caller
54    /// keeps the files when the request fails, so it can retry with them.
55    pub attachments: Vec<TurnPromptAttachment>,
56}
57
58/// Idempotent turn submitted to one session.
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct DurableMessageRequest {
61    /// Agent-facing prompt.
62    pub message: String,
63    /// Stable operation identifier reused when delivery is retried.
64    pub operation_id: String,
65    /// Whether the machine-authored prompt is shown in the human transcript.
66    pub visibility: DurableMessageVisibility,
67}
68
69/// Transcript treatment for one durable prompt.
70#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
71pub enum DurableMessageVisibility {
72    /// Deliver generated context without displaying it as user chat.
73    #[default]
74    Hidden,
75    /// Display the submitted instruction in session history.
76    Visible,
77}
78
79/// Host implementation boundary for session persistence and workflows.
80///
81/// The trait is object-safe so agent loops and background workflows can hold a
82/// programmatic session capability without depending on a concrete frontend.
83#[async_trait]
84pub trait SessionBackend: Send + Sync {
85    /// Reserves generation without waiting for model completion.
86    async fn generate_graph_proposal(
87        &self,
88        request: crate::GenerateGraphProposalRequest,
89    ) -> Result<(), SessionError> {
90        let _ = request;
91        Err(SessionError::Operation(
92            "Host does not support graph proposals".into(),
93        ))
94    }
95
96    /// Reads retained state without generating or launching work.
97    async fn get_graph_proposal(
98        &self,
99        id: &str,
100    ) -> Result<Option<crate::GraphProposalState>, SessionError> {
101        let _ = id;
102        Err(SessionError::Operation(
103            "Host does not support graph proposals".into(),
104        ))
105    }
106
107    /// Applies an explicit action to the exact inspected version.
108    async fn act_on_graph_proposal(
109        &self,
110        id: &str,
111        version: u32,
112        action: crate::GraphProposalAction,
113    ) -> Result<(), SessionError> {
114        let _ = (id, version, action);
115        Err(SessionError::Operation(
116            "Host does not support graph proposals".into(),
117        ))
118    }
119
120    /// Reads durable progress without launching or retrying work.
121    async fn get_execution_graph(
122        &self,
123        graph_id: &str,
124    ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
125        let _ = graph_id;
126
127        Err(SessionError::Operation(
128            "Host does not support execution graphs".into(),
129        ))
130    }
131
132    /// Closes graph admission durably, then signals its owned workers.
133    async fn cancel_execution_graph(
134        &self,
135        request: crate::GraphControlRequest,
136    ) -> Result<(), SessionError> {
137        let _ = request;
138
139        Err(SessionError::Operation(
140            "Host does not support execution graphs".into(),
141        ))
142    }
143
144    /// Explicitly restarts dispatch without replaying admitted executions.
145    async fn resume_execution_graph(
146        &self,
147        request: crate::ResumeExecutionGraphRequest,
148    ) -> Result<(), SessionError> {
149        let _ = request;
150
151        Err(SessionError::Operation(
152            "Host does not support execution graphs".into(),
153        ))
154    }
155
156    /// Authorizes one new attempt against an exact failed/question execution.
157    async fn continue_execution_graph_node(
158        &self,
159        request: crate::ContinueGraphNodeRequest,
160    ) -> Result<(), SessionError> {
161        let _ = request;
162
163        Err(SessionError::Operation(
164            "Host does not support execution graphs".into(),
165        ))
166    }
167
168    /// Saves and starts a static graph. Existing admitted nodes are never
169    /// replayed. Named budgets are fixed at first launch and their spending is
170    /// recorded durably, so relaunching never replenishes them.
171    async fn start_execution_graph(
172        &self,
173        request: StartExecutionGraphRequest,
174    ) -> Result<(), SessionError> {
175        let _ = request;
176
177        Err(SessionError::Operation(
178            "Host does not support execution graphs".into(),
179        ))
180    }
181
182    /// Records explicit acceptance of an exact graph output and wakes ready
183    /// dependents. Model output must never call this trusted host boundary.
184    async fn accept_execution_graph_result(
185        &self,
186        reference: crate::GraphResultRef,
187    ) -> Result<(), SessionError> {
188        let _ = reference;
189
190        Err(SessionError::Operation(
191            "Host does not support execution graphs".into(),
192        ))
193    }
194    /// Admits a role-bound attempt with its own isolated conversation.
195    async fn submit_agent_task(
196        &self,
197        session_id: &SessionId,
198        request: crate::SubmitAgentTaskRequest,
199    ) -> Result<(), SessionError> {
200        let _ = (session_id, request);
201
202        Err(SessionError::Operation(
203            "Host does not support role-aware tasks".to_string(),
204        ))
205    }
206
207    /// Reads isolated task responses without exposing host storage types.
208    async fn get_agent_task_history(
209        &self,
210        task_id: &str,
211    ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
212        let _ = task_id;
213
214        Err(SessionError::Operation(
215            "Host does not support role-aware tasks".to_string(),
216        ))
217    }
218
219    /// Explicitly accepts a standalone Planner response by producing version.
220    async fn accept_agent_plan(
221        &self,
222        _session_id: &SessionId,
223        _request: AcceptTaskPlanRequest,
224    ) -> Result<(), SessionError> {
225        Err(SessionError::Operation(
226            "Host does not support plan acceptance".into(),
227        ))
228    }
229
230    /// Persists an outcome without execution. Older hosts may omit support.
231    async fn create_task(
232        &self,
233        _session_id: &SessionId,
234        _request: CreateTaskRequest,
235    ) -> Result<(), SessionError> {
236        Err(SessionError::Operation(
237            "Host does not support tasks".to_string(),
238        ))
239    }
240
241    /// Lists a session's tasks, including unattempted and completed outcomes.
242    async fn list_tasks(&self, _session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
243        Err(SessionError::Operation(
244            "Host does not support tasks".to_string(),
245        ))
246    }
247
248    /// Admits an explicit task attempt. Older hosts may omit task support.
249    async fn submit_task(
250        &self,
251        _session_id: &SessionId,
252        _request: SubmitTaskRequest,
253    ) -> Result<(), SessionError> {
254        Err(SessionError::Operation(
255            "Host does not support tasks".to_string(),
256        ))
257    }
258
259    /// Loads the desired outcome and retained attempt history.
260    async fn get_task(&self, _task_id: &str) -> Result<Option<Task>, SessionError> {
261        Err(SessionError::Operation(
262            "Host does not support tasks".to_string(),
263        ))
264    }
265
266    /// Explicitly accepts the task outcome after all attempts have settled.
267    async fn complete_task(&self, _task_id: &str) -> Result<(), SessionError> {
268        Err(SessionError::Operation(
269            "Host does not support tasks".to_string(),
270        ))
271    }
272
273    /// Creates one session and returns its stable identifier.
274    async fn create_session(
275        &self,
276        request: CreateSessionRequest,
277    ) -> Result<SessionId, SessionError>;
278
279    /// Loads one complete session aggregate, including settings and messages.
280    async fn get_session(&self, session_id: &SessionId) -> Result<Option<Session>, SessionError>;
281
282    /// Sends one text message, starting, resuming, or queueing as appropriate.
283    async fn send_message(
284        &self,
285        session_id: &SessionId,
286        message: String,
287    ) -> Result<(), SessionError>;
288
289    /// Submits a durable turn without entering the lossy live-chat
290    /// queue used while an ordinary user turn is active.
291    async fn submit_durable_message(
292        &self,
293        session_id: &SessionId,
294        request: DurableMessageRequest,
295    ) -> Result<(), SessionError>;
296
297    /// Answers the complete current clarification-question set.
298    async fn answer_questions(
299        &self,
300        session_id: &SessionId,
301        request: AnswerQuestionsRequest,
302    ) -> Result<(), SessionError>;
303
304    /// Cancels one session through the host lifecycle workflow.
305    async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
306
307    /// Requests merge processing for one review-ready session.
308    async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
309
310    /// Queues publication of one session branch and creates or refreshes its
311    /// review request.
312    async fn create_review_request(
313        &self,
314        session_id: &SessionId,
315    ) -> Result<ReviewRequest, SessionError>;
316}
317
318/// Stable programmatic facade for session lifecycle operations.
319#[derive(Clone)]
320pub struct SessionService {
321    backend: Arc<dyn SessionBackend>,
322}
323
324/// Explicit static-graph launch, separate from ordinary chat.
325#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
326pub struct StartExecutionGraphRequest {
327    /// Validated immutable snapshot to save before admitting nodes.
328    pub graph: crate::ExecutionGraph,
329    /// Provider calls shared by nodes naming the same budget, including
330    /// repairs. These limits cannot be replenished by redelivering an
331    /// active launch.
332    pub provider_call_limits: std::collections::BTreeMap<String, usize>,
333}
334
335impl SessionService {
336    /// Generates a proposal through the host's bounded worker workflow.
337    ///
338    /// # Errors
339    /// Returns admission, permissions, or persistence errors.
340    pub async fn generate_graph_proposal(
341        &self,
342        request: crate::GenerateGraphProposalRequest,
343    ) -> Result<(), SessionError> {
344        self.backend.generate_graph_proposal(request).await
345    }
346
347    /// Queries pending, restored, or approved state without execution.
348    ///
349    /// # Errors
350    /// Returns query delivery or persistence errors.
351    pub async fn get_graph_proposal(
352        &self,
353        id: &str,
354    ) -> Result<Option<crate::GraphProposalState>, SessionError> {
355        self.backend.get_graph_proposal(id).await
356    }
357
358    /// Answers the complete question set on an exact proposal version.
359    ///
360    /// # Errors
361    /// Returns stale-version, incomplete-answer, or generation-limit errors.
362    pub async fn answer_graph_proposal(
363        &self,
364        id: &str,
365        version: u32,
366        answers: Vec<String>,
367    ) -> Result<(), SessionError> {
368        self.backend
369            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Answer(answers))
370            .await
371    }
372
373    /// Regenerates within the original captured generation ceiling.
374    ///
375    /// # Errors
376    /// Returns stale-version, approved-proposal, or exhausted-limit errors.
377    pub async fn regenerate_graph_proposal(
378        &self,
379        id: &str,
380        version: u32,
381    ) -> Result<(), SessionError> {
382        self.backend
383            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Regenerate)
384            .await
385    }
386
387    /// Regenerates with user feedback, including its images, added to the
388    /// generation history, within the original captured generation ceiling.
389    ///
390    /// # Errors
391    /// Returns stale-version, empty-feedback, approved-proposal, or
392    /// exhausted-limit errors.
393    pub async fn revise_graph_proposal(
394        &self,
395        id: &str,
396        version: u32,
397        feedback: TurnPrompt,
398    ) -> Result<(), SessionError> {
399        self.backend
400            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Revise(feedback))
401            .await
402    }
403
404    /// Approves the exact preview before dispatch. Redelivery never dispatches.
405    ///
406    /// # Errors
407    /// Returns stale-version, resolution, permissions, or publication errors.
408    pub async fn approve_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
409        self.backend
410            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Approve)
411            .await
412    }
413
414    /// Cancels a pending proposal and any active generating utility.
415    ///
416    /// # Errors
417    /// Returns stale-version or already-approved errors.
418    pub async fn cancel_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
419        self.backend
420            .act_on_graph_proposal(id, version, crate::GraphProposalAction::Cancel)
421            .await
422    }
423
424    /// Reads graph/node progress and immutable execution history.
425    ///
426    /// # Errors
427    /// Returns failed persistence or query delivery errors.
428    pub async fn get_execution_graph(
429        &self,
430        graph_id: &str,
431    ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
432        self.backend.get_execution_graph(graph_id).await
433    }
434
435    /// Permanently cancels this graph without canceling unrelated session work.
436    ///
437    /// # Errors
438    /// Rejects missing/stale graphs and failed durable cancellation.
439    pub async fn cancel_execution_graph(
440        &self,
441        request: crate::GraphControlRequest,
442    ) -> Result<(), SessionError> {
443        self.backend.cancel_execution_graph(request).await
444    }
445
446    /// Resumes dispatch explicitly; failed nodes still require a new action.
447    ///
448    /// # Errors
449    /// Rejects canceled/stale graphs, graphs without recorded launch limits,
450    /// or ineligible sessions.
451    pub async fn resume_execution_graph(
452        &self,
453        request: crate::ResumeExecutionGraphRequest,
454    ) -> Result<(), SessionError> {
455        self.backend.resume_execution_graph(request).await
456    }
457
458    /// Retries a failed node or answers its exact settled clarification set.
459    ///
460    /// # Errors
461    /// Rejects stale sources, partial answers, conflicting action identities,
462    /// canceled graphs, and failed persistence or delivery.
463    pub async fn continue_execution_graph_node(
464        &self,
465        request: crate::ContinueGraphNodeRequest,
466    ) -> Result<(), SessionError> {
467        self.backend.continue_execution_graph_node(request).await
468    }
469
470    /// Starts an explicit static graph without waiting for model execution.
471    ///
472    /// # Errors
473    /// Rejects unsupported profiles, stale/conflicting identities, missing
474    /// budgets, ineligible sessions, and failed persistence or delivery.
475    pub async fn start_execution_graph(
476        &self,
477        request: StartExecutionGraphRequest,
478    ) -> Result<(), SessionError> {
479        self.backend.start_execution_graph(request).await
480    }
481
482    /// Accepts one exact validated output and releases its acceptance gate.
483    ///
484    /// # Errors
485    /// Rejects stale or unvalidated references and failed persistence.
486    pub async fn accept_execution_graph_result(
487        &self,
488        reference: crate::GraphResultRef,
489    ) -> Result<(), SessionError> {
490        self.backend.accept_execution_graph_result(reference).await
491    }
492
493    /// Accepts a standalone Planner version from durable task history.
494    ///
495    /// # Errors
496    /// Returns an error for stale/ineligible versions or failed persistence.
497    pub async fn accept_agent_plan(
498        &self,
499        session_id: &SessionId,
500        request: AcceptTaskPlanRequest,
501    ) -> Result<(), SessionError> {
502        self.backend.accept_agent_plan(session_id, request).await
503    }
504
505    /// Creates an owned session capability backed by a shared host handle.
506    pub fn new(backend: Arc<dyn SessionBackend>) -> Self {
507        Self { backend }
508    }
509
510    /// Admits an isolated role-bound attempt, acknowledging durable admission.
511    /// Identical redeliveries do not execute again. Task completion is
512    /// explicit.
513    ///
514    /// # Errors
515    /// Returns an error for invalid input, unaccepted implementation plans,
516    /// conflicting identity, or a session unable to accept work.
517    pub async fn submit_agent_task(
518        &self,
519        session_id: &SessionId,
520        request: crate::SubmitAgentTaskRequest,
521    ) -> Result<(), SessionError> {
522        self.backend.submit_agent_task(session_id, request).await
523    }
524
525    /// Reads the task's own responses. Attempt status remains authoritative.
526    ///
527    /// # Errors
528    /// Returns an error when the host cannot load the isolated conversation.
529    pub async fn get_agent_task_history(
530        &self,
531        task_id: &str,
532    ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
533        self.backend.get_agent_task_history(task_id).await
534    }
535
536    /// Persists a task with zero attempts in an existing session, regardless
537    /// of its execution status. Does not start work or change session state.
538    /// Identical creation requests preserve the task and its history.
539    ///
540    /// # Errors
541    /// Returns an error for empty inputs, conflicting identity, a missing
542    /// session, or a host that cannot persist tasks.
543    pub async fn create_task(
544        &self,
545        session_id: &SessionId,
546        request: CreateTaskRequest,
547    ) -> Result<(), SessionError> {
548        self.backend.create_task(session_id, request).await
549    }
550
551    /// Lists all tasks owned by a session in creation order, including their
552    /// attempt histories in one snapshot. Equal timestamps retain insertion
553    /// order. Returns an empty list for a missing session or one without tasks.
554    ///
555    /// # Errors
556    /// Returns an error when the host cannot read tasks.
557    pub async fn list_tasks(&self, session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
558        self.backend.list_tasks(session_id).await
559    }
560
561    /// Admits one task attempt through the existing serialized session worker.
562    /// Creates the task atomically if it does not already exist.
563    /// Acceptance does not wait for execution or imply task completion.
564    /// Identical deliveries are acknowledged without running again.
565    ///
566    /// # Errors
567    /// Returns an error for conflicting identity, an unavailable host, a
568    /// completed task, or a session that cannot accept a new durable turn.
569    pub async fn submit_task(
570        &self,
571        session_id: &SessionId,
572        request: SubmitTaskRequest,
573    ) -> Result<(), SessionError> {
574        self.backend.submit_task(session_id, request).await
575    }
576
577    /// Loads a task and all its attempts from durable storage.
578    ///
579    /// # Errors
580    /// Returns an error when the host cannot read tasks.
581    pub async fn get_task(&self, task_id: &str) -> Result<Option<Task>, SessionError> {
582        self.backend.get_task(task_id).await
583    }
584
585    /// Explicitly accepts the outcome. Successful model execution alone never
586    /// completes a task. Repeated completion retains its original timestamp.
587    ///
588    /// # Errors
589    /// Returns an error if the task is missing, an attempt is unfinished, or
590    /// the host cannot persist completion.
591    pub async fn complete_task(&self, task_id: &str) -> Result<(), SessionError> {
592        self.backend.complete_task(task_id).await
593    }
594
595    /// Creates one session and returns its stable identifier.
596    ///
597    /// # Errors
598    /// Returns an error when the host cannot create the requested session.
599    pub async fn create_session(
600        &self,
601        request: CreateSessionRequest,
602    ) -> Result<SessionId, SessionError> {
603        self.backend.create_session(request).await
604    }
605
606    /// Loads one complete session aggregate by identifier.
607    ///
608    /// # Errors
609    /// Returns an error when persisted data cannot be loaded or decoded.
610    pub async fn get_session(
611        &self,
612        session_id: &SessionId,
613    ) -> Result<Option<Session>, SessionError> {
614        self.backend.get_session(session_id).await
615    }
616
617    /// Sends a text message to one session.
618    ///
619    /// # Errors
620    /// Returns an error when the session cannot accept or enqueue the message.
621    pub async fn send_message(
622        &self,
623        session_id: &SessionId,
624        message: impl Into<String> + Send,
625    ) -> Result<(), SessionError> {
626        self.backend.send_message(session_id, message.into()).await
627    }
628
629    /// Submits one durable turn directly to the serialized worker.
630    ///
631    /// # Errors
632    /// Returns an error when the session is busy or cannot accept the turn.
633    pub async fn submit_durable_message(
634        &self,
635        session_id: &SessionId,
636        request: DurableMessageRequest,
637    ) -> Result<(), SessionError> {
638        self.backend
639            .submit_durable_message(session_id, request)
640            .await
641    }
642
643    /// Answers the complete current clarification-question set.
644    ///
645    /// # Errors
646    /// Returns an error when the answers are stale, incomplete, or cannot be
647    /// enqueued as a follow-up turn.
648    pub async fn answer_questions(
649        &self,
650        session_id: &SessionId,
651        request: AnswerQuestionsRequest,
652    ) -> Result<(), SessionError> {
653        self.backend.answer_questions(session_id, request).await
654    }
655
656    /// Cancels one session through its host lifecycle workflow.
657    ///
658    /// # Errors
659    /// Returns an error when the session does not exist or cannot be canceled
660    /// in its current state.
661    pub async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
662        self.backend.cancel_session(session_id).await
663    }
664
665    /// Requests merge processing for one session.
666    ///
667    /// # Errors
668    /// Returns an error when the session is not mergeable or queueing fails.
669    pub async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
670        self.backend.merge_session(session_id).await
671    }
672
673    /// Queues publication of one session and creates or refreshes its review
674    /// request.
675    ///
676    /// # Errors
677    /// Returns an error when queueing, branch publication, forge access, or
678    /// persistence fails.
679    pub async fn create_review_request(
680        &self,
681        session_id: &SessionId,
682    ) -> Result<ReviewRequest, SessionError> {
683        self.backend.create_review_request(session_id).await
684    }
685}
686
687#[cfg(test)]
688#[path = "service_test.rs"]
689mod tests;