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};
9use crate::{
10 AcceptTaskChainPlanRequest, AcceptTaskPlanRequest, ContinueTaskChainRequest, CreateTaskRequest,
11 ReplyToTaskChainRequest, StartPlanThenImplementRequest, SubmitTaskRequest, Task, TaskChain,
12 TaskChainReplyOutcome,
13};
14
15/// Creation strategy for a new session.
16#[derive(Clone, Debug, Default, Eq, PartialEq)]
17pub enum CreateSessionMode {
18 /// Creates a regular root session with an eagerly materialized worktree.
19 #[default]
20 Regular,
21 /// Creates a root draft whose worktree is materialized on first send.
22 Draft,
23 /// Creates a regular root session that runs on the in-process
24 /// [`crate::AgentKind::Harness`] with its default model.
25 Harness,
26 /// Creates a draft stacked on an existing parent session.
27 Stacked {
28 /// Review-ready parent session whose branch becomes the stack base.
29 parent_session_id: SessionId,
30 },
31}
32
33/// Explicit input for creating one session.
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct CreateSessionRequest {
36 /// Existing session whose launch settings should be copied.
37 ///
38 /// When absent, the host resolves the owning project's current defaults.
39 pub inherit_from_session_id: Option<SessionId>,
40 /// Determines whether the session is regular, deferred, or stacked.
41 pub mode: CreateSessionMode,
42 /// Project that owns the new session.
43 pub project_id: i64,
44}
45
46/// One structured response to a persisted clarification question.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct QuestionAnswer {
49 /// User response paired with `question`.
50 pub answer: String,
51 /// Exact persisted question text being answered.
52 pub question: String,
53}
54
55/// Structured input for resuming one session from clarification questions.
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub struct AnswerQuestionsRequest {
58 /// Ordered question and answer pairs for the current question set.
59 pub answers: Vec<QuestionAnswer>,
60}
61
62/// Idempotent turn submitted to one session.
63#[derive(Clone, Debug, Eq, PartialEq)]
64pub struct DurableMessageRequest {
65 /// Agent-facing prompt.
66 pub message: String,
67 /// Stable operation identifier reused when delivery is retried.
68 pub operation_id: String,
69 /// Whether the machine-authored prompt is shown in the human transcript.
70 pub visibility: DurableMessageVisibility,
71}
72
73/// Transcript treatment for one durable prompt.
74#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
75pub enum DurableMessageVisibility {
76 /// Deliver generated context without displaying it as user chat.
77 #[default]
78 Hidden,
79 /// Display the submitted instruction in session history.
80 Visible,
81}
82
83/// Host implementation boundary for session persistence and workflows.
84///
85/// The trait is object-safe so agent loops and background workflows can hold a
86/// programmatic session capability without depending on a concrete frontend.
87#[async_trait]
88pub trait SessionBackend: Send + Sync {
89 /// Admits a role-bound attempt with its own isolated conversation.
90 async fn submit_agent_task(
91 &self,
92 session_id: &SessionId,
93 request: crate::SubmitAgentTaskRequest,
94 ) -> Result<(), SessionError> {
95 let _ = (session_id, request);
96
97 Err(SessionError::Operation(
98 "Host does not support role-aware tasks".to_string(),
99 ))
100 }
101
102 /// Reads isolated task responses without exposing host storage types.
103 async fn get_agent_task_history(
104 &self,
105 task_id: &str,
106 ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
107 let _ = task_id;
108
109 Err(SessionError::Operation(
110 "Host does not support role-aware tasks".to_string(),
111 ))
112 }
113
114 /// Explicitly accepts a standalone Planner response by producing version.
115 async fn accept_agent_plan(
116 &self,
117 _session_id: &SessionId,
118 _request: AcceptTaskPlanRequest,
119 ) -> Result<(), SessionError> {
120 Err(SessionError::Operation(
121 "Host does not support plan acceptance".into(),
122 ))
123 }
124
125 /// Launches a static workflow with one isolated Planner attempt.
126 async fn start_plan_then_implement(
127 &self,
128 _session_id: &SessionId,
129 _request: StartPlanThenImplementRequest,
130 ) -> Result<(), SessionError> {
131 Err(SessionError::Operation(
132 "Host does not support task chains".to_string(),
133 ))
134 }
135
136 /// Reads a workflow snapshot without recovering or replaying work.
137 async fn get_task_chain(&self, _chain_id: &str) -> Result<Option<TaskChain>, SessionError> {
138 Err(SessionError::Operation(
139 "Host does not support task chains".to_string(),
140 ))
141 }
142
143 /// Lists a session's workflows in creation order.
144 async fn list_task_chains(
145 &self,
146 _session_id: &SessionId,
147 ) -> Result<Vec<TaskChain>, SessionError> {
148 Err(SessionError::Operation(
149 "Host does not support task chains".to_string(),
150 ))
151 }
152
153 /// Explicitly accepts an exact Planner version and admits implementation.
154 async fn accept_task_chain_plan(
155 &self,
156 _chain_id: &str,
157 _request: AcceptTaskChainPlanRequest,
158 ) -> Result<(), SessionError> {
159 Err(SessionError::Operation(
160 "Host does not support task chains".to_string(),
161 ))
162 }
163
164 /// Explicitly continues the current stage; uses a new attempt identity.
165 async fn continue_task_chain(
166 &self,
167 _chain_id: &str,
168 _request: ContinueTaskChainRequest,
169 ) -> Result<(), SessionError> {
170 Err(SessionError::Operation(
171 "Host does not support task chains".to_string(),
172 ))
173 }
174
175 /// Requests cancellation of only this workflow's current attempt.
176 async fn cancel_task_chain(&self, _chain_id: &str) -> Result<(), SessionError> {
177 Err(SessionError::Operation(
178 "Host does not support task chains".to_string(),
179 ))
180 }
181
182 /// Routes a natural-language reply to the session's latest workflow.
183 async fn reply_to_task_chain(
184 &self,
185 _session_id: &SessionId,
186 _request: ReplyToTaskChainRequest,
187 ) -> Result<TaskChainReplyOutcome, SessionError> {
188 Err(SessionError::Operation(
189 "Host does not support task chains".to_string(),
190 ))
191 }
192
193 /// Persists an outcome without execution. Older hosts may omit support.
194 async fn create_task(
195 &self,
196 _session_id: &SessionId,
197 _request: CreateTaskRequest,
198 ) -> Result<(), SessionError> {
199 Err(SessionError::Operation(
200 "Host does not support tasks".to_string(),
201 ))
202 }
203
204 /// Lists a session's tasks, including unattempted and completed outcomes.
205 async fn list_tasks(&self, _session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
206 Err(SessionError::Operation(
207 "Host does not support tasks".to_string(),
208 ))
209 }
210
211 /// Admits an explicit task attempt. Older hosts may omit task support.
212 async fn submit_task(
213 &self,
214 _session_id: &SessionId,
215 _request: SubmitTaskRequest,
216 ) -> Result<(), SessionError> {
217 Err(SessionError::Operation(
218 "Host does not support tasks".to_string(),
219 ))
220 }
221
222 /// Loads the desired outcome and retained attempt history.
223 async fn get_task(&self, _task_id: &str) -> Result<Option<Task>, SessionError> {
224 Err(SessionError::Operation(
225 "Host does not support tasks".to_string(),
226 ))
227 }
228
229 /// Explicitly accepts the task outcome after all attempts have settled.
230 async fn complete_task(&self, _task_id: &str) -> Result<(), SessionError> {
231 Err(SessionError::Operation(
232 "Host does not support tasks".to_string(),
233 ))
234 }
235
236 /// Creates one session and returns its stable identifier.
237 async fn create_session(
238 &self,
239 request: CreateSessionRequest,
240 ) -> Result<SessionId, SessionError>;
241
242 /// Loads one complete session aggregate, including settings and messages.
243 async fn get_session(&self, session_id: &SessionId) -> Result<Option<Session>, SessionError>;
244
245 /// Sends one text message, starting, resuming, or queueing as appropriate.
246 async fn send_message(
247 &self,
248 session_id: &SessionId,
249 message: String,
250 ) -> Result<(), SessionError>;
251
252 /// Submits a durable turn without entering the lossy live-chat
253 /// queue used while an ordinary user turn is active.
254 async fn submit_durable_message(
255 &self,
256 session_id: &SessionId,
257 request: DurableMessageRequest,
258 ) -> Result<(), SessionError>;
259
260 /// Answers the complete current clarification-question set.
261 async fn answer_questions(
262 &self,
263 session_id: &SessionId,
264 request: AnswerQuestionsRequest,
265 ) -> Result<(), SessionError>;
266
267 /// Cancels one session through the host lifecycle workflow.
268 async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
269
270 /// Requests merge processing for one review-ready session.
271 async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
272
273 /// Queues publication of one session branch and creates or refreshes its
274 /// review request.
275 async fn create_review_request(
276 &self,
277 session_id: &SessionId,
278 ) -> Result<ReviewRequest, SessionError>;
279}
280
281/// Stable programmatic facade for session lifecycle operations.
282#[derive(Clone)]
283pub struct SessionService {
284 backend: Arc<dyn SessionBackend>,
285}
286
287impl SessionService {
288 /// Accepts a standalone Planner version from durable task history.
289 ///
290 /// # Errors
291 /// Returns an error for stale/ineligible versions or failed persistence.
292 pub async fn accept_agent_plan(
293 &self,
294 session_id: &SessionId,
295 request: AcceptTaskPlanRequest,
296 ) -> Result<(), SessionError> {
297 self.backend.accept_agent_plan(session_id, request).await
298 }
299
300 /// Starts one Planner attempt with a captured provider/model selection.
301 ///
302 /// # Errors
303 /// Returns an error for identity conflicts, ineligible sessions, or failed
304 /// admission.
305 pub async fn start_plan_then_implement(
306 &self,
307 session_id: &SessionId,
308 request: StartPlanThenImplementRequest,
309 ) -> Result<(), SessionError> {
310 self.backend
311 .start_plan_then_implement(session_id, request)
312 .await
313 }
314
315 /// Reads a durable workflow snapshot without dispatching work.
316 ///
317 /// # Errors
318 /// Returns an error when the host cannot read or decode the workflow.
319 pub async fn get_task_chain(&self, chain_id: &str) -> Result<Option<TaskChain>, SessionError> {
320 self.backend.get_task_chain(chain_id).await
321 }
322
323 /// Lists workflows owned by one session.
324 ///
325 /// # Errors
326 /// Returns an error when the host cannot read workflow snapshots.
327 pub async fn list_task_chains(
328 &self,
329 session_id: &SessionId,
330 ) -> Result<Vec<TaskChain>, SessionError> {
331 self.backend.list_task_chains(session_id).await
332 }
333
334 /// Accepts an exact latest plan and admits its isolated Implementer
335 /// attempt.
336 ///
337 /// # Errors
338 /// Returns an error for stale/ineligible plans, conflicts, or failed
339 /// admission.
340 pub async fn accept_task_chain_plan(
341 &self,
342 chain_id: &str,
343 request: AcceptTaskChainPlanRequest,
344 ) -> Result<(), SessionError> {
345 self.backend.accept_task_chain_plan(chain_id, request).await
346 }
347
348 /// Explicitly revises, clarifies, or retries the current stage.
349 ///
350 /// # Errors
351 /// Returns an error for unfinished attempts, conflicts, or failed
352 /// admission.
353 pub async fn continue_task_chain(
354 &self,
355 chain_id: &str,
356 request: ContinueTaskChainRequest,
357 ) -> Result<(), SessionError> {
358 self.backend.continue_task_chain(chain_id, request).await
359 }
360
361 /// Requests cancellation of this workflow's current attempt.
362 ///
363 /// # Errors
364 /// Returns an error when the workflow is missing or cancellation cannot
365 /// persist.
366 pub async fn cancel_task_chain(&self, chain_id: &str) -> Result<(), SessionError> {
367 self.backend.cancel_task_chain(chain_id).await
368 }
369
370 /// Records a user reply once and lets the host decide what it means.
371 ///
372 /// While a plan awaits acceptance, the host decides through a model run
373 /// whether the reply clearly approves the plan. Only clear approval with
374 /// no requested changes starts the Implementer; anything else, including
375 /// a failed or uncertain decision, revises the plan. In every other
376 /// settled phase the reply continues the current role. Redelivering the
377 /// same `reply_id` returns the original outcome.
378 ///
379 /// # Errors
380 /// Returns [`SessionError::TaskChainNotFound`] when the session owns no
381 /// workflow, [`SessionError::TaskChainBusy`] while an agent is working
382 /// or an earlier reply is being decided, and other errors for invalid
383 /// input, conflicts, or failed admission.
384 pub async fn reply_to_task_chain(
385 &self,
386 session_id: &SessionId,
387 request: ReplyToTaskChainRequest,
388 ) -> Result<TaskChainReplyOutcome, SessionError> {
389 self.backend.reply_to_task_chain(session_id, request).await
390 }
391
392 /// Creates an owned session capability backed by a shared host handle.
393 pub fn new(backend: Arc<dyn SessionBackend>) -> Self {
394 Self { backend }
395 }
396
397 /// Admits an isolated role-bound attempt, acknowledging durable admission.
398 /// Identical redeliveries do not execute again. Task completion is
399 /// explicit.
400 ///
401 /// # Errors
402 /// Returns an error for invalid input, unaccepted implementation plans,
403 /// conflicting identity, or a session unable to accept work.
404 pub async fn submit_agent_task(
405 &self,
406 session_id: &SessionId,
407 request: crate::SubmitAgentTaskRequest,
408 ) -> Result<(), SessionError> {
409 self.backend.submit_agent_task(session_id, request).await
410 }
411
412 /// Reads the task's own responses. Attempt status remains authoritative.
413 ///
414 /// # Errors
415 /// Returns an error when the host cannot load the isolated conversation.
416 pub async fn get_agent_task_history(
417 &self,
418 task_id: &str,
419 ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
420 self.backend.get_agent_task_history(task_id).await
421 }
422
423 /// Persists a task with zero attempts in an existing session, regardless
424 /// of its execution status. Does not start work or change session state.
425 /// Identical creation requests preserve the task and its history.
426 ///
427 /// # Errors
428 /// Returns an error for empty inputs, conflicting identity, a missing
429 /// session, or a host that cannot persist tasks.
430 pub async fn create_task(
431 &self,
432 session_id: &SessionId,
433 request: CreateTaskRequest,
434 ) -> Result<(), SessionError> {
435 self.backend.create_task(session_id, request).await
436 }
437
438 /// Lists all tasks owned by a session in creation order, including their
439 /// attempt histories in one snapshot. Equal timestamps retain insertion
440 /// order. Returns an empty list for a missing session or one without tasks.
441 ///
442 /// # Errors
443 /// Returns an error when the host cannot read tasks.
444 pub async fn list_tasks(&self, session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
445 self.backend.list_tasks(session_id).await
446 }
447
448 /// Admits one task attempt through the existing serialized session worker.
449 /// Creates the task atomically if it does not already exist.
450 /// Acceptance does not wait for execution or imply task completion.
451 /// Identical deliveries are acknowledged without running again.
452 ///
453 /// # Errors
454 /// Returns an error for conflicting identity, an unavailable host, a
455 /// completed task, or a session that cannot accept a new durable turn.
456 pub async fn submit_task(
457 &self,
458 session_id: &SessionId,
459 request: SubmitTaskRequest,
460 ) -> Result<(), SessionError> {
461 self.backend.submit_task(session_id, request).await
462 }
463
464 /// Loads a task and all its attempts from durable storage.
465 ///
466 /// # Errors
467 /// Returns an error when the host cannot read tasks.
468 pub async fn get_task(&self, task_id: &str) -> Result<Option<Task>, SessionError> {
469 self.backend.get_task(task_id).await
470 }
471
472 /// Explicitly accepts the outcome. Successful model execution alone never
473 /// completes a task. Repeated completion retains its original timestamp.
474 ///
475 /// # Errors
476 /// Returns an error if the task is missing, an attempt is unfinished, or
477 /// the host cannot persist completion.
478 pub async fn complete_task(&self, task_id: &str) -> Result<(), SessionError> {
479 self.backend.complete_task(task_id).await
480 }
481
482 /// Creates one session and returns its stable identifier.
483 ///
484 /// # Errors
485 /// Returns an error when the host cannot create the requested session.
486 pub async fn create_session(
487 &self,
488 request: CreateSessionRequest,
489 ) -> Result<SessionId, SessionError> {
490 self.backend.create_session(request).await
491 }
492
493 /// Loads one complete session aggregate by identifier.
494 ///
495 /// # Errors
496 /// Returns an error when persisted data cannot be loaded or decoded.
497 pub async fn get_session(
498 &self,
499 session_id: &SessionId,
500 ) -> Result<Option<Session>, SessionError> {
501 self.backend.get_session(session_id).await
502 }
503
504 /// Sends a text message to one session.
505 ///
506 /// # Errors
507 /// Returns an error when the session cannot accept or enqueue the message.
508 pub async fn send_message(
509 &self,
510 session_id: &SessionId,
511 message: impl Into<String> + Send,
512 ) -> Result<(), SessionError> {
513 self.backend.send_message(session_id, message.into()).await
514 }
515
516 /// Submits one durable turn directly to the serialized worker.
517 ///
518 /// # Errors
519 /// Returns an error when the session is busy or cannot accept the turn.
520 pub async fn submit_durable_message(
521 &self,
522 session_id: &SessionId,
523 request: DurableMessageRequest,
524 ) -> Result<(), SessionError> {
525 self.backend
526 .submit_durable_message(session_id, request)
527 .await
528 }
529
530 /// Answers the complete current clarification-question set.
531 ///
532 /// # Errors
533 /// Returns an error when the answers are stale, incomplete, or cannot be
534 /// enqueued as a follow-up turn.
535 pub async fn answer_questions(
536 &self,
537 session_id: &SessionId,
538 request: AnswerQuestionsRequest,
539 ) -> Result<(), SessionError> {
540 self.backend.answer_questions(session_id, request).await
541 }
542
543 /// Cancels one session through its host lifecycle workflow.
544 ///
545 /// # Errors
546 /// Returns an error when the session does not exist or cannot be canceled
547 /// in its current state.
548 pub async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
549 self.backend.cancel_session(session_id).await
550 }
551
552 /// Requests merge processing for one session.
553 ///
554 /// # Errors
555 /// Returns an error when the session is not mergeable or queueing fails.
556 pub async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
557 self.backend.merge_session(session_id).await
558 }
559
560 /// Queues publication of one session and creates or refreshes its review
561 /// request.
562 ///
563 /// # Errors
564 /// Returns an error when queueing, branch publication, forge access, or
565 /// persistence fails.
566 pub async fn create_review_request(
567 &self,
568 session_id: &SessionId,
569 ) -> Result<ReviewRequest, SessionError> {
570 self.backend.create_review_request(session_id).await
571 }
572}
573
574#[cfg(test)]
575#[path = "service_test.rs"]
576mod tests;