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